@elementumai/edk 0.10.4 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +49 -13
  2. package/dist-sdk/src/catalog/token.js +2 -1
  3. package/dist-sdk/src/core/triggers/on-demand.d.ts +2 -0
  4. package/dist-sdk/src/core/triggers/on-demand.js +3 -0
  5. package/dist-sdk/src/core/wire/ref-serializer.js +26 -1
  6. package/dist-sdk/src/engine/build/context.d.ts +4 -0
  7. package/dist-sdk/src/engine/coverage-gaps.d.ts +7 -0
  8. package/dist-sdk/src/engine/coverage-gaps.js +12 -0
  9. package/dist-sdk/src/engine/ei/json-stream-reader.d.ts +43 -0
  10. package/dist-sdk/src/engine/ei/json-stream-reader.js +234 -0
  11. package/dist-sdk/src/engine/ei/run.d.ts +42 -1
  12. package/dist-sdk/src/engine/ei/run.js +201 -32
  13. package/dist-sdk/src/engine/ei/saved-plan.d.ts +16 -0
  14. package/dist-sdk/src/engine/ei/saved-plan.js +19 -0
  15. package/dist-sdk/src/engine/ei/state.d.ts +1 -1
  16. package/dist-sdk/src/engine/ei/state.js +17 -4
  17. package/dist-sdk/src/engine/progress.d.ts +3 -1
  18. package/dist-sdk/src/engine/progress.js +7 -3
  19. package/dist-sdk/src/engine/pull/authored-address.d.ts +15 -1
  20. package/dist-sdk/src/engine/pull/authored-address.js +180 -29
  21. package/dist-sdk/src/engine/pull/context.d.ts +37 -2
  22. package/dist-sdk/src/engine/pull/context.js +7 -4
  23. package/dist-sdk/src/engine/pull/ref-only.d.ts +18 -0
  24. package/dist-sdk/src/engine/pull/ref-only.js +52 -0
  25. package/dist-sdk/src/engine/tf/index.d.ts +2 -2
  26. package/dist-sdk/src/engine/tf/index.js +2 -2
  27. package/dist-sdk/src/engine/tf/labels.d.ts +22 -0
  28. package/dist-sdk/src/engine/tf/labels.js +50 -0
  29. package/dist-sdk/src/engine/tf/model.d.ts +2 -0
  30. package/dist-sdk/src/engine/tf/model.js +26 -0
  31. package/dist-sdk/src/engine/validation.d.ts +2 -0
  32. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +18 -0
  33. package/dist-sdk/src/entities/access-policy/from-tf.js +58 -24
  34. package/dist-sdk/src/entities/access-policy/member-list.d.ts +32 -0
  35. package/dist-sdk/src/entities/access-policy/member-list.js +57 -0
  36. package/dist-sdk/src/entities/access-policy/module.js +10 -0
  37. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +4 -3
  38. package/dist-sdk/src/entities/access-policy/to-tf.js +21 -12
  39. package/dist-sdk/src/entities/agent/build.js +7 -5
  40. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +2 -0
  41. package/dist-sdk/src/entities/agent/from-tf.js +13 -3
  42. package/dist-sdk/src/entities/agent/to-tf.js +11 -5
  43. package/dist-sdk/src/entities/agent/tools.d.ts +8 -0
  44. package/dist-sdk/src/entities/agent/tools.js +6 -2
  45. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +2 -0
  46. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +29 -0
  47. package/dist-sdk/src/entities/agent-tool/to-tf.js +56 -3
  48. package/dist-sdk/src/entities/agent-tool/types.d.ts +12 -8
  49. package/dist-sdk/src/entities/agent-tool/types.js +13 -9
  50. package/dist-sdk/src/entities/app/build.d.ts +12 -1
  51. package/dist-sdk/src/entities/app/build.js +80 -4
  52. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +5 -7
  53. package/dist-sdk/src/entities/app/from-tf.js +17 -12
  54. package/dist-sdk/src/entities/app/stage-keys.d.ts +18 -3
  55. package/dist-sdk/src/entities/app/stage-keys.js +40 -6
  56. package/dist-sdk/src/entities/app/to-tf.js +7 -4
  57. package/dist-sdk/src/entities/automation/build.d.ts +52 -31
  58. package/dist-sdk/src/entities/automation/build.js +59 -20
  59. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +7 -4
  60. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +39 -14
  61. package/dist-sdk/src/entities/automation/from-tf.d.ts +35 -2
  62. package/dist-sdk/src/entities/automation/from-tf.js +721 -93
  63. package/dist-sdk/src/entities/automation/index.d.ts +1 -1
  64. package/dist-sdk/src/entities/automation/module.d.ts +22 -2
  65. package/dist-sdk/src/entities/automation/module.js +244 -57
  66. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +22 -2
  67. package/dist-sdk/src/entities/automation/output-key-wire-name.js +54 -3
  68. package/dist-sdk/src/entities/automation/run-target.d.ts +61 -0
  69. package/dist-sdk/src/entities/automation/run-target.js +104 -0
  70. package/dist-sdk/src/entities/automation/script-code.d.ts +11 -1
  71. package/dist-sdk/src/entities/automation/script-code.js +106 -4
  72. package/dist-sdk/src/entities/automation/script-lint.d.ts +13 -0
  73. package/dist-sdk/src/entities/automation/script-lint.js +418 -0
  74. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +17 -1
  75. package/dist-sdk/src/entities/automation/task-output-labels.js +58 -1
  76. package/dist-sdk/src/entities/automation/tasks.d.ts +67 -22
  77. package/dist-sdk/src/entities/automation/tasks.js +18 -4
  78. package/dist-sdk/src/entities/automation/to-tf.d.ts +1 -3
  79. package/dist-sdk/src/entities/automation/to-tf.js +354 -64
  80. package/dist-sdk/src/entities/automation/triggers.d.ts +63 -11
  81. package/dist-sdk/src/entities/automation/triggers.js +45 -5
  82. package/dist-sdk/src/entities/automation/types.d.ts +21 -0
  83. package/dist-sdk/src/entities/automation/types.js +26 -0
  84. package/dist-sdk/src/entities/chart/build.d.ts +9 -1
  85. package/dist-sdk/src/entities/chart/from-tf.d.ts +2 -2
  86. package/dist-sdk/src/entities/chart/from-tf.js +25 -1
  87. package/dist-sdk/src/entities/chart/index.d.ts +1 -1
  88. package/dist-sdk/src/entities/chart/printer.js +5 -2
  89. package/dist-sdk/src/entities/chart/to-tf.js +19 -1
  90. package/dist-sdk/src/entities/dashboard/from-tf.d.ts +11 -1
  91. package/dist-sdk/src/entities/dashboard/from-tf.js +57 -7
  92. package/dist-sdk/src/entities/dashboard/to-tf.js +13 -0
  93. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +8 -2
  94. package/dist-sdk/src/entities/dynamic-layout/condition-keys.d.ts +48 -0
  95. package/dist-sdk/src/entities/dynamic-layout/condition-keys.js +261 -0
  96. package/dist-sdk/src/entities/dynamic-layout/from-tf.d.ts +3 -0
  97. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +66 -20
  98. package/dist-sdk/src/entities/dynamic-layout/module.js +2 -1
  99. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +4 -2
  100. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +341 -32
  101. package/dist-sdk/src/entities/element/build.d.ts +10 -0
  102. package/dist-sdk/src/entities/element/build.js +1 -0
  103. package/dist-sdk/src/entities/element/from-tf.js +14 -9
  104. package/dist-sdk/src/entities/element/to-tf.js +7 -4
  105. package/dist-sdk/src/entities/field/from-tf.d.ts +24 -0
  106. package/dist-sdk/src/entities/field/from-tf.js +79 -1
  107. package/dist-sdk/src/entities/field/module.js +14 -1
  108. package/dist-sdk/src/entities/field/to-tf.d.ts +38 -3
  109. package/dist-sdk/src/entities/field/to-tf.js +108 -34
  110. package/dist-sdk/src/entities/file-reader/module.js +3 -3
  111. package/dist-sdk/src/entities/file-reader/to-tf.js +3 -3
  112. package/dist-sdk/src/entities/file-reader/types.d.ts +4 -16
  113. package/dist-sdk/src/entities/file-reader/types.js +7 -0
  114. package/dist-sdk/src/entities/org/group.d.ts +1 -0
  115. package/dist-sdk/src/entities/org/group.js +2 -1
  116. package/dist-sdk/src/entities/org/role.js +5 -0
  117. package/dist-sdk/src/entities/record-create-form/from-tf.d.ts +8 -0
  118. package/dist-sdk/src/entities/record-create-form/from-tf.js +10 -2
  119. package/dist-sdk/src/entities/record-create-form/to-tf.d.ts +2 -1
  120. package/dist-sdk/src/entities/record-create-form/to-tf.js +14 -2
  121. package/dist-sdk/src/entities/relationship/from-tf.d.ts +8 -0
  122. package/dist-sdk/src/entities/relationship/from-tf.js +88 -10
  123. package/dist-sdk/src/entities/relationship/to-tf.d.ts +3 -2
  124. package/dist-sdk/src/entities/relationship/to-tf.js +79 -8
  125. package/dist-sdk/src/entities/role/from-tf.js +24 -7
  126. package/dist-sdk/src/entities/role/to-tf.js +25 -7
  127. package/dist-sdk/src/entities/service-account/from-tf.js +2 -1
  128. package/dist-sdk/src/entities/service-account/module.js +20 -0
  129. package/dist-sdk/src/entities/service-account/role-fidelity.d.ts +5 -5
  130. package/dist-sdk/src/entities/service-account/role-fidelity.js +21 -13
  131. package/dist-sdk/src/entities/service-account/to-tf.js +12 -4
  132. package/dist-sdk/src/entities/shared/filters/ast.d.ts +2 -0
  133. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +1 -1
  134. package/dist-sdk/src/entities/shared/filters/tf-codec.js +12 -7
  135. package/dist-sdk/src/entities/shared/types/field-types.d.ts +6 -3
  136. package/dist-sdk/src/entities/shared/types/field-types.js +3 -1
  137. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +5 -2
  138. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +8 -1
  139. package/dist-sdk/src/entities/skill/from-tf.js +10 -3
  140. package/dist-sdk/src/entities/skill/module.js +18 -0
  141. package/dist-sdk/src/entities/skill/to-tf.d.ts +8 -1
  142. package/dist-sdk/src/entities/skill/to-tf.js +23 -14
  143. package/dist-sdk/src/entities/skill/tools.d.ts +8 -0
  144. package/dist-sdk/src/entities/skill/tools.js +6 -2
  145. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  146. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +8 -0
  147. package/dist-sdk/src/entities/skill-tool/to-tf.js +6 -2
  148. package/dist-sdk/src/entities/task/to-tf.js +1 -0
  149. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +8 -2
  150. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +20 -10
  151. package/dist-sdk/src/entities/view/from-tf.d.ts +68 -4
  152. package/dist-sdk/src/entities/view/from-tf.js +394 -22
  153. package/dist-sdk/src/entities/view/module.js +20 -0
  154. package/dist-sdk/src/entities/view/portable.d.ts +11 -0
  155. package/dist-sdk/src/entities/view/portable.js +47 -0
  156. package/dist-sdk/src/entities/view/to-tf.d.ts +4 -1
  157. package/dist-sdk/src/entities/view/to-tf.js +25 -7
  158. package/dist-sdk/src/entities/view/types.js +1 -1
  159. package/dist-sdk/src/entities/widget/build.d.ts +4 -3
  160. package/dist-sdk/src/entities/widget/from-tf.d.ts +3 -0
  161. package/dist-sdk/src/entities/widget/from-tf.js +100 -3
  162. package/dist-sdk/src/entities/widget/to-tf.d.ts +16 -1
  163. package/dist-sdk/src/entities/widget/to-tf.js +77 -14
  164. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +30 -9
  165. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  166. package/dist-sdk/src/graph/field-resource-types.d.ts +2 -0
  167. package/dist-sdk/src/graph/field-resource-types.js +11 -0
  168. package/dist-sdk/src/graph/index.d.ts +41 -3
  169. package/dist-sdk/src/graph/index.js +24 -2
  170. package/dist-sdk/src/graph/types.d.ts +195 -5
  171. package/package.json +1 -1
