@elementumai/edk 0.9.20 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +19 -7
  2. package/dist-sdk/src/catalog/factories.d.ts +10 -2
  3. package/dist-sdk/src/catalog/factories.js +10 -1
  4. package/dist-sdk/src/catalog/index.d.ts +2 -2
  5. package/dist-sdk/src/catalog/index.js +1 -1
  6. package/dist-sdk/src/catalog/token.js +4 -0
  7. package/dist-sdk/src/catalog/types.d.ts +7 -1
  8. package/dist-sdk/src/catalog/types.js +1 -0
  9. package/dist-sdk/src/core/triggers/on-demand.d.ts +2 -2
  10. package/dist-sdk/src/core/triggers/on-demand.js +7 -0
  11. package/dist-sdk/src/core/types/app.d.ts +2 -2
  12. package/dist-sdk/src/engine/coverage-gaps.d.ts +86 -0
  13. package/dist-sdk/src/engine/coverage-gaps.js +156 -0
  14. package/dist-sdk/src/engine/ei/run.d.ts +21 -1
  15. package/dist-sdk/src/engine/ei/run.js +89 -2
  16. package/dist-sdk/src/engine/pull/catalog-ref.d.ts +16 -0
  17. package/dist-sdk/src/engine/pull/catalog-ref.js +24 -0
  18. package/dist-sdk/src/engine/pull/context.d.ts +68 -6
  19. package/dist-sdk/src/engine/pull/context.js +40 -1
  20. package/dist-sdk/src/engine/pull/procedure-refs.d.ts +8 -0
  21. package/dist-sdk/src/engine/pull/procedure-refs.js +28 -0
  22. package/dist-sdk/src/engine/pull/result-output.js +27 -1
  23. package/dist-sdk/src/engine/tf/index.d.ts +1 -1
  24. package/dist-sdk/src/engine/tf/index.js +1 -1
  25. package/dist-sdk/src/engine/tf/labels.d.ts +22 -5
  26. package/dist-sdk/src/engine/tf/labels.js +45 -3
  27. package/dist-sdk/src/engine/tf/parse.js +3 -2
  28. package/dist-sdk/src/engine/validation.d.ts +5 -0
  29. package/dist-sdk/src/engine/validation.js +12 -2
  30. package/dist-sdk/src/entities/access-policy/from-tf.js +38 -1
  31. package/dist-sdk/src/entities/access-policy/principal.d.ts +2 -0
  32. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +3 -0
  33. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +42 -19
  34. package/dist-sdk/src/entities/agent/from-tf.js +11 -3
  35. package/dist-sdk/src/entities/agent/module.js +2 -0
  36. package/dist-sdk/src/entities/agent/to-tf.js +14 -3
  37. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +8 -1
  38. package/dist-sdk/src/entities/agent-tool/from-tf.js +11 -5
  39. package/dist-sdk/src/entities/agent-tool/module.js +3 -0
  40. package/dist-sdk/src/entities/app/auto-share.d.ts +38 -0
  41. package/dist-sdk/src/entities/app/auto-share.js +49 -0
  42. package/dist-sdk/src/entities/app/build.d.ts +17 -3
  43. package/dist-sdk/src/entities/app/build.js +56 -4
  44. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +6 -1
  45. package/dist-sdk/src/entities/app/from-tf.js +4 -0
  46. package/dist-sdk/src/entities/app/index.d.ts +2 -1
  47. package/dist-sdk/src/entities/app/index.js +1 -8
  48. package/dist-sdk/src/entities/app/to-tf.d.ts +6 -0
  49. package/dist-sdk/src/entities/app/to-tf.js +21 -2
  50. package/dist-sdk/src/entities/automation/build.d.ts +10 -2
  51. package/dist-sdk/src/entities/automation/build.js +104 -17
  52. package/dist-sdk/src/entities/automation/calculation-expression.d.ts +7 -7
  53. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +17 -4
  54. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +156 -19
  55. package/dist-sdk/src/entities/automation/from-tf.d.ts +9 -2
  56. package/dist-sdk/src/entities/automation/from-tf.js +366 -86
  57. package/dist-sdk/src/entities/automation/index.d.ts +1 -1
  58. package/dist-sdk/src/entities/automation/index.js +1 -1
  59. package/dist-sdk/src/entities/automation/module.d.ts +3 -0
  60. package/dist-sdk/src/entities/automation/module.js +70 -7
  61. package/dist-sdk/src/entities/automation/script-code.d.ts +5 -2
  62. package/dist-sdk/src/entities/automation/script-code.js +23 -5
  63. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +37 -0
  64. package/dist-sdk/src/entities/automation/task-output-labels.js +76 -0
  65. package/dist-sdk/src/entities/automation/tasks.d.ts +92 -20
  66. package/dist-sdk/src/entities/automation/tasks.js +48 -15
  67. package/dist-sdk/src/entities/automation/to-tf.d.ts +20 -3
  68. package/dist-sdk/src/entities/automation/to-tf.js +606 -62
  69. package/dist-sdk/src/entities/automation/triggers.d.ts +8 -4
  70. package/dist-sdk/src/entities/automation/types.d.ts +9 -0
  71. package/dist-sdk/src/entities/automation/types.js +19 -0
  72. package/dist-sdk/src/entities/automation/value-ref-tf.d.ts +1 -1
  73. package/dist-sdk/src/entities/automation/value-ref-tf.js +1 -1
  74. package/dist-sdk/src/entities/chart/from-tf.js +9 -1
  75. package/dist-sdk/src/entities/data-lookup/module.js +2 -0
  76. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +1 -0
  77. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +7 -5
  78. package/dist-sdk/src/entities/element/build.d.ts +3 -0
  79. package/dist-sdk/src/entities/element/build.js +1 -0
  80. package/dist-sdk/src/entities/element/from-tf.js +4 -0
  81. package/dist-sdk/src/entities/element/to-tf.d.ts +1 -1
  82. package/dist-sdk/src/entities/element/to-tf.js +8 -14
  83. package/dist-sdk/src/entities/field/build.d.ts +3 -2
  84. package/dist-sdk/src/entities/field/calc.d.ts +7 -7
  85. package/dist-sdk/src/entities/field/from-tf.d.ts +4 -4
  86. package/dist-sdk/src/entities/field/from-tf.js +205 -48
  87. package/dist-sdk/src/entities/field/module.js +1 -0
  88. package/dist-sdk/src/entities/field/options.js +6 -1
  89. package/dist-sdk/src/entities/field/to-tf.d.ts +4 -4
  90. package/dist-sdk/src/entities/field/to-tf.js +7 -1
  91. package/dist-sdk/src/entities/field/types.d.ts +2 -0
  92. package/dist-sdk/src/entities/field/types.js +27 -0
  93. package/dist-sdk/src/entities/role/from-tf.js +3 -3
  94. package/dist-sdk/src/entities/role/to-tf.d.ts +2 -0
  95. package/dist-sdk/src/entities/role/to-tf.js +12 -4
  96. package/dist-sdk/src/entities/service-account/from-tf.js +3 -3
  97. package/dist-sdk/src/entities/service-account/workspace-owner.d.ts +16 -0
  98. package/dist-sdk/src/entities/service-account/workspace-owner.js +22 -0
  99. package/dist-sdk/src/entities/shared/filters/ast.d.ts +15 -1
  100. package/dist-sdk/src/entities/shared/filters/ast.js +2 -0
  101. package/dist-sdk/src/entities/shared/filters/index.d.ts +5 -0
  102. package/dist-sdk/src/entities/shared/filters/index.js +5 -0
  103. package/dist-sdk/src/entities/shared/filters/print.js +7 -2
  104. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +5 -0
  105. package/dist-sdk/src/entities/shared/filters/tf-codec.js +42 -7
  106. package/dist-sdk/src/entities/shared/filters/types.d.ts +8 -3
  107. package/dist-sdk/src/entities/shared/ref.d.ts +5 -7
  108. package/dist-sdk/src/entities/shared/ref.js +5 -7
  109. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +9 -0
  110. package/dist-sdk/src/entities/shared/tool-field-ref.js +35 -2
  111. package/dist-sdk/src/entities/shared/types/field-types.d.ts +10 -0
  112. package/dist-sdk/src/entities/shared/types/field-types.js +4 -0
  113. package/dist-sdk/src/entities/skill/access-policy.js +3 -3
  114. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +3 -0
  115. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +12 -5
  116. package/dist-sdk/src/entities/skill/from-tf.js +4 -2
  117. package/dist-sdk/src/entities/skill/module.js +2 -0
  118. package/dist-sdk/src/entities/skill-tool/from-tf.js +41 -8
  119. package/dist-sdk/src/entities/skill-tool/module.js +3 -0
  120. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +0 -6
  121. package/dist-sdk/src/entities/skill-tool/to-tf.js +22 -9
  122. package/dist-sdk/src/entities/task/build.d.ts +8 -0
  123. package/dist-sdk/src/entities/task/build.js +10 -1
  124. package/dist-sdk/src/entities/task/from-tf.d.ts +4 -2
  125. package/dist-sdk/src/entities/task/from-tf.js +7 -2
  126. package/dist-sdk/src/entities/task/module.js +2 -2
  127. package/dist-sdk/src/entities/task/to-tf.d.ts +8 -4
  128. package/dist-sdk/src/entities/task/to-tf.js +28 -1
  129. package/dist-sdk/src/entities/view/from-tf.js +9 -1
  130. package/dist-sdk/src/entities/view/to-tf.d.ts +6 -7
  131. package/dist-sdk/src/entities/view/to-tf.js +19 -8
  132. package/dist-sdk/src/entities/visual-flow/build.d.ts +16 -1
  133. package/dist-sdk/src/entities/visual-flow/build.js +9 -0
  134. package/dist-sdk/src/entities/visual-flow/from-tf.d.ts +14 -0
  135. package/dist-sdk/src/entities/visual-flow/from-tf.js +51 -3
  136. package/dist-sdk/src/entities/visual-flow/index.d.ts +1 -1
  137. package/dist-sdk/src/entities/visual-flow/index.js +1 -1
  138. package/dist-sdk/src/entities/visual-flow/printer.js +19 -0
  139. package/dist-sdk/src/entities/visual-flow/to-tf.js +87 -3
  140. package/dist-sdk/src/entities/widget/from-tf.js +3 -3
  141. package/dist-sdk/src/entities/widget/to-tf.d.ts +2 -0
  142. package/dist-sdk/src/entities/widget/to-tf.js +7 -6
  143. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +133 -9
  144. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  145. package/dist-sdk/src/graph/index.d.ts +1 -0
  146. package/dist-sdk/src/graph/types.d.ts +29 -3
  147. package/package.json +7 -3
