@elementumai/edk 0.11.0 → 0.13.0

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 (222) hide show
  1. package/README.md +40 -6
  2. package/dist-sdk/src/catalog/factories.d.ts +7 -1
  3. package/dist-sdk/src/catalog/factories.js +2 -0
  4. package/dist-sdk/src/catalog/index.d.ts +2 -2
  5. package/dist-sdk/src/catalog/index.js +1 -1
  6. package/dist-sdk/src/catalog/org.js +79 -34
  7. package/dist-sdk/src/catalog/token.js +5 -0
  8. package/dist-sdk/src/catalog/types.d.ts +7 -1
  9. package/dist-sdk/src/catalog/types.js +3 -0
  10. package/dist-sdk/src/core/system-fields.d.ts +1 -1
  11. package/dist-sdk/src/core/system-fields.js +1 -1
  12. package/dist-sdk/src/core/triggers/on-demand.d.ts +2 -0
  13. package/dist-sdk/src/core/triggers/on-demand.js +3 -0
  14. package/dist-sdk/src/core/types/app.d.ts +6 -0
  15. package/dist-sdk/src/engine/build/context.d.ts +3 -0
  16. package/dist-sdk/src/engine/coverage-gaps.d.ts +5 -0
  17. package/dist-sdk/src/engine/coverage-gaps.js +9 -0
  18. package/dist-sdk/src/engine/ei/run.d.ts +20 -1
  19. package/dist-sdk/src/engine/ei/run.js +102 -14
  20. package/dist-sdk/src/engine/pull/authored-address.js +42 -6
  21. package/dist-sdk/src/engine/pull/authored-root.d.ts +88 -0
  22. package/dist-sdk/src/engine/pull/authored-root.js +306 -0
  23. package/dist-sdk/src/engine/pull/context.d.ts +10 -0
  24. package/dist-sdk/src/engine/pull/field-refs-registry.d.ts +114 -0
  25. package/dist-sdk/src/engine/pull/field-refs-registry.js +501 -0
  26. package/dist-sdk/src/engine/pull/org.d.ts +1 -0
  27. package/dist-sdk/src/engine/pull/org.js +2 -0
  28. package/dist-sdk/src/engine/pull/partition.d.ts +8 -0
  29. package/dist-sdk/src/engine/pull/partition.js +43 -0
  30. package/dist-sdk/src/engine/pull/pulled-roots.d.ts +89 -0
  31. package/dist-sdk/src/engine/pull/pulled-roots.js +203 -0
  32. package/dist-sdk/src/engine/pull/ref-only.d.ts +22 -0
  33. package/dist-sdk/src/engine/pull/ref-only.js +59 -1
  34. package/dist-sdk/src/engine/pull/source-resources.d.ts +39 -0
  35. package/dist-sdk/src/engine/pull/source-resources.js +110 -0
  36. package/dist-sdk/src/engine/pull/stream-root.d.ts +148 -0
  37. package/dist-sdk/src/engine/pull/stream-root.js +563 -0
  38. package/dist-sdk/src/engine/workspace/reserved-catalog-keys.d.ts +47 -0
  39. package/dist-sdk/src/engine/workspace/reserved-catalog-keys.js +115 -0
  40. package/dist-sdk/src/entities/access-policy/build.d.ts +2 -1
  41. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +9 -1
  42. package/dist-sdk/src/entities/access-policy/from-tf.js +25 -4
  43. package/dist-sdk/src/entities/access-policy/module.js +5 -0
  44. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +19 -0
  45. package/dist-sdk/src/entities/access-policy/to-tf.js +65 -8
  46. package/dist-sdk/src/entities/agent/build.d.ts +52 -1
  47. package/dist-sdk/src/entities/agent/build.js +34 -0
  48. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +68 -0
  49. package/dist-sdk/src/entities/agent/from-tf.d.ts +34 -1
  50. package/dist-sdk/src/entities/agent/from-tf.js +262 -2
  51. package/dist-sdk/src/entities/agent/index.d.ts +1 -1
  52. package/dist-sdk/src/entities/agent/to-tf.d.ts +8 -10
  53. package/dist-sdk/src/entities/agent/to-tf.js +158 -14
  54. package/dist-sdk/src/entities/agent-tool/from-tf.js +6 -0
  55. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +2 -2
  56. package/dist-sdk/src/entities/agent-tool/to-tf.js +2 -2
  57. package/dist-sdk/src/entities/app/build.d.ts +34 -14
  58. package/dist-sdk/src/entities/app/build.js +93 -16
  59. package/dist-sdk/src/entities/app/from-tf.js +25 -11
  60. package/dist-sdk/src/entities/app/index.d.ts +1 -0
  61. package/dist-sdk/src/entities/app/index.js +1 -0
  62. package/dist-sdk/src/entities/app/module.js +1 -0
  63. package/dist-sdk/src/entities/app/stage-keys.d.ts +20 -5
  64. package/dist-sdk/src/entities/app/stage-keys.js +43 -9
  65. package/dist-sdk/src/entities/app/to-tf.js +2 -0
  66. package/dist-sdk/src/entities/approval-chain/build.d.ts +46 -11
  67. package/dist-sdk/src/entities/approval-chain/build.js +120 -8
  68. package/dist-sdk/src/entities/approval-chain/from-tf.d.ts +24 -2
  69. package/dist-sdk/src/entities/approval-chain/from-tf.js +148 -6
  70. package/dist-sdk/src/entities/approval-chain/index.d.ts +4 -1
  71. package/dist-sdk/src/entities/approval-chain/index.js +4 -1
  72. package/dist-sdk/src/entities/approval-chain/module.js +23 -5
  73. package/dist-sdk/src/entities/approval-chain/printer.d.ts +1 -1
  74. package/dist-sdk/src/entities/approval-chain/printer.js +91 -5
  75. package/dist-sdk/src/entities/approval-chain/steps-tf.d.ts +77 -0
  76. package/dist-sdk/src/entities/approval-chain/steps-tf.js +255 -0
  77. package/dist-sdk/src/entities/approval-chain/steps.d.ts +71 -0
  78. package/dist-sdk/src/entities/approval-chain/steps.js +83 -0
  79. package/dist-sdk/src/entities/approval-chain/to-tf.d.ts +16 -6
  80. package/dist-sdk/src/entities/approval-chain/to-tf.js +37 -4
  81. package/dist-sdk/src/entities/automation/build.d.ts +50 -24
  82. package/dist-sdk/src/entities/automation/build.js +86 -33
  83. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +52 -8
  84. package/dist-sdk/src/entities/automation/from-tf.d.ts +38 -6
  85. package/dist-sdk/src/entities/automation/from-tf.js +855 -157
  86. package/dist-sdk/src/entities/automation/index.d.ts +2 -1
  87. package/dist-sdk/src/entities/automation/index.js +1 -0
  88. package/dist-sdk/src/entities/automation/module.d.ts +4 -3
  89. package/dist-sdk/src/entities/automation/module.js +33 -12
  90. package/dist-sdk/src/entities/automation/refs-read.d.ts +19 -0
  91. package/dist-sdk/src/entities/automation/refs-read.js +48 -0
  92. package/dist-sdk/src/entities/automation/run-target.d.ts +2 -0
  93. package/dist-sdk/src/entities/automation/run-target.js +5 -0
  94. package/dist-sdk/src/entities/automation/script-code.d.ts +2 -1
  95. package/dist-sdk/src/entities/automation/script-code.js +82 -1
  96. package/dist-sdk/src/entities/automation/script-lint.d.ts +13 -0
  97. package/dist-sdk/src/entities/automation/script-lint.js +418 -0
  98. package/dist-sdk/src/entities/automation/slack-message-refs.d.ts +9 -0
  99. package/dist-sdk/src/entities/automation/slack-message-refs.js +75 -0
  100. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +12 -1
  101. package/dist-sdk/src/entities/automation/task-output-labels.js +32 -1
  102. package/dist-sdk/src/entities/automation/tasks.d.ts +76 -18
  103. package/dist-sdk/src/entities/automation/tasks.js +52 -15
  104. package/dist-sdk/src/entities/automation/to-tf.d.ts +3 -0
  105. package/dist-sdk/src/entities/automation/to-tf.js +585 -97
  106. package/dist-sdk/src/entities/automation/triggers.d.ts +48 -23
  107. package/dist-sdk/src/entities/automation/triggers.js +27 -12
  108. package/dist-sdk/src/entities/automation/unsafe-script-output.d.ts +50 -0
  109. package/dist-sdk/src/entities/automation/unsafe-script-output.js +92 -0
  110. package/dist-sdk/src/entities/chart/build.d.ts +18 -2
  111. package/dist-sdk/src/entities/chart/from-tf.d.ts +2 -2
  112. package/dist-sdk/src/entities/chart/from-tf.js +28 -1
  113. package/dist-sdk/src/entities/chart/index.d.ts +1 -1
  114. package/dist-sdk/src/entities/chart/printer.js +5 -2
  115. package/dist-sdk/src/entities/chart/to-tf.js +38 -3
  116. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +3 -0
  117. package/dist-sdk/src/entities/dynamic-layout/condition-keys.d.ts +48 -0
  118. package/dist-sdk/src/entities/dynamic-layout/condition-keys.js +261 -0
  119. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +45 -6
  120. package/dist-sdk/src/entities/dynamic-layout/module.js +2 -1
  121. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +46 -12
  122. package/dist-sdk/src/entities/element/audit-field-guard.d.ts +9 -0
  123. package/dist-sdk/src/entities/element/audit-field-guard.js +88 -0
  124. package/dist-sdk/src/entities/element/build.js +2 -1
  125. package/dist-sdk/src/entities/element/from-tf.js +15 -2
  126. package/dist-sdk/src/entities/element/module.js +3 -0
  127. package/dist-sdk/src/entities/element/system-fields.d.ts +13 -0
  128. package/dist-sdk/src/entities/element/system-fields.js +23 -0
  129. package/dist-sdk/src/entities/element/to-tf.js +2 -0
  130. package/dist-sdk/src/entities/field/build.d.ts +9 -0
  131. package/dist-sdk/src/entities/field/from-tf.d.ts +29 -1
  132. package/dist-sdk/src/entities/field/from-tf.js +99 -6
  133. package/dist-sdk/src/entities/field/module.js +12 -2
  134. package/dist-sdk/src/entities/field/to-tf.d.ts +13 -3
  135. package/dist-sdk/src/entities/field/to-tf.js +90 -46
  136. package/dist-sdk/src/entities/org/category.js +1 -0
  137. package/dist-sdk/src/entities/org/index.d.ts +1 -0
  138. package/dist-sdk/src/entities/org/index.js +1 -0
  139. package/dist-sdk/src/entities/org/role.js +5 -0
  140. package/dist-sdk/src/entities/org/voice-auth.d.ts +5 -0
  141. package/dist-sdk/src/entities/org/voice-auth.js +33 -0
  142. package/dist-sdk/src/entities/organization/build.d.ts +3 -0
  143. package/dist-sdk/src/entities/organization/build.js +2 -0
  144. package/dist-sdk/src/entities/organization/index.d.ts +1 -0
  145. package/dist-sdk/src/entities/organization/index.js +1 -0
  146. package/dist-sdk/src/entities/organization/to-tf.d.ts +2 -0
  147. package/dist-sdk/src/entities/organization/to-tf.js +59 -1
  148. package/dist-sdk/src/entities/organization/voice-auth.d.ts +60 -0
  149. package/dist-sdk/src/entities/organization/voice-auth.js +60 -0
  150. package/dist-sdk/src/entities/phone-service/build.d.ts +9 -1
  151. package/dist-sdk/src/entities/phone-service/build.js +1 -0
  152. package/dist-sdk/src/entities/phone-service/deserializer/print-phone-service.js +3 -0
  153. package/dist-sdk/src/entities/phone-service/from-tf.d.ts +1 -0
  154. package/dist-sdk/src/entities/phone-service/from-tf.js +8 -1
  155. package/dist-sdk/src/entities/phone-service/to-tf.js +16 -0
  156. package/dist-sdk/src/entities/record-create-form/from-tf.js +2 -2
  157. package/dist-sdk/src/entities/relationship/from-tf.js +7 -2
  158. package/dist-sdk/src/entities/relationship/module.js +2 -2
  159. package/dist-sdk/src/entities/relationship/pair-check.d.ts +6 -2
  160. package/dist-sdk/src/entities/relationship/pair-check.js +105 -18
  161. package/dist-sdk/src/entities/relationship/to-tf.js +5 -2
  162. package/dist-sdk/src/entities/role/permission-levels.d.ts +7 -0
  163. package/dist-sdk/src/entities/role/permission-levels.js +78 -0
  164. package/dist-sdk/src/entities/role/to-tf.js +32 -2
  165. package/dist-sdk/src/entities/service-account/module.d.ts +2 -1
  166. package/dist-sdk/src/entities/service-account/module.js +9 -1
  167. package/dist-sdk/src/entities/service-account/resource-type.d.ts +2 -0
  168. package/dist-sdk/src/entities/service-account/resource-type.js +2 -0
  169. package/dist-sdk/src/entities/service-account/role-fidelity.d.ts +5 -5
  170. package/dist-sdk/src/entities/service-account/role-fidelity.js +21 -13
  171. package/dist-sdk/src/entities/service-account/role-membership-check.d.ts +20 -0
  172. package/dist-sdk/src/entities/service-account/role-membership-check.js +80 -0
  173. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +15 -0
  174. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +36 -0
  175. package/dist-sdk/src/entities/shared/filters/ast.d.ts +4 -0
  176. package/dist-sdk/src/entities/shared/filters/index.d.ts +85 -14
  177. package/dist-sdk/src/entities/shared/filters/index.js +18 -6
  178. package/dist-sdk/src/entities/shared/filters/option-lookups.d.ts +57 -0
  179. package/dist-sdk/src/entities/shared/filters/option-lookups.js +108 -0
  180. package/dist-sdk/src/entities/shared/filters/print.js +9 -5
  181. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +12 -7
  182. package/dist-sdk/src/entities/shared/filters/tf-codec.js +9 -5
  183. package/dist-sdk/src/entities/shared/raw-option-id.d.ts +30 -0
  184. package/dist-sdk/src/entities/shared/raw-option-id.js +41 -0
  185. package/dist-sdk/src/entities/shared/tool-field-ref.js +6 -2
  186. package/dist-sdk/src/entities/shared/types/field-types.d.ts +6 -3
  187. package/dist-sdk/src/entities/shared/types/field-types.js +3 -1
  188. package/dist-sdk/src/entities/skill/input-coverage.js +5 -2
  189. package/dist-sdk/src/entities/skill/module.js +2 -0
  190. package/dist-sdk/src/entities/sla/build.d.ts +96 -0
  191. package/dist-sdk/src/entities/sla/build.js +124 -0
  192. package/dist-sdk/src/entities/sla/from-tf.d.ts +40 -0
  193. package/dist-sdk/src/entities/sla/from-tf.js +164 -0
  194. package/dist-sdk/src/entities/sla/index.d.ts +1 -0
  195. package/dist-sdk/src/entities/sla/index.js +1 -0
  196. package/dist-sdk/src/entities/sla/module.d.ts +4 -0
  197. package/dist-sdk/src/entities/sla/module.js +73 -0
  198. package/dist-sdk/src/entities/sla/printer.d.ts +2 -0
  199. package/dist-sdk/src/entities/sla/printer.js +84 -0
  200. package/dist-sdk/src/entities/sla/to-tf.d.ts +12 -0
  201. package/dist-sdk/src/entities/sla/to-tf.js +81 -0
  202. package/dist-sdk/src/entities/table/build.d.ts +7 -2
  203. package/dist-sdk/src/entities/table/build.js +22 -1
  204. package/dist-sdk/src/entities/table/deserializer/normalize.d.ts +4 -1
  205. package/dist-sdk/src/entities/table/from-tf.js +89 -14
  206. package/dist-sdk/src/entities/table/index.d.ts +1 -1
  207. package/dist-sdk/src/entities/table/to-tf.js +41 -2
  208. package/dist-sdk/src/entities/task/from-tf.js +2 -1
  209. package/dist-sdk/src/entities/task/to-tf.js +1 -0
  210. package/dist-sdk/src/entities/view/from-tf.d.ts +8 -4
  211. package/dist-sdk/src/entities/view/from-tf.js +10 -9
  212. package/dist-sdk/src/entities/view/module.js +5 -0
  213. package/dist-sdk/src/entities/widget/from-tf.js +15 -4
  214. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +51 -4
  215. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  216. package/dist-sdk/src/graph/index.d.ts +20 -2
  217. package/dist-sdk/src/graph/index.js +19 -0
  218. package/dist-sdk/src/graph/modules.js +11 -1
  219. package/dist-sdk/src/graph/resource-types.d.ts +47 -0
  220. package/dist-sdk/src/graph/resource-types.js +62 -0
  221. package/dist-sdk/src/graph/types.d.ts +116 -6
  222. package/package.json +6 -3
