@elementumai/edk 0.9.6 → 0.9.9

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 (180) hide show
  1. package/README.md +34 -3
  2. package/dist-sdk/src/catalog/factories.d.ts +26 -6
  3. package/dist-sdk/src/catalog/factories.js +41 -6
  4. package/dist-sdk/src/catalog/from-authoring.js +27 -33
  5. package/dist-sdk/src/catalog/index.d.ts +2 -2
  6. package/dist-sdk/src/catalog/index.js +2 -2
  7. package/dist-sdk/src/catalog/org.js +93 -42
  8. package/dist-sdk/src/catalog/token.js +10 -0
  9. package/dist-sdk/src/catalog/types.d.ts +42 -3
  10. package/dist-sdk/src/catalog/types.js +5 -0
  11. package/dist-sdk/src/core/index.d.ts +2 -2
  12. package/dist-sdk/src/core/index.js +1 -1
  13. package/dist-sdk/src/core/platform-id.d.ts +2 -0
  14. package/dist-sdk/src/core/platform-id.js +4 -0
  15. package/dist-sdk/src/core/system-fields.d.ts +18 -0
  16. package/dist-sdk/src/core/system-fields.js +21 -0
  17. package/dist-sdk/src/core/triggers/on-demand.d.ts +27 -24
  18. package/dist-sdk/src/core/triggers/on-demand.js +33 -12
  19. package/dist-sdk/src/core/types/app.d.ts +14 -9
  20. package/dist-sdk/src/core/types/aspect-category.d.ts +1 -0
  21. package/dist-sdk/src/core/types/aspect-category.js +1 -0
  22. package/dist-sdk/src/core/types/platform.d.ts +1 -1
  23. package/dist-sdk/src/engine/build/context.d.ts +24 -8
  24. package/dist-sdk/src/engine/build/source-context.d.ts +14 -17
  25. package/dist-sdk/src/engine/build/source-context.js +1 -1
  26. package/dist-sdk/src/engine/pull/context.d.ts +18 -0
  27. package/dist-sdk/src/engine/pull/org.d.ts +4 -0
  28. package/dist-sdk/src/engine/pull/org.js +17 -2
  29. package/dist-sdk/src/engine/pull/procedure-refs.d.ts +16 -0
  30. package/dist-sdk/src/engine/pull/procedure-refs.js +69 -0
  31. package/dist-sdk/src/engine/pull/ref-only.d.ts +14 -0
  32. package/dist-sdk/src/engine/pull/ref-only.js +35 -2
  33. package/dist-sdk/src/engine/tf/expr.js +1 -1
  34. package/dist-sdk/src/engine/workspace/authoring-layout.d.ts +15 -0
  35. package/dist-sdk/src/engine/workspace/authoring-layout.js +33 -1
  36. package/dist-sdk/src/engine/workspace/loader.d.ts +40 -0
  37. package/dist-sdk/src/engine/workspace/loader.js +328 -0
  38. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +4 -0
  39. package/dist-sdk/src/entities/access-policy/from-tf.js +24 -4
  40. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +7 -0
  41. package/dist-sdk/src/entities/access-policy/to-tf.js +11 -3
  42. package/dist-sdk/src/entities/agent/build.d.ts +54 -8
  43. package/dist-sdk/src/entities/agent/build.js +36 -1
  44. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +144 -3
  45. package/dist-sdk/src/entities/agent/from-tf.d.ts +7 -6
  46. package/dist-sdk/src/entities/agent/from-tf.js +176 -5
  47. package/dist-sdk/src/entities/agent/index.d.ts +2 -2
  48. package/dist-sdk/src/entities/agent/index.js +1 -1
  49. package/dist-sdk/src/entities/agent/module.js +1 -0
  50. package/dist-sdk/src/entities/agent/to-tf.d.ts +5 -4
  51. package/dist-sdk/src/entities/agent/to-tf.js +186 -11
  52. package/dist-sdk/src/entities/agent/tools.d.ts +16 -5
  53. package/dist-sdk/src/entities/agent/tools.js +13 -1
  54. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +16 -0
  55. package/dist-sdk/src/entities/agent-tool/from-tf.js +39 -6
  56. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +2 -0
  57. package/dist-sdk/src/entities/agent-tool/to-tf.js +12 -12
  58. package/dist-sdk/src/entities/agent-tool/types.js +1 -0
  59. package/dist-sdk/src/entities/app/build.d.ts +44 -24
  60. package/dist-sdk/src/entities/app/build.js +18 -8
  61. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +15 -0
  62. package/dist-sdk/src/entities/app/display-blocks-to-layout.d.ts +45 -0
  63. package/dist-sdk/src/entities/app/display-blocks-to-layout.js +98 -0
  64. package/dist-sdk/src/entities/app/display-blocks-to-record-create-form.d.ts +55 -0
  65. package/dist-sdk/src/entities/app/display-blocks-to-record-create-form.js +99 -0
  66. package/dist-sdk/src/entities/app/from-tf.js +79 -14
  67. package/dist-sdk/src/entities/app/index.d.ts +3 -2
  68. package/dist-sdk/src/entities/app/index.js +2 -1
  69. package/dist-sdk/src/entities/app/to-tf.js +30 -6
  70. package/dist-sdk/src/entities/automation/build.d.ts +37 -18
  71. package/dist-sdk/src/entities/automation/build.js +121 -12
  72. package/dist-sdk/src/entities/automation/catalog-render.js +5 -2
  73. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +8 -10
  74. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +2 -0
  75. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +103 -20
  76. package/dist-sdk/src/entities/automation/from-tf.d.ts +10 -1
  77. package/dist-sdk/src/entities/automation/from-tf.js +1165 -91
  78. package/dist-sdk/src/entities/automation/index.d.ts +1 -1
  79. package/dist-sdk/src/entities/automation/module.js +15 -5
  80. package/dist-sdk/src/entities/automation/operators.d.ts +2 -2
  81. package/dist-sdk/src/entities/automation/operators.js +1 -0
  82. package/dist-sdk/src/entities/automation/output-field-types.d.ts +17 -0
  83. package/dist-sdk/src/entities/automation/output-field-types.js +45 -0
  84. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +20 -4
  85. package/dist-sdk/src/entities/automation/output-key-wire-name.js +33 -6
  86. package/dist-sdk/src/entities/automation/script-code.d.ts +1 -1
  87. package/dist-sdk/src/entities/automation/script-code.js +168 -36
  88. package/dist-sdk/src/entities/automation/task-label.d.ts +2 -0
  89. package/dist-sdk/src/entities/automation/task-label.js +18 -0
  90. package/dist-sdk/src/entities/automation/tasks.d.ts +159 -45
  91. package/dist-sdk/src/entities/automation/tasks.js +60 -47
  92. package/dist-sdk/src/entities/automation/to-tf.d.ts +7 -1
  93. package/dist-sdk/src/entities/automation/to-tf.js +816 -87
  94. package/dist-sdk/src/entities/automation/triggers.d.ts +14 -5
  95. package/dist-sdk/src/entities/automation/triggers.js +1 -1
  96. package/dist-sdk/src/entities/automation/value-ref-tf.d.ts +78 -0
  97. package/dist-sdk/src/entities/automation/value-ref-tf.js +193 -0
  98. package/dist-sdk/src/entities/dashboard/from-tf.js +1 -1
  99. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +1 -0
  100. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +1 -1
  101. package/dist-sdk/src/entities/element/build.d.ts +30 -7
  102. package/dist-sdk/src/entities/element/build.js +7 -3
  103. package/dist-sdk/src/entities/element/from-tf.js +7 -3
  104. package/dist-sdk/src/entities/element/index.d.ts +3 -2
  105. package/dist-sdk/src/entities/element/index.js +3 -2
  106. package/dist-sdk/src/entities/element/to-tf.js +49 -8
  107. package/dist-sdk/src/entities/field/build.d.ts +94 -3
  108. package/dist-sdk/src/entities/field/build.js +82 -3
  109. package/dist-sdk/src/entities/field/from-tf.d.ts +6 -0
  110. package/dist-sdk/src/entities/field/from-tf.js +104 -1
  111. package/dist-sdk/src/entities/field/locals.js +6 -7
  112. package/dist-sdk/src/entities/field/module.js +1 -0
  113. package/dist-sdk/src/entities/field/options.d.ts +2 -0
  114. package/dist-sdk/src/entities/field/options.js +12 -2
  115. package/dist-sdk/src/entities/field/record-shape.d.ts +12 -15
  116. package/dist-sdk/src/entities/field/to-tf.d.ts +13 -3
  117. package/dist-sdk/src/entities/field/to-tf.js +191 -56
  118. package/dist-sdk/src/entities/field/types.js +2 -0
  119. package/dist-sdk/src/entities/org/category-ref.d.ts +5 -0
  120. package/dist-sdk/src/entities/org/category-ref.js +12 -0
  121. package/dist-sdk/src/entities/record-create-form/from-tf.js +3 -3
  122. package/dist-sdk/src/entities/record-create-form/to-tf.d.ts +1 -0
  123. package/dist-sdk/src/entities/record-create-form/to-tf.js +18 -13
  124. package/dist-sdk/src/entities/relationship/from-tf.js +100 -7
  125. package/dist-sdk/src/entities/role/from-tf.js +10 -4
  126. package/dist-sdk/src/entities/search-table/build.d.ts +1 -1
  127. package/dist-sdk/src/entities/search-table/from-tf.d.ts +1 -0
  128. package/dist-sdk/src/entities/search-table/from-tf.js +6 -0
  129. package/dist-sdk/src/entities/search-table/printer.js +3 -1
  130. package/dist-sdk/src/entities/search-table/to-tf.js +3 -3
  131. package/dist-sdk/src/entities/search-table/types.js +1 -0
  132. package/dist-sdk/src/entities/service-account/from-tf.js +10 -4
  133. package/dist-sdk/src/entities/service-account/to-tf.d.ts +2 -1
  134. package/dist-sdk/src/entities/service-account/to-tf.js +7 -0
  135. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +9 -0
  136. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +39 -0
  137. package/dist-sdk/src/entities/shared/filters/ast.d.ts +24 -1
  138. package/dist-sdk/src/entities/shared/filters/ast.js +4 -0
  139. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +13 -2
  140. package/dist-sdk/src/entities/shared/filters/tf-codec.js +14 -8
  141. package/dist-sdk/src/entities/shared/handle-description.d.ts +12 -0
  142. package/dist-sdk/src/entities/shared/handle-description.js +20 -0
  143. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +5 -3
  144. package/dist-sdk/src/entities/shared/tool-field-ref.js +11 -16
  145. package/dist-sdk/src/entities/shared/types/common.d.ts +7 -5
  146. package/dist-sdk/src/entities/shared/types/field-types.d.ts +6 -1
  147. package/dist-sdk/src/entities/shared/types/field-types.js +5 -8
  148. package/dist-sdk/src/entities/shared/types/platform.d.ts +15 -2
  149. package/dist-sdk/src/entities/skill/build.d.ts +51 -2
  150. package/dist-sdk/src/entities/skill/build.js +65 -8
  151. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +1 -1
  152. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +79 -18
  153. package/dist-sdk/src/entities/skill/from-tf.d.ts +11 -0
  154. package/dist-sdk/src/entities/skill/from-tf.js +47 -5
  155. package/dist-sdk/src/entities/skill/index.d.ts +1 -1
  156. package/dist-sdk/src/entities/skill/index.js +1 -1
  157. package/dist-sdk/src/entities/skill/input-coverage.d.ts +89 -0
  158. package/dist-sdk/src/entities/skill/input-coverage.js +327 -0
  159. package/dist-sdk/src/entities/skill/module.js +2 -0
  160. package/dist-sdk/src/entities/skill/to-tf.d.ts +9 -25
  161. package/dist-sdk/src/entities/skill/to-tf.js +29 -40
  162. package/dist-sdk/src/entities/skill/tools.d.ts +12 -2
  163. package/dist-sdk/src/entities/skill/tools.js +3 -6
  164. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +19 -0
  165. package/dist-sdk/src/entities/skill-tool/from-tf.js +50 -14
  166. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +9 -7
  167. package/dist-sdk/src/entities/skill-tool/to-tf.js +29 -23
  168. package/dist-sdk/src/entities/table/to-tf.js +21 -5
  169. package/dist-sdk/src/entities/task/to-tf.js +3 -2
  170. package/dist-sdk/src/entities/view/from-tf.js +36 -10
  171. package/dist-sdk/src/entities/view/to-tf.d.ts +2 -0
  172. package/dist-sdk/src/entities/view/to-tf.js +49 -30
  173. package/dist-sdk/src/entities/visual-flow/from-tf.js +6 -2
  174. package/dist-sdk/src/entities/widget/from-tf.js +2 -2
  175. package/dist-sdk/src/entities/widget/to-tf.d.ts +1 -0
  176. package/dist-sdk/src/entities/widget/to-tf.js +52 -23
  177. package/dist-sdk/src/graph/index.d.ts +19 -1
  178. package/dist-sdk/src/graph/index.js +20 -0
  179. package/dist-sdk/src/graph/types.d.ts +22 -0
  180. package/package.json +11 -5