@@ -18,9 +18,9 @@ import { apiTaskRefAuthoringPath, executeScriptAuthoringPath, matchesOutputWireK
18
18
  import { RESOURCE_TYPE_TO_EXECUTOR, TASK_OUTPUT_CONTRACTS } from "./generated/task-output-contracts.js";
19
19
  import { systemRefNameRoundTrips } from "./system-ref-name.js";
20
20
  import { taskTfLabel } from "./task-label.js";
21
- import { parseTriggerAttachmentPayloadRefJson, parseTriggerWholeRecordRefJson, TRIGGER_WHOLE_RECORD_REF_NAME } from "./task-output-labels.js";
21
+ import { parseTriggerAttachmentPayloadRefJson, parseTriggerWholeRecordRefJson, TASK_OUTPUT_REFERENCE_NAMES, TRIGGER_WHOLE_RECORD_REF_NAME } from "./task-output-labels.js";
22
22
  import { workflowOutputTypeFromFieldType } from "./workflow-output.js";
23
- import { ALL_AUTOMATION_TASK_TYPE_SET, AUTOMATION_BRANCH_TYPE_SET, AUTOMATION_RESOURCE_TYPE, AUTOMATION_TRIGGER_TYPE_SET, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
23
+ import { ALL_AUTOMATION_TASK_TYPE_SET, AUTOMATION_BRANCH_TYPE_SET, AUTOMATION_RESOURCE_TYPE, AUTOMATION_TRIGGER_TYPE_SET, WEBHOOK_REQUEST_REF_PATTERN, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
24
24
  const TRIGGER_KINDS = {
25
25
  elementum_record_created_trigger: "recordCreate",
26
26
  elementum_record_updated_trigger: "recordUpdate",
@@ -35,6 +35,7 @@ const TRIGGER_KINDS = {
35
35
  elementum_datamine_trigger: "dataMine",
36
36
  elementum_survey_trigger: "surveyResponseCreate",
37
37
  elementum_schedule_trigger: "schedule",
38
+ elementum_temporal_trigger: "temporal",
38
39
  };
39
40
  const TASK_FACTORIES = {
40
41
  elementum_message_task: "postComment",
@@ -175,6 +176,11 @@ function scriptOutputScalarFromStringNode(definition) {
175
176
  throw new EntityTfError(`unsupported execute-script output string format ${JSON.stringify(format)}; expected DATE, DATETIME, EMAIL, or UUID4`);
176
177
  }
177
178
  }
179
+ /** An api task block's `response_type`; undefined when absent (the provider default, JSON). */
180
+ function apiResponseTypeAttr(block) {
181
+ const value = block?.attrs.response_type;
182
+ return typeof value === "string" ? value : undefined;
183
+ }
178
184
  /**
179
185
  * Detects a switch task's default/catch-all branch and which of the two
180
186
  * mutually-exclusive wire shapes the platform is currently using to mark it.
@@ -327,15 +333,19 @@ const TRIGGER_ATTRIBUTES = new Set([
327
333
  "fire_on_recovery", "email_alias_id", "survey_template_id",
328
334
  "frequency", "interval", "timezone", "start_at", "weekdays", "day_of_month",
329
335
  "end_at", "ends_after_count", "interval_unit",
336
+ "aspect_field_id", "temporal_unit", "value",
337
+ // Build-derived from the owner's field order and never printed (edk#2280).
338
+ "object_field_ids",
330
339
  ]);
331
340
  const TASK_ATTRIBUTES = new Set([
332
- "parent", "name", "depends_on", "filter", "fields", "inputs", "output_schema",
341
+ "parent", "name", "depends_on", "object_field_ids", "filter", "fields", "inputs", "output_schema",
333
342
  "list", "code", "variables", "updates", "variable", "value",
334
343
  "object_id", "table_id", "record_reference", "record_id", "source_record_ids",
335
344
  "approval_process_id", "requester_reference", "approver_references", "reason", "summary",
336
345
  "approval_reference", "status",
337
346
  "target_record_id", "message", "message_body", "body", "from_username",
338
- "from_personal", "external_emails", "users", "groups", "attachments", "contents",
347
+ "from_personal", "external_emails", "users", "groups", "attachments", "email_attachments",
348
+ "email_send_domain_id", "contents",
339
349
  "agent_id", "prompt", "output_type", "json_fields", "ai_provider_connector_id",
340
350
  "url", "response_type", "continue_on_error", "search_table_id",
341
351
  "text_to_summarize", "text_to_classify", "field_type", "category_source", "dynamic_category_source",
@@ -506,7 +516,9 @@ function declaredOnDemandInputFieldType(trigger, wireName) {
506
516
  return undefined;
507
517
  return {
508
518
  // Inverse of to-tf's on-demand parameter type spelling.
509
- fieldType: parameter.type === "attachment" ? "ATTACHMENT_ID" : parameter.type.toUpperCase(),
519
+ fieldType: parameter.type === "attachment" ? "ATTACHMENT_ID"
520
+ : parameter.type === "group" ? "GROUP_ID"
521
+ : parameter.type.toUpperCase(),
510
522
  multiple: parameter.multiple === true,
511
523
  };
512
524
  }
@@ -586,9 +598,12 @@ export const AI_SEARCH_TABLE_TASK_REF_SEGMENT_TO_TS = {
586
598
  // proxy at build time and omits the script/filter input entirely.
587
599
  export const TABLE_RECORDS_SEARCH_TASK_REF_SEGMENT_TO_TS = {
588
600
  // Canonical count output `count` → the `totalCount` accessor (edk#835 — same
589
- // as recordSearch). "All matching table rows" is the legacy display form.
601
+ // as recordSearch).
590
602
  count: "totalCount",
603
+ // The refs keys a deployed task has (edk#2407, task-output-labels.ts).
591
604
  "All matching table rows": "records",
605
+ "First matching table row": "record",
606
+ "Row count": "totalCount",
592
607
  };
593
608
  // Platform-fixed output labels → authoring path, inverse of
594
609
  // task-output-labels.ts and executeScript's "Text Result". Scoped per task
@@ -597,6 +612,8 @@ const TASK_OUTPUT_LABEL_TO_TS = {
597
612
  elementum_record_search_task: { "First found record": ["record"] },
598
613
  elementum_create_record_task: { "Created record": ["record"] },
599
614
  elementum_update_field_task: { "Updated record": ["record"] },
615
+ // Build indexes bulkUpdateFields outputs by these display-label refs keys (edk#2281).
616
+ elementum_bulk_update_fields_task: Object.fromEntries(Object.entries(TASK_OUTPUT_REFERENCE_NAMES["elementum_bulk_update_fields_task"] ?? {}).map(([key, name]) => [key, [name]])),
600
617
  elementum_execute_script_task: {
601
618
  // Display keys. Canonical `result` / `stringArrayResult` are not refs keys;
602
619
  // `Result` is the whole JSON envelope, not a property named Result (#1656).
@@ -644,20 +661,6 @@ function aiAgentTaskRefPath(block, name) {
644
661
  .find((fieldName) => (fieldName === candidate || fieldName.toLowerCase() === candidate.toLowerCase()));
645
662
  return schemaName === undefined ? undefined : ["result", schemaName];
646
663
  }
647
- /**
648
- * A webhook trigger's `body`/`headers` refs come back as "Body (Plain
649
- * Text)"/"Headers (Content-Type)" - one wire segment naming both the
650
- * top-level property (always "body"/"headers", both typed
651
- * `Record<string, unknown>` on WebhookTriggerOutput) and an arbitrary
652
- * sub-key. Splitting it lets the sub-key print as a plain bracket access on
653
- * an already string-indexable type, instead of a false top-level property
654
- * like `ctx.trigger["Body (Plain Text)"]` that WebhookTriggerOutput never
655
- * declares. Gated on the trigger's actual resource type, not just the
656
- * string shape - a different trigger's field could otherwise coincidentally
657
- * be named "Body (something)" and get misinterpreted as this webhook-only
658
- * convention.
659
- */
660
- const WEBHOOK_REF_PATTERN = /^(Body|Headers) \((.+)\)$/;
661
664
  function aspectOwnerRefNameFromObjectId(objectId, appRefName, appTfLabel, dataBlocks, foreignAppRefNames, foreignElementRefNames, foreignTaskRefNames) {
662
665
  if (!isTfExpr(objectId))
663
666
  return undefined;
@@ -1155,7 +1158,18 @@ function triggerRefPath(path, ctx) {
1155
1158
  return ["body_html"];
1156
1159
  }
1157
1160
  if (ctx.trigger.type === "elementum_webhook_trigger") {
1158
- const webhookMatch = WEBHOOK_REF_PATTERN.exec(wireName);
1161
+ // A webhook trigger's `body`/`headers` refs come back as "Body (Plain
1162
+ // Text)"/"Headers (Content-Type)" - one wire segment naming both the
1163
+ // top-level property (always "body"/"headers", both typed
1164
+ // `Record<string, unknown>` on WebhookTriggerOutput) and an arbitrary
1165
+ // sub-key. Splitting it lets the sub-key print as a plain bracket access on
1166
+ // an already string-indexable type, instead of a false top-level property
1167
+ // like `ctx.trigger["Body (Plain Text)"]` that WebhookTriggerOutput never
1168
+ // declares. Gated on the trigger's actual resource type, not just the
1169
+ // string shape - a different trigger's field could otherwise coincidentally
1170
+ // be named "Body (something)" and get misinterpreted as this webhook-only
1171
+ // convention.
1172
+ const webhookMatch = WEBHOOK_REQUEST_REF_PATTERN.exec(wireName);
1159
1173
  if (webhookMatch)
1160
1174
  return [webhookMatch[1].toLowerCase(), webhookMatch[2]];
1161
1175
  }
@@ -1381,7 +1395,7 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
1381
1395
  }
1382
1396
  }
1383
1397
  if (block?.type === "elementum_api_task" && pathSegments.length === 1) {
1384
- const apiPath = apiTaskRefAuthoringPath(pathSegments[0]);
1398
+ const apiPath = apiTaskRefAuthoringPath(pathSegments[0], apiResponseTypeAttr(block));
1385
1399
  if (apiPath !== undefined) {
1386
1400
  return { kind: "taskRef", task: refKey, path: apiPath };
1387
1401
  }
@@ -1903,7 +1917,7 @@ function decodeValue(value, ctx) {
1903
1917
  // …) that don't match the lowercase authoring property names
1904
1918
  // (`file`, `file.contentType`) - see API_TASK_REF_AUTHORING_NAMES.
1905
1919
  if (task.block.type === "elementum_api_task" && rawSegments.length === 1) {
1906
- const apiPath = apiTaskRefAuthoringPath(rawSegments[0]);
1920
+ const apiPath = apiTaskRefAuthoringPath(rawSegments[0], apiResponseTypeAttr(task.block));
1907
1921
  if (apiPath !== undefined) {
1908
1922
  return { kind: "taskRef", task: task.refKey, path: apiPath };
1909
1923
  }
@@ -2207,7 +2221,17 @@ function decodeValue(value, ctx) {
2207
2221
  if (typeof name !== "string" || name === "") {
2208
2222
  throw new EntityTfError(`data.elementum_group.${value.label}: name lookup is missing`);
2209
2223
  }
2210
- const groupKey = ctx.groupKeysByName?.get(name) ?? tfLabelToTsLabel(sanitizeName(name));
2224
+ const orgKey = ctx.groupKeysByName?.get(name);
2225
+ if (orgKey === undefined && ctx.groupKeysByName !== undefined) {
2226
+ // The org catalog this pull loaded doesn't carry this group: org.ts
2227
+ // predates it, or org.ts is missing or failed to import (the pull
2228
+ // then passes an empty map). A guessed org.groups key would be
2229
+ // undefined at load and fail the build (edk#2241): print a by-name
2230
+ // groupRef, which builds to the same data.elementum_group lookup.
2231
+ ctx.groupsMissingFromOrg?.add(name);
2232
+ return { kind: "orgGroup", groupKey: tfLabelToTsLabel(sanitizeName(name)), name, inOrgCatalog: false };
2233
+ }
2234
+ const groupKey = orgKey ?? tfLabelToTsLabel(sanitizeName(name));
2211
2235
  return { kind: "orgGroup", groupKey, name };
2212
2236
  }
2213
2237
  if (value.$expr === "variable") {
@@ -2391,6 +2415,153 @@ const FILTER_FIELD_SCOPE_BY_FACTORY = {
2391
2415
  userSearch: "user",
2392
2416
  userGroupSearch: "userGroup",
2393
2417
  };
2418
+ function collectOptionLabels(out, value) {
2419
+ if (!Array.isArray(value))
2420
+ return;
2421
+ for (const item of value) {
2422
+ if (!isObject(item) || typeof item.label !== "string" || item.label === "")
2423
+ continue;
2424
+ out.add(item.label);
2425
+ }
2426
+ }
2427
+ function labelsFromOptions(value) {
2428
+ const labels = new Set();
2429
+ collectOptionLabels(labels, value);
2430
+ return labels.size > 0 ? labels : undefined;
2431
+ }
2432
+ /**
2433
+ * Option labels build can turn back into an options-by-label local for this
2434
+ * field id expression. A reference to another task's record is not a field
2435
+ * id, and a stub without options cannot be reversed (#2099).
2436
+ */
2437
+ function optionLabelsForFieldIdExpr(value, blocks) {
2438
+ if (!isTfExpr(value))
2439
+ return undefined;
2440
+ if (value.$expr === "resource-attr" && value.type.endsWith("_field") && value.path[0] === "id") {
2441
+ const block = blocks.get(`${value.type}.${value.label}`);
2442
+ if (block?.type !== "elementum_dropdown_field" && block?.type !== "elementum_multiselect_field")
2443
+ return undefined;
2444
+ return labelsFromOptions(block.attrs.options);
2445
+ }
2446
+ if ((value.$expr === "resource-attr" || value.$expr === "data-attr") &&
2447
+ (value.type === "elementum_app" || value.type === "elementum_element") &&
2448
+ value.path[0] === "status_field_id") {
2449
+ return labelsFromOptions(blocks.get(`${value.type}.${value.label}`)?.attrs.status_options);
2450
+ }
2451
+ if (value.$expr === "local" && value.name.endsWith("_field_id")) {
2452
+ const ownerAndField = value.name.slice(0, -"_field_id".length);
2453
+ if (ownerAndField.endsWith("_status")) {
2454
+ const owner = ownerAndField.slice(0, -"_status".length);
2455
+ const block = blocks.get(`elementum_app.${owner}`) ?? blocks.get(`elementum_element.${owner}`);
2456
+ return labelsFromOptions(block?.attrs.status_options);
2457
+ }
2458
+ for (const block of blocks.values()) {
2459
+ if (block.type !== "elementum_dropdown_field" && block.type !== "elementum_multiselect_field")
2460
+ continue;
2461
+ if (block.label === ownerAndField)
2462
+ return labelsFromOptions(block.attrs.options);
2463
+ }
2464
+ }
2465
+ return undefined;
2466
+ }
2467
+ function optionLabelsForDecodedField(field, ctx) {
2468
+ if (!isObject(field) || field.kind !== "field" || typeof field.fieldKey !== "string")
2469
+ return undefined;
2470
+ const ownerHandle = typeof field.appHandle === "string" ? field.appHandle : ctx.appRefName;
2471
+ if (field.fieldKey === "status") {
2472
+ const ownerBlock = ownerHandle === ctx.appRefName
2473
+ ? ctx.resourceBlocks.get(`${ctx.ownerScope === "element" ? "elementum_element" : "elementum_app"}.${ctx.appTfLabel}`)
2474
+ : [...ctx.resourceBlocks.values()].find((block) => (block.type === "elementum_app" || block.type === "elementum_element") &&
2475
+ block.label !== undefined &&
2476
+ tfLabelToTsLabel(block.label) === ownerHandle);
2477
+ return labelsFromOptions(ownerBlock?.attrs.status_options);
2478
+ }
2479
+ const labels = new Set();
2480
+ for (const block of ctx.resourceBlocks.values()) {
2481
+ if ((block.type !== "elementum_dropdown_field" && block.type !== "elementum_multiselect_field") || block.label === undefined)
2482
+ continue;
2483
+ if (fieldBagKey(block.label, ctx) !== field.fieldKey)
2484
+ continue;
2485
+ const owned = ownerFromScopedChildLabel(block.label);
2486
+ const ownerTf = owned?.ownerTfLabel ?? ctx.appTfLabel;
2487
+ if (tfLabelToTsLabel(ownerTf) !== ownerHandle)
2488
+ continue;
2489
+ collectOptionLabels(labels, block.attrs.options);
2490
+ }
2491
+ return labels.size > 0 ? labels : undefined;
2492
+ }
2493
+ /**
2494
+ * A filter literal's option id, printed as the label only when the compared
2495
+ * field lists that label. Build then writes the options-by-label local.
2496
+ * Anything else stays the raw id (#2099).
2497
+ */
2498
+ function filterOptionLabel(value, field, ctx) {
2499
+ if (typeof value !== "string" || !isUuid(value))
2500
+ return undefined;
2501
+ const label = ctx.picklistOptionLabelById?.get(value);
2502
+ if (label === undefined)
2503
+ return undefined;
2504
+ return optionLabelsForDecodedField(field, ctx)?.has(label) === true ? label : undefined;
2505
+ }
2506
+ /** Option ids `filterOptionLabel` will print as labels. The export still holds the id. */
2507
+ export function filterOptionIdsPrintedAsLabels(doc, optionLabelById) {
2508
+ const resolved = new Set();
2509
+ if (optionLabelById === undefined || optionLabelById.size === 0)
2510
+ return resolved;
2511
+ const blocks = new Map();
2512
+ for (const block of doc.blocks) {
2513
+ if (block.kind !== "resource" || block.type === undefined || block.label === undefined)
2514
+ continue;
2515
+ blocks.set(`${block.type}.${block.label}`, block);
2516
+ }
2517
+ const visit = (value) => {
2518
+ if (Array.isArray(value)) {
2519
+ value.forEach((item) => visit(item));
2520
+ return;
2521
+ }
2522
+ if (!isObject(value))
2523
+ return;
2524
+ if (typeof value.type === "string" && (value.type.toLowerCase() === "and" || value.type.toLowerCase() === "or") && Array.isArray(value.children)) {
2525
+ value.children.forEach((child) => visit(child));
2526
+ return;
2527
+ }
2528
+ const fieldId = value.field_id ?? (isObject(value.left_value) ? value.left_value.field_id : undefined);
2529
+ if (fieldId === undefined) {
2530
+ if (Array.isArray(value.children))
2531
+ value.children.forEach((child) => visit(child));
2532
+ return;
2533
+ }
2534
+ const labels = optionLabelsForFieldIdExpr(fieldId, blocks);
2535
+ if (labels === undefined)
2536
+ return;
2537
+ const consider = (literal) => {
2538
+ if (typeof literal !== "string" || !optionLabelById.has(literal))
2539
+ return;
2540
+ const label = optionLabelById.get(literal);
2541
+ if (label !== undefined && labels.has(label))
2542
+ resolved.add(literal);
2543
+ };
2544
+ if (isObject(value.value))
2545
+ consider(value.value.value);
2546
+ if (isObject(value.min))
2547
+ consider(value.min.value);
2548
+ if (isObject(value.max))
2549
+ consider(value.max.value);
2550
+ if (Array.isArray(value.values)) {
2551
+ for (const item of value.values) {
2552
+ if (isObject(item))
2553
+ consider(item.value);
2554
+ }
2555
+ }
2556
+ };
2557
+ for (const block of blocks.values()) {
2558
+ for (const [attr, attrValue] of Object.entries(block.attrs)) {
2559
+ if (attr === "filter")
2560
+ visit(attrValue);
2561
+ }
2562
+ }
2563
+ return resolved;
2564
+ }
2394
2565
  function picklistOptionLabel(value) {
2395
2566
  if (value === undefined || !isTfExpr(value))
2396
2567
  return undefined;
@@ -2593,7 +2764,7 @@ function decodeCalculationTaskMustache(taskId, wireName, ctx) {
2593
2764
  }
2594
2765
  }
2595
2766
  if (taskBlock?.type === "elementum_api_task") {
2596
- const apiPath = apiTaskRefAuthoringPath(wireName);
2767
+ const apiPath = apiTaskRefAuthoringPath(wireName, apiResponseTypeAttr(taskBlock));
2597
2768
  if (apiPath !== undefined) {
2598
2769
  return { kind: "taskRef", task: refKey, path: apiPath };
2599
2770
  }
@@ -2606,16 +2777,11 @@ function decodeCalculationTaskMustache(taskId, wireName, ctx) {
2606
2777
  const keyPath = wireName.split(".");
2607
2778
  const taskKind = taskBlock?.type !== undefined ? TASK_FACTORIES[taskBlock.type] : undefined;
2608
2779
  const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
2609
- // Case-SENSITIVE here, unlike the refs-map/envelope call sites: a
2610
- // calculation mustache carries the calc-engine's own lowercase name
2611
- // (WorkflowTaskReference, e.g. "response"), never the refs-map display
2612
- // key ("Response") - calculationTaskMustache already documents that the
2613
- // display label does not resolve in this dialect. Case-folding this site
2614
- // too made "response" fold to "output" (correct) but ALSO folded any
2615
- // other lowercase wire name that happens to match a wireOutputKey
2616
- // case-insensitively, rewriting the mustache as {{task name="Response"}}
2617
- // on the next build - a key the calc engine's real API never has either.
2618
- const outputKeyPath = wireOutputKey !== undefined && keyPath[0] === wireOutputKey
2780
+ // A calculation mustache names a single-output AI task's output by the calc
2781
+ // engine's canonical name (`response`), not the refs label (`Response`).
2782
+ // Both read back as `output`, which build writes as `response` (#2405).
2783
+ // Only the exact or lowercased wire key matches, as in the refs decoder.
2784
+ const outputKeyPath = wireOutputKey !== undefined && keyPath[0] !== undefined && matchesOutputWireKey(keyPath[0], wireOutputKey)
2619
2785
  ? ["output", ...keyPath.slice(1)]
2620
2786
  : keyPath.map((segment) => WIRE_REF_SEGMENT_TO_TS[segment] ?? segment);
2621
2787
  return { kind: "taskRef", task: refKey, path: outputKeyPath };
@@ -2782,6 +2948,7 @@ function workflowOutputTaskIdOrKey(taskId, ctx) {
2782
2948
  return undefined;
2783
2949
  }
2784
2950
  function filterReference(value, ctx, role) {
2951
+ assertFilterTaskRefResolves(filterReferenceTaskId(value), ctx);
2785
2952
  return typeof value === "string"
2786
2953
  ? decodeReferenceString(value, ctx) ?? { kind: "unresolved", uuid: value, hint: "filter-reference" }
2787
2954
  : decodeFilterReferenceEnvelope(value, ctx, undefined, role)
@@ -2790,6 +2957,32 @@ function filterReference(value, ctx, role) {
2790
2957
  ?? decodeTemplateForEachRef(value, ctx)
2791
2958
  ?? decodeValue(value, ctx);
2792
2959
  }
2960
+ /** The platform task id a filter reference names: `task.<id>.<name>`, or an envelope's `taskReference.taskId`. */
2961
+ function filterReferenceTaskId(value) {
2962
+ if (typeof value === "string") {
2963
+ const pieces = value.split(".");
2964
+ return pieces[0] === "task" && pieces.length > 2 ? pieces[1] : undefined;
2965
+ }
2966
+ let raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
2967
+ while (isObject(raw) && "value" in raw && Object.keys(raw).length === 1)
2968
+ raw = raw.value;
2969
+ if (!isObject(raw) || !isObject(raw.taskReference))
2970
+ return undefined;
2971
+ const taskId = raw.taskReference.taskId;
2972
+ return typeof taskId === "string" ? taskId : undefined;
2973
+ }
2974
+ /**
2975
+ * A filter's task reference must name one of this automation's own tasks.
2976
+ * Returning the raw id let source generation fail later with only the id
2977
+ * (#2054); say what the id is instead, and fail closed (#1974).
2978
+ */
2979
+ function assertFilterTaskRefResolves(taskId, ctx) {
2980
+ if (taskId === undefined || !isUuid(taskId))
2981
+ return;
2982
+ if (resolveTaskRefKey(taskId, ctx).block !== undefined)
2983
+ return;
2984
+ throw new UnresolvedTaskFilterRefError(taskId, ctx.describeUnresolvedTask?.(taskId) ?? `is not one of this automation's tasks. ${FIX_FILTER_IN_BUILDER}`, ctx.automationId);
2985
+ }
2793
2986
  function filterReferenceType(value, fallback, ctx) {
2794
2987
  const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
2795
2988
  if (!isObject(raw))
@@ -2894,15 +3087,71 @@ function decodeFilter(value, ctx, fieldScope = "app") {
2894
3087
  },
2895
3088
  reference: (reference, role) => filterReference(reference, ctx, role),
2896
3089
  referenceType: (reference, fallback) => filterReferenceType(reference, fallback, ctx),
2897
- literal: (literal) => picklistOptionLabel(literal) ?? stageFilterName(literal, ctx) ?? literal,
3090
+ literal: (literal, _valueType, field) => picklistOptionLabel(literal) ?? stageFilterName(literal, ctx) ?? filterOptionLabel(literal, field, ctx) ?? literal,
2898
3091
  }, fieldScope);
2899
3092
  }
3093
+ /**
3094
+ * A Checkbox (`boolean`) input's default. The provider's `default_value` is a
3095
+ * string, so HCL holds "true"/"false"; source authors a boolean (#2204).
3096
+ */
3097
+ function booleanDefault(value) {
3098
+ if (value === "true")
3099
+ return true;
3100
+ if (value === "false")
3101
+ return false;
3102
+ return value;
3103
+ }
3104
+ /**
3105
+ * A datamine trigger's condition (edk#2287). Pull used to drop it, so the next
3106
+ * apply cleared the live condition. It now comes back as source. A condition
3107
+ * that can't be decoded, or that tests anything but a column of the datamine's
3108
+ * own table, is an error rather than a silent drop: `pull automation` stops, and
3109
+ * `pull app` skips the automation with a coverage warning.
3110
+ */
3111
+ function dataMineCondition(raw, datamineTable, ctx) {
3112
+ const stop = (why) => {
3113
+ throw new EntityTfError(`datamine trigger condition ${why}; this automation was not pulled, rather than pulled without its condition, because the next apply would clear the condition on the platform ` +
3114
+ "(`pull automation` stops here; `pull app` skips the automation with a coverage warning). " +
3115
+ "Fix the trigger condition in the Elementum UI so it tests columns of the datamine's table, then pull again.");
3116
+ };
3117
+ let condition;
3118
+ try {
3119
+ condition = UnresolvedTaskFilterRefError.within("trigger", () => decodeFilter(raw, ctx));
3120
+ }
3121
+ catch (err) {
3122
+ if (err instanceof UnresolvedTaskFilterRefError)
3123
+ throw err;
3124
+ return stop(`can't be decoded (${err instanceof Error ? err.message : String(err)})`);
3125
+ }
3126
+ const visit = (node) => {
3127
+ if (!isObject(node))
3128
+ return;
3129
+ const field = node.field;
3130
+ if (isObject(field)) {
3131
+ if (field.kind === "unresolved")
3132
+ stop(`tests field ${JSON.stringify(field.uuid)}, which is not a column this pull can resolve`);
3133
+ if (field.kind !== "tableColumn")
3134
+ stop(`tests a ${String(field.kind)} reference, not a column of the datamine's table`);
3135
+ if (datamineTable !== undefined && field.tableHandle !== datamineTable) {
3136
+ stop(`tests column ${JSON.stringify(field.name ?? field.columnKey)} of table "${String(field.tableHandle)}", but the datamine reads table "${datamineTable}"`);
3137
+ }
3138
+ }
3139
+ if (Array.isArray(node.children))
3140
+ node.children.forEach(visit);
3141
+ };
3142
+ visit(condition);
3143
+ return condition;
3144
+ }
2900
3145
  function triggerFromBlock(block, ctx) {
2901
3146
  const kind = TRIGGER_KINDS[block.type];
2902
3147
  if (kind === undefined)
2903
3148
  throw new EntityTfError(`unknown trigger resource type "${block.type}"`);
2904
3149
  const app = appRef(ctx.appRefName);
2905
- const filter = block.attrs.filter !== undefined ? decodeFilter(block.attrs.filter, ctx) : undefined;
3150
+ // A datamine trigger's condition decodes in its own case, which fails
3151
+ // closed with a message naming the trigger (edk#2287).
3152
+ const filter = block.attrs.filter !== undefined && kind !== "dataMine"
3153
+ ? UnresolvedTaskFilterRefError.within("trigger", () => decodeFilter(block.attrs.filter, ctx))
3154
+ : undefined;
2906
3155
  switch (kind) {
2907
3156
  case "onDemand": {
2908
3157
  const parameters = block.attrs.parameters ?? [];
@@ -2917,10 +3166,12 @@ function triggerFromBlock(block, ctx) {
2917
3166
  // (onDemand's TriggerFieldTypeAlias) does. Map back so printed
2918
3167
  // source uses a type-checkable alias instead of a raw wire string
2919
3168
  // "attachment" that TriggerFieldTypeAlias doesn't accept. The
2920
- // provider's "user" is USER_ID, authored as "userId".
3169
+ // provider's "user" is USER_ID, authored as "userId", and its
3170
+ // "group" is GROUP_ID, authored as "groupId" (#2204).
2921
3171
  const type = parameter.type === "attachment" ? "attachmentId"
2922
3172
  : parameter.type === "user" ? "userId"
2923
- : parameter.type;
3173
+ : parameter.type === "group" ? "groupId"
3174
+ : parameter.type;
2924
3175
  const record = type === "record";
2925
3176
  const recordApp = record
2926
3177
  ? aspectRefFromObjectId(parameter.default_value, ctx)
@@ -2935,7 +3186,7 @@ function triggerFromBlock(block, ctx) {
2935
3186
  ...(parameter.required === true ? { required: true } : {}),
2936
3187
  ...(parameter.multiple === true ? { multiple: true } : {}),
2937
3188
  ...(!record && parameter.default_value !== undefined
2938
- ? { defaultValue: type === "userId" ? userIdDefault(parameter.default_value, ctx) : parameter.default_value }
3189
+ ? { defaultValue: type === "userId" ? userIdDefault(parameter.default_value, ctx) : type === "boolean" ? booleanDefault(parameter.default_value) : parameter.default_value }
2939
3190
  : {}),
2940
3191
  ...(typeof parameter.description === "string" ? { description: parameter.description } : {}),
2941
3192
  };
@@ -2987,7 +3238,10 @@ function triggerFromBlock(block, ctx) {
2987
3238
  if (typeof datamine !== "string" && (!isObject(datamine) || datamine.kind !== "datamine")) {
2988
3239
  throw new EntityTfError("datamine trigger requires a managed datamine reference or explicit platform id");
2989
3240
  }
2990
- return { kind, datamine: datamine, ...(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 } : {}) };
3241
+ const condition = block.attrs.filter !== undefined
3242
+ ? dataMineCondition(block.attrs.filter, typeof datamine === "string" || typeof datamine.tableHandle !== "string" ? undefined : datamine.tableHandle, ctx)
3243
+ : undefined;
3244
+ return { kind, datamine: datamine, ...(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 } : {}), ...(condition ? { filter: condition } : {}) };
2991
3245
  }
2992
3246
  case "emailReceived":
2993
3247
  if (typeof block.attrs.email_alias_id !== "string")
@@ -2997,7 +3251,7 @@ function triggerFromBlock(block, ctx) {
2997
3251
  case "surveyResponseCreate":
2998
3252
  if (typeof block.attrs.survey_template_id !== "string")
2999
3253
  throw new EntityTfError("survey trigger requires survey_template_id");
3000
- return { kind, app, survey: block.attrs.survey_template_id };
3254
+ return { kind, app, survey: block.attrs.survey_template_id, ...(filter ? { filter } : {}) };
3001
3255
  case "schedule": {
3002
3256
  if (typeof block.attrs.frequency !== "string")
3003
3257
  throw new EntityTfError("schedule trigger requires frequency");
@@ -3034,16 +3288,36 @@ function triggerFromBlock(block, ctx) {
3034
3288
  ...(typeof block.attrs.day_of_month === "number" ? { dayOfMonth: block.attrs.day_of_month } : {}),
3035
3289
  };
3036
3290
  }
3291
+ case "temporal": {
3292
+ const unit = block.attrs.temporal_unit;
3293
+ if (unit !== "MINUTES" && unit !== "HOURS" && unit !== "DAYS") {
3294
+ throw new EntityTfError(`temporal trigger temporal_unit "${String(unit)}" is not MINUTES, HOURS or DAYS`);
3295
+ }
3296
+ if (typeof block.attrs.value !== "number")
3297
+ throw new EntityTfError("temporal trigger requires value");
3298
+ if (block.attrs.aspect_field_id === undefined)
3299
+ throw new EntityTfError("temporal trigger requires aspect_field_id");
3300
+ return {
3301
+ kind,
3302
+ app,
3303
+ field: fieldRef(block.attrs.aspect_field_id, ctx),
3304
+ temporalUnit: unit,
3305
+ value: block.attrs.value,
3306
+ ...(filter ? { filter } : {}),
3307
+ };
3308
+ }
3037
3309
  default: throw new EntityTfError(`trigger "${kind}" is outside the Terraform contract`);
3038
3310
  }
3039
3311
  }
3040
3312
  function taskArgs(block, factory, ctx, taskDiagnostics) {
3041
3313
  const args = {};
3042
3314
  for (const [attr, value] of Object.entries(block.attrs)) {
3043
- if (attr === "parent" || attr === "name" || attr === "depends_on")
3315
+ // object_field_ids is build-derived from the target's field order (edk#2280).
3316
+ if (attr === "parent" || attr === "name" || attr === "depends_on" || attr === "object_field_ids")
3044
3317
  continue;
3045
3318
  if (attr === "filter") {
3046
- args.filter = decodeFilter(value, ctx, FILTER_FIELD_SCOPE_BY_FACTORY[factory] ?? "app");
3319
+ const where = `task ${JSON.stringify(typeof block.attrs.name === "string" ? block.attrs.name : block.label)} (${factory})`;
3320
+ args.filter = UnresolvedTaskFilterRefError.within(where, () => decodeFilter(value, ctx, FILTER_FIELD_SCOPE_BY_FACTORY[factory] ?? "app"));
3047
3321
  continue;
3048
3322
  }
3049
3323
  if (attr === "fields" && (factory === "createRecord" || factory === "updateField" || factory === "bulkUpdateFields")) {
@@ -3298,13 +3572,18 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3298
3572
  // option requires a `FileReaderCatalogRef` object, failing tsc on the
3299
3573
  // generated file (edk#483). Route it through the same `unresolved`
3300
3574
  // escape hatch already used for other unreconstructable references
3301
- // (`"<uuid>" as any /* TODO: ... */`) instead.
3575
+ // (`"<uuid>" as any /* TODO: ... */`) instead. The one exception is
3576
+ // another app's reader that workspace state binds to this exact id
3577
+ // (edk#2007).
3302
3578
  if (attr === "file_reader_id" && factory === "documentModel") {
3303
3579
  const decoded = decodeValue(value, ctx);
3580
+ const foreign = typeof value === "string" ? ctx.foreignFileReaderRefsById?.get(value) : undefined;
3304
3581
  args.documentModel =
3305
3582
  typeof decoded === "object" && decoded !== null && decoded.kind === "documentModel"
3306
3583
  ? decoded
3307
- : { kind: "unresolved", uuid: typeof value === "string" ? value : JSON.stringify(value), hint: "file reader" };
3584
+ : foreign !== undefined
3585
+ ? { kind: "documentModel", appHandle: foreign.ownerRefName, documentModelKey: foreign.refName }
3586
+ : { kind: "unresolved", uuid: typeof value === "string" ? value : JSON.stringify(value), hint: "file reader" };
3308
3587
  continue;
3309
3588
  }
3310
3589
  if (attr === "calculations" && factory === "calculation") {
@@ -3361,7 +3640,9 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3361
3640
  ...(value.description_field_id !== undefined
3362
3641
  ? { descriptionField: fieldRef(value.description_field_id, ctx) }
3363
3642
  : {}),
3364
- ...(value.filter !== undefined ? { filter: decodeFilter(value.filter, ctx) } : {}),
3643
+ ...(value.filter !== undefined ? {
3644
+ filter: UnresolvedTaskFilterRefError.within(`task ${JSON.stringify(typeof block.attrs.name === "string" ? block.attrs.name : block.label)} (${factory}) dynamic category source`, () => decodeFilter(value.filter, ctx)),
3645
+ } : {}),
3365
3646
  ...(typeof value.limit === "number" ? { limit: value.limit } : {}),
3366
3647
  };
3367
3648
  continue;
@@ -3440,15 +3721,17 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3440
3721
  args.outputType = typeof value === "string" ? value.toLowerCase() : decodeValue(value, ctx);
3441
3722
  continue;
3442
3723
  }
3443
- if (attr === "attachments" && factory === "aiAgent") {
3724
+ // aiAgent's attachments and sendEmail's email_attachments share one shape.
3725
+ if ((attr === "attachments" && factory === "aiAgent") || (attr === "email_attachments" && factory === "sendEmail")) {
3726
+ const kind = factory === "aiAgent" ? "AI agent attachment" : "email attachment";
3444
3727
  if (!Array.isArray(value))
3445
- throw new EntityTfError(`${block.type}.${block.label}: attachments must be an array`);
3728
+ throw new EntityTfError(`${block.type}.${block.label}: ${attr} must be an array`);
3446
3729
  args.attachments = value.map((item) => {
3447
3730
  if (!isObject(item))
3448
- throw new EntityTfError(`${block.type}.${block.label}: invalid AI agent attachment`);
3449
- const present = ["file", "attachment", "record"].filter((key) => item[key] !== undefined);
3731
+ throw new EntityTfError(`${block.type}.${block.label}: invalid ${kind}`);
3732
+ const present = ["file", "attachment", "record"].filter((key) => item[key] !== undefined && item[key] !== null);
3450
3733
  if (present.length !== 1) {
3451
- throw new EntityTfError(`${block.type}.${block.label}: AI agent attachment must set exactly one of file, attachment, or record`);
3734
+ throw new EntityTfError(`${block.type}.${block.label}: ${kind} must set exactly one of file, attachment, or record`);
3452
3735
  }
3453
3736
  const key = present[0];
3454
3737
  return { [key]: decodeValue(item[key], ctx) };
@@ -3685,36 +3968,137 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3685
3968
  }
3686
3969
  return args;
3687
3970
  }
3971
+ const UNMANAGED_PREDECESSOR_LOCAL_PREFIX = "edk_unmanaged_predecessor_";
3972
+ function documentLocals(doc) {
3973
+ return Object.assign({}, ...doc.blocks.filter((block) => block.kind === "locals").map((block) => block.attrs));
3974
+ }
3975
+ /** `type.label` plus a path such as `.inner`. A bare resource reference has no path. */
3976
+ function refAddress(value) {
3977
+ const ref = resourceRef(value);
3978
+ if (ref === undefined)
3979
+ return undefined;
3980
+ const suffix = ref.path.length > 0 ? `.${pathNames(ref.path).join(".")}` : "";
3981
+ return `${ref.type}.${ref.label}${suffix}`;
3982
+ }
3983
+ function unmanagedDataBlock(doc, label) {
3984
+ return doc.blocks.find((block) => block.kind === "data" && block.type === "elementum_unmanaged_task_reference" && block.label === label);
3985
+ }
3688
3986
  /**
3689
- * Resolve an `elementum_unmanaged_task_reference` data block's OWN real
3690
- * position in the task tree from its `operator_child_id`/`operator_task_id`/
3691
- * `parent_is_trigger` attributes (edk#821) - the platform already records
3692
- * exactly which switch case / fork-join branch / forEach body (or the
3693
- * trigger) the unsupported task sits in; this was previously discarded
3694
- * entirely in favor of always anchoring to the trigger. Returns `undefined`
3695
- * when none of those attributes resolve to an address this automation
3696
- * actually owns, so the caller can fall back to the trigger-anchor + diagnostic
3697
- * safety net rather than pointing at an address nothing will ever visit.
3987
+ * Where the task after an unsupported step sits. The local names the step it
3988
+ * comes after. The data source's operator fields are only the enclosing
3989
+ * branch, never that predecessor: the provider copies them onto the following
3990
+ * task (edk#2320). `parent_is_trigger` is not a position. It is always false
3991
+ * on a task reference, and treating it as "after the trigger" makes the next
3992
+ * plan move the live task.
3698
3993
  */
3699
- function resolveUnmanagedTaskPosition(dataBlock, triggerAddress, ownedAddresses) {
3700
- if (dataBlock.attrs.parent_is_trigger === true)
3701
- return triggerAddress;
3702
- const operatorRef = resourceRef(dataBlock.attrs.operator_task_id);
3703
- if (operatorRef?.type === "elementum_for_each_task") {
3704
- const inner = `${operatorRef.type}.${operatorRef.label}.inner`;
3705
- return ownedAddresses.has(`${operatorRef.type}.${operatorRef.label}`) ? inner : undefined;
3706
- }
3707
- const childRef = resourceRef(dataBlock.attrs.operator_child_id);
3708
- if (childRef !== undefined) {
3709
- const address = `${childRef.type}.${childRef.label}`;
3710
- return ownedAddresses.has(address) ? address : undefined;
3711
- }
3712
- if (operatorRef !== undefined) {
3713
- const address = `${operatorRef.type}.${operatorRef.label}`;
3714
- return ownedAddresses.has(address) ? address : undefined;
3994
+ function unmanagedSuccessorPosition(doc, label, ownedAddresses, addressByPlatformId, seen = new Set()) {
3995
+ if (seen.has(label))
3996
+ return undefined;
3997
+ const nextSeen = new Set(seen);
3998
+ nextSeen.add(label);
3999
+ const local = documentLocals(doc)[`${UNMANAGED_PREDECESSOR_LOCAL_PREFIX}${label}`];
4000
+ // A run of unsupported steps points each local at the previous data source.
4001
+ // The managed task at the end stays placed only when that chain reaches an
4002
+ // owned step (edk#2320).
4003
+ const predecessor = unmanagedTaskRef(local);
4004
+ if (predecessor !== undefined) {
4005
+ const predecessorPosition = unmanagedSuccessorPosition(doc, predecessor.label, ownedAddresses, addressByPlatformId, nextSeen);
4006
+ return predecessorPosition === undefined
4007
+ ? undefined
4008
+ : `elementum_unmanaged_task_reference.${predecessor.label}`;
4009
+ }
4010
+ const fromLocal = refAddress(local);
4011
+ const predecessorOwned = fromLocal !== undefined && (ownedAddresses.has(fromLocal) ||
4012
+ (fromLocal.endsWith(".inner") && ownedAddresses.has(fromLocal.slice(0, -".inner".length))));
4013
+ if (predecessorOwned)
4014
+ return fromLocal;
4015
+ const dataBlock = unmanagedDataBlock(doc, label);
4016
+ if (dataBlock === undefined)
4017
+ return undefined;
4018
+ return resolveUnmanagedTaskPosition(dataBlock, ownedAddresses, addressByPlatformId);
4019
+ }
4020
+ /** Puts every earlier unsupported step of a run into the same tree as the one a managed task parents onto. */
4021
+ function rememberUnmanagedPredecessors(doc, label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen) {
4022
+ const predecessor = unmanagedTaskRef(documentLocals(doc)[`${UNMANAGED_PREDECESSOR_LOCAL_PREFIX}${label}`]);
4023
+ if (predecessor === undefined || seen.has(predecessor.label))
4024
+ return;
4025
+ seen.add(predecessor.label);
4026
+ const address = `elementum_unmanaged_task_reference.${predecessor.label}`;
4027
+ if (!unmanagedTaskPositions.has(address)) {
4028
+ const dataBlock = dataBlocks.get(address);
4029
+ const position = unmanagedSuccessorPosition(doc, predecessor.label, ownedAddresses, addressByPlatformId);
4030
+ if (dataBlock === undefined || position === undefined)
4031
+ return;
4032
+ unmanagedTaskPositions.set(address, position);
4033
+ const refKey = typeof dataBlock.attrs.name === "string" && dataBlock.attrs.name !== ""
4034
+ ? dataBlock.attrs.name
4035
+ : tfLabelToTsLabel(dataBlock.label ?? "task");
4036
+ taskByAddress.set(address, { block: dataBlock, refKey });
4037
+ placeholderTasks.push({
4038
+ name: refKey,
4039
+ taskType: typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown",
4040
+ });
3715
4041
  }
4042
+ rememberUnmanagedPredecessors(doc, predecessor.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen);
4043
+ }
4044
+ function importPlatformId(doc, type, label) {
4045
+ for (const block of doc.blocks) {
4046
+ if (block.kind !== "import" || typeof block.attrs.id !== "string")
4047
+ continue;
4048
+ const target = resourceRef(block.attrs.to);
4049
+ if (target?.type !== type || target.label !== label)
4050
+ continue;
4051
+ const id = block.attrs.id.split(/[:/]/).at(-1);
4052
+ return id !== "" ? id : undefined;
4053
+ }
4054
+ return undefined;
4055
+ }
4056
+ function unmanagedBelongsToAutomation(doc, label, automationLabel, automationPlatformId) {
4057
+ const id = unmanagedDataBlock(doc, label)?.attrs.automation_id;
4058
+ if (typeof id === "string")
4059
+ return automationPlatformId !== undefined && id === automationPlatformId;
4060
+ const ref = resourceRef(id);
4061
+ return ref?.type === AUTOMATION_RESOURCE_TYPE && ref.label === automationLabel;
4062
+ }
4063
+ function resolveUnmanagedTaskPosition(dataBlock, ownedAddresses, addressByPlatformId) {
4064
+ // The export writes these as the platform id. A rebuild writes a resource
4065
+ // reference. Both name the same task (edk#2320).
4066
+ const operatorAddress = taskAddressOf(dataBlock.attrs.operator_task_id, addressByPlatformId);
4067
+ if (operatorAddress?.startsWith("elementum_for_each_task.")) {
4068
+ const taskAddress = operatorAddress;
4069
+ return ownedAddresses.has(taskAddress) ? `${taskAddress}.inner` : undefined;
4070
+ }
4071
+ const childAddress = taskAddressOf(dataBlock.attrs.operator_child_id, addressByPlatformId);
4072
+ if (childAddress !== undefined && ownedAddresses.has(childAddress))
4073
+ return childAddress;
4074
+ if (operatorAddress !== undefined && ownedAddresses.has(operatorAddress))
4075
+ return operatorAddress;
3716
4076
  return undefined;
3717
4077
  }
4078
+ /** The resource address a parent-position attribute names: a resource reference, or a platform id carried by an import. */
4079
+ function taskAddressOf(value, addressByPlatformId) {
4080
+ const ref = resourceRef(value);
4081
+ if (ref !== undefined)
4082
+ return `${ref.type}.${ref.label}`;
4083
+ if (typeof value !== "string" || value === "")
4084
+ return undefined;
4085
+ return addressByPlatformId.get(value);
4086
+ }
4087
+ /** Import id leaf (the platform task or case id) to its resource address. */
4088
+ function taskAddressesByPlatformId(doc) {
4089
+ const addresses = new Map();
4090
+ for (const block of doc.blocks) {
4091
+ if (block.kind !== "import" || typeof block.attrs.id !== "string")
4092
+ continue;
4093
+ const target = resourceRef(block.attrs.to);
4094
+ if (target === undefined)
4095
+ continue;
4096
+ const id = block.attrs.id;
4097
+ const leaf = id.includes(":") ? id.slice(id.lastIndexOf(":") + 1) : id;
4098
+ addresses.set(leaf, `${target.type}.${target.label}`);
4099
+ }
4100
+ return addresses;
4101
+ }
3718
4102
  /**
3719
4103
  * `triggerAddress`/`onUnmanagedParent` are the fallback of last resort: a
3720
4104
  * task whose real predecessor is an unsupported task type, when that
@@ -3804,6 +4188,16 @@ export function automationOwnedAddresses(doc, automationLabel) {
3804
4188
  owned.add(`${block.type}.${block.label}`);
3805
4189
  }
3806
4190
  }
4191
+ // A published automation names every task it owns in workflow_publish.depends_on.
4192
+ // A task whose parent is an unsupported step is only reachable that way:
4193
+ // the parent is a data source, not a resource (edk#2320).
4194
+ const publish = doc.blocks.find((block) => block.kind === "resource" && block.type === WORKFLOW_PUBLISH_RESOURCE_TYPE && references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel));
4195
+ const publishDependencies = new Set(Array.isArray(publish?.attrs.depends_on)
4196
+ ? publish.attrs.depends_on.flatMap((value) => {
4197
+ const ref = resourceRef(value);
4198
+ return ref === undefined ? [] : [`${ref.type}.${ref.label}`];
4199
+ })
4200
+ : []);
3807
4201
  let changed = true;
3808
4202
  while (changed) {
3809
4203
  changed = false;
@@ -3817,6 +4211,14 @@ export function automationOwnedAddresses(doc, automationLabel) {
3817
4211
  if (parent !== undefined && owned.has(`${parent.type}.${parent.label}`)) {
3818
4212
  owned.add(address);
3819
4213
  changed = true;
4214
+ continue;
4215
+ }
4216
+ const unmanagedLabel = unmanagedTaskRef(block.attrs.parent)?.label;
4217
+ const placed = unmanagedLabel !== undefined && unmanagedSuccessorPosition(doc, unmanagedLabel, owned, taskAddressesByPlatformId(doc)) !== undefined;
4218
+ const draftOfThis = publish === undefined && unmanagedLabel !== undefined && unmanagedBelongsToAutomation(doc, unmanagedLabel, automationLabel, importPlatformId(doc, AUTOMATION_RESOURCE_TYPE, automationLabel));
4219
+ if (placed && (publishDependencies.has(address) || draftOfThis)) {
4220
+ owned.add(address);
4221
+ changed = true;
3820
4222
  }
3821
4223
  }
3822
4224
  }
@@ -3986,18 +4388,86 @@ export class UnsupportedMultiTriggerError extends EntityTfError {
3986
4388
  this.triggerCount = triggerCount;
3987
4389
  }
3988
4390
  }
4391
+ /**
4392
+ * A filter names a task id that is not one of its automation's tasks (#2054).
4393
+ * Pull fails on it rather than skip the automation: the message says what the
4394
+ * id points to so it can be fixed in the platform's automation builder.
4395
+ */
4396
+ export class UnresolvedTaskFilterRefError extends EntityTfError {
4397
+ taskId;
4398
+ target;
4399
+ automationId;
4400
+ where;
4401
+ constructor(taskId, target, automationId, where) {
4402
+ super(`${where ?? "a filter"}${automationId !== undefined ? ` in automation ${automationId}` : ""} ` +
4403
+ `references task ${taskId}, which ${target}.`);
4404
+ this.name = "UnresolvedTaskFilterRefError";
4405
+ this.taskId = taskId;
4406
+ this.target = target;
4407
+ this.automationId = automationId;
4408
+ this.where = where;
4409
+ }
4410
+ /** Run `decode`, naming `where` (the task, branch or trigger whose filter it is) on this error. */
4411
+ static within(where, decode) {
4412
+ try {
4413
+ return decode();
4414
+ }
4415
+ catch (err) {
4416
+ if (err instanceof UnresolvedTaskFilterRefError && err.where === undefined) {
4417
+ throw new UnresolvedTaskFilterRefError(err.taskId, err.target, err.automationId, `${where}'s filter`);
4418
+ }
4419
+ throw err;
4420
+ }
4421
+ }
4422
+ }
4423
+ /**
4424
+ * The EDK ref of the app that owns a `data "elementum_service_account"`
4425
+ * lookup. Export looks up another app's account through its owning app
4426
+ * (edk#2197): `app_id = data.elementum_app.<label>.id`, that block naming the
4427
+ * app by namespace (or name). Undefined when `app_id` is not such a lookup,
4428
+ * so the account stays on the automation's own app. `{ missingApp }` when the
4429
+ * lookup names an app the workspace does not know, or names none: it
4430
+ * describes the lookup (`namespace "ns"`), and the caller throws
4431
+ * `UnresolvedServiceAccountOwnerAppError` with it (edk#2416).
4432
+ */
4433
+ function dataServiceAccountOwnerRefName(appId, dataBlocks, foreignAppRefNames, foreignAppRefNamespaces) {
4434
+ const appDataLabel = dataRefLabel(appId, "elementum_app");
4435
+ if (appDataLabel === undefined)
4436
+ return undefined;
4437
+ const appBlock = dataBlocks.get(`elementum_app.${appDataLabel}`);
4438
+ const namespace = appBlock?.attrs.namespace;
4439
+ if (typeof namespace === "string")
4440
+ return foreignAppRefNamespaces?.get(namespace) ?? { missingApp: `namespace "${namespace}"` };
4441
+ const name = appBlock?.attrs.name;
4442
+ if (typeof name === "string")
4443
+ return foreignAppRefNames?.get(name) ?? { missingApp: `name "${name}"` };
4444
+ return { missingApp: `data.elementum_app.${appDataLabel}, which names no namespace or name` };
4445
+ }
3989
4446
  /**
3990
4447
  * A bare service_account_id belongs to an app this export does not contain.
3991
4448
  * Pull cannot print a serviceAccountRef until that app is in the workspace,
3992
4449
  * and printing nothing would clear the live account.
3993
4450
  */
3994
4451
  export class UnresolvedForeignServiceAccountError extends EntityTfError {
3995
- constructor(automationLabel) {
3996
- super(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}: service_account_id names a service account outside this export ` +
3997
- "that no pulled app in state owns; pull the app that owns it first");
4452
+ constructor(automationLabel, message = `${AUTOMATION_RESOURCE_TYPE}.${automationLabel}: service_account_id names a service account outside this export ` +
4453
+ "that no pulled app in state owns; pull the app that owns it first") {
4454
+ super(message);
3998
4455
  this.name = "UnresolvedForeignServiceAccountError";
3999
4456
  }
4000
4457
  }
4458
+ /**
4459
+ * The service account is another app's, looked up through that app
4460
+ * (`data.elementum_app.<label>`), and no app in the workspace declares it.
4461
+ * Pull names the app so the next step can say which one to pull.
4462
+ */
4463
+ export class UnresolvedServiceAccountOwnerAppError extends UnresolvedForeignServiceAccountError {
4464
+ constructor(automationLabel, serviceAccountName, missingApp) {
4465
+ const account = serviceAccountName === undefined ? "a service account" : `service account "${serviceAccountName}"`;
4466
+ super(automationLabel, `${AUTOMATION_RESOURCE_TYPE}.${automationLabel}: service_account_id runs as ${account} of the app with ${missingApp}, ` +
4467
+ "and no app in this workspace declares it; pull that app first");
4468
+ this.name = "UnresolvedServiceAccountOwnerAppError";
4469
+ }
4470
+ }
4001
4471
  /**
4002
4472
  * #1320: a task reads the current item of a loop that doesn't enclose it.
4003
4473
  * Pull skips the automation like any other exclusion, and additionally
@@ -4012,8 +4482,101 @@ export class ForEachItemOutsideLoopError extends EntityTfError {
4012
4482
  this.name = "ForEachItemOutsideLoopError";
4013
4483
  }
4014
4484
  }
4485
+ const UNMANAGED_TASK_REFERENCE_TYPE = "elementum_unmanaged_task_reference";
4486
+ const FIX_FILTER_IN_BUILDER = "Fix the filter's reference in the platform's automation builder, then pull again";
4487
+ /**
4488
+ * What a task id that none of this automation's tasks carries points to
4489
+ * (#2054), worded to follow "references task <id>, which". The export is the
4490
+ * whole app, so the id can be another automation's task (a cloned filter that
4491
+ * still points at the source automation), a task of this draft that pull did
4492
+ * not place in the automation, a task type EDK cannot export, or nothing.
4493
+ */
4494
+ function describeUnresolvedTask(taskId, doc, automationLabel, taskByAddress, resourceBlocks, dataBlocks, resourceImportIds) {
4495
+ // Task import ids are `<workflow_id>:<task_id>`.
4496
+ const workflowByTaskAddress = new Map();
4497
+ let taskAddress;
4498
+ for (const block of doc.blocks) {
4499
+ if (block.kind !== "import" || typeof block.attrs.id !== "string")
4500
+ continue;
4501
+ const target = resourceRef(block.attrs.to);
4502
+ if (target === undefined || !ALL_AUTOMATION_TASK_TYPE_SET.has(target.type))
4503
+ continue;
4504
+ const [workflowId, id] = block.attrs.id.split(":");
4505
+ const address = `${target.type}.${target.label}`;
4506
+ if (workflowId !== undefined && id !== undefined)
4507
+ workflowByTaskAddress.set(address, workflowId);
4508
+ if (id === taskId)
4509
+ taskAddress = address;
4510
+ }
4511
+ const automationByImportId = new Map();
4512
+ for (const [address, id] of resourceImportIds) {
4513
+ if (address.startsWith(`${AUTOMATION_RESOURCE_TYPE}.`))
4514
+ automationByImportId.set(id, address.slice(AUTOMATION_RESOURCE_TYPE.length + 1));
4515
+ }
4516
+ const describeAutomation = (label) => {
4517
+ const name = resourceBlocks.get(`${AUTOMATION_RESOURCE_TYPE}.${label}`)?.attrs.name;
4518
+ const id = resourceImportIds.get(`${AUTOMATION_RESOURCE_TYPE}.${label}`);
4519
+ return `automation ${JSON.stringify(typeof name === "string" && name !== "" ? name : label)}${id !== undefined ? ` (${id})` : ""}`;
4520
+ };
4521
+ // Walk parents up to a trigger (or a #785 placeholder, which names its automation).
4522
+ const owningAutomationLabel = (start) => {
4523
+ const seen = new Set();
4524
+ for (let cursor = start; cursor !== undefined && !seen.has(cursor);) {
4525
+ seen.add(cursor);
4526
+ const data = cursor.startsWith(`${UNMANAGED_TASK_REFERENCE_TYPE}.`) ? dataBlocks.get(cursor) : undefined;
4527
+ if (data !== undefined) {
4528
+ return typeof data.attrs.automation_id === "string" ? automationByImportId.get(data.attrs.automation_id) : undefined;
4529
+ }
4530
+ const block = resourceBlocks.get(cursor);
4531
+ if (block === undefined)
4532
+ return undefined;
4533
+ if (AUTOMATION_TRIGGER_TYPE_SET.has(block.type ?? "")) {
4534
+ const automation = resourceRef(block.attrs.automation);
4535
+ return automation?.type === AUTOMATION_RESOURCE_TYPE ? automation.label : undefined;
4536
+ }
4537
+ const unmanaged = unmanagedTaskRef(block.attrs.parent);
4538
+ const parent = resourceRef(block.attrs.parent) ?? resourceRef(block.attrs.switch_task) ?? resourceRef(block.attrs.fork_join_task);
4539
+ cursor = unmanaged !== undefined
4540
+ ? `${UNMANAGED_TASK_REFERENCE_TYPE}.${unmanaged.label}`
4541
+ : parent !== undefined ? `${parent.type}.${parent.label}` : undefined;
4542
+ }
4543
+ return undefined;
4544
+ };
4545
+ const isDraft = !doc.blocks.some((block) => block.kind === "resource" && block.type === WORKFLOW_PUBLISH_RESOURCE_TYPE && references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel));
4546
+ if (taskAddress !== undefined) {
4547
+ const block = resourceBlocks.get(taskAddress);
4548
+ const name = typeof block?.attrs.name === "string" ? ` ${JSON.stringify(block.attrs.name)}` : "";
4549
+ const ownWorkflows = new Set([...taskByAddress.keys()].map((address) => workflowByTaskAddress.get(address)).filter((id) => id !== undefined));
4550
+ const workflowId = workflowByTaskAddress.get(taskAddress);
4551
+ // A task the walk cannot place still shares its workflow with its automation's other tasks.
4552
+ const sibling = [...workflowByTaskAddress].find(([address, id]) => id === workflowId && address !== taskAddress && owningAutomationLabel(address) !== undefined);
4553
+ const owner = owningAutomationLabel(taskAddress) ?? (sibling !== undefined ? owningAutomationLabel(sibling[0]) : undefined);
4554
+ if (owner !== undefined && owner !== automationLabel) {
4555
+ return `is task${name} of ${describeAutomation(owner)}, not of this automation: a filter copied from another automation ` +
4556
+ "still points at that automation's task. In the platform's automation builder, point the filter at a task of this automation, then pull again";
4557
+ }
4558
+ // Its parents lead back to this automation (a #785 placeholder names it),
4559
+ // or it shares a workflow with a task pull did place: either way it is
4560
+ // this automation's own task that pull left out, an EDK bug.
4561
+ if (owner === automationLabel || (workflowId !== undefined && ownWorkflows.has(workflowId))) {
4562
+ return `is task${name} of this automation${isDraft ? "'s draft" : ""}, but pull did not place it in the automation ` +
4563
+ "(it follows a task EDK cannot export, or nothing connects it to the trigger). Report this as an EDK bug";
4564
+ }
4565
+ return `is task${name} of workflow ${workflowId ?? "(unknown)"}, which no automation in this export owns. ${FIX_FILTER_IN_BUILDER}; if the reference is right, report this as an EDK bug`;
4566
+ }
4567
+ for (const block of dataBlocks.values()) {
4568
+ if (block.type !== UNMANAGED_TASK_REFERENCE_TYPE || block.attrs.id !== taskId)
4569
+ continue;
4570
+ const name = typeof block.attrs.name === "string" ? ` ${JSON.stringify(block.attrs.name)}` : "";
4571
+ const type = typeof block.attrs.task_type === "string" && block.attrs.task_type !== "" ? block.attrs.task_type : "unknown";
4572
+ return `is task${name} of type ${type}, which EDK cannot export yet, so source cannot reference it. ` +
4573
+ "In the platform's automation builder, point the filter at another task, then pull again";
4574
+ }
4575
+ return "is not a task of this automation or of any other automation in this export: it was deleted or replaced in the draft " +
4576
+ `(the platform checks references only when an automation is published), or it is a task type EDK cannot export. ${FIX_FILTER_IN_BUILDER}`;
4577
+ }
4015
4578
  /** Extract one app- or element-owned automation graph from an ei export. */
4016
- function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames, procedureKeysByDiscriminator, foreignTaskRefNames, groupKeysByName, serviceAccountsById) {
4579
+ function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames, procedureKeysByDiscriminator, foreignTaskRefNames, groupKeysByName, serviceAccountsById, foreignFileReaderRefsById, foreignAppRefNamespaces) {
4017
4580
  const automation = doc.blocks.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE && block.label === automationLabel);
4018
4581
  if (automation === undefined)
4019
4582
  throw new EntityTfError(`automation resource "${automationLabel}" not found`);
@@ -4078,9 +4641,14 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4078
4641
  }
4079
4642
  // edk#785: a data-source parent is always "resolved" (see unmanagedTaskRef) -
4080
4643
  // doesn't need its target to already be owned the way a resource-attr parent does.
4081
- else if (!parent && unmanagedTaskRef(task.attrs.parent) && publishDependencyAddresses.has(`${task.type}.${task.label}`) && !owned.has(`${task.type}.${task.label}`)) {
4082
- owned.add(`${task.type}.${task.label}`);
4083
- changed = true;
4644
+ else if (!parent && unmanagedTaskRef(task.attrs.parent) && !owned.has(`${task.type}.${task.label}`)) {
4645
+ const unmanagedLabel = unmanagedTaskRef(task.attrs.parent)?.label;
4646
+ const placed = unmanagedLabel !== undefined && unmanagedSuccessorPosition(doc, unmanagedLabel, owned, taskAddressesByPlatformId(doc)) !== undefined;
4647
+ const draftOfThis = publish === undefined && unmanagedLabel !== undefined && unmanagedBelongsToAutomation(doc, unmanagedLabel, automationLabel, importPlatformId(doc, AUTOMATION_RESOURCE_TYPE, automationLabel));
4648
+ if (placed && (publishDependencyAddresses.has(`${task.type}.${task.label}`) || draftOfThis)) {
4649
+ owned.add(`${task.type}.${task.label}`);
4650
+ changed = true;
4651
+ }
4084
4652
  }
4085
4653
  }
4086
4654
  }
@@ -4148,12 +4716,50 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4148
4716
  const appTfLabel = app.label;
4149
4717
  const dataBlocks = new Map(doc.blocks.filter((block) => block.kind === "data" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
4150
4718
  const taskByAddress = new Map(tasks.map((block) => [`${block.type}.${block.label}`, { block, refKey: taskRefKey(block, automationLabel, appTfLabel) }]));
4151
- const adoptionAddressAliases = [...taskByAddress.entries()].flatMap(([from, { block, refKey }]) => {
4719
+ const taskAddressAliases = [...taskByAddress.entries()].flatMap(([from, { block, refKey }]) => {
4152
4720
  if (soleVariableName(block) === undefined)
4153
4721
  return [];
4154
4722
  const to = `${block.type}.${taskTfLabel(automationLabel, refKey)}`;
4155
4723
  return to === from ? [] : [{ from, to }];
4156
4724
  });
4725
+ // edk#2010: ei's branch resource label follows the branch's own live
4726
+ // display text, which can diverge from the canonical authored parent
4727
+ // label (e.g. a parent switch/forkJoin task whose refKey round-trips
4728
+ // through the camelCase bijection, confirmed live on Offering Versions
4729
+ // 7a: `..._switch_case.offeringver_7a_...` vs the rebuilt
4730
+ // `..._switch_case.offeringver__7a_...`). to-tf.ts rebuilds every branch
4731
+ // label as `${parentTfLabel}_${sanitizeName(child.label ?? child.defaultLabel ?? fallbackLabel)}`
4732
+ // (to-tf.ts's emitTasks, switch/forkJoin branch). `child.label` there is
4733
+ // `null` on a default case, so `??` always skips to the real display text
4734
+ // (defaultLabel, carrying the SAME raw string as a non-default `label`)
4735
+ // and only reaches the fixed fallback ("default"/"case") when ei wrote no
4736
+ // label at all - collapsing to one audited formula below:
4737
+ // `sanitizeName(rawLabel ?? (isDefault ? "default" : "case"))`.
4738
+ const branchAddressAliases = ownedBranches.flatMap((branch) => {
4739
+ const parentAttr = branch.type === "elementum_switch_case" ? "switch_task" : "fork_join_task";
4740
+ const parentRef = resourceRef(branch.attrs[parentAttr]);
4741
+ const parentEntry = parentRef !== undefined ? taskByAddress.get(`${parentRef.type}.${parentRef.label}`) : undefined;
4742
+ if (parentEntry === undefined)
4743
+ return []; // unresolved parent is already reported via the task walk above
4744
+ const parentTfLabel = taskTfLabel(automationLabel, parentEntry.refKey);
4745
+ // Mirrors to-tf.ts's `isDefault = wireType === "switch" && (child.isDefault === true || child.label === null)`:
4746
+ // a fork_join_branch is never a default; a switch_case is default exactly
4747
+ // when it carries one of the two live wire shapes defaultSwitchShape detects.
4748
+ const isDefault = branch.type === "elementum_switch_case" && defaultSwitchShape(branch) !== undefined;
4749
+ const rawLabel = typeof branch.attrs.label === "string" ? branch.attrs.label : undefined;
4750
+ const suffix = sanitizeName(rawLabel ?? (isDefault ? "default" : "case"));
4751
+ const from = `${branch.type}.${branch.label}`;
4752
+ const to = `${branch.type}.${parentTfLabel}_${suffix}`;
4753
+ return to === from ? [] : [{ from, to }];
4754
+ });
4755
+ // A genuine suffix collision between two siblings (to-tf.ts's usedSuffixes
4756
+ // guard - e.g. an unlabeled case next to one explicitly labeled "Case")
4757
+ // would make the authored source unbuildable either way, so there is no
4758
+ // single correct target to prefer; reconcileAdoptionAddressAliases
4759
+ // (adopt.ts) already refuses two aliases that claim the same target
4760
+ // address, naming both "from" addresses, so that case fails loudly here
4761
+ // instead of silently importing the wrong state.
4762
+ const adoptionAddressAliases = [...taskAddressAliases, ...branchAddressAliases];
4157
4763
  const taskTargetOwnerRefNameByAddress = new Map();
4158
4764
  const taskTargetOwnerKindByAddress = new Map();
4159
4765
  for (const [address, { block }] of taskByAddress) {
@@ -4198,6 +4804,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4198
4804
  }
4199
4805
  }
4200
4806
  const stringifiedValueReferences = { unresolved: false };
4807
+ const groupsMissingFromOrg = new Set();
4201
4808
  const ctx = {
4202
4809
  appRefName,
4203
4810
  appTfLabel: app.label,
@@ -4212,6 +4819,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4212
4819
  ...(foreignFieldRefsById !== undefined && { foreignFieldRefsById }),
4213
4820
  ...(foreignFieldRefsByDataAddress !== undefined && { foreignFieldRefsByDataAddress }),
4214
4821
  ...(foreignTableRefsById !== undefined && { foreignTableRefsById }),
4822
+ ...(foreignFileReaderRefsById !== undefined && { foreignFileReaderRefsById }),
4215
4823
  ...(picklistOptionLabelById !== undefined && { picklistOptionLabelById }),
4216
4824
  ...(fieldNamesByOwnerRefName !== undefined && { fieldNamesByOwnerRefName }),
4217
4825
  ...(taskTargetOwnerRefNameByAddress.size > 0 && { taskTargetOwnerRefNameByAddress }),
@@ -4222,8 +4830,14 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4222
4830
  ...(procedureKeysByDiscriminator !== undefined && { procedureKeysByDiscriminator }),
4223
4831
  ...(groupKeysByName !== undefined && { groupKeysByName }),
4224
4832
  stringifiedValueReferences,
4833
+ groupsMissingFromOrg,
4834
+ ...(resourceImportIds.has(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`) && {
4835
+ automationId: resourceImportIds.get(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`),
4836
+ }),
4837
+ describeUnresolvedTask: (taskId) => describeUnresolvedTask(taskId, doc, automationLabel, taskByAddress, resourceBlocks, dataBlocks, resourceImportIds),
4225
4838
  };
4226
4839
  let serviceAccountName;
4840
+ let foreignServiceAccountAppRefName;
4227
4841
  const serviceAccountValue = automation.attrs.service_account_id;
4228
4842
  if (serviceAccountValue !== undefined &&
4229
4843
  isTfExpr(serviceAccountValue) &&
@@ -4241,8 +4855,15 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4241
4855
  serviceAccountName = `${block.attrs.first_name} ${block.attrs.last_name}`;
4242
4856
  }
4243
4857
  }
4858
+ if (reference.$expr === "data-attr" && block !== undefined) {
4859
+ const owner = dataServiceAccountOwnerRefName(block.attrs.app_id, dataBlocks, foreignAppRefNames, foreignAppRefNamespaces);
4860
+ if (typeof owner === "object")
4861
+ throw new UnresolvedServiceAccountOwnerAppError(automationLabel, serviceAccountName, owner.missingApp);
4862
+ if (owner !== undefined)
4863
+ foreignServiceAccountAppRefName = owner;
4864
+ }
4244
4865
  }
4245
- let serviceAccountAppRefName;
4866
+ let serviceAccountAppRefName = foreignServiceAccountAppRefName;
4246
4867
  if (typeof serviceAccountValue === "string" && isUuid(serviceAccountValue) && serviceAccountsById !== undefined) {
4247
4868
  const owned = serviceAccountsById.get(serviceAccountValue);
4248
4869
  if (owned !== undefined) {
@@ -4274,6 +4895,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4274
4895
  ]);
4275
4896
  const unmanagedTaskPositions = new Map();
4276
4897
  const placeholderTasks = [];
4898
+ const addressByPlatformId = taskAddressesByPlatformId(doc);
4277
4899
  for (const task of tasks) {
4278
4900
  const unmanagedRef = unmanagedTaskRef(task.attrs.parent);
4279
4901
  if (unmanagedRef === undefined)
@@ -4282,7 +4904,9 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4282
4904
  if (unmanagedTaskPositions.has(address))
4283
4905
  continue;
4284
4906
  const dataBlock = dataBlocks.get(address);
4285
- const position = dataBlock !== undefined ? resolveUnmanagedTaskPosition(dataBlock, triggerAddress, ownedAddresses) : undefined;
4907
+ const position = unmanagedRef.label !== undefined
4908
+ ? unmanagedSuccessorPosition(doc, unmanagedRef.label, ownedAddresses, addressByPlatformId)
4909
+ : undefined;
4286
4910
  if (dataBlock === undefined || position === undefined)
4287
4911
  continue; // falls back to parentAddress's trigger-anchor + diagnostic
4288
4912
  unmanagedTaskPositions.set(address, position);
@@ -4292,6 +4916,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4292
4916
  name: refKey,
4293
4917
  taskType: typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown",
4294
4918
  });
4919
+ rememberUnmanagedPredecessors(doc, unmanagedRef.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, new Set([unmanagedRef.label]));
4295
4920
  }
4296
4921
  const childrenByParent = new Map();
4297
4922
  for (const task of tasks) {
@@ -4340,7 +4965,9 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4340
4965
  // unmarked default, so leaving this unset there keeps printed
4341
4966
  // output terse and matches a freshly-authored default branch.
4342
4967
  ...(shape === "explicitTrueFilter" ? { defaultFilterMode: shape } : {}),
4343
- ...(!isDefault && branch.attrs.filter !== undefined ? { filter: decodeFilter(branch.attrs.filter, ctx) } : {}),
4968
+ ...(!isDefault && branch.attrs.filter !== undefined ? {
4969
+ filter: UnresolvedTaskFilterRefError.within(`task ${JSON.stringify(typeof block.attrs.name === "string" ? block.attrs.name : block.label)} (${factory}) branch ${JSON.stringify(rawLabel ?? branch.label)}`, () => decodeFilter(branch.attrs.filter, ctx)),
4970
+ } : {}),
4344
4971
  tasks: buildTasks(`${branch.type}.${branch.label}`),
4345
4972
  };
4346
4973
  });
@@ -4440,18 +5067,19 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
4440
5067
  ast,
4441
5068
  blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])],
4442
5069
  adoptionAddressAliases,
4443
- ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0 || outputDiagnostics.length > 0 || taskDiagnostics.length > 0) && {
5070
+ ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0 || outputDiagnostics.length > 0 || taskDiagnostics.length > 0 || groupsMissingFromOrg.size > 0) && {
4444
5071
  diagnostics: [
4445
5072
  ...unrebuildableTasks.map((address) => `automation "${automationLabel}": ${address}'s real parent is a task type EDK doesn't support yet, so its authored position couldn't be reconstructed (anchored to the trigger instead) - not rebuildable from this source until that task type is supported`),
4446
5073
  ...placeholderTasks.map(({ name, taskType }) => `automation "${automationLabel}" uses platform task type "${taskType}" ("${name}"), which EDK doesn't implement - kept as an unimplementedTask(...) placeholder; its configuration isn't authorable, but its position and downstream chain are round-trip-safe`),
4447
5074
  ...outputDiagnostics,
4448
5075
  ...taskDiagnostics.map((message) => `automation "${automationLabel}": ${message}`),
5076
+ ...[...groupsMissingFromOrg].map((name) => `automation "${automationLabel}": group "${name}" is not in the org catalog this pull loaded (org.ts doesn't carry it, or org.ts is missing or couldn't be imported), so it was pulled as groupRef({ name: ${JSON.stringify(name)} }); run \`elementum pull org --data-only\`, then pull this app again to refer to it as org.groups.<key>`),
4449
5077
  ],
4450
5078
  }),
4451
5079
  ...(stringifiedValueReferences.unresolved ? { stringifiedValueReferences: true } : {}),
4452
5080
  };
4453
5081
  }
4454
- export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth) {
5082
+ export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth) {
4455
5083
  if (Array.isArray(first)) {
4456
5084
  const ctx = second;
4457
5085
  const automationBlock = first.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE);
@@ -4460,18 +5088,18 @@ export function automationFromTf(first, second, third, fourth, fifth, sixth, sev
4460
5088
  throw new EntityTfError(`automation graph has no ${AUTOMATION_RESOURCE_TYPE} resource, so its resources (${addresses.join(", ") || "none"}) cannot be pulled`);
4461
5089
  }
4462
5090
  try {
4463
- const result = automationFromTfDocument({ blocks: [...first] }, automationBlock.label, ctx.ownerHandle, ctx.foreignFieldRefsById, ctx.foreignFieldRefsByDataAddress, ctx.foreignTableRefsById, ctx.picklistOptionLabelById, ctx.fieldNamesByOwnerRefName, ctx.foreignAppRefNames, ctx.foreignElementRefNames, ctx.procedureKeysByDiscriminator, ctx.foreignTaskRefNames, ctx.groupKeysByName, ctx.serviceAccountsById);
5091
+ const result = automationFromTfDocument({ blocks: [...first] }, automationBlock.label, ctx.ownerHandle, ctx.foreignFieldRefsById, ctx.foreignFieldRefsByDataAddress, ctx.foreignTableRefsById, ctx.picklistOptionLabelById, ctx.fieldNamesByOwnerRefName, ctx.foreignAppRefNames, ctx.foreignElementRefNames, ctx.procedureKeysByDiscriminator, ctx.foreignTaskRefNames, ctx.groupKeysByName, ctx.serviceAccountsById, ctx.foreignFileReaderRefsById, ctx.foreignAppRefNamespaces);
4464
5092
  if (result.diagnostics)
4465
5093
  ctx.diagnostics.push(...result.diagnostics);
4466
5094
  return { automation: result.ast };
4467
5095
  }
4468
5096
  catch (err) {
4469
- if (err instanceof UnsupportedMultiTriggerError)
5097
+ if (err instanceof UnsupportedMultiTriggerError || err instanceof UnresolvedTaskFilterRefError)
4470
5098
  throw err;
4471
5099
  const message = err instanceof Error ? err.message : String(err);
4472
5100
  ctx.diagnostics.push(message);
4473
5101
  return { skippedReason: message };
4474
5102
  }
4475
5103
  }
4476
- return automationFromTfDocument(first, second, third ?? "", fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth);
5104
+ return automationFromTfDocument(first, second, third ?? "", fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth);
4477
5105
  }