@elementumai/edk 0.8.0-preview.11 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.md +378 -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 +65 -2
  6. package/dist-sdk/src/catalog/from-authoring.js +6 -1
  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 +83 -6
  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 +14 -0
  14. package/dist-sdk/src/catalog/types.d.ts +60 -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 +20 -1
  21. package/dist-sdk/src/engine/build/context.d.ts +18 -0
  22. package/dist-sdk/src/engine/build/source-context.d.ts +45 -0
  23. package/dist-sdk/src/engine/build/source-context.js +23 -0
  24. package/dist-sdk/src/engine/pull/context.d.ts +15 -0
  25. package/dist-sdk/src/engine/pull/org.d.ts +10 -0
  26. package/dist-sdk/src/engine/pull/org.js +34 -4
  27. package/dist-sdk/src/engine/tf/index.d.ts +1 -1
  28. package/dist-sdk/src/engine/tf/index.js +1 -1
  29. package/dist-sdk/src/engine/tf/labels.d.ts +45 -0
  30. package/dist-sdk/src/engine/tf/labels.js +71 -0
  31. package/dist-sdk/src/entities/access-policy/build.d.ts +26 -0
  32. package/dist-sdk/src/entities/access-policy/build.js +7 -0
  33. package/dist-sdk/src/entities/access-policy/filter.d.ts +61 -0
  34. package/dist-sdk/src/entities/access-policy/filter.js +83 -0
  35. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +48 -0
  36. package/dist-sdk/src/entities/access-policy/from-tf.js +189 -0
  37. package/dist-sdk/src/entities/access-policy/module.d.ts +3 -0
  38. package/dist-sdk/src/entities/access-policy/module.js +17 -0
  39. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +36 -0
  40. package/dist-sdk/src/entities/access-policy/to-tf.js +149 -0
  41. package/dist-sdk/src/entities/access-policy/types.d.ts +4 -0
  42. package/dist-sdk/src/entities/access-policy/types.js +10 -0
  43. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +38 -3
  44. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +199 -32
  45. package/dist-sdk/src/entities/agent/from-tf.d.ts +18 -3
  46. package/dist-sdk/src/entities/agent/from-tf.js +135 -15
  47. package/dist-sdk/src/entities/agent/index.d.ts +1 -1
  48. package/dist-sdk/src/entities/agent/module.js +8 -2
  49. package/dist-sdk/src/entities/agent/to-tf.js +62 -10
  50. package/dist-sdk/src/entities/agent/tools.d.ts +88 -9
  51. package/dist-sdk/src/entities/agent/tools.js +46 -7
  52. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +51 -4
  53. package/dist-sdk/src/entities/agent-tool/from-tf.js +131 -35
  54. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +4 -2
  55. package/dist-sdk/src/entities/agent-tool/to-tf.js +103 -17
  56. package/dist-sdk/src/entities/agent-tool/types.d.ts +5 -4
  57. package/dist-sdk/src/entities/agent-tool/types.js +38 -6
  58. package/dist-sdk/src/entities/app/build.d.ts +63 -13
  59. package/dist-sdk/src/entities/app/build.js +48 -1
  60. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +3 -0
  61. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -1
  62. package/dist-sdk/src/entities/app/from-tf.js +32 -15
  63. package/dist-sdk/src/entities/app/index.d.ts +4 -1
  64. package/dist-sdk/src/entities/app/index.js +2 -1
  65. package/dist-sdk/src/entities/app/module.js +9 -2
  66. package/dist-sdk/src/entities/app/to-tf.d.ts +5 -0
  67. package/dist-sdk/src/entities/app/to-tf.js +33 -4
  68. package/dist-sdk/src/entities/automation/build.d.ts +57 -13
  69. package/dist-sdk/src/entities/automation/build.js +48 -36
  70. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +25 -8
  71. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +16 -1
  72. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +179 -43
  73. package/dist-sdk/src/entities/automation/filter.d.ts +15 -3
  74. package/dist-sdk/src/entities/automation/filter.js +12 -2
  75. package/dist-sdk/src/entities/automation/from-tf.d.ts +26 -27
  76. package/dist-sdk/src/entities/automation/from-tf.js +1229 -223
  77. package/dist-sdk/src/entities/automation/index.d.ts +4 -0
  78. package/dist-sdk/src/entities/automation/index.js +4 -0
  79. package/dist-sdk/src/entities/automation/module.js +29 -32
  80. package/dist-sdk/src/entities/automation/operators.d.ts +29 -2
  81. package/dist-sdk/src/entities/automation/operators.js +27 -1
  82. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +19 -0
  83. package/dist-sdk/src/entities/automation/output-key-wire-name.js +24 -0
  84. package/dist-sdk/src/entities/automation/script-code.d.ts +10 -21
  85. package/dist-sdk/src/entities/automation/script-code.js +272 -5
  86. package/dist-sdk/src/entities/automation/tasks.d.ts +125 -19
  87. package/dist-sdk/src/entities/automation/tasks.js +83 -15
  88. package/dist-sdk/src/entities/automation/to-tf.d.ts +10 -29
  89. package/dist-sdk/src/entities/automation/to-tf.js +1134 -231
  90. package/dist-sdk/src/entities/automation/triggers.d.ts +9 -1
  91. package/dist-sdk/src/entities/automation/types.d.ts +29 -4
  92. package/dist-sdk/src/entities/automation/types.js +76 -46
  93. package/dist-sdk/src/entities/element/build.d.ts +23 -10
  94. package/dist-sdk/src/entities/element/build.js +1 -0
  95. package/dist-sdk/src/entities/element/from-tf.d.ts +1 -1
  96. package/dist-sdk/src/entities/element/from-tf.js +18 -3
  97. package/dist-sdk/src/entities/element/index.d.ts +4 -1
  98. package/dist-sdk/src/entities/element/index.js +2 -1
  99. package/dist-sdk/src/entities/element/module.js +3 -1
  100. package/dist-sdk/src/entities/element/to-tf.js +21 -3
  101. package/dist-sdk/src/entities/field/build.d.ts +56 -13
  102. package/dist-sdk/src/entities/field/build.js +10 -0
  103. package/dist-sdk/src/entities/field/calc/runtime.js +4 -0
  104. package/dist-sdk/src/entities/field/from-tf.d.ts +5 -3
  105. package/dist-sdk/src/entities/field/from-tf.js +118 -7
  106. package/dist-sdk/src/entities/field/module.js +3 -2
  107. package/dist-sdk/src/entities/field/to-tf.d.ts +27 -9
  108. package/dist-sdk/src/entities/field/to-tf.js +62 -17
  109. package/dist-sdk/src/entities/field/types.d.ts +26 -0
  110. package/dist-sdk/src/entities/field/types.js +34 -12
  111. package/dist-sdk/src/entities/file-reader/build.d.ts +108 -50
  112. package/dist-sdk/src/entities/file-reader/build.js +23 -23
  113. package/dist-sdk/src/entities/file-reader/deserializer/print-file-reader.d.ts +6 -0
  114. package/dist-sdk/src/entities/file-reader/deserializer/print-file-reader.js +109 -0
  115. package/dist-sdk/src/entities/file-reader/from-tf.d.ts +13 -0
  116. package/dist-sdk/src/entities/file-reader/from-tf.js +172 -0
  117. package/dist-sdk/src/entities/file-reader/index.d.ts +8 -3
  118. package/dist-sdk/src/entities/file-reader/index.js +7 -2
  119. package/dist-sdk/src/entities/file-reader/module.d.ts +3 -0
  120. package/dist-sdk/src/entities/file-reader/module.js +115 -0
  121. package/dist-sdk/src/entities/file-reader/to-tf.d.ts +14 -0
  122. package/dist-sdk/src/entities/file-reader/to-tf.js +84 -0
  123. package/dist-sdk/src/entities/file-reader/types.d.ts +32 -0
  124. package/dist-sdk/src/entities/file-reader/types.js +30 -0
  125. package/dist-sdk/src/entities/org/ai-provider.d.ts +13 -0
  126. package/dist-sdk/src/entities/org/ai-provider.js +46 -0
  127. package/dist-sdk/src/entities/org/connector.d.ts +8 -1
  128. package/dist-sdk/src/entities/org/connector.js +12 -14
  129. package/dist-sdk/src/entities/org/group.js +10 -1
  130. package/dist-sdk/src/entities/org/index.d.ts +1 -0
  131. package/dist-sdk/src/entities/org/index.js +1 -0
  132. package/dist-sdk/src/entities/org/user.js +10 -1
  133. package/dist-sdk/src/entities/shared/filters/ast.d.ts +44 -9
  134. package/dist-sdk/src/entities/shared/filters/types.d.ts +1 -1
  135. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +17 -0
  136. package/dist-sdk/src/entities/shared/tool-field-ref.js +31 -0
  137. package/dist-sdk/src/entities/shared/types/field-types.d.ts +10 -1
  138. package/dist-sdk/src/entities/shared/types/field-types.js +9 -0
  139. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +19 -0
  140. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +36 -8
  141. package/dist-sdk/src/entities/skill/from-tf.js +4 -3
  142. package/dist-sdk/src/entities/skill/index.d.ts +1 -1
  143. package/dist-sdk/src/entities/skill/module.js +6 -1
  144. package/dist-sdk/src/entities/skill/to-tf.js +3 -2
  145. package/dist-sdk/src/entities/skill/tools.d.ts +25 -3
  146. package/dist-sdk/src/entities/skill/tools.js +17 -0
  147. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +15 -2
  148. package/dist-sdk/src/entities/skill-tool/from-tf.js +32 -11
  149. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +2 -0
  150. package/dist-sdk/src/entities/skill-tool/to-tf.js +32 -9
  151. package/dist-sdk/src/entities/view/from-tf.d.ts +6 -2
  152. package/dist-sdk/src/entities/view/from-tf.js +11 -9
  153. package/dist-sdk/src/entities/view/to-tf.d.ts +9 -7
  154. package/dist-sdk/src/entities/view/to-tf.js +33 -18
  155. package/dist-sdk/src/entities/view/types.d.ts +1 -1
  156. package/dist-sdk/src/entities/view/types.js +1 -1
  157. package/dist-sdk/src/graph/deferred-catalog-render.d.ts +0 -5
  158. package/dist-sdk/src/graph/deferred-catalog-render.js +1 -20
  159. package/dist-sdk/src/graph/index.d.ts +8 -0
  160. package/dist-sdk/src/graph/index.js +13 -9
  161. package/dist-sdk/src/graph/modules.js +6 -1
  162. package/dist-sdk/src/graph/types.d.ts +77 -3
  163. package/package.json +42 -14
  164. package/dist-sdk/src/entities/automation/value-ref-tf.d.ts +0 -76
  165. package/dist-sdk/src/entities/automation/value-ref-tf.js +0 -190
