@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,13 +1,19 @@
1
1
  import { USER_FIELD_KEYS } from "../../catalog/types.js";
2
2
  import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEYS } from "../../core/system-fields.js";
3
3
  import { EntityTfError } from "../../engine/entity.js";
4
- import { bareChildResourceLabel, childPartFromScopedLabel, isTfExpr, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, } from "../../engine/tf/index.js";
4
+ import { procedureDiscriminator } from "../../engine/pull/procedure-refs.js";
5
+ import { childPartFromScopedLabel, isTfExpr, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
6
+ import { SUB_TYPE_BY_RESOURCE } from "../field/types.js";
5
7
  import { IMPLEMENTED_FILE_READER_RESOURCE_TYPES } from "../file-reader/types.js";
6
8
  import { connectorIdentityFromTf } from "../shared/connector-from-tf.js";
9
+ import { fieldTypeToValueType } from "../shared/filters/index.js";
7
10
  import { UNRESOLVED_FIELD_MARKER } from "../shared/ref.js";
8
11
  import { filterFromTf as deserializeFilterFromTf } from "../shared/filters/tf-codec.js";
9
12
  import { TABLE_RESOURCE_TYPE } from "../table/module.js";
10
- import { OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
13
+ import { SEARCH_TABLE_RESOURCE_TYPES } from "../search-table/types.js";
14
+ import { outputFieldTypesFromScriptSchema } from "./output-field-types.js";
15
+ import { apiTaskRefAuthoringPath, OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
16
+ import { taskTfLabel } from "./task-label.js";
11
17
  import { ALL_AUTOMATION_TASK_TYPE_SET, AUTOMATION_BRANCH_TYPE_SET, AUTOMATION_RESOURCE_TYPE, AUTOMATION_TRIGGER_TYPE_SET, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
12
18
  const TRIGGER_KINDS = {
13
19
  elementum_record_created_trigger: "recordCreate",
@@ -57,6 +63,11 @@ const TASK_FACTORIES = {
57
63
  elementum_run_automation_task: "runAutomation",
58
64
  elementum_aspect_record_field_locking_task: "recordFieldLocking",
59
65
  elementum_ai_file_read_task: "aiFileAnalysis",
66
+ // Not a real task resource - a read-only reference to a platform task type
67
+ // EDK doesn't implement (edk#785/edk#821). Synthesized into the same tree
68
+ // walk as a real task (see buildTasks) so its downstream chain lands in its
69
+ // real position instead of being silently hoisted to the automation's top level.
70
+ elementum_unmanaged_task_reference: "unimplementedTask",
60
71
  };
61
72
  const ATTR_TO_ARG = {
62
73
  object_id: "app",
@@ -88,8 +99,6 @@ const ATTR_TO_ARG = {
88
99
  category_source: "categorySource",
89
100
  user_ids: "userIds",
90
101
  group_ids: "groupIds",
91
- user_value_references: "userRefs",
92
- group_value_references: "groupRefs",
93
102
  notify_watchers: "notifyWatchers",
94
103
  fields_to_lock: "fieldsToLock",
95
104
  fields_to_unlock: "fieldsToUnlock",
@@ -142,6 +151,76 @@ function references(value, type, label) {
142
151
  const ref = resourceRef(value);
143
152
  return ref?.type === type && ref.label === label;
144
153
  }
154
+ /**
155
+ * edk#785: a task's `parent` can be a `data.elementum_unmanaged_task_reference.*`
156
+ * reference instead of a resource reference, when its real predecessor is a
157
+ * task type EDK doesn't support at all (no HCL block ever emitted for it).
158
+ * The data source is read-only and inherently "resolved" (its id/workflow_id/
159
+ * etc. are always concrete inputs, never dependent on anything else in the
160
+ * graph), so a task pointing at one is never itself unowned/orphaned - it
161
+ * just has no real branch/case address to anchor its authored position under.
162
+ */
163
+ function unmanagedTaskRef(value) {
164
+ return isTfExpr(value) && value.$expr === "data-attr" && value.type === "elementum_unmanaged_task_reference"
165
+ ? { label: value.label }
166
+ : undefined;
167
+ }
168
+ /**
169
+ * Order switch_case / fork_join_branch blocks by their previous_*_id chain.
170
+ * Falls back to depends_on index / label only when the chain is incomplete.
171
+ * Alphabetical label order inverts real evaluation order whenever a later
172
+ * case's display name sorts before the first (Sanofi: "…Invalid" before
173
+ * "…Valid"), which rebuilds previous_case_id edges backwards and plans
174
+ * in-place updates on every case.
175
+ */
176
+ function orderBranchesByPreviousLink(matching, previousAttr, dependencyOrder) {
177
+ if (matching.length <= 1)
178
+ return matching;
179
+ const byAddress = new Map(matching.map((branch) => [`${branch.type}.${branch.label}`, branch]));
180
+ const successor = new Map();
181
+ const roots = [];
182
+ for (const branch of matching) {
183
+ const prev = resourceRef(branch.attrs[previousAttr]);
184
+ if (prev === undefined) {
185
+ roots.push(branch);
186
+ continue;
187
+ }
188
+ const prevAddress = `${prev.type}.${prev.label}`;
189
+ if (!byAddress.has(prevAddress)) {
190
+ roots.push(branch);
191
+ continue;
192
+ }
193
+ if (successor.has(prevAddress)) {
194
+ // Ambiguous chain — fall back to legacy sort for the whole set.
195
+ return [...matching].sort((a, b) => (dependencyOrder.get(`${a.type}.${a.label}`) ?? Number.MAX_SAFE_INTEGER)
196
+ - (dependencyOrder.get(`${b.type}.${b.label}`) ?? Number.MAX_SAFE_INTEGER)
197
+ || a.label.localeCompare(b.label));
198
+ }
199
+ successor.set(prevAddress, branch);
200
+ }
201
+ if (roots.length !== 1) {
202
+ return [...matching].sort((a, b) => (dependencyOrder.get(`${a.type}.${a.label}`) ?? Number.MAX_SAFE_INTEGER)
203
+ - (dependencyOrder.get(`${b.type}.${b.label}`) ?? Number.MAX_SAFE_INTEGER)
204
+ || a.label.localeCompare(b.label));
205
+ }
206
+ const ordered = [];
207
+ let cursor = roots[0];
208
+ const seen = new Set();
209
+ while (cursor !== undefined) {
210
+ const address = `${cursor.type}.${cursor.label}`;
211
+ if (seen.has(address))
212
+ break;
213
+ seen.add(address);
214
+ ordered.push(cursor);
215
+ cursor = successor.get(address);
216
+ }
217
+ if (ordered.length !== matching.length) {
218
+ return [...matching].sort((a, b) => (dependencyOrder.get(`${a.type}.${a.label}`) ?? Number.MAX_SAFE_INTEGER)
219
+ - (dependencyOrder.get(`${b.type}.${b.label}`) ?? Number.MAX_SAFE_INTEGER)
220
+ || a.label.localeCompare(b.label));
221
+ }
222
+ return ordered;
223
+ }
145
224
  function assertAllowed(block, allowed) {
146
225
  for (const key of Object.keys(block.attrs)) {
147
226
  if (!allowed.has(key))
@@ -156,15 +235,16 @@ const TRIGGER_ATTRIBUTES = new Set([
156
235
  ]);
157
236
  const TASK_ATTRIBUTES = new Set([
158
237
  "parent", "name", "depends_on", "filter", "fields", "inputs", "output_schema",
159
- "list", "code", "variable_name", "variable_type", "variable", "value",
238
+ "list", "code", "variable_name", "variable_type", "variable_id", "variable", "value",
160
239
  "object_id", "table_id", "record_reference", "record_id", "source_record_ids",
240
+ "approval_process_id", "requester_reference", "approver_references", "reason", "summary",
241
+ "approval_reference", "status",
161
242
  "target_record_id", "message", "message_body", "body", "from_username",
162
243
  "from_personal", "external_emails", "users", "groups", "attachments", "contents",
163
244
  "agent_id", "prompt", "output_type", "json_fields", "ai_provider_connector_id",
164
245
  "url", "response_type", "continue_on_error", "search_table_id",
165
246
  "text_to_summarize", "text_to_classify", "field_type", "category_source",
166
- "title", "user_ids", "group_ids", "user_value_references",
167
- "group_value_references", "notify_watchers", "field_id", "user_id", "group_id",
247
+ "title", "user_ids", "group_ids", "notify_watchers", "field_id", "user_id", "group_id",
168
248
  "fields_to_lock", "fields_to_unlock", "file", "file_id", "attachment", "attachment_id", "view_state", "target_automation_id",
169
249
  "target_automation_ref", "input_mappings", "dynamic_input_mappings",
170
250
  "output_mappings", "file_reader_id", "raw_text", "procedure_id",
@@ -190,7 +270,7 @@ function appRef(appRefName) {
190
270
  // be added here. A hardcoded flat entry here short-circuits triggerRefPath's
191
271
  // field-name+suffix matching below (pathNames runs first), producing an
192
272
  // invalid, un-typed property name instead of the real ["record", field.key,
193
- // "email"] path - confirmed live: "Created by Email"/"Updated by Manager
273
+ // "email"] path - confirmed live: "Created By Email"/"Updated By Manager
194
274
  // Email" were hardcoded this way and printed as ctx.trigger.createdByEmail /
195
275
  // ctx.trigger.updatedByManagerEmail, neither of which exists on the typed
196
276
  // ctx, so every pulled automation using them failed `tsc --noEmit`.
@@ -211,6 +291,9 @@ const FIELD_REF_SUFFIX_FROM_WIRE = [
211
291
  [" Manager Name", ["employee", "manager", "name"]],
212
292
  [" Manager", ["employee", "manager"]],
213
293
  [" Field ID", ["fieldId"]],
294
+ // Dynamically sourced Dropdown selected source record. Confirmed
295
+ // live as "<Field> - Record" with type ASPECT_RECORD_ID.
296
+ [" - Record", ["recordId"]],
214
297
  // Deliberately the literal suffix text, not a camelCase "asText" segment:
215
298
  // Ref<T> has no ".asText" projection anywhere in the type system (checked
216
299
  // shared/ref.ts - it's a sealed brand, nothing else), so claiming one as a
@@ -238,16 +321,17 @@ function pathNames(path) {
238
321
  * create-record task outputs; both use the same display-name + suffix wire
239
322
  * convention.
240
323
  */
241
- function recordFieldRefPath(wireName, ctx) {
242
- // Case-insensitive: the platform re-cases "By" to "by" when building some
243
- // compound ref phrases (e.g. field "Created By" -> ref key "Created by
244
- // Email").
324
+ function recordFieldRefPath(wireName, ctx, ownerRefName = ctx.appRefName, rootName = "record") {
325
+ // Case-insensitive so exports remain readable across historical platform
326
+ // casing while authored HCL targets the current exact live ref keys.
245
327
  const wireNameLower = wireName.toLowerCase();
246
- for (const field of ctx.fieldById.values()) {
247
- for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
248
- if (wireNameLower === `${field.name}${suffix}`.toLowerCase()) {
249
- return ["record", field.key, ...suffixPath];
250
- }
328
+ for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
329
+ if (!wireNameLower.endsWith(suffix.toLowerCase()))
330
+ continue;
331
+ const base = wireName.slice(0, wireName.length - suffix.length);
332
+ const fieldKey = lookupFieldKeyByDisplayName(ownerRefName, base, ctx);
333
+ if (fieldKey !== undefined) {
334
+ return [rootName, fieldKey, ...suffixPath];
251
335
  }
252
336
  }
253
337
  // System fields have no `*_field` resource block, so they never appear in
@@ -256,7 +340,7 @@ function recordFieldRefPath(wireName, ctx) {
256
340
  const defaultName = DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[key];
257
341
  for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
258
342
  if (wireNameLower === `${defaultName}${suffix}`.toLowerCase()) {
259
- return ["record", key, ...suffixPath];
343
+ return [rootName, key, ...suffixPath];
260
344
  }
261
345
  }
262
346
  }
@@ -279,6 +363,31 @@ function isDeclaredOnDemandParameter(trigger, wireName) {
279
363
  const parameters = trigger.attrs.parameters;
280
364
  return Array.isArray(parameters) && parameters.some((parameter) => isObject(parameter) && parameter.name === wireName);
281
365
  }
366
+ function onDemandRecordParameters(trigger) {
367
+ if (trigger.type !== "elementum_on_demand_trigger" || !Array.isArray(trigger.attrs.parameters))
368
+ return [];
369
+ return trigger.attrs.parameters.filter((parameter) => isObject(parameter) && parameter.type === "record" && typeof parameter.name === "string");
370
+ }
371
+ function prefixedOnDemandRecordRefPath(wireName, ctx) {
372
+ const recordParams = onDemandRecordParameters(ctx.trigger);
373
+ if (recordParams.length < 2)
374
+ return undefined;
375
+ const sortedParams = [...recordParams].sort((a, b) => String(b.name).length - String(a.name).length);
376
+ for (const parameter of sortedParams) {
377
+ const name = parameter.name;
378
+ const prefix = `${name} - `;
379
+ if (!wireName.startsWith(prefix))
380
+ continue;
381
+ const displayName = wireName.slice(prefix.length);
382
+ if (displayName === "Record")
383
+ return [name];
384
+ const ownerRefName = aspectOwnerRefNameFromObjectId(parameter.default_value, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames);
385
+ return ownerRefName === undefined
386
+ ? undefined
387
+ : recordFieldRefPath(displayName, ctx, ownerRefName, name);
388
+ }
389
+ return undefined;
390
+ }
282
391
  // recordSearch's own output ref names ("Records Size" -> totalCount, "All
283
392
  // found records" -> records) — deliberately NOT in WIRE_REF_SEGMENT_TO_TS,
284
393
  // which triggerRefPath also consults: a record-created/updated trigger's ref
@@ -291,6 +400,7 @@ function isDeclaredOnDemandParameter(trigger, wireName) {
291
400
  const RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS = {
292
401
  "Records Size": "totalCount",
293
402
  "All found records": "records",
403
+ Record: "record",
294
404
  };
295
405
  // aiSearchTable's own output ref name — same scoping reason as
296
406
  // RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS: "All Records" is a platform-fixed
@@ -299,6 +409,34 @@ const RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS = {
299
409
  const AI_SEARCH_TABLE_TASK_REF_SEGMENT_TO_TS = {
300
410
  "All Records": "records",
301
411
  };
412
+ // tableRecordsSearch collection output — platform wire key
413
+ // "All matching table rows" (not recordSearch's "All found records" or
414
+ // aiSearchTable's "All Records"). Leaving it unmapped prints
415
+ // `(ctx.actions.x as any)["All matching table rows"]`, which drops the Ref
416
+ // proxy at build time and omits the script/filter input entirely.
417
+ const TABLE_RECORDS_SEARCH_TASK_REF_SEGMENT_TO_TS = {
418
+ "All matching table rows": "records",
419
+ };
420
+ /**
421
+ * Restore the public aiAgent `.result` shape from either a provider refs-map
422
+ * key (`Action Response` / authored schema field) or the nested platform
423
+ * taskReference.name carried by workflow publish envelopes.
424
+ */
425
+ function aiAgentTaskRefPath(block, name) {
426
+ if (block.type !== "elementum_ai_agent_task")
427
+ return undefined;
428
+ if (name === "Action Response" || name === "ai_agent_task_response")
429
+ return ["result"];
430
+ const nestedPrefix = "ai_agent_task_structured_output.";
431
+ const candidate = name.startsWith(nestedPrefix) ? name.slice(nestedPrefix.length) : name;
432
+ const jsonFields = block.attrs.json_fields;
433
+ if (!Array.isArray(jsonFields))
434
+ return undefined;
435
+ const schemaName = jsonFields
436
+ .flatMap((field) => isObject(field) && typeof field.name === "string" ? [field.name] : [])
437
+ .find((fieldName) => (fieldName === candidate || fieldName.toLowerCase() === candidate.toLowerCase()));
438
+ return schemaName === undefined ? undefined : ["result", schemaName];
439
+ }
302
440
  /**
303
441
  * A webhook trigger's `body`/`headers` refs come back as "Body (Plain
304
442
  * Text)"/"Headers (Content-Type)" - one wire segment naming both the
@@ -313,20 +451,64 @@ const AI_SEARCH_TABLE_TASK_REF_SEGMENT_TO_TS = {
313
451
  * convention.
314
452
  */
315
453
  const WEBHOOK_REF_PATTERN = /^(Body|Headers) \((.+)\)$/;
316
- function aspectOwnerRefNameFromObjectId(objectId, appRefName, appTfLabel) {
454
+ function aspectOwnerRefNameFromObjectId(objectId, appRefName, appTfLabel, dataBlocks, foreignAppRefNames, foreignElementRefNames) {
317
455
  if (!isTfExpr(objectId))
318
456
  return undefined;
319
457
  if (objectId.$expr === "data-attr" && (objectId.type === "elementum_app" || objectId.type === "elementum_element") && objectId.path[0] === "id") {
320
- return tfLabelToTsLabel(objectId.label);
321
- }
322
- if (objectId.$expr === "resource-attr" && objectId.type === "elementum_app" && objectId.label === appTfLabel && objectId.path[0] === "id") {
323
- return appRefName;
458
+ // The data block's own tf label is an arbitrary export alias, not
459
+ // necessarily the target's real refName (confirmed live: a
460
+ // `data.elementum_element "approvals_log"` block's real namespace is
461
+ // "approvals") - resolve through its name/namespace, same as decodeValue's
462
+ // generic app/element data-attr case, falling back to the label only when
463
+ // the target hasn't itself been pulled yet.
464
+ const lookup = dataBlocks.get(`${objectId.type}.${objectId.label}`);
465
+ const identity = lookup?.attrs.name ?? lookup?.attrs.namespace;
466
+ const mapped = typeof identity === "string"
467
+ ? (objectId.type === "elementum_element" ? foreignElementRefNames : foreignAppRefNames)?.get(identity)
468
+ : undefined;
469
+ return mapped ?? tfLabelToTsLabel(objectId.label);
324
470
  }
325
- if (objectId.$expr === "resource-attr" && objectId.type === "elementum_element" && objectId.path[0] === "id") {
326
- return tfLabelToTsLabel(objectId.label);
471
+ if (objectId.$expr === "resource-attr" &&
472
+ (objectId.type === "elementum_app" || objectId.type === "elementum_element") &&
473
+ objectId.path[0] === "id") {
474
+ return objectId.type === "elementum_app" && objectId.label === appTfLabel
475
+ ? appRefName
476
+ : tfLabelToTsLabel(objectId.label);
327
477
  }
328
478
  return undefined;
329
479
  }
480
+ function aspectRefFromObjectId(objectId, ctx) {
481
+ if (!isTfExpr(objectId))
482
+ return undefined;
483
+ if (objectId.$expr === "resource-attr" &&
484
+ (objectId.type === "elementum_app" || objectId.type === "elementum_element") &&
485
+ objectId.path[0] === "id") {
486
+ return {
487
+ kind: "app",
488
+ appHandle: objectId.label === ctx.appTfLabel ? ctx.appRefName : tfLabelToTsLabel(objectId.label),
489
+ };
490
+ }
491
+ if (objectId.$expr !== "data-attr" ||
492
+ (objectId.type !== "elementum_app" && objectId.type !== "elementum_element") ||
493
+ objectId.path[0] !== "id") {
494
+ return undefined;
495
+ }
496
+ const lookup = ctx.dataBlocks.get(`${objectId.type}.${objectId.label}`);
497
+ const identity = lookup?.attrs.name ?? lookup?.attrs.namespace;
498
+ const mapped = typeof identity === "string"
499
+ ? (objectId.type === "elementum_element" ? ctx.foreignElementRefNames : ctx.foreignAppRefNames)?.get(identity)
500
+ : undefined;
501
+ if (mapped !== undefined)
502
+ return { kind: "app", appHandle: mapped };
503
+ if (typeof identity !== "string" || identity === "")
504
+ return undefined;
505
+ return {
506
+ kind: "app",
507
+ appHandle: tfLabelToTsLabel(objectId.label),
508
+ entityType: objectId.type === "elementum_element" ? "element" : "app",
509
+ name: identity,
510
+ };
511
+ }
330
512
  function lookupFieldKeyByDisplayName(ownerRefName, displayName, ctx) {
331
513
  const lower = displayName.toLowerCase();
332
514
  const foreign = ctx.fieldNamesByOwnerRefName?.get(ownerRefName)?.get(lower);
@@ -359,7 +541,116 @@ function taskRecordSearchFieldPath(taskAddress, wireName, ctx) {
359
541
  }
360
542
  return undefined;
361
543
  }
544
+ /**
545
+ * Sentinel returned by {@link approverReferenceFieldAuthoringType} for a
546
+ * field-shaped reference (matches one of the FIELD_REF_SUFFIX_FROM_WIRE
547
+ * display-name suffixes) into a FOREIGN aspect whose fields have never been
548
+ * captured locally AT ALL — not merely "this one field is unknown", but
549
+ * "this aspect has never been pulled, so nothing about its fields can be
550
+ * verified". Distinct from a real authoring-type string so callers can give
551
+ * a different diagnostic (pull the foreign aspect first) than the
552
+ * positively-wrong-type case (edk#655) below. See edk#768.
553
+ */
554
+ const UNVERIFIABLE_FOREIGN_FIELD_TYPE = "__edkUnverifiableForeignFieldType";
555
+ /**
556
+ * If `value` is a `refs["<Field> ID"]`-style reference into a field's
557
+ * output, return that field's public authoring type (e.g. "USER", "GROUP")
558
+ * so callers requiring a USER field (approvalChain's requester/approver
559
+ * references) can catch a live automation already wired to the wrong field
560
+ * type before it reaches the provider's own plan-time rejection (edk#655).
561
+ * Covers both a LOCAL field (this app's own `fieldById`) and a FOREIGN one
562
+ * (a non-recursive export never carries the foreign aspect's field
563
+ * resources, so this falls back to the cross-pull field-refs registry,
564
+ * populated once that aspect has itself been pulled at least once — see
565
+ * field-refs-registry.ts's `fieldType`).
566
+ *
567
+ * When the reference targets a FOREIGN aspect that has never been pulled at
568
+ * all, its field types are entirely unknown to the registry — genuinely
569
+ * unverifiable, not "not a field". Returns
570
+ * {@link UNVERIFIABLE_FOREIGN_FIELD_TYPE} in that case rather than silently
571
+ * treating it as safe: confirmed live (eu/sanofi purchaserequisition, edk#768)
572
+ * that letting an unverifiable foreign reference through crashes the WHOLE
573
+ * app's adoption at `ei plan` the same way a known-bad type does. A LOCAL
574
+ * non-match is never ambiguous this way — the app being pulled always
575
+ * carries its own fields exhaustively in this same export — so this fallback
576
+ * only applies to foreign owners.
577
+ */
578
+ function approverReferenceFieldAuthoringType(value, ctx) {
579
+ if (!isTfExpr(value) || value.$expr !== "resource-attr" || value.path[0] !== "refs")
580
+ return undefined;
581
+ const taskAddress = `${value.type}.${value.label}`;
582
+ const ownerRefName = ctx.taskTargetOwnerRefNameByAddress?.get(taskAddress);
583
+ if (ownerRefName === undefined)
584
+ return undefined;
585
+ const rawSegments = pathNames(value.path.slice(1));
586
+ if (rawSegments.length !== 1)
587
+ return undefined;
588
+ const wireName = rawSegments[0];
589
+ const wireNameLower = wireName.toLowerCase();
590
+ const typeForFieldKey = (fieldKey) => {
591
+ if (ownerRefName === ctx.appRefName) {
592
+ for (const field of ctx.fieldById.values()) {
593
+ if (field.key === fieldKey)
594
+ return SUB_TYPE_BY_RESOURCE.get(field.resourceType)?.authoringType;
595
+ }
596
+ }
597
+ for (const foreign of ctx.foreignFieldRefsById?.values() ?? []) {
598
+ if (foreign.ownerRefName === ownerRefName && foreign.fieldKey === fieldKey && foreign.fieldType !== undefined) {
599
+ return foreign.fieldType;
600
+ }
601
+ }
602
+ return undefined;
603
+ };
604
+ // An EXACT field display name always wins over a suffix-stripped guess: a
605
+ // field literally named "Approver ID" must never be shadowed by treating
606
+ // the wire name as the " ID" projection of a DIFFERENT field named
607
+ // "Approver" (edk#768 PR review — this exact collision let a TEXT-typed
608
+ // field through undetected because the wrong guess resolved to the base
609
+ // field's USER type). Once the wire name matches a real field's own name,
610
+ // that field's identity is settled: fall through only to the
611
+ // "unverifiable" check below if ITS type can't be resolved — never guess
612
+ // via a different field's suffix projection instead.
613
+ const exactFieldKey = lookupFieldKeyByDisplayName(ownerRefName, wireName, ctx);
614
+ if (exactFieldKey !== undefined) {
615
+ const type = typeForFieldKey(exactFieldKey);
616
+ if (type !== undefined)
617
+ return type;
618
+ return ownerRefName !== ctx.appRefName &&
619
+ ![...ctx.foreignFieldRefsById?.values() ?? []].some((foreign) => foreign.ownerRefName === ownerRefName)
620
+ ? UNVERIFIABLE_FOREIGN_FIELD_TYPE
621
+ : undefined;
622
+ }
623
+ let fieldShaped = false;
624
+ for (const [suffix] of FIELD_REF_SUFFIX_FROM_WIRE) {
625
+ if (suffix === "" || !wireNameLower.endsWith(suffix.toLowerCase()))
626
+ continue;
627
+ fieldShaped = true;
628
+ const base = wireName.slice(0, -suffix.length);
629
+ const fieldKey = lookupFieldKeyByDisplayName(ownerRefName, base, ctx);
630
+ if (fieldKey === undefined)
631
+ continue;
632
+ const type = typeForFieldKey(fieldKey);
633
+ if (type !== undefined)
634
+ return type;
635
+ }
636
+ if (fieldShaped &&
637
+ ownerRefName !== ctx.appRefName &&
638
+ ![...ctx.foreignFieldRefsById?.values() ?? []].some((foreign) => foreign.ownerRefName === ownerRefName)) {
639
+ return UNVERIFIABLE_FOREIGN_FIELD_TYPE;
640
+ }
641
+ return undefined;
642
+ }
362
643
  function decodeFieldAssignmentValue(value, ctx) {
644
+ // Multi-Select assignments are exported as jsonencode([<option UUID>, ...])
645
+ // rather than the options-by-label locals used for a scalar Dropdown. Walk
646
+ // that payload with the state-derived option registry so pulled source stays
647
+ // portable across organizations and fresh creates.
648
+ if (isTfExpr(value) && value.$expr === "jsonencode") {
649
+ return decodeFieldAssignmentValue(value.value, ctx);
650
+ }
651
+ if (Array.isArray(value)) {
652
+ return value.map((item) => decodeFieldAssignmentValue(item, ctx));
653
+ }
363
654
  if (typeof value === "string" && /^[a-f0-9-]{36}$/i.test(value)) {
364
655
  const label = ctx.picklistOptionLabelById?.get(value);
365
656
  if (label !== undefined)
@@ -398,6 +689,9 @@ function triggerRefPath(path, ctx) {
398
689
  return ["triggeredBy", "name"];
399
690
  if (wireName === "Triggered By's Email")
400
691
  return ["triggeredBy", "email"];
692
+ const recordPath = prefixedOnDemandRecordRefPath(wireName, ctx);
693
+ if (recordPath !== undefined)
694
+ return recordPath;
401
695
  }
402
696
  // An on-demand parameter is an explicitly declared top-level ctx.trigger
403
697
  // property. Check this before record-field inference: a perfectly ordinary
@@ -414,8 +708,20 @@ function triggerRefPath(path, ctx) {
414
708
  // it globally intercepted that task-level case before it could ever be
415
709
  // checked (decodeValue's own dedicated "Record" handling for those task
416
710
  // types).
417
- if (wireName === "Record")
418
- return ["record"];
711
+ if (wireName === "Record") {
712
+ const recordParams = onDemandRecordParameters(ctx.trigger);
713
+ return recordParams.length === 1
714
+ ? [recordParams[0].name]
715
+ : ["record"];
716
+ }
717
+ const singleRecordParam = onDemandRecordParameters(ctx.trigger);
718
+ if (singleRecordParam.length === 1) {
719
+ const parameter = singleRecordParam[0];
720
+ const ownerRefName = aspectOwnerRefNameFromObjectId(parameter.default_value, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames);
721
+ if (ownerRefName !== undefined) {
722
+ return recordFieldRefPath(wireName, ctx, ownerRefName, parameter.name) ?? names;
723
+ }
724
+ }
419
725
  if (!RECORD_BEARING_TRIGGER_TYPES.has(ctx.trigger.type ?? ""))
420
726
  return names;
421
727
  return recordFieldRefPath(wireName, ctx) ?? names;
@@ -436,6 +742,11 @@ function forEachItemRefPath(path, ctx) {
436
742
  return ["recordId"];
437
743
  const wireNameLower = wireName.toLowerCase();
438
744
  for (const field of ctx.fieldById.values()) {
745
+ // Some provider paths already contain the stable EDK field key (for
746
+ // example `for_each.<task-id>.productId`), while inner.refs uses the
747
+ // display name in other workflow shapes. Accept both forms.
748
+ if (wireName === field.key)
749
+ return [field.key];
439
750
  for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
440
751
  if (wireNameLower === `${field.name}${suffix}`.toLowerCase()) {
441
752
  return [field.key, ...suffixPath];
@@ -466,8 +777,25 @@ function resolveTaskRefKey(taskIdOrKey, ctx) {
466
777
  }
467
778
  return { refKey: taskIdOrKey };
468
779
  }
780
+ function resolveFieldKeyFromId(fieldId, ownerRefName, ctx) {
781
+ const local = ctx.fieldById.get(fieldId);
782
+ if (local !== undefined) {
783
+ if (ownerRefName === undefined || ownerRefName === ctx.appRefName)
784
+ return local.key;
785
+ }
786
+ const state = ctx.foreignFieldRefsById?.get(fieldId);
787
+ if (state === undefined)
788
+ return undefined;
789
+ const expectedOwner = ownerRefName ?? ctx.appRefName;
790
+ return state.ownerRefName === expectedOwner ? state.fieldKey : undefined;
791
+ }
469
792
  function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
470
793
  const { refKey, block } = resolveTaskRefKey(taskIdOrKey, ctx);
794
+ if (block !== undefined) {
795
+ const aiAgentPath = aiAgentTaskRefPath(block, pathSegments.join("."));
796
+ if (aiAgentPath !== undefined)
797
+ return { kind: "taskRef", task: refKey, path: aiAgentPath };
798
+ }
471
799
  if (block?.type === "elementum_record_search_task" && pathSegments.length >= 1) {
472
800
  const [head, ...tail] = pathSegments;
473
801
  if (head === "count") {
@@ -478,6 +806,22 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
478
806
  return { kind: "taskRef", task: refKey, path: [recordSearchName, ...tail] };
479
807
  }
480
808
  const taskAddress = block.label !== undefined ? `${block.type}.${block.label}` : undefined;
809
+ // Live filters often address a found-record field as
810
+ // `record.<field-uuid>[.suffix]` (Sanofi: Status Label → record.<status-id>.label).
811
+ // System fields have no `*_field` import; resolve the UUID through state the
812
+ // same way trigger `record.<uuid>` already does (#432).
813
+ if (taskAddress !== undefined &&
814
+ head === "record" &&
815
+ tail.length >= 1 &&
816
+ /^[a-f0-9-]{36}$/i.test(tail[0])) {
817
+ const ownerRefName = ctx.taskTargetOwnerRefNameByAddress?.get(taskAddress) ?? ctx.appRefName;
818
+ const fieldKey = resolveFieldKeyFromId(tail[0], ownerRefName, ctx);
819
+ return {
820
+ kind: "taskRef",
821
+ task: refKey,
822
+ path: ["record", fieldKey ?? tail[0], ...tail.slice(1)],
823
+ };
824
+ }
481
825
  if (taskAddress !== undefined) {
482
826
  const recordFieldPath = taskRecordSearchFieldPath(taskAddress, head, ctx);
483
827
  if (recordFieldPath !== undefined) {
@@ -492,6 +836,49 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
492
836
  return { kind: "taskRef", task: refKey, path: [aiSearchName, ...tail] };
493
837
  }
494
838
  }
839
+ if (block?.type === "elementum_table_records_search_task" && pathSegments.length >= 1) {
840
+ const [head, ...tail] = pathSegments;
841
+ const tableSearchName = TABLE_RECORDS_SEARCH_TASK_REF_SEGMENT_TO_TS[head];
842
+ if (tableSearchName !== undefined) {
843
+ return { kind: "taskRef", task: refKey, path: [tableSearchName, ...tail] };
844
+ }
845
+ }
846
+ // createRecord/findRelatedRecords record-id + field outputs (same as the
847
+ // refs["Title"] / refs["Record"] resource-attr path in decodeValue).
848
+ if ((block?.type === "elementum_create_record_task" || block?.type === "elementum_find_related_records_task") &&
849
+ pathSegments.length >= 1) {
850
+ const [head, ...tail] = pathSegments;
851
+ if (pathSegments.length === 1 && (head === "Record" || head === "Record ID")) {
852
+ return { kind: "taskRef", task: refKey, path: ["record", "recordId"] };
853
+ }
854
+ if (block.type === "elementum_create_record_task" &&
855
+ head === "record" &&
856
+ tail.length >= 1 &&
857
+ /^[a-f0-9-]{36}$/i.test(tail[0])) {
858
+ const taskAddress = block.label !== undefined ? `${block.type}.${block.label}` : undefined;
859
+ const ownerRefName = taskAddress !== undefined
860
+ ? ctx.taskTargetOwnerRefNameByAddress?.get(taskAddress) ?? ctx.appRefName
861
+ : ctx.appRefName;
862
+ const fieldKey = resolveFieldKeyFromId(tail[0], ownerRefName, ctx);
863
+ return {
864
+ kind: "taskRef",
865
+ task: refKey,
866
+ path: ["record", fieldKey ?? tail[0], ...tail.slice(1)],
867
+ };
868
+ }
869
+ if (block.type === "elementum_create_record_task" && pathSegments.length === 1) {
870
+ const recordPath = recordFieldRefPath(head, ctx);
871
+ if (recordPath !== undefined) {
872
+ return { kind: "taskRef", task: refKey, path: recordPath };
873
+ }
874
+ }
875
+ }
876
+ if (block?.type === "elementum_api_task" && pathSegments.length === 1) {
877
+ const apiPath = apiTaskRefAuthoringPath(pathSegments[0]);
878
+ if (apiPath !== undefined) {
879
+ return { kind: "taskRef", task: refKey, path: apiPath };
880
+ }
881
+ }
495
882
  const keyPath = pathSegments.map((segment) => WIRE_REF_SEGMENT_TO_TS[segment] ?? segment);
496
883
  const taskKind = block?.type !== undefined ? TASK_FACTORIES[block.type] : undefined;
497
884
  const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
@@ -530,18 +917,26 @@ function decodeReferenceString(value, ctx) {
530
917
  if (pieces[0] === "task" && pieces.length > 2) {
531
918
  return decodeTaskReferenceFromString(pieces[1], pieces.slice(2), ctx);
532
919
  }
533
- // Any other/future value_reference shape - confirmed live: conciergeforfield's
534
- // cff_find_nearby_accounts_if_user_is_impersonating_a_sales_rep switch_case
535
- // references a workflow variable ("variable.<uuid>"); setVariable/variable_task
536
- // authoring is itself deferred (no typed construct exists yet to resolve this
537
- // to - see the automation module's header), so it can never become a real ref
538
- // today, and any future dialect growth hits the same "we don't recognize this
539
- // reference shape" situation. Degrade to the {kind:"unresolved"} placeholder
540
- // (same escape hatch fieldRef already uses for an orphaned field_id) rather
541
- // than throwing and losing the whole automation (#171) - printFilterField
542
- // marks it distinctly from a field placeholder (hint !== "field") so the BUILD
543
- // direction fails loudly instead of silently mis-rebuilding it as a field_id
544
- // (#290; a value_reference position can never round-trip through field_id).
920
+ if (pieces[0] === "for_each" && pieces.length > 2) {
921
+ const { refKey } = resolveTaskRefKey(pieces[1], ctx);
922
+ return {
923
+ kind: "forEachItemRef",
924
+ forEachTask: refKey,
925
+ path: forEachItemRefPath(pieces.slice(2), ctx),
926
+ };
927
+ }
928
+ if (pieces[0] === "variable" && pieces.length > 1) {
929
+ const varPart = pieces.slice(1).join(".");
930
+ const resolved = resolveVariableReference(varPart, varPart, undefined, ctx);
931
+ if (resolved !== undefined)
932
+ return resolved;
933
+ }
934
+ if (value.startsWith("variable|")) {
935
+ const varPart = value.slice("variable|".length);
936
+ const resolved = resolveVariableReference(varPart, varPart, undefined, ctx);
937
+ if (resolved !== undefined)
938
+ return resolved;
939
+ }
545
940
  return { kind: "unresolved", uuid: value, hint: pieces[0] ?? "reference" };
546
941
  }
547
942
  /**
@@ -566,8 +961,34 @@ function decodeTemplateTriggerRecordFieldRef(value, ctx) {
566
961
  if (fieldKey === undefined)
567
962
  return undefined;
568
963
  const suffix = suffixPart === undefined ? [] : suffixPart.replace(/^\./, "").split(".").filter((s) => s.length > 0);
964
+ if (suffix.length === 1 && suffix[0] === "10000001-2000-4000-a000-800000000000") {
965
+ return { kind: "triggerRef", path: ["record", fieldKey, "recordId"] };
966
+ }
569
967
  return { kind: "triggerRef", path: ["record", fieldKey, ...suffix] };
570
968
  }
969
+ /**
970
+ * Inverse of filterReferenceToTf's TASK case: filters render
971
+ * `"task." + <task.id> + ".<wireName>"` templates so provider Read's plain
972
+ * `task.<uuid>.<wireName>` strings round-trip without perpetual plan drift.
973
+ */
974
+ function decodeTemplateTaskRef(value, ctx) {
975
+ if (!isTfExpr(value) || value.$expr !== "template")
976
+ return undefined;
977
+ const [prefix, idPart, suffixPart] = value.parts;
978
+ if (prefix !== "task." || idPart === undefined || typeof idPart === "string")
979
+ return undefined;
980
+ if (typeof suffixPart !== "string" || !suffixPart.startsWith("."))
981
+ return undefined;
982
+ if (!isTfExpr(idPart) || idPart.$expr !== "resource-attr" || idPart.path[0] !== "id")
983
+ return undefined;
984
+ const task = ctx.taskByAddress.get(`${idPart.type}.${idPart.label}`);
985
+ if (task === undefined)
986
+ return undefined;
987
+ const nameParts = suffixPart.slice(1).split(".").filter((segment) => segment.length > 0);
988
+ if (nameParts.length === 0)
989
+ return undefined;
990
+ return decodeTaskReferenceFromString(task.refKey, nameParts, ctx);
991
+ }
571
992
  /**
572
993
  * Resolve the field-id expression at the middle of a `trigger.record.<id>[.suffix]`
573
994
  * template. A custom field's id is a `resource-attr` (`elementum_x_field.<label>.id`);
@@ -607,6 +1028,107 @@ function resolveConnectorRef(connectorType, connectorLabel, ctx) {
607
1028
  });
608
1029
  return { handle: identity.handle, ...(identity.providerKey !== undefined && { providerKey: identity.providerKey }) };
609
1030
  }
1031
+ /**
1032
+ * `field_ids["Display Name"]` on either the managed table resource or its
1033
+ * `data` lookup. The bag key is derived the same way `table/from-tf.ts` derives
1034
+ * it for an out-of-stream table, so the printed token lines up with the key the
1035
+ * table's own catalog publishes.
1036
+ */
1037
+ function tableColumnRefFromPath(label, path, tableName) {
1038
+ const index = path[1];
1039
+ const name = typeof index === "string"
1040
+ ? index
1041
+ : typeof index === "object" && index !== null && "index" in index && typeof index.index === "string"
1042
+ ? index.index
1043
+ : undefined;
1044
+ if (name === undefined)
1045
+ throw new EntityTfError(`${TABLE_RESOURCE_TYPE}.${label}: field_ids reference has no column name`);
1046
+ return {
1047
+ kind: "tableColumn",
1048
+ tableHandle: tfLabelToTsLabel(label),
1049
+ columnKey: tfLabelToTsLabel(sanitizeName(name)),
1050
+ name,
1051
+ ...(tableName !== undefined ? { tableName } : {}),
1052
+ };
1053
+ }
1054
+ function resolveSearchTableFromBlock(block, searchTableLabel, ctx) {
1055
+ if (block.type === SEARCH_TABLE_RESOURCE_TYPES.table) {
1056
+ const tableId = block.attrs["table_id"];
1057
+ const targetTable = resourceRef(tableId);
1058
+ const tableLabel = targetTable?.label ??
1059
+ (isTfExpr(tableId) && tableId.$expr === "data-attr" && tableId.type === TABLE_RESOURCE_TYPE ? tableId.label : undefined);
1060
+ if (tableLabel !== undefined && tableLabel !== "") {
1061
+ const tableHandle = tfLabelToTsLabel(tableLabel);
1062
+ const prefix = `tables_${tableLabel}_`;
1063
+ const tableKey = tfLabelToTsLabel(searchTableLabel.startsWith(prefix) ? searchTableLabel.slice(prefix.length) : searchTableLabel);
1064
+ return { kind: "searchTable", appHandle: `tables.${tableHandle}`, tableKey };
1065
+ }
1066
+ return undefined;
1067
+ }
1068
+ if (block.type === SEARCH_TABLE_RESOURCE_TYPES.snowflake || block.type === SEARCH_TABLE_RESOURCE_TYPES.linked) {
1069
+ const objectId = block.attrs["object_id"];
1070
+ if (!isTfExpr(objectId) || (objectId.$expr !== "resource-attr" && objectId.$expr !== "data-attr") || objectId.type !== "elementum_element")
1071
+ return undefined;
1072
+ const elementHandle = aspectOwnerRefNameFromObjectId(objectId, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames);
1073
+ if (elementHandle === undefined)
1074
+ return undefined;
1075
+ const rawElementLabel = objectId.label.startsWith("elements_") ? objectId.label.slice("elements_".length) : objectId.label;
1076
+ const elementTfLabel = tsLabelToTfLabel(elementHandle);
1077
+ const tableKey = scopedLabelToBagKey(elementTfLabel, searchTableLabel, "element") !== tfLabelToTsLabel(searchTableLabel)
1078
+ ? scopedLabelToBagKey(elementTfLabel, searchTableLabel, "element")
1079
+ : scopedLabelToBagKey(rawElementLabel, searchTableLabel, "element");
1080
+ return { kind: "searchTable", appHandle: elementHandle, tableKey };
1081
+ }
1082
+ return undefined;
1083
+ }
1084
+ function decodeSearchTableReference(value, ctx) {
1085
+ if (isTfExpr(value) && value.$expr === "data-attr" && value.type === "elementum_search_table") {
1086
+ const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1087
+ const name = typeof lookup?.attrs.name === "string" ? lookup.attrs.name : undefined;
1088
+ const objectId = lookup?.attrs.object_id ?? lookup?.attrs.aspect_id;
1089
+ const elementHandle = objectId !== undefined
1090
+ ? aspectOwnerRefNameFromObjectId(objectId, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames)
1091
+ : undefined;
1092
+ if (elementHandle !== undefined && name !== undefined) {
1093
+ const tableKey = tfLabelToTsLabel(sanitizeName(name));
1094
+ return { kind: "searchTable", appHandle: elementHandle, tableKey };
1095
+ }
1096
+ return { kind: "unresolved", uuid: `data.${value.type}.${value.label}`, hint: "search table" };
1097
+ }
1098
+ const ref = resourceRef(value);
1099
+ if (ref !== undefined &&
1100
+ (ref.type === SEARCH_TABLE_RESOURCE_TYPES.snowflake ||
1101
+ ref.type === SEARCH_TABLE_RESOURCE_TYPES.linked ||
1102
+ ref.type === SEARCH_TABLE_RESOURCE_TYPES.table)) {
1103
+ const block = ctx.resourceBlocks.get(`${ref.type}.${ref.label}`);
1104
+ if (block !== undefined) {
1105
+ const resolved = resolveSearchTableFromBlock(block, ref.label, ctx);
1106
+ if (resolved !== undefined)
1107
+ return resolved;
1108
+ }
1109
+ const uuid = ctx.resourceImportIds.get(`${ref.type}.${ref.label}`) ?? `${ref.type}.${ref.label}`;
1110
+ return { kind: "unresolved", uuid, hint: "search table" };
1111
+ }
1112
+ if (typeof value === "string") {
1113
+ for (const [address, id] of ctx.resourceImportIds) {
1114
+ if (id === value) {
1115
+ const block = ctx.resourceBlocks.get(address);
1116
+ if (block !== undefined) {
1117
+ const searchTableLabel = address.split(".").slice(1).join(".");
1118
+ const resolved = resolveSearchTableFromBlock(block, searchTableLabel, ctx);
1119
+ if (resolved !== undefined)
1120
+ return resolved;
1121
+ }
1122
+ }
1123
+ }
1124
+ return { kind: "unresolved", uuid: value, hint: "search table" };
1125
+ }
1126
+ if (isTfExpr(value) && (value.$expr === "data-attr" || value.$expr === "resource-attr")) {
1127
+ const prefix = value.$expr === "data-attr" ? "data." : "";
1128
+ return { kind: "unresolved", uuid: `${prefix}${value.type}.${value.label}`, hint: "search table" };
1129
+ }
1130
+ return { kind: "unresolved", uuid: typeof value === "string" ? value : JSON.stringify(value), hint: "search table" };
1131
+ }
610
1132
  function decodeValue(value, ctx) {
611
1133
  if (isTfExpr(value)) {
612
1134
  if (value.$expr === "template") {
@@ -631,6 +1153,12 @@ function decodeValue(value, ctx) {
631
1153
  }
632
1154
  if (task !== undefined && value.path[0] === "refs") {
633
1155
  const rawSegments = pathNames(value.path.slice(1));
1156
+ if (rawSegments.length === 1) {
1157
+ const aiAgentPath = aiAgentTaskRefPath(task.block, rawSegments[0]);
1158
+ if (aiAgentPath !== undefined) {
1159
+ return { kind: "taskRef", task: task.refKey, path: aiAgentPath };
1160
+ }
1161
+ }
634
1162
  if (task.block.type === "elementum_record_search_task" && rawSegments.length === 1 && rawSegments[0] === "First found record id") {
635
1163
  return { kind: "taskRef", task: task.refKey, path: ["record", "recordId"] };
636
1164
  }
@@ -657,14 +1185,16 @@ function decodeValue(value, ctx) {
657
1185
  return { kind: "taskRef", task: task.refKey, path: recordPath };
658
1186
  }
659
1187
  }
660
- if (task.block.type === "elementum_record_search_task" && rawSegments.length === 1) {
1188
+ if (task.block.type === "elementum_record_search_task" && rawSegments.length >= 1) {
661
1189
  const recordSearchName = RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS[rawSegments[0]];
662
1190
  if (recordSearchName !== undefined) {
663
- return { kind: "taskRef", task: task.refKey, path: [recordSearchName] };
1191
+ return { kind: "taskRef", task: task.refKey, path: [recordSearchName, ...rawSegments.slice(1)] };
664
1192
  }
665
- const recordFieldPath = taskRecordSearchFieldPath(`${value.type}.${value.label}`, rawSegments[0], ctx);
666
- if (recordFieldPath !== undefined) {
667
- return { kind: "taskRef", task: task.refKey, path: recordFieldPath };
1193
+ if (rawSegments.length === 1) {
1194
+ const recordFieldPath = taskRecordSearchFieldPath(`${value.type}.${value.label}`, rawSegments[0], ctx);
1195
+ if (recordFieldPath !== undefined) {
1196
+ return { kind: "taskRef", task: task.refKey, path: recordFieldPath };
1197
+ }
668
1198
  }
669
1199
  }
670
1200
  if (task.block.type === "elementum_ai_search_table_task" && rawSegments.length === 1) {
@@ -673,6 +1203,21 @@ function decodeValue(value, ctx) {
673
1203
  return { kind: "taskRef", task: task.refKey, path: [aiSearchName] };
674
1204
  }
675
1205
  }
1206
+ if (task.block.type === "elementum_table_records_search_task" && rawSegments.length === 1) {
1207
+ const tableSearchName = TABLE_RECORDS_SEARCH_TASK_REF_SEGMENT_TO_TS[rawSegments[0]];
1208
+ if (tableSearchName !== undefined) {
1209
+ return { kind: "taskRef", task: task.refKey, path: [tableSearchName] };
1210
+ }
1211
+ }
1212
+ // apiRequest's refs map uses display labels ("File", "Content Type",
1213
+ // …) that don't match the lowercase authoring property names
1214
+ // (`file`, `file.contentType`) - see API_TASK_REF_AUTHORING_NAMES.
1215
+ if (task.block.type === "elementum_api_task" && rawSegments.length === 1) {
1216
+ const apiPath = apiTaskRefAuthoringPath(rawSegments[0]);
1217
+ if (apiPath !== undefined) {
1218
+ return { kind: "taskRef", task: task.refKey, path: apiPath };
1219
+ }
1220
+ }
676
1221
  const keyPath = rawSegments.flatMap((segment) => segment.split("."));
677
1222
  if (task.block.type === "elementum_variable_task") {
678
1223
  return { kind: "variableParamRef", varTask: task.refKey, name: keyPath.join(".") };
@@ -716,6 +1261,9 @@ function decodeValue(value, ctx) {
716
1261
  if (value.type === TABLE_RESOURCE_TYPE && value.path[0] === "id") {
717
1262
  return { kind: "table", tableHandle: tfLabelToTsLabel(value.label) };
718
1263
  }
1264
+ if (value.type === TABLE_RESOURCE_TYPE && value.path[0] === "field_ids") {
1265
+ return tableColumnRefFromPath(value.label, value.path, undefined);
1266
+ }
719
1267
  if (value.type === "elementum_datamine" && value.path[0] === "id") {
720
1268
  const datamineBlock = ctx.resourceBlocks.get(`elementum_datamine.${value.label}`);
721
1269
  const tableId = datamineBlock?.attrs["table_id"];
@@ -749,15 +1297,20 @@ function decodeValue(value, ctx) {
749
1297
  };
750
1298
  }
751
1299
  if (value.type === "elementum_approval_process" && value.path[0] === "id") {
752
- const bare = bareChildResourceLabel(ctx.appTfLabel, value.label);
753
1300
  const unresolvedId = ctx.resourceImportIds.get(`${value.type}.${value.label}`);
754
1301
  return {
755
1302
  kind: "approvalChain",
756
1303
  appHandle: ctx.appRefName,
757
- approvalChainKey: tfLabelToTsLabel(bare),
1304
+ approvalChainKey: scopedLabelToBagKey(ctx.appTfLabel, value.label),
758
1305
  ...(unresolvedId !== undefined ? { unresolvedId } : {}),
759
1306
  };
760
1307
  }
1308
+ if ((value.type === SEARCH_TABLE_RESOURCE_TYPES.snowflake ||
1309
+ value.type === SEARCH_TABLE_RESOURCE_TYPES.linked ||
1310
+ value.type === SEARCH_TABLE_RESOURCE_TYPES.table) &&
1311
+ value.path[0] === "id") {
1312
+ return decodeSearchTableReference(value, ctx);
1313
+ }
761
1314
  throw new EntityTfError(`unreconstructable resource reference ${value.type}.${value.label}`);
762
1315
  }
763
1316
  if (value.$expr === "data-attr" && value.type === TABLE_RESOURCE_TYPE && value.path[0] === "id") {
@@ -769,6 +1322,31 @@ function decodeValue(value, ctx) {
769
1322
  ...(typeof name === "string" ? { name } : {}),
770
1323
  };
771
1324
  }
1325
+ if (value.$expr === "data-attr" && value.type === TABLE_RESOURCE_TYPE && value.path[0] === "field_ids") {
1326
+ const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1327
+ const tableName = lookup?.attrs.name;
1328
+ return tableColumnRefFromPath(value.label, value.path, typeof tableName === "string" ? tableName : undefined);
1329
+ }
1330
+ if (value.$expr === "data-attr" && value.type === "elementum_datamine" && value.path[0] === "id") {
1331
+ const datamineLookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1332
+ const tableId = datamineLookup?.attrs["table_id"];
1333
+ if (tableId === undefined ||
1334
+ !isTfExpr(tableId) ||
1335
+ tableId.$expr !== "data-attr" ||
1336
+ tableId.type !== TABLE_RESOURCE_TYPE ||
1337
+ tableId.path[0] !== "id") {
1338
+ throw new EntityTfError(`data.elementum_datamine.${value.label}: table_id is not a table data reference`);
1339
+ }
1340
+ const prefix = `${tableId.label}_`;
1341
+ return {
1342
+ kind: "datamine",
1343
+ tableHandle: tfLabelToTsLabel(tableId.label),
1344
+ datamineKey: tfLabelToTsLabel(value.label.startsWith(prefix) ? value.label.slice(prefix.length) : value.label),
1345
+ };
1346
+ }
1347
+ if (value.$expr === "data-attr" && value.type === "elementum_search_table" && value.path[0] === "id") {
1348
+ return decodeSearchTableReference(value, ctx);
1349
+ }
772
1350
  if (value.$expr === "data-attr" && (value.type === "elementum_app" || value.type === "elementum_element") && value.path[0] === "id") {
773
1351
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
774
1352
  const name = lookup?.attrs.name ?? lookup?.attrs.namespace;
@@ -782,6 +1360,28 @@ function decodeValue(value, ctx) {
782
1360
  ...(typeof name === "string" ? { name } : {}),
783
1361
  };
784
1362
  }
1363
+ if (value.$expr === "data-attr" && value.type === AUTOMATION_RESOURCE_TYPE && value.path[0] === "id") {
1364
+ const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1365
+ const ownerId = lookup?.attrs["app_id"];
1366
+ if (ownerId === undefined ||
1367
+ !isTfExpr(ownerId) ||
1368
+ ownerId.$expr !== "data-attr" ||
1369
+ (ownerId.type !== "elementum_app" && ownerId.type !== "elementum_element") ||
1370
+ ownerId.path[0] !== "id") {
1371
+ throw new EntityTfError(`data.${AUTOMATION_RESOURCE_TYPE}.${value.label}: app_id is not a resolvable app/element data reference`);
1372
+ }
1373
+ const ownerLookup = ctx.dataBlocks.get(`${ownerId.type}.${ownerId.label}`);
1374
+ const ownerIdentity = ownerLookup?.attrs.namespace ?? ownerLookup?.attrs.name;
1375
+ const mappedHandle = typeof ownerIdentity === "string"
1376
+ ? (ownerId.type === "elementum_element" ? ctx.foreignElementRefNames : ctx.foreignAppRefNames)?.get(ownerIdentity)
1377
+ : undefined;
1378
+ const prefix = `${ownerId.label}_`;
1379
+ return {
1380
+ kind: "automation",
1381
+ appHandle: mappedHandle ?? tfLabelToTsLabel(ownerId.label),
1382
+ automationKey: tfLabelToTsLabel(value.label.startsWith(prefix) ? value.label.slice(prefix.length) : value.label),
1383
+ };
1384
+ }
785
1385
  if (value.$expr === "data-attr" && value.type === "elementum_field" && value.path[0] === "id") {
786
1386
  // The reverse of to-tf.ts's `crossAppFieldToTf`: a field belonging to a
787
1387
  // DIFFERENT app/element than this automation's own — resolved via the
@@ -819,6 +1419,51 @@ function decodeValue(value, ctx) {
819
1419
  if (value.$expr === "data-attr" && value.type === "elementum_ai_provider_connector" && value.path[0] === "id") {
820
1420
  return { kind: "connector", id: "", ...resolveConnectorRef(value.type, value.label, ctx) };
821
1421
  }
1422
+ if (value.$expr === "data-attr" && value.type === "elementum_stored_function" && value.path[0] === "id") {
1423
+ const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1424
+ const name = lookup?.attrs.name;
1425
+ const cloudLinkId = lookup?.attrs.cloudlink_id;
1426
+ const databaseName = lookup?.attrs.database_name;
1427
+ const schemaName = lookup?.attrs.schema_name;
1428
+ const functionType = lookup?.attrs.type;
1429
+ const parameterTypes = lookup?.attrs.parameter_types;
1430
+ if (typeof name !== "string" || name === "") {
1431
+ throw new EntityTfError(`data.elementum_stored_function.${value.label}: name lookup is missing`);
1432
+ }
1433
+ if (functionType !== "PROCEDURE") {
1434
+ throw new EntityTfError(`data.elementum_stored_function.${value.label}: type must be PROCEDURE for an automation procedure task`);
1435
+ }
1436
+ if (!Array.isArray(parameterTypes) || !parameterTypes.every((item) => typeof item === "string")) {
1437
+ throw new EntityTfError(`data.elementum_stored_function.${value.label}: parameter_types must carry the exact procedure signature`);
1438
+ }
1439
+ if (typeof databaseName !== "string" || databaseName === "" || typeof schemaName !== "string" || schemaName === "") {
1440
+ throw new EntityTfError(`data.elementum_stored_function.${value.label}: database_name and schema_name must identify the procedure location`);
1441
+ }
1442
+ if (cloudLinkId === undefined ||
1443
+ !isTfExpr(cloudLinkId) ||
1444
+ cloudLinkId.$expr !== "data-attr" ||
1445
+ cloudLinkId.type !== "elementum_cloudlink" ||
1446
+ cloudLinkId.path[0] !== "id") {
1447
+ throw new EntityTfError(`data.elementum_stored_function.${value.label}: cloudlink_id is not a resolvable CloudLink data reference`);
1448
+ }
1449
+ // Two procedures can share a sanitized name within one CloudLink
1450
+ // (overloads) — org.ts disambiguates them with a numeric suffix
1451
+ // assigned across the WHOLE procedure list, a decision this single
1452
+ // data block can't reconstruct alone. Resolve the exact bag key from
1453
+ // the already-pulled org catalog by the same discriminator
1454
+ // (CloudLink + name + database + schema + ordered parameter types);
1455
+ // fall back to the base sanitized key, which is already correct
1456
+ // whenever there's no overload to disambiguate.
1457
+ const cloudLinkName = ctx.dataBlocks.get(`${cloudLinkId.type}.${cloudLinkId.label}`)?.attrs.name;
1458
+ const resolvedKey = typeof cloudLinkName === "string"
1459
+ ? ctx.procedureKeysByDiscriminator?.get(procedureDiscriminator(cloudLinkName, name, databaseName, schemaName, parameterTypes))
1460
+ : undefined;
1461
+ return {
1462
+ kind: "procedure",
1463
+ cloudLinkKey: tfLabelToTsLabel(cloudLinkId.label),
1464
+ procedureKey: resolvedKey ?? tfLabelToTsLabel(sanitizeName(name)),
1465
+ };
1466
+ }
822
1467
  if (value.$expr === "data-attr" && value.type === "elementum_cloudlink" && value.path[0] === "id") {
823
1468
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
824
1469
  const name = lookup?.attrs.name;
@@ -921,6 +1566,24 @@ function fieldRef(value, ctx) {
921
1566
  }
922
1567
  throw new EntityTfError("field reference cannot be reconstructed");
923
1568
  }
1569
+ /**
1570
+ * A TABLE search's filter addresses table COLUMNS, not app fields. The bridge
1571
+ * now hydrates the searched table, so the left side arrives as
1572
+ * `field_ids["Column"]` where it used to be the raw column UUID that
1573
+ * `fieldRef` degraded to an `unresolved` field.
1574
+ */
1575
+ function filterFieldRef(value, ctx) {
1576
+ if (isTfExpr(value) &&
1577
+ (value.$expr === "resource-attr" || value.$expr === "data-attr") &&
1578
+ value.type === TABLE_RESOURCE_TYPE &&
1579
+ value.path[0] === "field_ids") {
1580
+ const tableName = value.$expr === "data-attr"
1581
+ ? ctx.dataBlocks.get(`${value.type}.${value.label}`)?.attrs.name
1582
+ : undefined;
1583
+ return tableColumnRefFromPath(value.label, value.path, typeof tableName === "string" ? tableName : undefined);
1584
+ }
1585
+ return fieldRef(value, ctx);
1586
+ }
924
1587
  const USER_FIELD_KEY_SET = new Set(USER_FIELD_KEYS);
925
1588
  function userFieldRef(value, ctx) {
926
1589
  if (typeof value === "string" && USER_FIELD_KEY_SET.has(value)) {
@@ -983,7 +1646,8 @@ function decodeCalculationFormula(value, ctx) {
983
1646
  if (index > cursor)
984
1647
  parts.push(value.slice(cursor, index));
985
1648
  if (match[3] !== undefined) {
986
- parts.push({ kind: "unresolved", uuid: `variable.${match[3]}`, hint: "variable" });
1649
+ const resolved = resolveVariableReference(match[3], match[3], undefined, ctx);
1650
+ parts.push(resolved ?? { kind: "unresolved", uuid: `variable.${match[3]}`, hint: "variable" });
987
1651
  cursor = index + match[0].length;
988
1652
  continue;
989
1653
  }
@@ -1025,6 +1689,11 @@ function decodeCalculationTaskMustache(taskId, wireName, ctx) {
1025
1689
  if (refKey === undefined) {
1026
1690
  return { kind: "unresolved", uuid: `task.${taskId}.${wireName}`, hint: "calculation-reference" };
1027
1691
  }
1692
+ if (taskBlock !== undefined) {
1693
+ const aiAgentPath = aiAgentTaskRefPath(taskBlock, wireName);
1694
+ if (aiAgentPath !== undefined)
1695
+ return { kind: "taskRef", task: refKey, path: aiAgentPath };
1696
+ }
1028
1697
  if (taskBlock?.type === "elementum_record_search_task") {
1029
1698
  const recordSearchName = RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS[wireName];
1030
1699
  if (recordSearchName !== undefined) {
@@ -1044,6 +1713,18 @@ function decodeCalculationTaskMustache(taskId, wireName, ctx) {
1044
1713
  return { kind: "taskRef", task: refKey, path: [aiSearchName] };
1045
1714
  }
1046
1715
  }
1716
+ if (taskBlock?.type === "elementum_table_records_search_task") {
1717
+ const tableSearchName = TABLE_RECORDS_SEARCH_TASK_REF_SEGMENT_TO_TS[wireName];
1718
+ if (tableSearchName !== undefined) {
1719
+ return { kind: "taskRef", task: refKey, path: [tableSearchName] };
1720
+ }
1721
+ }
1722
+ if (taskBlock?.type === "elementum_api_task") {
1723
+ const apiPath = apiTaskRefAuthoringPath(wireName);
1724
+ if (apiPath !== undefined) {
1725
+ return { kind: "taskRef", task: refKey, path: apiPath };
1726
+ }
1727
+ }
1047
1728
  const keyPath = wireName.split(".");
1048
1729
  const taskKind = taskBlock?.type !== undefined ? TASK_FACTORIES[taskBlock.type] : undefined;
1049
1730
  const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
@@ -1074,21 +1755,98 @@ function pulledRawCalculation(formula, outputType, multiple) {
1074
1755
  const resultType = PULLED_CALCULATION_RESULT_TYPES[outputType];
1075
1756
  return resultType === undefined ? undefined : { kind: "calculationRaw", text: formula, resultType };
1076
1757
  }
1077
- function decodeFilterReferenceEnvelope(value, ctx) {
1078
- const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
1758
+ function resolveVariableReference(rawId, rawName, outputName, ctx) {
1759
+ const variableTasks = [];
1760
+ for (const [, task] of ctx.taskByAddress) {
1761
+ if (task.block.type === "elementum_variable_task") {
1762
+ const varName = typeof task.block.attrs.variable_name === "string"
1763
+ ? task.block.attrs.variable_name
1764
+ : (typeof task.block.attrs.name === "string" ? task.block.attrs.name : task.refKey);
1765
+ const varId = typeof task.block.attrs.variable_id === "string"
1766
+ ? task.block.attrs.variable_id
1767
+ : undefined;
1768
+ variableTasks.push({ refKey: task.refKey, varName, varId });
1769
+ }
1770
+ }
1771
+ if (variableTasks.length === 0)
1772
+ return undefined;
1773
+ // 1. By variable ID if available on the variable task block
1774
+ if (rawId !== undefined) {
1775
+ const byId = variableTasks.find((vt) => vt.varId === rawId);
1776
+ if (byId !== undefined) {
1777
+ return { kind: "variableParamRef", varTask: byId.refKey, name: byId.varName };
1778
+ }
1779
+ }
1780
+ // 2. By variable name or refKey if rawName is not a synthetic variable|<uuid> name
1781
+ if (rawName !== undefined && !rawName.startsWith("variable|") && !rawName.startsWith("variable.")) {
1782
+ const byName = variableTasks.find((vt) => vt.varName === rawName || vt.refKey === rawName);
1783
+ if (byName !== undefined) {
1784
+ return { kind: "variableParamRef", varTask: byName.refKey, name: byName.varName };
1785
+ }
1786
+ }
1787
+ // 3. By target output name (only for workflow_publish outputs where outputName is provided)
1788
+ if (outputName !== undefined) {
1789
+ const byOutput = variableTasks.find((vt) => vt.varName === outputName || vt.refKey === outputName);
1790
+ if (byOutput !== undefined) {
1791
+ return { kind: "variableParamRef", varTask: byOutput.refKey, name: byOutput.varName };
1792
+ }
1793
+ }
1794
+ return undefined;
1795
+ }
1796
+ function decodeFilterReferenceEnvelope(value, ctx, outputName) {
1797
+ let raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
1798
+ while (isObject(raw) && "value" in raw && Object.keys(raw).length === 1) {
1799
+ raw = raw.value;
1800
+ }
1079
1801
  if (!isObject(raw))
1080
1802
  return undefined;
1081
1803
  const taskRef = raw.taskReference;
1082
- if (isObject(taskRef) && typeof taskRef.taskId === "string" && typeof taskRef.name === "string") {
1083
- return decodeTaskReferenceFromString(taskRef.taskId, taskRef.name.split("."), ctx);
1804
+ if (isObject(taskRef) && typeof taskRef.name === "string") {
1805
+ const taskIdOrKey = workflowOutputTaskIdOrKey(taskRef.taskId, ctx);
1806
+ if (taskIdOrKey !== undefined) {
1807
+ return decodeTaskReferenceFromString(taskIdOrKey, taskRef.name.split("."), ctx);
1808
+ }
1084
1809
  }
1085
1810
  const triggerRef = raw.triggerReference;
1086
1811
  if (isObject(triggerRef) && typeof triggerRef.name === "string") {
1087
1812
  return decodeReferenceString(`trigger.${triggerRef.name}`, ctx);
1088
1813
  }
1089
1814
  const variableRef = raw.variableReference;
1090
- if (isObject(variableRef) && typeof variableRef.id === "string") {
1091
- return { kind: "unresolved", uuid: `variable.${variableRef.id}`, hint: "variable" };
1815
+ if (isObject(variableRef)) {
1816
+ let rawId = typeof variableRef.id === "string" && variableRef.id !== "" ? variableRef.id : undefined;
1817
+ let rawName = typeof variableRef.name === "string" && variableRef.name !== "" ? variableRef.name : undefined;
1818
+ if (rawName !== undefined) {
1819
+ if (rawName.startsWith("variable|")) {
1820
+ const afterPrefix = rawName.slice("variable|".length);
1821
+ if (rawId === undefined)
1822
+ rawId = afterPrefix;
1823
+ }
1824
+ else if (rawName.startsWith("variable.")) {
1825
+ const afterPrefix = rawName.slice("variable.".length);
1826
+ if (rawId === undefined)
1827
+ rawId = afterPrefix;
1828
+ }
1829
+ }
1830
+ const resolved = resolveVariableReference(rawId, rawName, outputName, ctx);
1831
+ if (resolved !== undefined)
1832
+ return resolved;
1833
+ const fallbackUuid = rawId ?? (rawName !== undefined ? rawName.replace(/^variable[|.]/, "") : "unknown");
1834
+ return { kind: "unresolved", uuid: `variable.${fallbackUuid}`, hint: "variable" };
1835
+ }
1836
+ return undefined;
1837
+ }
1838
+ /** Resolve export UUID or build-time `task.id` resource attr to a task id/refKey. */
1839
+ function workflowOutputTaskIdOrKey(taskId, ctx) {
1840
+ if (typeof taskId === "string" && taskId !== "")
1841
+ return taskId;
1842
+ if (typeof taskId === "object" && taskId !== null && isTfExpr(taskId)) {
1843
+ const exprValue = taskId;
1844
+ if (exprValue.$expr === "resource-attr" && "path" in exprValue && Array.isArray(exprValue.path) && exprValue.path[0] === "id"
1845
+ && "type" in exprValue && "label" in exprValue
1846
+ && typeof exprValue.type === "string" && typeof exprValue.label === "string") {
1847
+ const task = ctx.taskByAddress.get(`${exprValue.type}.${exprValue.label}`);
1848
+ return task?.refKey;
1849
+ }
1092
1850
  }
1093
1851
  return undefined;
1094
1852
  }
@@ -1097,15 +1855,37 @@ function filterReference(value, ctx) {
1097
1855
  ? decodeReferenceString(value, ctx) ?? { kind: "unresolved", uuid: value, hint: "filter-reference" }
1098
1856
  : decodeFilterReferenceEnvelope(value, ctx)
1099
1857
  ?? decodeTemplateTriggerRecordFieldRef(value, ctx)
1858
+ ?? decodeTemplateTaskRef(value, ctx)
1100
1859
  ?? decodeValue(value, ctx);
1101
1860
  }
1861
+ function filterReferenceType(value, fallback, ctx) {
1862
+ const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
1863
+ if (!isObject(raw))
1864
+ return fallback;
1865
+ const taskRef = raw.taskReference;
1866
+ if (isObject(taskRef) && typeof taskRef.name === "string") {
1867
+ const taskIdOrKey = workflowOutputTaskIdOrKey(taskRef.taskId, ctx);
1868
+ const task = taskIdOrKey === undefined ? undefined : resolveTaskRefKey(taskIdOrKey, ctx).block;
1869
+ if (task?.type === "elementum_execute_script_task") {
1870
+ const schemaValue = task.attrs.output_schema;
1871
+ const schema = isTfExpr(schemaValue) && schemaValue.$expr === "jsonencode"
1872
+ ? schemaValue.value
1873
+ : schemaValue;
1874
+ const declared = outputFieldTypesFromScriptSchema(schema)?.get(taskRef.name);
1875
+ if (declared !== undefined)
1876
+ return fieldTypeToValueType(declared.fieldType);
1877
+ }
1878
+ }
1879
+ return typeof raw.fieldType === "string" ? fieldTypeToValueType(raw.fieldType) : fallback;
1880
+ }
1102
1881
  function decodeFilter(value, ctx, fieldScope = "app") {
1103
1882
  return deserializeFilterFromTf(value, {
1104
1883
  field: (fieldValue, scope) => {
1105
- const field = scope === "user" ? userFieldRef(fieldValue, ctx) : fieldRef(fieldValue, ctx);
1884
+ const field = scope === "user" ? userFieldRef(fieldValue, ctx) : filterFieldRef(fieldValue, ctx);
1106
1885
  return field ?? { kind: "unresolved", uuid: String(fieldValue), hint: "field" };
1107
1886
  },
1108
1887
  reference: (reference) => filterReference(reference, ctx),
1888
+ referenceType: (reference, fallback) => filterReferenceType(reference, fallback, ctx),
1109
1889
  literal: (literal) => picklistOptionLabel(literal) ?? stageFilterName(literal, ctx) ?? literal,
1110
1890
  }, fieldScope);
1111
1891
  }
@@ -1130,7 +1910,22 @@ function triggerFromBlock(block, ctx) {
1130
1910
  // source uses a type-checkable alias instead of a raw wire string
1131
1911
  // "attachment" that TriggerFieldTypeAlias doesn't accept.
1132
1912
  const type = parameter.type === "attachment" ? "attachmentId" : parameter.type;
1133
- return { name: parameter.name, type, ...(parameter.required === true ? { required: true } : {}), ...(parameter.multiple === true ? { multiple: true } : {}), ...(parameter.default_value !== undefined ? { defaultValue: parameter.default_value } : {}), ...(typeof parameter.description === "string" ? { description: parameter.description } : {}) };
1913
+ const record = type === "record";
1914
+ const recordApp = record
1915
+ ? aspectRefFromObjectId(parameter.default_value, ctx)
1916
+ : undefined;
1917
+ if (record && recordApp === undefined) {
1918
+ throw new EntityTfError(`on-demand record parameter "${parameter.name}" has no resolvable app/element default_value`);
1919
+ }
1920
+ return {
1921
+ name: parameter.name,
1922
+ type,
1923
+ ...(recordApp !== undefined ? { app: recordApp } : {}),
1924
+ ...(parameter.required === true ? { required: true } : {}),
1925
+ ...(parameter.multiple === true ? { multiple: true } : {}),
1926
+ ...(!record && parameter.default_value !== undefined ? { defaultValue: parameter.default_value } : {}),
1927
+ ...(typeof parameter.description === "string" ? { description: parameter.description } : {}),
1928
+ };
1134
1929
  }), ...(block.attrs.show_triggered_by === true ? { showTriggeredBy: true } : {})
1135
1930
  };
1136
1931
  }
@@ -1157,8 +1952,13 @@ function triggerFromBlock(block, ctx) {
1157
1952
  ...(block.attrs.custom_response !== undefined ? { customResponse: decodeCustomResponse(block.attrs.custom_response, ctx) } : {}),
1158
1953
  };
1159
1954
  case "approvalProcessStatusUpdated": {
1160
- if (block.attrs.approval_chain_template_id === undefined || typeof block.attrs.status !== "string")
1955
+ if (typeof block.attrs.status !== "string")
1161
1956
  throw new EntityTfError("approval trigger is incomplete");
1957
+ // approval_chain_template_id is genuinely omittable on the platform
1958
+ // (edk#712) - a null/never-set template means "any", not "unresolved".
1959
+ if (block.attrs.approval_chain_template_id === undefined) {
1960
+ return { kind, app, status: block.attrs.status };
1961
+ }
1162
1962
  const approvalChain = typeof block.attrs.approval_chain_template_id === "string"
1163
1963
  ? block.attrs.approval_chain_template_id
1164
1964
  : decodeValue(block.attrs.approval_chain_template_id, ctx);
@@ -1215,7 +2015,10 @@ function taskArgs(block, factory, ctx) {
1215
2015
  const fieldKey = field.kind === "field"
1216
2016
  ? field.fieldKey
1217
2017
  : `${UNRESOLVED_FIELD_MARKER}${field.uuid}`;
1218
- values[fieldKey] = decodeFieldAssignmentValue(item.value, ctx);
2018
+ const decodedValue = decodeFieldAssignmentValue(item.value, ctx);
2019
+ values[fieldKey] = item.update_mode === "add"
2020
+ ? { __fieldAssignment: true, value: decodedValue, updateMode: "add" }
2021
+ : decodedValue;
1219
2022
  }
1220
2023
  args.values = values;
1221
2024
  continue;
@@ -1232,8 +2035,9 @@ function taskArgs(block, factory, ctx) {
1232
2035
  }
1233
2036
  if (attr === "output_schema" && factory === "executeScript") {
1234
2037
  const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
1235
- const props = isObject(raw) && isObject(raw.object) && Array.isArray(raw.object.properties) ? raw.object.properties : [];
1236
- args.outputs = Object.fromEntries(props.map((property) => {
2038
+ const root = isObject(raw) && isObject(raw.object) ? raw.object : undefined;
2039
+ const props = Array.isArray(root?.properties) ? root.properties : [];
2040
+ const properties = Object.fromEntries(props.map((property) => {
1237
2041
  if (!isObject(property))
1238
2042
  throw new EntityTfError("invalid script output schema");
1239
2043
  const [type, definition] = Object.entries(property)[0] ?? [];
@@ -1241,6 +2045,12 @@ function taskArgs(block, factory, ctx) {
1241
2045
  throw new EntityTfError("invalid script output property");
1242
2046
  return [definition.name, type === "bool" ? "boolean" : type];
1243
2047
  }));
2048
+ // The root object's own name is inert to the platform but real stored
2049
+ // data, so carry it through rather than rebuilding a schema that
2050
+ // differs from the one just read.
2051
+ args.outputs = typeof root?.name === "string" && root.name !== ""
2052
+ ? { name: root.name, properties }
2053
+ : properties;
1244
2054
  continue;
1245
2055
  }
1246
2056
  if (attr === "input_mappings" && factory === "runAutomation") {
@@ -1251,17 +2061,31 @@ function taskArgs(block, factory, ctx) {
1251
2061
  throw new EntityTfError(`${block.type}.${block.label}: invalid input mapping`);
1252
2062
  }
1253
2063
  const parameter = item.parameter_id;
1254
- if (!isTfExpr(parameter) ||
1255
- parameter.$expr !== "resource-attr" ||
1256
- parameter.type !== "elementum_on_demand_trigger" ||
1257
- parameter.path[0] !== "parameter_ids" ||
1258
- typeof parameter.path[1] !== "object" ||
1259
- parameter.path[1] === null ||
1260
- !("index" in parameter.path[1]) ||
1261
- typeof parameter.path[1].index !== "string") {
1262
- throw new EntityTfError(`${block.type}.${block.label}: input mapping parameter_id is not a named trigger parameter reference`);
2064
+ if (isTfExpr(parameter) &&
2065
+ (parameter.$expr === "resource-attr" &&
2066
+ parameter.type === "elementum_on_demand_trigger" ||
2067
+ parameter.$expr === "data-attr" &&
2068
+ parameter.type === AUTOMATION_RESOURCE_TYPE) &&
2069
+ parameter.path[0] === "parameter_ids" &&
2070
+ typeof parameter.path[1] === "object" &&
2071
+ parameter.path[1] !== null &&
2072
+ "index" in parameter.path[1] &&
2073
+ typeof parameter.path[1].index === "string") {
2074
+ return { name: parameter.path[1].index, value: decodeValue(item.value, ctx) };
2075
+ }
2076
+ // ei emits bare platform parameter UUIDs when the target automation's
2077
+ // onDemand trigger is not in this export (foreign / undiscovered).
2078
+ // Throwing here used to abort the WHOLE parent automation extract, so
2079
+ // skill tools that only needed the automation catalog key (e.g.
2080
+ // ridesTriggerRides) were dropped on build. Keep extract alive with an
2081
+ // unresolved placeholder — printer emits a TODO, build stays honest.
2082
+ if (typeof parameter === "string" && parameter !== "") {
2083
+ return {
2084
+ name: parameter,
2085
+ value: decodeValue(item.value, ctx),
2086
+ };
1263
2087
  }
1264
- return { name: parameter.path[1].index, value: decodeValue(item.value, ctx) };
2088
+ throw new EntityTfError(`${block.type}.${block.label}: input mapping parameter_id is not a named trigger parameter reference`);
1265
2089
  });
1266
2090
  continue;
1267
2091
  }
@@ -1339,6 +2163,50 @@ function taskArgs(block, factory, ctx) {
1339
2163
  : decodeValue(value, ctx);
1340
2164
  continue;
1341
2165
  }
2166
+ if (attr === "search_table_id" && factory === "aiSearchTable") {
2167
+ args.table = decodeSearchTableReference(value, ctx);
2168
+ continue;
2169
+ }
2170
+ if (factory === "approvalChain" && attr === "approval_process_id") {
2171
+ args.approvalProcess = decodeValue(value, ctx);
2172
+ continue;
2173
+ }
2174
+ if (factory === "approvalChain" && attr === "record_reference") {
2175
+ args.record = decodeValue(value, ctx);
2176
+ continue;
2177
+ }
2178
+ if (factory === "approvalChain" && attr === "requester_reference") {
2179
+ const fieldType = approverReferenceFieldAuthoringType(value, ctx);
2180
+ if (fieldType === UNVERIFIABLE_FOREIGN_FIELD_TYPE) {
2181
+ throw new EntityTfError(`${block.type}.${block.label}: requester_reference targets a field on a foreign aspect that has never been ` +
2182
+ "pulled locally — its type cannot be verified against the platform's required USER_ID reference; pull that " +
2183
+ "aspect first (`elementum pull app`/`pull element`), then re-pull this app (edk#768)");
2184
+ }
2185
+ if (fieldType !== undefined && fieldType !== "USER") {
2186
+ throw new EntityTfError(`${block.type}.${block.label}: requester_reference targets a "${fieldType}" field, not a USER field — ` +
2187
+ `the platform's approval-chain validation requires a USER_ID type reference (edk#655)`);
2188
+ }
2189
+ args.requester = decodeValue(value, ctx);
2190
+ continue;
2191
+ }
2192
+ if (factory === "approvalChain" && attr === "approver_references") {
2193
+ if (!Array.isArray(value))
2194
+ throw new EntityTfError(`${block.type}.${block.label}: approver_references must be an array`);
2195
+ for (const item of value) {
2196
+ const fieldType = approverReferenceFieldAuthoringType(item, ctx);
2197
+ if (fieldType === UNVERIFIABLE_FOREIGN_FIELD_TYPE) {
2198
+ throw new EntityTfError(`${block.type}.${block.label}: approver_references targets a field on a foreign aspect that has never been ` +
2199
+ "pulled locally — its type cannot be verified against the platform's required USER_ID reference; pull that " +
2200
+ "aspect first (`elementum pull app`/`pull element`), then re-pull this app (edk#768)");
2201
+ }
2202
+ if (fieldType !== undefined && fieldType !== "USER") {
2203
+ throw new EntityTfError(`${block.type}.${block.label}: approver_references targets a "${fieldType}" field, not a USER field — ` +
2204
+ `the platform's approval-chain validation requires a USER_ID type reference (edk#655)`);
2205
+ }
2206
+ }
2207
+ args.approvers = value.map((item) => decodeValue(item, ctx));
2208
+ continue;
2209
+ }
1342
2210
  if (attr === "list" && factory === "forEach") {
1343
2211
  args.collection = decodeValue(value, ctx);
1344
2212
  continue;
@@ -1360,6 +2228,29 @@ function taskArgs(block, factory, ctx) {
1360
2228
  args.outputType = typeof value === "string" ? value.toLowerCase() : decodeValue(value, ctx);
1361
2229
  continue;
1362
2230
  }
2231
+ if (attr === "json_fields" && factory === "aiAgent") {
2232
+ const outputType = block.attrs.output_type;
2233
+ if (typeof outputType !== "string" || outputType.toLowerCase() !== "json")
2234
+ continue;
2235
+ if (!Array.isArray(value))
2236
+ throw new EntityTfError(`${block.type}.${block.label}: json_fields must be an array`);
2237
+ args.schema = Object.fromEntries(value.map((field) => {
2238
+ if (!isObject(field) || typeof field.name !== "string" || typeof field.type !== "string") {
2239
+ throw new EntityTfError(`${block.type}.${block.label}: invalid json_fields entry`);
2240
+ }
2241
+ return [
2242
+ field.name,
2243
+ {
2244
+ type: field.type.toLowerCase(),
2245
+ ...(typeof field.description === "string" && field.description !== ""
2246
+ ? { description: field.description }
2247
+ : {}),
2248
+ ...(typeof field.required === "boolean" ? { required: field.required } : {}),
2249
+ },
2250
+ ];
2251
+ }));
2252
+ continue;
2253
+ }
1363
2254
  // procedure()'s wire shape wraps each positional argument as
1364
2255
  // `{index, value}` (see tasks.ts's procedure()); ProcedureOptions.parameters
1365
2256
  // is a plain, position-ordered array - unwrap rather than round-tripping
@@ -1488,6 +2379,13 @@ function taskArgs(block, factory, ctx) {
1488
2379
  args.message = decodeValue(value, ctx);
1489
2380
  continue;
1490
2381
  }
2382
+ // Notification's dynamic-recipient HCL attributes share the names
2383
+ // `users`/`groups` with sendEmail, but their public options are
2384
+ // userRefs/groupRefs (not sendEmail's toUsers/toGroups).
2385
+ if (factory === "notification" && (attr === "users" || attr === "groups")) {
2386
+ args[attr === "users" ? "userRefs" : "groupRefs"] = decodeValue(value, ctx);
2387
+ continue;
2388
+ }
1491
2389
  const arg = ATTR_TO_ARG[attr] ?? attr.replace(/_([a-z])/g, (_, char) => char.toUpperCase());
1492
2390
  args[arg] = decodeValue(value, ctx);
1493
2391
  }
@@ -1497,6 +2395,18 @@ function taskArgs(block, factory, ctx) {
1497
2395
  args.relatedApp = args.app ?? appRef(ctx.appRefName);
1498
2396
  delete args.app;
1499
2397
  }
2398
+ if (factory === "procedure") {
2399
+ const procedure = args.procedureId;
2400
+ if (isObject(procedure) && procedure.kind === "procedure") {
2401
+ const cloudLink = args.cloudLinkId;
2402
+ if (!isObject(cloudLink) || cloudLink.kind !== "cloudLink" || cloudLink.handle !== procedure.cloudLinkKey) {
2403
+ throw new EntityTfError(`${block.type}.${block.label}: stored function and task cloudlink_id refer to different CloudLinks`);
2404
+ }
2405
+ args.procedure = procedure;
2406
+ delete args.procedureId;
2407
+ delete args.cloudLinkId;
2408
+ }
2409
+ }
1500
2410
  if (factory === "setVariable") {
1501
2411
  if (block.type === "elementum_variable_task") {
1502
2412
  if (typeof block.attrs.variable_name !== "string" || typeof block.attrs.variable_type !== "string")
@@ -1510,10 +2420,62 @@ function taskArgs(block, factory, ctx) {
1510
2420
  }
1511
2421
  return args;
1512
2422
  }
1513
- function parentAddress(block) {
2423
+ /**
2424
+ * Resolve an `elementum_unmanaged_task_reference` data block's OWN real
2425
+ * position in the task tree from its `operator_child_id`/`operator_task_id`/
2426
+ * `parent_is_trigger` attributes (edk#821) - the platform already records
2427
+ * exactly which switch case / fork-join branch / forEach body (or the
2428
+ * trigger) the unsupported task sits in; this was previously discarded
2429
+ * entirely in favor of always anchoring to the trigger. Returns `undefined`
2430
+ * when none of those attributes resolve to an address this automation
2431
+ * actually owns, so the caller can fall back to the trigger-anchor + diagnostic
2432
+ * safety net rather than pointing at an address nothing will ever visit.
2433
+ */
2434
+ function resolveUnmanagedTaskPosition(dataBlock, triggerAddress, ownedAddresses) {
2435
+ if (dataBlock.attrs.parent_is_trigger === true)
2436
+ return triggerAddress;
2437
+ const operatorRef = resourceRef(dataBlock.attrs.operator_task_id);
2438
+ if (operatorRef?.type === "elementum_for_each_task") {
2439
+ const inner = `${operatorRef.type}.${operatorRef.label}.inner`;
2440
+ return ownedAddresses.has(`${operatorRef.type}.${operatorRef.label}`) ? inner : undefined;
2441
+ }
2442
+ const childRef = resourceRef(dataBlock.attrs.operator_child_id);
2443
+ if (childRef !== undefined) {
2444
+ const address = `${childRef.type}.${childRef.label}`;
2445
+ return ownedAddresses.has(address) ? address : undefined;
2446
+ }
2447
+ if (operatorRef !== undefined) {
2448
+ const address = `${operatorRef.type}.${operatorRef.label}`;
2449
+ return ownedAddresses.has(address) ? address : undefined;
2450
+ }
2451
+ return undefined;
2452
+ }
2453
+ /**
2454
+ * `triggerAddress`/`onUnmanagedParent` are the fallback of last resort: a
2455
+ * task whose real predecessor is an unsupported task type, when that
2456
+ * predecessor's own position couldn't be resolved either (see
2457
+ * `resolveUnmanagedTaskPosition`), is anchored to the trigger instead - not
2458
+ * its true live position, but keeps it (and anything chained after it) from
2459
+ * being silently dropped from the authored source. `unmanagedTaskPositions`
2460
+ * maps each such data block's OWN address to its resolved position (edk#821)
2461
+ * - when present, the downstream task anchors onto the placeholder's own
2462
+ * address (its position in the tree), not the placeholder's resolved
2463
+ * position directly, so `buildTasks`'s normal flat-chain recursion picks up
2464
+ * the whole downstream chain from there.
2465
+ */
2466
+ function parentAddress(block, triggerAddress, unmanagedTaskPositions, onUnmanagedParent) {
1514
2467
  const parent = resourceRef(block.attrs.parent);
1515
- if (parent === undefined)
2468
+ if (parent === undefined) {
2469
+ const unmanagedRef = unmanagedTaskRef(block.attrs.parent);
2470
+ if (unmanagedRef !== undefined) {
2471
+ const address = `elementum_unmanaged_task_reference.${unmanagedRef.label}`;
2472
+ if (unmanagedTaskPositions.has(address))
2473
+ return address;
2474
+ onUnmanagedParent?.(block);
2475
+ return triggerAddress;
2476
+ }
1516
2477
  throw new EntityTfError(`${block.type}.${block.label}: missing or invalid parent`);
2478
+ }
1517
2479
  const suffix = parent.path.length > 0 ? `.${pathNames(parent.path).join(".")}` : "";
1518
2480
  return `${parent.type}.${parent.label}${suffix}`;
1519
2481
  }
@@ -1524,6 +2486,18 @@ function taskRefKey(block, automationLabel, appTfLabel) {
1524
2486
  const taskName = typeof block.attrs.name === "string" ? block.attrs.name : undefined;
1525
2487
  if (taskName !== undefined) {
1526
2488
  const sanitized = sanitizeName(taskName);
2489
+ // The platform can export created-variable tasks under generated positional
2490
+ // names such as "lookup_result_state 1" even though current-API authoring
2491
+ // keys them by the variable they create. Restrict this reconciliation to
2492
+ // that positional export shape: named tasks such as "set_variable_task"
2493
+ // remain valid action identities used by workflow outputs.
2494
+ if (block.type === "elementum_variable_task" &&
2495
+ typeof block.attrs.variable_name === "string" &&
2496
+ block.attrs.variable_name !== "" &&
2497
+ /(?:\s|-)\d+$/.test(taskName.trim()) &&
2498
+ (sanitized === tail || sanitized === `_${tail}`)) {
2499
+ return block.attrs.variable_name;
2500
+ }
1527
2501
  // ei sanitizes `<automation>_<task>` as ONE combined string
1528
2502
  // (imports.go), so the digit-leading guard only ever sees the
1529
2503
  // automation's own first character - a task name that itself starts
@@ -1603,7 +2577,7 @@ function unresolvedAuthoringValues(doc) {
1603
2577
  return values;
1604
2578
  }
1605
2579
  /** Extract one app-owned automation graph from an ei app export. */
1606
- function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames) {
2580
+ function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames, procedureKeysByDiscriminator) {
1607
2581
  const automation = doc.blocks.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE && block.label === automationLabel);
1608
2582
  if (automation === undefined)
1609
2583
  throw new EntityTfError(`automation resource "${automationLabel}" not found`);
@@ -1629,6 +2603,15 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1629
2603
  const branches = doc.blocks.filter((block) => block.kind === "resource" && AUTOMATION_BRANCH_TYPE_SET.has(block.type ?? ""));
1630
2604
  const taskCandidates = doc.blocks.filter((block) => block.kind === "resource" && ALL_AUTOMATION_TASK_TYPE_SET.has(block.type ?? ""));
1631
2605
  const resourceBlocks = new Map(doc.blocks.filter((block) => block.kind === "resource" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
2606
+ // edk#785: workflow_publish.depends_on is this automation's own manifest of
2607
+ // everything it owns (Go's build emits exactly one entry per task/trigger/
2608
+ // branch belonging to it) - the only reliable way to scope a task back to
2609
+ // THIS automation, since taskCandidates spans the whole app (doc.blocks is
2610
+ // every automation's blocks combined) and task labels carry no ownership
2611
+ // guarantee of their own.
2612
+ const publishDependencyAddresses = new Set(Array.isArray(publish?.attrs.depends_on)
2613
+ ? publish.attrs.depends_on.map((value) => resourceRef(value)).filter((ref) => ref !== undefined).map((ref) => `${ref.type}.${ref.label}`)
2614
+ : []);
1632
2615
  const owned = new Set([`${trigger.type}.${trigger.label}`]);
1633
2616
  let changed = true;
1634
2617
  while (changed) {
@@ -1646,6 +2629,12 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1646
2629
  owned.add(`${task.type}.${task.label}`);
1647
2630
  changed = true;
1648
2631
  }
2632
+ // edk#785: a data-source parent is always "resolved" (see unmanagedTaskRef) -
2633
+ // doesn't need its target to already be owned the way a resource-attr parent does.
2634
+ else if (!parent && unmanagedTaskRef(task.attrs.parent) && publishDependencyAddresses.has(`${task.type}.${task.label}`) && !owned.has(`${task.type}.${task.label}`)) {
2635
+ owned.add(`${task.type}.${task.label}`);
2636
+ changed = true;
2637
+ }
1649
2638
  }
1650
2639
  }
1651
2640
  const tasks = taskCandidates.filter((block) => owned.has(`${block.type}.${block.label}`));
@@ -1695,17 +2684,31 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1695
2684
  }
1696
2685
  for (const task of tasks) {
1697
2686
  const parent = resourceRef(task.attrs.parent);
1698
- if (parent === undefined || !owned.has(`${parent.type}.${parent.label}`))
2687
+ if (parent === undefined) {
2688
+ if (unmanagedTaskRef(task.attrs.parent) !== undefined)
2689
+ continue; // edk#785: always resolved, see unmanagedTaskRef
2690
+ throw new EntityTfError(`${task.type}.${task.label}: unresolved parent`);
2691
+ }
2692
+ if (!owned.has(`${parent.type}.${parent.label}`))
1699
2693
  throw new EntityTfError(`${task.type}.${task.label}: unresolved parent`);
1700
2694
  if (parent.path.length > 0 && !(parent.type === "elementum_for_each_task" && parent.path.length === 1 && parent.path[0] === "inner")) {
1701
2695
  throw new EntityTfError(`${task.type}.${task.label}: unsupported parent path`);
1702
2696
  }
1703
2697
  }
1704
2698
  const appTfLabel = app.label;
2699
+ const dataBlocks = new Map(doc.blocks.filter((block) => block.kind === "data" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
1705
2700
  const taskByAddress = new Map(tasks.map((block) => [`${block.type}.${block.label}`, { block, refKey: taskRefKey(block, automationLabel, appTfLabel) }]));
2701
+ const adoptionAddressAliases = [...taskByAddress.entries()].flatMap(([from, { block, refKey }]) => {
2702
+ if (block.type !== "elementum_variable_task" ||
2703
+ typeof block.attrs.variable_name !== "string" ||
2704
+ block.attrs.variable_name === "")
2705
+ return [];
2706
+ const to = `${block.type}.${taskTfLabel(automationLabel, refKey)}`;
2707
+ return to === from ? [] : [{ from, to }];
2708
+ });
1706
2709
  const taskTargetOwnerRefNameByAddress = new Map();
1707
2710
  for (const [address, { block }] of taskByAddress) {
1708
- const ownerRefName = aspectOwnerRefNameFromObjectId(block.attrs.object_id, appRefName, appTfLabel);
2711
+ const ownerRefName = aspectOwnerRefNameFromObjectId(block.attrs.object_id, appRefName, appTfLabel, dataBlocks, foreignAppRefNames, foreignElementRefNames);
1709
2712
  if (ownerRefName !== undefined)
1710
2713
  taskTargetOwnerRefNameByAddress.set(address, ownerRefName);
1711
2714
  }
@@ -1728,9 +2731,9 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1728
2731
  fieldById.set(id, {
1729
2732
  key: scopedLabelToBagKey(appTfLabel, block.label ?? ""),
1730
2733
  name: typeof block.attrs.name === "string" ? block.attrs.name : block.label,
2734
+ resourceType: block.type,
1731
2735
  });
1732
2736
  }
1733
- const dataBlocks = new Map(doc.blocks.filter((block) => block.kind === "data" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
1734
2737
  const stagesByKey = new Map();
1735
2738
  const stagesAttr = resourceBlocks.get(`elementum_app.${app.label}`)?.attrs["stages"];
1736
2739
  if (Array.isArray(stagesAttr)) {
@@ -1757,6 +2760,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1757
2760
  ...(taskTargetOwnerRefNameByAddress.size > 0 && { taskTargetOwnerRefNameByAddress }),
1758
2761
  ...(foreignAppRefNames !== undefined && { foreignAppRefNames }),
1759
2762
  ...(foreignElementRefNames !== undefined && { foreignElementRefNames }),
2763
+ ...(procedureKeysByDiscriminator !== undefined && { procedureKeysByDiscriminator }),
1760
2764
  };
1761
2765
  let serviceAccountName;
1762
2766
  const serviceAccountValue = automation.attrs.service_account_id;
@@ -1781,16 +2785,54 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1781
2785
  if (publish && Array.isArray(publish.attrs.depends_on))
1782
2786
  publish.attrs.depends_on.forEach((dep, index) => { const ref = resourceRef(dep); if (ref)
1783
2787
  dependencyOrder.set(`${ref.type}.${ref.label}`, index); });
2788
+ const triggerAddress = `${trigger.type}.${trigger.label}`;
2789
+ const unrebuildableTasks = [];
2790
+ // edk#821: resolve each elementum_unmanaged_task_reference this automation's
2791
+ // OWN tasks actually parent onto (never the whole doc's data blocks - a
2792
+ // sibling automation sharing this export can have its own, edk#785) to its
2793
+ // real position, and merge it into the same address space real tasks live
2794
+ // in so its downstream chain lands in the right switch case / forkJoin
2795
+ // branch / forEach body instead of being hoisted to the automation's top level.
2796
+ const ownedAddresses = new Set([
2797
+ triggerAddress,
2798
+ ...tasks.map((t) => `${t.type}.${t.label}`),
2799
+ ...ownedBranches.map((b) => `${b.type}.${b.label}`),
2800
+ ]);
2801
+ const unmanagedTaskPositions = new Map();
2802
+ const placeholderTasks = [];
2803
+ for (const task of tasks) {
2804
+ const unmanagedRef = unmanagedTaskRef(task.attrs.parent);
2805
+ if (unmanagedRef === undefined)
2806
+ continue;
2807
+ const address = `elementum_unmanaged_task_reference.${unmanagedRef.label}`;
2808
+ if (unmanagedTaskPositions.has(address))
2809
+ continue;
2810
+ const dataBlock = dataBlocks.get(address);
2811
+ const position = dataBlock !== undefined ? resolveUnmanagedTaskPosition(dataBlock, triggerAddress, ownedAddresses) : undefined;
2812
+ if (dataBlock === undefined || position === undefined)
2813
+ continue; // falls back to parentAddress's trigger-anchor + diagnostic
2814
+ unmanagedTaskPositions.set(address, position);
2815
+ const refKey = typeof dataBlock.attrs.name === "string" && dataBlock.attrs.name !== "" ? dataBlock.attrs.name : tfLabelToTsLabel(dataBlock.label ?? "task");
2816
+ taskByAddress.set(address, { block: dataBlock, refKey });
2817
+ placeholderTasks.push({
2818
+ name: refKey,
2819
+ taskType: typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown",
2820
+ });
2821
+ }
1784
2822
  const childrenByParent = new Map();
1785
2823
  for (const task of tasks) {
1786
- const parent = parentAddress(task);
2824
+ const parent = parentAddress(task, triggerAddress, unmanagedTaskPositions, (b) => unrebuildableTasks.push(`${b.type}.${b.label}`));
1787
2825
  childrenByParent.set(parent, [...(childrenByParent.get(parent) ?? []), task]);
1788
2826
  }
2827
+ for (const [address, position] of unmanagedTaskPositions) {
2828
+ const dataBlock = taskByAddress.get(address).block;
2829
+ childrenByParent.set(position, [...(childrenByParent.get(position) ?? []), dataBlock]);
2830
+ }
1789
2831
  for (const list of childrenByParent.values())
1790
2832
  list.sort((a, b) => (dependencyOrder.get(`${a.type}.${a.label}`) ?? Number.MAX_SAFE_INTEGER) - (dependencyOrder.get(`${b.type}.${b.label}`) ?? Number.MAX_SAFE_INTEGER) || a.label.localeCompare(b.label));
1791
2833
  const visiting = new Set();
1792
2834
  const visited = new Set();
1793
- const buildTasks = (parent) => (childrenByParent.get(parent) ?? []).flatMap((block) => {
2835
+ const buildTasks = (parent) => (childrenByParent.get(parent) ?? []).flatMap((block, siblingIndex) => {
1794
2836
  const address = `${block.type}.${block.label}`;
1795
2837
  if (visiting.has(address))
1796
2838
  throw new EntityTfError(`cycle detected at ${address}`);
@@ -1805,14 +2847,15 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1805
2847
  children = [{ label: null, tasks: buildTasks(`${address}.inner`) }];
1806
2848
  if (factory === "switchTask" || factory === "forkJoin") {
1807
2849
  const branchAttr = factory === "switchTask" ? "switch_task" : "fork_join_task";
2850
+ const previousAttr = factory === "switchTask" ? "previous_case_id" : "previous_branch_id";
1808
2851
  const matching = ownedBranches.filter((branch) => references(branch.attrs[branchAttr], block.type, block.label));
1809
- matching.sort((a, b) => (dependencyOrder.get(`${a.type}.${a.label}`) ?? Number.MAX_SAFE_INTEGER) - (dependencyOrder.get(`${b.type}.${b.label}`) ?? Number.MAX_SAFE_INTEGER) || a.label.localeCompare(b.label));
1810
- children = matching.map((branch) => {
2852
+ const ordered = orderBranchesByPreviousLink(matching, previousAttr, dependencyOrder);
2853
+ children = ordered.map((branch) => {
1811
2854
  const shape = factory === "switchTask" ? defaultSwitchShape(branch) : undefined;
1812
2855
  const isDefault = shape !== undefined;
1813
2856
  const rawLabel = typeof branch.attrs.label === "string" ? branch.attrs.label : undefined;
1814
2857
  return {
1815
- label: isDefault ? null : rawLabel ?? null,
2858
+ ...(isDefault ? { label: null, isDefault: true } : rawLabel !== undefined ? { label: rawLabel } : {}),
1816
2859
  // ei always writes SOME display label on the default case, but it's
1817
2860
  // not always the literal string "Default" (e.g. a manual rename to
1818
2861
  // "Default Path") - carry the real text so the printer/build round
@@ -1829,20 +2872,41 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1829
2872
  });
1830
2873
  }
1831
2874
  const parent = resourceRef(block.attrs.parent);
1832
- const parentTask = parent === undefined ? undefined : taskByAddress.get(`${parent.type}.${parent.label}`);
1833
- const hclParent = parent?.type === trigger.type && parent?.label === trigger.label ? "trigger" : parentTask?.refKey;
1834
- const call = { factory, refKey, args: taskArgs(block, factory, ctx), ...(children ? { children } : {}), ...(typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {}), ...(hclParent !== undefined ? { hclParent } : {}) };
2875
+ const unmanagedParentRef = parent === undefined ? unmanagedTaskRef(block.attrs.parent) : undefined;
2876
+ const parentTask = parent !== undefined
2877
+ ? taskByAddress.get(`${parent.type}.${parent.label}`)
2878
+ : unmanagedParentRef !== undefined
2879
+ ? taskByAddress.get(`elementum_unmanaged_task_reference.${unmanagedParentRef.label}`)
2880
+ : undefined;
2881
+ // A sole/first child of its real parent is exactly what buildTasks's own
2882
+ // recursion already prints immediately after that parent, so an explicit
2883
+ // anchor is redundant with implicit sequential chaining - only a 2nd+
2884
+ // sibling sharing the same real parent is actually ambiguous without one.
2885
+ const hclParent = siblingIndex === 0
2886
+ ? undefined
2887
+ : parent?.type === trigger.type && parent?.label === trigger.label ? "trigger" : parentTask?.refKey;
2888
+ const args = factory === "unimplementedTask"
2889
+ ? {
2890
+ id: typeof block.attrs.id === "string" ? block.attrs.id : "",
2891
+ taskType: typeof block.attrs.task_type === "string" ? block.attrs.task_type : "",
2892
+ }
2893
+ : taskArgs(block, factory, ctx);
2894
+ const call = { factory, refKey, args, ...(children ? { children } : {}), ...(typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {}), ...(hclParent !== undefined ? { hclParent } : {}) };
1835
2895
  visiting.delete(address);
1836
2896
  return [call, ...buildTasks(address)];
1837
2897
  });
1838
2898
  const topTasks = buildTasks(`${trigger.type}.${trigger.label}`);
1839
- if (visited.size !== tasks.length)
2899
+ if (visited.size !== tasks.length + unmanagedTaskPositions.size)
1840
2900
  throw new EntityTfError(`automation "${automationLabel}" contains an orphaned task graph`);
1841
2901
  const outputBlocks = publish?.attrs.outputs;
1842
2902
  const outputs = Array.isArray(outputBlocks) ? outputBlocks.map((output) => {
1843
2903
  if (!isObject(output) || typeof output.name !== "string" || output.value === undefined)
1844
2904
  throw new EntityTfError("invalid workflow output");
1845
- return { name: output.name, value: decodeValue(output.value, ctx) };
2905
+ // Export/provider Read emit jsonencode({fieldType, taskReference, ...});
2906
+ // collapse that envelope to a RefExpr the same way filter references do.
2907
+ const value = decodeFilterReferenceEnvelope(output.value, ctx, output.name)
2908
+ ?? decodeValue(output.value, ctx);
2909
+ return { name: output.name, value };
1846
2910
  }) : undefined;
1847
2911
  const exportedRevision = publish?.attrs.workflow_revision;
1848
2912
  if (exportedRevision !== undefined && typeof exportedRevision !== "string") {
@@ -1862,10 +2926,19 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1862
2926
  };
1863
2927
  return {
1864
2928
  refName: scopedLabelToBagKey(appTfLabel, automationLabel),
1865
- tfLabel: automationLabel, ast, blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])]
2929
+ tfLabel: automationLabel,
2930
+ ast,
2931
+ blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])],
2932
+ adoptionAddressAliases,
2933
+ ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0) && {
2934
+ diagnostics: [
2935
+ ...unrebuildableTasks.map((address) => `automation "${automationLabel}": ${address}'s real parent is a task type EDK doesn't support yet, so its authored position couldn't be reconstructed (anchored to the trigger instead) - not rebuildable from this source until that task type is supported`),
2936
+ ...placeholderTasks.map(({ name, taskType }) => `automation "${automationLabel}" uses platform task type "${taskType}" ("${name}"), which EDK doesn't implement - kept as an unimplementedTask(...) placeholder; its configuration isn't authorable, but its position and downstream chain are round-trip-safe`),
2937
+ ],
2938
+ }),
1866
2939
  };
1867
2940
  }
1868
- export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth) {
2941
+ export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh) {
1869
2942
  if (Array.isArray(first)) {
1870
2943
  const ctx = second;
1871
2944
  const automationBlock = first.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE);
@@ -1873,9 +2946,10 @@ export function automationFromTf(first, second, third, fourth, fifth, sixth, sev
1873
2946
  return { skippedReason: "automation resource not found" };
1874
2947
  }
1875
2948
  try {
1876
- return {
1877
- automation: automationFromTfDocument({ blocks: [...first] }, automationBlock.label, ctx.ownerHandle, ctx.foreignFieldRefsById, ctx.foreignFieldRefsByDataAddress, ctx.foreignTableRefsById, ctx.picklistOptionLabelById, ctx.fieldNamesByOwnerRefName, ctx.foreignAppRefNames, ctx.foreignElementRefNames).ast,
1878
- };
2949
+ const result = automationFromTfDocument({ blocks: [...first] }, automationBlock.label, ctx.ownerHandle, ctx.foreignFieldRefsById, ctx.foreignFieldRefsByDataAddress, ctx.foreignTableRefsById, ctx.picklistOptionLabelById, ctx.fieldNamesByOwnerRefName, ctx.foreignAppRefNames, ctx.foreignElementRefNames, ctx.procedureKeysByDiscriminator);
2950
+ if (result.diagnostics)
2951
+ ctx.diagnostics.push(...result.diagnostics);
2952
+ return { automation: result.ast };
1879
2953
  }
1880
2954
  catch (err) {
1881
2955
  const message = err instanceof Error ? err.message : String(err);
@@ -1883,5 +2957,5 @@ export function automationFromTf(first, second, third, fourth, fifth, sixth, sev
1883
2957
  return { skippedReason: message };
1884
2958
  }
1885
2959
  }
1886
- return automationFromTfDocument(first, second, third ?? "", fourth, fifth, sixth, seventh, eighth, ninth, tenth);
2960
+ return automationFromTfDocument(first, second, third ?? "", fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh);
1887
2961
  }