@@ -1,5 +1,6 @@
1
1
  import { EntityTfError, recordFieldContextOf } from "../../engine/entity.js";
2
2
  import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET } from "../../core/system-fields.js";
3
+ import { isUnsafePlatformId } from "../../core/platform-id.js";
3
4
  import { appResourceLabelPrefix, appScopedResourceLabel, expr, isTfExpr, isUuid, sanitizeName, scopedResourceLabel, snakeSlug, tsLabelToTfLabel, } from "../../engine/tf/index.js";
4
5
  import { workspaceAspectKey } from "../../engine/build/context.js";
5
6
  import { SEARCH_TABLE_RESOURCE_TYPES } from "../search-table/types.js";
@@ -7,11 +8,16 @@ import { fieldRefToTfValue } from "../field/to-tf.js";
7
8
  import { SERVICE_ACCOUNT_RESOURCE_TYPE } from "../service-account/module.js";
8
9
  import { resolveForeignRef } from "../shared/foreign-ref.js";
9
10
  import { filterToTf as serializeFilterToTf } from "../shared/filters/tf-codec.js";
11
+ import { API_TASK_REF_AUTHORING_NAMES, API_TASK_REF_WIRE_NAMES } from "./output-key-wire-name.js";
12
+ import { outputFieldTypesFromScriptSchema } from "./output-field-types.js";
10
13
  import { CONNECTOR_ORG_BAG } from "../org/connector.js";
11
14
  import { FILE_READER_SUB_TYPE_BY_RESOURCE, FILE_READER_SUB_TYPE_BY_TYPE_KEY } from "../file-reader/types.js";
12
15
  import { UNRESOLVED_FIELD_MARKER } from "../shared/ref.js";
13
16
  import { TABLE_RESOURCE_TYPE } from "../table/module.js";
14
17
  import { AUTOMATION_RESOURCE_TYPE, WORKFLOW_PUBLISH_RESOURCE_TYPE } from "./types.js";
18
+ import { onDemandTriggerRefKey } from "./value-ref-tf.js";
19
+ import { taskTfLabel } from "./task-label.js";
20
+ import { isOnDemandRecordType } from "../shared/types/field-types.js";
15
21
  function scopedLabel(appTfLabel, label) {
16
22
  return appScopedResourceLabel(appTfLabel, label);
17
23
  }
@@ -102,6 +108,10 @@ const TASK_RESOURCES = {
102
108
  runAutomation: "elementum_run_automation_task",
103
109
  aspectRecordFieldLocking: "elementum_aspect_record_field_locking_task",
104
110
  aiFileAnalysis: "elementum_ai_file_read_task",
111
+ // Not a real resource - a read-only data-source reference to a platform
112
+ // task type EDK doesn't implement (edk#785/edk#821). See the `isData` flag
113
+ // on `taskRefs` entries and the dedicated emission branch in `emitTasks`.
114
+ unimplementedTask: "elementum_unmanaged_task_reference",
105
115
  };
