@elementumai/edk 0.8.0-preview.11 → 0.8.2-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/README.md +510 -324
  2. package/dist-sdk/src/catalog/ai-provider-models.d.ts +30 -0
  3. package/dist-sdk/src/catalog/ai-provider-models.js +63 -0
  4. package/dist-sdk/src/catalog/factories.d.ts +56 -3
  5. package/dist-sdk/src/catalog/factories.js +83 -4
  6. package/dist-sdk/src/catalog/from-authoring.js +19 -2
  7. package/dist-sdk/src/catalog/index.d.ts +3 -2
  8. package/dist-sdk/src/catalog/index.js +3 -2
  9. package/dist-sdk/src/catalog/org.d.ts +1 -1
  10. package/dist-sdk/src/catalog/org.js +134 -50
  11. package/dist-sdk/src/catalog/render.d.ts +13 -1
  12. package/dist-sdk/src/catalog/render.js +21 -4
  13. package/dist-sdk/src/catalog/token.js +18 -0
  14. package/dist-sdk/src/catalog/types.d.ts +75 -3
  15. package/dist-sdk/src/catalog/types.js +3 -0
  16. package/dist-sdk/src/core/system-fields.d.ts +2 -0
  17. package/dist-sdk/src/core/system-fields.js +2 -0
  18. package/dist-sdk/src/core/types/ai-provider.d.ts +10 -23
  19. package/dist-sdk/src/core/types/ai-provider.js +1 -25
  20. package/dist-sdk/src/core/types/app.d.ts +26 -1
  21. package/dist-sdk/src/engine/build/context.d.ts +58 -0
  22. package/dist-sdk/src/engine/build/context.js +11 -1
  23. package/dist-sdk/src/engine/build/source-context.d.ts +45 -0
  24. package/dist-sdk/src/engine/build/source-context.js +23 -0
  25. package/dist-sdk/src/engine/pull/context.d.ts +15 -0
  26. package/dist-sdk/src/engine/pull/org.d.ts +10 -0
  27. package/dist-sdk/src/engine/pull/org.js +34 -4
  28. package/dist-sdk/src/engine/tf/index.d.ts +2 -2
  29. package/dist-sdk/src/engine/tf/index.js +2 -2
  30. package/dist-sdk/src/engine/tf/labels.d.ts +54 -0
  31. package/dist-sdk/src/engine/tf/labels.js +75 -0
  32. package/dist-sdk/src/engine/tf/parse.d.ts +15 -0
  33. package/dist-sdk/src/engine/tf/parse.js +162 -0
  34. package/dist-sdk/src/entities/access-policy/build.d.ts +26 -0
  35. package/dist-sdk/src/entities/access-policy/build.js +7 -0
  36. package/dist-sdk/src/entities/access-policy/filter.d.ts +61 -0
  37. package/dist-sdk/src/entities/access-policy/filter.js +83 -0
  38. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +66 -0
  39. package/dist-sdk/src/entities/access-policy/from-tf.js +187 -0
  40. package/dist-sdk/src/entities/access-policy/module.d.ts +3 -0
  41. package/dist-sdk/src/entities/access-policy/module.js +17 -0
  42. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +43 -0
  43. package/dist-sdk/src/entities/access-policy/to-tf.js +164 -0
  44. package/dist-sdk/src/entities/access-policy/types.d.ts +4 -0
  45. package/dist-sdk/src/entities/access-policy/types.js +10 -0
  46. package/dist-sdk/src/entities/agent/build.d.ts +2 -0
  47. package/dist-sdk/src/entities/agent/build.js +1 -0
  48. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +38 -3
  49. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +257 -32
  50. package/dist-sdk/src/entities/agent/from-tf.d.ts +29 -9
  51. package/dist-sdk/src/entities/agent/from-tf.js +146 -19
  52. package/dist-sdk/src/entities/agent/index.d.ts +1 -1
  53. package/dist-sdk/src/entities/agent/module.js +14 -4
  54. package/dist-sdk/src/entities/agent/to-tf.d.ts +46 -1
  55. package/dist-sdk/src/entities/agent/to-tf.js +160 -14
  56. package/dist-sdk/src/entities/agent/tools.d.ts +88 -9
  57. package/dist-sdk/src/entities/agent/tools.js +46 -7
  58. package/dist-sdk/src/entities/agent-a2a-skill/from-tf.d.ts +17 -0
  59. package/dist-sdk/src/entities/agent-a2a-skill/from-tf.js +64 -0
  60. package/dist-sdk/src/entities/agent-a2a-skill/module.d.ts +4 -0
  61. package/dist-sdk/src/entities/agent-a2a-skill/module.js +14 -0
  62. package/dist-sdk/src/entities/agent-a2a-skill/to-tf.d.ts +40 -0
  63. package/dist-sdk/src/entities/agent-a2a-skill/to-tf.js +47 -0
  64. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +51 -4
  65. package/dist-sdk/src/entities/agent-tool/from-tf.js +131 -35
  66. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +11 -4
  67. package/dist-sdk/src/entities/agent-tool/to-tf.js +176 -30
  68. package/dist-sdk/src/entities/agent-tool/types.d.ts +5 -4
  69. package/dist-sdk/src/entities/agent-tool/types.js +38 -6
  70. package/dist-sdk/src/entities/app/build.d.ts +91 -13
  71. package/dist-sdk/src/entities/app/build.js +63 -5
  72. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +3 -0
  73. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -1
  74. package/dist-sdk/src/entities/app/from-tf.js +32 -22
  75. package/dist-sdk/src/entities/app/index.d.ts +4 -1
  76. package/dist-sdk/src/entities/app/index.js +2 -1
  77. package/dist-sdk/src/entities/app/module.js +10 -2
  78. package/dist-sdk/src/entities/app/to-tf.d.ts +5 -0
  79. package/dist-sdk/src/entities/app/to-tf.js +45 -4
  80. package/dist-sdk/src/entities/automation/build.d.ts +57 -13
  81. package/dist-sdk/src/entities/automation/build.js +62 -42
  82. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +25 -8
  83. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +16 -1
  84. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +206 -47
  85. package/dist-sdk/src/entities/automation/filter.d.ts +37 -3
  86. package/dist-sdk/src/entities/automation/filter.js +54 -3
  87. package/dist-sdk/src/entities/automation/from-tf.d.ts +26 -27
  88. package/dist-sdk/src/entities/automation/from-tf.js +1344 -222
  89. package/dist-sdk/src/entities/automation/index.d.ts +4 -0
  90. package/dist-sdk/src/entities/automation/index.js +4 -0
  91. package/dist-sdk/src/entities/automation/module.js +29 -32
  92. package/dist-sdk/src/entities/automation/operators.d.ts +29 -2
  93. package/dist-sdk/src/entities/automation/operators.js +27 -1
  94. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +19 -0
  95. package/dist-sdk/src/entities/automation/output-key-wire-name.js +24 -0
  96. package/dist-sdk/src/entities/automation/script-code.d.ts +10 -21
  97. package/dist-sdk/src/entities/automation/script-code.js +272 -5
  98. package/dist-sdk/src/entities/automation/tasks.d.ts +125 -19
  99. package/dist-sdk/src/entities/automation/tasks.js +83 -15
  100. package/dist-sdk/src/entities/automation/to-tf.d.ts +10 -29
  101. package/dist-sdk/src/entities/automation/to-tf.js +1291 -230
  102. package/dist-sdk/src/entities/automation/triggers.d.ts +9 -1
  103. package/dist-sdk/src/entities/automation/types.d.ts +29 -4
  104. package/dist-sdk/src/entities/automation/types.js +76 -46
  105. package/dist-sdk/src/entities/element/build.d.ts +44 -13
  106. package/dist-sdk/src/entities/element/build.js +45 -3
  107. package/dist-sdk/src/entities/element/from-tf.d.ts +1 -1
  108. package/dist-sdk/src/entities/element/from-tf.js +28 -14
  109. package/dist-sdk/src/entities/element/index.d.ts +4 -1
  110. package/dist-sdk/src/entities/element/index.js +2 -1
  111. package/dist-sdk/src/entities/element/module.js +4 -1
  112. package/dist-sdk/src/entities/element/to-tf.js +26 -3
  113. package/dist-sdk/src/entities/field/build.d.ts +61 -14
  114. package/dist-sdk/src/entities/field/build.js +10 -0
  115. package/dist-sdk/src/entities/field/calc/runtime.js +4 -0
  116. package/dist-sdk/src/entities/field/from-tf.d.ts +5 -3
  117. package/dist-sdk/src/entities/field/from-tf.js +118 -7
  118. package/dist-sdk/src/entities/field/module.js +3 -2
  119. package/dist-sdk/src/entities/field/to-tf.d.ts +46 -11
  120. package/dist-sdk/src/entities/field/to-tf.js +166 -17
  121. package/dist-sdk/src/entities/field/types.d.ts +26 -0
  122. package/dist-sdk/src/entities/field/types.js +34 -12
  123. package/dist-sdk/src/entities/file-reader/build.d.ts +108 -50
  124. package/dist-sdk/src/entities/file-reader/build.js +23 -23
  125. package/dist-sdk/src/entities/file-reader/deserializer/print-file-reader.d.ts +6 -0
  126. package/dist-sdk/src/entities/file-reader/deserializer/print-file-reader.js +109 -0
  127. package/dist-sdk/src/entities/file-reader/from-tf.d.ts +13 -0
  128. package/dist-sdk/src/entities/file-reader/from-tf.js +172 -0
  129. package/dist-sdk/src/entities/file-reader/index.d.ts +8 -3
  130. package/dist-sdk/src/entities/file-reader/index.js +7 -2
  131. package/dist-sdk/src/entities/file-reader/module.d.ts +3 -0
  132. package/dist-sdk/src/entities/file-reader/module.js +115 -0
  133. package/dist-sdk/src/entities/file-reader/to-tf.d.ts +14 -0
  134. package/dist-sdk/src/entities/file-reader/to-tf.js +84 -0
  135. package/dist-sdk/src/entities/file-reader/types.d.ts +32 -0
  136. package/dist-sdk/src/entities/file-reader/types.js +30 -0
  137. package/dist-sdk/src/entities/org/ai-provider.d.ts +13 -0
  138. package/dist-sdk/src/entities/org/ai-provider.js +46 -0
  139. package/dist-sdk/src/entities/org/connector.d.ts +8 -1
  140. package/dist-sdk/src/entities/org/connector.js +12 -14
  141. package/dist-sdk/src/entities/org/group.js +10 -1
  142. package/dist-sdk/src/entities/org/index.d.ts +1 -0
  143. package/dist-sdk/src/entities/org/index.js +1 -0
  144. package/dist-sdk/src/entities/org/user.js +10 -1
  145. package/dist-sdk/src/entities/shared/filters/ast.d.ts +59 -9
  146. package/dist-sdk/src/entities/shared/filters/types.d.ts +1 -1
  147. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +17 -0
  148. package/dist-sdk/src/entities/shared/tool-field-ref.js +46 -0
  149. package/dist-sdk/src/entities/shared/types/field-types.d.ts +10 -1
  150. package/dist-sdk/src/entities/shared/types/field-types.js +9 -0
  151. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +19 -0
  152. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +128 -11
  153. package/dist-sdk/src/entities/skill/from-tf.js +4 -3
  154. package/dist-sdk/src/entities/skill/index.d.ts +1 -1
  155. package/dist-sdk/src/entities/skill/module.js +7 -1
  156. package/dist-sdk/src/entities/skill/to-tf.d.ts +26 -0
  157. package/dist-sdk/src/entities/skill/to-tf.js +65 -4
  158. package/dist-sdk/src/entities/skill/tools.d.ts +37 -8
  159. package/dist-sdk/src/entities/skill/tools.js +43 -1
  160. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +34 -4
  161. package/dist-sdk/src/entities/skill-tool/from-tf.js +128 -18
  162. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +13 -1
  163. package/dist-sdk/src/entities/skill-tool/to-tf.js +164 -25
  164. package/dist-sdk/src/entities/skill-tool/types.d.ts +5 -7
  165. package/dist-sdk/src/entities/skill-tool/types.js +47 -11
  166. package/dist-sdk/src/entities/view/from-tf.d.ts +6 -2
  167. package/dist-sdk/src/entities/view/from-tf.js +11 -9
  168. package/dist-sdk/src/entities/view/to-tf.d.ts +9 -7
  169. package/dist-sdk/src/entities/view/to-tf.js +39 -18
  170. package/dist-sdk/src/entities/view/types.d.ts +1 -1
  171. package/dist-sdk/src/entities/view/types.js +1 -1
  172. package/dist-sdk/src/graph/deferred-catalog-render.d.ts +0 -5
  173. package/dist-sdk/src/graph/deferred-catalog-render.js +1 -20
  174. package/dist-sdk/src/graph/index.d.ts +8 -0
  175. package/dist-sdk/src/graph/index.js +13 -9
  176. package/dist-sdk/src/graph/modules.js +8 -1
  177. package/dist-sdk/src/graph/types.d.ts +98 -4
  178. package/package.json +49 -16
  179. package/dist-sdk/src/entities/automation/value-ref-tf.d.ts +0 -76
  180. package/dist-sdk/src/entities/automation/value-ref-tf.js +0 -190