@@ -1,6 +1,6 @@
1
1
  import { EntityTfError, recordFieldContextOf } from "../../engine/entity.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";
2
+ import { currentValidationMode, recordValidations, ValidationFailureError } from "../../engine/validation.js";
3
+ import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET } from "../../core/system-fields.js";
4
4
  import { ELEMENT_AUDIT_SYSTEM_FIELD_KEYS } from "../element/system-fields.js";
5
5
  import { isUnsafePlatformId } from "../../core/platform-id.js";
6
6
  import { appResourceLabelPrefix, appScopedResourceLabel, expr, isTfExpr, isUuid, sanitizeName, stableIdSuffix, scopedResourceLabel, tfLabelToTsLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
@@ -11,22 +11,36 @@ import { SERVICE_ACCOUNT_RESOURCE_TYPE } from "../service-account/module.js";
11
11
  import { foreignFieldDataLabel, resolveForeignRef } from "../shared/foreign-ref.js";
12
12
  import { filterToTf as serializeFilterToTf } from "../shared/filters/tf-codec.js";
13
13
  import { referenceValueTypeForField } from "../shared/filters/index.js";
14
- import { API_TASK_REF_AUTHORING_NAMES, API_TASK_REF_WIRE_NAMES } from "./output-key-wire-name.js";
14
+ import { API_TASK_REF_AUTHORING_NAMES, API_TASK_REF_WIRE_NAMES, OUTPUT_KEY_CANONICAL, OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
15
15
  import { outputFieldTypesFromScriptSchema, scriptOutputReferenceIsDeclared } from "./output-field-types.js";
16
16
  import { RESOURCE_TYPE_TO_EXECUTOR, TASK_OUTPUT_CONTRACTS } from "./generated/task-output-contracts.js";
17
17
  import { CONNECTOR_ORG_BAG } from "../org/connector.js";
18
+ import { GROUP_ORG_BAG } from "../org/group.js";
18
19
  import { FILE_READER_SUB_TYPE_BY_RESOURCE, FILE_READER_SUB_TYPE_BY_TYPE_KEY } from "../file-reader/types.js";
19
20
  import { UNRESOLVED_FIELD_MARKER } from "../shared/ref.js";
20
21
  import { ELEMENT_SYSTEM_FIELD_KEYS } from "../element/system-fields.js";
21
22
  import { TABLE_RESOURCE_TYPE } from "../table/module.js";
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";
23
+ import { AUTOMATION_RESOURCE_TYPE, WORKFLOW_PUBLISH_RESOURCE_TYPE, automationResourceLabel } from "./types.js";
24
+ import { AI_SEARCH_TABLE_OUTPUT_NAMES, TASK_OUTPUT_REFERENCE_NAMES, TRIGGER_WHOLE_RECORD_MARKER, USER_SEARCH_REF_WIRE_NAMES, triggerAttachmentPayloadRef, triggerWholeRecordRefJson, } from "./task-output-labels.js";
24
25
  import { onDemandTriggerRefKey } from "./value-ref-tf.js";
25
26
  import { normalizeOnDemandParamKey } from "../../../pull/util.js";
26
27
  import { PROVIDER_FIXED_SYSTEM_FIELD_KEYS, recordFieldWireRefName } from "./system-ref-name.js";
27
28
  import { taskTfLabel } from "./task-label.js";
28
29
  import { isOnDemandRecordType } from "../shared/types/field-types.js";
29
30
  /** The context for reading records of `appRefName` (a `kind`), retargeted from the owner. */
31
+ /**
32
+ * Wire WorkflowFieldType -> elementum_on_demand_trigger `parameters[].type`.
33
+ * Keys are exactly the provider's OneOf enum; anything else (JSON, OBJECT)
34
+ * is refused at build rather than lowercased into an invalid value (#1415).
35
+ */
36
+ const ON_DEMAND_TF_PARAM_TYPES = new Map([
37
+ ["TEXT", "text"], ["NUMBER", "number"], ["DECIMAL", "decimal"], ["BOOLEAN", "boolean"],
38
+ ["DATE", "date"], ["DATETIME", "datetime"], ["USER", "user"], ["USER_ID", "user"],
39
+ ["GROUP_ID", "group"], ["ATTACHMENT_ID", "attachment"], ["ASPECT_RECORD", "record"],
40
+ // Already-provider spellings pass through unchanged.
41
+ ...["text", "number", "decimal", "boolean", "date", "datetime", "user", "group", "attachment", "record"]
42
+ .map((t) => [t, t]),
43
+ ]);
30
44
  function recordOwnerContext(owner, appRefName, kind, fieldNames) {
31
45
  if (appRefName === owner.appRefName && (kind === undefined || kind === owner.parentScope))
32
46
  return owner;
@@ -49,6 +63,41 @@ function labelHash(value) {
49
63
  }
50
64
  return (hash >>> 0).toString(36);
51
65
  }
66
+ /**
67
+ * Terraform data label for a vault key. Keep this in lockstep with the
68
+ * exporter's VaultEntryLabel: readable for conventional uppercase keys and
69
+ * hash-suffixed whenever normalization could collide.
70
+ */
71
+ export function vaultEntryLabel(key) {
72
+ let label = key.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
73
+ if (label === "" || /^[0-9]/.test(label))
74
+ label = `vault_${label}`;
75
+ if (label.toUpperCase() === key)
76
+ return label;
77
+ let hash = 0x811c9dc5;
78
+ for (const byte of new TextEncoder().encode(key)) {
79
+ hash ^= byte;
80
+ hash = Math.imul(hash, 0x01000193);
81
+ }
82
+ return `${label}_${(hash >>> 0).toString(16).padStart(8, "0")}`;
83
+ }
84
+ function vaultEntryRefToTf(key, refs) {
85
+ if (key === "")
86
+ throw new EntityTfError("secret() requires a vault entry key");
87
+ const label = vaultEntryLabel(key);
88
+ if (refs.owner.orgRefs !== undefined) {
89
+ refs.owner.orgRefs.rawLookup("elementum_vault_entry", label, key);
90
+ }
91
+ else {
92
+ refs.dataBlocks.set(`elementum_vault_entry.${label}`, {
93
+ kind: "data",
94
+ type: "elementum_vault_entry",
95
+ label,
96
+ attrs: { key },
97
+ });
98
+ }
99
+ return expr.dataAttr("elementum_vault_entry", label, ["value_reference"]);
100
+ }
52
101
  function scopedOptionLocalName(localName, owner) {
53
102
  for (const suffix of ["_options_by_label", "_option_ids_by_label"]) {
54
103
  if (!localName.endsWith(suffix))
@@ -79,9 +128,16 @@ const TRIGGER_RESOURCES = {
79
128
  survey: "elementum_survey_trigger",
80
129
  schedule: "elementum_schedule_trigger",
81
130
  };
131
+ /**
132
+ * The live platform id of a created variable: `variables[<index>].id` on its
133
+ * elementum_variable_task (edk#1456; was the single-variable `variable_id`).
134
+ */
135
+ function variableIdAttr(target) {
136
+ return expr.resourceAttr(target.type, target.label, ["variables", { index: String(target.index) }, "id"]);
137
+ }
82
138
  /**
83
139
  * setVariable tasks share one wire key ("variable") but two distinct
84
- * resource types depending on create vs. update — TASK_RESOURCES can't
140
+ * resource types depending on whether they create any variable — TASK_RESOURCES can't
85
141
  * carry both under one key. Shared by preRegister (so an explicit
86
142
  * hclParent onto an update-variant task resolves to the right type — see
87
143
  * edk#287) and emitTasks's own block emission, so the two can never
@@ -90,14 +146,18 @@ const TRIGGER_RESOURCES = {
90
146
  function variableTaskResourceType(taskBody, refKey) {
91
147
  const creates = Array.isArray(taskBody.create) ? taskBody.create : [];
92
148
  const updates = Array.isArray(taskBody.update) ? taskBody.update : [];
93
- if (creates.length + updates.length !== 1) {
94
- throw new EntityTfError(`setVariable task "${refKey}" must contain exactly one create or update for Terraform`);
149
+ if (creates.length + updates.length === 0) {
150
+ throw new EntityTfError(`setVariable task "${refKey}" must contain at least one create or update for Terraform`);
95
151
  }
96
- return creates.length === 1 ? "elementum_variable_task" : "elementum_update_variable_task";
152
+ // edk#1456: a task with any create entry is an elementum_variable_task
153
+ // (variables, plus updates when mixed); update-only is
154
+ // elementum_update_variable_task (updates).
155
+ return creates.length > 0 ? "elementum_variable_task" : "elementum_update_variable_task";
97
156
  }
98
157
  const TASK_RESOURCES = {
99
158
  message: "elementum_message_task",
100
159
  updateField: "elementum_update_field_task",
160
+ bulkUpdateFields: "elementum_bulk_update_fields_task",
101
161
  variable: "elementum_variable_task",
102
162
  createRecord: "elementum_create_record_task",
103
163
  recordSearch: "elementum_record_search_task",
@@ -120,6 +180,7 @@ const TASK_RESOURCES = {
120
180
  aiSearchTable: "elementum_ai_search_table_task",
121
181
  aiTransform: "elementum_ai_transform_task",
122
182
  saveAttachment: "elementum_save_attachment_task",
183
+ unzip: "elementum_unzip_file_task",
123
184
  userSearch: "elementum_user_search_task",
124
185
  userGroupSearch: "elementum_user_group_search_task",
125
186
  calculation: "elementum_calculation_task",
@@ -460,8 +521,11 @@ function automationTargetToTf(value, ctx, dataBlocks) {
460
521
  ? sibling.tfLabel
461
522
  : undefined;
462
523
  if (managedOwnerLabel !== undefined) {
463
- const managedLabel = scopedLabel(managedOwnerLabel, tsLabelToTfLabel(value.refName));
464
524
  const targetOwner = ctx.workspaceAspects?.get(workspaceAspectKey(ownerKind, isOwn ? ctx.appRefName : value.parent ?? ""));
525
+ const managedHandle = ownerKind === "element"
526
+ ? elementHandleOf(isOwn ? ctx.ownerHandle : undefined, targetOwner?.streamRootEntity?.payload)
527
+ : undefined;
528
+ const managedLabel = automationResourceLabel(managedOwnerLabel, value.refName, ownerKind === "element" ? "element" : "app", managedHandle);
465
529
  const targetActiveRefs = targetOwner?.activeAutomationRefNames;
466
530
  const isActive = targetActiveRefs !== undefined
467
531
  ? targetActiveRefs.has(value.refName)
@@ -482,7 +546,11 @@ function automationTargetToTf(value, ctx, dataBlocks) {
482
546
  type: AUTOMATION_RESOURCE_TYPE,
483
547
  label: currentBindingLabel,
484
548
  attrs: {
485
- app_id: expr.resourceAttr(ownerKind === "element" ? "elementum_element" : "elementum_app", managedOwnerLabel, ["id"]),
549
+ // The owner id comes from the target automation itself. Referencing
550
+ // the app/element resource would defer this read whenever the app
551
+ // record has a pending change, making every parameter id unknown
552
+ // (edk#1514). `depends_on` still orders the read after publish.
553
+ app_id: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, managedLabel, ["app_id"]),
486
554
  id: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, managedLabel, ["id"]),
487
555
  depends_on: [expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, managedLabel)],
488
556
  },
@@ -839,7 +907,24 @@ function tokenToTf(value, ctx, dataBlocks) {
839
907
  // label (see ApprovalChainRef); preferring it rewrote live pulls to UUIDs.
840
908
  const refName = typeof value.refName === "string" ? value.refName.trim() : "";
841
909
  if (refName !== "") {
842
- return expr.resourceAttr("elementum_approval_process", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(refName)), ["id"]);
910
+ const address = `elementum_approval_process.${scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(refName))}`;
911
+ // Never emit a reference to an approval process this build doesn't
912
+ // declare (edk#1416). The build records the app's discovered
913
+ // approval-chain files; direct callers without that information keep
914
+ // the managed reference.
915
+ const declared = ctx.workspaceAspects
916
+ ?.get(workspaceAspectKey("app", ctx.appRefName))
917
+ ?.managedChildRefNames?.get("approval-chain");
918
+ if (declared === undefined || declared.has(refName)) {
919
+ return expr.resourceAttr("elementum_approval_process", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(refName)), ["id"]);
920
+ }
921
+ if (value.unresolvedId !== undefined) {
922
+ ctx.diagnostics.push(`automation ${ctx.automationTfLabel}: approval chain "${refName}" is not declared in this build (${address} would be undeclared); ` +
923
+ `using its pulled platform id ${value.unresolvedId} instead`);
924
+ return value.unresolvedId;
925
+ }
926
+ throw new EntityTfError(`automation ${ctx.automationTfLabel}: approval chain "${refName}" is not declared in this build (${address} is undeclared) ` +
927
+ `and the reference has no unresolvedId — add approval-chains/${refName}.ts to app "${ctx.appRefName}" or reference an existing approval process`);
843
928
  }
844
929
  if (value.unresolvedId !== undefined)
845
930
  return value.unresolvedId;
@@ -857,6 +942,33 @@ function tokenToTf(value, ctx, dataBlocks) {
857
942
  }
858
943
  return expr.resourceAttr(subType.resourceType, scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
859
944
  }
945
+ case "group": {
946
+ // Static notification/add-watcher recipients (edk#1389). An org.ts
947
+ // group resolves to its catalog lookup (or the managed resource), by
948
+ // key for an org.groups token or by name for a standalone
949
+ // groupRef({ name }) (whose refName is the display name). A group
950
+ // org.ts doesn't carry still builds as a name lookup, which is what
951
+ // the provider resolves anyway.
952
+ const refName = typeof value.refName === "string" ? value.refName : "";
953
+ const name = typeof value.name === "string" && value.name !== "" ? value.name : refName;
954
+ if (name === "")
955
+ throw new EntityTfError("group token has neither refName nor name");
956
+ const resolved = (refName !== "" ? ctx.orgRefs?.byTsLabel(GROUP_ORG_BAG, refName) : undefined)
957
+ ?? ctx.orgRefs?.byName(GROUP_ORG_BAG, name);
958
+ if (resolved !== undefined) {
959
+ return resolved.managed === true
960
+ ? expr.resourceAttr("elementum_group", resolved.tfLabel, ["id"])
961
+ : expr.dataAttr("elementum_group", resolved.tfLabel, ["id"]);
962
+ }
963
+ const label = sanitizeName(name);
964
+ if (ctx.orgRefs !== undefined) {
965
+ ctx.orgRefs.rawLookup("elementum_group", label, name);
966
+ }
967
+ else {
968
+ dataBlocks.set(`elementum_group.${label}`, { kind: "data", type: "elementum_group", label, attrs: { name } });
969
+ }
970
+ return expr.dataAttr("elementum_group", label, ["id"]);
971
+ }
860
972
  default:
861
973
  throw new EntityTfError(`catalog ref kind "${value.__kind}" has no automation HCL representation`);
862
974
  }
@@ -1031,7 +1143,7 @@ function calculationFormulaRefToParts(value, refs) {
1031
1143
  refs.owner.diagnostics.push(`automation unresolved variable ref ${JSON.stringify(value.variableReference.id)} preserved as a literal calculation reference`);
1032
1144
  return [`variable.${value.variableReference.id}`];
1033
1145
  }
1034
- return ["variable.", expr.resourceAttr(target.type, target.label, ["variable_id"])];
1146
+ return ["variable.", variableIdAttr(target)];
1035
1147
  }
1036
1148
  if (isObject(value.templateReference))
1037
1149
  return calculationTemplateToParts(value.templateReference, refs);
@@ -1120,8 +1232,9 @@ const FOUND_RECORD_TASK_TYPES = new Set([
1120
1232
  /**
1121
1233
  * A short-form `task.<id>.<name>` value reference addresses a found record's
1122
1234
  * 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.
1235
+ * not by the refs-map display label. A record of an app/element outside this
1236
+ * build gets its field id from a `data.elementum_field` lookup. Undefined when
1237
+ * the field's id cannot be resolved, which keeps the display-label form.
1125
1238
  */
1126
1239
  function foundRecordFieldReferenceName(targetType, name, taskRefKey, refs) {
1127
1240
  const segments = name.split(".");
@@ -1135,10 +1248,37 @@ function foundRecordFieldReferenceName(targetType, name, taskRefKey, refs) {
1135
1248
  }
1136
1249
  catch (error) {
1137
1250
  if (error instanceof EntityTfError)
1138
- return undefined;
1251
+ return foreignFoundRecordFieldReferenceName(segments, taskRefKey, refs);
1139
1252
  throw error;
1140
1253
  }
1141
1254
  }
1255
+ function foreignFoundRecordFieldReferenceName(segments, taskRefKey, refs) {
1256
+ const target = refs.tasks.get(taskRefKey)?.recordTarget;
1257
+ if (target === undefined || (target.__kind !== "app" && target.__kind !== "element") || target.name === undefined) {
1258
+ return undefined;
1259
+ }
1260
+ if (refs.owner.workspaceAspects?.has(workspaceAspectKey(target.__kind, target.refName)))
1261
+ return undefined;
1262
+ const fieldKey = segments[1];
1263
+ const fieldName = refs.fieldNamesByAppRefName?.get(target.refName)?.get(fieldKey);
1264
+ if (fieldName === undefined)
1265
+ return undefined;
1266
+ const fieldToken = {
1267
+ __kind: "field",
1268
+ refName: fieldKey,
1269
+ name: fieldName,
1270
+ parent: target.refName,
1271
+ parentKind: target.__kind,
1272
+ parentName: target.name,
1273
+ ...(target.namespace !== undefined ? { parentNamespace: target.namespace } : {}),
1274
+ };
1275
+ const suffix = segments.slice(2).join(".");
1276
+ return [
1277
+ "record.",
1278
+ expr.dataAttr("elementum_field", registerForeignFieldLookup(fieldToken, refs.owner, refs.dataBlocks), ["id"]),
1279
+ ...(suffix.length > 0 ? [`.${suffix}`] : []),
1280
+ ];
1281
+ }
1142
1282
  function calculationTriggerMustache(name, refs) {
1143
1283
  const onDemandName = onDemandTriggerRefName(name, refs);
1144
1284
  if (onDemandName !== undefined)
@@ -1202,6 +1342,11 @@ const TS_TRIGGER_REF_TO_WIRE = {
1202
1342
  // onto FIELD_REF_SUFFIX_TO_WIRE — that table's `id` suffix is " ID", which
1203
1343
  // would emit the wrong wire key "Attachment ID" and fail live validation.
1204
1344
  "attachment.id": "Attachment Id",
1345
+ // Pull decodes refs["Record"] (ASPECT_RECORD_ID) as the branded accessor
1346
+ // ctx.trigger.recordId (from-tf wireName "Record" → ["recordId"]). Rebuild
1347
+ // must emit the live key — without this entry wireRefName leaves "recordId"
1348
+ // verbatim and plan fails with Invalid index on refs["recordId"].
1349
+ recordId: "Record",
1205
1350
  // NOT createdByEmail/updatedByManagerEmail: the real record-field path
1206
1351
  // ("record.createdBy.email") never reaches this flat lookup table (see
1207
1352
  // from-tf.ts's matching comment) — this table is for genuine trigger-level
@@ -1221,7 +1366,14 @@ const TS_TRIGGER_REF_TO_WIRE = {
1221
1366
  body: "Body (Plain Text)",
1222
1367
  body_html: "Body (Rich Text)",
1223
1368
  };
1224
- const DISPLAY_REF_CANONICAL_CASE = Object.fromEntries(Object.values(TS_TRIGGER_REF_TO_WIRE).map((value) => [value.toLowerCase(), value]));
1369
+ // Exclude "Attachment Id" (attachment-trigger ATTACHMENT_ID): its
1370
+ // case-insensitive key collides with save_attachment's distinct live ref
1371
+ // "Attachment ID". Trigger paths resolve via TS_TRIGGER_REF_TO_WIRE
1372
+ // ("attachment.id") before this map; bracket-access "Attachment ID" must
1373
+ // pass through unchanged (#1651).
1374
+ const DISPLAY_REF_CANONICAL_CASE = Object.fromEntries(Object.values(TS_TRIGGER_REF_TO_WIRE)
1375
+ .filter((value) => value !== "Attachment Id")
1376
+ .map((value) => [value.toLowerCase(), value]));
1225
1377
  const FIELD_REF_SUFFIX_TO_WIRE = {
1226
1378
  "": "",
1227
1379
  id: " ID",
@@ -1570,8 +1722,8 @@ function recordParamFieldWireName(paramName, suffix, refs) {
1570
1722
  return wireRefName(`record.${suffix}`, recordOwnerContext(refs.owner, targetRefName, target.__kind === "element" || target.__kind === "app" ? target.__kind : undefined, targetFieldNames));
1571
1723
  }
1572
1724
  /** Run-automation targets reference publish for ACTIVE automations, automation for draft/inactive. */
1573
- export function automationRunTargetResourceAttr(appTfLabel, automationRefName, activeAutomationRefNames) {
1574
- const label = appScopedResourceLabel(appTfLabel, tsLabelToTfLabel(automationRefName));
1725
+ export function automationRunTargetResourceAttr(appTfLabel, automationRefName, activeAutomationRefNames, scope = "app", handle) {
1726
+ const label = automationResourceLabel(appTfLabel, automationRefName, scope, handle);
1575
1727
  if (activeAutomationRefNames?.has(automationRefName) === true) {
1576
1728
  return expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, label, ["id"]);
1577
1729
  }
@@ -1604,14 +1756,26 @@ function assertLiteralFitsFieldType(value, field) {
1604
1756
  if (rule === undefined)
1605
1757
  return;
1606
1758
  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}`);
1759
+ if (isObject(value) && typeof value.__kind === "string") {
1760
+ const tokenKind = value.__kind;
1761
+ if ((fieldType === "USER" && tokenKind === "user") || (fieldType === "GROUP" && tokenKind === "group"))
1762
+ return;
1763
+ if (tokenKind === "user" || tokenKind === "group") {
1764
+ const identity = tokenKind === "user" && typeof value.email === "string"
1765
+ ? value.email
1766
+ : typeof value.name === "string" ? value.name : tokenKind;
1767
+ throw new EntityTfError(`automation field "${label}" (${fieldType}) is given a ${tokenKind} token ${JSON.stringify(identity)}; it needs ${rule.expected}`);
1768
+ }
1769
+ }
1770
+ const text = isObject(value) && value.kind === "literal" && typeof value.value === "string" ? value.value : value;
1771
+ if (typeof text !== "string") {
1772
+ throw new EntityTfError(`automation field "${label}" (${fieldType}) is given a ${typeof text} literal; it needs ${rule.expected}`);
1609
1773
  }
1610
1774
  // The provider refuses `${...}` templates on these four types too, so a
1611
1775
  // template string is not left to the platform here.
1612
- if (rule.test(value))
1776
+ if (rule.test(text))
1613
1777
  return;
1614
- throw new EntityTfError(`automation field "${label}" (${fieldType}) is given the text ${JSON.stringify(value)}; it needs ${rule.expected}`);
1778
+ throw new EntityTfError(`automation field "${label}" (${fieldType}) is given the text ${JSON.stringify(text)}; it needs ${rule.expected}`);
1615
1779
  }
1616
1780
  /**
1617
1781
  * The platform refuses an element record create that leaves the title system
@@ -1833,7 +1997,7 @@ function workflowPublishOutputEnvelope(value, refs) {
1833
1997
  return {
1834
1998
  taskReference: null,
1835
1999
  triggerReference: null,
1836
- variableReference: { name: expr.template(["variable|", expr.resourceAttr(target.type, target.label, ["variable_id"])]) },
2000
+ variableReference: { name: expr.template(["variable|", variableIdAttr(target)]) },
1837
2001
  };
1838
2002
  }
1839
2003
  const name = typeof value.variableReference.name === "string" ? value.variableReference.name : undefined;
@@ -1913,6 +2077,84 @@ function collectUnresolvedForEachItems(value, found) {
1913
2077
  for (const nested of Object.values(value))
1914
2078
  collectUnresolvedForEachItems(nested, found);
1915
2079
  }
2080
+ /** The onDemand trigger's record parameters: they expose only a record ID. */
2081
+ function onDemandRecordParamNames(trigger) {
2082
+ const inputs = trigger?.onDemand?.inputs;
2083
+ if (!Array.isArray(inputs))
2084
+ return new Set();
2085
+ return new Set(inputs.flatMap((input) => {
2086
+ const param = input;
2087
+ return typeof param?.name === "string" && isOnDemandRecordType(typeof param.type === "string" ? param.type : undefined) ? [param.name] : [];
2088
+ }));
2089
+ }
2090
+ /** refKey → task kind (`findRelatedRecords`, …) for every task, nested ones included. */
2091
+ function collectPayloadTaskKinds(value, kinds) {
2092
+ if (Array.isArray(value)) {
2093
+ for (const item of value)
2094
+ collectPayloadTaskKinds(item, kinds);
2095
+ return kinds;
2096
+ }
2097
+ if (!isObject(value))
2098
+ return kinds;
2099
+ if (typeof value.refKey === "string" && isObject(value.task)) {
2100
+ const kind = Object.keys(value.task)[0];
2101
+ if (kind !== undefined)
2102
+ kinds.set(value.refKey, kind);
2103
+ }
2104
+ for (const nested of Object.values(value))
2105
+ collectPayloadTaskKinds(nested, kinds);
2106
+ return kinds;
2107
+ }
2108
+ /**
2109
+ * edk#1499: script-input field mappings read fields off a whole record. A
2110
+ * value that exposes only a record ID (an onDemand record parameter, or
2111
+ * findRelatedRecords' `.record`) deploys refs["Record"] (ASPECT_RECORD_ID)
2112
+ * plus field mappings, and the script receives `{}` at runtime. Record
2113
+ * triggers' `ctx.trigger.record` and the `.record` of recordSearch,
2114
+ * createRecord and updateField carry the whole record (#1284, #1489).
2115
+ */
2116
+ export function recordIdFieldMappingFailures(entity, payload, address) {
2117
+ const onDemandRecordParams = onDemandRecordParamNames(payload.trigger);
2118
+ const taskKinds = collectPayloadTaskKinds(payload, new Map());
2119
+ const name = "name" in payload && typeof payload.name === "string" && payload.name !== "" ? payload.name : entity.refName;
2120
+ const failures = [];
2121
+ const visit = (value, action) => {
2122
+ if (Array.isArray(value)) {
2123
+ for (const item of value)
2124
+ visit(item, action);
2125
+ return;
2126
+ }
2127
+ if (!isObject(value))
2128
+ return;
2129
+ const here = typeof value.refKey === "string" && isObject(value.task) ? value.refKey : action;
2130
+ if (Array.isArray(value.field_mappings) && isObject(value.value)) {
2131
+ let source;
2132
+ const trigger = value.value.triggerReference;
2133
+ if (isObject(trigger) && typeof trigger.name === "string" && onDemandRecordParams.has(trigger.name)) {
2134
+ source = `ctx.trigger.${trigger.name} (an on-demand record parameter)`;
2135
+ }
2136
+ const task = value.value.taskReference;
2137
+ if (isObject(task) && typeof task.taskRefKey === "string" && task.name === "record" && taskKinds.get(task.taskRefKey) === "findRelatedRecords") {
2138
+ source = `ctx.actions.${task.taskRefKey}.record (findRelatedRecords)`;
2139
+ }
2140
+ if (source !== undefined) {
2141
+ failures.push({
2142
+ severity: "fatal",
2143
+ address,
2144
+ name,
2145
+ ownerKind: "automation",
2146
+ message: `action "${here ?? "?"}" input "${typeof value.name === "string" ? value.name : "?"}": withFieldMappings(${source}) maps fields off a value that is only a record ID, ` +
2147
+ "so the script would receive {} at runtime. Look the record up first with a recordSearch on that ID " +
2148
+ "(e.g. .recordSearch(\"lookup\", …) filtered on the record id) and pass withFieldMappings(ctx.actions.lookup.record, …).",
2149
+ });
2150
+ }
2151
+ }
2152
+ for (const nested of Object.values(value))
2153
+ visit(nested, here);
2154
+ };
2155
+ visit(payload, undefined);
2156
+ return failures;
2157
+ }
1916
2158
  function unresolvedForEachFailures(entity, payload, address) {
1917
2159
  const found = [];
1918
2160
  collectUnresolvedForEachItems(payload, found);
@@ -1930,6 +2172,73 @@ function unresolvedForEachFailures(entity, payload, address) {
1930
2172
  "(e.g. restructure the loops, or pass the value through a variable) before this automation can build",
1931
2173
  }));
1932
2174
  }
2175
+ /**
2176
+ * execute_script `inputs[].value` only. Provider Read stores the
2177
+ * Mobius-normalized short name (`reasonForClosingEarly`) for on-demand
2178
+ * scalars; emitting refs["Reason for Closing Early"] drifts when that
2179
+ * display name also labels an app field. Other attrs keep refs["…"].
2180
+ */
2181
+ function executeScriptInputValueToTf(value, refs) {
2182
+ if (isObject(value) &&
2183
+ isObject(value.triggerReference) &&
2184
+ typeof value.triggerReference.name === "string" &&
2185
+ value[TRIGGER_WHOLE_RECORD_MARKER] !== true &&
2186
+ refs.trigger.type === TRIGGER_RESOURCES.onDemand) {
2187
+ const inputName = onDemandTriggerRefKey(value.triggerReference.name, [...refs.triggerParamFieldTypes.keys()]);
2188
+ const input = refs.triggerParamFieldTypes.get(inputName);
2189
+ // userId params publish no refs — fall through so valueToTf refuses them.
2190
+ if (input !== undefined &&
2191
+ !refs.recordParamNames.includes(inputName) &&
2192
+ !refs.userParamNames.includes(inputName)) {
2193
+ const typed = typeof value.fieldType === "string"
2194
+ ? { fieldType: value.fieldType, multiple: value.multiple === true }
2195
+ : input;
2196
+ return expr.jsonencode({
2197
+ fieldType: typed.fieldType,
2198
+ multiple: typed.multiple,
2199
+ triggerReference: { name: normalizeOnDemandParamKey(inputName) },
2200
+ });
2201
+ }
2202
+ }
2203
+ return valueToTf(value, refs);
2204
+ }
2205
+ /**
2206
+ * Pulled createRecord / updateField values sometimes embed a JSON envelope
2207
+ * string whose `triggerReference.name` is `recordId` and whose `fieldType`
2208
+ * is still `TEXT`. Live provider state for that record-trigger identity is
2209
+ * `ASPECT_RECORD_ID` (#1626). `record.id` is the TEXT handle (`refs["ID"]`)
2210
+ * and an on-demand text input that happens to be named `recordId` stays
2211
+ * TEXT, so neither is rewritten. Sibling keys and their order are kept.
2212
+ */
2213
+ function normalizeTriggerRecordIdEnvelopeString(raw, refs) {
2214
+ const trimmed = raw.trim();
2215
+ if (!trimmed.startsWith("{"))
2216
+ return raw;
2217
+ let parsed;
2218
+ try {
2219
+ parsed = JSON.parse(trimmed);
2220
+ }
2221
+ catch {
2222
+ return raw;
2223
+ }
2224
+ if (!isObject(parsed) || typeof parsed.fieldType !== "string")
2225
+ return raw;
2226
+ if (!isObject(parsed.triggerReference) || typeof parsed.triggerReference.name !== "string")
2227
+ return raw;
2228
+ if (parsed.triggerReference.name !== "recordId")
2229
+ return raw;
2230
+ if (refs.trigger.type === TRIGGER_RESOURCES.onDemand) {
2231
+ const inputName = onDemandTriggerRefKey(parsed.triggerReference.name, [...refs.triggerParamFieldTypes.keys()]);
2232
+ if (refs.triggerParamFieldTypes.has(inputName))
2233
+ return raw;
2234
+ }
2235
+ if (parsed.fieldType === "ASPECT_RECORD_ID" && parsed.multiple === false)
2236
+ return raw;
2237
+ const envelope = parsed;
2238
+ envelope.fieldType = "ASPECT_RECORD_ID";
2239
+ envelope.multiple = false;
2240
+ return JSON.stringify(envelope);
2241
+ }
1933
2242
  function valueToTf(value, refs) {
1934
2243
  const catalog = token(value);
1935
2244
  if (catalog !== undefined)
@@ -1971,6 +2280,17 @@ function valueToTf(value, refs) {
1971
2280
  return expr.resourceAttr(target.type, target.label, ["refs", { index: target.name }]);
1972
2281
  }
1973
2282
  if (isObject(value.triggerReference) && typeof value.triggerReference.name === "string") {
2283
+ // A record trigger's whole record has no refs key of its own: refs["Record"]
2284
+ // is the record ID (edk#1284). On-demand triggers name record params, not
2285
+ // `record`, so they keep their refs keys.
2286
+ if (value[TRIGGER_WHOLE_RECORD_MARKER] === true && refs.trigger.type !== TRIGGER_RESOURCES.onDemand) {
2287
+ return triggerWholeRecordRefJson(value.triggerReference.name);
2288
+ }
2289
+ if (refs.trigger.type === TRIGGER_RESOURCES.attachment && value.triggerReference.name.startsWith("attachment.")) {
2290
+ const payloadRef = triggerAttachmentPayloadRef(value.triggerReference.name.slice("attachment.".length));
2291
+ if (payloadRef !== undefined)
2292
+ return expr.jsonencode(payloadRef);
2293
+ }
1974
2294
  return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: triggerWireRefName(value.triggerReference.name, refs) }]);
1975
2295
  }
1976
2296
  if (isObject(value.taskReference) && typeof value.taskReference.taskRefKey === "string" && typeof value.taskReference.name === "string") {
@@ -2001,7 +2321,7 @@ function valueToTf(value, refs) {
2001
2321
  if (isObject(value.templateReference))
2002
2322
  return templateToTf(value.templateReference, refs);
2003
2323
  if (isObject(value.secretReference) && typeof value.secretReference.secretId === "string") {
2004
- throw new EntityTfError("secret references have no provider HCL representation");
2324
+ return vaultEntryRefToTf(value.secretReference.secretId, refs);
2005
2325
  }
2006
2326
  if (typeof value.kind === "string") {
2007
2327
  if (value.kind === "localRef" && typeof value.localName === "string" && Array.isArray(value.path)) {
@@ -2091,6 +2411,17 @@ function onDemandRecordFieldFilterReference(name, refs, operator) {
2091
2411
  throw new EntityTfError(`filter reference to "${fieldKey}" on on-demand record input "${paramName}": ${target.refName} is not built in this ` +
2092
2412
  `workspace or has no field "${fieldKey}", so its field id cannot be resolved`);
2093
2413
  }
2414
+ /**
2415
+ * The canonical (`service_tasks`) name of a single-output AI task's output,
2416
+ * when `wireName` is that output's refs display label. The filter short form
2417
+ * `task.<id>.<name>` uses it (`response`), not the label (`Response`).
2418
+ */
2419
+ function canonicalSingleOutputName(resourceType, wireName) {
2420
+ const taskKey = Object.keys(TASK_RESOURCES).find((key) => TASK_RESOURCES[key] === resourceType);
2421
+ if (taskKey === undefined || OUTPUT_KEY_WIRE_NAME[taskKey] !== wireName)
2422
+ return undefined;
2423
+ return OUTPUT_KEY_CANONICAL[taskKey];
2424
+ }
2094
2425
  function filterReferenceToTf(value, refs, role = "value", realType, operator) {
2095
2426
  // Raw pass-through for a filter left side the pull-time deserializer
2096
2427
  // couldn't decode to a typed ref (filter.ts's leftDescriptor, matching the
@@ -2195,6 +2526,16 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
2195
2526
  return `trigger.${value.name.replace(UNRESOLVED_FIELD_MARKER, "")}`;
2196
2527
  }
2197
2528
  }
2529
+ // Whole-record ID in a FILTER on a record-event trigger: ei exports the
2530
+ // short form `trigger.recordId`. Task inputs correctly use refs["Record"]
2531
+ // (ASPECT_RECORD_ID), but that JSON envelope plans as drift against the
2532
+ // short form after every pull. On-demand must NOT take this path —
2533
+ // `record` / `recordId` there are declared inputs that belong in
2534
+ // filter_refs["Record"] (edk#1524).
2535
+ if (refs.trigger.type !== TRIGGER_RESOURCES.onDemand &&
2536
+ (value.name === "recordId" || value.name === "record")) {
2537
+ return "trigger.recordId";
2538
+ }
2198
2539
  const triggerRefKey = triggerWireRefName(value.name, refs);
2199
2540
  if (refs.trigger.type === TRIGGER_RESOURCES.onDemand) {
2200
2541
  // filter_refs holds only declared inputs, so the clicking user has no key there.
@@ -2259,6 +2600,66 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
2259
2600
  },
2260
2601
  });
2261
2602
  }
2603
+ // A file reader's `refs` keys each parsed value by its own name; the
2604
+ // `jsonValues.<key>` path exists only as a stored envelope.
2605
+ if (isFileReaderTask && wireName.startsWith("jsonValues.")) {
2606
+ return expr.jsonencode({
2607
+ fieldType: (realType ?? "TEXT").toUpperCase(),
2608
+ multiple: false,
2609
+ taskReference: {
2610
+ name: wireName,
2611
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2612
+ },
2613
+ });
2614
+ }
2615
+ // An explicit filter.text() on a runAutomation output is a TEXT
2616
+ // envelope. A missing realType stays on .refs; the provider's refs
2617
+ // map is already TEXT for outputs ei stores that way.
2618
+ if (task.type === TASK_RESOURCES.runAutomation && realType?.toUpperCase() === "TEXT") {
2619
+ return expr.jsonencode({
2620
+ fieldType: "TEXT",
2621
+ multiple: false,
2622
+ taskReference: {
2623
+ name: wireName,
2624
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2625
+ },
2626
+ });
2627
+ }
2628
+ // A text comparison of a boolean, integer, or script-number output
2629
+ // stores a TEXT envelope, while `refs` carries the declared type.
2630
+ // A script `number` output is declared DECIMAL; NUMBER is the integer
2631
+ // projection. Id-typed outputs keep their own type.
2632
+ const envelopeName = TASK_OUTPUT_REFERENCE_NAMES[task.type]?.[wireName] ?? wireName;
2633
+ const executor = RESOURCE_TYPE_TO_EXECUTOR[task.type];
2634
+ const declared = task.outputFieldTypes?.get(wireName) ??
2635
+ (executor === undefined ? undefined : TASK_OUTPUT_CONTRACTS[executor]?.[envelopeName]);
2636
+ if (realType?.toUpperCase() === "TEXT" && (declared?.fieldType === "BOOLEAN" || declared?.fieldType === "NUMBER" || declared?.fieldType === "DECIMAL")) {
2637
+ return expr.jsonencode({
2638
+ fieldType: "TEXT",
2639
+ multiple: declared.multiple,
2640
+ taskReference: {
2641
+ name: envelopeName,
2642
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2643
+ },
2644
+ });
2645
+ }
2646
+ // `filter.number()` on an execute-script `number` output: the platform
2647
+ // stores the NUMBER envelope the author wrote, while `refs` types the
2648
+ // output from its schema as DECIMAL. Building from `refs` plans
2649
+ // `fieldType` NUMBER -> DECIMAL on every pulled case (#1618: 29
2650
+ // cases across 5 apps, 15 in signatureenvelope). Only this observed
2651
+ // direction is handled; no live DECIMAL envelope on a NUMBER output
2652
+ // has been seen.
2653
+ if (realType?.toUpperCase() === "NUMBER" && declared?.fieldType === "DECIMAL") {
2654
+ return expr.jsonencode({
2655
+ fieldType: "NUMBER",
2656
+ multiple: declared.multiple,
2657
+ taskReference: {
2658
+ name: envelopeName,
2659
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2660
+ },
2661
+ });
2662
+ }
2262
2663
  const ambiguousRecordField = recordRefKeyIsAmbiguous(value.name, wireName, value.taskRefKey, refs)
2263
2664
  ? foundRecordFieldReferenceName(task.type, value.name, value.taskRefKey, refs)
2264
2665
  : undefined;
@@ -2285,14 +2686,37 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
2285
2686
  },
2286
2687
  });
2287
2688
  }
2689
+ // A text comparison of a found record's field stores a TEXT envelope
2690
+ // named by field id, while `refs` carries the field's own type
2691
+ // (JSON_TEXT, PICKLIST_ID).
2692
+ const textCastRecordField = realType?.toUpperCase() === "TEXT"
2693
+ ? foundRecordFieldReferenceName(task.type, value.name, value.taskRefKey, refs)
2694
+ : undefined;
2695
+ if (textCastRecordField !== undefined) {
2696
+ return expr.jsonencode({
2697
+ fieldType: "TEXT",
2698
+ multiple: false,
2699
+ taskReference: {
2700
+ name: expr.template(textCastRecordField),
2701
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2702
+ },
2703
+ });
2704
+ }
2288
2705
  return expr.resourceAttr(task.type, task.label, ["refs", { index: wireName }]);
2289
2706
  }
2290
2707
  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.
2708
+ // The short form addresses user-search outputs by path, and an AI task's
2709
+ // single output by its canonical name (`response`, edk#1509); only
2710
+ // `.refs` is keyed by their display labels. recordSearch's ASPECT_RECORD_ID
2711
+ // is keyed `First found record id` in refs, but filter RHS / ei export use
2712
+ // the canonical short name `recordId` (service_tasks) — emitting the
2713
+ // display label here plans drift after every pull (edk#1524).
2293
2714
  const shortName = task.type === TASK_RESOURCES.userSearch
2294
2715
  ? USER_SEARCH_PATH_BY_WIRE_NAME.get(wireName) ?? wireName
2295
- : wireName;
2716
+ : task.type === TASK_RESOURCES.recordSearch &&
2717
+ (wireName === "First found record id" || value.name === "record.recordId" || value.name === "recordId")
2718
+ ? "recordId"
2719
+ : canonicalSingleOutputName(task.type, wireName) ?? wireName;
2296
2720
  return expr.template([
2297
2721
  "task.",
2298
2722
  expr.resourceAttr(task.type, task.label, ["id"]),
@@ -2330,7 +2754,7 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
2330
2754
  if (target === undefined) {
2331
2755
  throw new EntityTfError("variable filter reference could not be resolved to a variable task — the referenced workflow variable must be created by a setVariable task in the same automation");
2332
2756
  }
2333
- return expr.template(["variable.", expr.resourceAttr(target.type, target.label, ["variable_id"])]);
2757
+ return expr.template(["variable.", variableIdAttr(target)]);
2334
2758
  }
2335
2759
  default:
2336
2760
  throw new EntityTfError(`unsupported filter reference type "${value.type}"`);
@@ -2484,8 +2908,8 @@ function filterToTf(value, refs) {
2484
2908
  if (parsed === undefined)
2485
2909
  return authored;
2486
2910
  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)) {
2911
+ // An option picklist's bare or `.id` reference is a UUID. A dynamic dropdown's is stored as text.
2912
+ if ((parsed.suffix === "" || parsed.suffix === "id") && metadata?.fieldType === "PICKLIST" && !isOptionBearingPicklist(metadata)) {
2489
2913
  return authored;
2490
2914
  }
2491
2915
  const inferred = referenceValueTypeForField(metadata?.fieldType, parsed.suffix);
@@ -2505,8 +2929,22 @@ function filterToTf(value, refs) {
2505
2929
  literal: (literal, field) => picklistFilterValueToTf(literal, token(field), refs) ?? valueToTf(literal, refs),
2506
2930
  });
2507
2931
  }
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"));
2932
+ /**
2933
+ * System fields a record-updated trigger cannot meaningfully watch: these never
2934
+ * change after create, or change on every update. Closed At and Closed By change
2935
+ * once, on close, and the platform stores them in changed_fields.
2936
+ */
2937
+ const UNWATCHABLE_SYSTEM_FIELD_KEYS = new Set(["id", "createdAt", "createdBy", "updatedAt", "updatedBy"]);
2938
+ function isRunAutomationValueReference(raw) {
2939
+ if (!isObject(raw))
2940
+ return false;
2941
+ return (isObject(raw.triggerReference) ||
2942
+ isObject(raw.taskReference) ||
2943
+ isObject(raw.forEachReference) ||
2944
+ isObject(raw.templateReference) ||
2945
+ isObject(raw.secretReference) ||
2946
+ isObject(raw.variableReference));
2947
+ }
2510
2948
  function configAttrs(kind, config, refs) {
2511
2949
  const attrs = {};
2512
2950
  for (const [key, raw] of Object.entries(config)) {
@@ -2556,6 +2994,27 @@ function configAttrs(kind, config, refs) {
2556
2994
  attrs.code = raw;
2557
2995
  continue;
2558
2996
  }
2997
+ // execute_script input values: provider Read stores Mobius-normalized
2998
+ // short names for on-demand scalars. Keep that envelope here only —
2999
+ // templates, notifications, and other attrs still use refs["…"].
3000
+ if (key === "inputs" && kind === "elementum_execute_script_task") {
3001
+ if (!Array.isArray(raw))
3002
+ throw new EntityTfError("executeScript inputs must be an array");
3003
+ attrs.inputs = raw.map((item) => {
3004
+ if (!isObject(item) || typeof item.name !== "string") {
3005
+ throw new EntityTfError("invalid executeScript input");
3006
+ }
3007
+ const mapped = {
3008
+ name: item.name,
3009
+ value: executeScriptInputValueToTf(item.value, refs),
3010
+ };
3011
+ if (item.field_mappings !== undefined) {
3012
+ mapped.field_mappings = valueToTf(item.field_mappings, refs);
3013
+ }
3014
+ return mapped;
3015
+ });
3016
+ continue;
3017
+ }
2559
3018
  if (key === "inputMappings" && kind === "elementum_run_automation_task") {
2560
3019
  if (!Array.isArray(raw))
2561
3020
  throw new EntityTfError("runAutomation inputMappings must be an array");
@@ -2590,12 +3049,22 @@ function configAttrs(kind, config, refs) {
2590
3049
  continue;
2591
3050
  }
2592
3051
  if (key === "targetAutomationRef" && kind === "elementum_run_automation_task") {
3052
+ // A Dynamic Reference is a serialized value reference (trigger, task,
3053
+ // loop, template, secret, variable). `{ type: "DYNAMIC" }` is not one;
3054
+ // that shape still has to be a STATIC catalog target.
3055
+ if (isRunAutomationValueReference(raw)) {
3056
+ if (config.synchronous !== true) {
3057
+ throw new EntityTfError("runAutomation Dynamic Reference target requires synchronous: true");
3058
+ }
3059
+ attrs["target_automation_ref"] = valueToTf(raw, refs);
3060
+ continue;
3061
+ }
2593
3062
  if (!isObject(raw) || raw.type !== "STATIC") {
2594
3063
  throw new EntityTfError("runAutomation targetAutomationRef must be { type: \"STATIC\", value: ... }");
2595
3064
  }
2596
3065
  const target = token(raw.value);
2597
3066
  if (target?.__kind === "automation") {
2598
- attrs["target_automation_ref"] = automationRunTargetResourceAttr(refs.owner.appTfLabel, target.refName, refs.owner.activeAutomationRefNames);
3067
+ attrs["target_automation_ref"] = automationRunTargetResourceAttr(refs.owner.appTfLabel, target.refName, refs.owner.activeAutomationRefNames, refs.owner.parentScope, refs.owner.ownerHandle);
2599
3068
  continue;
2600
3069
  }
2601
3070
  // Pull may leave a bare platform UUID when the target automation was
@@ -2778,15 +3247,17 @@ function configAttrs(kind, config, refs) {
2778
3247
  const parameters = raw.map((input) => {
2779
3248
  if (!isObject(input))
2780
3249
  throw new EntityTfError("onDemand input must be an object");
3250
+ if (typeof input.type !== "string" || !ON_DEMAND_TF_PARAM_TYPES.has(input.type)) {
3251
+ throw new EntityTfError(`onDemand parameter ${JSON.stringify(input.name)} has type ${JSON.stringify(input.type)}, which ` +
3252
+ `elementum_on_demand_trigger does not support (allowed: text, number, decimal, boolean, date, ` +
3253
+ `datetime, userId, attachmentId, record). Use "text" for a JSON string.`);
3254
+ }
2781
3255
  const mapped = Object.fromEntries(Object.entries(input)
2782
3256
  .filter(([k]) => k !== "app")
2783
3257
  .map(([k, v]) => [
2784
3258
  CONFIG_ATTRS[k] ?? snake(k),
2785
3259
  valueToTf(k === "defaultValue" ? unwrapDefault(v) :
2786
- k === "type" && v === "ATTACHMENT_ID" ? "attachment" :
2787
- k === "type" && v === "USER_ID" ? "user" :
2788
- k === "type" && v === "ASPECT_RECORD" ? "record" :
2789
- k === "type" && typeof v === "string" ? v.toLowerCase() : v, refs),
3260
+ k === "type" && typeof v === "string" ? ON_DEMAND_TF_PARAM_TYPES.get(v) : v, refs),
2790
3261
  ]));
2791
3262
  if (isOnDemandRecordType(typeof input.type === "string" ? input.type : undefined)) {
2792
3263
  const target = token(input.app);
@@ -2843,9 +3314,16 @@ function configAttrs(kind, config, refs) {
2843
3314
  const optionValue = staticValue !== undefined
2844
3315
  ? picklistFilterValueToTf(staticValue, fieldToken, refs)
2845
3316
  : undefined;
3317
+ let reference = field.valueReference;
3318
+ if (typeof reference === "string") {
3319
+ reference = normalizeTriggerRecordIdEnvelopeString(reference, refs);
3320
+ }
3321
+ else if (isObject(reference) && typeof reference.value === "string" && Object.keys(reference).length === 1) {
3322
+ reference = { value: normalizeTriggerRecordIdEnvelopeString(reference.value, refs) };
3323
+ }
2846
3324
  return {
2847
3325
  field_id: valueToTf(field.aspectFieldId, refs),
2848
- value: optionValue ?? valueToTf(field.valueReference, refs),
3326
+ value: optionValue ?? valueToTf(reference, refs),
2849
3327
  ...(field.operation === "ADD" ? { update_mode: "add" } : {}),
2850
3328
  };
2851
3329
  });
@@ -2911,12 +3389,34 @@ function configAttrs(kind, config, refs) {
2911
3389
  if (key === "basicAuth" && kind === "elementum_api_task") {
2912
3390
  if (!isObject(raw))
2913
3391
  throw new EntityTfError("apiRequest basicAuth must be an object");
3392
+ // A requiredSecret username is write-only on the platform: emit the
3393
+ // provider's write-only username_wo so a null read never plans a
3394
+ // change (edk#1400).
3395
+ // A secret("KEY") username is bound to a vault entry: emit
3396
+ // reference_username so the platform resolves it at runtime instead of
3397
+ // storing the lookup as a static username (edk#1283).
2914
3398
  attrs.basic_auth = {
2915
- username: valueToTf(raw.username, refs),
3399
+ ...(isVaultSecretRaw(raw.username)
3400
+ ? { reference_username: valueToTf(raw.username, refs) }
3401
+ : isRequiredSecretRaw(raw.username)
3402
+ ? { username_wo: valueToTf(raw.username, refs) }
3403
+ : { username: valueToTf(raw.username, refs) }),
2916
3404
  ...(raw.referencePassword !== undefined ? { reference_password: valueToTf(raw.referencePassword, refs) } : {}),
2917
3405
  };
2918
3406
  continue;
2919
3407
  }
3408
+ if (key === "headers" && kind === "elementum_api_task" && Array.isArray(raw)) {
3409
+ // A requiredSecret header value is unreadable on the platform: emit the
3410
+ // write-only value_wo so the imported null never plans a change (edk#1400).
3411
+ attrs.headers = raw.map((h) => {
3412
+ if (!isObject(h))
3413
+ throw new EntityTfError("invalid apiRequest header");
3414
+ const header = { name: valueToTf(h.name, refs) };
3415
+ header[isRequiredSecretRaw(h.value) ? "value_wo" : "value"] = valueToTf(h.value, refs);
3416
+ return header;
3417
+ });
3418
+ continue;
3419
+ }
2920
3420
  if (key === "bearerAuth" && kind === "elementum_api_task") {
2921
3421
  if (!isObject(raw))
2922
3422
  throw new EntityTfError("apiRequest bearerAuth must be an object");
@@ -2939,8 +3439,15 @@ function configAttrs(kind, config, refs) {
2939
3439
  attrs.oauth = {
2940
3440
  request_type: valueToTf(raw.requestType, refs),
2941
3441
  ...(raw.url !== undefined ? { url: valueToTf(raw.url, refs) } : {}),
2942
- ...(raw.clientId !== undefined ? { client_id: valueToTf(raw.clientId, refs) } : {}),
2943
- ...(raw.clientSecret !== undefined ? { client_secret: valueToTf(raw.clientSecret, refs) } : {}),
3442
+ // secret("KEY") client credentials bind to vault entries through the
3443
+ // reference_ attributes; a static string stays client_id/client_secret
3444
+ // (edk#1283).
3445
+ ...(raw.clientId !== undefined
3446
+ ? { [isVaultSecretRaw(raw.clientId) ? "reference_client_id" : "client_id"]: valueToTf(raw.clientId, refs) }
3447
+ : {}),
3448
+ ...(raw.clientSecret !== undefined
3449
+ ? { [isVaultSecretRaw(raw.clientSecret) ? "reference_client_secret" : "client_secret"]: valueToTf(raw.clientSecret, refs) }
3450
+ : {}),
2944
3451
  ...(headers !== undefined ? { headers } : {}),
2945
3452
  };
2946
3453
  continue;
@@ -3011,11 +3518,20 @@ function fileReaderDependsOn(blocks) {
3011
3518
  return deps;
3012
3519
  }
3013
3520
  /** App- or element-owned `automation` entity → provider HCL blocks. */
3521
+ function elementHandleOf(explicit, payload) {
3522
+ if (explicit !== undefined && explicit !== "")
3523
+ return explicit;
3524
+ if (payload === null || typeof payload !== "object" || !("handle" in payload))
3525
+ return undefined;
3526
+ const handle = payload.handle;
3527
+ return typeof handle === "string" && handle !== "" ? handle : undefined;
3528
+ }
3014
3529
  export function automationToTf(entity, ctx) {
3015
- const automationTfLabel = scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(entity.refName));
3530
+ const automationTfLabel = automationResourceLabel(ctx.appTfLabel, entity.refName, ctx.parentScope, ctx.parentScope === "element" ? ctx.ownerHandle : undefined);
3016
3531
  const owner = {
3017
3532
  appRefName: ctx.appRefName ?? entity.parent,
3018
3533
  parentScope: ctx.parentScope ?? "app",
3534
+ ownerHandle: ctx.ownerHandle,
3019
3535
  appTfLabel: ctx.appTfLabel,
3020
3536
  automationTfLabel,
3021
3537
  fieldAddresses: ctx.fieldAddresses ?? new Map(),
@@ -3041,6 +3557,16 @@ export function automationToTf(entity, ctx) {
3041
3557
  const unresolved = unresolvedForEachFailures(entity, payload, `${AUTOMATION_RESOURCE_TYPE}.${automationTfLabel}`);
3042
3558
  if (unresolved.length > 0)
3043
3559
  throw new ValidationFailureError(unresolved);
3560
+ const recordIdMappings = recordIdFieldMappingFailures(entity, payload, `${AUTOMATION_RESOURCE_TYPE}.${automationTfLabel}`);
3561
+ if (recordIdMappings.length > 0) {
3562
+ // Fatal for build/plan/apply. Pull is a read of live config: it warns by
3563
+ // name and keeps emitting the live shape, so the source is still written
3564
+ // and the user can fix it (edk#1499).
3565
+ if (currentValidationMode() === "pull")
3566
+ recordValidations(recordIdMappings.map((failure) => ({ ...failure, severity: "warning" })));
3567
+ else
3568
+ throw new ValidationFailureError(recordIdMappings);
3569
+ }
3044
3570
  if (typeof payload.workflowRevision !== "string")
3045
3571
  throw new EntityTfError(`automation "${entity.refName}" has no workflowRevision`);
3046
3572
  const label = automationTfLabel;
@@ -3118,18 +3644,22 @@ export function automationToTf(entity, ctx) {
3118
3644
  ? [[field.name, { fieldType: field.type, multiple: false }]]
3119
3645
  : []))
3120
3646
  : undefined;
3647
+ const recordTarget = FOUND_RECORD_TASK_TYPES.has(resourceType)
3648
+ ? token(taskBody.aspectId ?? taskBody.relatedAspectId)
3649
+ : undefined;
3121
3650
  taskRefs.set(refKey, {
3122
3651
  type: resourceType,
3123
3652
  label: registeredLabel,
3124
3653
  ...(wireType === "unimplementedTask" ? { isData: true } : {}),
3125
3654
  ...(outputFieldTypes !== undefined && outputFieldTypes.size > 0 ? { outputFieldTypes } : {}),
3655
+ ...(recordTarget !== undefined ? { recordTarget } : {}),
3126
3656
  });
3127
3657
  if (wireType === "variable" && Array.isArray(taskBody.create)) {
3128
- for (const candidate of taskBody.create) {
3658
+ taskBody.create.forEach((candidate, index) => {
3129
3659
  if (isObject(candidate) && typeof candidate.id === "string" && typeof candidate.name === "string") {
3130
- variableById.set(candidate.id, { type: "elementum_variable_task", label: registeredLabel, name: candidate.name });
3660
+ variableById.set(candidate.id, { type: "elementum_variable_task", label: registeredLabel, name: candidate.name, index });
3131
3661
  }
3132
- }
3662
+ });
3133
3663
  }
3134
3664
  for (const child of task.children ?? [])
3135
3665
  preRegister(child.tasks ?? []);
@@ -3325,26 +3855,24 @@ export function automationToTf(entity, ctx) {
3325
3855
  }
3326
3856
  if (wireType === "variable") {
3327
3857
  const variableType = variableTaskResourceType(inner, refKey);
3328
- const isCreate = variableType === "elementum_variable_task";
3329
3858
  const creates = Array.isArray(inner.create) ? inner.create : [];
3330
3859
  const updates = Array.isArray(inner.update) ? inner.update : [];
3331
- const item = (isCreate ? creates[0] : updates[0]);
3332
- if (!isObject(item))
3333
- throw new EntityTfError(`invalid setVariable item on "${refKey}"`);
3334
3860
  const variableAttrs = { parent: taskParent, name: displayName };
3335
- if (isCreate) {
3336
- if (typeof item.name !== "string" || typeof item.type !== "string")
3337
- throw new EntityTfError(`variable task "${refKey}" requires name and type`);
3338
- variableAttrs.variable_name = item.name;
3339
- variableAttrs.variable_type = item.type;
3340
- if (item.value !== undefined)
3341
- variableAttrs.value = valueToTf(item.value, refs);
3861
+ if (creates.length > 0) {
3862
+ variableAttrs.variables = creates.map((item) => {
3863
+ if (!isObject(item) || typeof item.name !== "string" || typeof item.type !== "string") {
3864
+ throw new EntityTfError(`variable task "${refKey}" requires name and type on every variable`);
3865
+ }
3866
+ return { name: item.name, type: item.type, ...(item.value !== undefined ? { value: valueToTf(item.value, refs) } : {}) };
3867
+ });
3342
3868
  }
3343
- else {
3344
- // elementum_update_variable_task's real attribute is
3345
- // variable_reference (see from-tf.ts's matching comment).
3346
- variableAttrs.variable_reference = valueToTf(item.variable, refs);
3347
- variableAttrs.value = valueToTf(item.value, refs);
3869
+ if (updates.length > 0) {
3870
+ // The provider's attribute is variable_reference; the authoring key stays "variable".
3871
+ variableAttrs.updates = updates.map((item) => {
3872
+ if (!isObject(item))
3873
+ throw new EntityTfError(`invalid setVariable item on "${refKey}"`);
3874
+ return { variable_reference: valueToTf(item.variable, refs), value: valueToTf(item.value, refs) };
3875
+ });
3348
3876
  }
3349
3877
  blocks.push({ kind: "resource", type: variableType, label: tfLabel, attrs: variableAttrs });
3350
3878
  const address = expr.resourceAttr(variableType, tfLabel);
@@ -3552,3 +4080,19 @@ function requiredSecretVariableBlock(name) {
3552
4080
  },
3553
4081
  };
3554
4082
  }
4083
+ /** A serialized secret("KEY") vault-entry reference, optionally wrapped as { value: X }. */
4084
+ function isVaultSecretRaw(value) {
4085
+ if (!isObject(value))
4086
+ return false;
4087
+ if ("value" in value && Object.keys(value).length === 1)
4088
+ return isVaultSecretRaw(value.value);
4089
+ return isObject(value.secretReference) && typeof value.secretReference.secretId === "string";
4090
+ }
4091
+ function isRequiredSecretRaw(value) {
4092
+ if (!isObject(value))
4093
+ return false;
4094
+ // serializeValueOrRef wraps a plain value as { value: X } (unwrapped by valueToTf).
4095
+ if ("value" in value && Object.keys(value).length === 1)
4096
+ return isRequiredSecretRaw(value.value);
4097
+ return value.kind === "requiredSecret" && typeof value.variable === "string";
4098
+ }