@@ -1,4 +1,5 @@
1
1
  import { USER_FIELD_KEYS, USER_GROUP_FIELD_KEYS } from "../../catalog/types.js";
2
+ import { RECORD_ID_REFERENCE_FIELD } from "./task-output-labels.js";
2
3
  import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET, SYSTEM_FIELD_KEYS } from "../../core/system-fields.js";
3
4
  import { normalizeOnDemandParamKey } from "../../../pull/util.js";
4
5
  import { EntityTfError } from "../../engine/entity.js";
@@ -8,7 +9,7 @@ import { appResourceLabelPrefix, childPartFromScopedLabel, elementResourceLabelP
8
9
  import { SUB_TYPE_BY_RESOURCE } from "../field/types.js";
9
10
  import { IMPLEMENTED_FILE_READER_RESOURCE_TYPES } from "../file-reader/types.js";
10
11
  import { connectorIdentityFromTf } from "../shared/connector-from-tf.js";
11
- import { fieldTypeToValueType } from "../shared/filters/index.js";
12
+ import { fieldTypeToValueType, textOption } from "../shared/filters/index.js";
12
13
  import { UNRESOLVED_FIELD_MARKER } from "../shared/ref.js";
13
14
  import { filterFromTf as deserializeFilterFromTf } from "../shared/filters/tf-codec.js";
14
15
  import { TABLE_RESOURCE_TYPE } from "../table/module.js";
@@ -18,8 +19,9 @@ import { apiTaskRefAuthoringPath, executeScriptAuthoringPath, matchesOutputWireK
18
19
  import { RESOURCE_TYPE_TO_EXECUTOR, TASK_OUTPUT_CONTRACTS } from "./generated/task-output-contracts.js";
19
20
  import { systemRefNameRoundTrips } from "./system-ref-name.js";
20
21
  import { taskTfLabel } from "./task-label.js";
21
- import { parseTriggerAttachmentPayloadRefJson, parseTriggerWholeRecordRefJson, TRIGGER_WHOLE_RECORD_REF_NAME } from "./task-output-labels.js";
22
+ import { parseTriggerAttachmentPayloadRefJson, parseTriggerWholeRecordRefJson, TASK_OUTPUT_REFERENCE_NAMES, TRIGGER_WHOLE_RECORD_REF_NAME } from "./task-output-labels.js";
22
23
  import { workflowOutputTypeFromFieldType } from "./workflow-output.js";
24
+ import { slackMessageTriggerPathFromWire } from "./slack-message-refs.js";
23
25
  import { ALL_AUTOMATION_TASK_TYPE_SET, AUTOMATION_BRANCH_TYPE_SET, AUTOMATION_RESOURCE_TYPE, AUTOMATION_TRIGGER_TYPE_SET, WEBHOOK_REQUEST_REF_PATTERN, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
24
26
  const TRIGGER_KINDS = {
25
27
  elementum_record_created_trigger: "recordCreate",
@@ -334,15 +336,23 @@ const TRIGGER_ATTRIBUTES = new Set([
334
336
  "frequency", "interval", "timezone", "start_at", "weekdays", "day_of_month",
335
337
  "end_at", "ends_after_count", "interval_unit",
336
338
  "aspect_field_id", "temporal_unit", "value",
339
+ // Build-derived from the owner's field order and never printed (edk#2280).
340
+ "object_field_ids",
341
+ // Build-derived from the owner's fields and never printed (edk#2438).
342
+ "object_fields",
343
+ "object_system_field_ids",
344
+ // Build-derived from the refs keys the automation reads (edk#2648).
345
+ "refs_read",
337
346
  ]);
338
347
  const TASK_ATTRIBUTES = new Set([
339
- "parent", "name", "depends_on", "filter", "fields", "inputs", "output_schema",
348
+ "parent", "name", "depends_on", "object_field_ids", "object_fields", "object_system_field_ids", "refs_read", "filter", "fields", "inputs", "output_schema",
340
349
  "list", "code", "variables", "updates", "variable", "value",
341
350
  "object_id", "table_id", "record_reference", "record_id", "source_record_ids",
342
351
  "approval_process_id", "requester_reference", "approver_references", "reason", "summary",
343
352
  "approval_reference", "status",
344
353
  "target_record_id", "message", "message_body", "body", "from_username",
345
- "from_personal", "external_emails", "users", "groups", "attachments", "contents",
354
+ "from_personal", "external_emails", "users", "groups", "attachments", "email_attachments",
355
+ "email_send_domain_id", "contents",
346
356
  "agent_id", "prompt", "output_type", "json_fields", "ai_provider_connector_id",
347
357
  "url", "response_type", "continue_on_error", "search_table_id",
348
358
  "text_to_summarize", "text_to_classify", "field_type", "category_source", "dynamic_category_source",
@@ -350,7 +360,7 @@ const TASK_ATTRIBUTES = new Set([
350
360
  "fields_to_lock", "fields_to_unlock", "file", "file_id", "attachment", "attachment_id", "view_state", "target_automation_id",
351
361
  "target_automation_ref", "input_mappings", "dynamic_input_mappings",
352
362
  "output_mappings", "file_reader_id", "raw_text", "procedure_id",
353
- "calculations", "categories", "limit", "sort", "tag", "tags", "context", "length",
363
+ "calculations", "categories", "limit", "sort", "tag", "tags", "context", "length", "dimensions",
354
364
  "subject", "phone_service_id", "phone_number", "default_language", "first_message",
355
365
  "synchronous", "cloudlink_id", "stored_function_id",
356
366
  "relate_to_record_reference", "method", "parameters", "headers",
@@ -381,14 +391,6 @@ function appRef(appRefName) {
381
391
  const WIRE_REF_SEGMENT_TO_TS = {
382
392
  "Changed Fields": "changedFieldIds",
383
393
  "Iteration": "iteration",
384
- "Slack Thread ID": "slackThreadId",
385
- "Slack Channel ID": "slackChannelId",
386
- "Message Author Email": "messageAuthorEmail",
387
- "Message Author ID": "messageAuthorId",
388
- "Message Author Name": "messageAuthorName",
389
- "Message Content": "messageContent",
390
- "Message ID": "messageId",
391
- "Message Metadata": "messageMetadata",
392
394
  };
393
395
  const ON_DEMAND_TRIGGERED_BY_FROM_WIRE = {
394
396
  "Triggered By's Id": ["triggeredBy", "id"],
@@ -444,7 +446,60 @@ function recordFieldRefPath(wireName, ctx, ownerRefName = ctx.appRefName, rootNa
444
446
  }
445
447
  }
446
448
  const systemPath = systemFieldRefPath(wireName);
447
- return systemPath === undefined ? undefined : [rootName, ...systemPath];
449
+ if (systemPath === undefined)
450
+ return undefined;
451
+ // A leftover default wire name after a Title/Handle/Status rename must not
452
+ // decode as the typed key: build would emit the new name (#2671 N1).
453
+ const systemKey = systemPath[0];
454
+ if (ownerRefName === ctx.appRefName &&
455
+ systemKey !== undefined &&
456
+ renamedSystemFieldKey(systemKey, ctx)) {
457
+ return undefined;
458
+ }
459
+ return [rootName, ...systemPath];
460
+ }
461
+ /** Whether the owner renamed this system field away from its deploy default. */
462
+ function renamedSystemFieldKey(key, ctx) {
463
+ if (key === "title")
464
+ return ctx.titleFieldName !== undefined;
465
+ if (key === "id")
466
+ return ctx.idFieldName !== undefined;
467
+ if (key === "status")
468
+ return ctx.statusFieldName !== undefined;
469
+ return false;
470
+ }
471
+ /** Current display name of a renamable system field on the automation owner. */
472
+ function currentRenamableSystemName(key, ctx) {
473
+ if (key === "title")
474
+ return ctx.titleFieldName ?? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES.title;
475
+ if (key === "id")
476
+ return ctx.idFieldName ?? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES.id;
477
+ return ctx.statusFieldName ?? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES.status;
478
+ }
479
+ /**
480
+ * Map a renamed Title/Handle/Status display name to its fixed key. Only the
481
+ * rename attributes match positively; Title wins when its rename equals
482
+ * Handle/Status's current name (e.g. Title renamed to "ID"). An id/status
483
+ * rename that collides with another renamable's current name is refused (#2671 S1).
484
+ */
485
+ function renamableSystemFieldKeyByDisplayName(displayNameLower, ctx) {
486
+ const fromAttrs = [];
487
+ if (ctx.titleFieldName?.toLowerCase() === displayNameLower)
488
+ fromAttrs.push("title");
489
+ if (ctx.idFieldName?.toLowerCase() === displayNameLower)
490
+ fromAttrs.push("id");
491
+ if (ctx.statusFieldName?.toLowerCase() === displayNameLower)
492
+ fromAttrs.push("status");
493
+ if (fromAttrs.length === 0)
494
+ return undefined;
495
+ if (fromAttrs.includes("title"))
496
+ return "title";
497
+ for (const key of fromAttrs) {
498
+ const collides = ["title", "id", "status"].some((other) => other !== key && currentRenamableSystemName(other, ctx).toLowerCase() === displayNameLower);
499
+ if (!collides)
500
+ return key;
501
+ }
502
+ return undefined;
448
503
  }
449
504
  function systemFieldPathRoundTrips(fieldKey, wireSuffix, wireName) {
450
505
  return !SYSTEM_FIELD_KEY_SET.has(fieldKey) ||
@@ -513,7 +568,9 @@ function declaredOnDemandInputFieldType(trigger, wireName) {
513
568
  return undefined;
514
569
  return {
515
570
  // Inverse of to-tf's on-demand parameter type spelling.
516
- fieldType: parameter.type === "attachment" ? "ATTACHMENT_ID" : parameter.type.toUpperCase(),
571
+ fieldType: parameter.type === "attachment" ? "ATTACHMENT_ID"
572
+ : parameter.type === "group" ? "GROUP_ID"
573
+ : parameter.type.toUpperCase(),
517
574
  multiple: parameter.multiple === true,
518
575
  };
519
576
  }
@@ -593,9 +650,12 @@ export const AI_SEARCH_TABLE_TASK_REF_SEGMENT_TO_TS = {
593
650
  // proxy at build time and omits the script/filter input entirely.
594
651
  export const TABLE_RECORDS_SEARCH_TASK_REF_SEGMENT_TO_TS = {
595
652
  // Canonical count output `count` → the `totalCount` accessor (edk#835 — same
596
- // as recordSearch). "All matching table rows" is the legacy display form.
653
+ // as recordSearch).
597
654
  count: "totalCount",
655
+ // The refs keys a deployed task has (edk#2407, task-output-labels.ts).
598
656
  "All matching table rows": "records",
657
+ "First matching table row": "record",
658
+ "Row count": "totalCount",
599
659
  };
600
660
  // Platform-fixed output labels → authoring path, inverse of
601
661
  // task-output-labels.ts and executeScript's "Text Result". Scoped per task
@@ -604,6 +664,8 @@ const TASK_OUTPUT_LABEL_TO_TS = {
604
664
  elementum_record_search_task: { "First found record": ["record"] },
605
665
  elementum_create_record_task: { "Created record": ["record"] },
606
666
  elementum_update_field_task: { "Updated record": ["record"] },
667
+ // Build indexes bulkUpdateFields outputs by these display-label refs keys (edk#2281).
668
+ elementum_bulk_update_fields_task: Object.fromEntries(Object.entries(TASK_OUTPUT_REFERENCE_NAMES["elementum_bulk_update_fields_task"] ?? {}).map(([key, name]) => [key, [name]])),
607
669
  elementum_execute_script_task: {
608
670
  // Display keys. Canonical `result` / `stringArrayResult` are not refs keys;
609
671
  // `Result` is the whole JSON envelope, not a property named Result (#1656).
@@ -742,6 +804,8 @@ function findRelatedRecordsFieldPath(wireName, taskAddress, ctx) {
742
804
  const kind = taskAddress !== undefined
743
805
  ? ctx.taskTargetOwnerKindByAddress?.get(taskAddress)
744
806
  : undefined;
807
+ if (wireName === "All found records")
808
+ return ["records"];
745
809
  const lower = wireName.toLowerCase();
746
810
  if (kind === "app" && (lower === "title" || lower === "id")) {
747
811
  return ["record", "id"];
@@ -758,8 +822,19 @@ function lookupFieldKeyByDisplayName(ownerRefName, displayName, ctx) {
758
822
  if (field.name.toLowerCase() === lower)
759
823
  return field.key;
760
824
  }
825
+ // Renamed Title/Handle/Status have no field blocks; build keys them by
826
+ // their fixed keys (#2650, #2671 S1). Title wins when its rename collides
827
+ // with Handle/Status's current name (e.g. Title renamed to "ID").
828
+ const renamedKey = renamableSystemFieldKeyByDisplayName(lower, ctx);
829
+ if (renamedKey !== undefined)
830
+ return renamedKey;
761
831
  }
832
+ const ownerRenames = ownerRefName === ctx.appRefName;
762
833
  for (const key of SYSTEM_FIELD_KEYS) {
834
+ // Skip defaults for fields this owner renamed; systemFieldRefPath is gated
835
+ // the same way so trigger refs honor it too (#2671 N1).
836
+ if (ownerRenames && renamedSystemFieldKey(key, ctx))
837
+ continue;
763
838
  if (DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[key].toLowerCase() === lower)
764
839
  return key;
765
840
  }
@@ -906,13 +981,52 @@ function decodeFieldAssignmentValue(value, ctx, diagnostics, where = "field assi
906
981
  if (Array.isArray(value)) {
907
982
  return value.map((item) => decodeFieldAssignmentValue(item, ctx, diagnostics, where));
908
983
  }
909
- if (typeof value === "string" && /^[a-f0-9-]{36}$/i.test(value)) {
910
- const label = ctx.picklistOptionLabelById?.get(value);
911
- if (label !== undefined)
912
- return { kind: "literal", value: label };
913
- }
914
984
  return decodeValueOrStringifiedRef(value, ctx, diagnostics, where);
915
985
  }
986
+ /**
987
+ * A Dropdown or Multi-Select assignment's option, printed as
988
+ * `filter.textOption(label)`, the one spelling build accepts there (#1733).
989
+ * Export holds an option id as its options-by-label lookup and Read keeps the
990
+ * label, so either decodes to a label here. A label the field no longer lists
991
+ * keeps the selection too, and build names it. A raw id becomes its label only
992
+ * when it is one of this field's current options (#2568); any other id stays
993
+ * as written and warns, so the building agent can pick a current option. That
994
+ * holds for another app's or element's field too: its id must be one of the
995
+ * options state lists for that field, and its label one of the field's
996
+ * reference options when the reference carries them (#2592, #2596). `raw` is
997
+ * the exported field id and value, which name a foreign field's options. The
998
+ * "" clear stays as written. Any field without static options, record-sourced
999
+ * Dropdowns included, keeps its value.
1000
+ */
1001
+ function assignmentOptionValue(value, field, raw, ctx, diagnostics, where) {
1002
+ const ownLabels = optionLabelsForDecodedField(field, ctx);
1003
+ const foreignLabels = ownLabels === undefined ? foreignOptionIdLabels(raw.fieldId, raw.value, field, ctx) : undefined;
1004
+ if (ownLabels === undefined && foreignLabels === undefined)
1005
+ return value;
1006
+ const optionLabel = (id) => {
1007
+ if (foreignLabels === undefined)
1008
+ return decodedFieldOptionLabel(id, field, ctx);
1009
+ const label = foreignFieldOptionLabel(id, field, ctx);
1010
+ return label !== undefined && foreignLabels.has(label) ? label : undefined;
1011
+ };
1012
+ const decode = (item) => {
1013
+ if (Array.isArray(item))
1014
+ return item.map(decode);
1015
+ const text = isObject(item) && item.kind === "literal" ? item.value : item;
1016
+ if (typeof text !== "string" || text === "")
1017
+ return item;
1018
+ if (!isUuid(text))
1019
+ return textOption(text);
1020
+ const label = optionLabel(text);
1021
+ if (label !== undefined)
1022
+ return textOption(label);
1023
+ const warning = unknownOptionIdWarning(where, text, field, ctx, foreignLabels !== undefined);
1024
+ if (warning !== undefined)
1025
+ diagnostics.push(warning);
1026
+ return item;
1027
+ };
1028
+ return decode(value);
1029
+ }
916
1030
  const VALUE_REFERENCE_KEYS = ["taskReference", "triggerReference", "variableReference"];
917
1031
  /**
918
1032
  * edk#1646: ei's exporter falls back to a stringified wire ValueReference
@@ -1106,12 +1220,18 @@ function canonicalTriggerRecordIdSlot(value, ctx) {
1106
1220
  value.kind === "triggerRef" &&
1107
1221
  Array.isArray(value.path) &&
1108
1222
  ((value.path.length === 1 && value.path[0] === "recordId") ||
1109
- (value.path.length === 2 && value.path[0] === "record" && value.path[1] === "10000001-2000-4000-a000-800000000000"))) {
1223
+ (value.path.length === 2 && value.path[0] === "record" && value.path[1] === RECORD_ID_REFERENCE_FIELD))) {
1110
1224
  return { ...value, path: ["record"] };
1111
1225
  }
1112
1226
  return value;
1113
1227
  }
1114
1228
  function triggerRefPath(path, ctx) {
1229
+ // Slack message keys ("Message Content" -> content) are mapped only on that
1230
+ // trigger, so a field or task output with the same display name elsewhere
1231
+ // keeps its own path (#2581).
1232
+ const slackPath = slackTriggerPath(path.map((segment) => typeof segment === "string" ? segment : segment.index), ctx);
1233
+ if (slackPath !== undefined)
1234
+ return slackPath;
1115
1235
  const names = pathNames(path);
1116
1236
  if (names.length !== 1)
1117
1237
  return names;
@@ -1207,12 +1327,89 @@ function triggerRefPath(path, ctx) {
1207
1327
  return names;
1208
1328
  return recordFieldRefPath(wireName, ctx) ?? names;
1209
1329
  }
1330
+ // Top-level properties the record trigger outputs declare (RecordTriggerOutput,
1331
+ // AttachmentTriggerOutput, CommentAddedTriggerOutput in triggers.ts).
1332
+ const RECORD_TRIGGER_OUTPUT_HEADS = new Set(["record", "changedFieldIds", "attachment", "comment"]);
1333
+ const UNDECLARED_HEAD_TRIGGER_TYPES = new Set([
1334
+ "elementum_record_created_trigger",
1335
+ "elementum_record_updated_trigger",
1336
+ "elementum_attachment_added_trigger",
1337
+ "elementum_comment_added_trigger",
1338
+ "elementum_approval_chain_trigger",
1339
+ ]);
1340
+ /**
1341
+ * A record trigger ref whose single name matches no field or declared output
1342
+ * (an unknown name, or a group-qualified key such as
1343
+ * "Record Update Trigger - Record Type"). The output type has no index
1344
+ * signature, so pull prints it through an `as any` escape (#2643).
1345
+ */
1346
+ function undeclaredRecordTriggerHead(path, ctx) {
1347
+ return UNDECLARED_HEAD_TRIGGER_TYPES.has(ctx.trigger.type ?? "") && path.length === 1 && !RECORD_TRIGGER_OUTPUT_HEADS.has(path[0]);
1348
+ }
1210
1349
  function forEachItemOwnerRefName(loop, ctx) {
1211
1350
  const collection = loop === undefined ? undefined : resourceRef(loop.attrs.list);
1212
1351
  return collection === undefined ? undefined : ctx.taskTargetOwnerRefNameByAddress?.get(`${collection.type}.${collection.label}`);
1213
1352
  }
1353
+ /**
1354
+ * The tf label of a record loop's collection owner, from the source task's
1355
+ * `object_id` (`elementum_app.<label>.id` / `elementum_element.<label>.id`).
1356
+ * Build names that owner's system-field ids `local.<label>_<field>_field_id`
1357
+ * (calculationFieldScope), which may be another in-workspace aspect.
1358
+ */
1359
+ function forEachItemOwnerTfLabel(loop, ctx) {
1360
+ const collection = resourceRef(loop.attrs.list);
1361
+ const source = collection === undefined ? undefined : ctx.taskByAddress.get(`${collection.type}.${collection.label}`);
1362
+ const objectId = (source?.block.attrs.object_id ?? null);
1363
+ if (!isTfExpr(objectId) || objectId.$expr !== "resource-attr" ||
1364
+ (objectId.type !== "elementum_app" && objectId.type !== "elementum_element") || objectId.path[0] !== "id") {
1365
+ return undefined;
1366
+ }
1367
+ return objectId.label;
1368
+ }
1369
+ /** Build's sentinel for a record's own id decodes to the typed `recordId`, at any depth. */
1370
+ function recordIdSegments(segments) {
1371
+ return segments.map((segment) => segment === RECORD_ID_REFERENCE_FIELD ? "recordId" : segment);
1372
+ }
1373
+ /**
1374
+ * The item field key behind a `for_each.<id>.${<field id>}` filter path. A
1375
+ * system field's id is a local named by the collection owner's tf label, which
1376
+ * is not this automation's app when the loop reads another aspect's records;
1377
+ * decodeValue only knows this app's prefix and would throw for the whole
1378
+ * automation, so locals resolve here against the owner first.
1379
+ */
1380
+ function forEachItemFieldKey(fieldPart, loop, ctx) {
1381
+ if (fieldPart.$expr === "local") {
1382
+ if (!fieldPart.name.endsWith("_field_id"))
1383
+ return undefined;
1384
+ const ownerLabel = forEachItemOwnerTfLabel(loop, ctx) ?? ctx.appTfLabel;
1385
+ const prefix = `${ownerLabel}_`;
1386
+ return fieldPart.name.startsWith(prefix)
1387
+ ? tfLabelToTsLabel(fieldPart.name.slice(prefix.length, -"_field_id".length))
1388
+ : undefined;
1389
+ }
1390
+ try {
1391
+ const field = fieldRef(fieldPart, ctx);
1392
+ if (field.kind === "field")
1393
+ return field.fieldKey;
1394
+ }
1395
+ catch (error) {
1396
+ if (!(error instanceof EntityTfError))
1397
+ throw error;
1398
+ }
1399
+ return fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx);
1400
+ }
1214
1401
  function forEachItemRefPath(path, ctx, loop) {
1215
1402
  const names = pathNames(path);
1403
+ const itemOwner = forEachItemOwnerRefName(loop, ctx);
1404
+ if (itemOwner !== undefined && names[0] !== undefined && isUuid(names[0])) {
1405
+ // Provider/filter export uses the actual field ID; script inputs use a
1406
+ // refs-map display name. Both spellings must print the same typed path.
1407
+ if (names.length === 1 && names[0] === RECORD_ID_REFERENCE_FIELD)
1408
+ return ["recordId"];
1409
+ const fieldKey = resolveFieldKeyFromId(names[0], itemOwner, ctx);
1410
+ if (fieldKey !== undefined)
1411
+ return [fieldKey, ...recordIdSegments(names.slice(1))];
1412
+ }
1216
1413
  if (names.length !== 1)
1217
1414
  return names.flatMap((segment) => segment.split("."));
1218
1415
  const wireName = names[0];
@@ -1222,7 +1419,6 @@ function forEachItemRefPath(path, ctx, loop) {
1222
1419
  if (wireName === "Record")
1223
1420
  return ["recordId"];
1224
1421
  const wireNameLower = wireName.toLowerCase();
1225
- const itemOwner = forEachItemOwnerRefName(loop, ctx);
1226
1422
  const ownFields = itemOwner === undefined || itemOwner === ctx.appRefName ? ctx.fieldById.values() : [];
1227
1423
  for (const field of ownFields) {
1228
1424
  // Some provider paths already contain the stable EDK field key (for
@@ -1236,6 +1432,14 @@ function forEachItemRefPath(path, ctx, loop) {
1236
1432
  }
1237
1433
  }
1238
1434
  }
1435
+ if (itemOwner !== undefined) {
1436
+ // A record collection can belong to a different app/element. Resolve
1437
+ // its refs-map display names through that owner's catalog, just as
1438
+ // build does, rather than printing a foreign label as an item key.
1439
+ const recordPath = recordFieldRefPath(wireName, ctx, itemOwner);
1440
+ if (recordPath !== undefined)
1441
+ return recordPath.slice(1);
1442
+ }
1239
1443
  return systemFieldRefPath(wireName) ?? names.flatMap((segment) => segment.split("."));
1240
1444
  }
1241
1445
  function resolveTaskRefKey(taskIdOrKey, ctx) {
@@ -1406,10 +1610,17 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
1406
1610
  : keyPath;
1407
1611
  return { kind: "taskRef", task: refKey, path: outputKeyPath };
1408
1612
  }
1613
+ /** A Slack message trigger reference's accessor path; undefined on any other trigger. */
1614
+ function slackTriggerPath(path, ctx) {
1615
+ return ctx.trigger.type === "elementum_slack_message_trigger" ? slackMessageTriggerPathFromWire(path) : undefined;
1616
+ }
1409
1617
  function decodeReferenceString(value, ctx) {
1410
1618
  const pieces = value.split(".");
1411
1619
  if (pieces[0] === "trigger" && pieces.length > 1) {
1412
1620
  const path = pieces.slice(1);
1621
+ const slackPath = slackTriggerPath(path, ctx);
1622
+ if (slackPath !== undefined)
1623
+ return { kind: "triggerRef", path: slackPath };
1413
1624
  const declaredInput = path.length === 1 ? declaredOnDemandInputForWireName(ctx.trigger, path[0]) : undefined;
1414
1625
  if (declaredInput !== undefined)
1415
1626
  return { kind: "triggerRef", path: [declaredInput] };
@@ -1500,7 +1711,7 @@ function decodeTemplateTriggerRecordFieldRef(value, ctx) {
1500
1711
  if (fieldKey === undefined)
1501
1712
  return undefined;
1502
1713
  const suffix = suffixPart === undefined ? [] : suffixPart.replace(/^\./, "").split(".").filter((s) => s.length > 0);
1503
- if (suffix.length === 1 && suffix[0] === "10000001-2000-4000-a000-800000000000") {
1714
+ if (suffix.length === 1 && suffix[0] === RECORD_ID_REFERENCE_FIELD) {
1504
1715
  return { kind: "triggerRef", path: [root, fieldKey, "recordId"] };
1505
1716
  }
1506
1717
  return { kind: "triggerRef", path: [root, fieldKey, ...suffix] };
@@ -1568,7 +1779,7 @@ function templateRecordFieldPath(parts, taskBlock, ctx) {
1568
1779
  function decodeTemplateForEachRef(value, ctx) {
1569
1780
  if (!isTfExpr(value) || value.$expr !== "template")
1570
1781
  return undefined;
1571
- const [prefix, idPart, suffixPart] = value.parts;
1782
+ const [prefix, idPart, suffixPart, fieldPart, fieldSuffix, ...rest] = mergeAdjacentTemplateStrings(value.parts);
1572
1783
  if (prefix !== "for_each." || idPart === undefined || typeof idPart === "string")
1573
1784
  return undefined;
1574
1785
  if (typeof suffixPart !== "string" || !suffixPart.startsWith("."))
@@ -1578,6 +1789,17 @@ function decodeTemplateForEachRef(value, ctx) {
1578
1789
  const task = ctx.taskByAddress.get(`${idPart.type}.${idPart.label}`);
1579
1790
  if (task === undefined)
1580
1791
  return undefined;
1792
+ if (suffixPart === "." && fieldPart !== undefined && typeof fieldPart !== "string") {
1793
+ if (rest.length > 0 || (fieldSuffix !== undefined && (typeof fieldSuffix !== "string" || !fieldSuffix.startsWith("."))))
1794
+ return undefined;
1795
+ const fieldKey = forEachItemFieldKey(fieldPart, task.block, ctx);
1796
+ if (fieldKey === undefined)
1797
+ return undefined;
1798
+ const suffix = (fieldSuffix ?? "").split(".").filter((part) => part.length > 0);
1799
+ return { kind: "forEachItemRef", forEachTask: task.refKey, path: [fieldKey, ...recordIdSegments(suffix)] };
1800
+ }
1801
+ if (fieldPart !== undefined)
1802
+ return undefined;
1581
1803
  const nameParts = suffixPart.slice(1).split(".").filter((segment) => segment.length > 0);
1582
1804
  if (nameParts.length === 0 && suffixPart !== ".")
1583
1805
  return undefined;
@@ -1816,7 +2038,10 @@ function decodeValue(value, ctx) {
1816
2038
  if (optionLabel !== undefined)
1817
2039
  return { kind: "literal", value: optionLabel };
1818
2040
  if (value.type === ctx.trigger.type && value.label === ctx.trigger.label && value.path[0] === "refs") {
1819
- return { kind: "triggerRef", path: triggerRefPath(value.path.slice(1), ctx) };
2041
+ const path = triggerRefPath(value.path.slice(1), ctx);
2042
+ return (undeclaredRecordTriggerHead(path, ctx)
2043
+ ? { kind: "triggerRef", path, undeclaredHead: true }
2044
+ : { kind: "triggerRef", path });
1820
2045
  }
1821
2046
  const task = ctx.taskByAddress.get(`${value.type}.${value.label}`);
1822
2047
  if (task !== undefined && value.path[0] === "inner" && value.path[1] === "refs") {
@@ -2211,7 +2436,17 @@ function decodeValue(value, ctx) {
2211
2436
  if (typeof name !== "string" || name === "") {
2212
2437
  throw new EntityTfError(`data.elementum_group.${value.label}: name lookup is missing`);
2213
2438
  }
2214
- const groupKey = ctx.groupKeysByName?.get(name) ?? tfLabelToTsLabel(sanitizeName(name));
2439
+ const orgKey = ctx.groupKeysByName?.get(name);
2440
+ if (orgKey === undefined && ctx.groupKeysByName !== undefined) {
2441
+ // The org catalog this pull loaded doesn't carry this group: org.ts
2442
+ // predates it, or org.ts is missing or failed to import (the pull
2443
+ // then passes an empty map). A guessed org.groups key would be
2444
+ // undefined at load and fail the build (edk#2241): print a by-name
2445
+ // groupRef, which builds to the same data.elementum_group lookup.
2446
+ ctx.groupsMissingFromOrg?.add(name);
2447
+ return { kind: "orgGroup", groupKey: tfLabelToTsLabel(sanitizeName(name)), name, inOrgCatalog: false };
2448
+ }
2449
+ const groupKey = orgKey ?? tfLabelToTsLabel(sanitizeName(name));
2215
2450
  return { kind: "orgGroup", groupKey, name };
2216
2451
  }
2217
2452
  if (value.$expr === "variable") {
@@ -2410,37 +2645,20 @@ function labelsFromOptions(value) {
2410
2645
  return labels.size > 0 ? labels : undefined;
2411
2646
  }
2412
2647
  /**
2413
- * Option labels build can turn back into an options-by-label local for this
2414
- * field id expression. A reference to another task's record is not a field
2415
- * id, and a stub without options cannot be reversed (#2099).
2648
+ * The static Dropdown or Multi-Select block a filter's field id expression
2649
+ * names. A reference to another task's record is not a field id, and app
2650
+ * status options are not read here (#2099, #2568).
2416
2651
  */
2417
- function optionLabelsForFieldIdExpr(value, blocks) {
2652
+ function picklistBlockForFieldIdExpr(value, blocks) {
2418
2653
  if (!isTfExpr(value))
2419
2654
  return undefined;
2420
2655
  if (value.$expr === "resource-attr" && value.type.endsWith("_field") && value.path[0] === "id") {
2421
2656
  const block = blocks.get(`${value.type}.${value.label}`);
2422
- if (block?.type !== "elementum_dropdown_field" && block?.type !== "elementum_multiselect_field")
2423
- return undefined;
2424
- return labelsFromOptions(block.attrs.options);
2425
- }
2426
- if ((value.$expr === "resource-attr" || value.$expr === "data-attr") &&
2427
- (value.type === "elementum_app" || value.type === "elementum_element") &&
2428
- value.path[0] === "status_field_id") {
2429
- return labelsFromOptions(blocks.get(`${value.type}.${value.label}`)?.attrs.status_options);
2657
+ return isPicklistFieldBlock(block) ? block : undefined;
2430
2658
  }
2431
2659
  if (value.$expr === "local" && value.name.endsWith("_field_id")) {
2432
- const ownerAndField = value.name.slice(0, -"_field_id".length);
2433
- if (ownerAndField.endsWith("_status")) {
2434
- const owner = ownerAndField.slice(0, -"_status".length);
2435
- const block = blocks.get(`elementum_app.${owner}`) ?? blocks.get(`elementum_element.${owner}`);
2436
- return labelsFromOptions(block?.attrs.status_options);
2437
- }
2438
- for (const block of blocks.values()) {
2439
- if (block.type !== "elementum_dropdown_field" && block.type !== "elementum_multiselect_field")
2440
- continue;
2441
- if (block.label === ownerAndField)
2442
- return labelsFromOptions(block.attrs.options);
2443
- }
2660
+ const fieldLabel = value.name.slice(0, -"_field_id".length);
2661
+ return [...blocks.values()].find((block) => isPicklistFieldBlock(block) && block.label === fieldLabel);
2444
2662
  }
2445
2663
  return undefined;
2446
2664
  }
@@ -2448,46 +2666,247 @@ function optionLabelsForDecodedField(field, ctx) {
2448
2666
  if (!isObject(field) || field.kind !== "field" || typeof field.fieldKey !== "string")
2449
2667
  return undefined;
2450
2668
  const ownerHandle = typeof field.appHandle === "string" ? field.appHandle : ctx.appRefName;
2451
- if (field.fieldKey === "status") {
2452
- const ownerBlock = ownerHandle === ctx.appRefName
2453
- ? ctx.resourceBlocks.get(`${ctx.ownerScope === "element" ? "elementum_element" : "elementum_app"}.${ctx.appTfLabel}`)
2454
- : [...ctx.resourceBlocks.values()].find((block) => (block.type === "elementum_app" || block.type === "elementum_element") &&
2455
- block.label !== undefined &&
2456
- tfLabelToTsLabel(block.label) === ownerHandle);
2457
- return labelsFromOptions(ownerBlock?.attrs.status_options);
2669
+ const statusLabels = systemStatusLabels(field, ctx);
2670
+ if (statusLabels !== undefined)
2671
+ return statusLabels;
2672
+ const labels = new Set();
2673
+ for (const block of picklistBlocksForDecodedField(field, ctx))
2674
+ collectOptionLabels(labels, block.attrs.options);
2675
+ // The app's system stage: its value decodes from stage_ids_by_key to the
2676
+ // stage name, and build reads that name as a static option (#1733).
2677
+ if (labels.size === 0 && field.fieldKey === "stage" && ownerHandle === ctx.appRefName && ctx.ownerScope === "app") {
2678
+ for (const name of ctx.stagesByKey.values())
2679
+ labels.add(name);
2680
+ }
2681
+ return labels.size > 0 ? labels : undefined;
2682
+ }
2683
+ /** True when `handle` is a ref name this pull already bound to an element or task. */
2684
+ function refMapNames(map, handle) {
2685
+ if (map === undefined)
2686
+ return false;
2687
+ if (map.has(handle))
2688
+ return true;
2689
+ for (const refName of map.values()) {
2690
+ if (refName === handle)
2691
+ return true;
2692
+ }
2693
+ return false;
2694
+ }
2695
+ /**
2696
+ * A plain string on a foreign field is that app's system stage name.
2697
+ * Elements and tasks have no system stage. A picklist type is not enough:
2698
+ * a record-sourced Dropdown is `PICKLIST` and has no static options.
2699
+ */
2700
+ function foreignStageName(field, ctx, systemStage) {
2701
+ if (field.fieldKey !== "stage")
2702
+ return false;
2703
+ const meta = isObject(field.foreign) ? field.foreign : undefined;
2704
+ const entityType = typeof meta?.entityType === "string" ? meta.entityType : undefined;
2705
+ if (entityType === "element" || entityType === "task")
2706
+ return false;
2707
+ if (entityType !== "app" || meta?.ownerKindUnknown === true) {
2708
+ const handle = typeof field.appHandle === "string" ? field.appHandle : undefined;
2709
+ if (handle === undefined || refMapNames(ctx.foreignElementRefNames, handle) || refMapNames(ctx.foreignTaskRefNames, handle))
2710
+ return false;
2458
2711
  }
2712
+ if (systemStage)
2713
+ return true;
2714
+ // A foreign field whose metadata has neither a type nor a name.
2715
+ const fieldType = typeof meta?.fieldType === "string" ? meta.fieldType : undefined;
2716
+ const fieldName = typeof meta?.fieldName === "string" ? meta.fieldName : undefined;
2717
+ return fieldType === undefined && fieldName === undefined;
2718
+ }
2719
+ /**
2720
+ * A raw field id whose registry entry is the system Stage. Those entries come
2721
+ * from system-field state: the key is `stage` and there is no field type.
2722
+ * The display name is recorded too, so its presence is not a custom field.
2723
+ */
2724
+ function rawIdSystemStage(fieldId, ctx) {
2725
+ if (typeof fieldId !== "string")
2726
+ return false;
2727
+ const identity = ctx.foreignFieldRefsById?.get(fieldId);
2728
+ return identity !== undefined && identity.fieldKey === "stage" && identity.fieldType === undefined;
2729
+ }
2730
+ /** The strings inside a field assignment, including a Multi-Select `jsonencode([...])`. */
2731
+ function foreignAssignmentItems(value) {
2732
+ if (isTfExpr(value) && value.$expr === "jsonencode")
2733
+ return foreignAssignmentItems(value.value);
2734
+ if (Array.isArray(value))
2735
+ return value.flatMap((item) => foreignAssignmentItems(item));
2736
+ return [value];
2737
+ }
2738
+ /**
2739
+ * The option labels of another app's or element's field. A non-recursive
2740
+ * export carries no field resource for it: the static options on its
2741
+ * reference, else the current options state lists for that same field
2742
+ * (#2568). A plain string is a stage name only for the system Stage.
2743
+ * Undefined for an own field, a record-sourced Dropdown, or a field with no
2744
+ * known options.
2745
+ */
2746
+ function foreignOptionIdLabels(fieldId, value, field, ctx) {
2747
+ if (!isObject(field) || field.kind !== "field")
2748
+ return undefined;
2749
+ const foreign = field.foreign !== undefined || (typeof field.appHandle === "string" && field.appHandle !== ctx.appRefName);
2750
+ if (!foreign)
2751
+ return undefined;
2752
+ const dataField = isTfExpr(fieldId) && fieldId.$expr === "data-attr"
2753
+ ? ctx.foreignFieldRefsByDataAddress?.get(`${fieldId.type}.${fieldId.label}`)
2754
+ : undefined;
2755
+ if (dataField?.options !== undefined && dataField.options.length > 0)
2756
+ return new Set(dataField.options);
2757
+ const stateOptions = foreignFieldStateOptions(field, ctx);
2758
+ if (stateOptions.length > 0)
2759
+ return new Set(stateOptions.flatMap((options) => [...options.values()]));
2760
+ const systemStage = dataField?.systemStage === true || rawIdSystemStage(fieldId, ctx);
2459
2761
  const labels = new Set();
2460
- for (const block of ctx.resourceBlocks.values()) {
2461
- if ((block.type !== "elementum_dropdown_field" && block.type !== "elementum_multiselect_field") || block.label === undefined)
2762
+ for (const item of foreignAssignmentItems(value)) {
2763
+ if (typeof item === "string" && item !== "" && !isUuid(item) && foreignStageName(field, ctx, systemStage))
2764
+ labels.add(item);
2765
+ }
2766
+ return labels.size > 0 ? labels : undefined;
2767
+ }
2768
+ /**
2769
+ * The current options state lists for another app's or element's field: the
2770
+ * picklist resources whose scoped label names that owner and field key
2771
+ * (#2568). Empty when this org's state does not manage that field.
2772
+ */
2773
+ function foreignFieldStateOptions(field, ctx) {
2774
+ if (!isObject(field) || field.kind !== "field" || typeof field.fieldKey !== "string" || typeof field.appHandle !== "string")
2775
+ return [];
2776
+ const out = [];
2777
+ for (const [label, options] of ctx.picklistOptionsByField ?? []) {
2778
+ const owner = ownerFromScopedChildLabel(label);
2779
+ if (owner === undefined || tfLabelToTsLabel(owner.ownerTfLabel) !== field.appHandle)
2462
2780
  continue;
2781
+ if (fieldBagKey(label, ctx) === field.fieldKey)
2782
+ out.push(options);
2783
+ }
2784
+ return out;
2785
+ }
2786
+ /** The label of option `id` when state lists it as an option of this foreign field (#2568). */
2787
+ function foreignFieldOptionLabel(id, field, ctx) {
2788
+ for (const options of foreignFieldStateOptions(field, ctx)) {
2789
+ const label = options.get(id);
2790
+ if (label !== undefined)
2791
+ return label;
2792
+ }
2793
+ return undefined;
2794
+ }
2795
+ /**
2796
+ * The owner's system status options, for a field keyed `status`. An element
2797
+ * has no system status, so its field keyed status is its own Dropdown and
2798
+ * this is undefined (#2683).
2799
+ */
2800
+ function systemStatusLabels(field, ctx) {
2801
+ if (!isObject(field) || field.kind !== "field" || field.fieldKey !== "status")
2802
+ return undefined;
2803
+ const ownerHandle = typeof field.appHandle === "string" ? field.appHandle : ctx.appRefName;
2804
+ const ownerBlock = ownerHandle === ctx.appRefName
2805
+ ? ctx.resourceBlocks.get(`${ctx.ownerScope === "element" ? "elementum_element" : "elementum_app"}.${ctx.appTfLabel}`)
2806
+ : [...ctx.resourceBlocks.values()].find((block) => (block.type === "elementum_app" || block.type === "elementum_element") &&
2807
+ block.label !== undefined &&
2808
+ tfLabelToTsLabel(block.label) === ownerHandle);
2809
+ return labelsFromOptions(ownerBlock?.attrs.status_options);
2810
+ }
2811
+ /**
2812
+ * The static Dropdown and Multi-Select blocks in this export that a decoded
2813
+ * field names. An owner's system status (non-empty `status_options`) is not
2814
+ * one of those blocks. An element Dropdown keyed `status` is.
2815
+ */
2816
+ function picklistBlocksForDecodedField(field, ctx) {
2817
+ if (!isObject(field) || field.kind !== "field" || typeof field.fieldKey !== "string")
2818
+ return [];
2819
+ if (systemStatusLabels(field, ctx) !== undefined)
2820
+ return [];
2821
+ const ownerHandle = typeof field.appHandle === "string" ? field.appHandle : ctx.appRefName;
2822
+ return [...ctx.resourceBlocks.values()].filter((block) => {
2823
+ if (!isPicklistFieldBlock(block) || block.label === undefined)
2824
+ return false;
2463
2825
  if (fieldBagKey(block.label, ctx) !== field.fieldKey)
2464
- continue;
2465
- const owned = ownerFromScopedChildLabel(block.label);
2466
- const ownerTf = owned?.ownerTfLabel ?? ctx.appTfLabel;
2467
- if (tfLabelToTsLabel(ownerTf) !== ownerHandle)
2468
- continue;
2469
- collectOptionLabels(labels, block.attrs.options);
2826
+ return false;
2827
+ const ownerTf = ownerFromScopedChildLabel(block.label)?.ownerTfLabel ?? ctx.appTfLabel;
2828
+ return tfLabelToTsLabel(ownerTf) === ownerHandle;
2829
+ });
2830
+ }
2831
+ function isPicklistFieldBlock(block) {
2832
+ return block?.type === "elementum_dropdown_field" || block?.type === "elementum_multiselect_field";
2833
+ }
2834
+ /**
2835
+ * The label of option `id` of this picklist block: state must list `id` as
2836
+ * one of the field's options, and the export must still list its label
2837
+ * (#2568). An id of another field, or a deleted option, has none.
2838
+ */
2839
+ function picklistBlockOptionLabel(id, block, optionsByField) {
2840
+ if (block.label === undefined)
2841
+ return undefined;
2842
+ const label = optionsByField?.get(block.label)?.get(id);
2843
+ return label !== undefined && labelsFromOptions(block.attrs.options)?.has(label) === true ? label : undefined;
2844
+ }
2845
+ /** The compared field's label for option `id`, when `id` is one of its current options (#2568). */
2846
+ function decodedFieldOptionLabel(id, field, ctx) {
2847
+ if (!isUuid(id))
2848
+ return undefined;
2849
+ for (const block of picklistBlocksForDecodedField(field, ctx)) {
2850
+ const label = picklistBlockOptionLabel(id, block, ctx.picklistOptionsByField);
2851
+ if (label !== undefined)
2852
+ return label;
2470
2853
  }
2471
- return labels.size > 0 ? labels : undefined;
2854
+ return undefined;
2472
2855
  }
2473
2856
  /**
2474
- * A filter literal's option id, printed as the label only when the compared
2475
- * field lists that label. Build then writes the options-by-label local.
2476
- * Anything else stays the raw id (#2099).
2857
+ * The pull warning for an assigned option id that is not one of the field's
2858
+ * current options (#2568). Dax, 2026-11-03: "Any bad configuration shouldn't
2859
+ * abort a pull. It should warn so the building agent can suggest a
2860
+ * correction". Undefined for an own field this export does not hold as a
2861
+ * picklist. `foreign` is a field of another app or element that the caller
2862
+ * already knows has static options; its ids are checked against state alone.
2863
+ */
2864
+ function unknownOptionIdWarning(where, id, field, ctx, foreign = false) {
2865
+ const blocks = foreign ? [] : picklistBlocksForDecodedField(field, ctx);
2866
+ if (!foreign && blocks.length === 0)
2867
+ return undefined;
2868
+ const known = foreign
2869
+ ? foreignFieldStateOptions(field, ctx).length > 0
2870
+ : blocks.some((block) => block.label !== undefined && ctx.picklistOptionsByField?.has(block.label) === true);
2871
+ const reason = known
2872
+ ? "is not one of the field's current options (deleted, or an option of another field)"
2873
+ : "cannot be checked because the field's option ids are not in state";
2874
+ return `${where}: option id ${JSON.stringify(id)} ${reason}, so it is kept as the raw id. Select a current option with filter.textOption("<label>")`;
2875
+ }
2876
+ /**
2877
+ * A filter literal's option id, printed as the label only when it is one of
2878
+ * the compared field's current options. Build then writes the
2879
+ * options-by-label local. An id compared with a static picklist field that
2880
+ * is not one of its current options stays the raw id, and pull names it with
2881
+ * the same warning an assignment gets (#2099, #2568).
2477
2882
  */
2478
2883
  function filterOptionLabel(value, field, ctx) {
2479
2884
  if (typeof value !== "string" || !isUuid(value))
2480
2885
  return undefined;
2481
- const label = ctx.picklistOptionLabelById?.get(value);
2482
- if (label === undefined)
2886
+ const label = decodedFieldOptionLabel(value, field, ctx);
2887
+ if (label !== undefined)
2888
+ return label;
2889
+ // A record-sourced Dropdown has no static options, and its values are record
2890
+ // ids, so they get no option warning (the assignment path skips them too).
2891
+ if (optionLabelsForDecodedField(field, ctx) === undefined)
2483
2892
  return undefined;
2484
- return optionLabelsForDecodedField(field, ctx)?.has(label) === true ? label : undefined;
2893
+ const fieldKey = isObject(field) && typeof field.fieldKey === "string" ? field.fieldKey : "?";
2894
+ const warning = unknownOptionIdWarning(`filter on field ${fieldKey}`, value, field, ctx);
2895
+ if (warning !== undefined)
2896
+ ctx.optionIdWarnings?.add(warning);
2897
+ return undefined;
2485
2898
  }
2486
- /** Option ids `filterOptionLabel` will print as labels. The export still holds the id. */
2487
- export function filterOptionIdsPrintedAsLabels(doc, optionLabelById) {
2488
- const resolved = new Set();
2489
- if (optionLabelById === undefined || optionLabelById.size === 0)
2490
- return resolved;
2899
+ /**
2900
+ * Option ids `filterOptionLabel` prints as labels at every filter comparison
2901
+ * that holds them. The export still holds the id. An id that any comparison
2902
+ * keeps raw, on another field or a deleted option, is left out, so its
2903
+ * unresolved-UUID warning is not muted (#2568).
2904
+ */
2905
+ export function filterOptionIdsPrintedAsLabels(doc, optionsByField) {
2906
+ const printed = new Set();
2907
+ const keptRaw = new Set();
2908
+ if (optionsByField === undefined || optionsByField.size === 0)
2909
+ return printed;
2491
2910
  const blocks = new Map();
2492
2911
  for (const block of doc.blocks) {
2493
2912
  if (block.kind !== "resource" || block.type === undefined || block.label === undefined)
@@ -2511,15 +2930,14 @@ export function filterOptionIdsPrintedAsLabels(doc, optionLabelById) {
2511
2930
  value.children.forEach((child) => visit(child));
2512
2931
  return;
2513
2932
  }
2514
- const labels = optionLabelsForFieldIdExpr(fieldId, blocks);
2515
- if (labels === undefined)
2516
- return;
2933
+ const block = picklistBlockForFieldIdExpr(fieldId, blocks);
2517
2934
  const consider = (literal) => {
2518
- if (typeof literal !== "string" || !optionLabelById.has(literal))
2935
+ if (typeof literal !== "string" || !isUuid(literal))
2519
2936
  return;
2520
- const label = optionLabelById.get(literal);
2521
- if (label !== undefined && labels.has(label))
2522
- resolved.add(literal);
2937
+ if (block !== undefined && picklistBlockOptionLabel(literal, block, optionsByField) !== undefined)
2938
+ printed.add(literal);
2939
+ else
2940
+ keptRaw.add(literal);
2523
2941
  };
2524
2942
  if (isObject(value.value))
2525
2943
  consider(value.value.value);
@@ -2540,7 +2958,7 @@ export function filterOptionIdsPrintedAsLabels(doc, optionLabelById) {
2540
2958
  visit(attrValue);
2541
2959
  }
2542
2960
  }
2543
- return resolved;
2961
+ return new Set([...printed].filter((id) => !keptRaw.has(id)));
2544
2962
  }
2545
2963
  function picklistOptionLabel(value) {
2546
2964
  if (value === undefined || !isTfExpr(value))
@@ -2757,16 +3175,11 @@ function decodeCalculationTaskMustache(taskId, wireName, ctx) {
2757
3175
  const keyPath = wireName.split(".");
2758
3176
  const taskKind = taskBlock?.type !== undefined ? TASK_FACTORIES[taskBlock.type] : undefined;
2759
3177
  const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
2760
- // Case-SENSITIVE here, unlike the refs-map/envelope call sites: a
2761
- // calculation mustache carries the calc-engine's own lowercase name
2762
- // (WorkflowTaskReference, e.g. "response"), never the refs-map display
2763
- // key ("Response") - calculationTaskMustache already documents that the
2764
- // display label does not resolve in this dialect. Case-folding this site
2765
- // too made "response" fold to "output" (correct) but ALSO folded any
2766
- // other lowercase wire name that happens to match a wireOutputKey
2767
- // case-insensitively, rewriting the mustache as {{task name="Response"}}
2768
- // on the next build - a key the calc engine's real API never has either.
2769
- const outputKeyPath = wireOutputKey !== undefined && keyPath[0] === wireOutputKey
3178
+ // A calculation mustache names a single-output AI task's output by the calc
3179
+ // engine's canonical name (`response`), not the refs label (`Response`).
3180
+ // Both read back as `output`, which build writes as `response` (#2405).
3181
+ // Only the exact or lowercased wire key matches, as in the refs decoder.
3182
+ const outputKeyPath = wireOutputKey !== undefined && keyPath[0] !== undefined && matchesOutputWireKey(keyPath[0], wireOutputKey)
2770
3183
  ? ["output", ...keyPath.slice(1)]
2771
3184
  : keyPath.map((segment) => WIRE_REF_SEGMENT_TO_TS[segment] ?? segment);
2772
3185
  return { kind: "taskRef", task: refKey, path: outputKeyPath };
@@ -2934,13 +3347,34 @@ function workflowOutputTaskIdOrKey(taskId, ctx) {
2934
3347
  }
2935
3348
  function filterReference(value, ctx, role) {
2936
3349
  assertFilterTaskRefResolves(filterReferenceTaskId(value), ctx);
2937
- return typeof value === "string"
3350
+ return markUndeclaredScriptOutput(typeof value === "string"
2938
3351
  ? decodeReferenceString(value, ctx) ?? { kind: "unresolved", uuid: value, hint: "filter-reference" }
2939
3352
  : decodeFilterReferenceEnvelope(value, ctx, undefined, role)
2940
3353
  ?? decodeTemplateTriggerRecordFieldRef(value, ctx)
2941
3354
  ?? decodeTemplateTaskRef(value, ctx)
2942
3355
  ?? decodeTemplateForEachRef(value, ctx)
2943
- ?? decodeValue(value, ctx);
3356
+ ?? decodeValue(value, ctx), ctx);
3357
+ }
3358
+ /**
3359
+ * A filter reference to an execute-script output its schema doesn't declare
3360
+ * (a switch left-value envelope, or a RHS `task.<id>.result.<name>`) prints as
3361
+ * `unsafeScriptOutput(...)`, the only form build accepts in a filter (#1725).
3362
+ */
3363
+ function markUndeclaredScriptOutput(reference, ctx) {
3364
+ if (reference.kind !== "taskRef" || reference.undeclaredScriptOutput === true)
3365
+ return reference;
3366
+ if (reference.path[0] !== "result" || reference.path.length < 2)
3367
+ return reference;
3368
+ const task = resolveTaskRefKey(reference.task, ctx).block;
3369
+ if (task?.type !== "elementum_execute_script_task")
3370
+ return reference;
3371
+ const schemaValue = task.attrs.output_schema;
3372
+ const schema = isTfExpr(schemaValue) && schemaValue.$expr === "jsonencode"
3373
+ ? schemaValue.value
3374
+ : schemaValue;
3375
+ return scriptOutputReferenceIsDeclared(outputFieldTypesFromScriptSchema(schema), reference.path.join("."))
3376
+ ? reference
3377
+ : { ...reference, undeclaredScriptOutput: true };
2944
3378
  }
2945
3379
  /** The platform task id a filter reference names: `task.<id>.<name>`, or an envelope's `taskReference.taskId`. */
2946
3380
  function filterReferenceTaskId(value) {
@@ -3073,8 +3507,22 @@ function decodeFilter(value, ctx, fieldScope = "app") {
3073
3507
  reference: (reference, role) => filterReference(reference, ctx, role),
3074
3508
  referenceType: (reference, fallback) => filterReferenceType(reference, fallback, ctx),
3075
3509
  literal: (literal, _valueType, field) => picklistOptionLabel(literal) ?? stageFilterName(literal, ctx) ?? filterOptionLabel(literal, field, ctx) ?? literal,
3510
+ // A plain string builds as literal text, so a stored option id must print
3511
+ // as `filter.textOption(label)` to build back to that id (#1733).
3512
+ optionLookupsAreIdentities: true,
3076
3513
  }, fieldScope);
3077
3514
  }
3515
+ /**
3516
+ * A Checkbox (`boolean`) input's default. The provider's `default_value` is a
3517
+ * string, so HCL holds "true"/"false"; source authors a boolean (#2204).
3518
+ */
3519
+ function booleanDefault(value) {
3520
+ if (value === "true")
3521
+ return true;
3522
+ if (value === "false")
3523
+ return false;
3524
+ return value;
3525
+ }
3078
3526
  /**
3079
3527
  * A datamine trigger's condition (edk#2287). Pull used to drop it, so the next
3080
3528
  * apply cleared the live condition. It now comes back as source. A condition
@@ -3116,7 +3564,28 @@ function dataMineCondition(raw, datamineTable, ctx) {
3116
3564
  visit(condition);
3117
3565
  return condition;
3118
3566
  }
3119
- function triggerFromBlock(block, ctx) {
3567
+ // default_value is a string attribute, so number and decimal defaults come back quoted ("2").
3568
+ function numericDefault(name, type, value, diagnostics) {
3569
+ if (typeof value !== "string")
3570
+ return value;
3571
+ const decoded = numericLiteral(type, value);
3572
+ if (decoded !== undefined)
3573
+ return decoded;
3574
+ diagnostics.push(`on-demand ${type} parameter "${name}" default ${JSON.stringify(value)} has no exact ${type} literal form, ` +
3575
+ `so it was printed as a string${type === "number" ? ", which build rejects until it is rewritten as an integer" : ""}`);
3576
+ return value;
3577
+ }
3578
+ // Only forms that rebuild to the exact same string, so to-tf's stringified default matches the export.
3579
+ function numericLiteral(type, value) {
3580
+ const pattern = type === "number" ? /^-?\d+$/ : /^-?\d+(\.\d+)?$/;
3581
+ if (!pattern.test(value))
3582
+ return undefined;
3583
+ const decoded = Number(value);
3584
+ if (type === "number" && !Number.isSafeInteger(decoded))
3585
+ return undefined;
3586
+ return String(decoded) === value ? decoded : undefined;
3587
+ }
3588
+ function triggerFromBlock(block, ctx, diagnostics) {
3120
3589
  const kind = TRIGGER_KINDS[block.type];
3121
3590
  if (kind === undefined)
3122
3591
  throw new EntityTfError(`unknown trigger resource type "${block.type}"`);
@@ -3140,10 +3609,12 @@ function triggerFromBlock(block, ctx) {
3140
3609
  // (onDemand's TriggerFieldTypeAlias) does. Map back so printed
3141
3610
  // source uses a type-checkable alias instead of a raw wire string
3142
3611
  // "attachment" that TriggerFieldTypeAlias doesn't accept. The
3143
- // provider's "user" is USER_ID, authored as "userId".
3612
+ // provider's "user" is USER_ID, authored as "userId", and its
3613
+ // "group" is GROUP_ID, authored as "groupId" (#2204).
3144
3614
  const type = parameter.type === "attachment" ? "attachmentId"
3145
3615
  : parameter.type === "user" ? "userId"
3146
- : parameter.type;
3616
+ : parameter.type === "group" ? "groupId"
3617
+ : parameter.type;
3147
3618
  const record = type === "record";
3148
3619
  const recordApp = record
3149
3620
  ? aspectRefFromObjectId(parameter.default_value, ctx)
@@ -3158,7 +3629,10 @@ function triggerFromBlock(block, ctx) {
3158
3629
  ...(parameter.required === true ? { required: true } : {}),
3159
3630
  ...(parameter.multiple === true ? { multiple: true } : {}),
3160
3631
  ...(!record && parameter.default_value !== undefined
3161
- ? { defaultValue: type === "userId" ? userIdDefault(parameter.default_value, ctx) : parameter.default_value }
3632
+ ? { defaultValue: type === "userId" ? userIdDefault(parameter.default_value, ctx)
3633
+ : type === "boolean" ? booleanDefault(parameter.default_value)
3634
+ : type === "number" || type === "decimal" ? numericDefault(parameter.name, type, parameter.default_value, diagnostics)
3635
+ : parameter.default_value }
3162
3636
  : {}),
3163
3637
  ...(typeof parameter.description === "string" ? { description: parameter.description } : {}),
3164
3638
  };
@@ -3284,7 +3758,10 @@ function triggerFromBlock(block, ctx) {
3284
3758
  function taskArgs(block, factory, ctx, taskDiagnostics) {
3285
3759
  const args = {};
3286
3760
  for (const [attr, value] of Object.entries(block.attrs)) {
3287
- if (attr === "parent" || attr === "name" || attr === "depends_on")
3761
+ // object_field_ids is build-derived from the target's field order (edk#2280),
3762
+ // object_fields / object_system_field_ids from the owner's fields (edk#2680 / #2692),
3763
+ // refs_read from the refs keys the automation reads (edk#2648).
3764
+ if (attr === "parent" || attr === "name" || attr === "depends_on" || attr === "object_field_ids" || attr === "object_fields" || attr === "object_system_field_ids" || attr === "refs_read")
3288
3765
  continue;
3289
3766
  if (attr === "filter") {
3290
3767
  const where = `task ${JSON.stringify(typeof block.attrs.name === "string" ? block.attrs.name : block.label)} (${factory})`;
@@ -3310,9 +3787,10 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3310
3787
  ? field.fieldKey
3311
3788
  : `${UNRESOLVED_FIELD_MARKER}${field.uuid}`;
3312
3789
  const decodedValue = decodeFieldAssignmentValue(item.value, ctx, taskDiagnostics, `${block.type}.${block.label} field ${field.kind === "field" ? field.fieldKey : field.uuid}`);
3790
+ const optionValue = assignmentOptionValue(decodedValue, field, { fieldId: item.field_id, value: item.value }, ctx, taskDiagnostics, `${block.type}.${block.label} field ${field.kind === "field" ? field.fieldKey : field.uuid}`);
3313
3791
  const canonicalValue = factory === "createRecord" || factory === "updateField"
3314
- ? canonicalTriggerRecordIdSlot(decodedValue, ctx)
3315
- : decodedValue;
3792
+ ? canonicalTriggerRecordIdSlot(optionValue, ctx)
3793
+ : optionValue;
3316
3794
  const foreignInfo = field.kind === "field" && field.foreign !== undefined
3317
3795
  ? {
3318
3796
  foreignFieldName: field.foreign.fieldName,
@@ -3631,10 +4109,24 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3631
4109
  args.table = decodeSearchTableReference(value, ctx);
3632
4110
  continue;
3633
4111
  }
4112
+ if (factory === "approvalStatusUpdate" && attr === "approval_reference") {
4113
+ args.approvalReference = decodeValue(value, ctx);
4114
+ continue;
4115
+ }
4116
+ if (factory === "approvalStatusUpdate" && attr === "record_reference") {
4117
+ args.record = decodeValue(value, ctx);
4118
+ continue;
4119
+ }
3634
4120
  if (factory === "approvalChain" && attr === "approval_process_id") {
3635
4121
  args.approvalProcess = decodeValue(value, ctx);
3636
4122
  continue;
3637
4123
  }
4124
+ // The wire attribute is `tags`; approvalChain()'s option is the product's
4125
+ // singular Approval Process Tag (the message task's `tags` is its channel).
4126
+ if (factory === "approvalChain" && attr === "tags") {
4127
+ args.tag = decodeValue(value, ctx);
4128
+ continue;
4129
+ }
3638
4130
  if (factory === "approvalChain" && attr === "record_reference") {
3639
4131
  args.record = decodeValue(value, ctx);
3640
4132
  continue;
@@ -3692,15 +4184,17 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3692
4184
  args.outputType = typeof value === "string" ? value.toLowerCase() : decodeValue(value, ctx);
3693
4185
  continue;
3694
4186
  }
3695
- if (attr === "attachments" && factory === "aiAgent") {
4187
+ // aiAgent's attachments and sendEmail's email_attachments share one shape.
4188
+ if ((attr === "attachments" && factory === "aiAgent") || (attr === "email_attachments" && factory === "sendEmail")) {
4189
+ const kind = factory === "aiAgent" ? "AI agent attachment" : "email attachment";
3696
4190
  if (!Array.isArray(value))
3697
- throw new EntityTfError(`${block.type}.${block.label}: attachments must be an array`);
4191
+ throw new EntityTfError(`${block.type}.${block.label}: ${attr} must be an array`);
3698
4192
  args.attachments = value.map((item) => {
3699
4193
  if (!isObject(item))
3700
- throw new EntityTfError(`${block.type}.${block.label}: invalid AI agent attachment`);
3701
- const present = ["file", "attachment", "record"].filter((key) => item[key] !== undefined);
4194
+ throw new EntityTfError(`${block.type}.${block.label}: invalid ${kind}`);
4195
+ const present = ["file", "attachment", "record"].filter((key) => item[key] !== undefined && item[key] !== null);
3702
4196
  if (present.length !== 1) {
3703
- throw new EntityTfError(`${block.type}.${block.label}: AI agent attachment must set exactly one of file, attachment, or record`);
4197
+ throw new EntityTfError(`${block.type}.${block.label}: ${kind} must set exactly one of file, attachment, or record`);
3704
4198
  }
3705
4199
  const key = present[0];
3706
4200
  return { [key]: decodeValue(item[key], ctx) };
@@ -3878,10 +4372,10 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3878
4372
  args.message = decodeValue(value, ctx);
3879
4373
  continue;
3880
4374
  }
3881
- // Notification's dynamic-recipient HCL attributes share the names
4375
+ // Notification's and addWatcher's dynamic HCL attributes share the names
3882
4376
  // `users`/`groups` with sendEmail, but their public options are
3883
4377
  // userRefs/groupRefs (not sendEmail's toUsers/toGroups).
3884
- if (factory === "notification" && (attr === "users" || attr === "groups")) {
4378
+ if ((factory === "notification" || factory === "addWatcher") && (attr === "users" || attr === "groups")) {
3885
4379
  args[attr === "users" ? "userRefs" : "groupRefs"] = decodeValue(value, ctx);
3886
4380
  continue;
3887
4381
  }
@@ -3937,36 +4431,137 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3937
4431
  }
3938
4432
  return args;
3939
4433
  }
4434
+ const UNMANAGED_PREDECESSOR_LOCAL_PREFIX = "edk_unmanaged_predecessor_";
4435
+ function documentLocals(doc) {
4436
+ return Object.assign({}, ...doc.blocks.filter((block) => block.kind === "locals").map((block) => block.attrs));
4437
+ }
4438
+ /** `type.label` plus a path such as `.inner`. A bare resource reference has no path. */
4439
+ function refAddress(value) {
4440
+ const ref = resourceRef(value);
4441
+ if (ref === undefined)
4442
+ return undefined;
4443
+ const suffix = ref.path.length > 0 ? `.${pathNames(ref.path).join(".")}` : "";
4444
+ return `${ref.type}.${ref.label}${suffix}`;
4445
+ }
4446
+ function unmanagedDataBlock(doc, label) {
4447
+ return doc.blocks.find((block) => block.kind === "data" && block.type === "elementum_unmanaged_task_reference" && block.label === label);
4448
+ }
3940
4449
  /**
3941
- * Resolve an `elementum_unmanaged_task_reference` data block's OWN real
3942
- * position in the task tree from its `operator_child_id`/`operator_task_id`/
3943
- * `parent_is_trigger` attributes (edk#821) - the platform already records
3944
- * exactly which switch case / fork-join branch / forEach body (or the
3945
- * trigger) the unsupported task sits in; this was previously discarded
3946
- * entirely in favor of always anchoring to the trigger. Returns `undefined`
3947
- * when none of those attributes resolve to an address this automation
3948
- * actually owns, so the caller can fall back to the trigger-anchor + diagnostic
3949
- * safety net rather than pointing at an address nothing will ever visit.
4450
+ * Where the task after an unsupported step sits. The local names the step it
4451
+ * comes after. The data source's operator fields are only the enclosing
4452
+ * branch, never that predecessor: the provider copies them onto the following
4453
+ * task (edk#2320). `parent_is_trigger` is not a position. It is always false
4454
+ * on a task reference, and treating it as "after the trigger" makes the next
4455
+ * plan move the live task.
3950
4456
  */
3951
- function resolveUnmanagedTaskPosition(dataBlock, triggerAddress, ownedAddresses) {
3952
- if (dataBlock.attrs.parent_is_trigger === true)
3953
- return triggerAddress;
3954
- const operatorRef = resourceRef(dataBlock.attrs.operator_task_id);
3955
- if (operatorRef?.type === "elementum_for_each_task") {
3956
- const inner = `${operatorRef.type}.${operatorRef.label}.inner`;
3957
- return ownedAddresses.has(`${operatorRef.type}.${operatorRef.label}`) ? inner : undefined;
3958
- }
3959
- const childRef = resourceRef(dataBlock.attrs.operator_child_id);
3960
- if (childRef !== undefined) {
3961
- const address = `${childRef.type}.${childRef.label}`;
3962
- return ownedAddresses.has(address) ? address : undefined;
3963
- }
3964
- if (operatorRef !== undefined) {
3965
- const address = `${operatorRef.type}.${operatorRef.label}`;
3966
- return ownedAddresses.has(address) ? address : undefined;
4457
+ function unmanagedSuccessorPosition(doc, label, ownedAddresses, addressByPlatformId, seen = new Set()) {
4458
+ if (seen.has(label))
4459
+ return undefined;
4460
+ const nextSeen = new Set(seen);
4461
+ nextSeen.add(label);
4462
+ const local = documentLocals(doc)[`${UNMANAGED_PREDECESSOR_LOCAL_PREFIX}${label}`];
4463
+ // A run of unsupported steps points each local at the previous data source.
4464
+ // The managed task at the end stays placed only when that chain reaches an
4465
+ // owned step (edk#2320).
4466
+ const predecessor = unmanagedTaskRef(local);
4467
+ if (predecessor !== undefined) {
4468
+ const predecessorPosition = unmanagedSuccessorPosition(doc, predecessor.label, ownedAddresses, addressByPlatformId, nextSeen);
4469
+ return predecessorPosition === undefined
4470
+ ? undefined
4471
+ : `elementum_unmanaged_task_reference.${predecessor.label}`;
4472
+ }
4473
+ const fromLocal = refAddress(local);
4474
+ const predecessorOwned = fromLocal !== undefined && (ownedAddresses.has(fromLocal) ||
4475
+ (fromLocal.endsWith(".inner") && ownedAddresses.has(fromLocal.slice(0, -".inner".length))));
4476
+ if (predecessorOwned)
4477
+ return fromLocal;
4478
+ const dataBlock = unmanagedDataBlock(doc, label);
4479
+ if (dataBlock === undefined)
4480
+ return undefined;
4481
+ return resolveUnmanagedTaskPosition(dataBlock, ownedAddresses, addressByPlatformId);
4482
+ }
4483
+ /** Puts every earlier unsupported step of a run into the same tree as the one a managed task parents onto. */
4484
+ function rememberUnmanagedPredecessors(doc, label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen) {
4485
+ const predecessor = unmanagedTaskRef(documentLocals(doc)[`${UNMANAGED_PREDECESSOR_LOCAL_PREFIX}${label}`]);
4486
+ if (predecessor === undefined || seen.has(predecessor.label))
4487
+ return;
4488
+ seen.add(predecessor.label);
4489
+ const address = `elementum_unmanaged_task_reference.${predecessor.label}`;
4490
+ if (!unmanagedTaskPositions.has(address)) {
4491
+ const dataBlock = dataBlocks.get(address);
4492
+ const position = unmanagedSuccessorPosition(doc, predecessor.label, ownedAddresses, addressByPlatformId);
4493
+ if (dataBlock === undefined || position === undefined)
4494
+ return;
4495
+ unmanagedTaskPositions.set(address, position);
4496
+ const refKey = typeof dataBlock.attrs.name === "string" && dataBlock.attrs.name !== ""
4497
+ ? dataBlock.attrs.name
4498
+ : tfLabelToTsLabel(dataBlock.label ?? "task");
4499
+ taskByAddress.set(address, { block: dataBlock, refKey });
4500
+ placeholderTasks.push({
4501
+ name: refKey,
4502
+ taskType: typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown",
4503
+ });
4504
+ }
4505
+ rememberUnmanagedPredecessors(doc, predecessor.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen);
4506
+ }
4507
+ function importPlatformId(doc, type, label) {
4508
+ for (const block of doc.blocks) {
4509
+ if (block.kind !== "import" || typeof block.attrs.id !== "string")
4510
+ continue;
4511
+ const target = resourceRef(block.attrs.to);
4512
+ if (target?.type !== type || target.label !== label)
4513
+ continue;
4514
+ const id = block.attrs.id.split(/[:/]/).at(-1);
4515
+ return id !== "" ? id : undefined;
3967
4516
  }
3968
4517
  return undefined;
3969
4518
  }
4519
+ function unmanagedBelongsToAutomation(doc, label, automationLabel, automationPlatformId) {
4520
+ const id = unmanagedDataBlock(doc, label)?.attrs.automation_id;
4521
+ if (typeof id === "string")
4522
+ return automationPlatformId !== undefined && id === automationPlatformId;
4523
+ const ref = resourceRef(id);
4524
+ return ref?.type === AUTOMATION_RESOURCE_TYPE && ref.label === automationLabel;
4525
+ }
4526
+ function resolveUnmanagedTaskPosition(dataBlock, ownedAddresses, addressByPlatformId) {
4527
+ // The export writes these as the platform id. A rebuild writes a resource
4528
+ // reference. Both name the same task (edk#2320).
4529
+ const operatorAddress = taskAddressOf(dataBlock.attrs.operator_task_id, addressByPlatformId);
4530
+ if (operatorAddress?.startsWith("elementum_for_each_task.")) {
4531
+ const taskAddress = operatorAddress;
4532
+ return ownedAddresses.has(taskAddress) ? `${taskAddress}.inner` : undefined;
4533
+ }
4534
+ const childAddress = taskAddressOf(dataBlock.attrs.operator_child_id, addressByPlatformId);
4535
+ if (childAddress !== undefined && ownedAddresses.has(childAddress))
4536
+ return childAddress;
4537
+ if (operatorAddress !== undefined && ownedAddresses.has(operatorAddress))
4538
+ return operatorAddress;
4539
+ return undefined;
4540
+ }
4541
+ /** The resource address a parent-position attribute names: a resource reference, or a platform id carried by an import. */
4542
+ function taskAddressOf(value, addressByPlatformId) {
4543
+ const ref = resourceRef(value);
4544
+ if (ref !== undefined)
4545
+ return `${ref.type}.${ref.label}`;
4546
+ if (typeof value !== "string" || value === "")
4547
+ return undefined;
4548
+ return addressByPlatformId.get(value);
4549
+ }
4550
+ /** Import id leaf (the platform task or case id) to its resource address. */
4551
+ function taskAddressesByPlatformId(doc) {
4552
+ const addresses = new Map();
4553
+ for (const block of doc.blocks) {
4554
+ if (block.kind !== "import" || typeof block.attrs.id !== "string")
4555
+ continue;
4556
+ const target = resourceRef(block.attrs.to);
4557
+ if (target === undefined)
4558
+ continue;
4559
+ const id = block.attrs.id;
4560
+ const leaf = id.includes(":") ? id.slice(id.lastIndexOf(":") + 1) : id;
4561
+ addresses.set(leaf, `${target.type}.${target.label}`);
4562
+ }
4563
+ return addresses;
4564
+ }
3970
4565
  /**
3971
4566
  * `triggerAddress`/`onUnmanagedParent` are the fallback of last resort: a
3972
4567
  * task whose real predecessor is an unsupported task type, when that
@@ -3996,10 +4591,21 @@ function parentAddress(block, triggerAddress, unmanagedTaskPositions, onUnmanage
3996
4591
  const suffix = parent.path.length > 0 ? `.${pathNames(parent.path).join(".")}` : "";
3997
4592
  return `${parent.type}.${parent.label}${suffix}`;
3998
4593
  }
3999
- function taskRefKey(block, automationLabel, appTfLabel) {
4594
+ function taskRefKey(block, automationLabel, appTfLabel, exportAutoChild) {
4000
4595
  const autoChild = childPartFromScopedLabel(appTfLabel, automationLabel, "app");
4001
4596
  const taskChild = childPartFromScopedLabel(appTfLabel, block.label ?? "", "app");
4002
- const tail = taskChild.startsWith(`${autoChild}_`) ? taskChild.slice(autoChild.length + 1) : taskChild;
4597
+ // edk#2484: a renamed automation keeps its authored label, but ei still prefixes its tasks with the new name.
4598
+ // When both prefixes fit, take the one that leaves the task's own name, so a task named after the added or
4599
+ // removed word keeps that word; otherwise fall back to the longer prefix.
4600
+ const owners = [autoChild, exportAutoChild]
4601
+ .filter((child) => child !== undefined && taskChild.startsWith(`${child}_`))
4602
+ .sort((a, b) => b.length - a.length);
4603
+ const ownNameKey = typeof block.attrs.name === "string" ? sanitizeName(block.attrs.name) : undefined;
4604
+ const owner = owners.find((child) => {
4605
+ const rest = taskChild.slice(child.length + 1);
4606
+ return rest === ownNameKey || `_${rest}` === ownNameKey;
4607
+ }) ?? owners[0];
4608
+ const tail = owner !== undefined ? taskChild.slice(owner.length + 1) : taskChild;
4003
4609
  const taskName = typeof block.attrs.name === "string" ? block.attrs.name : undefined;
4004
4610
  if (taskName !== undefined) {
4005
4611
  const sanitized = sanitizeName(taskName);
@@ -4056,6 +4662,16 @@ export function automationOwnedAddresses(doc, automationLabel) {
4056
4662
  owned.add(`${block.type}.${block.label}`);
4057
4663
  }
4058
4664
  }
4665
+ // A published automation names every task it owns in workflow_publish.depends_on.
4666
+ // A task whose parent is an unsupported step is only reachable that way:
4667
+ // the parent is a data source, not a resource (edk#2320).
4668
+ const publish = doc.blocks.find((block) => block.kind === "resource" && block.type === WORKFLOW_PUBLISH_RESOURCE_TYPE && references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel));
4669
+ const publishDependencies = new Set(Array.isArray(publish?.attrs.depends_on)
4670
+ ? publish.attrs.depends_on.flatMap((value) => {
4671
+ const ref = resourceRef(value);
4672
+ return ref === undefined ? [] : [`${ref.type}.${ref.label}`];
4673
+ })
4674
+ : []);
4059
4675
  let changed = true;
4060
4676
  while (changed) {
4061
4677
  changed = false;
@@ -4069,6 +4685,14 @@ export function automationOwnedAddresses(doc, automationLabel) {
4069
4685
  if (parent !== undefined && owned.has(`${parent.type}.${parent.label}`)) {
4070
4686
  owned.add(address);
4071
4687
  changed = true;
4688
+ continue;
4689
+ }
4690
+ const unmanagedLabel = unmanagedTaskRef(block.attrs.parent)?.label;
4691
+ const placed = unmanagedLabel !== undefined && unmanagedSuccessorPosition(doc, unmanagedLabel, owned, taskAddressesByPlatformId(doc)) !== undefined;
4692
+ const draftOfThis = publish === undefined && unmanagedLabel !== undefined && unmanagedBelongsToAutomation(doc, unmanagedLabel, automationLabel, importPlatformId(doc, AUTOMATION_RESOURCE_TYPE, automationLabel));
4693
+ if (placed && (publishDependencies.has(address) || draftOfThis)) {
4694
+ owned.add(address);
4695
+ changed = true;
4072
4696
  }
4073
4697
  }
4074
4698
  }
@@ -4270,18 +4894,54 @@ export class UnresolvedTaskFilterRefError extends EntityTfError {
4270
4894
  }
4271
4895
  }
4272
4896
  }
4897
+ /**
4898
+ * The EDK ref of the app that owns a `data "elementum_service_account"`
4899
+ * lookup. Export looks up another app's account through its owning app
4900
+ * (edk#2197): `app_id = data.elementum_app.<label>.id`, that block naming the
4901
+ * app by namespace (or name). Undefined when `app_id` is not such a lookup,
4902
+ * so the account stays on the automation's own app. `{ missingApp }` when the
4903
+ * lookup names an app the workspace does not know, or names none: it
4904
+ * describes the lookup (`namespace "ns"`), and the caller throws
4905
+ * `UnresolvedServiceAccountOwnerAppError` with it (edk#2416).
4906
+ */
4907
+ function dataServiceAccountOwnerRefName(appId, dataBlocks, foreignAppRefNames, foreignAppRefNamespaces) {
4908
+ const appDataLabel = dataRefLabel(appId, "elementum_app");
4909
+ if (appDataLabel === undefined)
4910
+ return undefined;
4911
+ const appBlock = dataBlocks.get(`elementum_app.${appDataLabel}`);
4912
+ const namespace = appBlock?.attrs.namespace;
4913
+ if (typeof namespace === "string")
4914
+ return foreignAppRefNamespaces?.get(namespace) ?? { missingApp: `namespace "${namespace}"` };
4915
+ const name = appBlock?.attrs.name;
4916
+ if (typeof name === "string")
4917
+ return foreignAppRefNames?.get(name) ?? { missingApp: `name "${name}"` };
4918
+ return { missingApp: `data.elementum_app.${appDataLabel}, which names no namespace or name` };
4919
+ }
4273
4920
  /**
4274
4921
  * A bare service_account_id belongs to an app this export does not contain.
4275
4922
  * Pull cannot print a serviceAccountRef until that app is in the workspace,
4276
4923
  * and printing nothing would clear the live account.
4277
4924
  */
4278
4925
  export class UnresolvedForeignServiceAccountError extends EntityTfError {
4279
- constructor(automationLabel) {
4280
- super(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}: service_account_id names a service account outside this export ` +
4281
- "that no pulled app in state owns; pull the app that owns it first");
4926
+ constructor(automationLabel, message = `${AUTOMATION_RESOURCE_TYPE}.${automationLabel}: service_account_id names a service account outside this export ` +
4927
+ "that no pulled app in state owns; pull the app that owns it first") {
4928
+ super(message);
4282
4929
  this.name = "UnresolvedForeignServiceAccountError";
4283
4930
  }
4284
4931
  }
4932
+ /**
4933
+ * The service account is another app's, looked up through that app
4934
+ * (`data.elementum_app.<label>`), and no app in the workspace declares it.
4935
+ * Pull names the app so the next step can say which one to pull.
4936
+ */
4937
+ export class UnresolvedServiceAccountOwnerAppError extends UnresolvedForeignServiceAccountError {
4938
+ constructor(automationLabel, serviceAccountName, missingApp) {
4939
+ const account = serviceAccountName === undefined ? "a service account" : `service account "${serviceAccountName}"`;
4940
+ super(automationLabel, `${AUTOMATION_RESOURCE_TYPE}.${automationLabel}: service_account_id runs as ${account} of the app with ${missingApp}, ` +
4941
+ "and no app in this workspace declares it; pull that app first");
4942
+ this.name = "UnresolvedServiceAccountOwnerAppError";
4943
+ }
4944
+ }
4285
4945
  /**
4286
4946
  * #1320: a task reads the current item of a loop that doesn't enclose it.
4287
4947
  * Pull skips the automation like any other exclusion, and additionally
@@ -4390,7 +5050,7 @@ function describeUnresolvedTask(taskId, doc, automationLabel, taskByAddress, res
4390
5050
  `(the platform checks references only when an automation is published), or it is a task type EDK cannot export. ${FIX_FILTER_IN_BUILDER}`;
4391
5051
  }
4392
5052
  /** Extract one app- or element-owned automation graph from an ei export. */
4393
- function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames, procedureKeysByDiscriminator, foreignTaskRefNames, groupKeysByName, serviceAccountsById, foreignFileReaderRefsById) {
5053
+ function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionsByField, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames, procedureKeysByDiscriminator, foreignTaskRefNames, groupKeysByName, serviceAccountsById, foreignFileReaderRefsById, foreignAppRefNamespaces) {
4394
5054
  const automation = doc.blocks.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE && block.label === automationLabel);
4395
5055
  if (automation === undefined)
4396
5056
  throw new EntityTfError(`automation resource "${automationLabel}" not found`);
@@ -4455,9 +5115,14 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4455
5115
  }
4456
5116
  // edk#785: a data-source parent is always "resolved" (see unmanagedTaskRef) -
4457
5117
  // doesn't need its target to already be owned the way a resource-attr parent does.
4458
- else if (!parent && unmanagedTaskRef(task.attrs.parent) && publishDependencyAddresses.has(`${task.type}.${task.label}`) && !owned.has(`${task.type}.${task.label}`)) {
4459
- owned.add(`${task.type}.${task.label}`);
4460
- changed = true;
5118
+ else if (!parent && unmanagedTaskRef(task.attrs.parent) && !owned.has(`${task.type}.${task.label}`)) {
5119
+ const unmanagedLabel = unmanagedTaskRef(task.attrs.parent)?.label;
5120
+ const placed = unmanagedLabel !== undefined && unmanagedSuccessorPosition(doc, unmanagedLabel, owned, taskAddressesByPlatformId(doc)) !== undefined;
5121
+ const draftOfThis = publish === undefined && unmanagedLabel !== undefined && unmanagedBelongsToAutomation(doc, unmanagedLabel, automationLabel, importPlatformId(doc, AUTOMATION_RESOURCE_TYPE, automationLabel));
5122
+ if (placed && (publishDependencyAddresses.has(`${task.type}.${task.label}`) || draftOfThis)) {
5123
+ owned.add(`${task.type}.${task.label}`);
5124
+ changed = true;
5125
+ }
4461
5126
  }
4462
5127
  }
4463
5128
  }
@@ -4524,9 +5189,14 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4524
5189
  }
4525
5190
  const appTfLabel = app.label;
4526
5191
  const dataBlocks = new Map(doc.blocks.filter((block) => block.kind === "data" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
4527
- const taskByAddress = new Map(tasks.map((block) => [`${block.type}.${block.label}`, { block, refKey: taskRefKey(block, automationLabel, appTfLabel) }]));
5192
+ // edk#2484: the trigger keeps ei's label for the automation's current name; the authored label can be an older one.
5193
+ const exportAutoChild = trigger.label !== automationLabel ? childPartFromScopedLabel(appTfLabel, trigger.label ?? "", "app") : undefined;
5194
+ const renamed = (block) => exportAutoChild !== undefined && childPartFromScopedLabel(appTfLabel, block.label ?? "", "app").startsWith(`${exportAutoChild}_`);
5195
+ const taskByAddress = new Map(tasks.map((block) => [`${block.type}.${block.label}`, { block, refKey: taskRefKey(block, automationLabel, appTfLabel, exportAutoChild) }]));
5196
+ const ownerAliases = [trigger, publish].flatMap((block) => block !== undefined && exportAutoChild !== undefined && block.label !== automationLabel
5197
+ ? [{ from: `${block.type}.${block.label}`, to: `${block.type}.${automationLabel}` }] : []);
4528
5198
  const taskAddressAliases = [...taskByAddress.entries()].flatMap(([from, { block, refKey }]) => {
4529
- if (soleVariableName(block) === undefined)
5199
+ if (soleVariableName(block) === undefined && !renamed(block))
4530
5200
  return [];
4531
5201
  const to = `${block.type}.${taskTfLabel(automationLabel, refKey)}`;
4532
5202
  return to === from ? [] : [{ from, to }];
@@ -4568,7 +5238,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4568
5238
  // (adopt.ts) already refuses two aliases that claim the same target
4569
5239
  // address, naming both "from" addresses, so that case fails loudly here
4570
5240
  // instead of silently importing the wrong state.
4571
- const adoptionAddressAliases = [...taskAddressAliases, ...branchAddressAliases];
5241
+ const adoptionAddressAliases = [...ownerAliases, ...taskAddressAliases, ...branchAddressAliases];
4572
5242
  const taskTargetOwnerRefNameByAddress = new Map();
4573
5243
  const taskTargetOwnerKindByAddress = new Map();
4574
5244
  for (const [address, { block }] of taskByAddress) {
@@ -4604,6 +5274,13 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4604
5274
  resourceType: block.type,
4605
5275
  });
4606
5276
  }
5277
+ const ownerAttrs = resourceBlocks.get(`${app.type}.${app.label}`)?.attrs;
5278
+ const titleFieldNameAttr = ownerAttrs?.["title_field_name"];
5279
+ const titleFieldName = typeof titleFieldNameAttr === "string" && titleFieldNameAttr !== "" ? titleFieldNameAttr : undefined;
5280
+ const idFieldNameAttr = ownerAttrs?.["id_field_name"];
5281
+ const idFieldName = typeof idFieldNameAttr === "string" && idFieldNameAttr !== "" ? idFieldNameAttr : undefined;
5282
+ const statusFieldNameAttr = ownerAttrs?.["status_field_name"];
5283
+ const statusFieldName = typeof statusFieldNameAttr === "string" && statusFieldNameAttr !== "" ? statusFieldNameAttr : undefined;
4607
5284
  const stagesByKey = new Map();
4608
5285
  const stagesAttr = resourceBlocks.get(`elementum_app.${app.label}`)?.attrs["stages"];
4609
5286
  if (Array.isArray(stagesAttr)) {
@@ -4613,6 +5290,8 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4613
5290
  }
4614
5291
  }
4615
5292
  const stringifiedValueReferences = { unresolved: false };
5293
+ const groupsMissingFromOrg = new Set();
5294
+ const optionIdWarnings = new Set();
4616
5295
  const ctx = {
4617
5296
  appRefName,
4618
5297
  appTfLabel: app.label,
@@ -4624,11 +5303,14 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4624
5303
  resourceImportIds,
4625
5304
  fieldById,
4626
5305
  stagesByKey,
5306
+ ...(titleFieldName !== undefined && { titleFieldName }),
5307
+ ...(idFieldName !== undefined && { idFieldName }),
5308
+ ...(statusFieldName !== undefined && { statusFieldName }),
4627
5309
  ...(foreignFieldRefsById !== undefined && { foreignFieldRefsById }),
4628
5310
  ...(foreignFieldRefsByDataAddress !== undefined && { foreignFieldRefsByDataAddress }),
4629
5311
  ...(foreignTableRefsById !== undefined && { foreignTableRefsById }),
4630
5312
  ...(foreignFileReaderRefsById !== undefined && { foreignFileReaderRefsById }),
4631
- ...(picklistOptionLabelById !== undefined && { picklistOptionLabelById }),
5313
+ ...(picklistOptionsByField !== undefined && { picklistOptionsByField }),
4632
5314
  ...(fieldNamesByOwnerRefName !== undefined && { fieldNamesByOwnerRefName }),
4633
5315
  ...(taskTargetOwnerRefNameByAddress.size > 0 && { taskTargetOwnerRefNameByAddress }),
4634
5316
  ...(taskTargetOwnerKindByAddress.size > 0 && { taskTargetOwnerKindByAddress }),
@@ -4638,12 +5320,15 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4638
5320
  ...(procedureKeysByDiscriminator !== undefined && { procedureKeysByDiscriminator }),
4639
5321
  ...(groupKeysByName !== undefined && { groupKeysByName }),
4640
5322
  stringifiedValueReferences,
5323
+ groupsMissingFromOrg,
5324
+ optionIdWarnings,
4641
5325
  ...(resourceImportIds.has(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`) && {
4642
5326
  automationId: resourceImportIds.get(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`),
4643
5327
  }),
4644
5328
  describeUnresolvedTask: (taskId) => describeUnresolvedTask(taskId, doc, automationLabel, taskByAddress, resourceBlocks, dataBlocks, resourceImportIds),
4645
5329
  };
4646
5330
  let serviceAccountName;
5331
+ let foreignServiceAccountAppRefName;
4647
5332
  const serviceAccountValue = automation.attrs.service_account_id;
4648
5333
  if (serviceAccountValue !== undefined &&
4649
5334
  isTfExpr(serviceAccountValue) &&
@@ -4661,8 +5346,15 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4661
5346
  serviceAccountName = `${block.attrs.first_name} ${block.attrs.last_name}`;
4662
5347
  }
4663
5348
  }
5349
+ if (reference.$expr === "data-attr" && block !== undefined) {
5350
+ const owner = dataServiceAccountOwnerRefName(block.attrs.app_id, dataBlocks, foreignAppRefNames, foreignAppRefNamespaces);
5351
+ if (typeof owner === "object")
5352
+ throw new UnresolvedServiceAccountOwnerAppError(automationLabel, serviceAccountName, owner.missingApp);
5353
+ if (owner !== undefined)
5354
+ foreignServiceAccountAppRefName = owner;
5355
+ }
4664
5356
  }
4665
- let serviceAccountAppRefName;
5357
+ let serviceAccountAppRefName = foreignServiceAccountAppRefName;
4666
5358
  if (typeof serviceAccountValue === "string" && isUuid(serviceAccountValue) && serviceAccountsById !== undefined) {
4667
5359
  const owned = serviceAccountsById.get(serviceAccountValue);
4668
5360
  if (owned !== undefined) {
@@ -4694,6 +5386,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4694
5386
  ]);
4695
5387
  const unmanagedTaskPositions = new Map();
4696
5388
  const placeholderTasks = [];
5389
+ const addressByPlatformId = taskAddressesByPlatformId(doc);
4697
5390
  for (const task of tasks) {
4698
5391
  const unmanagedRef = unmanagedTaskRef(task.attrs.parent);
4699
5392
  if (unmanagedRef === undefined)
@@ -4702,7 +5395,9 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4702
5395
  if (unmanagedTaskPositions.has(address))
4703
5396
  continue;
4704
5397
  const dataBlock = dataBlocks.get(address);
4705
- const position = dataBlock !== undefined ? resolveUnmanagedTaskPosition(dataBlock, triggerAddress, ownedAddresses) : undefined;
5398
+ const position = unmanagedRef.label !== undefined
5399
+ ? unmanagedSuccessorPosition(doc, unmanagedRef.label, ownedAddresses, addressByPlatformId)
5400
+ : undefined;
4706
5401
  if (dataBlock === undefined || position === undefined)
4707
5402
  continue; // falls back to parentAddress's trigger-anchor + diagnostic
4708
5403
  unmanagedTaskPositions.set(address, position);
@@ -4712,6 +5407,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4712
5407
  name: refKey,
4713
5408
  taskType: typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown",
4714
5409
  });
5410
+ rememberUnmanagedPredecessors(doc, unmanagedRef.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, new Set([unmanagedRef.label]));
4715
5411
  }
4716
5412
  const childrenByParent = new Map();
4717
5413
  for (const task of tasks) {
@@ -4852,7 +5548,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4852
5548
  ...(serviceAccountName !== undefined ? { serviceAccountName } : {}),
4853
5549
  ...(serviceAccountAppRefName !== undefined ? { serviceAccountAppRefName } : {}),
4854
5550
  status: automation.attrs.status === "INACTIVE" ? "INACTIVE" : publish ? "ACTIVE" : "DRAFT",
4855
- trigger: triggerFromBlock(trigger, ctx),
5551
+ trigger: triggerFromBlock(trigger, ctx, taskDiagnostics),
4856
5552
  tasks: topTasks,
4857
5553
  ...(outputs && outputs.length > 0 ? { outputs } : {}),
4858
5554
  };
@@ -4862,18 +5558,20 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4862
5558
  ast,
4863
5559
  blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])],
4864
5560
  adoptionAddressAliases,
4865
- ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0 || outputDiagnostics.length > 0 || taskDiagnostics.length > 0) && {
5561
+ ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0 || outputDiagnostics.length > 0 || taskDiagnostics.length > 0 || groupsMissingFromOrg.size > 0 || optionIdWarnings.size > 0) && {
4866
5562
  diagnostics: [
4867
5563
  ...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`),
4868
5564
  ...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`),
4869
5565
  ...outputDiagnostics,
4870
5566
  ...taskDiagnostics.map((message) => `automation "${automationLabel}": ${message}`),
5567
+ ...[...optionIdWarnings].map((message) => `automation "${automationLabel}": ${message}`),
5568
+ ...[...groupsMissingFromOrg].map((name) => `automation "${automationLabel}": group "${name}" is not in the org catalog this pull loaded (org.ts doesn't carry it, or org.ts is missing or couldn't be imported), so it was pulled as groupRef({ name: ${JSON.stringify(name)} }); run \`elementum pull org --data-only\`, then pull this app again to refer to it as org.groups.<key>`),
4871
5569
  ],
4872
5570
  }),
4873
5571
  ...(stringifiedValueReferences.unresolved ? { stringifiedValueReferences: true } : {}),
4874
5572
  };
4875
5573
  }
4876
- export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth) {
5574
+ export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth) {
4877
5575
  if (Array.isArray(first)) {
4878
5576
  const ctx = second;
4879
5577
  const automationBlock = first.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE);
@@ -4882,7 +5580,7 @@ export function automationFromTf(first, second, third, fourth, fifth, sixth, sev
4882
5580
  throw new EntityTfError(`automation graph has no ${AUTOMATION_RESOURCE_TYPE} resource, so its resources (${addresses.join(", ") || "none"}) cannot be pulled`);
4883
5581
  }
4884
5582
  try {
4885
- 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, ctx.foreignTaskRefNames, ctx.groupKeysByName, ctx.serviceAccountsById, ctx.foreignFileReaderRefsById);
5583
+ const result = automationFromTfDocument({ blocks: [...first] }, automationBlock.label, ctx.ownerHandle, ctx.foreignFieldRefsById, ctx.foreignFieldRefsByDataAddress, ctx.foreignTableRefsById, ctx.picklistOptionsByField, ctx.fieldNamesByOwnerRefName, ctx.foreignAppRefNames, ctx.foreignElementRefNames, ctx.procedureKeysByDiscriminator, ctx.foreignTaskRefNames, ctx.groupKeysByName, ctx.serviceAccountsById, ctx.foreignFileReaderRefsById, ctx.foreignAppRefNamespaces);
4886
5584
  if (result.diagnostics)
4887
5585
  ctx.diagnostics.push(...result.diagnostics);
4888
5586
  return { automation: result.ast };
@@ -4895,5 +5593,5 @@ export function automationFromTf(first, second, third, fourth, fifth, sixth, sev
4895
5593
  return { skippedReason: message };
4896
5594
  }
4897
5595
  }
4898
- return automationFromTfDocument(first, second, third ?? "", fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth);
5596
+ return automationFromTfDocument(first, second, third ?? "", fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth);
4899
5597
  }