106
116
  const CONFIG_ATTRS = {
107
117
  aspectId: "object_id",
@@ -117,9 +127,13 @@ const CONFIG_ATTRS = {
117
127
  fireOnRecovery: "fire_on_recovery",
118
128
  emailAliasId: "email_alias_id",
119
129
  approvalChainTemplateId: "approval_chain_template_id",
130
+ approvalProcessId: "approval_process_id",
131
+ approvalReference: "approval_reference",
120
132
  surveyTemplateId: "survey_template_id",
121
133
  workflowFields: "fields",
122
134
  recordReference: "record_reference",
135
+ requesterReference: "requester_reference",
136
+ approverReferences: "approver_references",
123
137
  recordId: "record_reference",
124
138
  sourceRecordIds: "source_record_ids",
125
139
  targetRecordId: "target_record_id",
@@ -148,8 +162,6 @@ const CONFIG_ATTRS = {
148
162
  categorySource: "category_source",
149
163
  titleReference: "title",
150
164
  messageReference: "message",
151
- userValueReferences: "user_value_references",
152
- groupValueReferences: "group_value_references",
153
165
  notifyWatchers: "notify_watchers",
154
166
  fieldId: "field_id",
155
167
  userId: "user_id",
@@ -272,9 +284,10 @@ function foreignFieldNaming(value) {
272
284
  * `locals.tf` attrs, when the build wired one up ({@link
273
285
  * AutomationToTfContext.localsAttrs}). Cross-app counterpart to
274
286
  * `field/locals.ts`'s same-app `appendFieldLocals`; unconditional per field
275
- * (options empty for non-picklist/calculated fields), matching that
276
- * same-app precedent of always emitting the local whether or not any
277
- * automation ends up looking a label up through it.
287
+ * (options empty for non-picklist/calculated fields, and for a dynamic or
288
+ * API-sourced picklist, whose record-backed labels are not a lookup
289
+ * domain), matching that same-app precedent of always emitting the local
290
+ * whether or not any automation ends up looking a label up through it.
278
291
  */
279
292
  function registerForeignOptionsByLabelLocal(fieldLabel, ctx) {
280
293
  if (ctx.localsAttrs === undefined)
@@ -333,6 +346,118 @@ function crossAppFieldToTf(value, ctx, dataBlocks) {
333
346
  registerForeignOptionsByLabelLocal(fieldLabel, ctx);
334
347
  return expr.dataAttr("elementum_field", fieldLabel, ["id"]);
335
348
  }
349
+ /**
350
+ * Resolve an automation token as a managed definition (same stream root or a
351
+ * sibling root in this build) or as a ref-only `data.elementum_automation`
352
+ * lookup. The latter deliberately preserves the provider's static
353
+ * `automation { id }` + `inputMappings.parameter.id` contract; it must never
354
+ * degrade to `target_automation_ref` / `dynamic_input_mappings`.
355
+ */
356
+ function automationTargetToTf(value, ctx, dataBlocks) {
357
+ const ownerKind = value.parentKind ?? ctx.parentScope;
358
+ const isOwn = value.parent === undefined ||
359
+ (value.parent === ctx.appRefName && ownerKind === ctx.parentScope);
360
+ const sibling = !isOwn && value.parent !== undefined
361
+ ? ctx.workspaceAspects?.get(workspaceAspectKey(ownerKind, value.parent))
362
+ : undefined;
363
+ const managedOwnerLabel = isOwn
364
+ ? ctx.appTfLabel
365
+ : sibling !== undefined && sibling.kind !== "table"
366
+ ? sibling.tfLabel
367
+ : undefined;
368
+ if (managedOwnerLabel !== undefined) {
369
+ const managedLabel = scopedLabel(managedOwnerLabel, tsLabelToTfLabel(value.refName));
370
+ const targetOwner = ctx.workspaceAspects?.get(workspaceAspectKey(ownerKind, isOwn ? ctx.appRefName : value.parent ?? ""));
371
+ const targetActiveNames = targetOwner?.activeAutomationNamesByRefName;
372
+ const isActive = targetActiveNames !== undefined
373
+ ? targetActiveNames.has(value.refName)
374
+ : isOwn && ctx.activeAutomationRefNames?.has(value.refName) === true;
375
+ // The on-demand trigger resource exposes the parameter ids from the
376
+ // mutable draft workflow. Once an ACTIVE target is published, however,
377
+ // run-automation validation is performed against its current workflow.
378
+ // Re-read the target after publish so both the target id and parameter
379
+ // ids describe that same current revision. Draft/inactive targets retain
380
+ // the direct resource references below because they have no publish edge.
381
+ if (isActive) {
382
+ const lookupName = targetActiveNames?.get(value.refName) ??
383
+ (isOwn ? ctx.automationNamesByRefName?.get(value.refName) : undefined) ??
384
+ value.name;
385
+ if (lookupName === undefined || lookupName === "") {
386
+ throw new EntityTfError(`managed ACTIVE automation ref "${value.refName}" has no lookup name`);
387
+ }
388
+ // Data block addresses are module-global even though EDK emits one
389
+ // file per automation. Scope the lookup to this caller so two callers
390
+ // of the same target cannot declare a duplicate data address.
391
+ const currentBindingLabel = `${managedLabel}_for_${ctx.automationTfLabel}`;
392
+ dataBlocks.set(`${AUTOMATION_RESOURCE_TYPE}.${currentBindingLabel}`, {
393
+ kind: "data",
394
+ type: AUTOMATION_RESOURCE_TYPE,
395
+ label: currentBindingLabel,
396
+ attrs: {
397
+ app_id: expr.resourceAttr(ownerKind === "element" ? "elementum_element" : "elementum_app", managedOwnerLabel, ["id"]),
398
+ name: lookupName,
399
+ depends_on: [expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, managedLabel)],
400
+ },
401
+ });
402
+ return {
403
+ id: expr.dataAttr(AUTOMATION_RESOURCE_TYPE, currentBindingLabel, ["id"]),
404
+ parameterId: (name) => expr.dataAttr(AUTOMATION_RESOURCE_TYPE, currentBindingLabel, ["parameter_ids", { index: name }]),
405
+ managedLabel,
406
+ };
407
+ }
408
+ return {
409
+ id: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, managedLabel, ["id"]),
410
+ parameterId: (name) => expr.resourceAttr("elementum_on_demand_trigger", managedLabel, ["parameter_ids", { index: name }]),
411
+ managedLabel,
412
+ };
413
+ }
414
+ if (value.parent === undefined || value.parent === "") {
415
+ throw new EntityTfError(`foreign automation ref "${value.refName}" has no parent`);
416
+ }
417
+ if (value.parentName === undefined || value.parentName === "") {
418
+ throw new EntityTfError(`foreign automation ref "${value.parent}.${value.refName}" has no parentName; the owner lookup cannot use a refName as a display name`);
419
+ }
420
+ if (value.name === undefined || value.name === "") {
421
+ throw new EntityTfError(`foreign automation ref "${value.parent}.${value.refName}" has no lookup name`);
422
+ }
423
+ let ownerLabel;
424
+ let ownerId;
425
+ if (ctx.orgRefs !== undefined) {
426
+ const owner = resolveForeignRef(ownerKind, { name: value.parentName, namespace: value.parentNamespace }, ctx.orgRefs, ctx.diagnostics, `automation "${value.refName}" owner`);
427
+ ownerLabel = owner.tfLabel;
428
+ ownerId = owner.value;
429
+ }
430
+ else {
431
+ const owner = foreignRootLookup(ownerKind, {
432
+ name: value.parentName,
433
+ namespace: value.parentNamespace,
434
+ });
435
+ ownerLabel = owner.tfLabel;
436
+ ownerId = expr.dataAttr(owner.resourceType, owner.tfLabel, ["id"]);
437
+ dataBlocks.set(`${owner.resourceType}.${owner.tfLabel}`, {
438
+ kind: "data",
439
+ type: owner.resourceType,
440
+ label: owner.tfLabel,
441
+ attrs: { [owner.lookupAttr]: owner.lookupValue },
442
+ });
443
+ }
444
+ const automationLabel = `${ownerLabel}_${tsLabelToTfLabel(value.refName)}`;
445
+ if (ctx.orgRefs !== undefined) {
446
+ ctx.orgRefs.rawLookup(AUTOMATION_RESOURCE_TYPE, automationLabel, value.name, { app_id: ownerId });
447
+ }
448
+ else {
449
+ dataBlocks.set(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`, {
450
+ kind: "data",
451
+ type: AUTOMATION_RESOURCE_TYPE,
452
+ label: automationLabel,
453
+ attrs: { app_id: ownerId, name: value.name },
454
+ });
455
+ }
456
+ return {
457
+ id: expr.dataAttr(AUTOMATION_RESOURCE_TYPE, automationLabel, ["id"]),
458
+ parameterId: (name) => expr.dataAttr(AUTOMATION_RESOURCE_TYPE, automationLabel, ["parameter_ids", { index: name }]),
459
+ };
460
+ }
336
461
  function tokenToTf(value, ctx, dataBlocks) {
337
462
  switch (value.__kind) {
338
463
  case "user": {
@@ -358,7 +483,7 @@ function tokenToTf(value, ctx, dataBlocks) {
358
483
  return value.refName;
359
484
  case "app":
360
485
  case "element":
361
- if (value.refName !== ctx.appRefName) {
486
+ if (value.refName !== ctx.appRefName || value.__kind !== ctx.parentScope) {
362
487
  const sibling = ctx.workspaceAspects?.get(workspaceAspectKey(value.__kind, value.refName));
363
488
  if (sibling !== undefined) {
364
489
  const siblingType = sibling.kind === "element" ? "elementum_element" : "elementum_app";
@@ -379,7 +504,7 @@ function tokenToTf(value, ctx, dataBlocks) {
379
504
  });
380
505
  return expr.dataAttr(resolved.resourceType, resolved.tfLabel, ["id"]);
381
506
  }
382
- return expr.resourceAttr("elementum_app", ctx.appTfLabel, ["id"]);
507
+ return expr.resourceAttr(ctx.parentScope === "element" ? "elementum_element" : "elementum_app", ctx.appTfLabel, ["id"]);
383
508
  case "field": {
384
509
  // `!== ctx.appRefName` alone isn't enough: an app and a FOREIGN
385
510
  // ELEMENT can share a refName (workspace keys disambiguate by
@@ -415,10 +540,7 @@ function tokenToTf(value, ctx, dataBlocks) {
415
540
  return expr.dataAttr("elementum_cloudlink", label, ["id"]);
416
541
  }
417
542
  case "automation":
418
- if (value.parent !== undefined && value.parent !== ctx.appRefName) {
419
- throw new EntityTfError(`cross-app automation ref "${value.parent}.${value.refName}" is not supported`);
420
- }
421
- return expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
543
+ return automationTargetToTf(value, ctx, dataBlocks).id;
422
544
  case "agent":
423
545
  return expr.resourceAttr("elementum_agent", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
424
546
  case "phone-service":
@@ -430,7 +552,40 @@ function tokenToTf(value, ctx, dataBlocks) {
430
552
  if (value.parent === undefined || value.parent === "") {
431
553
  throw new EntityTfError(`datamine ref "${value.refName}" is missing its owning table`);
432
554
  }
433
- return expr.resourceAttr("elementum_datamine", `${tsLabelToTfLabel(value.parent)}_${tsLabelToTfLabel(value.refName)}`, ["id"]);
555
+ {
556
+ const label = `${tsLabelToTfLabel(value.parent)}_${tsLabelToTfLabel(value.refName)}`;
557
+ const tableSibling = ctx.workspaceAspects?.get(workspaceAspectKey("table", value.parent));
558
+ let tableId;
559
+ if (tableSibling !== undefined) {
560
+ tableId = expr.resourceAttr(TABLE_RESOURCE_TYPE, tableSibling.tfLabel, ["id"]);
561
+ if (tableSibling.managedDatamineLabels?.has(label) === true) {
562
+ return expr.resourceAttr("elementum_datamine", label, ["id"]);
563
+ }
564
+ }
565
+ else {
566
+ const tableLabel = tsLabelToTfLabel(value.parent);
567
+ const tableName = value.parent;
568
+ if (ctx.orgRefs !== undefined) {
569
+ ctx.orgRefs.rawLookup(TABLE_RESOURCE_TYPE, tableLabel, tableName);
570
+ }
571
+ else {
572
+ dataBlocks.set(`${TABLE_RESOURCE_TYPE}.${tableLabel}`, {
573
+ kind: "data",
574
+ type: TABLE_RESOURCE_TYPE,
575
+ label: tableLabel,
576
+ attrs: { name: tableName },
577
+ });
578
+ }
579
+ tableId = expr.dataAttr(TABLE_RESOURCE_TYPE, tableLabel, ["id"]);
580
+ }
581
+ dataBlocks.set(`elementum_datamine.${label}`, {
582
+ kind: "data",
583
+ type: "elementum_datamine",
584
+ label,
585
+ attrs: { table_id: tableId, name: value.name ?? value.refName },
586
+ });
587
+ return expr.dataAttr("elementum_datamine", label, ["id"]);
588
+ }
434
589
  case "table": {
435
590
  const sibling = ctx.workspaceAspects?.get(workspaceAspectKey("table", value.refName));
436
591
  if (sibling !== undefined) {
@@ -453,6 +608,32 @@ function tokenToTf(value, ctx, dataBlocks) {
453
608
  }
454
609
  return expr.dataAttr(TABLE_RESOURCE_TYPE, label, ["id"]);
455
610
  }
611
+ case "tableColumn": {
612
+ // Columns are addressed by DISPLAY name in `field_ids`, never by bag key.
613
+ const columnName = value.name ?? value.refName;
614
+ const owner = value.parent;
615
+ if (owner === undefined || owner === "") {
616
+ throw new EntityTfError(`table column ref "${value.refName}" is missing its owning table`);
617
+ }
618
+ const sibling = ctx.workspaceAspects?.get(workspaceAspectKey("table", owner));
619
+ if (sibling !== undefined) {
620
+ return expr.resourceAttr(TABLE_RESOURCE_TYPE, sibling.tfLabel, ["field_ids", { index: columnName }]);
621
+ }
622
+ const tableName = value.parentName ?? owner;
623
+ const label = tsLabelToTfLabel(owner);
624
+ if (ctx.orgRefs !== undefined) {
625
+ ctx.orgRefs.rawLookup(TABLE_RESOURCE_TYPE, label, tableName);
626
+ }
627
+ else {
628
+ dataBlocks.set(`${TABLE_RESOURCE_TYPE}.${label}`, {
629
+ kind: "data",
630
+ type: TABLE_RESOURCE_TYPE,
631
+ label,
632
+ attrs: { name: tableName },
633
+ });
634
+ }
635
+ return expr.dataAttr(TABLE_RESOURCE_TYPE, label, ["field_ids", { index: columnName }]);
636
+ }
456
637
  case "searchTable": {
457
638
  // Ownership + variant contract:
458
639
  // snowflake / linked -> owned by an ELEMENT
@@ -528,6 +709,61 @@ function tokenToTf(value, ctx, dataBlocks) {
528
709
  throw new EntityTfError(`catalog ref kind "${value.__kind}" has no automation HCL representation`);
529
710
  }
530
711
  }
712
+ function procedureToTf(value, ctx, dataBlocks) {
713
+ if (value.__kind !== "procedure")
714
+ throw new EntityTfError("procedure requires a procedure catalog reference");
715
+ if (!value.name)
716
+ throw new EntityTfError(`procedure token "${value.refName}" has no lookup name`);
717
+ if (!value.parent)
718
+ throw new EntityTfError(`procedure token "${value.refName}" is missing its owning CloudLink`);
719
+ if (!value.parentName) {
720
+ throw new EntityTfError(`procedure token "${value.parent}.${value.refName}" has no CloudLink lookup name`);
721
+ }
722
+ if (!Array.isArray(value.parameterTypes) || !value.parameterTypes.every((type) => typeof type === "string")) {
723
+ throw new EntityTfError(`procedure token "${value.parent}.${value.refName}" is missing its exact parameter signature`);
724
+ }
725
+ if (!value.databaseName || !value.schemaName) {
726
+ throw new EntityTfError(`procedure token "${value.parent}.${value.refName}" is missing its Snowflake database/schema`);
727
+ }
728
+ const cloudLinkLabel = tsLabelToTfLabel(value.parent);
729
+ const procedureLabel = `${cloudLinkLabel}_${tsLabelToTfLabel(value.refName)}`;
730
+ const cloudLinkId = expr.dataAttr("elementum_cloudlink", cloudLinkLabel, ["id"]);
731
+ if (ctx.orgRefs !== undefined) {
732
+ ctx.orgRefs.rawLookup("elementum_cloudlink", cloudLinkLabel, value.parentName);
733
+ ctx.orgRefs.rawLookup("elementum_stored_function", procedureLabel, value.name, {
734
+ cloudlink_id: cloudLinkId,
735
+ database_name: value.databaseName,
736
+ schema_name: value.schemaName,
737
+ type: "PROCEDURE",
738
+ parameter_types: value.parameterTypes,
739
+ });
740
+ }
741
+ else {
742
+ dataBlocks.set(`elementum_cloudlink.${cloudLinkLabel}`, {
743
+ kind: "data",
744
+ type: "elementum_cloudlink",
745
+ label: cloudLinkLabel,
746
+ attrs: { name: value.parentName },
747
+ });
748
+ dataBlocks.set(`elementum_stored_function.${procedureLabel}`, {
749
+ kind: "data",
750
+ type: "elementum_stored_function",
751
+ label: procedureLabel,
752
+ attrs: {
753
+ cloudlink_id: cloudLinkId,
754
+ name: value.name,
755
+ database_name: value.databaseName,
756
+ schema_name: value.schemaName,
757
+ type: "PROCEDURE",
758
+ parameter_types: value.parameterTypes,
759
+ },
760
+ });
761
+ }
762
+ return {
763
+ cloudLinkId,
764
+ procedureId: expr.dataAttr("elementum_stored_function", procedureLabel, ["id"]),
765
+ };
766
+ }
531
767
  function templateToTf(value, refs) {
532
768
  const template = value.template;
533
769
  const parameters = value.parameters;
@@ -545,11 +781,17 @@ function templateToTf(value, refs) {
545
781
  let cursor = 0;
546
782
  const pattern = /\{\{\{([^}]+)\}\}\}/g;
547
783
  for (let match = pattern.exec(template); match !== null; match = pattern.exec(template)) {
784
+ // The parameter list, not triple-brace text alone, identifies EDK
785
+ // reference placeholders. Third-party URLs and payloads can legitimately
786
+ // contain their own `{{{name}}}` syntax; leave unmatched occurrences in
787
+ // the surrounding literal so pull -> build reproduces them verbatim.
788
+ if (!byName.has(match[1]))
789
+ continue;
548
790
  if (match.index > cursor)
549
791
  parts.push(template.slice(cursor, match.index));
550
792
  const part = byName.get(match[1]);
551
793
  if (part === undefined || !isTfExpr(part)) {
552
- throw new EntityTfError(`template parameter "${match[1]}" is missing or is not a reference`);
794
+ throw new EntityTfError(`template parameter "${match[1]}" is not a reference`);
553
795
  }
554
796
  parts.push(part);
555
797
  cursor = match.index + match[0].length;
@@ -645,9 +887,14 @@ function calculationFormulaRefToParts(value, refs) {
645
887
  * not the task display name). Task id interpolates from the task resource.
646
888
  */
647
889
  function calculationTaskMustache(taskRefKey, wireName, refs) {
890
+ if (wireName.includes('"')) {
891
+ throw new EntityTfError(`calculation task output name "${wireName}" contains a double quote`);
892
+ }
648
893
  const target = refs.tasks.get(taskRefKey);
649
- if (target === undefined)
650
- throw new EntityTfError(`unresolved task ref "${taskRefKey}" in calculation formula`);
894
+ if (target === undefined) {
895
+ refs.owner.diagnostics.push(`automation unresolved task ref ${JSON.stringify(taskRefKey)} preserved as a literal calculation reference`);
896
+ return [`{{task name="${wireName}" id="${taskRefKey}"}}`];
897
+ }
651
898
  if (wireName.includes('"')) {
652
899
  throw new EntityTfError(`calculation task output name "${wireName}" contains a double quote`);
653
900
  }
@@ -715,8 +962,8 @@ const TS_TRIGGER_REF_TO_WIRE = {
715
962
  "triggeredBy.id": "Triggered By's Id",
716
963
  "triggeredBy.name": "Triggered By's Name",
717
964
  "triggeredBy.email": "Triggered By's Email",
718
- createdByEmail: "Created by Email",
719
- updatedByManagerEmail: "Updated by Manager Email",
965
+ createdByEmail: "Created By Email",
966
+ updatedByManagerEmail: "Updated By Manager Email",
720
967
  slackThreadId: "Slack Thread ID",
721
968
  slackChannelId: "Slack Channel ID",
722
969
  messageAuthorEmail: "Message Author Email",
@@ -734,6 +981,10 @@ const FIELD_REF_SUFFIX_TO_WIRE = {
734
981
  email: " Email",
735
982
  name: " Name",
736
983
  fieldId: " Field ID",
984
+ // A dynamically sourced Dropdown field's selected source record.
985
+ // Live refs name this "<Field> - Record" (ASPECT_RECORD_ID), distinct from
986
+ // `id` → " ID" (the selection's PICKLIST_ID).
987
+ recordId: " - Record",
737
988
  // Matches the literal path segment from-tf.ts now produces for this suffix
738
989
  // ("as text", not camelCase "asText") - Ref<T> has no ".asText" property
739
990
  // anywhere in the type system, so authored code can only reach this suffix
@@ -745,6 +996,15 @@ const FIELD_REF_SUFFIX_TO_WIRE = {
745
996
  "employee.manager.email": " Manager Email",
746
997
  "employee.manager.name": " Manager Name",
747
998
  };
999
+ const PROVIDER_FIXED_SYSTEM_FIELD_KEYS = new Set([
1000
+ "stage",
1001
+ "createdAt",
1002
+ "createdBy",
1003
+ "updatedAt",
1004
+ "updatedBy",
1005
+ "closedAt",
1006
+ "closedBy",
1007
+ ]);
748
1008
  function wireRefName(name, ctx) {
749
1009
  const known = TS_TRIGGER_REF_TO_WIRE[name];
750
1010
  if (known !== undefined)
@@ -755,13 +1015,31 @@ function wireRefName(name, ctx) {
755
1015
  const parts = name.split(".");
756
1016
  if (parts[0] === "record" && parts.length >= 2) {
757
1017
  const fieldKey = parts[1];
1018
+ // Pull preserves a deleted/unresolvable platform field as an explicit
1019
+ // bracket-access escape on the record ref. Rebuild that escape byte-for-
1020
+ // byte instead of trying to resolve the UUID as a current catalog key.
1021
+ // This is not a public authoring path: the printer is the only supported
1022
+ // producer, and it marks the access as an unresolved-field TODO.
1023
+ if (isUuid(fieldKey))
1024
+ return name;
1025
+ // Pull-time unresolvedField() uses a typed marker around the raw platform
1026
+ // id so the generated source remains explicit. Strip that marker on the
1027
+ // wire path, just as calculation refs do above.
1028
+ if (fieldKey.startsWith(UNRESOLVED_FIELD_MARKER)) {
1029
+ return `record.${fieldKey.slice(UNRESOLVED_FIELD_MARKER.length)}${parts.length > 2 ? `.${parts.slice(2).join(".")}` : ""}`;
1030
+ }
758
1031
  // System fields (title/status/stage/createdBy/...) have no entry in
759
1032
  // ctx.fieldNames - that map only carries the app's custom fields bag.
760
1033
  // Fall back to the provider's default display name for them; a renamed
761
1034
  // system field won't match and still throws below, same as an unknown
762
1035
  // custom field key would.
763
- const fieldName = ctx.fieldNames.get(fieldKey) ??
764
- (SYSTEM_FIELD_KEY_SET.has(fieldKey) ? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[fieldKey] : undefined);
1036
+ const systemFieldKey = SYSTEM_FIELD_KEY_SET.has(fieldKey)
1037
+ ? fieldKey
1038
+ : undefined;
1039
+ const fieldName = systemFieldKey !== undefined && PROVIDER_FIXED_SYSTEM_FIELD_KEYS.has(systemFieldKey)
1040
+ ? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[systemFieldKey]
1041
+ : ctx.fieldNames.get(fieldKey) ??
1042
+ (systemFieldKey !== undefined ? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[systemFieldKey] : undefined);
765
1043
  if (fieldName === undefined) {
766
1044
  throw new EntityTfError(`automation reference "${name}" targets field "${parts[1]}" which does not exist in app "${ctx.appRefName}"`);
767
1045
  }
@@ -770,15 +1048,11 @@ function wireRefName(name, ctx) {
770
1048
  if (wireSuffix === undefined) {
771
1049
  throw new EntityTfError(`automation reference "${name}" has unsupported record-field path "${suffix}"`);
772
1050
  }
773
- // The platform lowercases a system field's trailing " By" when it's the
774
- // PREFIX of a compound ref phrase (e.g. "Created By" + " Email" -> wire
775
- // ref key "Created by Email") but keeps it capitalized standalone -
776
- // confirmed live: plan failed with "Invalid index" against the real
777
- // refs map until this matched. from-tf.ts already reads refs
778
- // case-insensitively; build must reproduce the platform's exact casing
779
- // since terraform's refs[] map lookup is case-sensitive.
780
- const prefix = wireSuffix.length > 0 && fieldName.endsWith(" By") ? `${fieldName.slice(0, -3)} by` : fieldName;
781
- return `${prefix}${wireSuffix}`;
1051
+ // Build must reproduce the live refs[] key's exact casing because the
1052
+ // Terraform map lookup is case-sensitive. The current provider emits
1053
+ // compound audit refs with the system field's display casing intact
1054
+ // (for example "Created By ID").
1055
+ return `${fieldName}${wireSuffix}`;
782
1056
  }
783
1057
  // A webhook trigger's body/headers refs (ctx.trigger.body["X"]) can only
784
1058
  // type-check against DeepRefs<WebhookTriggerOutput>, so parts[0] being
@@ -838,6 +1112,176 @@ function taskWireRefName(name, taskRefKey, refs) {
838
1112
  fieldNames: foreignNames ?? new Map(),
839
1113
  });
840
1114
  }
1115
+ function triggerWireRefName(name, refs) {
1116
+ const scalarParams = refs.triggerParamNames.filter((param) => !refs.recordParamNames.includes(param));
1117
+ const declared = onDemandTriggerRefKey(name, scalarParams);
1118
+ if (declared !== name || scalarParams.includes(name))
1119
+ return declared;
1120
+ const recordParamName = refs.recordParamNames
1121
+ .filter((paramName) => name === paramName || name.startsWith(`${paramName}.`))
1122
+ .sort((a, b) => b.length - a.length)[0];
1123
+ if (recordParamName !== undefined) {
1124
+ const paramName = recordParamName;
1125
+ const suffix = name === paramName ? "" : name.slice(paramName.length + 1);
1126
+ const displayName = suffix === ""
1127
+ ? "Record"
1128
+ : recordParamFieldWireName(paramName, suffix, refs);
1129
+ return refs.recordParamNames.length > 1
1130
+ ? `${paramName} - ${displayName}`
1131
+ : displayName;
1132
+ }
1133
+ return wireRefName(name, refs.owner);
1134
+ }
1135
+ function recordParamFieldWireName(paramName, suffix, refs) {
1136
+ const target = refs.recordParamTargets.get(paramName);
1137
+ if (target === undefined) {
1138
+ throw new EntityTfError(`onDemand record parameter "${paramName}" is missing its target app/element`);
1139
+ }
1140
+ const targetRefName = target.refName;
1141
+ const targetFieldNames = targetRefName === refs.owner.appRefName && target.__kind === refs.owner.parentScope
1142
+ ? refs.owner.fieldNames
1143
+ : refs.fieldNamesByAppRefName?.get(targetRefName);
1144
+ return wireRefName(`record.${suffix}`, {
1145
+ ...refs.owner,
1146
+ appRefName: targetRefName,
1147
+ fieldNames: targetFieldNames ?? new Map(),
1148
+ });
1149
+ }
1150
+ /** Run-automation targets reference publish for ACTIVE automations, automation for draft/inactive. */
1151
+ export function automationRunTargetResourceAttr(appTfLabel, automationRefName, activeAutomationRefNames) {
1152
+ const label = appScopedResourceLabel(appTfLabel, tsLabelToTfLabel(automationRefName));
1153
+ if (activeAutomationRefNames?.has(automationRefName) === true) {
1154
+ return expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, label, ["id"]);
1155
+ }
1156
+ return expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label, ["id"]);
1157
+ }
1158
+ /**
1159
+ * workflow_publish outputs must match provider Read / ei export: a typed
1160
+ * `jsonencode({ fieldType, multiple, taskReference|... })` envelope — not
1161
+ * `task.refs[...]`, which can still resolve to a generic TEXT blob.
1162
+ */
1163
+ function workflowPublishOutputValueToTf(value, refs) {
1164
+ // Pulled `.outputs()` often wraps each envelope as `{ value: <envelope> }`
1165
+ // (ValueOrRef STATIC). Unwrap before classifying so name-only variable refs
1166
+ // still become `jsonencode(...)` strings.
1167
+ while (isObject(value) && "value" in value && Object.keys(value).length === 1) {
1168
+ value = value.value;
1169
+ }
1170
+ const envelope = workflowPublishOutputEnvelope(value, refs);
1171
+ if (envelope !== undefined)
1172
+ return expr.jsonencode(envelope);
1173
+ // Export-shaped envelopes (often name-only variable refs) must stay JSON
1174
+ // strings — the provider schema requires `outputs[].value` to be a string.
1175
+ if (isObject(value) && ("taskReference" in value || "triggerReference" in value || "variableReference" in value)) {
1176
+ return expr.jsonencode(valueToTf(value, refs));
1177
+ }
1178
+ return valueToTf(value, refs);
1179
+ }
1180
+ function workflowPublishOutputEnvelope(value, refs) {
1181
+ if (!isObject(value))
1182
+ return undefined;
1183
+ if (isObject(value.taskReference) && typeof value.taskReference.taskRefKey === "string" && typeof value.taskReference.name === "string") {
1184
+ if (value.taskReference.name.includes('"')) {
1185
+ throw new EntityTfError(`task output name "${value.taskReference.name}" contains a double quote`);
1186
+ }
1187
+ const target = refs.tasks.get(value.taskReference.taskRefKey);
1188
+ if (target === undefined)
1189
+ return undefined;
1190
+ const isFileReaderTask = target.type === "elementum_ai_file_read_task" || target.type === "elementum_file_reader_task";
1191
+ const isAiAgentTask = target.type === "elementum_ai_agent_task";
1192
+ const isAiSearchTableRecords = target.type === "elementum_ai_search_table_task" &&
1193
+ (value.taskReference.name === "records" || value.taskReference.name === "All Records");
1194
+ const isTableRecordsSearchRecords = target.type === "elementum_table_records_search_task" &&
1195
+ (value.taskReference.name === "records" || value.taskReference.name === "All matching table rows");
1196
+ const refsKey = isFileReaderTask || isAiAgentTask
1197
+ ? value.taskReference.name
1198
+ : isAiSearchTableRecords
1199
+ ? "All Records"
1200
+ : isTableRecordsSearchRecords
1201
+ ? value.taskReference.name === "All matching table rows"
1202
+ ? "All matching table rows"
1203
+ : "records"
1204
+ : taskWireRefName(value.taskReference.name, value.taskReference.taskRefKey, refs);
1205
+ const platformRefName = isAiAgentTask
1206
+ ? aiAgentPlatformRefName(refsKey)
1207
+ : refsKey;
1208
+ const typed = publishOutputType(value, target, refsKey);
1209
+ return {
1210
+ fieldType: typed.fieldType,
1211
+ multiple: typed.multiple,
1212
+ taskReference: {
1213
+ name: platformRefName,
1214
+ taskId: expr.resourceAttr(target.type, target.label, ["id"]),
1215
+ },
1216
+ // ei export always pads the unused reference arms with null.
1217
+ triggerReference: null,
1218
+ variableReference: null,
1219
+ };
1220
+ }
1221
+ if (isObject(value.triggerReference) && typeof value.triggerReference.name === "string") {
1222
+ const typed = publishOutputType(value, undefined, value.triggerReference.name);
1223
+ return {
1224
+ fieldType: typed.fieldType,
1225
+ multiple: typed.multiple,
1226
+ taskReference: null,
1227
+ triggerReference: { name: wireRefName(value.triggerReference.name, refs.owner) },
1228
+ variableReference: null,
1229
+ };
1230
+ }
1231
+ if (isObject(value.variableReference)) {
1232
+ const id = typeof value.variableReference.id === "string" ? value.variableReference.id : undefined;
1233
+ const name = typeof value.variableReference.name === "string" ? value.variableReference.name : undefined;
1234
+ // ei export / pull shape: `variableReference = { name = "variable|<uuid>" }`
1235
+ // with sibling null refs — not fieldType+id. Prefer that wire form.
1236
+ const wireName = name ?? (id !== undefined ? `variable|${id}` : undefined);
1237
+ if (wireName !== undefined) {
1238
+ return {
1239
+ taskReference: null,
1240
+ triggerReference: null,
1241
+ variableReference: { name: wireName },
1242
+ };
1243
+ }
1244
+ }
1245
+ return undefined;
1246
+ }
1247
+ /**
1248
+ * The provider's ai-agent refs map and the serialized platform reference use
1249
+ * different names. Keep the map key for Terraform indexing, but emit the
1250
+ * nested taskReference.name expected by workflow publish envelopes.
1251
+ */
1252
+ function aiAgentPlatformRefName(refsKey) {
1253
+ if (refsKey === "Action Response")
1254
+ return "ai_agent_task_response";
1255
+ if (refsKey === "ai_agent_task_response" || refsKey.startsWith("ai_agent_task_structured_output.")) {
1256
+ return refsKey;
1257
+ }
1258
+ return `ai_agent_task_structured_output.${refsKey.toLowerCase()}`;
1259
+ }
1260
+ function publishOutputType(value, target, wireName) {
1261
+ if (typeof value.fieldType === "string") {
1262
+ return { fieldType: value.fieldType, multiple: value.multiple === true };
1263
+ }
1264
+ if (target?.outputFieldTypes !== undefined) {
1265
+ const fromSchema = target.outputFieldTypes.get(wireName) ?? target.outputFieldTypes.get(wireName.replace(/^result\./, ""));
1266
+ if (fromSchema !== undefined)
1267
+ return fromSchema;
1268
+ }
1269
+ if (target !== undefined) {
1270
+ if ((target.type === "elementum_create_record_task" || target.type === "elementum_find_related_records_task") &&
1271
+ (wireName === "Record" || wireName === "Record ID")) {
1272
+ return { fieldType: "ASPECT_RECORD_ID", multiple: false };
1273
+ }
1274
+ if ((target.type === "elementum_record_search_task" || target.type === "elementum_find_related_records_task") &&
1275
+ (wireName === "All found records" || wireName === "records")) {
1276
+ return { fieldType: "ASPECT_RECORD_ID", multiple: true };
1277
+ }
1278
+ if ((target.type === "elementum_ai_search_table_task" || target.type === "elementum_table_records_search_task") &&
1279
+ (wireName === "All Records" || wireName === "records" || wireName === "All matching table rows")) {
1280
+ return { fieldType: "TABLE_RECORD", multiple: true };
1281
+ }
1282
+ }
1283
+ return { fieldType: "TEXT", multiple: value.multiple === true };
1284
+ }
841
1285
  function valueToTf(value, refs) {
842
1286
  const catalog = token(value);
843
1287
  if (catalog !== undefined)
@@ -861,12 +1305,17 @@ function valueToTf(value, refs) {
861
1305
  return expr.resourceAttr(target.type, target.label, ["refs", { index: target.name }]);
862
1306
  }
863
1307
  if (isObject(value.triggerReference) && typeof value.triggerReference.name === "string") {
864
- return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: wireRefName(value.triggerReference.name, refs.owner) }]);
1308
+ return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: triggerWireRefName(value.triggerReference.name, refs) }]);
865
1309
  }
866
1310
  if (isObject(value.taskReference) && typeof value.taskReference.taskRefKey === "string" && typeof value.taskReference.name === "string") {
1311
+ if (value.taskReference.name.includes('"')) {
1312
+ throw new EntityTfError(`task output name "${value.taskReference.name}" contains a double quote`);
1313
+ }
867
1314
  const target = refs.tasks.get(value.taskReference.taskRefKey);
868
- if (target === undefined)
869
- throw new EntityTfError(`unresolved task ref "${value.taskReference.taskRefKey}"`);
1315
+ if (target === undefined) {
1316
+ refs.owner.diagnostics.push(`automation unresolved task ref ${JSON.stringify(value.taskReference.taskRefKey)} preserved as a literal reference`);
1317
+ return `{{task name="${value.taskReference.name}" id="${value.taskReference.taskRefKey}"}}`;
1318
+ }
870
1319
  // aiFileAnalysis/readFile's refs are keyed by whatever arbitrary field
871
1320
  // names the file reader schema itself defines (e.g. "title",
872
1321
  // "document_type") - wireRefName's generic segment table
@@ -877,17 +1326,23 @@ function valueToTf(value, refs) {
877
1326
  // resources' actual refs map - confirmed live via a real apply's
878
1327
  // "Invalid index" error. Their field names pass through verbatim.
879
1328
  const isFileReaderTask = target.type === "elementum_ai_file_read_task" || target.type === "elementum_file_reader_task";
1329
+ const isAiAgentTask = target.type === "elementum_ai_agent_task";
880
1330
  // aiSearchTable's collection is `refs["All Records"]`, not recordSearch's
881
1331
  // globally-mapped `refs["All found records"]` (TS_REF_SEGMENT_TO_WIRE).
882
1332
  // Accept both the authoring segment and the already-rewritten wire name
883
1333
  // from rewriteForwardTaskRefName so either path emits the same key.
884
1334
  const isAiSearchTableRecords = target.type === "elementum_ai_search_table_task" &&
885
1335
  (value.taskReference.name === "records" || value.taskReference.name === "All Records");
886
- const refKey = isFileReaderTask
1336
+ // tableRecordsSearch uses yet another wire key: "All matching table rows".
1337
+ const isTableRecordsSearchRecords = target.type === "elementum_table_records_search_task" &&
1338
+ (value.taskReference.name === "records" || value.taskReference.name === "All matching table rows");
1339
+ const refKey = isFileReaderTask || isAiAgentTask
887
1340
  ? value.taskReference.name
888
1341
  : isAiSearchTableRecords
889
1342
  ? "All Records"
890
- : taskWireRefName(value.taskReference.name, value.taskReference.taskRefKey, refs);
1343
+ : isTableRecordsSearchRecords
1344
+ ? "All matching table rows"
1345
+ : taskWireRefName(value.taskReference.name, value.taskReference.taskRefKey, refs);
891
1346
  return expr.resourceAttr(target.type, target.label, ["refs", { index: refKey }]);
892
1347
  }
893
1348
  if (isObject(value.forEachReference) && typeof value.forEachReference.forEachTaskRefKey === "string" && typeof value.forEachReference.name === "string") {
@@ -923,7 +1378,7 @@ function unwrapDefault(value) {
923
1378
  const values = Object.values(value);
924
1379
  return values.length === 1 ? values[0] : value;
925
1380
  }
926
- function filterReferenceToTf(value, refs) {
1381
+ function filterReferenceToTf(value, refs, role = "value", realType) {
927
1382
  // Raw pass-through for a filter left side the pull-time deserializer
928
1383
  // couldn't decode to a typed ref (filter.ts's leftDescriptor, matching the
929
1384
  // UNRESOLVED_REFERENCE_MARKER case) - reproduces the original value_reference
@@ -947,6 +1402,7 @@ function filterReferenceToTf(value, refs) {
947
1402
  const fieldKey = parts[1];
948
1403
  const address = refs.owner.fieldAddresses.get(fieldKey);
949
1404
  const suffix = parts.slice(2).join(".");
1405
+ const wireSuffix = suffix === "recordId" ? "10000001-2000-4000-a000-800000000000" : suffix;
950
1406
  // A bare reference to a PICKLIST field (STATUS/STAGE included —
951
1407
  // `serializeSystemFields` wire-wraps both as a picklist too) has no
952
1408
  // valid suffix-less wire form — confirmed live via the platform's
@@ -967,7 +1423,7 @@ function filterReferenceToTf(value, refs) {
967
1423
  return expr.template([
968
1424
  "trigger.record.",
969
1425
  addressExpr(address, ["id"]),
970
- ...(suffix.length > 0 ? [`.${suffix}`] : []),
1426
+ ...(wireSuffix.length > 0 ? [`.${wireSuffix}`] : []),
971
1427
  ]);
972
1428
  }
973
1429
  // System fields (id/title/status/createdBy/updatedBy/...) have no
@@ -983,7 +1439,7 @@ function filterReferenceToTf(value, refs) {
983
1439
  return expr.template([
984
1440
  "trigger.record.",
985
1441
  expr.local(`${refs.owner.appTfLabel}_${tsLabelToTfLabel(fieldKey)}_field_id`),
986
- ...(suffix.length > 0 ? [`.${suffix}`] : []),
1442
+ ...(wireSuffix.length > 0 ? [`.${wireSuffix}`] : []),
987
1443
  ]);
988
1444
  }
989
1445
  // Orphaned field reference: from-tf.ts round-trips a filter
@@ -997,7 +1453,11 @@ function filterReferenceToTf(value, refs) {
997
1453
  return `trigger.${value.name}`;
998
1454
  }
999
1455
  }
1000
- return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: wireRefName(value.name, refs.owner) }]);
1456
+ const triggerRefKey = triggerWireRefName(value.name, refs);
1457
+ if (refs.trigger.type === TRIGGER_RESOURCES.onDemand) {
1458
+ return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["filter_refs", { index: triggerRefKey }]);
1459
+ }
1460
+ return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: triggerRefKey }]);
1001
1461
  }
1002
1462
  case "TASK": {
1003
1463
  if (typeof value.taskRefKey !== "string" || typeof value.name !== "string")
@@ -1005,7 +1465,41 @@ function filterReferenceToTf(value, refs) {
1005
1465
  const task = refs.tasks.get(value.taskRefKey);
1006
1466
  if (task === undefined)
1007
1467
  throw new EntityTfError(`unresolved task filter ref "${value.taskRefKey}"`);
1008
- return expr.resourceAttr(task.type, task.label, ["refs", { index: taskWireRefName(value.name, value.taskRefKey, refs) }]);
1468
+ const isFileReaderTask = task.type === "elementum_ai_file_read_task" || task.type === "elementum_file_reader_task";
1469
+ const isAiAgentTask = task.type === "elementum_ai_agent_task";
1470
+ const wireName = isFileReaderTask || isAiAgentTask
1471
+ ? value.name
1472
+ : taskWireRefName(value.name, value.taskRefKey, refs);
1473
+ // left_value (switch cases): provider Read stores the JSON envelope that
1474
+ // `.refs["…"]` evaluates to (#490). Emitting the short `task.<id>.…`
1475
+ // string matches record_search RHS state but perpetual-diffs left_value.
1476
+ // value (RHS, e.g. record_search filters): state / ei use the short form.
1477
+ //
1478
+ // API `statusCode` is the exception: ei export jsonencodes the authored
1479
+ // TEXT envelope (`name = "statusCode"`). `.refs["API Response Status
1480
+ // Code"]` is NUMBER and plans against that export (Sanofi saveAttachment).
1481
+ if (role === "left") {
1482
+ const isApiStatusCode = task.type === TASK_RESOURCES.api &&
1483
+ (value.name === "statusCode" ||
1484
+ value.name === API_TASK_REF_WIRE_NAMES.statusCode ||
1485
+ wireName === API_TASK_REF_WIRE_NAMES.statusCode);
1486
+ if (isApiStatusCode) {
1487
+ return expr.jsonencode({
1488
+ fieldType: (realType ?? "TEXT").toUpperCase(),
1489
+ multiple: false,
1490
+ taskReference: {
1491
+ name: API_TASK_REF_AUTHORING_NAMES[wireName] ?? "statusCode",
1492
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
1493
+ },
1494
+ });
1495
+ }
1496
+ return expr.resourceAttr(task.type, task.label, ["refs", { index: wireName }]);
1497
+ }
1498
+ return expr.template([
1499
+ "task.",
1500
+ expr.resourceAttr(task.type, task.label, ["id"]),
1501
+ `.${wireName}`,
1502
+ ]);
1009
1503
  }
1010
1504
  case "FOR_EACH": {
1011
1505
  if (typeof value.forEachTaskRefKey !== "string" || typeof value.name !== "string")
@@ -1024,7 +1518,7 @@ function filterReferenceToTf(value, refs) {
1024
1518
  function picklistFilterValueToTf(value, field, refs) {
1025
1519
  if (typeof value !== "string" ||
1026
1520
  field?.__kind !== "field" ||
1027
- field.fieldType !== "PICKLIST" ||
1521
+ (field.fieldType !== "PICKLIST" && field.fieldType !== "MULTI_PICKLIST") ||
1028
1522
  field.options === undefined)
1029
1523
  return undefined;
1030
1524
  // An empty value is the platform's explicit "clear this field" payload,
@@ -1043,7 +1537,15 @@ function picklistFilterValueToTf(value, field, refs) {
1043
1537
  // rather than blocking on platform data it can't fix.
1044
1538
  if (isUuid(value))
1045
1539
  return undefined;
1046
- throw new EntityTfError(`automation filter for picklist field "${field.name ?? field.refName}" uses unknown option ${JSON.stringify(value)}; expected one of: ${field.options.map((option) => JSON.stringify(option)).join(", ")}`);
1540
+ // A pulled automation can legitimately retain a label for an option that
1541
+ // was deleted/recreated after the automation was authored. Keep the
1542
+ // literal so build remains a lossless offline round-trip; the provider
1543
+ // can report the platform-side mismatch during plan/apply.
1544
+ if (refs.allowUnknownPicklistOptions !== true) {
1545
+ throw new EntityTfError(`automation filter for picklist field "${field.name ?? field.refName}" uses unknown option ${JSON.stringify(value)}; expected one of: ${field.options.map((option) => JSON.stringify(option)).join(", ")}`);
1546
+ }
1547
+ refs.owner.diagnostics.push(`automation filter for picklist field ${JSON.stringify(field.name ?? field.refName)} preserves unknown option ${JSON.stringify(value)}`);
1548
+ return undefined;
1047
1549
  }
1048
1550
  if (field.parent !== undefined && field.parentKind !== undefined) {
1049
1551
  // A field owned by a SIBLING app/element built in this same workspace
@@ -1115,7 +1617,7 @@ function filterToTf(value, refs) {
1115
1617
  return serializeFilterToTf(value, {
1116
1618
  field: (field) => valueToTf(field, refs),
1117
1619
  fieldFromLeftValue: (left) => fieldFromFilterLeftValue(left, refs),
1118
- reference: (reference) => filterReferenceToTf(reference, refs),
1620
+ reference: (reference, role, realType) => filterReferenceToTf(reference, refs, role ?? "value", realType),
1119
1621
  literal: (literal, field) => picklistFilterValueToTf(literal, token(field), refs) ?? valueToTf(literal, refs),
1120
1622
  });
1121
1623
  }
@@ -1126,13 +1628,23 @@ function configAttrs(kind, config, refs) {
1126
1628
  continue;
1127
1629
  // A config value of exactly `undefined` almost always means the
1128
1630
  // authoring builder was called with a required option omitted (e.g. a
1129
- // TS-only-enforced field that jiti/bun never actually type-checks at
1631
+ // TS-only-enforced field that no runtime actually type-checks at
1130
1632
  // build time) - name the wire key here, since the generic valueToTf
1131
1633
  // fallback below has no attribute name to report by the time it gets to
1132
1634
  // its own "unsupported value" throw.
1133
1635
  if (raw === undefined) {
1134
1636
  throw new EntityTfError(`${kind}: config value for "${key}" is undefined — likely a missing required option on the authoring builder call that built this task/trigger`);
1135
1637
  }
1638
+ if (key === "procedure" && kind === "elementum_procedure_task") {
1639
+ const procedure = token(raw);
1640
+ if (procedure?.__kind !== "procedure") {
1641
+ throw new EntityTfError("procedure requires a procedure catalog reference");
1642
+ }
1643
+ const resolved = procedureToTf(procedure, refs.owner, refs.dataBlocks);
1644
+ attrs.cloudlink_id = resolved.cloudLinkId;
1645
+ attrs.stored_function_id = resolved.procedureId;
1646
+ continue;
1647
+ }
1136
1648
  // elementum_create_record_task has no "relate to record" boolean
1137
1649
  // attribute - relate_to_record_reference's presence alone conveys the
1138
1650
  // intent (see from-tf.ts's matching comment), so the flag itself is
@@ -1143,6 +1655,80 @@ function configAttrs(kind, config, refs) {
1143
1655
  attrs.relate_to_record_reference = valueToTf(raw, refs);
1144
1656
  continue;
1145
1657
  }
1658
+ if (key === "code" && kind === "elementum_execute_script_task") {
1659
+ if (typeof raw !== "string")
1660
+ throw new EntityTfError("executeScript code must be a string");
1661
+ attrs.code = raw;
1662
+ continue;
1663
+ }
1664
+ if (key === "inputMappings" && kind === "elementum_run_automation_task") {
1665
+ if (!Array.isArray(raw))
1666
+ throw new EntityTfError("runAutomation inputMappings must be an array");
1667
+ const target = token(config.targetAutomationId);
1668
+ if (target?.__kind !== "automation") {
1669
+ attrs.dynamic_input_mappings = raw.map((mapping) => {
1670
+ if (!isObject(mapping) || typeof mapping.name !== "string" || mapping.value === undefined) {
1671
+ throw new EntityTfError("runAutomation input mapping requires name and value");
1672
+ }
1673
+ return { name: mapping.name, value: valueToTf(mapping.value, refs) };
1674
+ });
1675
+ continue;
1676
+ }
1677
+ const resolvedTarget = automationTargetToTf(target, refs.owner, refs.dataBlocks);
1678
+ attrs.input_mappings = raw.map((mapping) => {
1679
+ if (!isObject(mapping) || typeof mapping.name !== "string" || mapping.value === undefined) {
1680
+ throw new EntityTfError("runAutomation input mapping requires name and value");
1681
+ }
1682
+ return {
1683
+ parameter_id: resolvedTarget.parameterId(mapping.name),
1684
+ value: valueToTf(mapping.value, refs),
1685
+ };
1686
+ });
1687
+ continue;
1688
+ }
1689
+ if (key === "outputMappings" && kind === "elementum_run_automation_task" && config.targetAutomationId !== undefined) {
1690
+ // Static run-automation tasks expose the published target's outputs in
1691
+ // `refs` automatically. The live API rejects even valid, matching
1692
+ // outputMappings with "Unable to validate" (#703), so keep authored
1693
+ // output names as a TypeScript typing aid and do not send the redundant
1694
+ // backend input. Dynamic targets still need their explicit mappings.
1695
+ continue;
1696
+ }
1697
+ if (key === "targetAutomationRef" && kind === "elementum_run_automation_task") {
1698
+ if (!isObject(raw) || raw.type !== "STATIC") {
1699
+ throw new EntityTfError("runAutomation targetAutomationRef must be { type: \"STATIC\", value: ... }");
1700
+ }
1701
+ const target = token(raw.value);
1702
+ if (target?.__kind === "automation") {
1703
+ attrs["target_automation_ref"] = automationRunTargetResourceAttr(refs.owner.appTfLabel, target.refName, refs.owner.activeAutomationRefNames);
1704
+ continue;
1705
+ }
1706
+ // Pull may leave a bare platform UUID when the target automation was
1707
+ // not discovered in this stream (ei export does the same). Emit
1708
+ // target_automation_id so the parent automation still builds —
1709
+ // otherwise skill tools that only need the catalog key fail closed.
1710
+ if (typeof raw.value === "string" && raw.value !== "") {
1711
+ attrs["target_automation_id"] = raw.value;
1712
+ refs.owner.diagnostics?.push(`runAutomation: target automation ${JSON.stringify(raw.value)} is unresolved; emitted as bare id`);
1713
+ continue;
1714
+ }
1715
+ throw new EntityTfError("runAutomation targetAutomationRef has an unresolved automation");
1716
+ }
1717
+ if (key === "targetAutomationId" && kind === "elementum_run_automation_task") {
1718
+ const target = token(raw);
1719
+ if (target?.__kind === "automation") {
1720
+ attrs["target_automation_id"] = automationTargetToTf(target, refs.owner, refs.dataBlocks).id;
1721
+ continue;
1722
+ }
1723
+ if (typeof raw === "string" && raw !== "") {
1724
+ attrs[Array.isArray(config.inputMappings) && config.inputMappings.length > 0
1725
+ ? "target_automation_ref"
1726
+ : "target_automation_id"] = raw;
1727
+ refs.owner.diagnostics?.push(`runAutomation: target automation ${JSON.stringify(raw)} is unresolved; emitted as bare id`);
1728
+ continue;
1729
+ }
1730
+ throw new EntityTfError("runAutomation targetAutomationId has an unresolved automation");
1731
+ }
1146
1732
  if (key === "filter") {
1147
1733
  attrs.filter = filterToTf(raw, refs);
1148
1734
  continue;
@@ -1209,6 +1795,10 @@ function configAttrs(kind, config, refs) {
1209
1795
  attrs.record_id = valueToTf(raw, refs);
1210
1796
  continue;
1211
1797
  }
1798
+ if (key === "recordId" && kind === "elementum_initiate_call_task") {
1799
+ attrs.record_id = valueToTf(raw, refs);
1800
+ continue;
1801
+ }
1212
1802
  if (key === "calculations" && kind === "elementum_calculation_task") {
1213
1803
  if (!Array.isArray(raw))
1214
1804
  throw new EntityTfError("calculations must be an array");
@@ -1261,18 +1851,23 @@ function configAttrs(kind, config, refs) {
1261
1851
  const parameters = raw.map((input) => {
1262
1852
  if (!isObject(input))
1263
1853
  throw new EntityTfError("onDemand input must be an object");
1264
- return Object.fromEntries(Object.entries(input).map(([k, v]) => [
1854
+ const mapped = Object.fromEntries(Object.entries(input)
1855
+ .filter(([k]) => k !== "app")
1856
+ .map(([k, v]) => [
1265
1857
  CONFIG_ATTRS[k] ?? snake(k),
1266
1858
  valueToTf(k === "defaultValue" ? unwrapDefault(v) :
1267
- // elementum_on_demand_trigger.parameters[].type's real validator
1268
- // (on_demand_trigger_resource.go) only accepts a bare "attachment"
1269
- // - there is no "attachment_id" variant at this layer, unlike the
1270
- // WorkflowFieldType enum name (ATTACHMENT_ID) the "attachmentId"
1271
- // authoring alias otherwise maps to. A generic lowercase would
1272
- // wrongly emit "attachment_id" and fail plan/apply.
1273
1859
  k === "type" && v === "ATTACHMENT_ID" ? "attachment" :
1274
- k === "type" && typeof v === "string" ? v.toLowerCase() : v, refs),
1860
+ k === "type" && v === "ASPECT_RECORD" ? "record" :
1861
+ k === "type" && typeof v === "string" ? v.toLowerCase() : v, refs),
1275
1862
  ]));
1863
+ if (isOnDemandRecordType(typeof input.type === "string" ? input.type : undefined)) {
1864
+ const target = token(input.app);
1865
+ if (target === undefined || (target.__kind !== "app" && target.__kind !== "element")) {
1866
+ throw new EntityTfError(`onDemand record parameter ${JSON.stringify(input.name)} requires an explicit app/element target`);
1867
+ }
1868
+ mapped.default_value = tokenToTf(target, refs.owner, refs.dataBlocks);
1869
+ }
1870
+ return mapped;
1276
1871
  });
1277
1872
  // The provider normalizes an absent parameter collection to null. An
1278
1873
  // explicit [] therefore creates perpetual [] vs null drift after pull.
@@ -1292,12 +1887,24 @@ function configAttrs(kind, config, refs) {
1292
1887
  const staticValue = isObject(field.valueReference) && "value" in field.valueReference
1293
1888
  ? field.valueReference.value
1294
1889
  : undefined;
1890
+ if (Array.isArray(staticValue)) {
1891
+ if (fieldToken?.fieldType !== "MULTI_PICKLIST") {
1892
+ throw new EntityTfError(`automation field "${fieldToken?.name ?? fieldToken?.refName ?? "unknown"}" uses an array value but is not a Multi-Select field`);
1893
+ }
1894
+ const values = staticValue.map((value) => picklistFilterValueToTf(value, fieldToken, refs) ?? valueToTf(value, refs));
1895
+ return {
1896
+ field_id: valueToTf(field.aspectFieldId, refs),
1897
+ value: expr.jsonencode(values),
1898
+ ...(field.operation === "ADD" ? { update_mode: "add" } : {}),
1899
+ };
1900
+ }
1295
1901
  const optionValue = staticValue !== undefined
1296
1902
  ? picklistFilterValueToTf(staticValue, fieldToken, refs)
1297
1903
  : undefined;
1298
1904
  return {
1299
1905
  field_id: valueToTf(field.aspectFieldId, refs),
1300
1906
  value: optionValue ?? valueToTf(field.valueReference, refs),
1907
+ ...(field.operation === "ADD" ? { update_mode: "add" } : {}),
1301
1908
  };
1302
1909
  });
1303
1910
  continue;
@@ -1455,26 +2062,14 @@ function fileReaderDependsOn(blocks) {
1455
2062
  });
1456
2063
  return deps;
1457
2064
  }
1458
- function taskLabel(automationLabel, refKey) {
1459
- // ei's task label is `<auto>_<sanitizeName(task name)>` (CLAUDE.md), and
1460
- // from-tf.ts's taskRefKey either preserves the task's raw display name
1461
- // verbatim (when it already round-trips through sanitizeName unchanged,
1462
- // e.g. "Send_field_update") or camelCases it via tfLabelToTsLabel (e.g.
1463
- // "notify_reviewer" -> "notifyReviewer"). sanitizeName reproduces the
1464
- // correct tf label for BOTH forms - splitCamelCase inserts the missing
1465
- // word boundary for the camelCase case, and is a no-op for the
1466
- // already-separated case. snakeSlug lowercases FIRST, so it never finds a
1467
- // boundary to split in pure camelCase input ("notifyReviewer" ->
1468
- // "notifyreviewer", no underscore) - confirmed live: this exact mismatch
1469
- // plans a spurious destroy+create pair on every apply.
1470
- const normalized = sanitizeName(refKey);
1471
- return normalized.startsWith(`${automationLabel}_`) ? normalized : `${automationLabel}_${normalized}`;
1472
- }
1473
2065
  /** App- or element-owned `automation` entity → provider HCL blocks. */
1474
2066
  export function automationToTf(entity, ctx) {
2067
+ const automationTfLabel = scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(entity.refName));
1475
2068
  const owner = {
1476
2069
  appRefName: ctx.appRefName ?? entity.parent,
2070
+ parentScope: ctx.parentScope ?? "app",
1477
2071
  appTfLabel: ctx.appTfLabel,
2072
+ automationTfLabel,
1478
2073
  fieldAddresses: ctx.fieldAddresses ?? new Map(),
1479
2074
  fieldNames: ctx.fieldNames ?? new Map(),
1480
2075
  fieldMetadata: ctx.fieldMetadata ?? new Map(),
@@ -1482,6 +2077,8 @@ export function automationToTf(entity, ctx) {
1482
2077
  localsAttrs: ctx.localsAttrs,
1483
2078
  workspaceAspects: ctx.workspaceAspects,
1484
2079
  diagnostics: ctx.diagnostics ?? [],
2080
+ activeAutomationRefNames: ctx.activeAutomationRefNames,
2081
+ automationNamesByRefName: ctx.automationNamesByRefName,
1485
2082
  };
1486
2083
  if (entity.kind !== "automation")
1487
2084
  throw new EntityTfError(`automationToTf expects kind "automation"; got "${entity.kind}"`);
@@ -1493,7 +2090,7 @@ export function automationToTf(entity, ctx) {
1493
2090
  throw new EntityTfError(`automation "${entity.refName}" has a non-object payload`);
1494
2091
  if (typeof payload.workflowRevision !== "string")
1495
2092
  throw new EntityTfError(`automation "${entity.refName}" has no workflowRevision`);
1496
- const label = scopedLabel(owner.appTfLabel, tsLabelToTfLabel(entity.refName));
2093
+ const label = automationTfLabel;
1497
2094
  const automation = {
1498
2095
  kind: "resource",
1499
2096
  type: AUTOMATION_RESOURCE_TYPE,
@@ -1543,13 +2140,28 @@ export function automationToTf(entity, ctx) {
1543
2140
  const resourceType = wireType === "variable" ? variableTaskResourceType(taskBody, refKey) : TASK_RESOURCES[wireType];
1544
2141
  if (resourceType === undefined)
1545
2142
  throw new EntityTfError(`task type "${wireType}" is not supported by the provider HCL contract`);
1546
- const registeredLabel = taskLabel(label, refKey);
2143
+ // elementum_unmanaged_task_reference is a data source exported under its
2144
+ // own bare sanitized-name label - never scoped under the automation the
2145
+ // way every real task resource is (confirmed live, edk#821).
2146
+ const registeredLabel = wireType === "unimplementedTask" ? sanitizeName(refKey) : taskTfLabel(label, refKey);
1547
2147
  const collidingRefKey = usedLabels.get(registeredLabel);
1548
2148
  if (collidingRefKey !== undefined) {
1549
2149
  throw new EntityTfError(`task "${refKey}" sanitizes to the same tf label as task "${collidingRefKey}" (${registeredLabel}) — rename one of them`);
1550
2150
  }
1551
2151
  usedLabels.set(registeredLabel, refKey);
1552
- taskRefs.set(refKey, { type: resourceType, label: registeredLabel });
2152
+ const outputFieldTypes = wireType === "executeScript"
2153
+ ? outputFieldTypesFromScriptSchema(taskBody.outputSchema)
2154
+ : wireType === "aiAgent" && Array.isArray(taskBody.jsonFields)
2155
+ ? new Map(taskBody.jsonFields.flatMap((field) => isObject(field) && typeof field.name === "string" && typeof field.type === "string"
2156
+ ? [[field.name, { fieldType: field.type, multiple: false }]]
2157
+ : []))
2158
+ : undefined;
2159
+ taskRefs.set(refKey, {
2160
+ type: resourceType,
2161
+ label: registeredLabel,
2162
+ ...(wireType === "unimplementedTask" ? { isData: true } : {}),
2163
+ ...(outputFieldTypes !== undefined && outputFieldTypes.size > 0 ? { outputFieldTypes } : {}),
2164
+ });
1553
2165
  if (wireType === "variable" && Array.isArray(taskBody.create)) {
1554
2166
  for (const candidate of taskBody.create) {
1555
2167
  if (isObject(candidate) && typeof candidate.id === "string" && typeof candidate.name === "string") {
@@ -1564,14 +2176,38 @@ export function automationToTf(entity, ctx) {
1564
2176
  preRegister(payload.tasks ?? []);
1565
2177
  const dataBlocks = new Map();
1566
2178
  const recordFieldContext = recordFieldContextOf(entity);
2179
+ const triggerParamNames = triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
2180
+ ? triggerConfig.inputs.flatMap((input) => isObject(input) && typeof input.name === "string" ? [input.name] : [])
2181
+ : [];
2182
+ const recordParamNames = triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
2183
+ ? triggerConfig.inputs.flatMap((input) => isObject(input) && typeof input.name === "string" && isOnDemandRecordType(typeof input.type === "string" ? input.type : undefined)
2184
+ ? [input.name]
2185
+ : [])
2186
+ : [];
2187
+ const recordParamTargets = new Map(triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
2188
+ ? triggerConfig.inputs.flatMap((input) => {
2189
+ if (!isObject(input) ||
2190
+ typeof input.name !== "string" ||
2191
+ !isOnDemandRecordType(typeof input.type === "string" ? input.type : undefined))
2192
+ return [];
2193
+ const target = token(input.app);
2194
+ return target !== undefined && (target.__kind === "app" || target.__kind === "element")
2195
+ ? [[input.name, target]]
2196
+ : [];
2197
+ })
2198
+ : []);
1567
2199
  const refs = {
1568
2200
  trigger: { type: triggerType, label },
2201
+ triggerParamNames,
2202
+ recordParamNames,
2203
+ recordParamTargets,
1569
2204
  tasks: taskRefs,
1570
2205
  owner,
1571
2206
  dataBlocks,
1572
2207
  variableById,
1573
2208
  ...(recordFieldContext !== undefined ? { recordFieldContext } : {}),
1574
2209
  ...(ctx.fieldNamesByAppRefName !== undefined ? { fieldNamesByAppRefName: ctx.fieldNamesByAppRefName } : {}),
2210
+ ...(ctx.allowUnknownPicklistOptions === true ? { allowUnknownPicklistOptions: true } : {}),
1575
2211
  };
1576
2212
  let triggerAttrs;
1577
2213
  try {
@@ -1590,7 +2226,14 @@ export function automationToTf(entity, ctx) {
1590
2226
  const blocks = [automation, trigger];
1591
2227
  const dependencies = [expr.resourceAttr(triggerType, label)];
1592
2228
  const runAutomationPublishes = new Set();
1593
- const emitTasks = (tasks, initialParent) => {
2229
+ // `enclosingOperator` describes the switch/forkJoin/forEach scope THIS
2230
+ // `emitTasks` call is nested inside (undefined at automation top level) -
2231
+ // needed only by `unimplementedTask` (edk#821) to populate
2232
+ // `operator_task_id`/`operator_child_id` correctly regardless of how many
2233
+ // real sibling tasks precede the placeholder within the same case/branch
2234
+ // (the rolling `taskParent` chain below tracks the PRECEDING SIBLING, not
2235
+ // the enclosing operator, once more than one task shares a scope).
2236
+ const emitTasks = (tasks, initialParent, enclosingOperator) => {
1594
2237
  let parent = initialParent;
1595
2238
  let first;
1596
2239
  for (const task of tasks) {
@@ -1608,7 +2251,67 @@ export function automationToTf(entity, ctx) {
1608
2251
  if (explicitParent === undefined) {
1609
2252
  throw new EntityTfError(`task "${refKey}" has unresolved explicit parent "${task.hclParent}"`);
1610
2253
  }
1611
- taskParent = expr.resourceAttr(explicitParent.type, explicitParent.label);
2254
+ // Naming the ENCLOSING forEach as the explicit parent means "head of the
2255
+ // loop body" (`<for_each>.inner`), not "sibling after the loop" (the
2256
+ // bare task) — ei writes those as two different addresses. Dropping the
2257
+ // path lifts the task out of the loop, and the provider then resolves
2258
+ // its operator context to the loop's own parent.
2259
+ const inBodyOfExplicitParent = initialParent.$expr === "resource-attr" &&
2260
+ initialParent.type === explicitParent.type &&
2261
+ initialParent.label === explicitParent.label &&
2262
+ initialParent.path.length === 1 &&
2263
+ initialParent.path[0] === "inner";
2264
+ taskParent = inBodyOfExplicitParent
2265
+ ? initialParent
2266
+ : explicitParent.isData === true
2267
+ ? expr.dataAttr(explicitParent.type, explicitParent.label)
2268
+ : expr.resourceAttr(explicitParent.type, explicitParent.label);
2269
+ }
2270
+ if (wireType === "unimplementedTask") {
2271
+ // elementum_unmanaged_task_reference (edk#785/edk#821) is a read-only
2272
+ // data source, not a resource: it has no CRUD, never joins
2273
+ // `depends_on`, and its structural fields (app_id/automation_id/
2274
+ // workflow_id/parent_is_trigger/operator_task_id/operator_child_id)
2275
+ // are re-derived from context rather than authored - only `id` and
2276
+ // `taskType` are authored (see tasks.ts's unimplementedTask).
2277
+ const idValue = isUnsafePlatformId(inner.id) ? inner.id.value : typeof inner.id === "string" ? inner.id : undefined;
2278
+ if (idValue === undefined)
2279
+ throw new EntityTfError(`unimplementedTask "${refKey}" requires an id`);
2280
+ if (typeof inner.taskType !== "string" || inner.taskType === "") {
2281
+ throw new EntityTfError(`unimplementedTask "${refKey}" requires a taskType`);
2282
+ }
2283
+ const operatorTaskAddress = enclosingOperator?.taskAddress;
2284
+ const operatorChildAddress = enclosingOperator?.childAddress;
2285
+ const isParentTrigger = enclosingOperator === undefined;
2286
+ const extraAttrs = {
2287
+ id: idValue,
2288
+ task_type: inner.taskType,
2289
+ workflow_id: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label, ["workflow_id"]),
2290
+ app_id: expr.resourceAttr(owner.parentScope === "element" ? "elementum_element" : "elementum_app", owner.appTfLabel, ["id"]),
2291
+ automation_id: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label, ["id"]),
2292
+ parent_is_trigger: isParentTrigger,
2293
+ ...(operatorTaskAddress !== undefined && operatorTaskAddress.$expr === "resource-attr"
2294
+ ? { operator_task_id: expr.resourceAttr(operatorTaskAddress.type, operatorTaskAddress.label, ["id"]) }
2295
+ : {}),
2296
+ ...(operatorChildAddress !== undefined && operatorChildAddress.$expr === "resource-attr"
2297
+ ? { operator_child_id: expr.resourceAttr(operatorChildAddress.type, operatorChildAddress.label, ["id"]) }
2298
+ : {}),
2299
+ };
2300
+ if (owner.orgRefs !== undefined) {
2301
+ owner.orgRefs.rawLookup("elementum_unmanaged_task_reference", tfLabel, displayName, extraAttrs);
2302
+ }
2303
+ else {
2304
+ dataBlocks.set(`elementum_unmanaged_task_reference.${tfLabel}`, {
2305
+ kind: "data",
2306
+ type: "elementum_unmanaged_task_reference",
2307
+ label: tfLabel,
2308
+ attrs: { name: displayName, ...extraAttrs },
2309
+ });
2310
+ }
2311
+ const address = expr.dataAttr("elementum_unmanaged_task_reference", tfLabel);
2312
+ first ??= address;
2313
+ parent = address;
2314
+ continue;
1612
2315
  }
1613
2316
  if (wireType === "variable") {
1614
2317
  const variableType = variableTaskResourceType(inner, refKey);
@@ -1652,28 +2355,34 @@ export function automationToTf(entity, ctx) {
1652
2355
  const block = { kind: "resource", type: resourceType, label: tfLabel, attrs };
1653
2356
  if (wireType === "runAutomation") {
1654
2357
  const target = token(inner.targetAutomationId) ?? (isObject(inner.targetAutomationRef) ? token(inner.targetAutomationRef.value) : undefined);
1655
- if (target === undefined || target.__kind !== "automation")
1656
- throw new EntityTfError(`runAutomation task "${refKey}" has an unresolved target`);
1657
- const targetLabel = scopedLabel(owner.appTfLabel, tsLabelToTfLabel(target.refName));
1658
- // A publish resource only exists for ACTIVE automations. Depending on
1659
- // a draft/inactive target's publish address produces invalid HCL.
1660
- if (ctx.activeAutomationRefNames?.has(target.refName) === true) {
1661
- block.attrs.depends_on = [expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, targetLabel)];
1662
- runAutomationPublishes.add(targetLabel);
2358
+ if (target?.__kind === "automation") {
2359
+ const targetLabel = scopedLabel(owner.appTfLabel, tsLabelToTfLabel(target.refName));
2360
+ // A publish resource only exists for ACTIVE automations. Depending on
2361
+ // a draft/inactive target's publish address produces invalid HCL.
2362
+ if (ctx.activeAutomationRefNames?.has(target.refName) === true) {
2363
+ block.attrs.depends_on = [expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, targetLabel)];
2364
+ runAutomationPublishes.add(targetLabel);
2365
+ }
1663
2366
  }
2367
+ // Bare-UUID / unresolved targets skip depends_on — configAttrs already
2368
+ // emitted target_automation_id as a literal and pushed a diagnostic.
1664
2369
  }
1665
2370
  blocks.push(block);
1666
2371
  const address = expr.resourceAttr(resourceType, tfLabel);
1667
2372
  dependencies.push(address);
1668
2373
  first ??= address;
1669
- // Only chain linear siblings; explicit hclParent keeps parallel roots under trigger.
1670
- if (task.hclParent === undefined)
1671
- parent = address;
2374
+ // Always advance the rolling continuation point to this task, even when
2375
+ // it was explicitly anchored (a fork root off the trigger or another
2376
+ // task). Whatever comes next in this same printed sequence is either
2377
+ // this task's own descendant (which must continue from it) or a task
2378
+ // with its own explicit anchor (which ignores this value entirely) -
2379
+ // never a sibling that should skip back to an earlier task.
2380
+ parent = address;
1672
2381
  if (wireType === "forEach") {
1673
2382
  const children = task.children ?? [];
1674
2383
  if (children.length !== 1)
1675
2384
  throw new EntityTfError(`forEach task "${refKey}" must have exactly one child body`);
1676
- emitTasks(children[0].tasks ?? [], expr.resourceAttr(resourceType, tfLabel, ["inner"]));
2385
+ emitTasks(children[0].tasks ?? [], expr.resourceAttr(resourceType, tfLabel, ["inner"]), { taskAddress: expr.resourceAttr(resourceType, tfLabel) });
1677
2386
  // The loop body is a separate operator-owned chain. A fluent sibling
1678
2387
  // authored after `forEach` continues from the for_each task itself,
1679
2388
  // not from the body's terminal task; the latter silently moves that
@@ -1684,20 +2393,40 @@ export function automationToTf(entity, ctx) {
1684
2393
  const children = task.children ?? [];
1685
2394
  if (children.length === 0)
1686
2395
  throw new EntityTfError(`${wireType} task "${refKey}" must have branches`);
2396
+ const usedLabels = new Map();
2397
+ for (const [index, child] of children.entries()) {
2398
+ const isDefault = wireType === "switch" && (child.isDefault === true || child.label === null);
2399
+ const displayLabel = isDefault
2400
+ ? (child.defaultLabel ?? "Default")
2401
+ : (child.label ?? "");
2402
+ const prior = usedLabels.get(displayLabel);
2403
+ if (prior !== undefined) {
2404
+ throw new EntityTfError(displayLabel === ""
2405
+ ? `${wireType} task "${refKey}" has more than one unlabeled case (cases ${prior} and ${index + 1}); give each case a unique label`
2406
+ : `${wireType} task "${refKey}" reuses label ${JSON.stringify(displayLabel)} on cases ${prior} and ${index + 1}`);
2407
+ }
2408
+ usedLabels.set(displayLabel, index + 1);
2409
+ }
1687
2410
  let previous;
1688
2411
  for (const [index, child] of children.entries()) {
1689
2412
  const branchType = wireType === "switch" ? "elementum_switch_case" : "elementum_fork_join_branch";
2413
+ const isDefault = wireType === "switch" && (child.isDefault === true || child.label === null);
1690
2414
  // ei's own resource label follows the branch's real display text
1691
2415
  // (a default branch renamed "Default Path" exports as
1692
2416
  // "..._default_path", not a hardcoded "..._default") - confirmed live.
1693
- const branchLabel = `${tfLabel}_${snakeSlug(child.label ?? child.defaultLabel ?? "default")}`;
2417
+ const fallbackLabel = isDefault ? "default" : `branch_${index + 1}`;
2418
+ const branchLabel = `${tfLabel}_${snakeSlug(child.label ?? child.defaultLabel ?? fallbackLabel)}`;
1694
2419
  const branchAttrs = {
1695
2420
  [wireType === "switch" ? "switch_task" : "fork_join_task"]: address,
1696
- label: child.label ?? child.defaultLabel ?? "Default",
2421
+ ...(isDefault
2422
+ ? { label: child.defaultLabel ?? "Default" }
2423
+ : child.label !== undefined && child.label !== null
2424
+ ? { label: child.label }
2425
+ : {}),
1697
2426
  ...(previous !== undefined ? { [wireType === "switch" ? "previous_case_id" : "previous_branch_id"]: { ...previous, path: ["id"] } } : {}),
1698
2427
  };
1699
2428
  if (wireType === "switch") {
1700
- if (child.label === null) {
2429
+ if (isDefault) {
1701
2430
  // The provider schema documents `filter`/`is_default` as
1702
2431
  // mutually exclusive ways to mark a switch default case, but
1703
2432
  // the platform doesn't retroactively normalize existing cases
@@ -1728,7 +2457,7 @@ export function automationToTf(entity, ctx) {
1728
2457
  blocks.push({ kind: "resource", type: branchType, label: branchLabel, attrs: branchAttrs });
1729
2458
  const branchAddress = expr.resourceAttr(branchType, branchLabel);
1730
2459
  dependencies.push(branchAddress);
1731
- emitTasks(child.tasks ?? [], branchAddress);
2460
+ emitTasks(child.tasks ?? [], branchAddress, { taskAddress: address, childAddress: branchAddress });
1732
2461
  previous = branchAddress;
1733
2462
  }
1734
2463
  }
@@ -1762,7 +2491,7 @@ export function automationToTf(entity, ctx) {
1762
2491
  ? { outputs: outputValues.map((output) => {
1763
2492
  if (typeof output.name !== "string")
1764
2493
  throw new EntityTfError("automation output has no name");
1765
- return { name: output.name, value: valueToTf(output.value, refs) };
2494
+ return { name: output.name, value: workflowPublishOutputValueToTf(output.value, refs) };
1766
2495
  }) }
1767
2496
  : {}),
1768
2497
  },