@elementumai/edk 0.9.18 → 0.9.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/README.md +154 -9
  2. package/dist-sdk/src/catalog/factories.d.ts +35 -1
  3. package/dist-sdk/src/catalog/factories.js +36 -0
  4. package/dist-sdk/src/catalog/from-authoring.d.ts +13 -8
  5. package/dist-sdk/src/catalog/from-authoring.js +34 -9
  6. package/dist-sdk/src/catalog/index.d.ts +2 -2
  7. package/dist-sdk/src/catalog/index.js +2 -2
  8. package/dist-sdk/src/catalog/org.d.ts +39 -1
  9. package/dist-sdk/src/catalog/org.js +460 -50
  10. package/dist-sdk/src/catalog/render.js +6 -6
  11. package/dist-sdk/src/catalog/token.js +7 -0
  12. package/dist-sdk/src/catalog/types.d.ts +44 -1
  13. package/dist-sdk/src/catalog/types.js +13 -0
  14. package/dist-sdk/src/core/triggers/on-demand.d.ts +39 -3
  15. package/dist-sdk/src/core/triggers/on-demand.js +10 -2
  16. package/dist-sdk/src/engine/build/context.d.ts +1 -1
  17. package/dist-sdk/src/engine/ei/run.d.ts +149 -0
  18. package/dist-sdk/src/engine/ei/run.js +1132 -0
  19. package/dist-sdk/src/engine/logging.d.ts +17 -0
  20. package/dist-sdk/src/engine/logging.js +18 -0
  21. package/dist-sdk/src/engine/pull/ref-only.d.ts +5 -0
  22. package/dist-sdk/src/engine/pull/ref-only.js +64 -27
  23. package/dist-sdk/src/engine/pull/result-output.d.ts +8 -0
  24. package/dist-sdk/src/engine/pull/result-output.js +88 -4
  25. package/dist-sdk/src/engine/tf/expr.js +39 -14
  26. package/dist-sdk/src/engine/tf/index.d.ts +3 -3
  27. package/dist-sdk/src/engine/tf/index.js +2 -2
  28. package/dist-sdk/src/engine/tf/labels.d.ts +8 -0
  29. package/dist-sdk/src/engine/tf/labels.js +13 -0
  30. package/dist-sdk/src/engine/tf/model.d.ts +22 -1
  31. package/dist-sdk/src/engine/tf/parse.d.ts +19 -0
  32. package/dist-sdk/src/engine/tf/parse.js +197 -10
  33. package/dist-sdk/src/engine/tf/render.d.ts +4 -2
  34. package/dist-sdk/src/engine/tf/render.js +41 -7
  35. package/dist-sdk/src/engine/validation.d.ts +39 -0
  36. package/dist-sdk/src/engine/validation.js +85 -0
  37. package/dist-sdk/src/engine/workspace/loader.js +49 -12
  38. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +11 -1
  39. package/dist-sdk/src/entities/access-policy/from-tf.js +6 -1
  40. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +11 -0
  41. package/dist-sdk/src/entities/access-policy/to-tf.js +16 -6
  42. package/dist-sdk/src/entities/agent/build.d.ts +4 -16
  43. package/dist-sdk/src/entities/agent/build.js +40 -5
  44. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +4 -2
  45. package/dist-sdk/src/entities/agent/to-tf.js +6 -3
  46. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +2 -0
  47. package/dist-sdk/src/entities/agent-tool/from-tf.js +7 -1
  48. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +2 -2
  49. package/dist-sdk/src/entities/agent-tool/to-tf.js +29 -6
  50. package/dist-sdk/src/entities/app/build.d.ts +98 -19
  51. package/dist-sdk/src/entities/app/build.js +51 -19
  52. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +22 -1
  53. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -0
  54. package/dist-sdk/src/entities/app/from-tf.js +11 -5
  55. package/dist-sdk/src/entities/app/index.d.ts +6 -5
  56. package/dist-sdk/src/entities/app/index.js +2 -0
  57. package/dist-sdk/src/entities/app/module.js +18 -2
  58. package/dist-sdk/src/entities/app/to-tf.js +21 -11
  59. package/dist-sdk/src/entities/automation/build.d.ts +49 -6
  60. package/dist-sdk/src/entities/automation/build.js +163 -19
  61. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +24 -1
  62. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +320 -39
  63. package/dist-sdk/src/entities/automation/from-tf.d.ts +28 -6
  64. package/dist-sdk/src/entities/automation/from-tf.js +563 -74
  65. package/dist-sdk/src/entities/automation/generated/task-output-contracts.d.ts +33 -0
  66. package/dist-sdk/src/entities/automation/generated/task-output-contracts.js +183 -0
  67. package/dist-sdk/src/entities/automation/index.d.ts +2 -2
  68. package/dist-sdk/src/entities/automation/index.js +1 -1
  69. package/dist-sdk/src/entities/automation/module.d.ts +2 -0
  70. package/dist-sdk/src/entities/automation/module.js +93 -8
  71. package/dist-sdk/src/entities/automation/output-field-types.d.ts +7 -0
  72. package/dist-sdk/src/entities/automation/output-field-types.js +36 -0
  73. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +9 -0
  74. package/dist-sdk/src/entities/automation/output-key-wire-name.js +13 -0
  75. package/dist-sdk/src/entities/automation/script-code.d.ts +17 -0
  76. package/dist-sdk/src/entities/automation/script-code.js +91 -5
  77. package/dist-sdk/src/entities/automation/system-ref-name.d.ts +16 -0
  78. package/dist-sdk/src/entities/automation/system-ref-name.js +48 -0
  79. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +17 -0
  80. package/dist-sdk/src/entities/automation/task-output-labels.js +47 -0
  81. package/dist-sdk/src/entities/automation/tasks.d.ts +53 -4
  82. package/dist-sdk/src/entities/automation/tasks.js +38 -9
  83. package/dist-sdk/src/entities/automation/to-tf.d.ts +4 -0
  84. package/dist-sdk/src/entities/automation/to-tf.js +647 -167
  85. package/dist-sdk/src/entities/automation/triggers.d.ts +4 -2
  86. package/dist-sdk/src/entities/automation/triggers.js +4 -0
  87. package/dist-sdk/src/entities/automation/types.js +1 -0
  88. package/dist-sdk/src/entities/chart/from-tf.js +33 -17
  89. package/dist-sdk/src/entities/chart/module.js +3 -1
  90. package/dist-sdk/src/entities/chart/printer.d.ts +1 -0
  91. package/dist-sdk/src/entities/chart/printer.js +26 -16
  92. package/dist-sdk/src/entities/chart/rebind-owner.d.ts +3 -0
  93. package/dist-sdk/src/entities/chart/rebind-owner.js +42 -0
  94. package/dist-sdk/src/entities/chart/to-tf.js +21 -12
  95. package/dist-sdk/src/entities/dashboard/build.d.ts +4 -0
  96. package/dist-sdk/src/entities/dashboard/from-tf.js +15 -4
  97. package/dist-sdk/src/entities/dashboard/to-tf.d.ts +2 -0
  98. package/dist-sdk/src/entities/dashboard/to-tf.js +13 -0
  99. package/dist-sdk/src/entities/dashboard-widget/module.js +4 -0
  100. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +72 -30
  101. package/dist-sdk/src/entities/dynamic-layout/dialect.d.ts +3 -0
  102. package/dist-sdk/src/entities/dynamic-layout/dialect.js +5 -0
  103. package/dist-sdk/src/entities/dynamic-layout/from-tf.d.ts +9 -6
  104. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +188 -26
  105. package/dist-sdk/src/entities/dynamic-layout/module.js +4 -1
  106. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +5 -1
  107. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +254 -23
  108. package/dist-sdk/src/entities/element/build.d.ts +33 -13
  109. package/dist-sdk/src/entities/element/build.js +5 -1
  110. package/dist-sdk/src/entities/element/from-tf.d.ts +12 -0
  111. package/dist-sdk/src/entities/element/from-tf.js +64 -3
  112. package/dist-sdk/src/entities/element/index.d.ts +5 -2
  113. package/dist-sdk/src/entities/element/index.js +2 -0
  114. package/dist-sdk/src/entities/element/module.js +11 -3
  115. package/dist-sdk/src/entities/element/to-tf.js +20 -2
  116. package/dist-sdk/src/entities/field/build.d.ts +14 -1
  117. package/dist-sdk/src/entities/field/build.js +3 -0
  118. package/dist-sdk/src/entities/field/from-tf.d.ts +3 -0
  119. package/dist-sdk/src/entities/field/from-tf.js +50 -1
  120. package/dist-sdk/src/entities/field/media-types.d.ts +6 -0
  121. package/dist-sdk/src/entities/field/media-types.js +30 -0
  122. package/dist-sdk/src/entities/field/module.js +1 -0
  123. package/dist-sdk/src/entities/field/to-tf.d.ts +23 -2
  124. package/dist-sdk/src/entities/field/to-tf.js +142 -22
  125. package/dist-sdk/src/entities/file-reader/from-tf.js +14 -5
  126. package/dist-sdk/src/entities/file-reader/module.js +1 -0
  127. package/dist-sdk/src/entities/file-reader/types.d.ts +2 -0
  128. package/dist-sdk/src/entities/file-reader/types.js +1 -1
  129. package/dist-sdk/src/entities/portal/build.d.ts +26 -0
  130. package/dist-sdk/src/entities/portal/build.js +37 -0
  131. package/dist-sdk/src/entities/portal/from-tf.d.ts +27 -0
  132. package/dist-sdk/src/entities/portal/from-tf.js +75 -0
  133. package/dist-sdk/src/entities/portal/index.d.ts +1 -0
  134. package/dist-sdk/src/entities/portal/index.js +1 -0
  135. package/dist-sdk/src/entities/portal/module.d.ts +3 -0
  136. package/dist-sdk/src/entities/portal/module.js +28 -0
  137. package/dist-sdk/src/entities/portal/to-tf.d.ts +12 -0
  138. package/dist-sdk/src/entities/portal/to-tf.js +73 -0
  139. package/dist-sdk/src/entities/portal/types.d.ts +1 -0
  140. package/dist-sdk/src/entities/portal/types.js +1 -0
  141. package/dist-sdk/src/entities/relationship/from-tf.d.ts +8 -1
  142. package/dist-sdk/src/entities/relationship/from-tf.js +53 -10
  143. package/dist-sdk/src/entities/relationship/module.js +2 -0
  144. package/dist-sdk/src/entities/relationship/pair-check.d.ts +7 -0
  145. package/dist-sdk/src/entities/relationship/pair-check.js +68 -0
  146. package/dist-sdk/src/entities/relationship/to-tf.d.ts +10 -0
  147. package/dist-sdk/src/entities/relationship/to-tf.js +31 -13
  148. package/dist-sdk/src/entities/search-table/module.js +1 -0
  149. package/dist-sdk/src/entities/search-table/to-tf.d.ts +1 -0
  150. package/dist-sdk/src/entities/search-table/to-tf.js +1 -1
  151. package/dist-sdk/src/entities/service-account/build.d.ts +15 -2
  152. package/dist-sdk/src/entities/service-account/from-tf.d.ts +2 -4
  153. package/dist-sdk/src/entities/service-account/from-tf.js +17 -5
  154. package/dist-sdk/src/entities/service-account/role-fidelity.d.ts +56 -0
  155. package/dist-sdk/src/entities/service-account/role-fidelity.js +243 -0
  156. package/dist-sdk/src/entities/service-account/to-tf.d.ts +14 -0
  157. package/dist-sdk/src/entities/service-account/to-tf.js +17 -0
  158. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +1 -1
  159. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +5 -2
  160. package/dist-sdk/src/entities/shared/filters/ast.d.ts +15 -2
  161. package/dist-sdk/src/entities/shared/filters/index.d.ts +25 -2
  162. package/dist-sdk/src/entities/shared/filters/index.js +38 -5
  163. package/dist-sdk/src/entities/shared/filters/print.js +31 -3
  164. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +25 -3
  165. package/dist-sdk/src/entities/shared/filters/tf-codec.js +51 -15
  166. package/dist-sdk/src/entities/shared/filters/types.d.ts +22 -5
  167. package/dist-sdk/src/entities/shared/foreign-ref.d.ts +16 -0
  168. package/dist-sdk/src/entities/shared/foreign-ref.js +17 -1
  169. package/dist-sdk/src/entities/shared/tool-field-ref.js +6 -9
  170. package/dist-sdk/src/entities/shared/types/field-types.d.ts +10 -5
  171. package/dist-sdk/src/entities/shared/types/field-types.js +4 -0
  172. package/dist-sdk/src/entities/skill/access-policy.d.ts +17 -0
  173. package/dist-sdk/src/entities/skill/access-policy.js +101 -0
  174. package/dist-sdk/src/entities/skill/build.d.ts +3 -0
  175. package/dist-sdk/src/entities/skill/build.js +3 -0
  176. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +4 -1
  177. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +23 -1
  178. package/dist-sdk/src/entities/skill/from-tf.d.ts +2 -0
  179. package/dist-sdk/src/entities/skill/from-tf.js +70 -22
  180. package/dist-sdk/src/entities/skill/index.d.ts +2 -0
  181. package/dist-sdk/src/entities/skill/index.js +1 -0
  182. package/dist-sdk/src/entities/skill/input-coverage.d.ts +7 -0
  183. package/dist-sdk/src/entities/skill/input-coverage.js +11 -0
  184. package/dist-sdk/src/entities/skill/module.js +1 -0
  185. package/dist-sdk/src/entities/skill/to-tf.d.ts +2 -2
  186. package/dist-sdk/src/entities/skill/to-tf.js +19 -6
  187. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  188. package/dist-sdk/src/entities/skill-tool/from-tf.js +8 -2
  189. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +2 -2
  190. package/dist-sdk/src/entities/skill-tool/to-tf.js +29 -6
  191. package/dist-sdk/src/entities/table/catalog.d.ts +14 -0
  192. package/dist-sdk/src/entities/table/catalog.js +66 -0
  193. package/dist-sdk/src/entities/table/module.js +2 -1
  194. package/dist-sdk/src/entities/table/to-tf.js +5 -5
  195. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +89 -0
  196. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +277 -0
  197. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.d.ts +51 -0
  198. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +360 -0
  199. package/dist-sdk/src/entities/view/agent-view-layout.d.ts +151 -0
  200. package/dist-sdk/src/entities/view/agent-view-layout.js +21 -0
  201. package/dist-sdk/src/entities/view/from-tf.d.ts +6 -3
  202. package/dist-sdk/src/entities/view/from-tf.js +161 -14
  203. package/dist-sdk/src/entities/view/module.js +30 -3
  204. package/dist-sdk/src/entities/view/to-tf.d.ts +24 -2
  205. package/dist-sdk/src/entities/view/to-tf.js +95 -9
  206. package/dist-sdk/src/entities/view/types.d.ts +4 -15
  207. package/dist-sdk/src/entities/view/types.js +17 -15
  208. package/dist-sdk/src/entities/widget/build.d.ts +16 -1
  209. package/dist-sdk/src/entities/widget/build.js +11 -1
  210. package/dist-sdk/src/entities/widget/to-tf.js +36 -10
  211. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +38 -10
  212. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  213. package/dist-sdk/src/graph/index.d.ts +54 -0
  214. package/dist-sdk/src/graph/index.js +30 -0
  215. package/dist-sdk/src/graph/modules.js +2 -0
  216. package/dist-sdk/src/graph/types.d.ts +133 -2
  217. package/dist-sdk/src/internal/sdk-package.d.ts +1 -1
  218. package/dist-sdk/src/internal/sdk-package.js +1 -0
  219. package/package.json +11 -1