@@ -1,266 +1,1169 @@
1
- /**
2
- * Automation emission (Phase 1). `automationToTf` consumes the discovered
3
- * `DeployableEntity` (the `defineAutomation` def() payload) and emits the
4
- * COMPOSITE ei dialect:
5
- *
6
- * elementum_automation.<autoLabel> — identity (app_id, name, ...)
7
- * elementum_<trigger>_trigger.<autoLabel> — the one trigger (automation ref)
8
- * elementum_<task>_task.<autoLabel>_<task> — one per task, parent-chained
9
- * elementum_workflow_publish.<autoLabel> — version + depends_on(all tasks)
10
- *
11
- * Labels follow ei's export: the automation label is `sanitizeName(name)` and a
12
- * task label is `<autoLabel>_<sanitizeName(taskName)>` — so build output matches
13
- * ei's addresses for adoption/build-vs-export. Ordering is encoded exactly as ei does it:
14
- * each task's `parent` points at the previous task (or the trigger, for the
15
- * first). References are BARE resource refs (`elementum_automation.x`, no `.id`),
16
- * matching the capture.
17
- *
18
- * Phase 1 carries the onDemand trigger and the executeScript + setVariable
19
- * (create form → elementum_variable_task) tasks. Any other trigger/task kind, or
20
- * an operator (forEach/forkJoin/switch), degrades through `diagnostics` —
21
- * reported, never silently dropped (plan §6). Task BODY attributes beyond the
22
- * Phase-1 set are reconciled against a fresh live capture (see the tranche plan).
23
- */
24
1
  import { EntityTfError } from "../../engine/entity.js";