@@ -1,252 +1,1374 @@
1
+ import { EntityTfError } from "../../engine/entity.js";
2
+ import { OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
3
+ import { USER_FIELD_KEYS } from "../../catalog/types.js";
4
+ import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEYS } from "../../core/system-fields.js";
5
+ import { bareChildResourceLabel, childPartFromScopedLabel, isTfExpr, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, } from "../../engine/tf/index.js";
6
+ import { IMPLEMENTED_FILE_READER_RESOURCE_TYPES } from "../file-reader/types.js";
7
+ import { ALL_AUTOMATION_TASK_TYPE_SET, AUTOMATION_BRANCH_TYPE_SET, AUTOMATION_RESOURCE_TYPE, AUTOMATION_TRIGGER_TYPE_SET, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
8
+ const TRIGGER_KINDS = {
9
+ elementum_record_created_trigger: "recordCreate",
10
+ elementum_record_updated_trigger: "recordUpdate",
11
+ elementum_attachment_added_trigger: "attachment",
12
+ elementum_comment_added_trigger: "commentAdded",
13
+ elementum_agent_conversation_ended_trigger: "conversationEnd",
14
+ elementum_slack_message_trigger: "slackMessage",
15
+ elementum_on_demand_trigger: "onDemand",
16
+ elementum_webhook_trigger: "webhook",
17
+ elementum_email_ingestion_trigger: "emailReceived",
18
+ elementum_approval_chain_trigger: "approvalProcessStatusUpdated",
19
+ elementum_datamine_trigger: "dataMine",
20
+ elementum_survey_trigger: "surveyResponseCreate",
21
+ };
22
+ const TASK_FACTORIES = {
23
+ elementum_message_task: "postComment",
24
+ elementum_update_field_task: "updateField",
25
+ elementum_variable_task: "setVariable",
26
+ elementum_update_variable_task: "setVariable",
27
+ elementum_create_record_task: "createRecord",
28
+ elementum_record_search_task: "recordSearch",
29
+ elementum_table_records_search_task: "tableRecordsSearch",
30
+ elementum_send_email_task: "sendEmail",
31
+ elementum_initiate_call_task: "initiateCall",
32
+ elementum_approval_chain_task: "approvalChain",
33
+ elementum_approval_status_update_task: "approvalStatusUpdate",
34
+ elementum_find_related_records_task: "findRelatedRecords",
35
+ elementum_api_task: "apiRequest",
36
+ elementum_ai_agent_task: "aiAgent",
37
+ elementum_for_each_task: "forEach",
38
+ elementum_switch_task: "switchTask",
39
+ elementum_fork_join_task: "forkJoin",
40
+ elementum_add_watcher_task: "addWatcher",
41
+ elementum_notification_task: "notification",
42
+ elementum_relate_records_task: "relateRecords",
43
+ elementum_ai_classify_task: "aiClassify",
44
+ elementum_ai_summarize_task: "aiSummarize",
45
+ elementum_ai_search_table_task: "aiSearchTable",
46
+ elementum_ai_transform_task: "aiTransform",
47
+ elementum_save_attachment_task: "saveAttachment",
48
+ elementum_user_search_task: "userSearch",
49
+ elementum_calculation_task: "calculation",
50
+ elementum_execute_script_task: "executeScript",
51
+ elementum_file_reader_task: "documentModel",
52
+ elementum_procedure_task: "procedure",
53
+ elementum_run_automation_task: "runAutomation",
54
+ elementum_aspect_record_field_locking_task: "recordFieldLocking",
55
+ elementum_ai_file_read_task: "aiFileAnalysis",
56
+ };
57
+ const ATTR_TO_ARG = {
58
+ object_id: "app",
59
+ table_id: "table",
60
+ record_reference: "recordRef",
61
+ source_record_ids: "sources",
62
+ target_record_id: "target",
63
+ message_body: "body",
64
+ from_username: "fromUsername",
65
+ from_personal: "fromDisplayName",
66
+ external_emails: "toAddresses",
67
+ users: "toUsers",
68
+ groups: "toGroups",
69
+ contents: "contents",
70
+ message: "contents",
71
+ agent_id: "agent",
72
+ prompt: "prompt",
73
+ output_type: "outputType",
74
+ json_fields: "schema",
75
+ ai_provider_connector_id: "connector",
76
+ url: "url",
77
+ response_type: "responseType",
78
+ continue_on_error: "continueOnError",
79
+ search_table_id: "table",
80
+ text_to_summarize: "text",
81
+ text_to_classify: "text",
82
+ field_type: "fieldType",
83
+ category_source: "categorySource",
84
+ user_ids: "userIds",
85
+ group_ids: "groupIds",
86
+ user_value_references: "userRefs",
87
+ group_value_references: "groupRefs",
88
+ notify_watchers: "notifyWatchers",
89
+ fields_to_lock: "fieldsToLock",
90
+ fields_to_unlock: "fieldsToUnlock",
91
+ view_state: "viewState",
92
+ target_automation_id: "automation",
93
+ target_automation_ref: "automation",
94
+ dynamic_input_mappings: "inputs",
95
+ output_mappings: "outputs",
96
+ file_reader_id: "documentModel",
97
+ file_id: "attachmentId",
98
+ cloudlink_id: "cloudLinkId",
99
+ // provider schema calls this stored_function_id; the authoring option
100
+ // stayed "procedureId" (pre-dating the provider's rename) to avoid an
101
+ // unnecessary breaking change to ProcedureOptions.
102
+ stored_function_id: "procedureId",
103
+ };
104
+ function isObject(value) {
105
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !("$expr" in value);
106
+ }
1
107
  /**
2
- * Automation extraction (Phase 1). `automationFromTf` consumes the composite
3
- * HCL blocks for ONE automation (its `elementum_automation` + trigger + task
4
- * blocks + `elementum_workflow_publish`) and produces the `AutomationAst` the
5
- * existing `printAutomationV2` renders to editable `.ts`.
6
- *
7
- * Task ORDER is reconstructed by walking the `parent` chain from the trigger:
8
- * the first task's `parent` is the trigger, each subsequent task's `parent` is
9
- * its predecessor. Unimplemented trigger/task kinds are REPORTED (plan §6),
10
- * never silently dropped — but note a kind we can't reconstruct also can't be
11
- * adopted (see module.ts), so in a full pull they never reach here.
12
- *
13
- * Per the tranche's typing decision: rather than a name-allowlist drift-guard
14
- * (the agent-tool `KNOWN_TOOL_ATTRS` pattern), each IMPLEMENTED kind has its own
15
- * small typed extractor naming the wire fields it reads. The declared-only kinds
16
- * carry no extractor — they are metadata for reporting, never parsed.
108
+ * Detects a switch task's default/catch-all branch and which of the two
109
+ * mutually-exclusive wire shapes the platform is currently using to mark it.
110
+ * Both are live-confirmed on real orgs for the identical case pattern (#157:
111
+ * one org's default case carries `is_default = true` with no `filter`;
112
+ * another's carries `filter = {type:"true"}` with no `is_default`) - the
113
+ * platform doesn't retroactively normalize existing cases to one shape, so
114
+ * this is a genuine per-case fact, not just export-version drift. Returning
115
+ * which shape was found (not just a boolean) lets to-tf.ts round-trip the
116
+ * same shape back on rebuild instead of guessing, so a re-pull doesn't
117
+ * propose a spurious "update" that provider bug #157 can't actually apply.
17
118
  */
18
- import { isTfExpr, sanitizeName } from "../../engine/tf/index.js";
19
- import { tfRefToAst } from "./value-ref-tf.js";
20
- import { AUTOMATION_RESOURCE_TYPE, AUTOMATION_SUB_TYPE_BY_RESOURCE, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
21
- /** The wire discriminant → the printer's factory name (TASK_FACTORY_V2 keys). */
22
- const FACTORY_BY_TYPE_KEY = {
23
- executeScript: "executeScript",
24
- variable: "setVariable",
119
+ function defaultSwitchShape(block) {
120
+ if (block.attrs.is_default === true)
121
+ return "isDefault";
122
+ const filter = block.attrs.filter;
123
+ if (block.label?.endsWith("_default") === true &&
124
+ block.attrs.label === "Default" &&
125
+ isObject(filter) &&
126
+ filter.type === "true") {
127
+ return "explicitTrueFilter";
128
+ }
129
+ return undefined;
130
+ }
131
+ function resourceRef(value) {
132
+ return isTfExpr(value) && value.$expr === "resource-attr"
133
+ ? { type: value.type, label: value.label, path: value.path }
134
+ : undefined;
135
+ }
136
+ function references(value, type, label) {
137
+ const ref = resourceRef(value);
138
+ return ref?.type === type && ref.label === label;
139
+ }
140
+ function assertAllowed(block, allowed) {
141
+ for (const key of Object.keys(block.attrs)) {
142
+ if (!allowed.has(key))
143
+ throw new EntityTfError(`${block.type}.${block.label}: unsupported attribute "${key}"`);
144
+ }
145
+ }
146
+ const TRIGGER_ATTRIBUTES = new Set([
147
+ "automation", "filter", "changed_fields", "think_ui", "conversation_type",
148
+ "authenticated", "custom_response", "show_triggered_by", "parameters",
149
+ "approval_chain_template_id", "status", "datamine_id", "fire_on_alert",
150
+ "fire_on_recovery", "email_alias_id", "survey_template_id",
151
+ ]);
152
+ const TASK_ATTRIBUTES = new Set([
153
+ "parent", "name", "depends_on", "filter", "fields", "inputs", "output_schema",
154
+ "list", "code", "variable_name", "variable_type", "variable", "value",
155
+ "object_id", "table_id", "record_reference", "record_id", "source_record_ids",
156
+ "target_record_id", "message", "message_body", "body", "from_username",
157
+ "from_personal", "external_emails", "users", "groups", "attachments", "contents",
158
+ "agent_id", "prompt", "output_type", "json_fields", "ai_provider_connector_id",
159
+ "url", "response_type", "continue_on_error", "search_table_id",
160
+ "text_to_summarize", "text_to_classify", "field_type", "category_source",
161
+ "title", "user_ids", "group_ids", "user_value_references",
162
+ "group_value_references", "notify_watchers", "field_id", "user_id", "group_id",
163
+ "fields_to_lock", "fields_to_unlock", "file", "file_id", "attachment", "attachment_id", "view_state", "target_automation_id",
164
+ "target_automation_ref", "input_mappings", "dynamic_input_mappings",
165
+ "output_mappings", "file_reader_id", "raw_text", "procedure_id",
166
+ "calculations", "categories", "limit", "sort", "tag", "tags", "context", "length",
167
+ "subject", "phone_service_id", "phone_number", "default_language", "first_message",
168
+ "synchronous", "cloudlink_id", "stored_function_id", "variable_reference",
169
+ "relate_to_record_reference", "method", "parameters", "headers",
170
+ "basic_auth", "bearer_auth", "oauth", "json_body", "form_body", "custom_body", "multipart_body",
171
+ ]);
172
+ const BRANCH_ATTRIBUTES = new Set([
173
+ "switch_task", "fork_join_task", "label", "is_default", "filter",
174
+ "previous_case_id", "previous_branch_id",
175
+ ]);
176
+ const PUBLISH_ATTRIBUTES = new Set([
177
+ "automation", "workflow_revision", "depends_on", "outputs",
178
+ ]);
179
+ function appRef(appRefName) {
180
+ return { kind: "app", appHandle: appRefName };
181
+ }
182
+ // Fixed, well-known ref keys ONLY - keys derived from a field's display name
183
+ // plus a suffix (e.g. "Created By" + " Email" -> "Created By Email") must NOT
184
+ // be added here. A hardcoded flat entry here short-circuits triggerRefPath's
185
+ // field-name+suffix matching below (pathNames runs first), producing an
186
+ // invalid, un-typed property name instead of the real ["record", field.key,
187
+ // "email"] path - confirmed live: "Created by Email"/"Updated by Manager
188
+ // Email" were hardcoded this way and printed as ctx.trigger.createdByEmail /
189
+ // ctx.trigger.updatedByManagerEmail, neither of which exists on the typed
190
+ // ctx, so every pulled automation using them failed `tsc --noEmit`.
191
+ const WIRE_REF_SEGMENT_TO_TS = {
192
+ "Changed Fields": "changedFieldIds",
193
+ "Iteration": "iteration",
194
+ "Slack Thread ID": "slackThreadId",
195
+ "Slack Channel ID": "slackChannelId",
196
+ "Message Author Email": "messageAuthorEmail",
197
+ "Message Author ID": "messageAuthorId",
198
+ "Message Author Name": "messageAuthorName",
199
+ "Message Content": "messageContent",
200
+ "Message ID": "messageId",
201
+ "Message Metadata": "messageMetadata",
202
+ };
203
+ const FIELD_REF_SUFFIX_FROM_WIRE = [
204
+ [" Manager Email", ["employee", "manager", "email"]],
205
+ [" Manager Name", ["employee", "manager", "name"]],
206
+ [" Manager", ["employee", "manager"]],
207
+ [" Field ID", ["fieldId"]],
208
+ // Deliberately the literal suffix text, not a camelCase "asText" segment:
209
+ // Ref<T> has no ".asText" projection anywhere in the type system (checked
210
+ // shared/ref.ts - it's a sealed brand, nothing else), so claiming one as a
211
+ // resolved identifier printed a property that could never type-check. The
212
+ // space keeps this segment identifier-unsafe, so printPathAccess's
213
+ // unresolved-segment escape (`as any` + bracket access) kicks in instead of
214
+ // printing a false, never-valid `.asText` access.
215
+ [" as text", ["as text"]],
216
+ [" Label", ["label"]],
217
+ [" Email", ["email"]],
218
+ [" Name", ["name"]],
219
+ [" ID", ["id"]],
220
+ ["", []],
221
+ ];
222
+ function pathNames(path) {
223
+ return path.map((segment) => {
224
+ const name = typeof segment === "string" ? segment : segment.index;
225
+ return WIRE_REF_SEGMENT_TO_TS[name] ?? name;
226
+ });
227
+ }
228
+ // recordSearch's own output ref names ("Records Size" -> totalCount, "All
229
+ // found records" -> records) — deliberately NOT in WIRE_REF_SEGMENT_TO_TS,
230
+ // which triggerRefPath also consults: a record-created/updated trigger's ref
231
+ // path is built from a FIELD's DISPLAY NAME, and a real field could
232
+ // coincidentally be named "Records Size" — translating it globally would
233
+ // misdecode that trigger ref as the unrelated task-output name "totalCount"
234
+ // before triggerRefPath's field-name matching even runs. Scoped to
235
+ // recordSearch task refs only, where these two strings are the platform's
236
+ // fixed wire names, never a field's own display name.
237
+ const RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS = {
238
+ "Records Size": "totalCount",
239
+ "All found records": "records",
25
240
  };
26
- function str(v) {
27
- return typeof v === "string" ? v : undefined;
28
- }
29
- /** Per-implemented-kind typed arg extraction (the from-tf half of the bridge). */
30
- function taskArgs(typeKey, attrs, refCtx) {
31
- switch (typeKey) {
32
- case "executeScript": {
33
- const args = { code: str(attrs["code"]) ?? "" };
34
- const rawInputs = Array.isArray(attrs["inputs"]) ? attrs["inputs"] : [];
35
- if (rawInputs.length > 0) {
36
- const inputs = {};
37
- for (const entry of rawInputs) {
38
- const inputName = str(entry?.name);
39
- if (inputName === undefined)
40
- continue;
41
- const converted = tfRefToAst((entry.value ?? ""), refCtx);
42
- if ("unsupported" in converted)
43
- return { unsupported: `input "${inputName}": ${converted.unsupported}` };
44
- inputs[inputName] = converted.ast;
241
+ /**
242
+ * A webhook trigger's `body`/`headers` refs come back as "Body (Plain
243
+ * Text)"/"Headers (Content-Type)" - one wire segment naming both the
244
+ * top-level property (always "body"/"headers", both typed
245
+ * `Record<string, unknown>` on WebhookTriggerOutput) and an arbitrary
246
+ * sub-key. Splitting it lets the sub-key print as a plain bracket access on
247
+ * an already string-indexable type, instead of a false top-level property
248
+ * like `ctx.trigger["Body (Plain Text)"]` that WebhookTriggerOutput never
249
+ * declares. Gated on the trigger's actual resource type, not just the
250
+ * string shape - a different trigger's field could otherwise coincidentally
251
+ * be named "Body (something)" and get misinterpreted as this webhook-only
252
+ * convention.
253
+ */
254
+ const WEBHOOK_REF_PATTERN = /^(Body|Headers) \((.+)\)$/;
255
+ function triggerRefPath(path, ctx) {
256
+ const names = pathNames(path);
257
+ if (names.length !== 1)
258
+ return names;
259
+ const wireName = names[0];
260
+ if (ctx.trigger.type === "elementum_webhook_trigger") {
261
+ const webhookMatch = WEBHOOK_REF_PATTERN.exec(wireName);
262
+ if (webhookMatch)
263
+ return [webhookMatch[1].toLowerCase(), webhookMatch[2]];
264
+ }
265
+ // A trigger's own bare record reference (confirmed live via `ei refs`,
266
+ // see trigger-record-id.test.ts) — deliberately scoped to triggerRefPath,
267
+ // not the shared WIRE_REF_SEGMENT_TO_TS table: createRecord/
268
+ // findRelatedRecords TASKS also expose a wire key literally named
269
+ // "Record", but as their scalar record-ID output (ASPECT_RECORD_ID, not
270
+ // this trigger-level ASPECT_RECORD whole-record reference) — translating
271
+ // it globally intercepted that task-level case before it could ever be
272
+ // checked (decodeValue's own dedicated "Record" handling for those task
273
+ // types).
274
+ if (wireName === "Record")
275
+ return ["record"];
276
+ // Case-insensitive: the platform re-cases "By" to "by" when building some
277
+ // compound ref phrases (e.g. field "Created By" -> ref key "Created by
278
+ // Email"), so a case-sensitive compare against the field's own display
279
+ // name misses the match entirely.
280
+ const wireNameLower = wireName.toLowerCase();
281
+ for (const field of ctx.fieldById.values()) {
282
+ for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
283
+ if (wireNameLower === `${field.name}${suffix}`.toLowerCase()) {
284
+ return ["record", field.key, ...suffixPath];
285
+ }
286
+ }
287
+ }
288
+ // System fields (id/title/status/stage/createdBy/updatedBy/...) have no
289
+ // `*_field` resource block of their own - they're elementum_app computed
290
+ // attributes, so they never appear in ctx.fieldById. Try their canonical
291
+ // bag keys against the provider's default display name too (e.g.
292
+ // "Created By" + " Email"). A renamed system field's ref key won't match
293
+ // here and falls through to the raw-name fallback below - no worse than
294
+ // today, since system fields were never matched at all before this.
295
+ for (const key of SYSTEM_FIELD_KEYS) {
296
+ const defaultName = DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[key];
297
+ for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
298
+ if (wireNameLower === `${defaultName}${suffix}`.toLowerCase()) {
299
+ return ["record", key, ...suffixPath];
300
+ }
301
+ }
302
+ }
303
+ return names;
304
+ }
305
+ function decodeReferenceString(value, ctx) {
306
+ const pieces = value.split(".");
307
+ if (pieces[0] === "trigger" && pieces.length > 1) {
308
+ const path = pieces.slice(1);
309
+ if (path[0] === "record" && path.length >= 2 && /^[a-f0-9-]{36}$/.test(path[1])) {
310
+ const sourceFieldId = path[1];
311
+ const field = ctx.fieldById.get(sourceFieldId);
312
+ // Orphaned: the field this filter's value_reference points at no
313
+ // longer exists in the app export at all (deleted/recreated field,
314
+ // same drift class as the orphaned picklist option ids and skill_ids
315
+ // fixed elsewhere) - confirmed live: a switch_case filter can
316
+ // reference a field id no custom or system field resolves to.
317
+ // Round-trip the raw id verbatim (printPathAccess's existing "as any"
318
+ // unresolved-segment escape already degrades a non-identifier path
319
+ // segment like this one) rather than throwing and losing the whole
320
+ // automation.
321
+ return { kind: "triggerRef", path: ["record", field?.key ?? sourceFieldId, ...path.slice(2)] };
322
+ }
323
+ return { kind: "triggerRef", path };
324
+ }
325
+ if (pieces[0] === "task" && pieces.length > 2)
326
+ return { kind: "taskRef", task: pieces[1], path: pieces.slice(2) };
327
+ // Any other/future value_reference shape - confirmed live: conciergeforfield's
328
+ // cff_find_nearby_accounts_if_user_is_impersonating_a_sales_rep switch_case
329
+ // references a workflow variable ("variable.<uuid>"); setVariable/variable_task
330
+ // authoring is itself deferred (no typed construct exists yet to resolve this
331
+ // to - see the automation module's header), so it can never become a real ref
332
+ // today, and any future dialect growth hits the same "we don't recognize this
333
+ // reference shape" situation. Degrade to the {kind:"unresolved"} placeholder
334
+ // (same escape hatch fieldRef already uses for an orphaned field_id) rather
335
+ // than throwing and losing the whole automation (#171) - printFilterField
336
+ // marks it distinctly from a field placeholder (hint !== "field") so the BUILD
337
+ // direction fails loudly instead of silently mis-rebuilding it as a field_id
338
+ // (#290; a value_reference position can never round-trip through field_id).
339
+ return { kind: "unresolved", uuid: value, hint: pieces[0] ?? "reference" };
340
+ }
341
+ /**
342
+ * Inverse of filterReferenceToTf's TRIGGER case (automation/to-tf.ts): a
343
+ * filter's value_reference for a trigger-record field renders as a template
344
+ * (`"trigger.record." + <live field ref> + ".<suffix>"?`), not a plain
345
+ * string, so decodeReferenceString never sees it. Recognize that exact shape
346
+ * and decode straight to a triggerRef, matching decodeReferenceString's
347
+ * output — anything else falls through to decodeValue's generic "template"
348
+ * kind, which refDataToFilterReference rejects (correctly, for a real
349
+ * interpolated string that isn't this specific field-address pattern).
350
+ */
351
+ function decodeTemplateTriggerRecordFieldRef(value, ctx) {
352
+ if (!isTfExpr(value) || value.$expr !== "template")
353
+ return undefined;
354
+ const [prefix, fieldPart, suffixPart] = value.parts;
355
+ if (prefix !== "trigger.record." || fieldPart === undefined || typeof fieldPart === "string")
356
+ return undefined;
357
+ if (suffixPart !== undefined && typeof suffixPart !== "string")
358
+ return undefined;
359
+ const fieldKey = fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx);
360
+ if (fieldKey === undefined)
361
+ return undefined;
362
+ const suffix = suffixPart === undefined ? [] : suffixPart.replace(/^\./, "").split(".").filter((s) => s.length > 0);
363
+ return { kind: "triggerRef", path: ["record", fieldKey, ...suffix] };
364
+ }
365
+ /**
366
+ * Resolve the field-id expression at the middle of a `trigger.record.<id>[.suffix]`
367
+ * template. A custom field's id is a `resource-attr` (`elementum_x_field.<label>.id`);
368
+ * a system field (id/title/status/createdBy/updatedBy/...) has no resource block of
369
+ * its own, so ei emits its id via a `<appTfLabel>_<field>_field_id` local instead -
370
+ * confirmed live on a switch-case condition keyed off `updatedBy`. Mirrors
371
+ * decodeValue's generic local handling, but resolves to a triggerRef bag key
372
+ * instead of a "field" RefExpr so it stays a valid filter LHS.
373
+ */
374
+ function fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx) {
375
+ if (fieldPart.$expr === "resource-attr" && fieldPart.type.endsWith("_field") && fieldPart.path[0] === "id") {
376
+ return scopedLabelToBagKey(ctx.appTfLabel, fieldPart.label);
377
+ }
378
+ if (fieldPart.$expr === "local") {
379
+ const prefix = `${ctx.appTfLabel}_`;
380
+ if (fieldPart.name.startsWith(prefix) && fieldPart.name.endsWith("_field_id")) {
381
+ return tfLabelToTsLabel(fieldPart.name.slice(prefix.length, -9));
382
+ }
383
+ }
384
+ return undefined;
385
+ }
386
+ /** Same provider/model derivation as `agentFromTf` and `renderAiProvidersBag`, read off the stream's own data blocks. */
387
+ function resolveConnectorRef(connectorType, connectorLabel, ctx) {
388
+ const connectorBlock = ctx.dataBlocks.get(`${connectorType}.${connectorLabel}`);
389
+ const modelName = connectorBlock?.attrs["model_name"];
390
+ const handle = typeof modelName === "string" ? tfLabelToTsLabel(sanitizeName(modelName)) : tfLabelToTsLabel(connectorLabel);
391
+ const providerIdAttr = connectorBlock?.attrs["provider_id"];
392
+ if (providerIdAttr === undefined || !isTfExpr(providerIdAttr) || providerIdAttr.$expr !== "data-attr")
393
+ return { handle };
394
+ const providerBlock = ctx.dataBlocks.get(`${providerIdAttr.type}.${providerIdAttr.label}`);
395
+ const providerName = providerBlock?.attrs["name"];
396
+ if (typeof providerName !== "string")
397
+ return { handle };
398
+ return { handle, providerKey: tfLabelToTsLabel(sanitizeName(providerName)) };
399
+ }
400
+ function decodeValue(value, ctx) {
401
+ if (isTfExpr(value)) {
402
+ if (value.$expr === "template") {
403
+ return { kind: "template", parts: value.parts.map((part) => typeof part === "string" ? part : decodeValue(part, ctx)) };
404
+ }
405
+ if (value.$expr === "jsonencode")
406
+ return decodePlain(value.value, ctx);
407
+ if (value.$expr === "resource-attr") {
408
+ if (value.type === ctx.trigger.type && value.label === ctx.trigger.label && value.path[0] === "refs") {
409
+ return { kind: "triggerRef", path: triggerRefPath(value.path.slice(1), ctx) };
410
+ }
411
+ const task = ctx.taskByAddress.get(`${value.type}.${value.label}`);
412
+ if (task !== undefined && value.path[0] === "refs") {
413
+ const rawSegments = pathNames(value.path.slice(1));
414
+ if (task.block.type === "elementum_record_search_task" && rawSegments.length === 1 && rawSegments[0] === "First found record id") {
415
+ return { kind: "taskRef", task: task.refKey, path: ["record", "recordId"] };
45
416
  }
46
- args["inputs"] = inputs;
47
- }
48
- const rawSchema = attrs["output_schema"];
49
- if (rawSchema !== undefined) {
50
- // Emitted as jsonencode({object:{properties:[{string:{name}},...]}}) —
51
- // invert to the authoring alias record ({NAME: "text"|...}).
52
- const schema = (isTfExpr(rawSchema) && rawSchema.$expr === "jsonencode" ? rawSchema.value : rawSchema);
53
- const aliasByTag = { string: "text", integer: "integer", number: "number", bool: "boolean" };
54
- const outputs = {};
55
- for (const prop of schema?.object?.properties ?? []) {
56
- const tag = Object.keys(prop)[0];
57
- const propName = tag !== undefined ? prop[tag]?.name : undefined;
58
- if (tag !== undefined && typeof propName === "string")
59
- outputs[propName] = aliasByTag[tag] ?? "text";
417
+ // createRecord/findRelatedRecords' own record-id output — confirmed
418
+ // live via `ei refs`: neither task exposes a "recordId" key at all;
419
+ // "Record" (ASPECT_RECORD_ID) is the real one, matching the
420
+ // provider's own schema docs (build.ts's rewriteForwardTaskRefName
421
+ // has the full citation). Previously unhandled here entirely — a
422
+ // pulled automation referencing this output round-tripped as a raw
423
+ // `ctx.tasks.<t>.Record` property access that doesn't exist on
424
+ // either task's typed output, failing tsc.
425
+ if ((task.block.type === "elementum_create_record_task" || task.block.type === "elementum_find_related_records_task") &&
426
+ rawSegments.length === 1 &&
427
+ rawSegments[0] === "Record") {
428
+ return { kind: "taskRef", task: task.refKey, path: ["record", "recordId"] };
60
429
  }
61
- if (Object.keys(outputs).length > 0)
62
- args["outputs"] = outputs;
430
+ if (task.block.type === "elementum_record_search_task" && rawSegments.length === 1) {
431
+ const recordSearchName = RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS[rawSegments[0]];
432
+ if (recordSearchName !== undefined) {
433
+ return { kind: "taskRef", task: task.refKey, path: [recordSearchName] };
434
+ }
435
+ }
436
+ const keyPath = rawSegments.flatMap((segment) => segment.split("."));
437
+ if (task.block.type === "elementum_variable_task") {
438
+ return { kind: "variableParamRef", varTask: task.refKey, name: keyPath.join(".") };
439
+ }
440
+ // Inverse of build.ts's OUTPUT_KEY_WIRE_NAME: a single-scalar-output
441
+ // task kind's wire name (e.g. aiClassify's "Response") reads back as
442
+ // the generic `output` accessor its EDK factory actually exposes.
443
+ const taskKind = task.block.type !== undefined ? TASK_FACTORIES[task.block.type] : undefined;
444
+ const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
445
+ const outputKeyPath = wireOutputKey !== undefined && keyPath[0] === wireOutputKey
446
+ ? ["output", ...keyPath.slice(1)]
447
+ : keyPath;
448
+ return { kind: "taskRef", task: task.refKey, path: outputKeyPath };
449
+ }
450
+ if (value.type === "elementum_app" && value.label === ctx.appTfLabel && value.path[0] === "id")
451
+ return appRef(ctx.appRefName);
452
+ if (value.type.endsWith("_field") && value.path[0] === "id") {
453
+ return {
454
+ kind: "field",
455
+ appHandle: ctx.appRefName,
456
+ fieldKey: scopedLabelToBagKey(ctx.appTfLabel, value.label),
457
+ };
458
+ }
459
+ if (value.type === AUTOMATION_RESOURCE_TYPE && value.path[0] === "id") {
460
+ return {
461
+ kind: "automation",
462
+ appHandle: ctx.appRefName,
463
+ automationKey: scopedLabelToBagKey(ctx.appTfLabel, value.label),
464
+ };
63
465
  }
64
- return { args };
466
+ if (value.type === "elementum_agent" && value.path[0] === "id") {
467
+ return { kind: "agent", appHandle: ctx.appRefName, agentKey: scopedLabelToBagKey(ctx.appTfLabel, value.label), name: value.label };
468
+ }
469
+ // IMPLEMENTED only, not ALL: a readFile task can reference an
470
+ // unimplemented reader type (ai/xml) - fileReaderFromTf correctly
471
+ // excludes those from extraction (no catalog entry is ever printed for
472
+ // them), so accepting the reference here would print a
473
+ // catalog.<app>.fileReaders.<key> access to a key that will never
474
+ // exist. Falling through to the throw below instead routes through
475
+ // automationOwnedAddresses (via extractAutomations' catch), which
476
+ // excludes the automation's FULL graph from adoption - not just this
477
+ // reference - the same safety net already proven for other
478
+ // unreconstructable references.
479
+ if (IMPLEMENTED_FILE_READER_RESOURCE_TYPES.includes(value.type) && value.path[0] === "id") {
480
+ return {
481
+ kind: "documentModel",
482
+ appHandle: ctx.appRefName,
483
+ documentModelKey: scopedLabelToBagKey(ctx.appTfLabel, value.label),
484
+ };
485
+ }
486
+ if (value.type === "elementum_approval_process" && value.path[0] === "id") {
487
+ const bare = bareChildResourceLabel(ctx.appTfLabel, value.label);
488
+ const unresolvedId = ctx.resourceImportIds.get(`${value.type}.${value.label}`);
489
+ return {
490
+ kind: "approvalChain",
491
+ appHandle: ctx.appRefName,
492
+ approvalChainKey: tfLabelToTsLabel(bare),
493
+ ...(unresolvedId !== undefined ? { unresolvedId } : {}),
494
+ };
495
+ }
496
+ throw new EntityTfError(`unreconstructable resource reference ${value.type}.${value.label}`);
497
+ }
498
+ if (value.$expr === "data-attr" && (value.type === "elementum_app" || value.type === "elementum_element") && value.path[0] === "id") {
499
+ const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
500
+ const name = lookup?.attrs.name;
501
+ return {
502
+ kind: "app",
503
+ appHandle: tfLabelToTsLabel(value.label),
504
+ entityType: value.type === "elementum_element" ? "element" : "app",
505
+ ...(typeof name === "string" ? { name } : {}),
506
+ };
507
+ }
508
+ if (value.$expr === "data-attr" && value.type === "elementum_field" && value.path[0] === "id") {
509
+ // The reverse of to-tf.ts's `crossAppFieldToTf`: a field belonging to a
510
+ // DIFFERENT app/element than this automation's own — resolved via the
511
+ // field's own `data.elementum_field` block, whose `object_id` names
512
+ // the owner's `data.elementum_app`/`data.elementum_element` lookup.
513
+ const fieldBlock = ctx.dataBlocks.get(`${value.type}.${value.label}`);
514
+ const objectId = fieldBlock?.attrs["object_id"];
515
+ if (objectId === undefined || !isTfExpr(objectId) || objectId.$expr !== "data-attr" || (objectId.type !== "elementum_app" && objectId.type !== "elementum_element")) {
516
+ throw new EntityTfError(`data.elementum_field.${value.label}: object_id is not a resolvable app/element data reference`);
517
+ }
518
+ const entityType = objectId.type === "elementum_element" ? "element" : "app";
519
+ const ownerLabel = objectId.label;
520
+ const kindPrefix = `${entityType}_${ownerLabel}_`;
521
+ const bareLabel = value.label.startsWith(kindPrefix)
522
+ ? value.label.slice(kindPrefix.length)
523
+ : value.label.startsWith(`${ownerLabel}_`)
524
+ ? value.label.slice(ownerLabel.length + 1)
525
+ : value.label;
526
+ const ownerName = ctx.dataBlocks.get(`${objectId.type}.${objectId.label}`)?.attrs["name"];
527
+ const fieldName = fieldBlock?.attrs["name"];
528
+ return {
529
+ kind: "field",
530
+ appHandle: tfLabelToTsLabel(ownerLabel),
531
+ fieldKey: tfLabelToTsLabel(bareLabel),
532
+ foreign: {
533
+ entityType,
534
+ name: typeof ownerName === "string" ? ownerName : tfLabelToTsLabel(ownerLabel),
535
+ ...(typeof fieldName === "string" ? { fieldName } : {}),
536
+ },
537
+ };
538
+ }
539
+ if (value.$expr === "data-attr" && value.type === "elementum_ai_provider_connector" && value.path[0] === "id") {
540
+ return { kind: "connector", id: "", ...resolveConnectorRef(value.type, value.label, ctx) };
65
541
  }
66
- case "variable": {
67
- // One variable per tf task: variable_name/variable_type/value.
68
- const decl = {
69
- name: str(attrs["variable_name"]) ?? "",
70
- type: str(attrs["variable_type"]) ?? "TEXT",
542
+ if (value.$expr === "data-attr" && value.type === "elementum_cloudlink" && value.path[0] === "id") {
543
+ const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
544
+ const name = lookup?.attrs.name;
545
+ return {
546
+ kind: "cloudLink",
547
+ handle: tfLabelToTsLabel(value.label),
548
+ ...(typeof name === "string" ? { name } : {}),
71
549
  };
72
- if (attrs["value"] !== undefined) {
73
- const converted = tfRefToAst(attrs["value"], refCtx);
74
- if ("unsupported" in converted)
75
- return { unsupported: `variable value: ${converted.unsupported}` };
76
- decl["value"] = converted.ast;
550
+ }
551
+ if (value.$expr === "local") {
552
+ const prefix = `${ctx.appTfLabel}_`;
553
+ if (value.name.startsWith(prefix) && value.name.endsWith("_field_id")) {
554
+ return { kind: "field", appHandle: ctx.appRefName, fieldKey: tfLabelToTsLabel(value.name.slice(prefix.length, -9)) };
555
+ }
556
+ // Outside filter values, preserve option lookups as an explicit local
557
+ // reference. Filters intentionally collapse the same expression to its
558
+ // readable label in filterValue(); task field assignments must retain
559
+ // the exact lookup so build reproduces the exported HCL.
560
+ if (picklistOptionLabel(value) !== undefined) {
561
+ return { kind: "localRef", localName: value.name, path: value.path };
77
562
  }
78
- return { args: { create: [decl] } };
563
+ throw new EntityTfError(`unreconstructable local reference local.${value.name}`);
79
564
  }
80
- default:
81
- return { args: {} };
565
+ throw new EntityTfError(`unsupported expression kind "${value.$expr}" in automation`);
82
566
  }
567
+ if (Array.isArray(value))
568
+ return value.map((item) => decodeValue(item, ctx));
569
+ if (isObject(value))
570
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, decodeValue(child, ctx)]));
571
+ return { kind: "literal", value };
83
572
  }
84
- /** Wire parameter type ("TEXT") → the authoring alias ("text"). */
85
- function paramTypeAlias(wireType) {
86
- const lower = wireType.toLowerCase();
87
- return lower === "bool" ? "boolean" : lower;
573
+ function decodePlain(value, ctx) {
574
+ const decoded = decodeValue(value, ctx);
575
+ if (isObject(decoded) && typeof decoded.kind === "string")
576
+ return decoded;
577
+ if (Array.isArray(decoded))
578
+ return decoded;
579
+ if (isObject(decoded))
580
+ return Object.fromEntries(Object.entries(decoded).map(([key, child]) => [key, decodePlain(child, ctx)]));
581
+ return decoded;
88
582
  }
89
- /** Build the `TriggerAst` for an implemented trigger block. */
90
- function triggerAst(typeKey, attrs) {
91
- switch (typeKey) {
583
+ function decodeCustomResponse(value, ctx) {
584
+ if (!isObject(value))
585
+ throw new EntityTfError("invalid custom_response");
586
+ const decodeSection = (section) => {
587
+ if (!isObject(section))
588
+ return undefined;
589
+ const format = typeof section.format === "string" ? section.format : "JSON";
590
+ // The provider contract stores webhook bodies as strings, including JSON
591
+ // strings. Decoding a plain string as a generic automation value wraps it
592
+ // in a literal RefExpr; stringifying that wrapper on every pull grows an
593
+ // additional { kind: "literal", value: ... } layer each round trip.
594
+ const bodyValue = typeof section.body === "string"
595
+ ? section.body
596
+ : section.body !== undefined ? decodeValue(section.body, ctx) : "";
597
+ const body = typeof bodyValue === "string" ? bodyValue : JSON.stringify(bodyValue);
598
+ return {
599
+ enabled: section.enabled === true,
600
+ format: format,
601
+ ...(typeof section.status_code === "number" ? { statusCode: section.status_code } : {}),
602
+ body,
603
+ };
604
+ };
605
+ const success = decodeSection(value.success);
606
+ const failure = decodeSection(value.failure);
607
+ if (success === undefined && failure === undefined)
608
+ return undefined;
609
+ return { ...(success !== undefined ? { success } : {}), ...(failure !== undefined ? { failure } : {}) };
610
+ }
611
+ function fieldRef(value, ctx) {
612
+ const decoded = decodeValue(value, ctx);
613
+ if (isObject(decoded) && decoded.kind === "field")
614
+ return decoded;
615
+ if (typeof value === "string")
616
+ return { kind: "unresolved", uuid: value, hint: "field" };
617
+ throw new EntityTfError("field reference cannot be reconstructed");
618
+ }
619
+ const USER_FIELD_KEY_SET = new Set(USER_FIELD_KEYS);
620
+ function userFieldRef(value, ctx) {
621
+ if (typeof value === "string" && USER_FIELD_KEY_SET.has(value)) {
622
+ return { kind: "userField", fieldKey: value };
623
+ }
624
+ return fieldRef(value, ctx);
625
+ }
626
+ function picklistOptionLabel(value) {
627
+ if (value === undefined || !isTfExpr(value) || value.$expr !== "local" || value.path.length !== 1)
628
+ return undefined;
629
+ const segment = value.path[0];
630
+ const isOptionsLookup = value.name.endsWith("_options_by_label") || value.name.endsWith("_option_ids_by_label");
631
+ return isOptionsLookup &&
632
+ typeof segment === "object" &&
633
+ segment !== null &&
634
+ "index" in segment &&
635
+ typeof segment.index === "string"
636
+ ? segment.index
637
+ : undefined;
638
+ }
639
+ // The platform emits a system-stage filter as a KEY-keyed local
640
+ // `<appTfLabel>_stage_ids_by_key["<stageKey>"]` (unlike status/dropdown, which are
641
+ // LABEL-keyed). Resolve the key against the app's reconstructed stages so the filter
642
+ // decodes to the stage name instead of leaking the raw local expression (#116).
643
+ function stageFilterName(value, ctx) {
644
+ if (value === undefined || !isTfExpr(value) || value.$expr !== "local" || value.path.length !== 1)
645
+ return undefined;
646
+ if (value.name !== `${ctx.appTfLabel}_stage_ids_by_key`)
647
+ return undefined;
648
+ const segment = value.path[0];
649
+ if (typeof segment !== "object" || segment === null || !("index" in segment) || typeof segment.index !== "string")
650
+ return undefined;
651
+ return ctx.stagesByKey.get(segment.index);
652
+ }
653
+ function filterValue(value, ctx) {
654
+ const directOptionLabel = picklistOptionLabel(value);
655
+ if (directOptionLabel !== undefined)
656
+ return { kind: "text", value: directOptionLabel };
657
+ const directStageName = stageFilterName(value, ctx);
658
+ if (directStageName !== undefined)
659
+ return { kind: "text", value: directStageName };
660
+ if (!isObject(value) || isTfExpr(value))
661
+ return decodeValue(value, ctx);
662
+ const type = typeof value.type === "string" ? value.type.toLowerCase() : undefined;
663
+ if (type === undefined)
664
+ return decodeValue(value, ctx);
665
+ if (type === "null")
666
+ return { kind: "null" };
667
+ if (type === "current_user") {
668
+ const raw = typeof value.current_user_type === "string" ? value.current_user_type.toLowerCase() : "id";
669
+ const currentUserType = raw === "email" || raw === "domain" ? raw : "id";
670
+ return { kind: "currentUser", currentUserType };
671
+ }
672
+ // The provider's `filter.value` schema splits "static" from "dynamic"
673
+ // across two distinct attributes — `value` vs `value_reference` (same
674
+ // split `left_value` already respects, decoded via `value_reference`
675
+ // just below in `decodeFilter`) — so a reference-typed value's payload
676
+ // lives under `value_reference`, not `value`.
677
+ if (type === "reference")
678
+ return { kind: "reference", ref: decodeValue(value.value_reference, ctx) };
679
+ if (["text", "number", "boolean", "uuid", "date", "datetime"].includes(type)) {
680
+ const optionLabel = picklistOptionLabel(value.value);
681
+ if (optionLabel !== undefined)
682
+ return { kind: "text", value: optionLabel };
683
+ const stageName = stageFilterName(value.value, ctx);
684
+ if (stageName !== undefined)
685
+ return { kind: "text", value: stageName };
686
+ const raw = value.value;
687
+ return { kind: type, value: raw };
688
+ }
689
+ if (type === "field")
690
+ return { kind: "reference", ref: fieldRef(value.value, ctx) };
691
+ throw new EntityTfError(`unsupported filter value type "${type}"`);
692
+ }
693
+ function decodeFilter(value, ctx, fieldScope = "app") {
694
+ if (!isObject(value) || isTfExpr(value) || typeof value.type !== "string")
695
+ throw new EntityTfError("invalid filter object");
696
+ const type = value.type.toLowerCase();
697
+ if (type === "true" || type === "false")
698
+ return { kind: type };
699
+ if (type === "and" || type === "or") {
700
+ if (!Array.isArray(value.children))
701
+ throw new EntityTfError(`${type} filter has no children`);
702
+ return { kind: type, children: value.children.map((child) => decodeFilter(child, ctx, fieldScope)) };
703
+ }
704
+ const left = value.field_id !== undefined
705
+ ? fieldScope === "user" ? userFieldRef(value.field_id, ctx) : fieldRef(value.field_id, ctx)
706
+ : isObject(value.left_value) && value.left_value.value_reference !== undefined
707
+ ? typeof value.left_value.value_reference === "string"
708
+ ? decodeReferenceString(value.left_value.value_reference, ctx)
709
+ : decodeTemplateTriggerRecordFieldRef(value.left_value.value_reference, ctx)
710
+ ?? decodeValue(value.left_value.value_reference, ctx)
711
+ : value.left_value !== undefined ? decodeValue(value.left_value, ctx) : undefined;
712
+ if (left === undefined)
713
+ throw new EntityTfError(`${type} filter has no left side`);
714
+ const not = value.not === true ? { not: true } : {};
715
+ if (type === "is_null")
716
+ return { kind: "isNull", left, ...not };
717
+ if (type === "in") {
718
+ if (!Array.isArray(value.values))
719
+ throw new EntityTfError("in filter has no values");
720
+ return { kind: "in", left, values: value.values.map((item) => filterValue(item, ctx)), ...not };
721
+ }
722
+ if (type === "between") {
723
+ if (!Array.isArray(value.values) || value.values.length !== 2)
724
+ throw new EntityTfError("between filter requires two values");
725
+ return { kind: "between", left, values: [filterValue(value.values[0], ctx), filterValue(value.values[1], ctx)], ...not };
726
+ }
727
+ const kindByType = {
728
+ equals: "eq", greater_than: "gt", greater_than_equals: "gte", less_than: "lt", less_than_equals: "lte", like: "like",
729
+ };
730
+ const kind = kindByType[type];
731
+ if (kind === undefined || value.value === undefined)
732
+ throw new EntityTfError(`unsupported filter type "${type}"`);
733
+ const right = filterValue(value.value, ctx);
734
+ return kind === "like"
735
+ ? { kind, left, right, ...not, ...(typeof value.case_insensitive === "boolean" ? { caseInsensitive: value.case_insensitive } : {}), ...(typeof value.mode === "string" ? { mode: value.mode.toLowerCase() } : {}) }
736
+ : { kind, left, right, ...not };
737
+ }
738
+ function triggerFromBlock(block, ctx) {
739
+ const kind = TRIGGER_KINDS[block.type];
740
+ if (kind === undefined)
741
+ throw new EntityTfError(`unknown trigger resource type "${block.type}"`);
742
+ const app = appRef(ctx.appRefName);
743
+ const filter = block.attrs.filter !== undefined ? decodeFilter(block.attrs.filter, ctx) : undefined;
744
+ switch (kind) {
92
745
  case "onDemand": {
93
- const params = Array.isArray(attrs["parameters"]) ? attrs["parameters"] : [];
94
- const inputs = params
95
- .map((p) => {
96
- const name = str(p["name"]);
97
- if (name === undefined)
98
- return undefined;
99
- return {
100
- name,
101
- type: paramTypeAlias(str(p["type"]) ?? "TEXT"),
102
- ...(p["required"] === true ? { required: true } : {}),
103
- ...(p["multiple"] === true ? { multiple: true } : {}),
104
- ...(str(p["default_value"]) !== undefined ? { defaultValue: str(p["default_value"]) } : {}),
105
- };
106
- })
107
- .filter((p) => p !== undefined);
746
+ const parameters = block.attrs.parameters ?? [];
747
+ if (!Array.isArray(parameters))
748
+ throw new EntityTfError("on-demand parameters must be an array");
749
+ return { kind, inputs: parameters.map((parameter) => {
750
+ if (!isObject(parameter) || typeof parameter.name !== "string" || typeof parameter.type !== "string")
751
+ throw new EntityTfError("invalid on-demand parameter");
752
+ // Inverse of to-tf's "attachment" special case above — the wire has
753
+ // no "attachmentId" spelling at all, but the authoring alias
754
+ // (onDemand's TriggerFieldTypeAlias) does. Map back so printed
755
+ // source uses a type-checkable alias instead of a raw wire string
756
+ // "attachment" that TriggerFieldTypeAlias doesn't accept.
757
+ const type = parameter.type === "attachment" ? "attachmentId" : parameter.type;
758
+ return { name: parameter.name, type, ...(parameter.required === true ? { required: true } : {}), ...(parameter.multiple === true ? { multiple: true } : {}), ...(parameter.default_value !== undefined ? { defaultValue: parameter.default_value } : {}), ...(typeof parameter.description === "string" ? { description: parameter.description } : {}) };
759
+ }), ...(block.attrs.show_triggered_by === true ? { showTriggeredBy: true } : {}) };
760
+ }
761
+ case "recordCreate":
762
+ case "recordUpdate":
763
+ case "attachment":
764
+ return { kind, app, ...(filter ? { filter } : {}), ...(Array.isArray(block.attrs.changed_fields) ? { changedFields: block.attrs.changed_fields.map((item) => fieldRef(item, ctx)) } : {}), ...(typeof block.attrs.think_ui === "boolean" ? { thinkUi: block.attrs.think_ui } : {}) };
765
+ case "commentAdded":
766
+ if (typeof block.attrs.conversation_type !== "string")
767
+ throw new EntityTfError("comment trigger requires conversation_type");
768
+ return { kind, app, conversationType: block.attrs.conversation_type, ...(filter ? { filter } : {}) };
769
+ case "conversationEnd":
770
+ if (typeof block.attrs.conversation_type !== "string")
771
+ throw new EntityTfError("conversation trigger requires conversation_type");
772
+ return { kind, app, conversationType: block.attrs.conversation_type };
773
+ case "webhook":
108
774
  return {
109
- kind: "onDemand",
110
- inputs,
111
- ...(attrs["show_triggered_by"] === true ? { showTriggeredBy: true } : {}),
775
+ kind,
776
+ ...(typeof block.attrs.authenticated === "boolean" ? { authenticated: block.attrs.authenticated } : {}),
777
+ ...(block.attrs.custom_response !== undefined ? { customResponse: decodeCustomResponse(block.attrs.custom_response, ctx) } : {}),
112
778
  };
779
+ case "approvalProcessStatusUpdated": {
780
+ if (block.attrs.approval_chain_template_id === undefined || typeof block.attrs.status !== "string")
781
+ throw new EntityTfError("approval trigger is incomplete");
782
+ const approvalChain = typeof block.attrs.approval_chain_template_id === "string"
783
+ ? block.attrs.approval_chain_template_id
784
+ : decodeValue(block.attrs.approval_chain_template_id, ctx);
785
+ if (typeof approvalChain !== "string" && (!isObject(approvalChain) || approvalChain.kind !== "approvalChain")) {
786
+ throw new EntityTfError("approval trigger has an unreconstructable approval chain");
787
+ }
788
+ return { kind, app, approvalChain: approvalChain, status: block.attrs.status };
113
789
  }
114
- default:
115
- return undefined;
790
+ case "dataMine":
791
+ if (typeof block.attrs.datamine_id !== "string")
792
+ throw new EntityTfError("datamine trigger requires datamine_id");
793
+ return { kind, datamineId: block.attrs.datamine_id, ...(typeof block.attrs.fire_on_alert === "boolean" ? { fireOnAlert: block.attrs.fire_on_alert } : {}), ...(typeof block.attrs.fire_on_recovery === "boolean" ? { fireOnRecovery: block.attrs.fire_on_recovery } : {}) };
794
+ case "emailReceived":
795
+ if (typeof block.attrs.email_alias_id !== "string")
796
+ throw new EntityTfError("email trigger requires email_alias_id");
797
+ return { kind, emailAliasId: block.attrs.email_alias_id };
798
+ case "slackMessage": return { kind };
799
+ case "surveyResponseCreate":
800
+ if (typeof block.attrs.survey_template_id !== "string")
801
+ throw new EntityTfError("survey trigger requires survey_template_id");
802
+ return { kind, app, survey: block.attrs.survey_template_id };
803
+ default: throw new EntityTfError(`trigger "${kind}" is outside the Terraform contract`);
116
804
  }
117
805
  }
806
+ function taskArgs(block, factory, ctx) {
807
+ const args = {};
808
+ for (const [attr, value] of Object.entries(block.attrs)) {
809
+ if (attr === "parent" || attr === "name" || attr === "depends_on")
810
+ continue;
811
+ if (attr === "filter") {
812
+ args.filter = decodeFilter(value, ctx, factory === "userSearch" ? "user" : "app");
813
+ continue;
814
+ }
815
+ if (attr === "fields" && (factory === "createRecord" || factory === "updateField")) {
816
+ if (!Array.isArray(value))
817
+ throw new EntityTfError(`${block.type}.${block.label}: fields must be an array`);
818
+ const values = {};
819
+ const unresolvable = [];
820
+ for (const item of value) {
821
+ if (!isObject(item) || item.field_id === undefined)
822
+ throw new EntityTfError(`${block.type}.${block.label}: invalid field assignment`);
823
+ const field = fieldRef(item.field_id, ctx);
824
+ // Unlike an orphaned TRIGGER record-path field ref (which degrades
825
+ // gracefully - see decodeReferenceString), an unresolved field_id
826
+ // here means ei's own export couldn't resolve the field either (most
827
+ // commonly: a createRecord/updateField task targets a FOREIGN app via
828
+ // object_id, and `--recursive=false` never discovers that app's
829
+ // fields at all). ei's raw export still writes a bare field_id string
830
+ // plus an unresolved-value placeholder (with its own "Unresolved
831
+ // value references" warning) - the live platform's Read() resolves
832
+ // the real field fine (it exists), so that placeholder permanently
833
+ // mismatches state on every plan. Nothing on the TS side can fix a
834
+ // gap in ei's own export scope, so - confirmed live against
835
+ // demoapptwo's "Create record app external" automation, whose target
836
+ // field lives on a different app - throw (same as any other
837
+ // unreconstructable reference) so the automation's full graph is
838
+ // excluded from adoption via automationOwnedAddresses, rather than
839
+ // permanently failing the adoption gate for the whole app. A
840
+ // foreign-target task typically has EVERY field assignment
841
+ // unresolvable for the same reason (confirmed live:
842
+ // conciergeforfield's cff_analyze_agent_performance_v3 has 13) - collect
843
+ // them all before throwing instead of stopping at the first, so the
844
+ // message doesn't look like a single-field fluke (#285).
845
+ if (field.kind !== "field") {
846
+ unresolvable.push(field.kind === "unresolved" ? field.uuid : "unknown");
847
+ continue;
848
+ }
849
+ values[field.fieldKey] = decodeValue(item.value, ctx);
850
+ }
851
+ if (unresolvable.length > 0) {
852
+ throw new EntityTfError(`${block.type}.${block.label}: ${unresolvable.length} field assignment${unresolvable.length === 1 ? "" : "s"} ` +
853
+ `reference${unresolvable.length === 1 ? "s" : ""} an unresolvable field (${unresolvable.join(", ")}) — ` +
854
+ `likely a foreign object_id target the export didn't recursively discover (--recursive=false)`);
855
+ }
856
+ args.values = values;
857
+ continue;
858
+ }
859
+ if (attr === "inputs" && factory === "executeScript") {
860
+ if (!Array.isArray(value))
861
+ throw new EntityTfError("script inputs must be an array");
862
+ args.inputs = Object.fromEntries(value.map((item) => {
863
+ if (!isObject(item) || typeof item.name !== "string")
864
+ throw new EntityTfError("invalid script input");
865
+ return [item.name, decodeValue(item.value, ctx)];
866
+ }));
867
+ continue;
868
+ }
869
+ if (attr === "output_schema" && factory === "executeScript") {
870
+ const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
871
+ const props = isObject(raw) && isObject(raw.object) && Array.isArray(raw.object.properties) ? raw.object.properties : [];
872
+ args.outputs = Object.fromEntries(props.map((property) => {
873
+ if (!isObject(property))
874
+ throw new EntityTfError("invalid script output schema");
875
+ const [type, definition] = Object.entries(property)[0] ?? [];
876
+ if (type === undefined || !isObject(definition) || typeof definition.name !== "string")
877
+ throw new EntityTfError("invalid script output property");
878
+ return [definition.name, type === "bool" ? "boolean" : type];
879
+ }));
880
+ continue;
881
+ }
882
+ if (attr === "calculations" && factory === "calculation") {
883
+ if (!Array.isArray(value))
884
+ throw new EntityTfError("calculations must be an array");
885
+ args.calculations = value.map((item) => {
886
+ if (!isObject(item) || typeof item.variable_name !== "string" || item.formula === undefined) {
887
+ throw new EntityTfError(`${block.type}.${block.label}: invalid calculation entry`);
888
+ }
889
+ return { name: item.variable_name, expression: decodeValue(item.formula, ctx) };
890
+ });
891
+ continue;
892
+ }
893
+ if (attr === "categories" && factory === "aiClassify") {
894
+ if (!Array.isArray(value))
895
+ throw new EntityTfError("classification categories must be an array");
896
+ args.categorySource = {
897
+ type: "static",
898
+ categories: value.map((item) => {
899
+ if (!isObject(item) || item.label === undefined)
900
+ throw new EntityTfError("invalid classification category");
901
+ return {
902
+ name: decodeValue(item.label, ctx),
903
+ ...(item.description !== undefined ? { description: decodeValue(item.description, ctx) } : {}),
904
+ };
905
+ }),
906
+ };
907
+ continue;
908
+ }
909
+ if (attr === "list" && factory === "forEach") {
910
+ args.collection = decodeValue(value, ctx);
911
+ continue;
912
+ }
913
+ if (attr === "code" && factory === "executeScript") {
914
+ args.code = value;
915
+ continue;
916
+ }
917
+ if (attr === "record_id" && factory === "saveAttachment") {
918
+ args.recordRef = decodeValue(value, ctx);
919
+ continue;
920
+ }
921
+ if (attr === "source_record_ids" && factory === "relateRecords") {
922
+ const decoded = decodeValue(value, ctx);
923
+ args.sources = Array.isArray(decoded) ? decoded : [decoded];
924
+ continue;
925
+ }
926
+ if (attr === "output_type" && factory === "aiAgent") {
927
+ args.outputType = typeof value === "string" ? value.toLowerCase() : decodeValue(value, ctx);
928
+ continue;
929
+ }
930
+ // procedure()'s wire shape wraps each positional argument as
931
+ // `{index, value}` (see tasks.ts's procedure()); ProcedureOptions.parameters
932
+ // is a plain, position-ordered array - unwrap rather than round-tripping
933
+ // the index wrapper verbatim, which procedure() doesn't accept.
934
+ if (attr === "parameters" && factory === "procedure") {
935
+ if (!Array.isArray(value))
936
+ throw new EntityTfError(`${block.type}.${block.label}: procedure parameters must be an array`);
937
+ const sorted = [...value].sort((a, b) => {
938
+ const ai = isObject(a) && typeof a.index === "number" ? a.index : 0;
939
+ const bi = isObject(b) && typeof b.index === "number" ? b.index : 0;
940
+ return ai - bi;
941
+ });
942
+ args.parameters = sorted.map((item) => {
943
+ if (!isObject(item) || item.value === undefined)
944
+ throw new EntityTfError(`${block.type}.${block.label}: invalid procedure parameter`);
945
+ return decodeValue(item.value, ctx);
946
+ });
947
+ continue;
948
+ }
949
+ // createRecord's relate-to-record feature is carried by ONE attribute on
950
+ // the wire (relate_to_record_reference) - its presence alone implies
951
+ // relateToRecord: true (the provider has no separate boolean attribute).
952
+ if (attr === "relate_to_record_reference" && factory === "createRecord") {
953
+ args.record = decodeValue(value, ctx);
954
+ args.relateToRecord = true;
955
+ continue;
956
+ }
957
+ // elementum_file_reader_task's four data-source attrs are mutually
958
+ // exclusive (the provider schema enforces exactly one) - readFile's
959
+ // authoring shape collapses them into one discriminated dataSource arg.
960
+ if (factory === "documentModel" && (attr === "raw_text" || attr === "attachment" || attr === "attachment_id" || attr === "file")) {
961
+ const type = attr === "raw_text" ? "rawText" : attr === "attachment_id" ? "attachmentId" : attr;
962
+ args.dataSource = { type, value: decodeValue(value, ctx) };
963
+ continue;
964
+ }
965
+ if (attr === "source_record_ids" && factory === "relateRecords") {
966
+ const decoded = decodeValue(value, ctx);
967
+ args.sources = Array.isArray(decoded) ? decoded : [decoded];
968
+ continue;
969
+ }
970
+ // apiRequest's bearer_auth/oauth/custom_body/multipart_body (and
971
+ // basic_auth's reference_password) carry nested multi-word wire
972
+ // attribute names - the generic decodeValue object walk below preserves
973
+ // nested keys verbatim (snake_case, as exported), so these need the
974
+ // same explicit per-key mapping as tasks.ts's matching to-tf encode.
975
+ if (attr === "basic_auth" && factory === "apiRequest") {
976
+ if (!isObject(value))
977
+ throw new EntityTfError(`${block.type}.${block.label}: basic_auth must be an object`);
978
+ args.basicAuth = {
979
+ username: decodeValue(value.username, ctx),
980
+ ...(value.reference_password !== undefined ? { referencePassword: decodeValue(value.reference_password, ctx) } : {}),
981
+ };
982
+ continue;
983
+ }
984
+ if (attr === "bearer_auth" && factory === "apiRequest") {
985
+ if (!isObject(value))
986
+ throw new EntityTfError(`${block.type}.${block.label}: bearer_auth must be an object`);
987
+ args.bearerAuth = {
988
+ ...(value.token !== undefined ? { token: value.token } : {}),
989
+ ...(value.reference_token !== undefined ? { referenceToken: decodeValue(value.reference_token, ctx) } : {}),
990
+ };
991
+ continue;
992
+ }
993
+ if (attr === "oauth" && factory === "apiRequest") {
994
+ if (!isObject(value))
995
+ throw new EntityTfError(`${block.type}.${block.label}: oauth must be an object`);
996
+ const headers = Array.isArray(value.headers)
997
+ ? value.headers.map((h) => {
998
+ if (!isObject(h))
999
+ throw new EntityTfError(`${block.type}.${block.label}: invalid oauth header`);
1000
+ return { name: h.name, value: decodeValue(h.value, ctx) };
1001
+ })
1002
+ : undefined;
1003
+ args.oauth = {
1004
+ requestType: value.request_type,
1005
+ ...(value.url !== undefined ? { url: decodeValue(value.url, ctx) } : {}),
1006
+ ...(value.client_id !== undefined ? { clientId: value.client_id } : {}),
1007
+ ...(value.client_secret !== undefined ? { clientSecret: value.client_secret } : {}),
1008
+ ...(headers !== undefined ? { headers } : {}),
1009
+ };
1010
+ continue;
1011
+ }
1012
+ if (attr === "form_body" && factory === "apiRequest") {
1013
+ if (!Array.isArray(value))
1014
+ throw new EntityTfError(`${block.type}.${block.label}: form_body must be an array`);
1015
+ args.formBody = value.map((item) => {
1016
+ if (!isObject(item))
1017
+ throw new EntityTfError(`${block.type}.${block.label}: invalid form_body entry`);
1018
+ return { key: item.key, value: decodeValue(item.value, ctx) };
1019
+ });
1020
+ continue;
1021
+ }
1022
+ if (attr === "custom_body" && factory === "apiRequest") {
1023
+ if (!isObject(value))
1024
+ throw new EntityTfError(`${block.type}.${block.label}: custom_body must be an object`);
1025
+ args.customBody = {
1026
+ contentType: value.content_type,
1027
+ content: decodeValue(value.content, ctx),
1028
+ };
1029
+ continue;
1030
+ }
1031
+ if (attr === "multipart_body" && factory === "apiRequest") {
1032
+ if (!isObject(value) || !Array.isArray(value.parts))
1033
+ throw new EntityTfError(`${block.type}.${block.label}: multipart_body.parts must be an array`);
1034
+ args.multipartBody = {
1035
+ parts: value.parts.map((part) => {
1036
+ if (!isObject(part))
1037
+ throw new EntityTfError(`${block.type}.${block.label}: invalid multipart_body part`);
1038
+ return {
1039
+ name: part.name,
1040
+ ...(part.value !== undefined ? { value: decodeValue(part.value, ctx) } : {}),
1041
+ ...(part.attachment !== undefined ? { attachment: decodeValue(part.attachment, ctx) } : {}),
1042
+ ...(part.attachment_id !== undefined ? { attachmentId: decodeValue(part.attachment_id, ctx) } : {}),
1043
+ ...(part.file !== undefined ? { file: decodeValue(part.file, ctx) } : {}),
1044
+ };
1045
+ }),
1046
+ };
1047
+ continue;
1048
+ }
1049
+ // elementum_notification_task's `message` wire attribute means
1050
+ // notification()'s `message` option, not postComment()'s `contents` -
1051
+ // ATTR_TO_ARG's message → "contents" entry is correct for
1052
+ // elementum_message_task (which shares the same wire attribute name)
1053
+ // but wrong here. See edk#112.
1054
+ if (attr === "message" && factory === "notification") {
1055
+ args.message = decodeValue(value, ctx);
1056
+ continue;
1057
+ }
1058
+ const arg = ATTR_TO_ARG[attr] ?? attr.replace(/_([a-z])/g, (_, char) => char.toUpperCase());
1059
+ args[arg] = decodeValue(value, ctx);
1060
+ }
1061
+ if (["recordSearch", "createRecord", "updateField"].includes(factory))
1062
+ args.app ??= appRef(ctx.appRefName);
1063
+ if (factory === "findRelatedRecords") {
1064
+ args.relatedApp = args.app ?? appRef(ctx.appRefName);
1065
+ delete args.app;
1066
+ }
1067
+ if (factory === "setVariable") {
1068
+ if (block.type === "elementum_variable_task") {
1069
+ if (typeof block.attrs.variable_name !== "string" || typeof block.attrs.variable_type !== "string")
1070
+ throw new EntityTfError("variable task is incomplete");
1071
+ return { create: [{ name: block.attrs.variable_name, type: block.attrs.variable_type, ...(block.attrs.value !== undefined ? { value: decodeValue(block.attrs.value, ctx) } : {}) }] };
1072
+ }
1073
+ // The provider's real attribute is variable_reference (renamed from a
1074
+ // prior "variable" - confirmed against update_variable_task_resource.go's
1075
+ // current schema); the AST/authoring key stays "variable" (SetVariableOptions.update[].variable).
1076
+ return { update: [{ variable: decodeValue(block.attrs.variable_reference, ctx), value: decodeValue(block.attrs.value, ctx) }] };
1077
+ }
1078
+ return args;
1079
+ }
1080
+ function parentAddress(block) {
1081
+ const parent = resourceRef(block.attrs.parent);
1082
+ if (parent === undefined)
1083
+ throw new EntityTfError(`${block.type}.${block.label}: missing or invalid parent`);
1084
+ const suffix = parent.path.length > 0 ? `.${pathNames(parent.path).join(".")}` : "";
1085
+ return `${parent.type}.${parent.label}${suffix}`;
1086
+ }
1087
+ function taskRefKey(block, automationLabel, appTfLabel) {
1088
+ const autoChild = childPartFromScopedLabel(appTfLabel, automationLabel, "app");
1089
+ const taskChild = childPartFromScopedLabel(appTfLabel, block.label ?? "", "app");
1090
+ const tail = taskChild.startsWith(`${autoChild}_`) ? taskChild.slice(autoChild.length + 1) : taskChild;
1091
+ const taskName = typeof block.attrs.name === "string" ? block.attrs.name : undefined;
1092
+ if (taskName !== undefined) {
1093
+ const sanitized = sanitizeName(taskName);
1094
+ // ei sanitizes `<automation>_<task>` as ONE combined string
1095
+ // (imports.go), so the digit-leading guard only ever sees the
1096
+ // automation's own first character - a task name that itself starts
1097
+ // with a digit loses its own underscore fix once the automation's
1098
+ // child part is stripped back off above, so `sanitized` (computed on
1099
+ // the task name alone) still carries the underscore `tail` lacks
1100
+ // (issue #79).
1101
+ const matches = sanitized === tail || sanitized === `_${tail}`;
1102
+ if (matches && (taskName === tail || /[_\s-]/.test(taskName)))
1103
+ return taskName;
1104
+ }
1105
+ return tfLabelToTsLabel(/^[0-9]/.test(tail) ? `_${tail}` : tail);
1106
+ }
118
1107
  /**
119
- * Reconstruct one automation. `blocks` are the family blocks that belong to it
120
- * (already grouped by the caller: same `automation` ref / workflow_publish
121
- * depends_on set). Returns `{ automation }` or `{ skippedReason }`.
1108
+ * Best-effort resource footprint of one automation, used ONLY when whole-
1109
+ * automation extraction throws (module.ts's `extractAutomations` catch
1110
+ * branch) so adoption can exclude the FULL graph - not just the automation
1111
+ * root - from its import scope. Without this, a trigger/task/branch/publish
1112
+ * address is individually still an "adoptable" resource TYPE (the kind
1113
+ * works fine for OTHER automations), so it gets imported into state anyway;
1114
+ * build then can't reproduce what it never wrote to source, and `plan`
1115
+ * shows those addresses as destroy-on-apply (confirmed live: several
1116
+ * automations that failed extraction were imported into state anyway,
1117
+ * driving spurious destroys). Deliberately lenient - tolerant of the exact
1118
+ * conditions that make real extraction fail (zero/multiple triggers, an
1119
+ * unrecognized task kind) - so it over-collects rather than under-collects:
1120
+ * a false positive here just leaves one more resource unmanaged, a false
1121
+ * negative would silently destroy a live automation on apply.
122
1122
  */
123
- export function automationFromTf(blocks, ctx) {
124
- const automation = blocks.find((b) => b.type === AUTOMATION_RESOURCE_TYPE);
125
- if (automation === undefined || automation.label === undefined) {
126
- return { skippedReason: "no elementum_automation block in the group" };
127
- }
128
- const autoLabel = automation.label;
129
- const name = str(automation.attrs["name"]) ?? autoLabel;
130
- const where = `automation "${name}"`;
131
- // Trigger — exactly one per automation.
132
- const triggerBlock = blocks.find((b) => {
133
- const row = b.type !== undefined ? AUTOMATION_SUB_TYPE_BY_RESOURCE.get(b.type) : undefined;
134
- return row !== undefined && b.type?.endsWith("_trigger");
135
- });
136
- if (triggerBlock === undefined || triggerBlock.type === undefined) {
137
- return { skippedReason: `${where}: no trigger block` };
138
- }
139
- const triggerRow = AUTOMATION_SUB_TYPE_BY_RESOURCE.get(triggerBlock.type);
140
- if (triggerRow.implemented !== true) {
141
- ctx.diagnostics.push(`${where}: trigger kind ${triggerBlock.type} is not carried yet; skipped`);
142
- return { skippedReason: `${where}: unimplemented trigger ${triggerBlock.type}` };
143
- }
144
- const trigger = triggerAst(triggerRow.typeKey, triggerBlock.attrs);
145
- if (trigger === undefined)
146
- return { skippedReason: `${where}: no triggerAst for ${triggerRow.typeKey}` };
147
- // Tasks — walk the parent chain from the trigger to recover order.
148
- const taskBlocks = blocks.filter((b) => b.type?.endsWith("_task"));
149
- // Recover each task's authored refKey. The tf label is snake_case (ei's
150
- // labeling rule), so it is LOSSY for caps/spaces — but the block's `name`
151
- // attribute carries the exact authored name, and for EDK-authored tasks
152
- // name == refKey. Adopt `name` as the refKey whenever the label provably
153
- // derives from it (sanitizeName(name) == label suffix); otherwise keep the
154
- // label-suffix refKey and surface `name` as the displayName (a platform-
155
- // authored task whose name doesn't map to its label).
156
- const refKeyByLabel = new Map();
157
- for (const b of taskBlocks) {
158
- if (b.label === undefined)
159
- continue;
160
- const suffix = b.label.startsWith(`${autoLabel}_`) ? b.label.slice(autoLabel.length + 1) : b.label;
161
- const taskName = str(b.attrs["name"]);
162
- refKeyByLabel.set(b.label, taskName !== undefined && sanitizeName(taskName) === suffix ? taskName : suffix);
163
- }
164
- const refCtx = {
165
- autoLabel,
166
- isTriggerType: (type) => type.endsWith("_trigger") && AUTOMATION_SUB_TYPE_BY_RESOURCE.has(type),
167
- refKeyByLabel,
168
- };
169
- const childrenOf = (parentType, parentLabel) => taskBlocks.filter((b) => {
170
- const p = b.attrs["parent"];
171
- return (isTfExpr(p) && p.$expr === "resource-attr" && p.type === parentType && p.label === parentLabel);
172
- });
173
- const tasks = [];
174
- let curType = triggerBlock.type;
175
- let curLabel = autoLabel;
176
- const seen = new Set();
177
- for (;;) {
178
- const next = childrenOf(curType, curLabel);
179
- if (next.length === 0)
180
- break;
181
- if (next.length > 1) {
182
- ctx.diagnostics.push(`${where}: task "${curLabel}" has multiple children (branch/operator), not carried yet; stopping chain`);
183
- }
184
- const block = next[0];
185
- const addr = `${block.type}.${block.label}`;
186
- if (seen.has(addr)) {
187
- ctx.diagnostics.push(`${where}: cyclic parent chain at ${addr}; stopping`);
188
- break;
189
- }
190
- seen.add(addr);
191
- const row = block.type !== undefined ? AUTOMATION_SUB_TYPE_BY_RESOURCE.get(block.type) : undefined;
192
- if (row === undefined || row.implemented !== true || FACTORY_BY_TYPE_KEY[row.typeKey] === undefined) {
193
- ctx.diagnostics.push(`${where}: task ${addr} of an unimplemented kind; skipped`);
194
- curType = block.type;
195
- curLabel = block.label;
196
- continue;
197
- }
198
- const refKey = refKeyByLabel.get(block.label ?? "") ?? (block.label ?? "");
199
- const displayName = str(block.attrs["name"]);
200
- const extracted = taskArgs(row.typeKey, block.attrs, refCtx);
201
- if ("unsupported" in extracted) {
202
- ctx.diagnostics.push(`${where}: task ${addr}: ${extracted.unsupported}; skipped`);
203
- curType = block.type;
204
- curLabel = block.label;
205
- continue;
206
- }
207
- const call = {
208
- factory: FACTORY_BY_TYPE_KEY[row.typeKey],
209
- refKey,
210
- args: extracted.args,
211
- ...(displayName !== undefined && displayName !== refKey ? { displayName } : {}),
212
- };
213
- tasks.push(call);
214
- curType = block.type;
215
- curLabel = block.label;
1123
+ export function automationOwnedAddresses(doc, automationLabel) {
1124
+ const owned = new Set([`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`]);
1125
+ for (const block of doc.blocks) {
1126
+ if (block.kind === "resource" && block.type !== undefined && block.label !== undefined &&
1127
+ references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel)) {
1128
+ owned.add(`${block.type}.${block.label}`);
1129
+ }
1130
+ }
1131
+ let changed = true;
1132
+ while (changed) {
1133
+ changed = false;
1134
+ for (const block of doc.blocks) {
1135
+ if (block.kind !== "resource" || block.type === undefined || block.label === undefined)
1136
+ continue;
1137
+ const address = `${block.type}.${block.label}`;
1138
+ if (owned.has(address))
1139
+ continue;
1140
+ const parent = resourceRef(block.attrs.parent) ?? resourceRef(block.attrs.switch_task) ?? resourceRef(block.attrs.fork_join_task);
1141
+ if (parent !== undefined && owned.has(`${parent.type}.${parent.label}`)) {
1142
+ owned.add(address);
1143
+ changed = true;
1144
+ }
1145
+ }
1146
+ }
1147
+ return [...owned];
1148
+ }
1149
+ /** Extract one app-owned automation graph from an ei app export. */
1150
+ function automationFromTfDocument(doc, automationLabel, appRefName) {
1151
+ const automation = doc.blocks.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE && block.label === automationLabel);
1152
+ if (automation === undefined)
1153
+ throw new EntityTfError(`automation resource "${automationLabel}" not found`);
1154
+ assertAllowed(automation, new Set(["app_id", "name", "description", "triggers_other_automations", "depends_on"]));
1155
+ const app = resourceRef(automation.attrs.app_id);
1156
+ if (app === undefined || app.type !== "elementum_app" || app.path[0] !== "id")
1157
+ throw new EntityTfError(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}: app_id is not an app reference`);
1158
+ const triggers = doc.blocks.filter((block) => block.kind === "resource" && AUTOMATION_TRIGGER_TYPE_SET.has(block.type ?? "") && references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel));
1159
+ const publish = doc.blocks.find((block) => block.kind === "resource" && block.type === WORKFLOW_PUBLISH_RESOURCE_TYPE && references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel));
1160
+ const unknownDirectChild = doc.blocks.find((block) => block.kind === "resource" &&
1161
+ references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel) &&
1162
+ block.type !== WORKFLOW_PUBLISH_RESOURCE_TYPE &&
1163
+ !AUTOMATION_TRIGGER_TYPE_SET.has(block.type ?? ""));
1164
+ if (unknownDirectChild) {
1165
+ throw new EntityTfError(`unknown automation resource type "${unknownDirectChild.type}"`);
1166
+ }
1167
+ if (triggers.length !== 1)
1168
+ throw new EntityTfError(`automation "${automationLabel}" must have exactly one trigger; found ${triggers.length}`);
1169
+ const trigger = triggers[0];
1170
+ assertAllowed(trigger, TRIGGER_ATTRIBUTES);
1171
+ if (publish !== undefined)
1172
+ assertAllowed(publish, PUBLISH_ATTRIBUTES);
1173
+ const branches = doc.blocks.filter((block) => block.kind === "resource" && AUTOMATION_BRANCH_TYPE_SET.has(block.type ?? ""));
1174
+ const taskCandidates = doc.blocks.filter((block) => block.kind === "resource" && ALL_AUTOMATION_TASK_TYPE_SET.has(block.type ?? ""));
1175
+ const resourceBlocks = new Map(doc.blocks.filter((block) => block.kind === "resource" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
1176
+ const owned = new Set([`${trigger.type}.${trigger.label}`]);
1177
+ let changed = true;
1178
+ while (changed) {
1179
+ changed = false;
1180
+ for (const branch of branches) {
1181
+ const owner = resourceRef(branch.attrs.switch_task ?? branch.attrs.fork_join_task);
1182
+ if (owner && owned.has(`${owner.type}.${owner.label}`) && !owned.has(`${branch.type}.${branch.label}`)) {
1183
+ owned.add(`${branch.type}.${branch.label}`);
1184
+ changed = true;
1185
+ }
1186
+ }
1187
+ for (const task of taskCandidates) {
1188
+ const parent = resourceRef(task.attrs.parent);
1189
+ if (parent && owned.has(`${parent.type}.${parent.label}`) && !owned.has(`${task.type}.${task.label}`)) {
1190
+ owned.add(`${task.type}.${task.label}`);
1191
+ changed = true;
1192
+ }
1193
+ }
1194
+ }
1195
+ const tasks = taskCandidates.filter((block) => owned.has(`${block.type}.${block.label}`));
1196
+ const ownedBranches = branches.filter((block) => owned.has(`${block.type}.${block.label}`));
1197
+ tasks.forEach((block) => assertAllowed(block, TASK_ATTRIBUTES));
1198
+ ownedBranches.forEach((block) => assertAllowed(block, BRANCH_ATTRIBUTES));
1199
+ const publishDependencies = Array.isArray(publish?.attrs.depends_on)
1200
+ ? publish.attrs.depends_on.map((value) => resourceRef(value)).filter((value) => value !== undefined)
1201
+ : [];
1202
+ for (const dependency of publishDependencies) {
1203
+ if (dependency.type.startsWith("elementum_") &&
1204
+ dependency.type !== trigger.type &&
1205
+ !ALL_AUTOMATION_TASK_TYPE_SET.has(dependency.type) &&
1206
+ !AUTOMATION_BRANCH_TYPE_SET.has(dependency.type) &&
1207
+ dependency.type !== WORKFLOW_PUBLISH_RESOURCE_TYPE) {
1208
+ throw new EntityTfError(`unknown automation resource type "${dependency.type}"`);
1209
+ }
1210
+ const address = `${dependency.type}.${dependency.label}`;
1211
+ if (!ALL_AUTOMATION_TASK_TYPE_SET.has(dependency.type) || owned.has(address))
1212
+ continue;
1213
+ const seen = new Set();
1214
+ let cursor = address;
1215
+ while (cursor !== undefined && !owned.has(cursor)) {
1216
+ if (seen.has(cursor))
1217
+ throw new EntityTfError(`cycle detected at ${cursor}`);
1218
+ seen.add(cursor);
1219
+ const block = resourceBlocks.get(cursor);
1220
+ if (block === undefined)
1221
+ throw new EntityTfError(`${cursor}: unresolved parent`);
1222
+ const parent = resourceRef(block.attrs.parent);
1223
+ if (parent === undefined)
1224
+ throw new EntityTfError(`${cursor}: missing parent`);
1225
+ cursor = `${parent.type}.${parent.label}`;
1226
+ }
1227
+ throw new EntityTfError(`automation "${automationLabel}" contains an orphaned task ${address}`);
216
1228
  }
217
- // Workflow outputs live on the publish block ([{name, value: refs expr}]).
218
- const publish = blocks.find((b) => b.type === WORKFLOW_PUBLISH_RESOURCE_TYPE);
219
- const workflowRevision = publish !== undefined ? str(publish.attrs["workflow_revision"]) : undefined;
220
- const outputs = [];
221
- const rawOutputs = publish !== undefined && Array.isArray(publish.attrs["outputs"]) ? publish.attrs["outputs"] : [];
222
- for (const o of rawOutputs) {
223
- const outName = str(o?.name);
224
- if (outName === undefined)
1229
+ for (const task of tasks) {
1230
+ const parent = resourceRef(task.attrs.parent);
1231
+ if (parent === undefined || !owned.has(`${parent.type}.${parent.label}`))
1232
+ throw new EntityTfError(`${task.type}.${task.label}: unresolved parent`);
1233
+ if (parent.path.length > 0 && !(parent.type === "elementum_for_each_task" && parent.path.length === 1 && parent.path[0] === "inner")) {
1234
+ throw new EntityTfError(`${task.type}.${task.label}: unsupported parent path`);
1235
+ }
1236
+ }
1237
+ const appTfLabel = app.label;
1238
+ const taskByAddress = new Map(tasks.map((block) => [`${block.type}.${block.label}`, { block, refKey: taskRefKey(block, automationLabel, appTfLabel) }]));
1239
+ const resourceImportIds = new Map();
1240
+ for (const block of doc.blocks) {
1241
+ if (block.kind !== "import" || typeof block.attrs.id !== "string")
1242
+ continue;
1243
+ const target = resourceRef(block.attrs.to);
1244
+ if (target === undefined)
225
1245
  continue;
226
- const converted = tfRefToAst((o.value ?? ""), refCtx);
227
- if ("unsupported" in converted) {
228
- ctx.diagnostics.push(`${where}: output "${outName}": ${converted.unsupported}; skipped`);
1246
+ const unresolvedId = block.attrs.id.split(/[:/]/).at(-1);
1247
+ if (unresolvedId !== undefined && unresolvedId !== "")
1248
+ resourceImportIds.set(`${target.type}.${target.label}`, unresolvedId);
1249
+ }
1250
+ const fieldById = new Map();
1251
+ for (const [address, id] of resourceImportIds) {
1252
+ const block = resourceBlocks.get(address);
1253
+ if (block?.type?.endsWith("_field") !== true || block.label === undefined)
229
1254
  continue;
1255
+ fieldById.set(id, {
1256
+ key: scopedLabelToBagKey(appTfLabel, block.label ?? ""),
1257
+ name: typeof block.attrs.name === "string" ? block.attrs.name : block.label,
1258
+ });
1259
+ }
1260
+ const dataBlocks = new Map(doc.blocks.filter((block) => block.kind === "data" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
1261
+ const stagesByKey = new Map();
1262
+ const stagesAttr = resourceBlocks.get(`elementum_app.${app.label}`)?.attrs["stages"];
1263
+ if (Array.isArray(stagesAttr)) {
1264
+ for (const item of stagesAttr) {
1265
+ if (isObject(item) && !isTfExpr(item) && typeof item.key === "string" && typeof item.name === "string")
1266
+ stagesByKey.set(item.key, item.name);
230
1267
  }
231
- outputs.push({ name: outName, value: converted.ast });
232
1268
  }
1269
+ const ctx = { appRefName, appTfLabel: app.label, trigger, taskByAddress, resourceBlocks, dataBlocks, resourceImportIds, fieldById, stagesByKey };
1270
+ const dependencyOrder = new Map();
1271
+ if (publish && Array.isArray(publish.attrs.depends_on))
1272
+ publish.attrs.depends_on.forEach((dep, index) => { const ref = resourceRef(dep); if (ref)
1273
+ dependencyOrder.set(`${ref.type}.${ref.label}`, index); });
1274
+ const childrenByParent = new Map();
1275
+ for (const task of tasks) {
1276
+ const parent = parentAddress(task);
1277
+ childrenByParent.set(parent, [...(childrenByParent.get(parent) ?? []), task]);
1278
+ }
1279
+ for (const list of childrenByParent.values())
1280
+ list.sort((a, b) => (dependencyOrder.get(`${a.type}.${a.label}`) ?? Number.MAX_SAFE_INTEGER) - (dependencyOrder.get(`${b.type}.${b.label}`) ?? Number.MAX_SAFE_INTEGER) || a.label.localeCompare(b.label));
1281
+ const visiting = new Set();
1282
+ const visited = new Set();
1283
+ const buildTasks = (parent) => (childrenByParent.get(parent) ?? []).flatMap((block) => {
1284
+ const address = `${block.type}.${block.label}`;
1285
+ if (visiting.has(address))
1286
+ throw new EntityTfError(`cycle detected at ${address}`);
1287
+ visiting.add(address);
1288
+ visited.add(address);
1289
+ const factory = TASK_FACTORIES[block.type];
1290
+ if (factory === undefined)
1291
+ throw new EntityTfError(`unknown task resource type "${block.type}"`);
1292
+ const refKey = taskByAddress.get(address).refKey;
1293
+ let children;
1294
+ if (factory === "forEach")
1295
+ children = [{ label: null, tasks: buildTasks(`${address}.inner`) }];
1296
+ if (factory === "switchTask" || factory === "forkJoin") {
1297
+ const branchAttr = factory === "switchTask" ? "switch_task" : "fork_join_task";
1298
+ const matching = ownedBranches.filter((branch) => references(branch.attrs[branchAttr], block.type, block.label));
1299
+ matching.sort((a, b) => (dependencyOrder.get(`${a.type}.${a.label}`) ?? Number.MAX_SAFE_INTEGER) - (dependencyOrder.get(`${b.type}.${b.label}`) ?? Number.MAX_SAFE_INTEGER) || a.label.localeCompare(b.label));
1300
+ children = matching.map((branch) => {
1301
+ const shape = factory === "switchTask" ? defaultSwitchShape(branch) : undefined;
1302
+ const isDefault = shape !== undefined;
1303
+ const rawLabel = typeof branch.attrs.label === "string" ? branch.attrs.label : undefined;
1304
+ return {
1305
+ label: isDefault ? null : rawLabel ?? null,
1306
+ // ei always writes SOME display label on the default case, but it's
1307
+ // not always the literal string "Default" (e.g. a manual rename to
1308
+ // "Default Path") - carry the real text so the printer/build round
1309
+ // trip can reproduce it instead of hardcoding "Default".
1310
+ ...(isDefault && rawLabel !== undefined ? { defaultLabel: rawLabel } : {}),
1311
+ // Carry the observed wire shape only when it's the older
1312
+ // filter-based one - the newer is_default shape is to-tf.ts's
1313
+ // unmarked default, so leaving this unset there keeps printed
1314
+ // output terse and matches a freshly-authored default branch.
1315
+ ...(shape === "explicitTrueFilter" ? { defaultFilterMode: shape } : {}),
1316
+ ...(!isDefault && branch.attrs.filter !== undefined ? { filter: decodeFilter(branch.attrs.filter, ctx) } : {}),
1317
+ tasks: buildTasks(`${branch.type}.${branch.label}`),
1318
+ };
1319
+ });
1320
+ }
1321
+ const parent = resourceRef(block.attrs.parent);
1322
+ const parentTask = parent === undefined ? undefined : taskByAddress.get(`${parent.type}.${parent.label}`);
1323
+ const hclParent = parent?.type === trigger.type && parent?.label === trigger.label ? "trigger" : parentTask?.refKey;
1324
+ const call = { factory, refKey, args: taskArgs(block, factory, ctx), ...(children ? { children } : {}), ...(typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {}), ...(hclParent !== undefined ? { hclParent } : {}) };
1325
+ visiting.delete(address);
1326
+ return [call, ...buildTasks(address)];
1327
+ });
1328
+ const topTasks = buildTasks(`${trigger.type}.${trigger.label}`);
1329
+ if (visited.size !== tasks.length)
1330
+ throw new EntityTfError(`automation "${automationLabel}" contains an orphaned task graph`);
1331
+ const outputBlocks = publish?.attrs.outputs;
1332
+ const outputs = Array.isArray(outputBlocks) ? outputBlocks.map((output) => {
1333
+ if (!isObject(output) || typeof output.name !== "string" || output.value === undefined)
1334
+ throw new EntityTfError("invalid workflow output");
1335
+ return { name: output.name, value: decodeValue(output.value, ctx) };
1336
+ }) : undefined;
1337
+ const exportedRevision = publish?.attrs.workflow_revision;
1338
+ if (exportedRevision !== undefined && typeof exportedRevision !== "string") {
1339
+ throw new EntityTfError(`${WORKFLOW_PUBLISH_RESOURCE_TYPE}.${automationLabel}: workflow_revision must be a string`);
1340
+ }
1341
+ const ast = {
1342
+ ownerHandle: appRefName,
1343
+ name: typeof automation.attrs.name === "string" ? automation.attrs.name : "",
1344
+ workflowRevision: exportedRevision ?? "1.0.0",
1345
+ ...(typeof automation.attrs.description === "string" ? { description: automation.attrs.description } : {}),
1346
+ ...(typeof automation.attrs.triggers_other_automations === "boolean" ? { triggersOtherAutomations: automation.attrs.triggers_other_automations } : {}),
1347
+ status: publish ? "ACTIVE" : "DRAFT",
1348
+ trigger: triggerFromBlock(trigger, ctx),
1349
+ tasks: topTasks,
1350
+ ...(outputs && outputs.length > 0 ? { outputs } : {}),
1351
+ };
233
1352
  return {
234
- automation: {
235
- ownerHandle: ctx.ownerHandle,
236
- name,
237
- status: "DRAFT",
238
- ...(workflowRevision !== undefined ? { workflowRevision } : {}),
239
- trigger,
240
- tasks,
241
- ...(outputs.length > 0 ? { outputs } : {}),
242
- },
1353
+ refName: scopedLabelToBagKey(appTfLabel, automationLabel),
1354
+ tfLabel: automationLabel, ast, blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])]
243
1355
  };
244
1356
  }
245
- /** Recognizes the blocks that make up automation families (for the pull partition). */
246
- export function isAutomationFamilyType(type) {
247
- if (type === undefined)
248
- return false;
249
- return (type === AUTOMATION_RESOURCE_TYPE ||
250
- type === WORKFLOW_PUBLISH_RESOURCE_TYPE ||
251
- AUTOMATION_SUB_TYPE_BY_RESOURCE.has(type));
1357
+ export function automationFromTf(first, second, third) {
1358
+ if (Array.isArray(first)) {
1359
+ const ctx = second;
1360
+ const automationBlock = first.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE);
1361
+ if (automationBlock?.label === undefined) {
1362
+ return { skippedReason: "automation resource not found" };
1363
+ }
1364
+ try {
1365
+ return { automation: automationFromTfDocument({ blocks: [...first] }, automationBlock.label, ctx.ownerHandle).ast };
1366
+ }
1367
+ catch (err) {
1368
+ const message = err instanceof Error ? err.message : String(err);
1369
+ ctx.diagnostics.push(message);
1370
+ return { skippedReason: message };
1371
+ }
1372
+ }
1373
+ return automationFromTfDocument(first, second, third ?? "");
252
1374
  }