@@ -1,24 +1,42 @@
1
1
  import { EntityTfError, recordFieldContextOf } from "../../engine/entity.js";
2
- import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET } from "../../core/system-fields.js";
2
+ import { ValidationFailureError } from "../../engine/validation.js";
3
+ import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET, SYSTEM_FIELD_KEYS } 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";
8
10
  import { SERVICE_ACCOUNT_RESOURCE_TYPE } from "../service-account/module.js";
9
- import { resolveForeignRef } from "../shared/foreign-ref.js";
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
14
  import { API_TASK_REF_AUTHORING_NAMES, API_TASK_REF_WIRE_NAMES } 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";
15
18
  import { FILE_READER_SUB_TYPE_BY_RESOURCE, FILE_READER_SUB_TYPE_BY_TYPE_KEY } from "../file-reader/types.js";
16
19
  import { UNRESOLVED_FIELD_MARKER } from "../shared/ref.js";
20
+ import { ELEMENT_SYSTEM_FIELD_KEYS } from "../element/system-fields.js";
17
21
  import { TABLE_RESOURCE_TYPE } from "../table/module.js";
18
22
  import { AUTOMATION_RESOURCE_TYPE, WORKFLOW_PUBLISH_RESOURCE_TYPE } from "./types.js";
23
+ import { AI_SEARCH_TABLE_OUTPUT_NAMES, TASK_OUTPUT_REFERENCE_NAMES, USER_SEARCH_REF_WIRE_NAMES } from "./task-output-labels.js";
19
24
  import { onDemandTriggerRefKey } from "./value-ref-tf.js";
25
+ import { normalizeOnDemandParamKey } from "../../../pull/util.js";
26
+ import { PROVIDER_FIXED_SYSTEM_FIELD_KEYS, recordFieldWireRefName } from "./system-ref-name.js";
20
27
  import { taskTfLabel } from "./task-label.js";
21
28
  import { isOnDemandRecordType } from "../shared/types/field-types.js";
29
+ /** The context for reading records of `appRefName` (a `kind`), retargeted from the owner. */
30
+ function recordOwnerContext(owner, appRefName, kind, fieldNames) {
31
+ if (appRefName === owner.appRefName && (kind === undefined || kind === owner.parentScope))
32
+ return owner;
33
+ return {
34
+ ...owner,
35
+ appRefName,
36
+ fieldNames: fieldNames ?? new Map(),
37
+ recordLacksAuditFields: kind === "element" && owner.elementsWithoutAuditFields?.has(appRefName) === true,
38
+ };
39
+ }
22
40
  function scopedLabel(appTfLabel, label) {
23
41
  return appScopedResourceLabel(appTfLabel, label);
24
42
  }