25
- import { expr, sanitizeName } from "../../engine/tf/index.js";
26
- import { APP_RESOURCE_TYPE } from "../app/module.js";
27
- import { indexVariableIds, wireRefToTf } from "./value-ref-tf.js";
28
- import { AUTOMATION_RESOURCE_TYPE, AUTOMATION_SUB_TYPE_BY_TYPE_KEY, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
29
- /** A bare resource reference (`elementum_automation.x`, no attribute path). */
30
- function bareRef(type, label) {
31
- return expr.resourceAttr(type, label, []);
2
+ import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET } from "../../core/system-fields.js";
3
+ import { appResourceLabelPrefix, appScopedResourceLabel, expr, isTfExpr, isUuid, sanitizeName, snakeSlug, tsLabelToTfLabel, } from "../../engine/tf/index.js";
4
+ import { CONNECTOR_ORG_BAG } from "../org/connector.js";
5
+ import { FILE_READER_SUB_TYPE_BY_TYPE_KEY } from "../file-reader/types.js";
6
+ import { AUTOMATION_RESOURCE_TYPE, WORKFLOW_PUBLISH_RESOURCE_TYPE } from "./types.js";
7
+ function scopedLabel(appTfLabel, label) {
8
+ return appScopedResourceLabel(appTfLabel, label);
32
9
  }
33
- /** Discriminant + body of a one-of wire object (`{ onDemand: {...} }`). */
34
- function oneOf(wire) {
35
- if (wire === undefined || typeof wire !== "object")
36
- return undefined;
37
- const key = Object.keys(wire)[0];
38
- if (key === undefined)
10
+ function scopedOptionLocalName(localName, owner) {
11
+ for (const suffix of ["_options_by_label", "_option_ids_by_label"]) {
12
+ if (!localName.endsWith(suffix))
13
+ continue;
14
+ const fieldLabel = localName.slice(0, -suffix.length);
15
+ if (fieldLabel === `${owner.appTfLabel}_status` || fieldLabel === `${owner.appTfLabel}_stage`) {
16
+ return localName;
17
+ }
18
+ const prefix = appResourceLabelPrefix(owner.appTfLabel);
19
+ if (prefix !== "" && fieldLabel.startsWith(prefix))
20
+ return localName;
21
+ return `${scopedLabel(owner.appTfLabel, fieldLabel)}${suffix}`;
22
+ }
23
+ return localName;
24
+ }
25
+ const TRIGGER_RESOURCES = {
26
+ createRecord: "elementum_record_created_trigger",
27
+ updateRecord: "elementum_record_updated_trigger",
28
+ attachment: "elementum_attachment_added_trigger",
29
+ commentAdded: "elementum_comment_added_trigger",
30
+ conversationEnd: "elementum_agent_conversation_ended_trigger",
31
+ slackMessage: "elementum_slack_message_trigger",
32
+ onDemand: "elementum_on_demand_trigger",
33
+ webhook: "elementum_webhook_trigger",
34
+ emailReceived: "elementum_email_ingestion_trigger",
35
+ approvalChain: "elementum_approval_chain_trigger",
36
+ datamine: "elementum_datamine_trigger",
37
+ survey: "elementum_survey_trigger",
38
+ };
39
+ const TASK_RESOURCES = {
40
+ message: "elementum_message_task",
41
+ updateField: "elementum_update_field_task",
42
+ variable: "elementum_variable_task",
43
+ createRecord: "elementum_create_record_task",
44
+ recordSearch: "elementum_record_search_task",
45
+ tableRecordsSearch: "elementum_table_records_search_task",
46
+ sendEmail: "elementum_send_email_task",
47
+ initiateCall: "elementum_initiate_call_task",
48
+ approvalChain: "elementum_approval_chain_task",
49
+ approvalStatusUpdate: "elementum_approval_status_update_task",
50
+ findRelatedRecords: "elementum_find_related_records_task",
51
+ api: "elementum_api_task",
52
+ aiAgent: "elementum_ai_agent_task",
53
+ forEach: "elementum_for_each_task",
54
+ switch: "elementum_switch_task",
55
+ forkJoin: "elementum_fork_join_task",
56
+ addWatcher: "elementum_add_watcher_task",
57
+ notification: "elementum_notification_task",
58
+ relateRecords: "elementum_relate_records_task",
59
+ aiClassify: "elementum_ai_classify_task",
60
+ aiSummarize: "elementum_ai_summarize_task",
61
+ aiSearchTable: "elementum_ai_search_table_task",
62
+ aiTransform: "elementum_ai_transform_task",
63
+ saveAttachment: "elementum_save_attachment_task",
64
+ userSearch: "elementum_user_search_task",
65
+ calculation: "elementum_calculation_task",
66
+ executeScript: "elementum_execute_script_task",
67
+ documentModel: "elementum_file_reader_task",
68
+ procedure: "elementum_procedure_task",
69
+ runAutomation: "elementum_run_automation_task",
70
+ aspectRecordFieldLocking: "elementum_aspect_record_field_locking_task",
71
+ aiFileAnalysis: "elementum_ai_file_read_task",
72
+ };
73
+ const CONFIG_ATTRS = {
74
+ aspectId: "object_id",
75
+ relatedAspectId: "object_id",
76
+ aspectFieldId: "field_id",
77
+ changedFieldIds: "changed_fields",
78
+ thinkUi: "think_ui",
79
+ conversationType: "conversation_type",
80
+ customResponse: "custom_response",
81
+ showTriggeredBy: "show_triggered_by",
82
+ datamineId: "datamine_id",
83
+ fireOnAlert: "fire_on_alert",
84
+ fireOnRecovery: "fire_on_recovery",
85
+ emailAliasId: "email_alias_id",
86
+ approvalChainTemplateId: "approval_chain_template_id",
87
+ surveyTemplateId: "survey_template_id",
88
+ workflowFields: "fields",
89
+ recordReference: "record_reference",
90
+ recordId: "record_reference",
91
+ sourceRecordIds: "source_record_ids",
92
+ targetRecordId: "target_record_id",
93
+ tableId: "table_id",
94
+ messageBody: "message_body",
95
+ fromUsername: "from_username",
96
+ fromPersonal: "from_personal",
97
+ externalEmails: "external_emails",
98
+ emailAttachments: "attachments",
99
+ contentsReference: "message",
100
+ agentId: "agent_id",
101
+ agentPrompt: "prompt",
102
+ outputType: "output_type",
103
+ jsonFields: "json_fields",
104
+ aiProviderConnectorId: "ai_provider_connector_id",
105
+ outputSchema: "output_schema",
106
+ urlReference: "url",
107
+ responseType: "response_type",
108
+ continueOnError: "continue_on_error",
109
+ searchTableId: "search_table_id",
110
+ textToSummarize: "text_to_summarize",
111
+ textToClassify: "text_to_classify",
112
+ fieldType: "field_type",
113
+ categorySource: "category_source",
114
+ titleReference: "title",
115
+ messageReference: "message",
116
+ userValueReferences: "user_value_references",
117
+ groupValueReferences: "group_value_references",
118
+ notifyWatchers: "notify_watchers",
119
+ fieldId: "field_id",
120
+ userId: "user_id",
121
+ groupId: "group_id",
122
+ fieldsToLock: "fields_to_lock",
123
+ fieldsToUnlock: "fields_to_unlock",
124
+ fileInput: "file",
125
+ viewState: "view_state",
126
+ targetAutomationId: "target_automation_id",
127
+ targetAutomationRef: "target_automation_ref",
128
+ inputMappings: "input_mappings",
129
+ dynamicInputMappings: "dynamic_input_mappings",
130
+ outputMappings: "output_mappings",
131
+ fileReaderId: "file_reader_id",
132
+ rawText: "raw_text",
133
+ cloudLinkId: "cloudlink_id",
134
+ // provider schema calls this stored_function_id; see from-tf.ts's matching comment.
135
+ procedureId: "stored_function_id",
136
+ };
137
+ function isObject(value) {
138
+ return value !== null && typeof value === "object" && !Array.isArray(value);
139
+ }
140
+ function onlyEntry(value, subject) {
141
+ if (!isObject(value))
142
+ throw new EntityTfError(`${subject} must be an object`);
143
+ const entries = Object.entries(value);
144
+ if (entries.length !== 1 || !isObject(entries[0][1])) {
145
+ throw new EntityTfError(`${subject} must contain exactly one supported type`);
146
+ }
147
+ return entries[0];
148
+ }
149
+ function token(value) {
150
+ if (!isObject(value) || typeof value.__kind !== "string" || typeof value.refName !== "string")
39
151
  return undefined;
40
- const body = wire[key];
41
- return { key, body: body !== null && typeof body === "object" ? body : {} };
152
+ return value;
42
153
  }
43
- /**
44
- * Type-specific task-body attributes for the implemented task kinds. Returns
45
- * `unsupported` (the caller reports it) when the body carries something the
46
- * terraform dialect can't encode — never emits it wrong.
47
- */
48
- function taskBodyAttrs(typeKey, body, refCtx) {
49
- switch (typeKey) {
50
- case "executeScript": {
51
- const attrs = {};
52
- attrs["code"] = typeof body["code"] === "string" ? body["code"] : "";
53
- // Inputs: [{name, value: <ref envelope>}] → [{name, value: refs-syntax expr | literal}].
54
- const inputs = [];
55
- for (const entry of body["inputs"] ?? []) {
56
- if (typeof entry?.name !== "string")
57
- continue;
58
- const converted = wireRefToTf(entry.value, refCtx);
59
- if ("unsupported" in converted) {
60
- return { unsupported: `input "${entry.name}": ${converted.unsupported}` };
61
- }
62
- inputs.push({ name: entry.name, value: converted.value });
154
+ function addressExpr(address, path = ["id"]) {
155
+ const dot = address.indexOf(".");
156
+ if (dot === -1)
157
+ throw new EntityTfError(`invalid terraform address "${address}"`);
158
+ return expr.resourceAttr(address.slice(0, dot), address.slice(dot + 1), [...path]);
159
+ }
160
+ function tokenToTf(value, ctx, dataBlocks) {
161
+ switch (value.__kind) {
162
+ case "userField":
163
+ return value.refName;
164
+ case "app":
165
+ case "element":
166
+ if (value.refName !== ctx.appRefName) {
167
+ if (!value.name)
168
+ throw new EntityTfError(`cross-aspect ref "${value.refName}" has no lookup name`);
169
+ const type = value.__kind === "element" ? "elementum_element" : "elementum_app";
170
+ const label = tsLabelToTfLabel(value.refName);
171
+ dataBlocks.set(`${type}.${label}`, {
172
+ kind: "data",
173
+ type,
174
+ label,
175
+ attrs: { name: value.name },
176
+ });
177
+ return expr.dataAttr(type, label, ["id"]);
178
+ }
179
+ return expr.resourceAttr("elementum_app", ctx.appTfLabel, ["id"]);
180
+ case "field": {
181
+ if (value.parent !== undefined && value.parent !== ctx.appRefName) {
182
+ throw new EntityTfError(`cross-app field ref "${value.parent}.${value.refName}" is not reproducible offline`);
63
183
  }
64
- attrs["inputs"] = inputs;
65
- // The provider takes output_schema as a JSON-encoDED string.
66
- if (body["outputSchema"] !== undefined) {
67
- attrs["output_schema"] = { $expr: "jsonencode", value: body["outputSchema"] };
184
+ const address = ctx.fieldAddresses.get(value.refName);
185
+ return address === undefined
186
+ ? expr.local(`${ctx.appTfLabel}_${tsLabelToTfLabel(value.refName)}_field_id`)
187
+ : addressExpr(address);
188
+ }
189
+ case "connector": {
190
+ const tsLabel = value.parent !== undefined ? `${value.parent}.${value.refName}` : value.refName;
191
+ const resolved = ctx.orgRefs?.byTsLabel(CONNECTOR_ORG_BAG, tsLabel);
192
+ if (resolved === undefined) {
193
+ throw new EntityTfError(`connector token "${tsLabel}" is not in the org catalog — re-run \`elementum pull org --data-only\``);
194
+ }
195
+ return expr.dataAttr("elementum_ai_provider_connector", resolved.tfLabel, ["id"]);
196
+ }
197
+ case "cloudLink": {
198
+ if (!value.name)
199
+ throw new EntityTfError(`cloud link token "${value.refName}" has no lookup name`);
200
+ const label = tsLabelToTfLabel(value.refName);
201
+ dataBlocks.set(`elementum_cloudlink.${label}`, {
202
+ kind: "data",
203
+ type: "elementum_cloudlink",
204
+ label,
205
+ attrs: { name: value.name },
206
+ });
207
+ return expr.dataAttr("elementum_cloudlink", label, ["id"]);
208
+ }
209
+ case "automation":
210
+ if (value.parent !== undefined && value.parent !== ctx.appRefName) {
211
+ throw new EntityTfError(`cross-app automation ref "${value.parent}.${value.refName}" is not supported`);
68
212
  }
69
- return { attrs };
70
- }
71
- case "variable": {
72
- // The tf dialect carries ONE variable per task: variable_name /
73
- // variable_type / value. (The compose id is stamped for the compose
74
- // path; the provider's variable_id is Computed — no id in HCL.)
75
- const create = body["create"] ?? [];
76
- if (create.length !== 1) {
77
- return { unsupported: `elementum_variable_task carries exactly one variable; got ${create.length}` };
213
+ return expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
214
+ case "agent":
215
+ return expr.resourceAttr("elementum_agent", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
216
+ case "searchTable":
217
+ return expr.resourceAttr("elementum_ai_search_table", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
218
+ case "approvalChain":
219
+ return value.unresolvedId !== undefined
220
+ ? value.unresolvedId
221
+ : expr.resourceAttr("elementum_approval_process", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
222
+ case "documentModel": {
223
+ const subType = FILE_READER_SUB_TYPE_BY_TYPE_KEY.get(value.readerType ?? "");
224
+ // "xml"/"ai" are declared sub-types (FILE_READER_SUB_TYPES) but don't
225
+ // build yet - matches fileReaderToTf's own implemented guard. Without
226
+ // this, a readFile task referencing one would silently emit a
227
+ // reference to a resource block that's never written, failing only at
228
+ // `tofu plan`/`apply` instead of at build.
229
+ if (subType === undefined || subType.implemented !== true) {
230
+ throw new EntityTfError(`file reader token "${value.refName}" has no recognized readerType ("${value.readerType}") — was it built with defineFileReader?`);
78
231
  }
79
- const decl = create[0];
80
- const attrs = {
81
- variable_name: decl.name ?? "",
82
- variable_type: decl.type ?? "TEXT",
83
- };
84
- if (decl.value !== undefined) {
85
- const converted = wireRefToTf(decl.value, refCtx);
86
- if ("unsupported" in converted) {
87
- return { unsupported: `variable "${decl.name}": ${converted.unsupported}` };
232
+ return expr.resourceAttr(subType.resourceType, scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
233
+ }
234
+ default:
235
+ throw new EntityTfError(`catalog ref kind "${value.__kind}" has no automation HCL representation`);
236
+ }
237
+ }
238
+ function templateToTf(value, refs) {
239
+ const template = value.template;
240
+ const parameters = value.parameters;
241
+ if (typeof template !== "string" || !Array.isArray(parameters)) {
242
+ throw new EntityTfError("invalid templateReference");
243
+ }
244
+ const byName = new Map();
245
+ for (const parameter of parameters) {
246
+ if (!isObject(parameter) || !isObject(parameter.value) || typeof parameter.value.name !== "string") {
247
+ throw new EntityTfError("nested/list template parameters are not supported by the Terraform contract");
248
+ }
249
+ byName.set(parameter.value.name, valueToTf(parameter.value.value, refs));
250
+ }
251
+ const parts = [];
252
+ let cursor = 0;
253
+ const pattern = /\{\{\{([^}]+)\}\}\}/g;
254
+ for (let match = pattern.exec(template); match !== null; match = pattern.exec(template)) {
255
+ if (match.index > cursor)
256
+ parts.push(template.slice(cursor, match.index));
257
+ const part = byName.get(match[1]);
258
+ if (part === undefined || !isTfExpr(part)) {
259
+ throw new EntityTfError(`template parameter "${match[1]}" is missing or is not a reference`);
260
+ }
261
+ parts.push(part);
262
+ cursor = match.index + match[0].length;
263
+ }
264
+ if (cursor < template.length)
265
+ parts.push(template.slice(cursor));
266
+ return expr.template(parts);
267
+ }
268
+ const TS_REF_SEGMENT_TO_WIRE = {
269
+ record: "Record",
270
+ changedFieldIds: "Changed Fields",
271
+ records: "All found records",
272
+ iteration: "Iteration",
273
+ id: "ID",
274
+ title: "Title",
275
+ };
276
+ const TS_TRIGGER_REF_TO_WIRE = {
277
+ createdByEmail: "Created by Email",
278
+ updatedByManagerEmail: "Updated by Manager Email",
279
+ slackThreadId: "Slack Thread ID",
280
+ slackChannelId: "Slack Channel ID",
281
+ messageAuthorEmail: "Message Author Email",
282
+ messageAuthorId: "Message Author ID",
283
+ messageAuthorName: "Message Author Name",
284
+ messageContent: "Message Content",
285
+ messageId: "Message ID",
286
+ messageMetadata: "Message Metadata",
287
+ };
288
+ const DISPLAY_REF_CANONICAL_CASE = Object.fromEntries(Object.values(TS_TRIGGER_REF_TO_WIRE).map((value) => [value.toLowerCase(), value]));
289
+ const FIELD_REF_SUFFIX_TO_WIRE = {
290
+ "": "",
291
+ id: " ID",
292
+ label: " Label",
293
+ email: " Email",
294
+ name: " Name",
295
+ fieldId: " Field ID",
296
+ // Matches the literal path segment from-tf.ts now produces for this suffix
297
+ // ("as text", not camelCase "asText") - Ref<T> has no ".asText" property
298
+ // anywhere in the type system, so authored code can only reach this suffix
299
+ // through the unresolved-segment bracket-access escape
300
+ // (`(ctx.trigger.record.x as any)["as text"]`), which accumulates the
301
+ // literal string "as text" as the RefData path segment at runtime.
302
+ "as text": " as text",
303
+ "employee.manager": " Manager",
304
+ "employee.manager.email": " Manager Email",
305
+ "employee.manager.name": " Manager Name",
306
+ };
307
+ function wireRefName(name, ctx) {
308
+ const known = TS_TRIGGER_REF_TO_WIRE[name];
309
+ if (known !== undefined)
310
+ return known;
311
+ const canonicalDisplay = DISPLAY_REF_CANONICAL_CASE[name.toLowerCase()];
312
+ if (canonicalDisplay !== undefined)
313
+ return canonicalDisplay;
314
+ const parts = name.split(".");
315
+ if (parts[0] === "record" && parts.length >= 2) {
316
+ const fieldKey = parts[1];
317
+ // System fields (title/status/stage/createdBy/...) have no entry in
318
+ // ctx.fieldNames - that map only carries the app's custom fields bag.
319
+ // Fall back to the provider's default display name for them; a renamed
320
+ // system field won't match and still throws below, same as an unknown
321
+ // custom field key would.
322
+ const fieldName = ctx.fieldNames.get(fieldKey) ??
323
+ (SYSTEM_FIELD_KEY_SET.has(fieldKey) ? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[fieldKey] : undefined);
324
+ if (fieldName === undefined) {
325
+ throw new EntityTfError(`automation reference "${name}" targets field "${parts[1]}" which does not exist in app "${ctx.appRefName}"`);
326
+ }
327
+ const suffix = parts.slice(2).join(".");
328
+ const wireSuffix = FIELD_REF_SUFFIX_TO_WIRE[suffix];
329
+ if (wireSuffix === undefined) {
330
+ throw new EntityTfError(`automation reference "${name}" has unsupported record-field path "${suffix}"`);
331
+ }
332
+ // The platform lowercases a system field's trailing " By" when it's the
333
+ // PREFIX of a compound ref phrase (e.g. "Created By" + " Email" -> wire
334
+ // ref key "Created by Email") but keeps it capitalized standalone -
335
+ // confirmed live: plan failed with "Invalid index" against the real
336
+ // refs map until this matched. from-tf.ts already reads refs
337
+ // case-insensitively; build must reproduce the platform's exact casing
338
+ // since terraform's refs[] map lookup is case-sensitive.
339
+ const prefix = wireSuffix.length > 0 && fieldName.endsWith(" By") ? `${fieldName.slice(0, -3)} by` : fieldName;
340
+ return `${prefix}${wireSuffix}`;
341
+ }
342
+ // A webhook trigger's body/headers refs (ctx.trigger.body["X"]) can only
343
+ // type-check against DeepRefs<WebhookTriggerOutput>, so parts[0] being
344
+ // "body"/"headers" here already guarantees a genuine webhook reference -
345
+ // no trigger-type gate needed (unlike from-tf.ts's read-side regex, which
346
+ // has to guess at an arbitrary platform string). Reverses the "Body
347
+ // (Plain Text)" -> ["body", "Plain Text"] split from-tf.ts performs.
348
+ if ((parts[0] === "body" || parts[0] === "headers") && parts.length === 2) {
349
+ const label = parts[0] === "body" ? "Body" : "Headers";
350
+ return `${label} (${parts[1]})`;
351
+ }
352
+ parts[0] = TS_REF_SEGMENT_TO_WIRE[parts[0]] ?? parts[0];
353
+ return parts.join(".");
354
+ }
355
+ function valueToTf(value, refs) {
356
+ const catalog = token(value);
357
+ if (catalog !== undefined)
358
+ return tokenToTf(catalog, refs.owner, refs.dataBlocks);
359
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean")
360
+ return value;
361
+ if (Array.isArray(value))
362
+ return value.map((item) => valueToTf(item, refs));
363
+ if (!isObject(value))
364
+ throw new EntityTfError(`unsupported automation value ${String(value)}`);
365
+ if ("value" in value && Object.keys(value).length === 1)
366
+ return valueToTf(value.value, refs);
367
+ if (isObject(value.variableReference) && typeof value.variableReference.id === "string") {
368
+ const target = refs.variableById.get(value.variableReference.id);
369
+ if (target === undefined)
370
+ throw new EntityTfError("unresolved variable ref " + value.variableReference.id);
371
+ return expr.resourceAttr(target.type, target.label, ["refs", { index: target.name }]);
372
+ }
373
+ if (isObject(value.triggerReference) && typeof value.triggerReference.name === "string") {
374
+ return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: wireRefName(value.triggerReference.name, refs.owner) }]);
375
+ }
376
+ if (isObject(value.taskReference) && typeof value.taskReference.taskRefKey === "string" && typeof value.taskReference.name === "string") {
377
+ const target = refs.tasks.get(value.taskReference.taskRefKey);
378
+ if (target === undefined)
379
+ throw new EntityTfError(`unresolved task ref "${value.taskReference.taskRefKey}"`);
380
+ // aiFileAnalysis/readFile's refs are keyed by whatever arbitrary field
381
+ // names the file reader schema itself defines (e.g. "title",
382
+ // "document_type") - wireRefName's generic segment table
383
+ // (TS_REF_SEGMENT_TO_WIRE) is for a DIFFERENT thing (a task's own
384
+ // canonical record-identity fields, e.g. createRecord's generic "id"/
385
+ // "title"), and wrongly rewrites a reader field literally named "title"
386
+ // into the wire key "Title", which doesn't exist in these two
387
+ // resources' actual refs map - confirmed live via a real apply's
388
+ // "Invalid index" error. Their field names pass through verbatim.
389
+ const isFileReaderTask = target.type === "elementum_ai_file_read_task" || target.type === "elementum_file_reader_task";
390
+ const refKey = isFileReaderTask ? value.taskReference.name : wireRefName(value.taskReference.name, refs.owner);
391
+ return expr.resourceAttr(target.type, target.label, ["refs", { index: refKey }]);
392
+ }
393
+ if (isObject(value.forEachReference) && typeof value.forEachReference.forEachTaskRefKey === "string" && typeof value.forEachReference.name === "string") {
394
+ const target = refs.tasks.get(value.forEachReference.forEachTaskRefKey);
395
+ if (target === undefined)
396
+ throw new EntityTfError(`unresolved forEach ref "${value.forEachReference.forEachTaskRefKey}"`);
397
+ return expr.resourceAttr(target.type, target.label, ["refs", { index: wireRefName(value.forEachReference.name, refs.owner) }]);
398
+ }
399
+ if (isObject(value.templateReference))
400
+ return templateToTf(value.templateReference, refs);
401
+ if (isObject(value.secretReference) && typeof value.secretReference.secretId === "string") {
402
+ throw new EntityTfError("secret references have no provider HCL representation");
403
+ }
404
+ if (typeof value.kind === "string") {
405
+ if (value.kind === "localRef" && typeof value.localName === "string" && Array.isArray(value.path)) {
406
+ return expr.local(scopedOptionLocalName(value.localName, refs.owner), value.path);
407
+ }
408
+ if (value.kind === "unresolved" && typeof value.uuid === "string")
409
+ return value.uuid;
410
+ if (value.kind === "literal" && "value" in value)
411
+ return valueToTf(value.value, refs);
412
+ }
413
+ if (isTfExpr(value))
414
+ return value;
415
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, valueToTf(child, refs)]));
416
+ }
417
+ function snake(name) {
418
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/-/g, "_").toLowerCase();
419
+ }
420
+ function unwrapDefault(value) {
421
+ if (!isObject(value))
422
+ return value;
423
+ const values = Object.values(value);
424
+ return values.length === 1 ? values[0] : value;
425
+ }
426
+ function filterReferenceToTf(value, refs) {
427
+ if (!isObject(value) || typeof value.type !== "string") {
428
+ throw new EntityTfError("invalid automation filter reference");
429
+ }
430
+ switch (value.type.toUpperCase()) {
431
+ case "TRIGGER": {
432
+ if (typeof value.name !== "string")
433
+ throw new EntityTfError("trigger filter reference has no name");
434
+ // ei's dialect encodes a FILTER's reference to a trigger-record field as
435
+ // a plain "trigger.record.<fieldId>[.<suffix>]" string — a different
436
+ // convention from the `.refs[...]` map lookup used for task inputs.
437
+ // Reproduce it via a template so the field id stays a real reference
438
+ // (never hardcoded), matching the actual export byte-for-byte.
439
+ const parts = value.name.split(".");
440
+ if (parts[0] === "record" && parts.length >= 2) {
441
+ const fieldKey = parts[1];
442
+ const address = refs.owner.fieldAddresses.get(fieldKey);
443
+ const suffix = parts.slice(2).join(".");
444
+ if (address !== undefined) {
445
+ return expr.template([
446
+ "trigger.record.",
447
+ addressExpr(address, ["id"]),
448
+ ...(suffix.length > 0 ? [`.${suffix}`] : []),
449
+ ]);
450
+ }
451
+ // System fields (id/title/status/createdBy/updatedBy/...) have no
452
+ // resource block of their own - ei's export addresses their id via a
453
+ // `<appTfLabel>_<field>_field_id` local instead, mirroring
454
+ // tokenToTf's plain-field-ref fallback above. Reproduce that exact
455
+ // shape rather than falling through to the generic `.refs[...]`
456
+ // lookup below - confirmed live: that resourceAttr form evaluates to
457
+ // a DIFFERENT computed JSON envelope than the plain string ei
458
+ // exports/binds in state, so every apply after a pull replanned this
459
+ // filter as a spurious in-place update.
460
+ if (SYSTEM_FIELD_KEY_SET.has(fieldKey)) {
461
+ return expr.template([
462
+ "trigger.record.",
463
+ expr.local(`${refs.owner.appTfLabel}_${tsLabelToTfLabel(fieldKey)}_field_id`),
464
+ ...(suffix.length > 0 ? [`.${suffix}`] : []),
465
+ ]);
466
+ }
467
+ // Orphaned field reference: from-tf.ts round-trips a filter
468
+ // value_reference whose field id resolves to nothing in the app
469
+ // export (deleted/recreated field - same drift class as orphaned
470
+ // picklist option ids) as the raw id verbatim, via the generic
471
+ // unresolved-path escape. There's no field to look up here either -
472
+ // pass the original wire string straight through unchanged rather
473
+ // than routing it through wireRefName, which assumes a real field key.
474
+ if (isUuid(fieldKey)) {
475
+ return `trigger.${value.name}`;
88
476
  }
89
- attrs["value"] = converted.value;
90
477
  }
91
- return { attrs };
478
+ return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: wireRefName(value.name, refs.owner) }]);
479
+ }
480
+ case "TASK": {
481
+ if (typeof value.taskRefKey !== "string" || typeof value.name !== "string")
482
+ throw new EntityTfError("task filter reference is incomplete");
483
+ const task = refs.tasks.get(value.taskRefKey);
484
+ if (task === undefined)
485
+ throw new EntityTfError(`unresolved task filter ref "${value.taskRefKey}"`);
486
+ return expr.resourceAttr(task.type, task.label, ["refs", { index: value.name }]);
487
+ }
488
+ case "FOR_EACH": {
489
+ if (typeof value.forEachTaskRefKey !== "string" || typeof value.name !== "string")
490
+ throw new EntityTfError("forEach filter reference is incomplete");
491
+ const task = refs.tasks.get(value.forEachTaskRefKey);
492
+ if (task === undefined)
493
+ throw new EntityTfError(`unresolved forEach filter ref "${value.forEachTaskRefKey}"`);
494
+ return expr.resourceAttr(task.type, task.label, ["refs", { index: value.name }]);
92
495
  }
496
+ case "VALUE":
497
+ return valueToTf(value.value, refs);
93
498
  default:
94
- return { unsupported: `no terraform body mapping for task kind "${typeKey}"` };
499
+ throw new EntityTfError(`unsupported filter reference type "${value.type}"`);
95
500
  }
96
501
  }
97
- /** The composite ei dialect for one automation. */
98
- export function automationToTf(entity, ctx) {
99
- if (entity.kind !== "automation") {
100
- throw new EntityTfError(`automationToTf expects kind "automation"; got "${entity.kind}" (refName "${entity.refName}")`);
502
+ function picklistFilterValueToTf(value, field, refs) {
503
+ if (typeof value !== "string" ||
504
+ field?.__kind !== "field" ||
505
+ field.fieldType !== "PICKLIST" ||
506
+ field.options === undefined)
507
+ return undefined;
508
+ if (!field.options.includes(value)) {
509
+ // Status/dropdown options can be deleted and recreated (new ids)
510
+ // without the platform updating automations that already filtered on
511
+ // the old ones - confirmed live: a filter can reference an option id
512
+ // that matches none of the field's current live options. from-tf.ts
513
+ // already round-trips a value it can't resolve to a label as the raw
514
+ // literal string; passing a UUID-shaped one through unresolved (instead
515
+ // of throwing) lets build reproduce that exact orphaned reference
516
+ // rather than blocking on platform data it can't fix.
517
+ if (isUuid(value))
518
+ return undefined;
519
+ throw new EntityTfError(`automation filter for picklist field "${field.name ?? field.refName}" uses unknown option ${JSON.stringify(value)}; expected one of: ${field.options.map((option) => JSON.stringify(option)).join(", ")}`);
101
520
  }
102
- const payload = entity.payload;
103
- if (payload === null || typeof payload !== "object" || typeof payload.name !== "string") {
104
- throw new EntityTfError(`automation "${entity.refName}" has no payload.name — was it built with defineAutomation?`);
521
+ const localName = field.tags?.includes("STATUS")
522
+ ? `${refs.owner.appTfLabel}_status_options_by_label`
523
+ : field.tags?.includes("STAGE")
524
+ ? `${refs.owner.appTfLabel}_stage_options_by_label`
525
+ : `${scopedLabel(refs.owner.appTfLabel, tsLabelToTfLabel(field.refName))}_options_by_label`;
526
+ return expr.local(localName, [{ index: value }]);
527
+ }
528
+ function filterValueToTf(value, refs, field) {
529
+ if (!isObject(value) || typeof value.type !== "string")
530
+ return valueToTf(value, refs);
531
+ const type = value.type.toLowerCase();
532
+ const result = { type };
533
+ if (value.realType !== undefined)
534
+ result.real_type = String(value.realType).toLowerCase();
535
+ if (type === "current_user" && typeof value.currentUserType === "string") {
536
+ result.current_user_type = value.currentUserType;
105
537
  }
106
- const name = payload.name;
107
- const autoLabel = sanitizeName(name);
108
- const where = `automation "${name}"`;
109
- const blocks = [];
110
- // 1. elementum_automation — identity. `triggers_other_automations` is a
111
- // platform-derived flag (true iff another automation calls this one);
112
- // Phase 1 authors a single, uncalled automation, so it is false.
113
- blocks.push({
114
- kind: "resource",
115
- type: AUTOMATION_RESOURCE_TYPE,
116
- label: autoLabel,
117
- attrs: {
118
- app_id: expr.resourceAttr(APP_RESOURCE_TYPE, ctx.appTfLabel, ["id"]),
119
- name,
120
- triggers_other_automations: false,
121
- },
122
- });
123
- // 2. the trigger — one per automation, references the automation.
124
- const trig = oneOf(payload.trigger);
125
- if (trig === undefined)
126
- throw new EntityTfError(`${where} has no trigger`);
127
- const trigRow = AUTOMATION_SUB_TYPE_BY_TYPE_KEY.get(trig.key);
128
- if (trigRow?.implemented !== true) {
129
- throw new EntityTfError(`${where}: trigger "${trig.key}" is not carried by the terraform path yet (Phase 1 supports onDemand)`);
538
+ if (value.value !== undefined) {
539
+ result.value = type === "reference"
540
+ ? filterReferenceToTf(value.value, refs)
541
+ : picklistFilterValueToTf(value.value, field, refs) ?? valueToTf(value.value, refs);
130
542
  }
131
- const triggerType = trigRow.resourceType;
132
- const triggerAttrs = { automation: bareRef(AUTOMATION_RESOURCE_TYPE, autoLabel) };
133
- // onDemand parameter declarations live ON the trigger resource
134
- // (parameters = [{name, type, required, multiple, default_value}]).
135
- const wireInputs = trig.body["inputs"] ?? [];
136
- if (wireInputs.length > 0) {
137
- triggerAttrs["parameters"] = wireInputs.map((i) => {
138
- // The tf schema takes the lowercase authoring alias ("text"), not the
139
- // wire form ("TEXT"); wire "BOOL" is the alias "boolean".
140
- const wireType = String(i["type"] ?? "TEXT").toLowerCase();
141
- const param = {
142
- name: String(i["name"] ?? ""),
143
- type: wireType === "bool" ? "boolean" : wireType,
144
- required: i["required"] === true,
145
- multiple: i["multiple"] === true,
543
+ return result;
544
+ }
545
+ function fieldFromFilterLeftValue(value, refs) {
546
+ if (!isObject(value) || !isObject(value.value) || value.value.type?.toString().toUpperCase() !== "TRIGGER") {
547
+ return undefined;
548
+ }
549
+ const name = value.value.name;
550
+ if (typeof name !== "string")
551
+ return undefined;
552
+ const path = name.split(".");
553
+ if (path[0] !== "record" || path.length < 2)
554
+ return undefined;
555
+ const refName = path[1];
556
+ const metadata = refs.owner.fieldMetadata.get(refName);
557
+ if (metadata === undefined)
558
+ return undefined;
559
+ return { __kind: "field", refName, ...metadata };
560
+ }
561
+ function filterToTf(value, refs) {
562
+ if (!isObject(value) || typeof value.type !== "string")
563
+ throw new EntityTfError("invalid automation filter");
564
+ const result = { type: value.type.toLowerCase() };
565
+ const field = token(value.field) ?? fieldFromFilterLeftValue(value.leftValue, refs);
566
+ for (const [key, child] of Object.entries(value)) {
567
+ if (key === "type")
568
+ continue;
569
+ if (key === "field") {
570
+ result.field_id = valueToTf(child, refs);
571
+ continue;
572
+ }
573
+ if (key === "leftValue") {
574
+ if (!isObject(child))
575
+ throw new EntityTfError("invalid filter leftValue");
576
+ result.left_value = {
577
+ value_reference: filterReferenceToTf(child.value, refs),
578
+ ...(child.realType !== undefined ? { real_type: String(child.realType).toLowerCase() } : {}),
146
579
  };
147
- // Wire default is a typed envelope ({text: "..."} etc.) — the tf attr is
148
- // the bare string.
149
- const dv = i["defaultValue"];
150
- if (dv !== null && typeof dv === "object") {
151
- const inner = Object.values(dv)[0];
152
- if (inner !== undefined)
153
- param["default_value"] = String(inner);
154
- }
155
- return param;
156
- });
580
+ continue;
581
+ }
582
+ if (key === "children") {
583
+ if (!Array.isArray(child))
584
+ throw new EntityTfError("filter children must be an array");
585
+ result.children = child.map((item) => filterToTf(item, refs));
586
+ continue;
587
+ }
588
+ if (key === "value") {
589
+ result.value = filterValueToTf(child, refs, field);
590
+ continue;
591
+ }
592
+ if (key === "values") {
593
+ if (!Array.isArray(child))
594
+ throw new EntityTfError("filter values must be an array");
595
+ result.values = child.map((item) => filterValueToTf(item, refs, field));
596
+ continue;
597
+ }
598
+ if (key === "mode") {
599
+ if (typeof child !== "string")
600
+ throw new EntityTfError("filter mode must be a string");
601
+ result.mode = child.toLowerCase();
602
+ continue;
603
+ }
604
+ result[snake(key)] = valueToTf(child, refs);
157
605
  }
158
- if (trig.body["showTriggeredBy"] === true)
159
- triggerAttrs["show_triggered_by"] = true;
160
- blocks.push({ kind: "resource", type: triggerType, label: autoLabel, attrs: triggerAttrs });
161
- // Value-reference conversion context, shared by task bodies + outputs.
162
- const refCtx = {
163
- autoLabel,
164
- triggerType,
165
- paramNames: wireInputs.map((i) => String(i["name"] ?? "")).filter((n) => n !== ""),
166
- taskType: (refKey) => {
167
- const entry = (payload.tasks ?? []).find((t) => t.refKey === refKey);
168
- const kind = entry !== undefined ? oneOf(entry.task)?.key : undefined;
169
- const row = kind !== undefined ? AUTOMATION_SUB_TYPE_BY_TYPE_KEY.get(kind) : undefined;
170
- return row?.implemented === true ? row.resourceType : undefined;
171
- },
172
- taskResultProps: (refKey) => {
173
- const entry = (payload.tasks ?? []).find((t) => t.refKey === refKey);
174
- const schema = entry !== undefined ? oneOf(entry.task)?.body["outputSchema"] : undefined;
175
- return (schema?.object?.properties ?? [])
176
- .map((prop) => Object.values(prop)[0]?.name)
177
- .filter((n) => typeof n === "string");
178
- },
179
- variableById: indexVariableIds(payload.tasks ?? []),
180
- };
181
- // 3. tasks — parent-chained. First task's parent is the trigger; each
182
- // subsequent task's parent is its predecessor. Ordering IS the payload's
183
- // task array order.
184
- let parentType = triggerType;
185
- let parentLabel = autoLabel;
186
- const taskRefs = [];
187
- const usedTaskLabels = new Map();
188
- for (const t of payload.tasks ?? []) {
189
- const one = oneOf(t.task);
190
- const refKey = typeof t.refKey === "string" ? t.refKey : one !== undefined ? String(one.body.name ?? "") : "";
191
- if (one === undefined || refKey === "") {
192
- ctx.diagnostics.push(`${where}: a task has no recognizable body/refKey; dropped`);
606
+ // The platform silently defaults an unset LIKE mode to "legacy" and always
607
+ // echoes it back on export — emit it explicitly so build and export stay
608
+ // byte-fidelity equal instead of one omitting an attribute the other sets.
609
+ if (result.type === "like" && result.mode === undefined)
610
+ result.mode = "legacy";
611
+ return result;
612
+ }
613
+ function configAttrs(kind, config, refs) {
614
+ const attrs = {};
615
+ for (const [key, raw] of Object.entries(config)) {
616
+ if (key === "name" || key === "type" || key === "aspectId" && kind.endsWith("_trigger"))
193
617
  continue;
618
+ // A config value of exactly `undefined` almost always means the
619
+ // authoring builder was called with a required option omitted (e.g. a
620
+ // TS-only-enforced field that jiti/bun never actually type-checks at
621
+ // build time) - name the wire key here, since the generic valueToTf
622
+ // fallback below has no attribute name to report by the time it gets to
623
+ // its own "unsupported value" throw.
624
+ if (raw === undefined) {
625
+ throw new EntityTfError(`${kind}: config value for "${key}" is undefined — likely a missing required option on the authoring builder call that built this task/trigger`);
194
626
  }
195
- if (t.children !== undefined) {
196
- ctx.diagnostics.push(`${where}: task "${refKey}" has operator children (forEach/forkJoin/switch), not carried yet; dropped`);
627
+ // elementum_create_record_task has no "relate to record" boolean
628
+ // attribute - relate_to_record_reference's presence alone conveys the
629
+ // intent (see from-tf.ts's matching comment), so the flag itself is
630
+ // never emitted.
631
+ if (key === "relateToRecord")
632
+ continue;
633
+ if (key === "recordReference" && kind === "elementum_create_record_task") {
634
+ attrs.relate_to_record_reference = valueToTf(raw, refs);
197
635
  continue;
198
636
  }
199
- const row = AUTOMATION_SUB_TYPE_BY_TYPE_KEY.get(one.key);
200
- if (row?.implemented !== true) {
201
- ctx.diagnostics.push(`${where}: task "${refKey}" of kind "${one.key}" is not carried by the terraform path yet; dropped`);
637
+ if (key === "filter") {
638
+ attrs.filter = filterToTf(raw, refs);
202
639
  continue;
203
640
  }
204
- const body = taskBodyAttrs(one.key, one.body, refCtx);
205
- if ("unsupported" in body) {
206
- ctx.diagnostics.push(`${where}: task "${refKey}": ${body.unsupported}; dropped`);
641
+ if (key === "categorySource" && kind === "elementum_ai_classify_task") {
642
+ if (!isObject(raw))
643
+ throw new EntityTfError("invalid classification category source");
644
+ if (isObject(raw.static)) {
645
+ const categories = raw.static.categories;
646
+ if (!Array.isArray(categories))
647
+ throw new EntityTfError("static classification categories must be an array");
648
+ attrs.categories = categories.map((item) => {
649
+ if (!isObject(item) || item.name === undefined)
650
+ throw new EntityTfError("invalid static classification category");
651
+ return {
652
+ label: valueToTf(item.name, refs),
653
+ ...(item.description !== undefined ? { description: valueToTf(item.description, refs) } : {}),
654
+ };
655
+ });
656
+ }
657
+ else {
658
+ attrs.category_source = valueToTf(raw, refs);
659
+ }
207
660
  continue;
208
661
  }
209
- const taskType = row.resourceType;
210
- const taskLabel = `${autoLabel}_${sanitizeName(refKey)}`;
211
- if (usedTaskLabels.has(taskLabel)) {
212
- // Task names are open text, but their labels are sanitizeName(name) —
213
- // two names that sanitize identically ("My Task" / "my_task") would
214
- // collide on the tf address. Report loudly; skip the duplicate.
215
- ctx.diagnostics.push(`${where}: task "${refKey}" sanitizes to the same tf label as task "${usedTaskLabels.get(taskLabel)}" (${taskLabel}); dropped — rename one of them`);
662
+ if (key === "fileInput" && kind === "elementum_save_attachment_task") {
663
+ if (!isObject(raw) || raw.file === undefined)
664
+ throw new EntityTfError("saveAttachment file input is invalid");
665
+ attrs.file = valueToTf(raw.file, refs);
216
666
  continue;
217
667
  }
218
- usedTaskLabels.set(taskLabel, refKey);
219
- const displayName = typeof one.body.name === "string" ? (one.body.name) : refKey;
220
- blocks.push({
221
- kind: "resource",
222
- type: taskType,
223
- label: taskLabel,
224
- attrs: {
225
- parent: bareRef(parentType, parentLabel),
226
- name: displayName,
227
- ...body.attrs,
228
- },
229
- });
230
- taskRefs.push(bareRef(taskType, taskLabel));
231
- parentType = taskType;
232
- parentLabel = taskLabel;
668
+ if (key === "documentModelId") {
669
+ attrs.file_reader_id = valueToTf(raw, refs);
670
+ continue;
671
+ }
672
+ // aiFileAnalysis's `attachmentId` config key means the task's single
673
+ // generic `file_id` value reference (confirmed against
674
+ // ai_file_read_task_resource.go's buildAiFileReadInput/schema) - distinct
675
+ // from readFile's mutually-exclusive attachment/attachment_id/file/
676
+ // raw_text data-source union (handled separately via
677
+ // documentModelDataSource, below), which shares the wire key name.
678
+ if (key === "attachmentId" && kind === "elementum_ai_file_read_task") {
679
+ attrs.file_id = valueToTf(raw, refs);
680
+ continue;
681
+ }
682
+ if (key === "documentModelDataSource") {
683
+ if (!isObject(raw))
684
+ throw new EntityTfError("documentModel dataSource must be an object");
685
+ const entries = Object.entries(raw);
686
+ if (entries.length !== 1)
687
+ throw new EntityTfError("documentModel dataSource must have exactly one entry");
688
+ const [dsType, dsValue] = entries[0];
689
+ const attrName = dsType === "rawText" ? "raw_text" : dsType === "attachmentId" ? "attachment_id" : dsType;
690
+ attrs[attrName] = valueToTf(dsValue, refs);
691
+ continue;
692
+ }
693
+ // readFile's optional `record` has no elementum_file_reader_task
694
+ // attribute to carry it - the terraform resource's schema has no
695
+ // record-reference input at all (only the four data-source attrs) -
696
+ // dropped like other authoring knobs the terraform path doesn't model.
697
+ if (key === "recordId" && kind === "elementum_file_reader_task")
698
+ continue;
699
+ if (key === "recordId" && kind === "elementum_save_attachment_task") {
700
+ attrs.record_id = valueToTf(raw, refs);
701
+ continue;
702
+ }
703
+ if (key === "calculations" && kind === "elementum_calculation_task") {
704
+ if (!Array.isArray(raw))
705
+ throw new EntityTfError("calculations must be an array");
706
+ attrs.calculations = raw.map((item) => {
707
+ if (!isObject(item) || typeof item.name !== "string" || !isObject(item.calculationReference)) {
708
+ throw new EntityTfError("invalid calculation entry");
709
+ }
710
+ const reference = item.calculationReference;
711
+ if (!isObject(reference.templateReference))
712
+ throw new EntityTfError("calculation expression is not a template reference");
713
+ const template = reference.templateReference;
714
+ const parameters = template.parameters;
715
+ let formula;
716
+ if (template.template === "{{{p1}}}" && Array.isArray(parameters) && parameters.length === 1) {
717
+ const parameter = parameters[0];
718
+ if (!isObject(parameter) || !isObject(parameter.value) || parameter.value.name !== "p1") {
719
+ throw new EntityTfError("invalid calculation expression parameter");
720
+ }
721
+ formula = valueToTf(parameter.value.value, refs);
722
+ }
723
+ else {
724
+ formula = templateToTf(template, refs);
725
+ }
726
+ return { variable_name: item.name, formula };
727
+ });
728
+ continue;
729
+ }
730
+ if (key === "inputs" && kind === "elementum_on_demand_trigger") {
731
+ if (!Array.isArray(raw))
732
+ throw new EntityTfError("onDemand inputs must be an array");
733
+ const parameters = raw.map((input) => {
734
+ if (!isObject(input))
735
+ throw new EntityTfError("onDemand input must be an object");
736
+ return Object.fromEntries(Object.entries(input).map(([k, v]) => [
737
+ CONFIG_ATTRS[k] ?? snake(k),
738
+ valueToTf(k === "defaultValue" ? unwrapDefault(v) :
739
+ // elementum_on_demand_trigger.parameters[].type's real validator
740
+ // (on_demand_trigger_resource.go) only accepts a bare "attachment"
741
+ // - there is no "attachment_id" variant at this layer, unlike the
742
+ // WorkflowFieldType enum name (ATTACHMENT_ID) the "attachmentId"
743
+ // authoring alias otherwise maps to. A generic lowercase would
744
+ // wrongly emit "attachment_id" and fail plan/apply.
745
+ k === "type" && v === "ATTACHMENT_ID" ? "attachment" :
746
+ k === "type" && typeof v === "string" ? v.toLowerCase() : v, refs),
747
+ ]));
748
+ });
749
+ // The provider normalizes an absent parameter collection to null. An
750
+ // explicit [] therefore creates perpetual [] vs null drift after pull.
751
+ if (parameters.length > 0)
752
+ attrs.parameters = parameters;
753
+ continue;
754
+ }
755
+ if (key === "workflowFields") {
756
+ if (!Array.isArray(raw))
757
+ throw new EntityTfError("workflowFields must be an array");
758
+ attrs.fields = raw.map((field) => {
759
+ if (!isObject(field))
760
+ throw new EntityTfError("workflow field must be an object");
761
+ return {
762
+ field_id: valueToTf(field.aspectFieldId, refs),
763
+ value: valueToTf(field.valueReference, refs),
764
+ };
765
+ });
766
+ continue;
767
+ }
768
+ if (key === "outputSchema") {
769
+ attrs.output_schema = expr.jsonencode(valueToTf(raw, refs));
770
+ continue;
771
+ }
772
+ if (key === "forEach") {
773
+ attrs.list = valueToTf(raw, refs);
774
+ continue;
775
+ }
776
+ if (key === "customResponse") {
777
+ if (!isObject(raw))
778
+ throw new EntityTfError("invalid customResponse");
779
+ const encodeSection = (section) => {
780
+ if (!isObject(section))
781
+ return undefined;
782
+ const encoded = {
783
+ enabled: section.enabled === true,
784
+ format: typeof section.format === "string" ? section.format : "JSON",
785
+ body: valueToTf(section.body, refs),
786
+ };
787
+ if (typeof section.statusCode === "number")
788
+ encoded.status_code = section.statusCode;
789
+ return encoded;
790
+ };
791
+ const success = encodeSection(raw.success);
792
+ const failure = encodeSection(raw.failure);
793
+ if (success !== undefined || failure !== undefined) {
794
+ attrs.custom_response = {
795
+ ...(success !== undefined ? { success } : {}),
796
+ ...(failure !== undefined ? { failure } : {}),
797
+ };
798
+ }
799
+ continue;
800
+ }
801
+ if (key === "outputType") {
802
+ attrs.output_type = typeof raw === "string" ? raw.toUpperCase() : valueToTf(raw, refs);
803
+ continue;
804
+ }
805
+ if (key === "sourceRecordIds") {
806
+ if (Array.isArray(raw)) {
807
+ // ei exports a scalar when there is exactly one source record.
808
+ attrs.source_record_ids = raw.length === 1
809
+ ? valueToTf(raw[0], refs)
810
+ : raw.map((item) => valueToTf(item, refs));
811
+ }
812
+ else {
813
+ attrs.source_record_ids = valueToTf(raw, refs);
814
+ }
815
+ continue;
816
+ }
817
+ if (key === "create" || key === "update")
818
+ continue;
819
+ // apiRequest's bearerAuth/oauth/customBody/multipartBody (and
820
+ // basicAuth's referencePassword) all carry nested multi-word attribute
821
+ // names the provider expects snake_case (reference_token, client_id,
822
+ // content_type, attachment_id, ...) - the generic valueToTf object
823
+ // fallback below preserves nested keys verbatim, so these need the same
824
+ // explicit per-key mapping as customResponse above, not the generic path.
825
+ if (key === "basicAuth" && kind === "elementum_api_task") {
826
+ if (!isObject(raw))
827
+ throw new EntityTfError("apiRequest basicAuth must be an object");
828
+ attrs.basic_auth = {
829
+ username: valueToTf(raw.username, refs),
830
+ ...(raw.referencePassword !== undefined ? { reference_password: valueToTf(raw.referencePassword, refs) } : {}),
831
+ };
832
+ continue;
833
+ }
834
+ if (key === "bearerAuth" && kind === "elementum_api_task") {
835
+ if (!isObject(raw))
836
+ throw new EntityTfError("apiRequest bearerAuth must be an object");
837
+ attrs.bearer_auth = {
838
+ ...(raw.token !== undefined ? { token: valueToTf(raw.token, refs) } : {}),
839
+ ...(raw.referenceToken !== undefined ? { reference_token: valueToTf(raw.referenceToken, refs) } : {}),
840
+ };
841
+ continue;
842
+ }
843
+ if (key === "oauth" && kind === "elementum_api_task") {
844
+ if (!isObject(raw))
845
+ throw new EntityTfError("apiRequest oauth must be an object");
846
+ const headers = Array.isArray(raw.headers)
847
+ ? raw.headers.map((h) => {
848
+ if (!isObject(h))
849
+ throw new EntityTfError("invalid apiRequest oauth header");
850
+ return { name: valueToTf(h.name, refs), value: valueToTf(h.value, refs) };
851
+ })
852
+ : undefined;
853
+ attrs.oauth = {
854
+ request_type: valueToTf(raw.requestType, refs),
855
+ ...(raw.url !== undefined ? { url: valueToTf(raw.url, refs) } : {}),
856
+ ...(raw.clientId !== undefined ? { client_id: valueToTf(raw.clientId, refs) } : {}),
857
+ ...(raw.clientSecret !== undefined ? { client_secret: valueToTf(raw.clientSecret, refs) } : {}),
858
+ ...(headers !== undefined ? { headers } : {}),
859
+ };
860
+ continue;
861
+ }
862
+ if (key === "customBody" && kind === "elementum_api_task") {
863
+ if (!isObject(raw))
864
+ throw new EntityTfError("apiRequest customBody must be an object");
865
+ attrs.custom_body = {
866
+ content_type: valueToTf(raw.contentType, refs),
867
+ content: valueToTf(raw.content, refs),
868
+ };
869
+ continue;
870
+ }
871
+ if (key === "multipartBody" && kind === "elementum_api_task") {
872
+ if (!isObject(raw) || !Array.isArray(raw.parts))
873
+ throw new EntityTfError("apiRequest multipartBody.parts must be an array");
874
+ attrs.multipart_body = {
875
+ parts: raw.parts.map((part) => {
876
+ if (!isObject(part))
877
+ throw new EntityTfError("invalid apiRequest multipartBody part");
878
+ return {
879
+ name: valueToTf(part.name, refs),
880
+ ...(part.value !== undefined ? { value: valueToTf(part.value, refs) } : {}),
881
+ ...(part.attachment !== undefined ? { attachment: valueToTf(part.attachment, refs) } : {}),
882
+ ...(part.attachmentId !== undefined ? { attachment_id: valueToTf(part.attachmentId, refs) } : {}),
883
+ ...(part.file !== undefined ? { file: valueToTf(part.file, refs) } : {}),
884
+ };
885
+ }),
886
+ };
887
+ continue;
888
+ }
889
+ const attr = CONFIG_ATTRS[key] ?? snake(key);
890
+ attrs[attr] = valueToTf(raw, refs);
233
891
  }
234
- // 4. elementum_workflow_publish — versions the workflow, depends on every
235
- // task, and carries the workflow's OUTPUTS ([{name, value}], each value a
236
- // refs-syntax expression).
237
- const publishAttrs = {
238
- automation: bareRef(AUTOMATION_RESOURCE_TYPE, autoLabel),
239
- workflow_revision: payload.workflowRevision ?? "1.0.0",
240
- ...(taskRefs.length > 0 ? { depends_on: taskRefs } : {}),
892
+ return attrs;
893
+ }
894
+ function taskLabel(automationLabel, refKey) {
895
+ // ei's task label is `<auto>_<sanitizeName(task name)>` (CLAUDE.md), and
896
+ // from-tf.ts's taskRefKey either preserves the task's raw display name
897
+ // verbatim (when it already round-trips through sanitizeName unchanged,
898
+ // e.g. "Send_field_update") or camelCases it via tfLabelToTsLabel (e.g.
899
+ // "notify_reviewer" -> "notifyReviewer"). sanitizeName reproduces the
900
+ // correct tf label for BOTH forms - splitCamelCase inserts the missing
901
+ // word boundary for the camelCase case, and is a no-op for the
902
+ // already-separated case. snakeSlug lowercases FIRST, so it never finds a
903
+ // boundary to split in pure camelCase input ("notifyReviewer" ->
904
+ // "notifyreviewer", no underscore) - confirmed live: this exact mismatch
905
+ // plans a spurious destroy+create pair on every apply.
906
+ const normalized = sanitizeName(refKey);
907
+ return normalized.startsWith(`${automationLabel}_`) ? normalized : `${automationLabel}_${normalized}`;
908
+ }
909
+ /** App-owned `defineAutomation` entity → provider HCL blocks. */
910
+ export function automationToTf(entity, ctx) {
911
+ const owner = {
912
+ appRefName: ctx.appRefName ?? entity.parent,
913
+ appTfLabel: ctx.appTfLabel,
914
+ fieldAddresses: ctx.fieldAddresses ?? new Map(),
915
+ fieldNames: ctx.fieldNames ?? new Map(),
916
+ fieldMetadata: ctx.fieldMetadata ?? new Map(),
917
+ orgRefs: ctx.orgRefs,
241
918
  };
242
- const outputs = payload.outputProperties
243
- ?.outputs;
244
- if (outputs !== undefined && outputs.length > 0) {
245
- const converted = [];
246
- for (const o of outputs) {
247
- if (typeof o?.name !== "string")
248
- continue;
249
- const value = wireRefToTf(o.value, refCtx);
250
- if ("unsupported" in value) {
251
- ctx.diagnostics.push(`${where}: output "${o.name}": ${value.unsupported}; dropped`);
252
- continue;
919
+ if (entity.kind !== "automation")
920
+ throw new EntityTfError(`automationToTf expects kind "automation"; got "${entity.kind}"`);
921
+ if (entity.parent !== owner.appRefName) {
922
+ throw new EntityTfError("automation " + entity.refName + " is owned by " + entity.parent + ", not app " + owner.appRefName);
923
+ }
924
+ const payload = entity.payload;
925
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload))
926
+ throw new EntityTfError(`automation "${entity.refName}" has a non-object payload`);
927
+ if (typeof payload.workflowRevision !== "string")
928
+ throw new EntityTfError(`automation "${entity.refName}" has no workflowRevision`);
929
+ const label = scopedLabel(owner.appTfLabel, tsLabelToTfLabel(entity.refName));
930
+ const automation = {
931
+ kind: "resource",
932
+ type: AUTOMATION_RESOURCE_TYPE,
933
+ label,
934
+ attrs: {
935
+ app_id: expr.resourceAttr("elementum_app", ctx.appTfLabel, ["id"]),
936
+ name: payload.name ?? "",
937
+ ...(payload.description !== undefined ? { description: payload.description } : {}),
938
+ ...(payload.triggersOtherAutomations !== undefined ? { triggers_other_automations: payload.triggersOtherAutomations } : {}),
939
+ },
940
+ };
941
+ const [triggerKey, triggerConfig] = onlyEntry(payload.trigger, `automation "${entity.refName}" trigger`);
942
+ const triggerType = TRIGGER_RESOURCES[triggerKey];
943
+ if (triggerType === undefined)
944
+ throw new EntityTfError(`trigger type "${triggerKey}" is not supported by the provider HCL contract`);
945
+ const taskRefs = new Map();
946
+ const variableById = new Map();
947
+ const usedLabels = new Map(); // tf label → the refKey that claimed it
948
+ const preRegister = (tasks) => {
949
+ for (const task of tasks) {
950
+ const refKey = task.refKey;
951
+ if (typeof refKey !== "string" || refKey === "")
952
+ throw new EntityTfError("automation task has no refKey");
953
+ if (taskRefs.has(refKey))
954
+ throw new EntityTfError(`duplicate task refKey "${refKey}"`);
955
+ const [wireType, taskBody] = onlyEntry(task.task, "task " + refKey);
956
+ const resourceType = TASK_RESOURCES[wireType];
957
+ if (resourceType === undefined)
958
+ throw new EntityTfError(`task type "${wireType}" is not supported by the provider HCL contract`);
959
+ const registeredLabel = taskLabel(label, refKey);
960
+ const collidingRefKey = usedLabels.get(registeredLabel);
961
+ if (collidingRefKey !== undefined) {
962
+ throw new EntityTfError(`task "${refKey}" sanitizes to the same tf label as task "${collidingRefKey}" (${registeredLabel}) — rename one of them`);
253
963
  }
254
- converted.push({ name: o.name, value: value.value });
964
+ usedLabels.set(registeredLabel, refKey);
965
+ taskRefs.set(refKey, { type: resourceType, label: registeredLabel });
966
+ if (wireType === "variable" && Array.isArray(taskBody.create)) {
967
+ for (const candidate of taskBody.create) {
968
+ if (isObject(candidate) && typeof candidate.id === "string" && typeof candidate.name === "string") {
969
+ variableById.set(candidate.id, { type: "elementum_variable_task", label: registeredLabel, name: candidate.name });
970
+ }
971
+ }
972
+ }
973
+ for (const child of task.children ?? [])
974
+ preRegister(child.tasks ?? []);
255
975
  }
256
- if (converted.length > 0)
257
- publishAttrs["outputs"] = converted;
976
+ };
977
+ preRegister(payload.tasks ?? []);
978
+ const dataBlocks = new Map();
979
+ const refs = { trigger: { type: triggerType, label }, tasks: taskRefs, owner, dataBlocks, variableById };
980
+ let triggerAttrs;
981
+ try {
982
+ triggerAttrs = configAttrs(triggerType, triggerConfig, refs);
258
983
  }
259
- blocks.push({
984
+ catch (err) {
985
+ const message = err instanceof Error ? err.message : String(err);
986
+ throw new EntityTfError(`automation "${entity.refName}"'s ${triggerKey} trigger: ${message}`);
987
+ }
988
+ const trigger = {
260
989
  kind: "resource",
261
- type: WORKFLOW_PUBLISH_RESOURCE_TYPE,
262
- label: autoLabel,
263
- attrs: publishAttrs,
264
- });
265
- return { blocks, address: `${AUTOMATION_RESOURCE_TYPE}.${autoLabel}` };
990
+ type: triggerType,
991
+ label,
992
+ attrs: { automation: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label), ...triggerAttrs },
993
+ };
994
+ const blocks = [automation, trigger];
995
+ const dependencies = [expr.resourceAttr(triggerType, label)];
996
+ const runAutomationPublishes = new Set();
997
+ const emitTasks = (tasks, initialParent) => {
998
+ let parent = initialParent;
999
+ let first;
1000
+ for (const task of tasks) {
1001
+ const refKey = task.refKey;
1002
+ const [wireType, inner] = onlyEntry(task.task, `task "${refKey}"`);
1003
+ const resourceType = TASK_RESOURCES[wireType];
1004
+ const tfLabel = taskRefs.get(refKey).label;
1005
+ const displayName = typeof inner.name === "string" ? inner.name : refKey;
1006
+ let taskParent = parent;
1007
+ if (task.hclParent === "trigger") {
1008
+ taskParent = expr.resourceAttr(triggerType, label);
1009
+ }
1010
+ else if (task.hclParent !== undefined) {
1011
+ const explicitParent = taskRefs.get(task.hclParent);
1012
+ if (explicitParent === undefined) {
1013
+ throw new EntityTfError(`task "${refKey}" has unresolved explicit parent "${task.hclParent}"`);
1014
+ }
1015
+ taskParent = expr.resourceAttr(explicitParent.type, explicitParent.label);
1016
+ }
1017
+ if (wireType === "variable") {
1018
+ const creates = Array.isArray(inner.create) ? inner.create : [];
1019
+ const updates = Array.isArray(inner.update) ? inner.update : [];
1020
+ if (creates.length + updates.length !== 1) {
1021
+ throw new EntityTfError(`setVariable task "${refKey}" must contain exactly one create or update for Terraform`);
1022
+ }
1023
+ const isCreate = creates.length === 1;
1024
+ const item = (isCreate ? creates[0] : updates[0]);
1025
+ if (!isObject(item))
1026
+ throw new EntityTfError(`invalid setVariable item on "${refKey}"`);
1027
+ const variableType = isCreate ? "elementum_variable_task" : "elementum_update_variable_task";
1028
+ const variableAttrs = { parent: taskParent, name: displayName };
1029
+ if (isCreate) {
1030
+ if (typeof item.name !== "string" || typeof item.type !== "string")
1031
+ throw new EntityTfError(`variable task "${refKey}" requires name and type`);
1032
+ variableAttrs.variable_name = item.name;
1033
+ variableAttrs.variable_type = item.type;
1034
+ if (item.value !== undefined)
1035
+ variableAttrs.value = valueToTf(item.value, refs);
1036
+ }
1037
+ else {
1038
+ // elementum_update_variable_task's real attribute is
1039
+ // variable_reference (see from-tf.ts's matching comment).
1040
+ variableAttrs.variable_reference = valueToTf(item.variable, refs);
1041
+ variableAttrs.value = valueToTf(item.value, refs);
1042
+ }
1043
+ blocks.push({ kind: "resource", type: variableType, label: tfLabel, attrs: variableAttrs });
1044
+ const address = expr.resourceAttr(variableType, tfLabel);
1045
+ dependencies.push(address);
1046
+ first ??= address;
1047
+ parent = address;
1048
+ continue;
1049
+ }
1050
+ let taskAttrs;
1051
+ try {
1052
+ taskAttrs = configAttrs(resourceType, inner, refs);
1053
+ }
1054
+ catch (err) {
1055
+ const message = err instanceof Error ? err.message : String(err);
1056
+ throw new EntityTfError(`automation "${entity.refName}"'s task "${refKey}" (${wireType}): ${message}`);
1057
+ }
1058
+ const attrs = { parent: taskParent, name: displayName, ...taskAttrs };
1059
+ const block = { kind: "resource", type: resourceType, label: tfLabel, attrs };
1060
+ if (wireType === "runAutomation") {
1061
+ const target = token(inner.targetAutomationId) ?? (isObject(inner.targetAutomationRef) ? token(inner.targetAutomationRef.value) : undefined);
1062
+ if (target === undefined || target.__kind !== "automation")
1063
+ throw new EntityTfError(`runAutomation task "${refKey}" has an unresolved target`);
1064
+ const targetLabel = scopedLabel(owner.appTfLabel, tsLabelToTfLabel(target.refName));
1065
+ block.attrs.depends_on = [expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, targetLabel)];
1066
+ runAutomationPublishes.add(targetLabel);
1067
+ }
1068
+ blocks.push(block);
1069
+ const address = expr.resourceAttr(resourceType, tfLabel);
1070
+ dependencies.push(address);
1071
+ first ??= address;
1072
+ // Only chain linear siblings; explicit hclParent keeps parallel roots under trigger.
1073
+ if (task.hclParent === undefined)
1074
+ parent = address;
1075
+ if (wireType === "forEach") {
1076
+ const children = task.children ?? [];
1077
+ if (children.length !== 1)
1078
+ throw new EntityTfError(`forEach task "${refKey}" must have exactly one child body`);
1079
+ const childResult = emitTasks(children[0].tasks ?? [], expr.resourceAttr(resourceType, tfLabel, ["inner"]));
1080
+ if (childResult !== undefined)
1081
+ parent = childResult.terminal;
1082
+ }
1083
+ else if (wireType === "switch" || wireType === "forkJoin") {
1084
+ const children = task.children ?? [];
1085
+ if (children.length === 0)
1086
+ throw new EntityTfError(`${wireType} task "${refKey}" must have branches`);
1087
+ let previous;
1088
+ for (const [index, child] of children.entries()) {
1089
+ const branchType = wireType === "switch" ? "elementum_switch_case" : "elementum_fork_join_branch";
1090
+ // ei's own resource label follows the branch's real display text
1091
+ // (a default branch renamed "Default Path" exports as
1092
+ // "..._default_path", not a hardcoded "..._default") - confirmed live.
1093
+ const branchLabel = `${tfLabel}_${snakeSlug(child.label ?? child.defaultLabel ?? "default")}`;
1094
+ const branchAttrs = {
1095
+ [wireType === "switch" ? "switch_task" : "fork_join_task"]: address,
1096
+ label: child.label ?? child.defaultLabel ?? "Default",
1097
+ ...(previous !== undefined ? { [wireType === "switch" ? "previous_case_id" : "previous_branch_id"]: { ...previous, path: ["id"] } } : {}),
1098
+ };
1099
+ if (wireType === "switch") {
1100
+ if (child.label === null) {
1101
+ // The provider schema documents `filter`/`is_default` as
1102
+ // mutually exclusive ways to mark a switch default case, but
1103
+ // the platform doesn't retroactively normalize existing cases
1104
+ // to one shape - both are live-confirmed on real orgs for the
1105
+ // identical case pattern (#157: one org's default case carries
1106
+ // `is_default = true` with no `filter`, another's carries
1107
+ // `filter = {type:"true"}` with no `is_default`). Emitting the
1108
+ // "wrong" one for an already-adopted case proposes a spurious
1109
+ // update that provider bug #157 can't actually apply, so
1110
+ // from-tf.ts's defaultSwitchShape records which shape a pulled
1111
+ // case actually has and we reproduce it here; a
1112
+ // freshly-authored default branch (no defaultFilterMode) still
1113
+ // gets the newer is_default form.
1114
+ if (child.defaultFilterMode === "explicitTrueFilter") {
1115
+ branchAttrs.filter = { type: "true" };
1116
+ }
1117
+ else {
1118
+ branchAttrs.is_default = true;
1119
+ }
1120
+ }
1121
+ else if (child.filter !== undefined) {
1122
+ branchAttrs.filter = filterToTf(child.filter, refs);
1123
+ }
1124
+ else {
1125
+ throw new EntityTfError(`switch case ${index + 1} on "${refKey}" has no filter`);
1126
+ }
1127
+ }
1128
+ blocks.push({ kind: "resource", type: branchType, label: branchLabel, attrs: branchAttrs });
1129
+ const branchAddress = expr.resourceAttr(branchType, branchLabel);
1130
+ dependencies.push(branchAddress);
1131
+ emitTasks(child.tasks ?? [], branchAddress);
1132
+ previous = branchAddress;
1133
+ }
1134
+ }
1135
+ else if ((task.children?.length ?? 0) > 0) {
1136
+ throw new EntityTfError(`non-operator task "${refKey}" has child tasks`);
1137
+ }
1138
+ }
1139
+ return first === undefined ? undefined : { root: first, terminal: parent };
1140
+ };
1141
+ emitTasks(payload.tasks ?? [], expr.resourceAttr(triggerType, label));
1142
+ {
1143
+ const outputValues = payload.outputProperties?.outputs ?? [];
1144
+ const publish = {
1145
+ kind: "resource",
1146
+ type: WORKFLOW_PUBLISH_RESOURCE_TYPE,
1147
+ label,
1148
+ attrs: {
1149
+ automation: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label),
1150
+ workflow_revision: payload.workflowRevision,
1151
+ ...(dependencies.length > 0 || runAutomationPublishes.size > 0
1152
+ ? { depends_on: [
1153
+ ...[...runAutomationPublishes].sort().map((target) => expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, target)),
1154
+ ...dependencies,
1155
+ ] }
1156
+ : {}),
1157
+ ...(outputValues.length > 0
1158
+ ? { outputs: outputValues.map((output) => {
1159
+ if (typeof output.name !== "string")
1160
+ throw new EntityTfError("automation output has no name");
1161
+ return { name: output.name, value: valueToTf(output.value, refs) };
1162
+ }) }
1163
+ : {}),
1164
+ },
1165
+ };
1166
+ blocks.push(publish);
1167
+ }
1168
+ return { blocks: [...[...dataBlocks.values()].sort((a, b) => (a.type + "." + a.label).localeCompare(b.type + "." + b.label)), ...blocks], address: AUTOMATION_RESOURCE_TYPE + "." + label };
266
1169
  }