@@ -103,6 +121,7 @@ const TASK_RESOURCES = {
103
121
  aiTransform: "elementum_ai_transform_task",
104
122
  saveAttachment: "elementum_save_attachment_task",
105
123
  userSearch: "elementum_user_search_task",
124
+ userGroupSearch: "elementum_user_group_search_task",
106
125
  calculation: "elementum_calculation_task",
107
126
  executeScript: "elementum_execute_script_task",
108
127
  documentModel: "elementum_file_reader_task",
@@ -115,6 +134,7 @@ const TASK_RESOURCES = {
115
134
  // on `taskRefs` entries and the dedicated emission branch in `emitTasks`.
116
135
  unimplementedTask: "elementum_unmanaged_task_reference",
117
136
  };
137
+ const USER_SEARCH_PATH_BY_WIRE_NAME = new Map(Object.entries(USER_SEARCH_REF_WIRE_NAMES).map(([path, wire]) => [wire, path]));
118
138
  const CONFIG_ATTRS = {
119
139
  aspectId: "object_id",
120
140
  relatedAspectId: "object_id",
@@ -163,6 +183,7 @@ const CONFIG_ATTRS = {
163
183
  categorySource: "category_source",
164
184
  titleReference: "title",
165
185
  messageReference: "message",
186
+ descriptionReference: "description",
166
187
  notifyWatchers: "notify_watchers",
167
188
  fieldId: "field_id",
168
189
  userId: "user_id",
@@ -317,15 +338,8 @@ function foreignRootLookup(kind, identity) {
317
338
  lookupValue: identity.name,
318
339
  };
319
340
  }
320
- /**
321
- * Validates and derives the shared naming for a cross-app/element/task field
322
- * token — the `data.elementum_field` label {@link crossAppFieldToTf} emits,
323
- * and the matching `<fieldLabel>_options_by_label` local a foreign PICKLIST
324
- * field's option-label lookup (in {@link picklistFilterValueToTf}) resolves
325
- * against. Kept as one function so the two call sites can never drift apart
326
- * on how the label is built.
327
- */
328
- function foreignFieldNaming(value) {
341
+ /** Validates a cross-app/element/task field token's owner provenance. */
342
+ function foreignFieldProvenance(value) {
329
343
  const parent = value.parent;
330
344
  if (parent === undefined)
331
345
  throw new EntityTfError(`field ref "${value.refName}" has no parent`);
@@ -344,14 +358,7 @@ function foreignFieldNaming(value) {
344
358
  }
345
359
  const fieldName = value.name ?? value.refName;
346
360
  const ownerKind = value.parentKind === "task" ? "task" : value.parentKind === "element" ? "element" : "app";
347
- const resolved = foreignRootLookup(ownerKind, {
348
- name: value.parentName,
349
- namespace: value.parentNamespace,
350
- });
351
- const ownerType = resolved.resourceType;
352
- const ownerLabel = resolved.tfLabel;
353
- const fieldLabel = `${value.parentKind}_${ownerLabel}_${tsLabelToTfLabel(value.refName)}`;
354
- return { fieldName, ownerType, ownerLabel, ownerParentName: value.parentName, fieldLabel };
361
+ return { fieldName, ownerKind, ownerParentName: value.parentName };
355
362
  }
356
363
  /**
357
364
  * Registers the `<fieldLabel>_options_by_label` local — a for-expression
@@ -386,24 +393,36 @@ function crossAppFieldToTf(value, ctx, dataBlocks) {
386
393
  // table-owned search table has to be distinguishable from an element-owned
387
394
  // one.
388
395
  if (sibling !== undefined && sibling.kind !== "table" && sibling.kind !== "task") {
389
- const fieldValue = fieldRefToTfValue(value.fieldType ?? "", value.refName, sibling.tfLabel, sibling.kind);
396
+ const fieldValue = fieldRefToTfValue(value.fieldType ?? "", value.refName, sibling.tfLabel, sibling.kind, sibling.kind === "element" ? fieldNamesForAppRefName(ctx.fieldAddressesByAppRefName, value.parent) : undefined);
390
397
  if (fieldValue === undefined) {
391
398
  throw new EntityTfError(`field ref "${value.refName}" on sibling ${sibling.kind} "${value.parent}" has no terraform field resource mapping (fieldType ${JSON.stringify(value.fieldType ?? "")})`);
392
399
  }
393
400
  return fieldValue;
394
401
  }
395
402
  }
396
- const { fieldName, fieldLabel } = foreignFieldNaming(value);
397
- const ownerKind = value.parentKind === "task" ? "task" : value.parentKind === "element" ? "element" : "app";
403
+ return expr.dataAttr("elementum_field", registerForeignFieldLookup(value, ctx, dataBlocks), ["id"]);
404
+ }
405
+ /**
406
+ * Registers the `data.elementum_field` lookup (and its owner root lookup) for
407
+ * a genuinely foreign field, plus the matching `<label>_options_by_label`
408
+ * local, and returns the lookup label. The one place both a foreign field's
409
+ * id ({@link crossAppFieldToTf}) and its option-label local
410
+ * ({@link picklistFilterValueToTf}) get their label, so the two never drift.
411
+ */
412
+ function registerForeignFieldLookup(value, ctx, dataBlocks) {
413
+ const { fieldName, ownerKind, ownerParentName } = foreignFieldProvenance(value);
414
+ let fieldLabel;
398
415
  if (ctx.orgRefs !== undefined) {
399
- const owner = resolveForeignRef(ownerKind, { name: value.parentName, namespace: value.parentNamespace }, ctx.orgRefs, ctx.diagnostics, `automation field "${value.refName}" owner`);
416
+ const owner = resolveForeignRef(ownerKind, { name: ownerParentName, namespace: value.parentNamespace }, ctx.orgRefs, ctx.diagnostics, `automation field "${value.refName}" owner`);
417
+ fieldLabel = foreignFieldDataLabel(ownerKind, owner.tfLabel, fieldName);
400
418
  ctx.orgRefs.foreignField("elementum_field", fieldLabel, owner.value, fieldName);
401
419
  }
402
420
  else {
403
421
  const resolved = foreignRootLookup(ownerKind, {
404
- name: value.parentName,
422
+ name: ownerParentName,
405
423
  namespace: value.parentNamespace,
406
424
  });
425
+ fieldLabel = foreignFieldDataLabel(ownerKind, resolved.tfLabel, fieldName);
407
426
  const objectId = expr.dataAttr(resolved.resourceType, resolved.tfLabel, ["id"]);
408
427
  dataBlocks.set(`${resolved.resourceType}.${resolved.tfLabel}`, {
409
428
  kind: "data",
@@ -419,7 +438,7 @@ function crossAppFieldToTf(value, ctx, dataBlocks) {
419
438
  });
420
439
  }
421
440
  registerForeignOptionsByLabelLocal(fieldLabel, ctx);
422
- return expr.dataAttr("elementum_field", fieldLabel, ["id"]);
441
+ return fieldLabel;
423
442
  }
424
443
  /**
425
444
  * Resolve an automation token as a managed definition (same stream root or a
@@ -549,6 +568,7 @@ function tokenToTf(value, ctx, dataBlocks) {
549
568
  return expr.dataAttr("elementum_user", label, ["id"]);
550
569
  }
551
570
  case "userField":
571
+ case "userGroupField":
552
572
  return value.refName;
553
573
  case "task": {
554
574
  const sibling = ctx.workspaceAspects?.get(workspaceAspectKey("task", value.refName));
@@ -756,14 +776,49 @@ function tokenToTf(value, ctx, dataBlocks) {
756
776
  const variant = value.__variant ?? "snowflake";
757
777
  const element = aspects.get(workspaceAspectKey("element", owner));
758
778
  const table = aspects.get(workspaceAspectKey("table", owner));
759
- if (variant === "table") {
760
- if (table === undefined) {
761
- throw new EntityTfError(`search table "${owner}.${value.refName}" is table-owned, but "${owner}" is not a table in this build` +
762
- `${element !== undefined ? ` (it is an element — use searchTable, not tableSearchTable)` : ""}`);
763
- }
779
+ const pinnedId = typeof value.id === "string" && value.id !== "" ? value.id : undefined;
780
+ if (variant === "table" && table !== undefined && pinnedId === undefined) {
764
781
  // Label shape mirrors search-table/to-tf.ts's own table branch.
765
782
  return expr.resourceAttr(SEARCH_TABLE_RESOURCE_TYPES.table, `tables_${table.tfLabel}_${tsLabelToTfLabel(value.refName)}`, ["id"]);
766
783
  }
784
+ // A table outside this build has no managed elementum_table_search_table.
785
+ // Pin by id when the name is ambiguous; otherwise keep the name lookup
786
+ // a unique name already used. An element that merely shares the refName
787
+ // is still the wrong owner.
788
+ if (variant === "table") {
789
+ if (pinnedId === undefined && element !== undefined) {
790
+ 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)`);
791
+ }
792
+ const tableName = typeof value.parentName === "string" && value.parentName !== "" ? value.parentName : owner;
793
+ const tableLabel = sanitizeName(tableName);
794
+ const searchName = value.name ?? value.refName;
795
+ const label = pinnedId === undefined
796
+ ? `${tableLabel}_${sanitizeName(searchName)}`
797
+ : `${tableLabel}_${sanitizeName(searchName)}_${stableIdSuffix(pinnedId)}`;
798
+ const tableId = expr.dataAttr(TABLE_RESOURCE_TYPE, tableLabel, ["id"]);
799
+ const searchAttrs = { table_id: tableId, name: searchName };
800
+ if (pinnedId !== undefined)
801
+ searchAttrs.id = pinnedId;
802
+ if (ctx.orgRefs !== undefined) {
803
+ ctx.orgRefs.rawLookup(TABLE_RESOURCE_TYPE, tableLabel, tableName);
804
+ ctx.orgRefs.rawLookup("elementum_search_table", label, searchName, searchAttrs);
805
+ }
806
+ else {
807
+ dataBlocks.set(`${TABLE_RESOURCE_TYPE}.${tableLabel}`, {
808
+ kind: "data",
809
+ type: TABLE_RESOURCE_TYPE,
810
+ label: tableLabel,
811
+ attrs: { name: tableName },
812
+ });
813
+ dataBlocks.set(`elementum_search_table.${label}`, {
814
+ kind: "data",
815
+ type: "elementum_search_table",
816
+ label,
817
+ attrs: searchAttrs,
818
+ });
819
+ }
820
+ return expr.dataAttr("elementum_search_table", label, ["id"]);
821
+ }
767
822
  if (element !== undefined) {
768
823
  return expr.resourceAttr(SEARCH_TABLE_RESOURCE_TYPES[variant], scopedResourceLabel(element.tfLabel, tsLabelToTfLabel(value.refName), "element"), ["id"]);
769
824
  }
@@ -1020,31 +1075,18 @@ function calculationTaskMustache(taskRefKey, name, refs) {
1020
1075
  `"}}`,
1021
1076
  ];
1022
1077
  }
1023
- /**
1024
- * Task-own outputs whose calc-engine reference name differs from the
1025
- * refs-map key. Keys are the display labels the refs map uses (and that
1026
- * `build.ts`'s `rewriteForwardTaskRefName` already rewrote authoring names
1027
- * into); values are the underlying reference names — captured live with
1028
- * `ei refs --from-remote` against a real record-search task, and matching
1029
- * mobius' `shared.json` `aspect_records_search` label table.
1030
- */
1031
- const CALCULATION_TASK_OUTPUT_REF_NAME = {
1032
- elementum_record_search_task: {
1033
- "Records Size": "count",
1034
- "First found record id": "recordId",
1035
- },
1036
- };
1037
1078
  function calculationTaskRefName(targetType, name, taskRefKey, refs) {
1038
1079
  const segments = name.split(".");
1039
1080
  if (segments[0] === "record" && segments.length >= 2) {
1040
1081
  const suffix = segments.slice(2).join(".");
1082
+ const fieldKey = segments[1];
1041
1083
  return [
1042
1084
  "record.",
1043
- calculationRecordFieldId(segments[1], calculationFieldScope(taskRefKey, refs)),
1085
+ calculationRawFieldId(fieldKey) ?? calculationRecordFieldId(fieldKey, calculationFieldScope(taskRefKey, refs)),
1044
1086
  suffix.length > 0 ? `.${suffix}` : "",
1045
1087
  ];
1046
1088
  }
1047
- const refName = CALCULATION_TASK_OUTPUT_REF_NAME[targetType]?.[name] ?? name;
1089
+ const refName = TASK_OUTPUT_REFERENCE_NAMES[targetType]?.[name] ?? name;
1048
1090
  if (refName.includes('"')) {
1049
1091
  throw new EntityTfError(`calculation task output name "${refName}" contains a double quote`);
1050
1092
  }
@@ -1070,7 +1112,37 @@ function calculationFieldScope(taskRefKey, refs) {
1070
1112
  ?? refs.owner.workspaceAspects?.get(workspaceAspectKey("element", taskApp));
1071
1113
  return { appRefName: taskApp, appTfLabel: aspect?.tfLabel ?? refs.owner.appTfLabel, fieldAddresses };
1072
1114
  }
1115
+ const FOUND_RECORD_TASK_TYPES = new Set([
1116
+ "elementum_record_search_task",
1117
+ "elementum_create_record_task",
1118
+ "elementum_find_related_records_task",
1119
+ ]);
1120
+ /**
1121
+ * A short-form `task.<id>.<name>` value reference addresses a found record's
1122
+ * field by its platform reference name `record.<fieldId>` (as ei exports it),
1123
+ * not by the refs-map display label. Undefined when the field's id cannot be
1124
+ * resolved in this build, which keeps the display-label form.
1125
+ */
1126
+ function foundRecordFieldReferenceName(targetType, name, taskRefKey, refs) {
1127
+ const segments = name.split(".");
1128
+ const addressesRecordFields = FOUND_RECORD_TASK_TYPES.has(targetType) || targetType === TASK_RESOURCES.updateField;
1129
+ if (!addressesRecordFields || segments[0] !== "record" || segments.length < 2)
1130
+ return undefined;
1131
+ if (segments[1] === "recordId")
1132
+ return undefined;
1133
+ try {
1134
+ return calculationTaskRefName(targetType, name, taskRefKey, refs).filter((part) => part !== "");
1135
+ }
1136
+ catch (error) {
1137
+ if (error instanceof EntityTfError)
1138
+ return undefined;
1139
+ throw error;
1140
+ }
1141
+ }
1073
1142
  function calculationTriggerMustache(name, refs) {
1143
+ const onDemandName = onDemandTriggerRefName(name, refs);
1144
+ if (onDemandName !== undefined)
1145
+ return [`{{trigger name="${onDemandName}"}}`];
1074
1146
  const parts = name.split(".");
1075
1147
  if (parts[0] !== "record" || parts.length < 2) {
1076
1148
  return [`{{trigger name="${name}"}}`];
@@ -1084,11 +1156,16 @@ function calculationTriggerMustache(name, refs) {
1084
1156
  `${suffixPart}"}}`,
1085
1157
  ];
1086
1158
  }
1087
- function calculationRecordFieldId(fieldKey, scope) {
1159
+ /** A field id that is already on the wire (pulled raw UUID / unresolved marker) needs no aspect to resolve. */
1160
+ function calculationRawFieldId(fieldKey) {
1088
1161
  if (fieldKey.startsWith(UNRESOLVED_FIELD_MARKER))
1089
1162
  return fieldKey.slice(UNRESOLVED_FIELD_MARKER.length);
1090
- if (isUuid(fieldKey))
1091
- return fieldKey;
1163
+ return isUuid(fieldKey) ? fieldKey : undefined;
1164
+ }
1165
+ function calculationRecordFieldId(fieldKey, scope) {
1166
+ const raw = calculationRawFieldId(fieldKey);
1167
+ if (raw !== undefined)
1168
+ return raw;
1092
1169
  const address = scope.fieldAddresses.get(fieldKey);
1093
1170
  if (address !== undefined)
1094
1171
  return addressExpr(address, ["id"]);
@@ -1167,15 +1244,6 @@ const FIELD_REF_SUFFIX_TO_WIRE = {
1167
1244
  "employee.manager.email": " Manager Email",
1168
1245
  "employee.manager.name": " Manager Name",
1169
1246
  };
1170
- const PROVIDER_FIXED_SYSTEM_FIELD_KEYS = new Set([
1171
- "stage",
1172
- "createdAt",
1173
- "createdBy",
1174
- "updatedAt",
1175
- "updatedBy",
1176
- "closedAt",
1177
- "closedBy",
1178
- ]);
1179
1247
  function wireRefName(name, ctx) {
1180
1248
  const known = TS_TRIGGER_REF_TO_WIRE[name];
1181
1249
  if (known !== undefined)
@@ -1210,6 +1278,14 @@ function wireRefName(name, ctx) {
1210
1278
  const systemFieldKey = SYSTEM_FIELD_KEY_SET.has(fieldKey)
1211
1279
  ? fieldKey
1212
1280
  : undefined;
1281
+ if (systemFieldKey !== undefined &&
1282
+ ctx.recordLacksAuditFields === true &&
1283
+ ELEMENT_AUDIT_SYSTEM_FIELD_KEYS.includes(systemFieldKey) &&
1284
+ !ctx.fieldNames.has(fieldKey)) {
1285
+ throw new EntityTfError(`automation reference "${name}" reads audit field "${systemFieldKey}" on element "${ctx.appRefName}", which has no audit fields. ` +
1286
+ "The platform adds them to apps but only to some elements, and EDK cannot create them. " +
1287
+ "Remove the reference, or set systemFields: { audit: true } on an element the platform did give them to.");
1288
+ }
1213
1289
  const fieldName = systemFieldKey !== undefined && PROVIDER_FIXED_SYSTEM_FIELD_KEYS.has(systemFieldKey)
1214
1290
  ? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[systemFieldKey]
1215
1291
  : ctx.fieldNames.get(fieldKey) ??
@@ -1222,13 +1298,7 @@ function wireRefName(name, ctx) {
1222
1298
  if (wireSuffix === undefined) {
1223
1299
  throw new EntityTfError(`automation reference "${name}" has unsupported record-field path "${suffix}"`);
1224
1300
  }
1225
- // Email audit refs have historically varied in the capitalization of
1226
- // "by" between organizations. The provider exposes both spellings as
1227
- // aliases, so author the established lowercase wire name consistently.
1228
- const refName = `${fieldName}${wireSuffix}`;
1229
- return /^(Created|Updated) By (?:Manager )?Email$/.test(refName)
1230
- ? refName.replace(/ By(?= (?:Manager )?Email$)/, " by")
1231
- : refName;
1301
+ return recordFieldWireRefName(fieldName, wireSuffix);
1232
1302
  }
1233
1303
  // A webhook trigger's body/headers refs (ctx.trigger.body["X"]) can only
1234
1304
  // type-check against DeepRefs<WebhookTriggerOutput>, so parts[0] being
@@ -1269,8 +1339,14 @@ const RECORD_COLLECTION_TASK_WIRE_TYPES = new Set([
1269
1339
  const TS_FOR_EACH_GENERIC_SEGMENT_TO_WIRE = {
1270
1340
  iteration: "Iteration",
1271
1341
  };
1272
- function forEachCompactFilterName(name) {
1273
- return name === "recordId" ? "item" : name;
1342
+ function forEachCompactFilterName(name, isRecordCollection) {
1343
+ if (name === "recordId")
1344
+ return "item";
1345
+ // A plain-list loop's whole item is ForEachReference name "" on the
1346
+ // platform; provider Read renders it as `for_each.<id>.`.
1347
+ if (name === "item" && !isRecordCollection)
1348
+ return "";
1349
+ return name;
1274
1350
  }
1275
1351
  function forEachWireRefName(name, ctx, isRecordCollection) {
1276
1352
  // A recordSearch collection's whole item and branded record identity both
@@ -1394,15 +1470,11 @@ function taskWireRefName(name, taskRefKey, refs) {
1394
1470
  return handleKey;
1395
1471
  const normalized = normalizeIndexedRecordsFieldPath(name);
1396
1472
  const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
1397
- if (taskApp === undefined || taskApp === refs.owner.appRefName) {
1473
+ if (taskApp === undefined)
1398
1474
  return wireRefName(normalized, refs.owner);
1399
- }
1400
- const foreignNames = fieldNamesForAppRefName(refs.fieldNamesByAppRefName, taskApp);
1401
- return wireRefName(normalized, {
1402
- ...refs.owner,
1403
- appRefName: taskApp,
1404
- fieldNames: foreignNames ?? new Map(),
1405
- });
1475
+ return wireRefName(normalized, recordOwnerContext(refs.owner, taskApp, taskTargetKind(taskRefKey, refs), taskApp === refs.owner.appRefName
1476
+ ? refs.owner.fieldNames
1477
+ : fieldNamesForAppRefName(refs.fieldNamesByAppRefName, taskApp)));
1406
1478
  }
1407
1479
  /**
1408
1480
  * The platform refs-map key for one task output, given the emitting task's
@@ -1431,6 +1503,9 @@ function taskOutputWireRefKey(targetType, name, taskRefKey, refs) {
1431
1503
  if (targetType === "elementum_ai_search_table_task" && (name === "records" || name === "All Records")) {
1432
1504
  return "All Records";
1433
1505
  }
1506
+ if (targetType === "elementum_ai_search_table_task" && AI_SEARCH_TABLE_OUTPUT_NAMES[name] !== undefined) {
1507
+ return AI_SEARCH_TABLE_OUTPUT_NAMES[name][0];
1508
+ }
1434
1509
  // tableRecordsSearch uses yet another wire key: "All matching table rows".
1435
1510
  if (targetType === "elementum_table_records_search_task" &&
1436
1511
  (name === "records" || name === "All matching table rows")) {
@@ -1438,7 +1513,32 @@ function taskOutputWireRefKey(targetType, name, taskRefKey, refs) {
1438
1513
  }
1439
1514
  return taskWireRefName(name, taskRefKey, refs);
1440
1515
  }
1516
+ /** The platform's own on-demand "Triggered By" refs (live refs-map keys). */
1517
+ const ON_DEMAND_TRIGGERED_BY_REFS = {
1518
+ "triggeredBy": "Triggered By's Id",
1519
+ "triggeredBy.id": "Triggered By's Id",
1520
+ "triggeredBy.email": "Triggered By's Email",
1521
+ "triggeredBy.name": "Triggered By's Name",
1522
+ };
1523
+ /**
1524
+ * The refs-map name of an on-demand `ctx.trigger.triggeredBy` read, which
1525
+ * every trigger reference (task input, calculation, publish output) shares.
1526
+ * A userId input has no reference at all, so reading one is refused.
1527
+ */
1528
+ function onDemandTriggerRefName(name, refs) {
1529
+ if (refs.trigger.type !== TRIGGER_RESOURCES.onDemand)
1530
+ return undefined;
1531
+ const userParam = refs.userParamNames.find((param) => name === param || name.startsWith(`${param}.`));
1532
+ if (userParam !== undefined) {
1533
+ throw new EntityTfError(`ctx.trigger.${name}: the platform publishes no reference for on-demand userId input "${userParam}", ` +
1534
+ `so a task cannot read it. Use ctx.trigger.triggeredBy (id/email/name) for the user who ran the automation.`);
1535
+ }
1536
+ return ON_DEMAND_TRIGGERED_BY_REFS[name];
1537
+ }
1441
1538
  function triggerWireRefName(name, refs) {
1539
+ const onDemandName = onDemandTriggerRefName(name, refs);
1540
+ if (onDemandName !== undefined)
1541
+ return onDemandName;
1442
1542
  const scalarParams = refs.triggerParamNames.filter((param) => !refs.recordParamNames.includes(param));
1443
1543
  const declared = onDemandTriggerRefKey(name, scalarParams);
1444
1544
  if (declared !== name || scalarParams.includes(name))
@@ -1467,11 +1567,7 @@ function recordParamFieldWireName(paramName, suffix, refs) {
1467
1567
  const targetFieldNames = targetRefName === refs.owner.appRefName && target.__kind === refs.owner.parentScope
1468
1568
  ? refs.owner.fieldNames
1469
1569
  : fieldNamesForAppRefName(refs.fieldNamesByAppRefName, targetRefName);
1470
- return wireRefName(`record.${suffix}`, {
1471
- ...refs.owner,
1472
- appRefName: targetRefName,
1473
- fieldNames: targetFieldNames ?? new Map(),
1474
- });
1570
+ return wireRefName(`record.${suffix}`, recordOwnerContext(refs.owner, targetRefName, target.__kind === "element" || target.__kind === "app" ? target.__kind : undefined, targetFieldNames));
1475
1571
  }
1476
1572
  /** Run-automation targets reference publish for ACTIVE automations, automation for draft/inactive. */
1477
1573
  export function automationRunTargetResourceAttr(appTfLabel, automationRefName, activeAutomationRefNames) {
@@ -1481,6 +1577,88 @@ export function automationRunTargetResourceAttr(appTfLabel, automationRefName, a
1481
1577
  }
1482
1578
  return expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label, ["id"]);
1483
1579
  }
1580
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1581
+ const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
1582
+ /** The provider's `ValidateFieldValue` datetime shape: seconds and a timezone are required. */
1583
+ const ISO_DATETIME_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
1584
+ /**
1585
+ * A literal the platform cannot coerce into the target field only fails at
1586
+ * apply. Checked for the field types where free text is never accepted:
1587
+ * user and group fields take ids, date fields ISO dates, datetime fields
1588
+ * ISO timestamps.
1589
+ */
1590
+ function assertLiteralFitsFieldType(value, field) {
1591
+ if (field === undefined || value === undefined)
1592
+ return;
1593
+ const fieldType = field.fieldType;
1594
+ const accepts = {
1595
+ USER: { test: (text) => UUID_PATTERN.test(text), expected: "a user id, or a user reference such as ctx.trigger.record.<userField>" },
1596
+ GROUP: { test: (text) => UUID_PATTERN.test(text), expected: "a group id, or a group reference" },
1597
+ DATE: { test: (text) => ISO_DATE_PATTERN.test(text) && !Number.isNaN(Date.parse(text)), expected: "an ISO date (YYYY-MM-DD) or a date reference" },
1598
+ DATETIME: {
1599
+ test: (text) => ISO_DATETIME_PATTERN.test(text) && !Number.isNaN(Date.parse(text)),
1600
+ expected: "an ISO timestamp with seconds and a timezone (YYYY-MM-DDTHH:MM:SS[.fff]Z or ±HH:MM) or a datetime reference",
1601
+ },
1602
+ };
1603
+ const rule = fieldType === undefined ? undefined : accepts[fieldType];
1604
+ if (rule === undefined)
1605
+ return;
1606
+ const label = field.name ?? field.refName ?? "unknown";
1607
+ if (typeof value !== "string") {
1608
+ throw new EntityTfError(`automation field "${label}" (${fieldType}) is given a ${typeof value} literal; it needs ${rule.expected}`);
1609
+ }
1610
+ // The provider refuses `${...}` templates on these four types too, so a
1611
+ // template string is not left to the platform here.
1612
+ if (rule.test(value))
1613
+ return;
1614
+ throw new EntityTfError(`automation field "${label}" (${fieldType}) is given the text ${JSON.stringify(value)}; it needs ${rule.expected}`);
1615
+ }
1616
+ /**
1617
+ * The platform refuses an element record create that leaves the title system
1618
+ * field empty, but only at apply and only as "Unable to validate". Fields
1619
+ * given by raw id cannot be identified, so those creates are left alone.
1620
+ */
1621
+ function assertElementCreateSetsTitle(target, fields) {
1622
+ if (!isObject(target) || target.__kind !== "element")
1623
+ return;
1624
+ const element = typeof target.name === "string" ? target.name : String(target.refName);
1625
+ let title;
1626
+ for (const field of fields) {
1627
+ if (!isObject(field) || !isObject(field.aspectFieldId) || typeof field.aspectFieldId.__kind !== "string")
1628
+ return;
1629
+ const token = field.aspectFieldId;
1630
+ if (token.tags?.includes("TITLE") === true || token.refName === "title")
1631
+ title = field;
1632
+ }
1633
+ if (title === undefined) {
1634
+ 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")`);
1635
+ }
1636
+ const reference = title.valueReference;
1637
+ const staticValue = isObject(reference) && "value" in reference ? reference.value : undefined;
1638
+ if (reference === undefined || reference === null || staticValue === "" || staticValue === null) {
1639
+ 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")`);
1640
+ }
1641
+ }
1642
+ /**
1643
+ * The platform publishes outputs only from tasks at the top level of the
1644
+ * workflow, never from a task inside a switch case or for-each loop, and
1645
+ * rejects an output whose task is not in the workflow at all.
1646
+ */
1647
+ function assertPublishableOutputTask(outputName, value, topLevelTasks, refs) {
1648
+ while (isObject(value) && "value" in value && Object.keys(value).length === 1) {
1649
+ value = value.value;
1650
+ }
1651
+ if (!isObject(value) || !isObject(value.taskReference) || typeof value.taskReference.taskRefKey !== "string")
1652
+ return;
1653
+ const taskRefKey = value.taskReference.taskRefKey;
1654
+ if (!refs.tasks.has(taskRefKey)) {
1655
+ throw new EntityTfError(`automation output "${outputName}" references task "${taskRefKey}", which is not in this automation`);
1656
+ }
1657
+ if (!topLevelTasks.some((task) => task.refKey === taskRefKey)) {
1658
+ throw new EntityTfError(`automation output "${outputName}" references task "${taskRefKey}" inside a switch case or for-each loop; ` +
1659
+ "the platform publishes outputs only from top-level tasks. Copy the value into a variable at the top level and output that.");
1660
+ }
1661
+ }
1484
1662
  /**
1485
1663
  * workflow_publish outputs must match provider Read / ei export: a typed
1486
1664
  * `jsonencode({ fieldType, multiple, taskReference|... })` envelope — not
@@ -1541,55 +1719,92 @@ function createRecordOwnFieldRefTfValue(target, name, refs) {
1541
1719
  return undefined;
1542
1720
  return expr.template(["record.", fieldId, `.${suffix}`]);
1543
1721
  }
1722
+ /**
1723
+ * The canonical reference envelope for a workflow-OUTPUT task reference —
1724
+ * `{ fieldType, multiple, taskReference:{ name:<canonical>, taskId }, … }`.
1725
+ * By the time an output reaches here its `taskReference.name` is already the
1726
+ * platform's CANONICAL service_tasks output name (build.ts's
1727
+ * `rewriteCanonicalOutputRefName`): the platform validates the published output
1728
+ * against that name (edk#835), so EDK emits it directly instead of the refs-map
1729
+ * display label. The exceptions keep their existing resolution, since they
1730
+ * reference FIELDS / declared values by EDK-owned names, not the mobius
1731
+ * display-label drift class: a task's own record field (`record.<field>`),
1732
+ * aiAgent (platform-nested via {@link aiAgentPlatformRefName}), and file-reader
1733
+ * (arbitrary schema field names). `fieldType`/`multiple` come from the generated
1734
+ * service_tasks contract (via {@link publishOutputType}). Returns undefined when
1735
+ * the target task is unresolved so the caller keeps its own fallback.
1736
+ */
1737
+ function taskReferenceEnvelope(value, refs) {
1738
+ const taskRef = value.taskReference;
1739
+ if (taskRef.name.includes('"')) {
1740
+ throw new EntityTfError(`task output name "${taskRef.name}" contains a double quote`);
1741
+ }
1742
+ const target = refs.tasks.get(taskRef.taskRefKey);
1743
+ if (target === undefined)
1744
+ return undefined;
1745
+ const canonicalName = taskRef.name;
1746
+ const isFileReaderTask = target.type === "elementum_ai_file_read_task" || target.type === "elementum_file_reader_task";
1747
+ const isAiAgentTask = target.type === "elementum_ai_agent_task";
1748
+ // A task's OWN just-created/found record FIELD (`record.<field>`) is not a
1749
+ // task-output name — it resolves by the field's own id/display name. No
1750
+ // canonical output is ever spelled `record.<field>` (the contract has
1751
+ // record/records/recordId), so that dotted prefix uniquely marks it.
1752
+ const isOwnRecordFieldRef = canonicalName.startsWith("record.");
1753
+ const ownRecordFieldRef = createRecordOwnFieldRefTfValue(target, canonicalName, refs);
1754
+ const platformRefName = ownRecordFieldRef
1755
+ ?? (isFileReaderTask
1756
+ ? canonicalName
1757
+ : isOwnRecordFieldRef
1758
+ ? taskWireRefName(canonicalName, taskRef.taskRefKey, refs)
1759
+ : isAiAgentTask
1760
+ ? aiAgentPlatformRefName(canonicalName)
1761
+ : canonicalName);
1762
+ const typed = publishOutputType(value, target, canonicalName);
1763
+ return {
1764
+ fieldType: typed.fieldType,
1765
+ multiple: typed.multiple,
1766
+ taskReference: {
1767
+ name: platformRefName,
1768
+ taskId: expr.resourceAttr(target.type, target.label, ["id"]),
1769
+ },
1770
+ // ei export always pads the unused reference arms with null.
1771
+ triggerReference: null,
1772
+ variableReference: null,
1773
+ };
1774
+ }
1544
1775
  function workflowPublishOutputEnvelope(value, refs) {
1545
1776
  if (!isObject(value))
1546
1777
  return undefined;
1547
1778
  if (isObject(value.taskReference) && typeof value.taskReference.taskRefKey === "string" && typeof value.taskReference.name === "string") {
1548
- if (value.taskReference.name.includes('"')) {
1549
- throw new EntityTfError(`task output name "${value.taskReference.name}" contains a double quote`);
1550
- }
1551
- const target = refs.tasks.get(value.taskReference.taskRefKey);
1552
- if (target === undefined)
1553
- return undefined;
1554
- const isFileReaderTask = target.type === "elementum_ai_file_read_task" || target.type === "elementum_file_reader_task";
1555
- const isAiAgentTask = target.type === "elementum_ai_agent_task";
1556
- const isAiSearchTableRecords = target.type === "elementum_ai_search_table_task" &&
1557
- (value.taskReference.name === "records" || value.taskReference.name === "All Records");
1558
- const isTableRecordsSearchRecords = target.type === "elementum_table_records_search_task" &&
1559
- (value.taskReference.name === "records" || value.taskReference.name === "All matching table rows");
1560
- const refsKey = isFileReaderTask || isAiAgentTask
1561
- ? value.taskReference.name
1562
- : isAiSearchTableRecords
1563
- ? "All Records"
1564
- : isTableRecordsSearchRecords
1565
- ? value.taskReference.name === "All matching table rows"
1566
- ? "All matching table rows"
1567
- : "records"
1568
- : taskWireRefName(value.taskReference.name, value.taskReference.taskRefKey, refs);
1569
- const ownRecordFieldRef = createRecordOwnFieldRefTfValue(target, value.taskReference.name, refs);
1570
- const platformRefName = ownRecordFieldRef ?? (isAiAgentTask
1571
- ? aiAgentPlatformRefName(refsKey)
1572
- : refsKey);
1573
- const typed = publishOutputType(value, target, refsKey);
1574
- return {
1575
- fieldType: typed.fieldType,
1576
- multiple: typed.multiple,
1577
- taskReference: {
1578
- name: platformRefName,
1579
- taskId: expr.resourceAttr(target.type, target.label, ["id"]),
1580
- },
1581
- // ei export always pads the unused reference arms with null.
1582
- triggerReference: null,
1583
- variableReference: null,
1584
- };
1779
+ return taskReferenceEnvelope(value, refs);
1585
1780
  }
1586
1781
  if (isObject(value.triggerReference) && typeof value.triggerReference.name === "string") {
1782
+ const inputName = onDemandTriggerRefKey(value.triggerReference.name, [...refs.triggerParamFieldTypes.keys()]);
1783
+ const input = refs.triggerParamFieldTypes.get(inputName);
1784
+ if (input !== undefined) {
1785
+ // The platform stores a reference to an on-demand input under the
1786
+ // input's normalized name ("TICKET_ID" → "ticketId") and reads it back
1787
+ // that way, so emit that name rather than the declared one; the
1788
+ // envelope carries the input's declared type.
1789
+ const typed = typeof value.fieldType === "string"
1790
+ ? { fieldType: value.fieldType, multiple: value.multiple === true }
1791
+ : input;
1792
+ return {
1793
+ fieldType: typed.fieldType,
1794
+ multiple: typed.multiple,
1795
+ taskReference: null,
1796
+ triggerReference: { name: normalizeOnDemandParamKey(inputName) },
1797
+ variableReference: null,
1798
+ };
1799
+ }
1587
1800
  const typed = publishOutputType(value, undefined, value.triggerReference.name);
1588
1801
  return {
1589
1802
  fieldType: typed.fieldType,
1590
1803
  multiple: typed.multiple,
1591
1804
  taskReference: null,
1592
- triggerReference: { name: wireRefName(value.triggerReference.name, refs.owner) },
1805
+ triggerReference: {
1806
+ name: onDemandTriggerRefName(value.triggerReference.name, refs) ?? wireRefName(value.triggerReference.name, refs.owner),
1807
+ },
1593
1808
  variableReference: null,
1594
1809
  };
1595
1810
  }
@@ -1657,6 +1872,16 @@ function publishOutputType(value, target, wireName) {
1657
1872
  if (fromSchema !== undefined)
1658
1873
  return fromSchema;
1659
1874
  }
1875
+ // Canonical reference model: for a workflow OUTPUT, `wireName` is the platform's
1876
+ // canonical output name — take fieldType + multiple straight from the generated
1877
+ // service_tasks contract. The display-name heuristics below stay for the legacy
1878
+ // forms. See DESIGN-canonical-reference-model.md.
1879
+ if (target !== undefined) {
1880
+ const executor = RESOURCE_TYPE_TO_EXECUTOR[target.type];
1881
+ const contract = executor !== undefined ? TASK_OUTPUT_CONTRACTS[executor]?.[wireName] : undefined;
1882
+ if (contract !== undefined)
1883
+ return { fieldType: contract.fieldType, multiple: contract.multiple };
1884
+ }
1660
1885
  if (target !== undefined) {
1661
1886
  if ((target.type === "elementum_create_record_task" || target.type === "elementum_find_related_records_task") &&
1662
1887
  (wireName === "Record" || wireName === "Record ID")) {
@@ -1673,6 +1898,38 @@ function publishOutputType(value, target, wireName) {
1673
1898
  }
1674
1899
  return { fieldType: "TEXT", multiple: value.multiple === true };
1675
1900
  }
1901
+ function collectUnresolvedForEachItems(value, found) {
1902
+ if (Array.isArray(value)) {
1903
+ for (const item of value)
1904
+ collectUnresolvedForEachItems(item, found);
1905
+ return;
1906
+ }
1907
+ if (!isObject(value))
1908
+ return;
1909
+ if (typeof value.__edkUnresolvedForEachItem === "string") {
1910
+ const path = Array.isArray(value.path) ? value.path.filter((segment) => typeof segment === "string").join(".") : "";
1911
+ found.push({ ref: value.__edkUnresolvedForEachItem, path });
1912
+ }
1913
+ for (const nested of Object.values(value))
1914
+ collectUnresolvedForEachItems(nested, found);
1915
+ }
1916
+ function unresolvedForEachFailures(entity, payload, address) {
1917
+ const found = [];
1918
+ collectUnresolvedForEachItems(payload, found);
1919
+ if (found.length === 0)
1920
+ return [];
1921
+ const name = "name" in payload && typeof payload.name === "string" && payload.name !== "" ? payload.name : entity.refName;
1922
+ return found.map((item) => ({
1923
+ severity: "fatal",
1924
+ address,
1925
+ name,
1926
+ ownerKind: "automation",
1927
+ message: `unresolved forEach item reference to "${item.ref}"${item.path !== "" ? `.${item.path}` : ""}: ` +
1928
+ "EDK cannot express a reference to a sibling loop's current item (only an enclosing loop, as " +
1929
+ "ctx.loops.<name>.item) - re-express this by hand " +
1930
+ "(e.g. restructure the loops, or pass the value through a variable) before this automation can build",
1931
+ }));
1932
+ }
1676
1933
  function valueToTf(value, refs) {
1677
1934
  const catalog = token(value);
1678
1935
  if (catalog !== undefined)
@@ -1685,14 +1942,16 @@ function valueToTf(value, refs) {
1685
1942
  throw new EntityTfError(`unsupported automation value ${String(value)}`);
1686
1943
  if (typeof value.__edkUnresolvedForEachItem === "string") {
1687
1944
  // Printed by print-automation.ts for a forEachItemRef pointing at a
1688
- // sibling or non-nearest-ancestor loop - EDK has no authoring primitive
1689
- // for "another loop's current item". Fail the build loudly instead of
1690
- // silently reinterpreting this as a task-output reference: `ctx.actions`
1691
- // would have turned ANY property-access shape into a real, but WRONG,
1692
- // task ref (review feedback on PR #1097, cursor[bot]).
1945
+ // sibling loop - one that doesn't enclose the task. EDK has no
1946
+ // authoring form for it (an enclosing loop is ctx.loops.<name>.item,
1947
+ // #1320). Fail the build loudly instead of silently reinterpreting
1948
+ // this as a task-output reference: `ctx.actions` would have turned ANY
1949
+ // property-access shape into a real, but WRONG, task ref (review
1950
+ // feedback on PR #1097, cursor[bot]).
1693
1951
  const path = Array.isArray(value.path) ? value.path.join(".") : "";
1694
1952
  throw new EntityTfError(`unresolved forEach item reference to "${value.__edkUnresolvedForEachItem}"${path ? `.${path}` : ""}: ` +
1695
- `EDK cannot express a reference to another loop's current item - re-express this by hand ` +
1953
+ `EDK cannot express a reference to a sibling loop's current item (only an enclosing loop, as ` +
1954
+ `ctx.loops.<name>.item) - re-express this by hand ` +
1696
1955
  `(e.g. restructure the loops, or pass the value through a variable) before this automation can build`);
1697
1956
  }
1698
1957
  if (value.__unsafe === "platformId" && typeof value.value === "string") {
@@ -1701,6 +1960,10 @@ function valueToTf(value, refs) {
1701
1960
  }
1702
1961
  if ("value" in value && Object.keys(value).length === 1)
1703
1962
  return valueToTf(value.value, refs);
1963
+ if (value.kind === "requiredSecret" && typeof value.variable === "string") {
1964
+ refs.requiredSecrets.add(value.variable);
1965
+ return expr.variable(value.variable);
1966
+ }
1704
1967
  if (isObject(value.variableReference) && typeof value.variableReference.id === "string") {
1705
1968
  const target = refs.variableById.get(value.variableReference.id);
1706
1969
  if (target === undefined)
@@ -1726,7 +1989,13 @@ function valueToTf(value, refs) {
1726
1989
  const target = refs.tasks.get(value.forEachReference.forEachTaskRefKey);
1727
1990
  if (target === undefined)
1728
1991
  throw new EntityTfError(`unresolved forEach ref "${value.forEachReference.forEachTaskRefKey}"`);
1729
- const index = forEachWireRefName(value.forEachReference.name, refs.owner, refs.recordItemForEachRefKeys.has(value.forEachReference.forEachTaskRefKey));
1992
+ const source = refs.recordItemForEachSourceByRefKey.get(value.forEachReference.forEachTaskRefKey);
1993
+ const sourceApp = source === undefined ? undefined : refs.recordFieldContext?.taskAppRefNameByRefKey?.[source];
1994
+ const index = forEachWireRefName(value.forEachReference.name, source === undefined || sourceApp === undefined
1995
+ ? refs.owner
1996
+ : recordOwnerContext(refs.owner, sourceApp, taskTargetKind(source, refs), sourceApp === refs.owner.appRefName
1997
+ ? refs.owner.fieldNames
1998
+ : fieldNamesForAppRefName(refs.fieldNamesByAppRefName, sourceApp) ?? refs.owner.fieldNames), refs.recordItemForEachRefKeys.has(value.forEachReference.forEachTaskRefKey));
1730
1999
  return expr.resourceAttr(target.type, target.label, ["inner", "refs", { index }]);
1731
2000
  }
1732
2001
  if (isObject(value.templateReference))
@@ -1756,6 +2025,72 @@ function unwrapDefault(value) {
1756
2025
  const values = Object.values(value);
1757
2026
  return values.length === 1 ? values[0] : value;
1758
2027
  }
2028
+ /** `options` is filled only from picklistValues, so a related-record dropdown is a PICKLIST with none. */
2029
+ function isOptionBearingPicklist(metadata) {
2030
+ return metadata?.fieldType === "PICKLIST" && (metadata.options?.length ?? 0) > 0;
2031
+ }
2032
+ /** 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. */
2033
+ function isIdentityField(metadata) {
2034
+ return metadata?.fieldType === "USER" || metadata?.fieldType === "GROUP";
2035
+ }
2036
+ /**
2037
+ * A filter on an on-demand record input's field. The platform names it
2038
+ * `<parameter>.<fieldId>` (the internal path `availableReferences` reports
2039
+ * for every record input, `record.<fieldId>` included), so the short form is
2040
+ * `trigger.<parameter>.<fieldId>[.<suffix>]`. `filter_refs` only carries
2041
+ * whole parameters and has no key for a field.
2042
+ */
2043
+ function onDemandRecordFieldPath(name, refs) {
2044
+ const paramName = refs.recordParamNames
2045
+ .filter((param) => name.startsWith(`${param}.`))
2046
+ .sort((a, b) => b.length - a.length)[0];
2047
+ if (paramName === undefined)
2048
+ return undefined;
2049
+ const [fieldKey, ...rest] = name.slice(paramName.length + 1).split(".");
2050
+ if (fieldKey === undefined || fieldKey === "")
2051
+ return undefined;
2052
+ const target = refs.recordParamTargets.get(paramName);
2053
+ if (target === undefined) {
2054
+ throw new EntityTfError(`onDemand record parameter "${paramName}" is missing its target app/element`);
2055
+ }
2056
+ const isOwner = target.refName === refs.owner.appRefName && (target.__kind ?? refs.owner.parentScope) === refs.owner.parentScope;
2057
+ return { paramName, fieldKey, suffix: rest.join("."), target, isOwner };
2058
+ }
2059
+ function onDemandRecordFieldFilterReference(name, refs, operator) {
2060
+ const path = onDemandRecordFieldPath(name, refs);
2061
+ if (path === undefined)
2062
+ return undefined;
2063
+ const { paramName, fieldKey, suffix, target, isOwner } = path;
2064
+ if (fieldKey.startsWith(UNRESOLVED_FIELD_MARKER))
2065
+ return `trigger.${name.replace(UNRESOLVED_FIELD_MARKER, "")}`;
2066
+ const fieldAddresses = isOwner ? refs.owner.fieldAddresses : fieldNamesForAppRefName(refs.fieldAddressesByAppRefName, target.refName);
2067
+ if (suffix.length === 0 && isOwner && isOptionBearingPicklist(refs.owner.fieldMetadata.get(fieldKey)) && operator !== "is_null") {
2068
+ throw new EntityTfError(`filter reference to picklist field "${fieldKey}" is ambiguous — write ".id" ` +
2069
+ `(ctx.trigger.${paramName}.${fieldKey}.id) or ".label" (ctx.trigger.${paramName}.${fieldKey}.label) explicitly.`);
2070
+ }
2071
+ const wireSuffix = suffix === "recordId"
2072
+ ? "10000001-2000-4000-a000-800000000000"
2073
+ : suffix.length === 0 && isOwner && isOptionBearingPicklist(refs.owner.fieldMetadata.get(fieldKey)) ? "id"
2074
+ : suffix.length === 0 && isOwner && operator === "is_null" && isIdentityField(refs.owner.fieldMetadata.get(fieldKey)) ? "id" : suffix;
2075
+ const tail = wireSuffix.length > 0 ? [`.${wireSuffix}`] : [];
2076
+ const address = fieldAddresses?.get(fieldKey);
2077
+ if (address !== undefined) {
2078
+ return expr.template([`trigger.${paramName}.`, addressExpr(address, ["id"]), ...tail]);
2079
+ }
2080
+ const targetTfLabel = isOwner
2081
+ ? refs.owner.appTfLabel
2082
+ : refs.owner.workspaceAspects?.get(workspaceAspectKey(target.__kind === "element" ? "element" : "app", target.refName))?.tfLabel;
2083
+ const isSystemField = (target.__kind ?? refs.owner.parentScope) === "element"
2084
+ ? ELEMENT_SYSTEM_FIELD_KEYS.includes(fieldKey)
2085
+ : SYSTEM_FIELD_KEY_SET.has(fieldKey);
2086
+ if (isSystemField && targetTfLabel !== undefined) {
2087
+ return expr.template([`trigger.${paramName}.`, expr.local(`${targetTfLabel}_${tsLabelToTfLabel(fieldKey)}_field_id`), ...tail]);
2088
+ }
2089
+ if (isUuid(fieldKey))
2090
+ return `trigger.${name}`;
2091
+ throw new EntityTfError(`filter reference to "${fieldKey}" on on-demand record input "${paramName}": ${target.refName} is not built in this ` +
2092
+ `workspace or has no field "${fieldKey}", so its field id cannot be resolved`);
2093
+ }
1759
2094
  function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1760
2095
  // Raw pass-through for a filter left side the pull-time deserializer
1761
2096
  // couldn't decode to a typed ref (filter.ts's leftDescriptor, matching the
@@ -1775,23 +2110,20 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1775
2110
  // convention from the `.refs[...]` map lookup used for task inputs.
1776
2111
  // Reproduce it via a template so the field id stays a real reference
1777
2112
  // (never hardcoded), matching the actual export byte-for-byte.
2113
+ if (refs.trigger.type === TRIGGER_RESOURCES.onDemand) {
2114
+ const recordField = onDemandRecordFieldFilterReference(value.name, refs, operator);
2115
+ if (recordField !== undefined)
2116
+ return recordField;
2117
+ }
1778
2118
  const parts = value.name.split(".");
1779
2119
  if (parts[0] === "record" && parts.length >= 2) {
1780
2120
  const fieldKey = parts[1];
1781
2121
  const address = refs.owner.fieldAddresses.get(fieldKey);
1782
2122
  const suffix = parts.slice(2).join(".");
1783
2123
  let wireSuffix = suffix === "recordId" ? "10000001-2000-4000-a000-800000000000" : suffix;
1784
- // A bare reference to a PICKLIST field (STATUS/STAGE included —
1785
- // `serializeSystemFields` wire-wraps both as a picklist too) has no
1786
- // valid suffix-less wire form — confirmed live via the platform's
1787
- // own switch-case editor, which always sends an explicit `.id`
1788
- // (compare by the chosen option's real id) or `.label` (compare by
1789
- // display text, unvalidated) and never a bare `record.<fieldId>`.
1790
- // Comparisons stay ambiguous (eq/in/…). Null-checks are equivalent
1791
- // for `.id` and `.label` when no option is selected, so
1792
- // `isNull`/`isNotNull` on a bare Dropdown emit the platform editor's
1793
- // `.id` + uuid shape — the Accept `isNotNull(record.dropdown)` form.
1794
- if (suffix.length === 0 && refs.owner.fieldMetadata.get(fieldKey)?.fieldType === "PICKLIST") {
2124
+ // An option-bearing picklist has no bare wire form. The platform editor
2125
+ // sends `.id` or `.label`, and a null-check emits `.id`.
2126
+ if (suffix.length === 0 && isOptionBearingPicklist(refs.owner.fieldMetadata.get(fieldKey))) {
1795
2127
  if (operator === "is_null") {
1796
2128
  wireSuffix = "id";
1797
2129
  }
@@ -1801,6 +2133,8 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1801
2133
  `(ctx.trigger.record.${fieldKey}.label, compare by display text) explicitly.`);
1802
2134
  }
1803
2135
  }
2136
+ if (suffix.length === 0 && operator === "is_null" && isIdentityField(refs.owner.fieldMetadata.get(fieldKey)))
2137
+ wireSuffix = "id";
1804
2138
  if (refs.trigger.type === TRIGGER_RESOURCES.datamine && refs.triggerDatamineTable !== undefined) {
1805
2139
  const table = refs.triggerDatamineTable;
1806
2140
  const tableAttr = resolveTableColumnFieldExpr({
@@ -1863,6 +2197,12 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1863
2197
  }
1864
2198
  const triggerRefKey = triggerWireRefName(value.name, refs);
1865
2199
  if (refs.trigger.type === TRIGGER_RESOURCES.onDemand) {
2200
+ // filter_refs holds only declared inputs, so the clicking user has no key there.
2201
+ if (ON_DEMAND_TRIGGERED_BY_REFS[value.name] !== undefined) {
2202
+ throw new EntityTfError(`filter on ctx.trigger.${value.name}: an on-demand filter can only reference declared inputs, ` +
2203
+ `and the platform publishes no filter reference for the user who ran the automation. ` +
2204
+ `Read ctx.trigger.triggeredBy in a task input instead.`);
2205
+ }
1866
2206
  return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["filter_refs", { index: triggerRefKey }]);
1867
2207
  }
1868
2208
  return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: triggerRefKey }]);
@@ -1919,12 +2259,45 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1919
2259
  },
1920
2260
  });
1921
2261
  }
2262
+ const ambiguousRecordField = recordRefKeyIsAmbiguous(value.name, wireName, value.taskRefKey, refs)
2263
+ ? foundRecordFieldReferenceName(task.type, value.name, value.taskRefKey, refs)
2264
+ : undefined;
2265
+ if (ambiguousRecordField !== undefined) {
2266
+ return expr.jsonencode({
2267
+ fieldType: (realType ?? "TEXT").toUpperCase(),
2268
+ multiple: false,
2269
+ taskReference: {
2270
+ name: expr.template(ambiguousRecordField),
2271
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2272
+ },
2273
+ });
2274
+ }
2275
+ // A field id the workspace cannot resolve (a foreign element's field)
2276
+ // has no display label to key `refs` by; only the envelope names it.
2277
+ const unresolvedFieldId = wireName.split(".")[1];
2278
+ if (wireName.startsWith("record.") && unresolvedFieldId !== undefined && isUuid(unresolvedFieldId)) {
2279
+ return expr.jsonencode({
2280
+ fieldType: (realType ?? "TEXT").toUpperCase(),
2281
+ multiple: false,
2282
+ taskReference: {
2283
+ name: wireName,
2284
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2285
+ },
2286
+ });
2287
+ }
1922
2288
  return expr.resourceAttr(task.type, task.label, ["refs", { index: wireName }]);
1923
2289
  }
2290
+ const recordFieldName = foundRecordFieldReferenceName(task.type, value.name, value.taskRefKey, refs);
2291
+ // The short form addresses user-search outputs by path; only `.refs`
2292
+ // is keyed by their display labels.
2293
+ const shortName = task.type === TASK_RESOURCES.userSearch
2294
+ ? USER_SEARCH_PATH_BY_WIRE_NAME.get(wireName) ?? wireName
2295
+ : wireName;
1924
2296
  return expr.template([
1925
2297
  "task.",
1926
2298
  expr.resourceAttr(task.type, task.label, ["id"]),
1927
- `.${wireName}`,
2299
+ ".",
2300
+ ...(recordFieldName ?? [shortName]),
1928
2301
  ]);
1929
2302
  }
1930
2303
  case "FOR_EACH": {
@@ -1936,7 +2309,7 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1936
2309
  return expr.template([
1937
2310
  "for_each.",
1938
2311
  expr.resourceAttr(task.type, task.label, ["id"]),
1939
- `.${forEachCompactFilterName(value.name)}`,
2312
+ `.${forEachCompactFilterName(value.name, refs.recordItemForEachRefKeys.has(value.forEachTaskRefKey))}`,
1940
2313
  ]);
1941
2314
  }
1942
2315
  case "VALUE":
@@ -2008,9 +2381,9 @@ function picklistFilterValueToTf(value, field, refs) {
2008
2381
  // Table siblings excluded for the same reason as in `crossAppFieldToTf`: a
2009
2382
  // picklist field's owner is an app or an element, never a table.
2010
2383
  if (sibling !== undefined && sibling.kind !== "table" && sibling.kind !== "task") {
2011
- const localName = field.tags?.includes("STATUS")
2384
+ const localName = sibling.kind === "app" && field.tags?.includes("STATUS")
2012
2385
  ? `${sibling.tfLabel}_status_options_by_label`
2013
- : field.tags?.includes("STAGE")
2386
+ : sibling.kind === "app" && field.tags?.includes("STAGE")
2014
2387
  ? `${sibling.tfLabel}_stage_options_by_label`
2015
2388
  : `${scopedResourceLabel(sibling.tfLabel, tsLabelToTfLabel(field.refName), sibling.kind)}_options_by_label`;
2016
2389
  return expr.local(localName, [{ index: value }]);
@@ -2019,26 +2392,27 @@ function picklistFilterValueToTf(value, field, refs) {
2019
2392
  if (field.parent !== undefined && (field.parent !== refs.owner.appRefName || field.parentKind === "element")) {
2020
2393
  // A foreign field's options-by-label local is sourced from
2021
2394
  // `data.elementum_field.<label>.options` (issue #353) rather than an
2022
- // owned resource's `options` attribute — `crossAppFieldToTf` registers
2023
- // both the data block and the matching local; reuse the SAME naming
2024
- // (`foreignFieldNaming`) so this reference always lines up with
2025
- // whatever label that registration used, then make sure the data block
2026
- // (and local) actually gets registered even when nothing else in this
2027
- // payload resolves the field's id.
2028
- const naming = foreignFieldNaming(field);
2029
- crossAppFieldToTf(field, refs.owner, refs.dataBlocks);
2030
- return expr.local(naming.fieldLabel + "_options_by_label", [{ index: value }]);
2031
- }
2032
- const localName = field.tags?.includes("STATUS")
2395
+ // owned resource's `options` attribute. Registering here also covers a
2396
+ // payload where nothing else resolves the field's id.
2397
+ const fieldLabel = registerForeignFieldLookup(field, refs.owner, refs.dataBlocks);
2398
+ return expr.local(fieldLabel + "_options_by_label", [{ index: value }]);
2399
+ }
2400
+ const localName = refs.owner.parentScope === "app" && field.tags?.includes("STATUS")
2033
2401
  ? `${refs.owner.appTfLabel}_status_options_by_label`
2034
- : field.tags?.includes("STAGE")
2402
+ : refs.owner.parentScope === "app" && field.tags?.includes("STAGE")
2035
2403
  ? `${refs.owner.appTfLabel}_stage_options_by_label`
2036
- : `${scopedLabel(refs.owner.appTfLabel, tsLabelToTfLabel(field.refName))}_options_by_label`;
2404
+ : `${scopedResourceLabel(refs.owner.appTfLabel, tsLabelToTfLabel(field.refName), refs.owner.parentScope)}_options_by_label`;
2037
2405
  return expr.local(localName, [{ index: value }]);
2038
2406
  }
2039
- function triggerRecordFieldPath(reference) {
2407
+ function triggerRecordFieldPath(reference, refs) {
2040
2408
  if (!isObject(reference) || typeof reference.name !== "string")
2041
2409
  return undefined;
2410
+ if (refs.trigger.type === TRIGGER_RESOURCES.onDemand && reference.type?.toString().toUpperCase() === "TRIGGER") {
2411
+ const onDemandPath = onDemandRecordFieldPath(reference.name, refs);
2412
+ // Field metadata is only known for the automation's own app or element.
2413
+ if (onDemandPath !== undefined)
2414
+ return onDemandPath.isOwner ? onDemandPath : undefined;
2415
+ }
2042
2416
  const path = reference.name.split(".");
2043
2417
  if (path[0] !== "record" || path.length < 2)
2044
2418
  return undefined;
@@ -2047,10 +2421,15 @@ function triggerRecordFieldPath(reference) {
2047
2421
  function fieldFromFilterLeftValue(value, refs) {
2048
2422
  if (isObject(value) && value.type === "FIELD")
2049
2423
  return token(value.value ?? value.field);
2050
- if (!isObject(value) || !isObject(value.value) || value.value.type?.toString().toUpperCase() !== "TRIGGER") {
2424
+ if (!isObject(value) || !isObject(value.value))
2051
2425
  return undefined;
2052
- }
2053
- const parsed = triggerRecordFieldPath(value.value);
2426
+ const referenceType = value.value.type?.toString().toUpperCase();
2427
+ const ownAppTask = referenceType === "TASK" &&
2428
+ typeof value.value.taskRefKey === "string" &&
2429
+ taskSearchesOwnerApp(value.value.taskRefKey, refs);
2430
+ if (referenceType !== "TRIGGER" && !ownAppTask)
2431
+ return undefined;
2432
+ const parsed = triggerRecordFieldPath(value.value, refs);
2054
2433
  if (parsed === undefined)
2055
2434
  return undefined;
2056
2435
  const { fieldKey: refName, suffix } = parsed;
@@ -2067,22 +2446,57 @@ function fieldFromFilterLeftValue(value, refs) {
2067
2446
  return undefined;
2068
2447
  return { __kind: "field", refName, ...metadata };
2069
2448
  }
2449
+ function taskSearchesOwnerApp(taskRefKey, refs) {
2450
+ const task = refs.tasks.get(taskRefKey);
2451
+ if (task === undefined || !FOUND_RECORD_TASK_TYPES.has(task.type))
2452
+ return false;
2453
+ const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
2454
+ return taskApp === undefined || taskApp === refs.owner.appRefName;
2455
+ }
2456
+ /**
2457
+ * `refs` is keyed by display label, so a drilled-down record field (the
2458
+ * Stage field's `.id` is "Stage ID") can share its key with another field's
2459
+ * own label (a custom "Stage ID" text field) on the same app.
2460
+ */
2461
+ function recordRefKeyIsAmbiguous(name, wireName, taskRefKey, refs) {
2462
+ const segments = name.split(".");
2463
+ if (segments[0] !== "record" || segments.length < 3)
2464
+ return false;
2465
+ const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
2466
+ const fieldNames = taskApp === undefined || taskApp === refs.owner.appRefName
2467
+ ? refs.owner.fieldNames
2468
+ : fieldNamesForAppRefName(refs.fieldNamesByAppRefName, taskApp);
2469
+ for (const [fieldKey, fieldName] of fieldNames ?? []) {
2470
+ if (fieldKey !== segments[1] && fieldName === wireName)
2471
+ return true;
2472
+ }
2473
+ return false;
2474
+ }
2070
2475
  function filterToTf(value, refs) {
2071
2476
  return serializeFilterToTf(value, {
2072
2477
  field: (field) => valueToTf(field, refs),
2073
2478
  fieldFromLeftValue: (left) => fieldFromFilterLeftValue(left, refs),
2074
2479
  reference: (reference, role, realType, operator) => filterReferenceToTf(reference, refs, role ?? "value", realType, operator),
2075
2480
  referenceRealType: (reference, _role, authored) => {
2076
- const parsed = triggerRecordFieldPath(reference);
2481
+ if (!isObject(reference) || reference.type?.toString().toUpperCase() !== "TRIGGER")
2482
+ return authored;
2483
+ const parsed = triggerRecordFieldPath(reference, refs);
2077
2484
  if (parsed === undefined)
2078
2485
  return authored;
2079
2486
  const metadata = refs.owner.fieldMetadata.get(parsed.fieldKey);
2487
+ // A suffix-less option picklist is a UUID. A bare dynamic dropdown is stored as text.
2488
+ if (parsed.suffix === "" && metadata?.fieldType === "PICKLIST" && !isOptionBearingPicklist(metadata)) {
2489
+ return authored;
2490
+ }
2080
2491
  const inferred = referenceValueTypeForField(metadata?.fieldType, parsed.suffix);
2081
2492
  if (inferred === undefined)
2082
2493
  return authored;
2083
- // Operator fallbacks and `filter.text()` are TEXT. Field metadata is
2084
- // the authority for a known trigger-record field (PICKLIST .id → UUID).
2085
- // Explicit non-TEXT wrappers (`filter.uuid()`, `filter.number()`, …) win.
2494
+ // This hook only sees unmarked references. `filter.text()` and the
2495
+ // other typed wrappers set `explicit`, and the filter codec keeps that
2496
+ // type before calling here. What remains is the operator fallback:
2497
+ // TEXT on an unwrapped trigger-record field yields to field metadata
2498
+ // (PICKLIST `.id` → UUID). A non-TEXT fallback (`gt` → NUMBER) already
2499
+ // names its type.
2086
2500
  const authoredNorm = authored?.toUpperCase();
2087
2501
  if (authoredNorm !== undefined && authoredNorm !== "TEXT")
2088
2502
  return authored;
@@ -2091,6 +2505,8 @@ function filterToTf(value, refs) {
2091
2505
  literal: (literal, field) => picklistFilterValueToTf(literal, token(field), refs) ?? valueToTf(literal, refs),
2092
2506
  });
2093
2507
  }
2508
+ /** System fields the platform stamps itself; a record-updated trigger can only watch Title, Status and Stage. */
2509
+ const UNWATCHABLE_SYSTEM_FIELD_KEYS = new Set(SYSTEM_FIELD_KEYS.filter((key) => key !== "title" && key !== "status" && key !== "stage"));
2094
2510
  function configAttrs(kind, config, refs) {
2095
2511
  const attrs = {};
2096
2512
  for (const [key, raw] of Object.entries(config)) {
@@ -2338,6 +2754,24 @@ function configAttrs(kind, config, refs) {
2338
2754
  });
2339
2755
  continue;
2340
2756
  }
2757
+ if (key === "changedFieldIds" && Array.isArray(raw)) {
2758
+ const watched = raw.filter((field) => {
2759
+ const fieldToken = token(field);
2760
+ if (fieldToken?.__kind !== "field" ||
2761
+ !UNWATCHABLE_SYSTEM_FIELD_KEYS.has(fieldToken.refName) ||
2762
+ refs.owner.fieldAddresses.has(fieldToken.refName))
2763
+ return true;
2764
+ refs.owner.diagnostics.push(`changedFields: system field "${fieldToken.name ?? fieldToken.refName}" is platform-managed and cannot be watched; dropped`);
2765
+ return false;
2766
+ });
2767
+ // An omitted or empty changed_fields fires the trigger on every field change.
2768
+ if (watched.length === 0 && raw.length > 0) {
2769
+ throw new EntityTfError("changedFields lists only platform-managed system fields, which cannot be watched; " +
2770
+ "list at least one other field, or leave changedFields out to fire on any change");
2771
+ }
2772
+ attrs.changed_fields = valueToTf(watched, refs);
2773
+ continue;
2774
+ }
2341
2775
  if (key === "inputs" && kind === "elementum_on_demand_trigger") {
2342
2776
  if (!Array.isArray(raw))
2343
2777
  throw new EntityTfError("onDemand inputs must be an array");
@@ -2350,8 +2784,9 @@ function configAttrs(kind, config, refs) {
2350
2784
  CONFIG_ATTRS[k] ?? snake(k),
2351
2785
  valueToTf(k === "defaultValue" ? unwrapDefault(v) :
2352
2786
  k === "type" && v === "ATTACHMENT_ID" ? "attachment" :
2353
- k === "type" && v === "ASPECT_RECORD" ? "record" :
2354
- k === "type" && typeof v === "string" ? v.toLowerCase() : v, refs),
2787
+ k === "type" && v === "USER_ID" ? "user" :
2788
+ k === "type" && v === "ASPECT_RECORD" ? "record" :
2789
+ k === "type" && typeof v === "string" ? v.toLowerCase() : v, refs),
2355
2790
  ]));
2356
2791
  if (isOnDemandRecordType(typeof input.type === "string" ? input.type : undefined)) {
2357
2792
  const target = token(input.app);
@@ -2371,6 +2806,8 @@ function configAttrs(kind, config, refs) {
2371
2806
  if (key === "workflowFields") {
2372
2807
  if (!Array.isArray(raw))
2373
2808
  throw new EntityTfError("workflowFields must be an array");
2809
+ if (kind === "elementum_create_record_task")
2810
+ assertElementCreateSetsTitle(config.aspectId, raw);
2374
2811
  attrs.fields = raw.map((field) => {
2375
2812
  if (!isObject(field))
2376
2813
  throw new EntityTfError("workflow field must be an object");
@@ -2402,6 +2839,7 @@ function configAttrs(kind, config, refs) {
2402
2839
  ...(field.operation === "ADD" ? { update_mode: "add" } : {}),
2403
2840
  };
2404
2841
  }
2842
+ assertLiteralFitsFieldType(staticValue, fieldToken);
2405
2843
  const optionValue = staticValue !== undefined
2406
2844
  ? picklistFilterValueToTf(staticValue, fieldToken, refs)
2407
2845
  : undefined;
@@ -2534,6 +2972,12 @@ function configAttrs(kind, config, refs) {
2534
2972
  };
2535
2973
  continue;
2536
2974
  }
2975
+ // The platform stores whatever string it is given and the trigger or task
2976
+ // then never matches an alias, so an alias name instead of its id only
2977
+ // shows up as mail that is silently not ingested.
2978
+ if (key === "emailAliasId" && typeof raw === "string" && !UUID_PATTERN.test(raw)) {
2979
+ throw new EntityTfError(`emailAliasId "${raw}" is not an email alias id; pass the alias's platform id (a UUID), not its name or address`);
2980
+ }
2537
2981
  const attr = CONFIG_ATTRS[key] ?? snake(key);
2538
2982
  attrs[attr] = valueToTf(raw, refs);
2539
2983
  }
@@ -2582,6 +3026,9 @@ export function automationToTf(entity, ctx) {
2582
3026
  workspaceAspects: ctx.workspaceAspects,
2583
3027
  diagnostics: ctx.diagnostics ?? [],
2584
3028
  activeAutomationRefNames: ctx.activeAutomationRefNames,
3029
+ ...(ctx.elementsWithoutAuditFields !== undefined ? { elementsWithoutAuditFields: ctx.elementsWithoutAuditFields } : {}),
3030
+ ...(ctx.fieldAddressesByAppRefName !== undefined ? { fieldAddressesByAppRefName: ctx.fieldAddressesByAppRefName } : {}),
3031
+ recordLacksAuditFields: ctx.parentScope === "element" && ctx.ownerAuditFields !== true,
2585
3032
  };
2586
3033
  if (entity.kind !== "automation")
2587
3034
  throw new EntityTfError(`automationToTf expects kind "automation"; got "${entity.kind}"`);
@@ -2591,6 +3038,9 @@ export function automationToTf(entity, ctx) {
2591
3038
  const payload = entity.payload;
2592
3039
  if (payload === null || typeof payload !== "object" || Array.isArray(payload))
2593
3040
  throw new EntityTfError(`automation "${entity.refName}" has a non-object payload`);
3041
+ const unresolved = unresolvedForEachFailures(entity, payload, `${AUTOMATION_RESOURCE_TYPE}.${automationTfLabel}`);
3042
+ if (unresolved.length > 0)
3043
+ throw new ValidationFailureError(unresolved);
2594
3044
  if (typeof payload.workflowRevision !== "string")
2595
3045
  throw new EntityTfError(`automation "${entity.refName}" has no workflowRevision`);
2596
3046
  const label = automationTfLabel;
@@ -2690,7 +3140,7 @@ export function automationToTf(entity, ctx) {
2690
3140
  // output. Everything else - a script array, a file-reader payload, an API
2691
3141
  // response, a variable, a nested item sub-array - keys its items by their
2692
3142
  // own keys, so their names pass through untouched.
2693
- const recordItemForEachRefKeys = new Set([...forEachCollectionByRefKey].flatMap(([refKey, collection]) => {
3143
+ const recordItemForEachSourceByRefKey = new Map([...forEachCollectionByRefKey].flatMap(([refKey, collection]) => {
2694
3144
  if (!isObject(collection) || !isObject(collection.taskReference))
2695
3145
  return [];
2696
3146
  const sourceRefKey = collection.taskReference.taskRefKey;
@@ -2698,9 +3148,10 @@ export function automationToTf(entity, ctx) {
2698
3148
  return [];
2699
3149
  const sourceWireType = wireTypeByRefKey.get(sourceRefKey);
2700
3150
  return sourceWireType !== undefined && RECORD_COLLECTION_TASK_WIRE_TYPES.has(sourceWireType)
2701
- ? [refKey]
3151
+ ? [[refKey, sourceRefKey]]
2702
3152
  : [];
2703
3153
  }));
3154
+ const recordItemForEachRefKeys = new Set(recordItemForEachSourceByRefKey.keys());
2704
3155
  const dataBlocks = new Map();
2705
3156
  const recordFieldContext = recordFieldContextOf(entity);
2706
3157
  const triggerParamNames = triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
@@ -2711,6 +3162,15 @@ export function automationToTf(entity, ctx) {
2711
3162
  ? [input.name]
2712
3163
  : [])
2713
3164
  : [];
3165
+ const userParamNames = triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
3166
+ ? triggerConfig.inputs.flatMap((input) => isObject(input) && typeof input.name === "string" && input.type === "USER_ID" ? [input.name] : [])
3167
+ : [];
3168
+ const triggerParamFieldTypes = new Map(triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
3169
+ ? triggerConfig.inputs.flatMap((input) => isObject(input) && typeof input.name === "string" && typeof input.type === "string" &&
3170
+ !isOnDemandRecordType(input.type)
3171
+ ? [[input.name, { fieldType: input.type, multiple: input.multiple === true }]]
3172
+ : [])
3173
+ : []);
2714
3174
  const recordParamTargets = new Map(triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
2715
3175
  ? triggerConfig.inputs.flatMap((input) => {
2716
3176
  if (!isObject(input) ||
@@ -2743,12 +3203,16 @@ export function automationToTf(entity, ctx) {
2743
3203
  trigger: { type: triggerType, label },
2744
3204
  triggerParamNames,
2745
3205
  recordParamNames,
3206
+ triggerParamFieldTypes,
2746
3207
  recordParamTargets,
3208
+ userParamNames,
2747
3209
  tasks: taskRefs,
2748
3210
  owner,
2749
3211
  dataBlocks,
2750
3212
  variableById,
3213
+ requiredSecrets: new Set(),
2751
3214
  recordItemForEachRefKeys,
3215
+ recordItemForEachSourceByRefKey,
2752
3216
  ...(recordFieldContext !== undefined ? { recordFieldContext } : {}),
2753
3217
  ...(ctx.fieldNamesByAppRefName !== undefined ? { fieldNamesByAppRefName: ctx.fieldNamesByAppRefName } : {}),
2754
3218
  ...(ctx.fieldAddressesByAppRefName !== undefined ? { fieldAddressesByAppRefName: ctx.fieldAddressesByAppRefName } : {}),
@@ -3063,6 +3527,7 @@ export function automationToTf(entity, ctx) {
3063
3527
  ? { outputs: outputValues.map((output) => {
3064
3528
  if (typeof output.name !== "string")
3065
3529
  throw new EntityTfError("automation output has no name");
3530
+ assertPublishableOutputTask(output.name, output.value, payload.tasks ?? [], refs);
3066
3531
  return { name: output.name, value: workflowPublishOutputValueToTf(output.value, refs) };
3067
3532
  }) }
3068
3533
  : {}),
@@ -3070,5 +3535,20 @@ export function automationToTf(entity, ctx) {
3070
3535
  };
3071
3536
  blocks.push(publish);
3072
3537
  }
3073
- return { blocks: [...[...dataBlocks.values()].sort((a, b) => (a.type + "." + a.label).localeCompare(b.type + "." + b.label)), ...blocks], address: AUTOMATION_RESOURCE_TYPE + "." + label };
3538
+ const secretBlocks = [...refs.requiredSecrets].sort().map(requiredSecretVariableBlock);
3539
+ return { blocks: [...secretBlocks, ...[...dataBlocks.values()].sort((a, b) => (a.type + "." + a.label).localeCompare(b.type + "." + b.label)), ...blocks], address: AUTOMATION_RESOURCE_TYPE + "." + label };
3540
+ }
3541
+ function requiredSecretVariableBlock(name) {
3542
+ return {
3543
+ kind: "variable",
3544
+ label: name,
3545
+ attrs: {
3546
+ sensitive: true,
3547
+ description: `Write-only secret. Supply a non-empty value as TF_VAR_${name} before plan or apply.`,
3548
+ },
3549
+ variableValidation: {
3550
+ condition: `var.${name} != ""`,
3551
+ errorMessage: `TF_VAR_${name} must be a non-empty value. An empty string would overwrite the live write-only secret.`,
3552
+ },
3553
+ };
3074
3554
  }