@elementumai/edk 0.13.4 → 0.14.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 (123) hide show
  1. package/dist-sdk/src/catalog/factories.d.ts +4 -2
  2. package/dist-sdk/src/catalog/factories.js +3 -1
  3. package/dist-sdk/src/catalog/from-authoring.d.ts +8 -3
  4. package/dist-sdk/src/catalog/from-authoring.js +21 -8
  5. package/dist-sdk/src/engine/build/context.d.ts +17 -0
  6. package/dist-sdk/src/engine/coverage-gaps.d.ts +10 -0
  7. package/dist-sdk/src/engine/coverage-gaps.js +16 -0
  8. package/dist-sdk/src/engine/pull/context.d.ts +56 -0
  9. package/dist-sdk/src/engine/pull/context.js +8 -0
  10. package/dist-sdk/src/engine/pull/pulled-roots.d.ts +14 -1
  11. package/dist-sdk/src/engine/pull/pulled-roots.js +23 -3
  12. package/dist-sdk/src/engine/pull/ref-only.d.ts +6 -1
  13. package/dist-sdk/src/engine/pull/ref-only.js +4 -1
  14. package/dist-sdk/src/engine/pull/stream-root.d.ts +13 -1
  15. package/dist-sdk/src/engine/pull/stream-root.js +54 -4
  16. package/dist-sdk/src/engine/validation.d.ts +36 -1
  17. package/dist-sdk/src/engine/validation.js +56 -2
  18. package/dist-sdk/src/engine/workspace/loader.d.ts +6 -0
  19. package/dist-sdk/src/engine/workspace/loader.js +87 -2
  20. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +7 -0
  21. package/dist-sdk/src/entities/access-policy/from-tf.js +58 -17
  22. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +3 -1
  23. package/dist-sdk/src/entities/access-policy/to-tf.js +1 -1
  24. package/dist-sdk/src/entities/agent/build.d.ts +15 -0
  25. package/dist-sdk/src/entities/agent/build.js +139 -16
  26. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +3 -3
  27. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +39 -25
  28. package/dist-sdk/src/entities/agent/module.js +95 -3
  29. package/dist-sdk/src/entities/agent/to-tf.js +6 -4
  30. package/dist-sdk/src/entities/agent-evaluation/from-tf.d.ts +7 -0
  31. package/dist-sdk/src/entities/agent-evaluation/from-tf.js +14 -5
  32. package/dist-sdk/src/entities/agent-evaluation/module.js +4 -2
  33. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +11 -2
  34. package/dist-sdk/src/entities/agent-tool/from-tf.js +38 -40
  35. package/dist-sdk/src/entities/agent-tool/to-tf.js +12 -5
  36. package/dist-sdk/src/entities/app/build.d.ts +1 -1
  37. package/dist-sdk/src/entities/automation/build.d.ts +75 -42
  38. package/dist-sdk/src/entities/automation/build.js +17 -7
  39. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +14 -2
  40. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +9 -0
  41. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +57 -12
  42. package/dist-sdk/src/entities/automation/from-tf.d.ts +51 -0
  43. package/dist-sdk/src/entities/automation/from-tf.js +476 -93
  44. package/dist-sdk/src/entities/automation/index.d.ts +1 -1
  45. package/dist-sdk/src/entities/automation/index.js +1 -1
  46. package/dist-sdk/src/entities/automation/module.js +90 -9
  47. package/dist-sdk/src/entities/automation/operators.d.ts +6 -2
  48. package/dist-sdk/src/entities/automation/operators.js +0 -2
  49. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +8 -0
  50. package/dist-sdk/src/entities/automation/task-output-labels.js +11 -0
  51. package/dist-sdk/src/entities/automation/tasks.d.ts +37 -2
  52. package/dist-sdk/src/entities/automation/tasks.js +38 -1
  53. package/dist-sdk/src/entities/automation/to-tf.d.ts +8 -0
  54. package/dist-sdk/src/entities/automation/to-tf.js +413 -47
  55. package/dist-sdk/src/entities/chart/to-tf.js +18 -5
  56. package/dist-sdk/src/entities/dashboard/from-tf.js +45 -11
  57. package/dist-sdk/src/entities/dashboard-widget-order/order.d.ts +5 -3
  58. package/dist-sdk/src/entities/dashboard-widget-order/order.js +6 -4
  59. package/dist-sdk/src/entities/datamine/from-tf.js +10 -3
  60. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +9 -2
  61. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +35 -7
  62. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +63 -7
  63. package/dist-sdk/src/entities/element/build.d.ts +4 -1
  64. package/dist-sdk/src/entities/element/build.js +3 -4
  65. package/dist-sdk/src/entities/field/from-tf.js +8 -1
  66. package/dist-sdk/src/entities/field/to-tf.d.ts +29 -2
  67. package/dist-sdk/src/entities/field/to-tf.js +106 -7
  68. package/dist-sdk/src/entities/phone-service/from-tf.d.ts +7 -0
  69. package/dist-sdk/src/entities/phone-service/from-tf.js +15 -7
  70. package/dist-sdk/src/entities/phone-service/module.js +4 -2
  71. package/dist-sdk/src/entities/portal/to-tf.d.ts +1 -1
  72. package/dist-sdk/src/entities/portal/to-tf.js +61 -2
  73. package/dist-sdk/src/entities/record-create-form/from-tf.js +3 -1
  74. package/dist-sdk/src/entities/relationship/from-tf.js +34 -4
  75. package/dist-sdk/src/entities/relationship/to-tf.js +24 -6
  76. package/dist-sdk/src/entities/role/from-tf.js +3 -1
  77. package/dist-sdk/src/entities/search-table/from-tf.d.ts +3 -1
  78. package/dist-sdk/src/entities/search-table/from-tf.js +6 -3
  79. package/dist-sdk/src/entities/search-table/module.js +18 -2
  80. package/dist-sdk/src/entities/search-table/to-tf.js +10 -16
  81. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +6 -1
  82. package/dist-sdk/src/entities/shared/filters/index.d.ts +6 -1
  83. package/dist-sdk/src/entities/shared/filters/index.js +8 -2
  84. package/dist-sdk/src/entities/shared/filters/print.js +18 -7
  85. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +11 -0
  86. package/dist-sdk/src/entities/shared/filters/tf-codec.js +24 -2
  87. package/dist-sdk/src/entities/shared/run-automation-requirement.d.ts +15 -0
  88. package/dist-sdk/src/entities/shared/run-automation-requirement.js +28 -0
  89. package/dist-sdk/src/entities/shared/search-table-address.d.ts +17 -0
  90. package/dist-sdk/src/entities/shared/search-table-address.js +24 -0
  91. package/dist-sdk/src/entities/shared/skip-release.d.ts +49 -0
  92. package/dist-sdk/src/entities/shared/skip-release.js +74 -0
  93. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +3 -3
  94. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +11 -5
  95. package/dist-sdk/src/entities/skill/module.js +3 -25
  96. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +4 -2
  97. package/dist-sdk/src/entities/skill-tool/from-tf.js +28 -27
  98. package/dist-sdk/src/entities/skill-tool/to-tf.js +12 -5
  99. package/dist-sdk/src/entities/skill-tool/types.d.ts +1 -0
  100. package/dist-sdk/src/entities/skill-tool/types.js +2 -1
  101. package/dist-sdk/src/entities/table/catalog.d.ts +16 -0
  102. package/dist-sdk/src/entities/table/catalog.js +44 -2
  103. package/dist-sdk/src/entities/table/from-tf.js +30 -4
  104. package/dist-sdk/src/entities/table/keys.d.ts +27 -0
  105. package/dist-sdk/src/entities/table/keys.js +46 -0
  106. package/dist-sdk/src/entities/table/to-tf.js +2 -2
  107. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +12 -1
  108. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +9 -4
  109. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +215 -10
  110. package/dist-sdk/src/entities/view/agent-view-layout.d.ts +10 -4
  111. package/dist-sdk/src/entities/view/custom-view-runtime-rules.d.ts +43 -0
  112. package/dist-sdk/src/entities/view/custom-view-runtime-rules.js +285 -0
  113. package/dist-sdk/src/entities/view/custom-view-validate.d.ts +3 -1
  114. package/dist-sdk/src/entities/view/custom-view-validate.js +24 -5
  115. package/dist-sdk/src/entities/view/from-tf.js +14 -1
  116. package/dist-sdk/src/entities/widget/from-tf.js +14 -7
  117. package/dist-sdk/src/entities/widget/to-tf.js +7 -5
  118. package/dist-sdk/src/graph/index.d.ts +14 -1
  119. package/dist-sdk/src/graph/index.js +2 -0
  120. package/dist-sdk/src/graph/resource-types.d.ts +2 -0
  121. package/dist-sdk/src/graph/resource-types.js +3 -0
  122. package/dist-sdk/src/graph/types.d.ts +82 -0
  123. package/package.json +1 -1
@@ -1,4 +1,6 @@
1
1
  import { USER_FIELD_KEYS, USER_GROUP_FIELD_KEYS } from "../../catalog/types.js";
2
+ import { RUN_AUTOMATION_TOOL_RESOURCE_TYPE } from "../agent-tool/types.js";
3
+ import { SKILL_RUN_AUTOMATION_TOOL_RESOURCE_TYPE } from "../skill-tool/types.js";
2
4
  import { RECORD_ID_REFERENCE_FIELD } from "./task-output-labels.js";
3
5
  import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET, SYSTEM_FIELD_KEYS } from "../../core/system-fields.js";
4
6
  import { normalizeOnDemandParamKey } from "../../../pull/util.js";
@@ -24,6 +26,8 @@ import { workflowOutputTypeFromFieldType } from "./workflow-output.js";
24
26
  import { slackMessageTriggerPathFromWire } from "./slack-message-refs.js";
25
27
  import { APPROVAL_TRIGGER_OUTPUT_HEADS, approvalTriggerPathFromRefsKey } from "./approval-trigger-refs.js";
26
28
  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";
29
+ import { tableColumnKey, tableColumnKeysByName } from "../table/keys.js";
30
+ import { readRefOnlyMetadata } from "../../engine/pull/ref-only.js";
27
31
  const TRIGGER_KINDS = {
28
32
  elementum_record_created_trigger: "recordCreate",
29
33
  elementum_record_updated_trigger: "recordUpdate",
@@ -349,7 +353,7 @@ const TASK_ATTRIBUTES = new Set([
349
353
  "parent", "name", "depends_on", "object_field_ids", "object_fields", "object_system_field_ids", "refs_read", "filter", "fields", "inputs", "output_schema",
350
354
  "list", "code", "variables", "updates", "variable", "value",
351
355
  "object_id", "table_id", "record_reference", "record_id", "source_record_ids",
352
- "approval_process_id", "requester_reference", "approver_references", "reason", "summary",
356
+ "approval_process_id", "requester_reference", "approver_references", "approvers", "reason", "summary",
353
357
  "approval_reference", "status",
354
358
  "target_record_id", "message", "message_body", "body", "from_username",
355
359
  "from_personal", "external_emails", "users", "groups", "attachments", "email_attachments",
@@ -380,6 +384,72 @@ const PUBLISH_ATTRIBUTES = new Set([
380
384
  function appRef(appRefName) {
381
385
  return { kind: "app", appHandle: appRefName };
382
386
  }
387
+ /** Run `decode` with the repair site set to `site` (undefined pauses collection). */
388
+ function atRepairSite(ctx, site, decode) {
389
+ const repairs = ctx.triggerReferenceRepairs;
390
+ if (repairs === undefined)
391
+ return decode();
392
+ const previous = repairs.site;
393
+ repairs.site = site;
394
+ try {
395
+ return decode();
396
+ }
397
+ finally {
398
+ repairs.site = previous;
399
+ }
400
+ }
401
+ /** The current repair site with a different `input` label (built only while collecting); undefined while collection is paused. */
402
+ function repairInput(ctx, input) {
403
+ const site = ctx.triggerReferenceRepairs?.site;
404
+ return site === undefined ? undefined : { ...site, input: input() };
405
+ }
406
+ /**
407
+ * Record a repair when `decoded` is the `ctx.trigger.<wireName>` reference
408
+ * pull made from a live reference spelled `wireName`, and `wireName` is a
409
+ * declared scalar on-demand input the platform knows by another
410
+ * (normalized) name.
411
+ */
412
+ function noteTriggerReferenceSpelling(wireName, decoded, ctx) {
413
+ const repairs = ctx.triggerReferenceRepairs;
414
+ if (repairs?.site === undefined || wireName === undefined)
415
+ return;
416
+ if (!isObject(decoded) || decoded.kind !== "triggerRef")
417
+ return;
418
+ const path = decoded.path;
419
+ if (!Array.isArray(path) || path.length !== 1 || path[0] !== wireName)
420
+ return;
421
+ if (normalizeOnDemandParamKey(wireName) === wireName || !Array.isArray(ctx.trigger.attrs.parameters))
422
+ return;
423
+ // Build writes the normalized name only for a scalar input; a record or
424
+ // user input keeps its spelling (or doesn't build), so the plan leaves it.
425
+ const parameter = ctx.trigger.attrs.parameters.find((candidate) => isObject(candidate) && candidate.name === wireName);
426
+ if (!isObject(parameter) || parameter.type === "record" || parameter.type === "user")
427
+ return;
428
+ repairs.found.push({ ...repairs.site, declared: wireName });
429
+ }
430
+ /** A field's display name for a repair site; its key when the export doesn't carry it. */
431
+ function fieldDisplayName(fieldKey, ctx) {
432
+ for (const field of ctx.fieldById.values()) {
433
+ if (field.key === fieldKey)
434
+ return field.name;
435
+ }
436
+ if (SYSTEM_FIELD_KEY_SET.has(fieldKey)) {
437
+ const renamed = fieldKey === "title" ? ctx.titleFieldName : fieldKey === "id" ? ctx.idFieldName : fieldKey === "status" ? ctx.statusFieldName : undefined;
438
+ return renamed ?? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[fieldKey];
439
+ }
440
+ return fieldKey;
441
+ }
442
+ /** `triggerReference.name` of a ValueReference envelope (jsonencode, object, or `{ value: … }` wrapper). */
443
+ function envelopeTriggerReferenceName(value) {
444
+ let raw = isTfExpr(value) && value.$expr === "jsonencode"
445
+ ? value.value
446
+ : value;
447
+ while (isObject(raw) && "value" in raw && Object.keys(raw).length === 1)
448
+ raw = raw.value;
449
+ if (!isObject(raw) || !isObject(raw.triggerReference))
450
+ return undefined;
451
+ return typeof raw.triggerReference.name === "string" ? raw.triggerReference.name : undefined;
452
+ }
383
453
  // Fixed, well-known ref keys ONLY - keys derived from a field's display name
384
454
  // plus a suffix (e.g. "Created By" + " Email" -> "Created By Email") must NOT
385
455
  // be added here. A hardcoded flat entry here short-circuits triggerRefPath's
@@ -717,6 +787,17 @@ const TASK_OUTPUT_LABEL_TO_TS = {
717
787
  "All found users": ["users"],
718
788
  },
719
789
  };
790
+ /**
791
+ * A record attachment reads Find Related Records' whole record through
792
+ * `refs["First found record"]` (build: ATTACHMENT_WHOLE_RECORD_REF_WIRE_NAMES,
793
+ * #3069). Elsewhere that key has no authoring path, so only an attachment's
794
+ * `record` prints it as `.record`.
795
+ */
796
+ function attachmentWholeRecordPath(decoded) {
797
+ if (!isObject(decoded) || decoded.kind !== "taskRef" || !Array.isArray(decoded.path))
798
+ return decoded;
799
+ return decoded.path.length === 1 && decoded.path[0] === "First found record" ? { ...decoded, path: ["record"] } : decoded;
800
+ }
720
801
  // userGroupSearch refs-map keys → authoring path; inverse of build.ts's
721
802
  // USER_GROUP_SEARCH_REF_WIRE_NAMES. "ID"/"Name" are only these outputs on
722
803
  // elementum_user_group_search_task, so the table must stay scoped to it.
@@ -1145,6 +1226,7 @@ function decodeStringifiedValueReference(value, ctx, diagnostics, where, fieldAs
1145
1226
  if (reference.kind === "taskRef" && reference.undeclaredScriptOutput === true) {
1146
1227
  recordUndeclaredScriptOutputFieldRead(reference, ctx);
1147
1228
  }
1229
+ noteTriggerReferenceSpelling(envelopeTriggerReferenceName(parsed), reference, ctx);
1148
1230
  parts.push(reference);
1149
1231
  }
1150
1232
  cursor = end;
@@ -1296,7 +1378,7 @@ function shadowedOnDemandParamFromEnvelope(value, ctx) {
1296
1378
  : undefined;
1297
1379
  if (!isObject(parameter) || parameter.type === "record" || parameter.type === "user")
1298
1380
  return undefined;
1299
- return declared;
1381
+ return { declared, wireName };
1300
1382
  }
1301
1383
  /** decodeValue, upgrading a stringified ValueReference envelope (edk#1646). */
1302
1384
  function decodeValueOrStringifiedRef(value, ctx, diagnostics, where, fieldAssignment) {
@@ -1607,13 +1689,56 @@ function resolveFieldKeyFromId(fieldId, ownerRefName, ctx) {
1607
1689
  const expectedOwner = ownerRefName ?? ctx.appRefName;
1608
1690
  return state.ownerRefName === expectedOwner ? state.fieldKey : undefined;
1609
1691
  }
1610
- function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
1692
+ const CALCULATION_OUTPUT_MAP = "calculationOutputMap";
1693
+ /**
1694
+ * A Calculation task's output reference names a calculation the task doesn't have (deleted after the reference
1695
+ * was made). Build would index `refs` by a key the provider doesn't publish, so plan fails with "Invalid index";
1696
+ * the automation is left out instead (#3085).
1697
+ */
1698
+ export class UnresolvedCalculationOutputError extends EntityTfError {
1699
+ constructor(taskName, reference) {
1700
+ super(`calculation task "${taskName}" has no calculation that its output reference "${reference}" names ` +
1701
+ "(a calculation deleted after the reference was made); fix the reference in the platform");
1702
+ this.name = "UnresolvedCalculationOutputError";
1703
+ }
1704
+ }
1705
+ /**
1706
+ * The variable name of the calculation that a `calculationOutputMap.<id>` reference, or the legacy by-name
1707
+ * `calculationOutputMap.<variable name>` one, names: the task's `refs` key for that output (#3085). Mobius
1708
+ * offers only those two names for a calculation's result (`TaskValueReferenceUtil.collectCalculationTaskOutput`).
1709
+ * Undefined for any other path; throws when the path names no calculation of the task.
1710
+ */
1711
+ function calculationVariableForOutputKey(block, pathSegments) {
1712
+ if (pathSegments.length !== 2 || pathSegments[0] !== CALCULATION_OUTPUT_MAP)
1713
+ return undefined;
1714
+ const key = pathSegments[1];
1715
+ const calculations = block.attrs["calculations"];
1716
+ const entries = (Array.isArray(calculations) ? calculations : []).filter(isObject);
1717
+ const variable = (entry) => typeof entry["variable_name"] === "string" && entry["variable_name"] !== "" ? entry["variable_name"] : undefined;
1718
+ const named = entries.find((entry) => entry["id"] === key) ?? entries.find((entry) => variable(entry) === key);
1719
+ const found = named === undefined ? undefined : variable(named);
1720
+ if (found !== undefined)
1721
+ return found;
1722
+ const taskName = typeof block.attrs["name"] === "string" ? block.attrs["name"] : block.label ?? "?";
1723
+ throw new UnresolvedCalculationOutputError(taskName, pathSegments.join("."));
1724
+ }
1725
+ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx, spelling = "stored-name") {
1611
1726
  const { refKey, block } = resolveTaskRefKey(taskIdOrKey, ctx);
1612
1727
  if (block !== undefined) {
1613
1728
  const aiAgentPath = aiAgentTaskRefPath(block, pathSegments.join("."));
1614
1729
  if (aiAgentPath !== undefined)
1615
1730
  return { kind: "taskRef", task: refKey, path: aiAgentPath };
1616
1731
  }
1732
+ // A Calculation's output is stored as `calculationOutputMap.<calculation id>`,
1733
+ // while the task's refs (and EDK's accessor) name it by its variable name
1734
+ // (#3085). Only where build writes a refs index: where it writes the stored
1735
+ // name back (a filter value's short form, a formula), the platform accepts
1736
+ // only `calculationOutputMap.<id|name>`, so the raw path stays.
1737
+ const calculationVariable = block?.type === "elementum_calculation_task" && spelling === "refs-key"
1738
+ ? calculationVariableForOutputKey(block, pathSegments)
1739
+ : undefined;
1740
+ if (calculationVariable !== undefined)
1741
+ return { kind: "taskRef", task: refKey, path: [calculationVariable] };
1617
1742
  // A task's own record output can be addressed by an unresolved field UUID
1618
1743
  // (`record.<field-uuid>[.suffix]`) the same way a recordSearch task's
1619
1744
  // found-record fields already are below - an updateField task's "record"
@@ -1753,7 +1878,7 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
1753
1878
  function slackTriggerPath(path, ctx) {
1754
1879
  return ctx.trigger.type === "elementum_slack_message_trigger" ? slackMessageTriggerPathFromWire(path) : undefined;
1755
1880
  }
1756
- function decodeReferenceString(value, ctx) {
1881
+ function decodeReferenceString(value, ctx, spelling = "stored-name") {
1757
1882
  const pieces = value.split(".");
1758
1883
  if (pieces[0] === "trigger" && pieces.length > 1) {
1759
1884
  const path = pieces.slice(1);
@@ -1787,7 +1912,7 @@ function decodeReferenceString(value, ctx) {
1787
1912
  return { kind: "triggerRef", path };
1788
1913
  }
1789
1914
  if (pieces[0] === "task" && pieces.length > 2) {
1790
- return decodeTaskReferenceFromString(pieces[1], pieces.slice(2), ctx);
1915
+ return decodeTaskReferenceFromString(pieces[1], pieces.slice(2), ctx, spelling);
1791
1916
  }
1792
1917
  if (pieces[0] === "for_each" && pieces.length > 2) {
1793
1918
  const { refKey, block } = resolveTaskRefKey(pieces[1], ctx);
@@ -1860,7 +1985,7 @@ function decodeTemplateTriggerRecordFieldRef(value, ctx) {
1860
1985
  * `"task." + <task.id> + ".<wireName>"` templates so provider Read's plain
1861
1986
  * `task.<uuid>.<wireName>` strings round-trip without perpetual plan drift.
1862
1987
  */
1863
- function decodeTemplateTaskRef(value, ctx) {
1988
+ function decodeTemplateTaskRef(value, ctx, spelling = "stored-name") {
1864
1989
  if (!isTfExpr(value) || value.$expr !== "template")
1865
1990
  return undefined;
1866
1991
  const [prefix, idPart, ...nameTemplate] = mergeAdjacentTemplateStrings(value.parts);
@@ -1881,7 +2006,7 @@ function decodeTemplateTaskRef(value, ctx) {
1881
2006
  const nameParts = suffixPart.slice(1).split(".").filter((segment) => segment.length > 0);
1882
2007
  if (nameParts.length === 0)
1883
2008
  return undefined;
1884
- return decodeTaskReferenceFromString(task.refKey, nameParts, ctx);
2009
+ return decodeTaskReferenceFromString(task.refKey, nameParts, ctx, spelling);
1885
2010
  }
1886
2011
  function mergeAdjacentTemplateStrings(parts) {
1887
2012
  const out = [];
@@ -2012,7 +2137,7 @@ function fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx) {
2012
2137
  ? index.index
2013
2138
  : undefined;
2014
2139
  if (name !== undefined) {
2015
- return tfLabelToTsLabel(sanitizeName(name));
2140
+ return tableColumnKeyIn(fieldPart, name, ctx);
2016
2141
  }
2017
2142
  }
2018
2143
  return undefined;
@@ -2035,13 +2160,85 @@ function resolveConnectorRef(connectorType, connectorLabel, ctx) {
2035
2160
  });
2036
2161
  return { handle: identity.handle, ...(identity.providerKey !== undefined && { providerKey: identity.providerKey }) };
2037
2162
  }
2163
+ /**
2164
+ * Another app's or element's automation that an export names through
2165
+ * `data.elementum_automation.<label>` (`app_id` = the owner's data lookup,
2166
+ * `name` = the automation's display name): its owner's catalog handle, its
2167
+ * catalog key, its display name, and whether the owner is an app or element
2168
+ * in this workspace (`mapped`; otherwise the handle comes from the owner
2169
+ * lookup's label). Shared by the decoder and by extraction's check for a
2170
+ * target the owner's source leaves out (#3064).
2171
+ */
2172
+ export function foreignAutomationTarget(label, dataBlocks, foreignAppRefNames, foreignElementRefNames) {
2173
+ const lookup = dataBlocks.get(`${AUTOMATION_RESOURCE_TYPE}.${label}`);
2174
+ const ownerId = lookup?.attrs["app_id"];
2175
+ if (ownerId === undefined ||
2176
+ !isTfExpr(ownerId) ||
2177
+ ownerId.$expr !== "data-attr" ||
2178
+ (ownerId.type !== "elementum_app" && ownerId.type !== "elementum_element") ||
2179
+ ownerId.path[0] !== "id") {
2180
+ throw new EntityTfError(`data.${AUTOMATION_RESOURCE_TYPE}.${label}: app_id is not a resolvable app/element data reference`);
2181
+ }
2182
+ const ownerLookup = dataBlocks.get(`${ownerId.type}.${ownerId.label}`);
2183
+ const ownerIdentity = ownerLookup?.attrs.namespace ?? ownerLookup?.attrs.name;
2184
+ const mappedHandle = typeof ownerIdentity === "string"
2185
+ ? (ownerId.type === "elementum_element" ? foreignElementRefNames : foreignAppRefNames)?.get(ownerIdentity)
2186
+ : undefined;
2187
+ const prefix = `${ownerId.label}_`;
2188
+ const name = lookup?.attrs["name"];
2189
+ return {
2190
+ appHandle: mappedHandle ?? tfLabelToTsLabel(ownerId.label),
2191
+ automationKey: tfLabelToTsLabel(label.startsWith(prefix) ? label.slice(prefix.length) : label),
2192
+ ...(typeof name === "string" && name !== "" && { name }),
2193
+ ownerKind: ownerId.type === "elementum_element" ? "element" : "app",
2194
+ mapped: mappedHandle !== undefined,
2195
+ };
2196
+ }
2197
+ const tableColumnKeysByDocument = new WeakMap();
2198
+ /**
2199
+ * Display name → catalog key of every column of each table the export names,
2200
+ * by `data.<label>` (a lookup, whose columns the ref-only catalog local lists)
2201
+ * or `resource.<label>` (a managed table, whose `fields` list them). Keyed by
2202
+ * `tableColumnKeysByName`, as the table's own source and its ref-only catalog
2203
+ * are, so "DOMAIN" and "Domain" keep two keys (#3167). One pass per export:
2204
+ * every automation of a stream decodes against the same document.
2205
+ */
2206
+ function tableColumnKeysInDocument(doc) {
2207
+ const cached = tableColumnKeysByDocument.get(doc);
2208
+ if (cached !== undefined)
2209
+ return cached;
2210
+ const keys = new Map();
2211
+ let namesByTableName;
2212
+ for (const block of doc.blocks) {
2213
+ if (block.type !== TABLE_RESOURCE_TYPE || block.label === undefined)
2214
+ continue;
2215
+ if (block.kind === "data" && typeof block.attrs.name === "string") {
2216
+ namesByTableName ??= new Map(readRefOnlyMetadata(doc).roots
2217
+ .filter((root) => root.kind === "table")
2218
+ .map((root) => [root.name, root.columns.map((column) => column.name)]));
2219
+ const names = namesByTableName.get(block.attrs.name);
2220
+ if (names !== undefined)
2221
+ keys.set(`data.${block.label}`, tableColumnKeysByName(names));
2222
+ }
2223
+ else if (block.kind === "resource" && Array.isArray(block.attrs.fields)) {
2224
+ keys.set(`resource.${block.label}`, tableColumnKeysByName(block.attrs.fields.flatMap((field) => isObject(field) && typeof field.name === "string" ? [field.name] : [])));
2225
+ }
2226
+ }
2227
+ tableColumnKeysByDocument.set(doc, keys);
2228
+ return keys;
2229
+ }
2230
+ /** The catalog key of column `name` of the table `value` reads (`field_ids[...]` on a lookup or managed table). */
2231
+ function tableColumnKeyIn(value, name, ctx) {
2232
+ const table = ctx.tableColumnKeys?.get(`${value.$expr === "data-attr" ? "data" : "resource"}.${value.label}`);
2233
+ return table?.get(name) ?? tableColumnKey(name);
2234
+ }
2038
2235
  /**
2039
2236
  * `field_ids["Display Name"]` on either the managed table resource or its
2040
- * `data` lookup. The bag key is derived the same way `table/from-tf.ts` derives
2041
- * it for an out-of-stream table, so the printed token lines up with the key the
2042
- * table's own catalog publishes.
2237
+ * `data` lookup. The bag key is the one the table's own pulled source and its
2238
+ * ref-only catalog both give the column (#3063, #3167).
2043
2239
  */
2044
- function tableColumnRefFromPath(label, path, tableName) {
2240
+ function tableColumnRefFromPath(value, tableName, ctx) {
2241
+ const { label, path } = value;
2045
2242
  const index = path[1];
2046
2243
  const name = typeof index === "string"
2047
2244
  ? index
@@ -2053,7 +2250,7 @@ function tableColumnRefFromPath(label, path, tableName) {
2053
2250
  return {
2054
2251
  kind: "tableColumn",
2055
2252
  tableHandle: tfLabelToTsLabel(label),
2056
- columnKey: tfLabelToTsLabel(sanitizeName(name)),
2253
+ columnKey: tableColumnKeyIn(value, name, ctx),
2057
2254
  name,
2058
2255
  ...(tableName !== undefined ? { tableName } : {}),
2059
2256
  };
@@ -2088,6 +2285,20 @@ function resolveSearchTableFromBlock(block, searchTableLabel, ctx) {
2088
2285
  }
2089
2286
  return undefined;
2090
2287
  }
2288
+ /**
2289
+ * The display name of the element a search-table lookup's `object_id` names:
2290
+ * the key a pulled search table's catalog identity is remembered under
2291
+ * (`[element name, lookup name]`), as for an agent or skill tool's target.
2292
+ */
2293
+ function elementDisplayName(objectId, elementHandle, ctx) {
2294
+ if (isTfExpr(objectId) && objectId.$expr === "data-attr" && objectId.type === "elementum_element") {
2295
+ const name = ctx.dataBlocks.get(`${objectId.type}.${objectId.label}`)?.attrs.name;
2296
+ if (typeof name === "string" && name !== "")
2297
+ return name;
2298
+ }
2299
+ // The name map holds each element's name before its namespace.
2300
+ return [...(ctx.foreignElementRefNames?.entries() ?? [])].find(([, refName]) => refName === elementHandle)?.[0];
2301
+ }
2091
2302
  function decodeSearchTableReference(value, ctx) {
2092
2303
  if (isTfExpr(value) && value.$expr === "data-attr" && value.type === "elementum_search_table") {
2093
2304
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
@@ -2113,8 +2324,21 @@ function decodeSearchTableReference(value, ctx) {
2113
2324
  ? aspectOwnerRefNameFromObjectId(objectId, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames)
2114
2325
  : undefined;
2115
2326
  if (elementHandle !== undefined && name !== undefined) {
2116
- const tableKey = tfLabelToTsLabel(sanitizeName(name));
2117
- return { kind: "searchTable", appHandle: elementHandle, tableKey };
2327
+ // The lookup name is not the catalog key: an unnamed table looks up by
2328
+ // the platform's display name ("Search Table") while the element's
2329
+ // catalog keys it by its export key (edk#2880). The printer maps
2330
+ // [element name, lookup name] to the key, as the agent and skill tool
2331
+ // printers do; a pinned id keeps the table when the name is shared (edk#3228).
2332
+ const parentName = elementDisplayName(objectId, elementHandle, ctx);
2333
+ return {
2334
+ kind: "searchTable",
2335
+ appHandle: elementHandle,
2336
+ tableKey: tfLabelToTsLabel(sanitizeName(name)),
2337
+ name,
2338
+ ...(parentName !== undefined ? { parentName } : {}),
2339
+ ...(pinnedId !== undefined ? { id: pinnedId } : {}),
2340
+ ownerKind: "element",
2341
+ };
2118
2342
  }
2119
2343
  return { kind: "unresolved", uuid: `data.${value.type}.${value.label}`, hint: "search table" };
2120
2344
  }
@@ -2164,8 +2388,11 @@ function decodeValue(value, ctx) {
2164
2388
  return { kind: "triggerRef", path: ["attachment", payloadKey] };
2165
2389
  }
2166
2390
  const shadowedParam = shadowedOnDemandParamFromEnvelope(value, ctx);
2167
- if (shadowedParam !== undefined)
2168
- return { kind: "triggerRef", path: [shadowedParam] };
2391
+ if (shadowedParam !== undefined) {
2392
+ const reference = { kind: "triggerRef", path: [shadowedParam.declared] };
2393
+ noteTriggerReferenceSpelling(shadowedParam.wireName, reference, ctx);
2394
+ return reference;
2395
+ }
2169
2396
  if (isTfExpr(value)) {
2170
2397
  if (value.$expr === "template") {
2171
2398
  return { kind: "template", parts: value.parts.map((part) => typeof part === "string" ? part : decodeValue(part, ctx)) };
@@ -2321,7 +2548,7 @@ function decodeValue(value, ctx) {
2321
2548
  return { kind: "table", tableHandle: tfLabelToTsLabel(value.label) };
2322
2549
  }
2323
2550
  if (value.type === TABLE_RESOURCE_TYPE && value.path[0] === "field_ids") {
2324
- return tableColumnRefFromPath(value.label, value.path, undefined);
2551
+ return tableColumnRefFromPath(value, undefined, ctx);
2325
2552
  }
2326
2553
  if (value.type === "elementum_datamine" && value.path[0] === "id") {
2327
2554
  const datamineBlock = ctx.resourceBlocks.get(`elementum_datamine.${value.label}`);
@@ -2386,7 +2613,7 @@ function decodeValue(value, ctx) {
2386
2613
  if (value.$expr === "data-attr" && value.type === TABLE_RESOURCE_TYPE && value.path[0] === "field_ids") {
2387
2614
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
2388
2615
  const tableName = lookup?.attrs.name;
2389
- return tableColumnRefFromPath(value.label, value.path, typeof tableName === "string" ? tableName : undefined);
2616
+ return tableColumnRefFromPath(value, typeof tableName === "string" ? tableName : undefined, ctx);
2390
2617
  }
2391
2618
  if (value.$expr === "data-attr" && value.type === "elementum_datamine" && value.path[0] === "id") {
2392
2619
  const datamineLookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
@@ -2424,28 +2651,16 @@ function decodeValue(value, ctx) {
2424
2651
  };
2425
2652
  }
2426
2653
  if (value.$expr === "data-attr" && value.type === AUTOMATION_RESOURCE_TYPE && value.path[0] === "id") {
2427
- const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
2428
- const ownerId = lookup?.attrs["app_id"];
2429
- if (ownerId === undefined ||
2430
- !isTfExpr(ownerId) ||
2431
- ownerId.$expr !== "data-attr" ||
2432
- (ownerId.type !== "elementum_app" && ownerId.type !== "elementum_element") ||
2433
- ownerId.path[0] !== "id") {
2434
- throw new EntityTfError(`data.${AUTOMATION_RESOURCE_TYPE}.${value.label}: app_id is not a resolvable app/element data reference`);
2435
- }
2436
- const ownerLookup = ctx.dataBlocks.get(`${ownerId.type}.${ownerId.label}`);
2437
- const ownerIdentity = ownerLookup?.attrs.namespace ?? ownerLookup?.attrs.name;
2438
- const mappedHandle = typeof ownerIdentity === "string"
2439
- ? (ownerId.type === "elementum_element" ? ctx.foreignElementRefNames : ctx.foreignAppRefNames)?.get(ownerIdentity)
2440
- : undefined;
2441
- const prefix = `${ownerId.label}_`;
2442
- return {
2443
- kind: "automation",
2444
- appHandle: mappedHandle ?? tfLabelToTsLabel(ownerId.label),
2445
- automationKey: tfLabelToTsLabel(value.label.startsWith(prefix) ? value.label.slice(prefix.length) : value.label),
2446
- };
2654
+ const target = foreignAutomationTarget(value.label, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames);
2655
+ return { kind: "automation", appHandle: target.appHandle, automationKey: target.automationKey };
2447
2656
  }
2448
2657
  if (value.$expr === "data-attr" && value.type === "elementum_field" && value.path[0] === "id") {
2658
+ // A field a ref-only catalog names resolves to that catalog's field,
2659
+ // as `fieldRef` does: a sort or field value on it must match the
2660
+ // filter on the same lookup (edk#3157).
2661
+ const refOnly = refOnlyFieldRef(value, ctx);
2662
+ if (refOnly !== undefined)
2663
+ return refOnly;
2449
2664
  // The reverse of to-tf.ts's `crossAppFieldToTf`: a field belonging to a
2450
2665
  // DIFFERENT app/element than this automation's own — resolved via the
2451
2666
  // field's own `data.elementum_field` block, whose `object_id` names
@@ -2681,30 +2896,42 @@ function managedFieldKeyForDisplayName(foreign, ctx) {
2681
2896
  }
2682
2897
  return keys.size === 1 ? keys.values().next().value : undefined;
2683
2898
  }
2899
+ /**
2900
+ * A `data.elementum_field` lookup the export also lists in a ref-only
2901
+ * catalog: the field that catalog names (a renamed system field keeps its
2902
+ * system key, `Created on` → `createdAt`). Every decoder of a foreign field
2903
+ * goes through this first, so a filter, a sort and a field mapping on the
2904
+ * same lookup print the same catalog field (edk#3157).
2905
+ */
2906
+ function refOnlyFieldRef(value, ctx) {
2907
+ if (!isTfExpr(value) || value.$expr !== "data-attr" || value.path.join(".") !== "id")
2908
+ return undefined;
2909
+ const foreign = ctx.foreignFieldRefsByDataAddress?.get(`${value.type}.${value.label}`);
2910
+ if (foreign === undefined)
2911
+ return undefined;
2912
+ const fieldKey = managedFieldKeyForDisplayName(foreign, ctx) ?? foreign.fieldKey;
2913
+ return {
2914
+ kind: "field",
2915
+ appHandle: foreign.ownerRefName,
2916
+ fieldKey,
2917
+ ...(foreign.ownerKind !== undefined || foreign.fieldName !== undefined || foreign.fieldType !== undefined
2918
+ ? {
2919
+ foreign: {
2920
+ entityType: foreign.ownerKind ?? "app",
2921
+ ...(foreign.ownerKind === undefined ? { ownerKindUnknown: true } : {}),
2922
+ name: foreign.ownerName ?? foreign.ownerRefName,
2923
+ ...(foreign.ownerNamespace !== undefined ? { namespace: foreign.ownerNamespace } : {}),
2924
+ ...(foreign.fieldName !== undefined ? { fieldName: foreign.fieldName } : {}),
2925
+ ...(foreign.fieldType !== undefined ? { fieldType: foreign.fieldType } : {}),
2926
+ },
2927
+ }
2928
+ : {}),
2929
+ };
2930
+ }
2684
2931
  function fieldRef(value, ctx) {
2685
- if (isTfExpr(value) && value.$expr === "data-attr" && value.path.join(".") === "id") {
2686
- const foreign = ctx.foreignFieldRefsByDataAddress?.get(`${value.type}.${value.label}`);
2687
- if (foreign !== undefined) {
2688
- const fieldKey = managedFieldKeyForDisplayName(foreign, ctx) ?? foreign.fieldKey;
2689
- return {
2690
- kind: "field",
2691
- appHandle: foreign.ownerRefName,
2692
- fieldKey,
2693
- ...(foreign.ownerKind !== undefined || foreign.fieldName !== undefined || foreign.fieldType !== undefined
2694
- ? {
2695
- foreign: {
2696
- entityType: foreign.ownerKind ?? "app",
2697
- ...(foreign.ownerKind === undefined ? { ownerKindUnknown: true } : {}),
2698
- name: foreign.ownerName ?? foreign.ownerRefName,
2699
- ...(foreign.ownerNamespace !== undefined ? { namespace: foreign.ownerNamespace } : {}),
2700
- ...(foreign.fieldName !== undefined ? { fieldName: foreign.fieldName } : {}),
2701
- ...(foreign.fieldType !== undefined ? { fieldType: foreign.fieldType } : {}),
2702
- },
2703
- }
2704
- : {}),
2705
- };
2706
- }
2707
- }
2932
+ const refOnly = refOnlyFieldRef(value, ctx);
2933
+ if (refOnly !== undefined)
2934
+ return refOnly;
2708
2935
  const decoded = decodeValue(value, ctx);
2709
2936
  if (isObject(decoded) && decoded.kind === "field")
2710
2937
  return decoded;
@@ -2747,7 +2974,7 @@ function filterFieldRef(value, ctx) {
2747
2974
  const tableName = value.$expr === "data-attr"
2748
2975
  ? ctx.dataBlocks.get(`${value.type}.${value.label}`)?.attrs.name
2749
2976
  : undefined;
2750
- return tableColumnRefFromPath(value.label, value.path, typeof tableName === "string" ? tableName : undefined);
2977
+ return tableColumnRefFromPath(value, typeof tableName === "string" ? tableName : undefined, ctx);
2751
2978
  }
2752
2979
  return fieldRef(value, ctx);
2753
2980
  }
@@ -3141,6 +3368,8 @@ function stageFilterName(value, ctx) {
3141
3368
  * Recognized shapes:
3142
3369
  * - `{{trigger name="record.<field-uuid>"}}`
3143
3370
  * - `{{task name="<wire output>" id="<task-uuid>"}}`
3371
+ * - `{{forEach name="<field-uuid or item key>" id="<loop-task-uuid>"}}`
3372
+ * (a loop's current item, edk#3131)
3144
3373
  * - `variable.<variable-uuid>` (calc-engine short form)
3145
3374
  */
3146
3375
  function decodeCalculationFormula(value, ctx) {
@@ -3148,7 +3377,7 @@ function decodeCalculationFormula(value, ctx) {
3148
3377
  return decodeValue(value, ctx);
3149
3378
  const parts = [];
3150
3379
  let cursor = 0;
3151
- const pattern = /\{\{(trigger|task)\s+([^}]*)\}\}|variable\.([a-f0-9-]{36})/g;
3380
+ const pattern = /\{\{(trigger|task|forEach)\s+([^}]*)\}\}|variable\.([a-f0-9-]{36})/g;
3152
3381
  while (cursor < value.length) {
3153
3382
  pattern.lastIndex = cursor;
3154
3383
  const match = pattern.exec(value);
@@ -3178,6 +3407,11 @@ function decodeCalculationFormula(value, ctx) {
3178
3407
  const decoded = name !== undefined ? decodeReferenceString(`trigger.${name}`, ctx) : undefined;
3179
3408
  parts.push(decoded ?? { kind: "unresolved", uuid: name ?? match[0], hint: "calculation-reference" });
3180
3409
  }
3410
+ else if (kind === "forEach") {
3411
+ const name = /name="([^"]*)"/.exec(attrs)?.[1];
3412
+ const id = /id="([^"]*)"/.exec(attrs)?.[1];
3413
+ parts.push(decodeCalculationForEachMustache(id, name, match[0], ctx));
3414
+ }
3181
3415
  else {
3182
3416
  const name = /name="([^"]*)"/.exec(attrs)?.[1];
3183
3417
  const id = /id="([^"]*)"/.exec(attrs)?.[1];
@@ -3244,6 +3478,22 @@ function nextCalculationJsonReference(value, fromIndex, ctx) {
3244
3478
  }
3245
3479
  return undefined;
3246
3480
  }
3481
+ /**
3482
+ * A loop's current item in a calculation, `{{forEach name="<name>"
3483
+ * id="<loop-task-uuid>"}}`: the same item path a filter's
3484
+ * `for_each.<loop>.<name>` decodes to (a record loop's field id becomes its
3485
+ * field key), printed as `ctx.item.<field>` or `ctx.loops.<loop>.item.<field>`
3486
+ * (edk#3131). A loop this stream doesn't hold stays unresolved.
3487
+ */
3488
+ function decodeCalculationForEachMustache(loopId, name, text, ctx) {
3489
+ if (loopId === undefined || name === undefined || name === "") {
3490
+ return { kind: "unresolved", uuid: text, hint: "calculation-reference" };
3491
+ }
3492
+ const { refKey, block } = resolveTaskRefKey(loopId, ctx);
3493
+ if (block === undefined)
3494
+ return { kind: "unresolved", uuid: text, hint: "calculation-reference" };
3495
+ return { kind: "forEachItemRef", forEachTask: refKey, path: forEachItemRefPath(name.split("."), ctx, block) };
3496
+ }
3247
3497
  function decodeCalculationTaskMustache(taskId, wireName, ctx) {
3248
3498
  if (taskId === undefined || wireName === undefined) {
3249
3499
  return { kind: "unresolved", uuid: `task:${taskId ?? "?"}:${wireName ?? "?"}`, hint: "calculation-reference" };
@@ -3410,7 +3660,9 @@ function decodeFilterReferenceEnvelope(value, ctx, outputName, role) {
3410
3660
  if (isObject(taskRef) && typeof taskRef.name === "string") {
3411
3661
  const taskIdOrKey = workflowOutputTaskIdOrKey(taskRef.taskId, ctx);
3412
3662
  if (taskIdOrKey !== undefined) {
3413
- const decoded = decodeTaskReferenceFromString(taskIdOrKey, taskRef.name.split("."), ctx);
3663
+ // A filter's left value and an envelope inside a text value build as a refs index (#3085).
3664
+ const spelling = role === "left" || role === "envelope" ? "refs-key" : "stored-name";
3665
+ const decoded = decodeTaskReferenceFromString(taskIdOrKey, taskRef.name.split("."), ctx, spelling);
3414
3666
  const task = resolveTaskRefKey(taskIdOrKey, ctx).block;
3415
3667
  if (decoded.kind === "taskRef" && task?.type === "elementum_execute_script_task") {
3416
3668
  const schemaValue = task.attrs.output_schema;
@@ -3486,13 +3738,22 @@ function workflowOutputTaskIdOrKey(taskId, ctx) {
3486
3738
  }
3487
3739
  function filterReference(value, ctx, role) {
3488
3740
  assertFilterTaskRefResolves(filterReferenceTaskId(value), ctx);
3489
- return markUndeclaredScriptOutput(typeof value === "string"
3490
- ? decodeReferenceString(value, ctx) ?? { kind: "unresolved", uuid: value, hint: "filter-reference" }
3491
- : decodeFilterReferenceEnvelope(value, ctx, undefined, role)
3492
- ?? decodeTemplateTriggerRecordFieldRef(value, ctx)
3493
- ?? decodeTemplateTaskRef(value, ctx)
3494
- ?? decodeTemplateForEachRef(value, ctx)
3495
- ?? decodeValue(value, ctx), ctx);
3741
+ // Build writes a left value's task output as a refs index, a value's as its stored name (#3085).
3742
+ const spelling = role === "left" ? "refs-key" : "stored-name";
3743
+ if (typeof value === "string") {
3744
+ const decoded = decodeReferenceString(value, ctx, spelling) ?? { kind: "unresolved", uuid: value, hint: "filter-reference" };
3745
+ // filter_refs holds `trigger.<normalized name>`, which build writes (#3109).
3746
+ noteTriggerReferenceSpelling(value.startsWith("trigger.") ? value.slice("trigger.".length) : undefined, decoded, ctx);
3747
+ return markUndeclaredScriptOutput(decoded, ctx);
3748
+ }
3749
+ const envelope = decodeFilterReferenceEnvelope(value, ctx, undefined, role);
3750
+ if (envelope !== undefined)
3751
+ noteTriggerReferenceSpelling(envelopeTriggerReferenceName(value), envelope, ctx);
3752
+ return markUndeclaredScriptOutput(envelope
3753
+ ?? decodeTemplateTriggerRecordFieldRef(value, ctx)
3754
+ ?? decodeTemplateTaskRef(value, ctx, spelling)
3755
+ ?? decodeTemplateForEachRef(value, ctx)
3756
+ ?? decodeValue(value, ctx), ctx);
3496
3757
  }
3497
3758
  /**
3498
3759
  * A filter reference to an execute-script output its schema doesn't declare
@@ -3903,7 +4164,12 @@ function triggerFromBlock(block, ctx, diagnostics) {
3903
4164
  }
3904
4165
  function taskArgs(block, factory, ctx, taskDiagnostics) {
3905
4166
  const args = {};
4167
+ // Each attribute is a repair site labelled by its name (#3109); the caller restores the task's site.
4168
+ const taskSite = ctx.triggerReferenceRepairs?.site;
3906
4169
  for (const [attr, value] of Object.entries(block.attrs)) {
4170
+ if (ctx.triggerReferenceRepairs !== undefined) {
4171
+ ctx.triggerReferenceRepairs.site = taskSite === undefined ? undefined : { ...taskSite, input: attr };
4172
+ }
3907
4173
  // object_field_ids is build-derived from the target's field order (edk#2280),
3908
4174
  // object_fields / object_system_field_ids from the owner's fields (edk#2680 / #2692),
3909
4175
  // refs_read from the refs keys the automation reads (edk#2648).
@@ -3932,7 +4198,7 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3932
4198
  const fieldKey = field.kind === "field"
3933
4199
  ? field.fieldKey
3934
4200
  : `${UNRESOLVED_FIELD_MARKER}${field.uuid}`;
3935
- const decodedValue = decodeFieldAssignmentValue(item.value, ctx, taskDiagnostics, `${block.type}.${block.label} field ${field.kind === "field" ? field.fieldKey : field.uuid}`);
4201
+ const decodedValue = atRepairSite(ctx, repairInput(ctx, () => `field ${JSON.stringify(field.kind === "field" ? fieldDisplayName(field.fieldKey, ctx) : field.uuid)}`), () => decodeFieldAssignmentValue(item.value, ctx, taskDiagnostics, `${block.type}.${block.label} field ${field.kind === "field" ? field.fieldKey : field.uuid}`));
3936
4202
  const optionValue = assignmentOptionValue(decodedValue, field, { fieldId: item.field_id, value: item.value }, ctx, taskDiagnostics, `${block.type}.${block.label} field ${field.kind === "field" ? field.fieldKey : field.uuid}`);
3937
4203
  const canonicalValue = factory === "createRecord" || factory === "updateField"
3938
4204
  ? canonicalTriggerRecordIdSlot(optionValue, ctx)
@@ -3973,7 +4239,8 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3973
4239
  args.inputs = Object.fromEntries(value.map((item) => {
3974
4240
  if (!isObject(item) || typeof item.name !== "string")
3975
4241
  throw new EntityTfError("invalid script input");
3976
- const decodedValue = decodeValue(item.value, ctx);
4242
+ const inputName = item.name;
4243
+ const decodedValue = atRepairSite(ctx, repairInput(ctx, () => `input ${JSON.stringify(inputName)}`), () => decodeValue(item.value, ctx));
3977
4244
  const rawMappings = item.field_mappings;
3978
4245
  // A list-valued input's field_mappings - which fields of each list
3979
4246
  // item the script can read, and under what alias. Kept as a tagged
@@ -4127,7 +4394,7 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
4127
4394
  `but the task targets ${mismatch.target}; pulled source maps ${JSON.stringify(name)} by name on the target, ` +
4128
4395
  "so build will not reproduce the exported mapping");
4129
4396
  }
4130
- return { name, value: decodeValue(item.value, ctx) };
4397
+ return { name, value: atRepairSite(ctx, repairInput(ctx, () => `input ${JSON.stringify(name)}`), () => decodeValue(item.value, ctx)) };
4131
4398
  }
4132
4399
  // ei emits bare platform parameter UUIDs when the target automation's
4133
4400
  // onDemand trigger is not in this export (foreign / undiscovered).
@@ -4138,7 +4405,7 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
4138
4405
  if (typeof parameter === "string" && parameter !== "") {
4139
4406
  return {
4140
4407
  name: parameter,
4141
- value: decodeValue(item.value, ctx),
4408
+ value: atRepairSite(ctx, repairInput(ctx, () => `input ${JSON.stringify(parameter)}`), () => decodeValue(item.value, ctx)),
4142
4409
  };
4143
4410
  }
4144
4411
  throw new EntityTfError(`${block.type}.${block.label}: input mapping parameter_id is not a named trigger parameter reference`);
@@ -4188,7 +4455,9 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
4188
4455
  if (!isObject(item) || typeof item.variable_name !== "string" || item.formula === undefined) {
4189
4456
  throw new EntityTfError(`${block.type}.${block.label}: invalid calculation entry`);
4190
4457
  }
4191
- const decodedExpression = decodeCalculationFormula(item.formula, ctx);
4458
+ // Build writes a formula's on-demand input as its declared name, so a
4459
+ // formula is no repair site (its record_id still is).
4460
+ const decodedExpression = atRepairSite(ctx, undefined, () => decodeCalculationFormula(item.formula, ctx));
4192
4461
  const expression = isObject(decodedExpression) && decodedExpression.kind === "literal"
4193
4462
  ? pulledRawCalculation(item.formula, item.output_type, item.multiple) ?? decodedExpression
4194
4463
  : decodedExpression;
@@ -4309,6 +4578,41 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
4309
4578
  args.approvers = value.map((item) => decodeValue(item, ctx));
4310
4579
  continue;
4311
4580
  }
4581
+ // A task with a group slot (edk#3163): `{ user = { user_id } }` prints as
4582
+ // the plain user reference, `{ group = { group_id, ... } }` as
4583
+ // `groupApprover(...)`.
4584
+ if (factory === "approvalChain" && attr === "approvers") {
4585
+ if (!Array.isArray(value))
4586
+ throw new EntityTfError(`${block.type}.${block.label}: approvers must be an array`);
4587
+ args.approvers = value.map((entry, index) => {
4588
+ const where = `${block.type}.${block.label}: approvers[${index}]`;
4589
+ if (!isObject(entry))
4590
+ throw new EntityTfError(`${where} must be an object`);
4591
+ if (isObject(entry.group)) {
4592
+ const { group_id: groupId, approvals_required: approvalsRequired, denials_required: denialsRequired } = entry.group;
4593
+ if (groupId === undefined || typeof approvalsRequired !== "number" || typeof denialsRequired !== "number") {
4594
+ throw new EntityTfError(`${where}.group needs group_id, approvals_required and denials_required`);
4595
+ }
4596
+ return { kind: "groupApprover", group: decodeValue(groupId, ctx), approvalsRequired, denialsRequired };
4597
+ }
4598
+ if (isObject(entry.user) && entry.user.user_id !== undefined) {
4599
+ const userId = entry.user.user_id;
4600
+ const fieldType = approverReferenceFieldAuthoringType(userId, ctx);
4601
+ if (fieldType === UNVERIFIABLE_FOREIGN_FIELD_TYPE) {
4602
+ throw new EntityTfError(`${where}.user targets a field on a foreign aspect that has never been pulled locally — its type cannot be ` +
4603
+ "verified against the platform's required USER_ID reference; pull that aspect first (`elementum pull app`/`pull element`), " +
4604
+ "then re-pull this app (edk#768)");
4605
+ }
4606
+ if (fieldType !== undefined && fieldType !== "USER") {
4607
+ throw new EntityTfError(`${where}.user targets a "${fieldType}" field, not a USER field — the platform's approval-chain validation requires a ` +
4608
+ "USER_ID type reference (edk#655)");
4609
+ }
4610
+ return decodeValue(userId, ctx);
4611
+ }
4612
+ throw new EntityTfError(`${where} sets neither user nor group`);
4613
+ });
4614
+ continue;
4615
+ }
4312
4616
  if (attr === "list" && factory === "forEach") {
4313
4617
  args.collection = decodeValueOrStringifiedRef(value, ctx, taskDiagnostics, `${block.type}.${block.label} list`);
4314
4618
  continue;
@@ -4343,7 +4647,8 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
4343
4647
  throw new EntityTfError(`${block.type}.${block.label}: ${kind} must set exactly one of file, attachment, or record`);
4344
4648
  }
4345
4649
  const key = present[0];
4346
- return { [key]: decodeValue(item[key], ctx) };
4650
+ const decoded = decodeValue(item[key], ctx);
4651
+ return { [key]: key === "record" ? attachmentWholeRecordPath(decoded) : decoded };
4347
4652
  });
4348
4653
  continue;
4349
4654
  }
@@ -4626,8 +4931,12 @@ function unmanagedSuccessorPosition(doc, label, ownedAddresses, addressByPlatfor
4626
4931
  return undefined;
4627
4932
  return resolveUnmanagedTaskPosition(dataBlock, ownedAddresses, addressByPlatformId);
4628
4933
  }
4934
+ /** The step's own name for warnings, which its placeholder key may not be. */
4935
+ function placeholderDisplayName(dataBlock, refKey) {
4936
+ return typeof dataBlock.attrs.name === "string" && dataBlock.attrs.name !== "" ? dataBlock.attrs.name : refKey;
4937
+ }
4629
4938
  /** Puts every earlier unsupported step of a run into the same tree as the one a managed task parents onto. */
4630
- function rememberUnmanagedPredecessors(doc, label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen) {
4939
+ function rememberUnmanagedPredecessors(doc, label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen, placeholderKey) {
4631
4940
  const predecessor = unmanagedTaskRef(documentLocals(doc)[`${UNMANAGED_PREDECESSOR_LOCAL_PREFIX}${label}`]);
4632
4941
  if (predecessor === undefined || seen.has(predecessor.label))
4633
4942
  return;
@@ -4639,16 +4948,14 @@ function rememberUnmanagedPredecessors(doc, label, ownedAddresses, addressByPlat
4639
4948
  if (dataBlock === undefined || position === undefined)
4640
4949
  return;
4641
4950
  unmanagedTaskPositions.set(address, position);
4642
- const refKey = typeof dataBlock.attrs.name === "string" && dataBlock.attrs.name !== ""
4643
- ? dataBlock.attrs.name
4644
- : tfLabelToTsLabel(dataBlock.label ?? "task");
4951
+ const refKey = placeholderKey(dataBlock);
4645
4952
  taskByAddress.set(address, { block: dataBlock, refKey });
4646
4953
  placeholderTasks.push({
4647
- name: refKey,
4954
+ name: placeholderDisplayName(dataBlock, refKey),
4648
4955
  taskType: typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown",
4649
4956
  });
4650
4957
  }
4651
- rememberUnmanagedPredecessors(doc, predecessor.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen);
4958
+ rememberUnmanagedPredecessors(doc, predecessor.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen, placeholderKey);
4652
4959
  }
4653
4960
  function importPlatformId(doc, type, label) {
4654
4961
  for (const block of doc.blocks) {
@@ -4779,6 +5086,8 @@ function taskRefKey(block, automationLabel, appTfLabel, exportAutoChild) {
4779
5086
  }
4780
5087
  return tfLabelToTsLabel(/^[0-9]/.test(tail) ? `_${tail}` : tail);
4781
5088
  }
5089
+ /** Skill and agent tools that run an automation; they belong to their skill or agent (edk#3151). */
5090
+ const RUN_AUTOMATION_TOOL_TYPES = new Set([SKILL_RUN_AUTOMATION_TOOL_RESOURCE_TYPE, RUN_AUTOMATION_TOOL_RESOURCE_TYPE]);
4782
5091
  /**
4783
5092
  * Best-effort resource footprint of one automation, used ONLY when whole-
4784
5093
  * automation extraction throws (module.ts's `extractAutomations` catch
@@ -4802,6 +5111,14 @@ function taskRefKey(block, automationLabel, appTfLabel, exportAutoChild) {
4802
5111
  export function automationOwnedAddresses(doc, automationLabel) {
4803
5112
  const owned = new Set([`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`]);
4804
5113
  for (const block of doc.blocks) {
5114
+ // A skill or agent tool that runs this automation belongs to its skill or
5115
+ // agent, not to the automation: stream-root leaves it out of that file
5116
+ // when the automation is skipped (requireRunAutomationTarget). Owning it
5117
+ // here skipped it first, so its owner's file kept a dangling catalog ref
5118
+ // whenever the tool named elementum_automation.<x>: a skill tool on an
5119
+ // inactive automation, and every agent tool (edk#3151).
5120
+ if (block.type !== undefined && RUN_AUTOMATION_TOOL_TYPES.has(block.type))
5121
+ continue;
4805
5122
  if (block.kind === "resource" && block.type !== undefined && block.label !== undefined &&
4806
5123
  (references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel) ||
4807
5124
  references(block.attrs.automation_id, AUTOMATION_RESOURCE_TYPE, automationLabel))) {
@@ -5439,6 +5756,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5439
5756
  const undeclaredScriptOutputFieldReads = new Map();
5440
5757
  const groupsMissingFromOrg = new Set();
5441
5758
  const optionIdWarnings = new Set();
5759
+ const triggerReferenceRepairs = { site: undefined, found: [] };
5442
5760
  const ctx = {
5443
5761
  appRefName,
5444
5762
  appTfLabel: app.label,
@@ -5456,6 +5774,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5456
5774
  ...(foreignFieldRefsById !== undefined && { foreignFieldRefsById }),
5457
5775
  ...(foreignFieldRefsByDataAddress !== undefined && { foreignFieldRefsByDataAddress }),
5458
5776
  ...(foreignTableRefsById !== undefined && { foreignTableRefsById }),
5777
+ tableColumnKeys: tableColumnKeysInDocument(doc),
5459
5778
  ...(foreignFileReaderRefsById !== undefined && { foreignFileReaderRefsById }),
5460
5779
  ...(picklistOptionsByField !== undefined && { picklistOptionsByField }),
5461
5780
  ...(fieldNamesByOwnerRefName !== undefined && { fieldNamesByOwnerRefName }),
@@ -5470,6 +5789,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5470
5789
  undeclaredScriptOutputFieldReads,
5471
5790
  groupsMissingFromOrg,
5472
5791
  optionIdWarnings,
5792
+ ...(trigger.type === "elementum_on_demand_trigger" && { triggerReferenceRepairs }),
5473
5793
  ...(resourceImportIds.has(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`) && {
5474
5794
  automationId: resourceImportIds.get(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`),
5475
5795
  }),
@@ -5534,6 +5854,12 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5534
5854
  ]);
5535
5855
  const unmanagedTaskPositions = new Map();
5536
5856
  const placeholderTasks = [];
5857
+ // edk#3133: the export labels a placeholder's data source the way it labels
5858
+ // a task, `<automation>_<step name>` with a `_N` for a repeat, and build
5859
+ // labels it with taskTfLabel, so its refKey comes from the label the same
5860
+ // way a task's does. Same-named steps get distinct keys, and two roots in a
5861
+ // workspace never share a data-source label.
5862
+ const placeholderKey = (dataBlock) => taskRefKey(dataBlock, automationLabel, appTfLabel, exportAutoChild);
5537
5863
  const addressByPlatformId = taskAddressesByPlatformId(doc);
5538
5864
  for (const task of tasks) {
5539
5865
  const unmanagedRef = unmanagedTaskRef(task.attrs.parent);
@@ -5549,13 +5875,37 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5549
5875
  if (dataBlock === undefined || position === undefined)
5550
5876
  continue; // falls back to parentAddress's trigger-anchor + diagnostic
5551
5877
  unmanagedTaskPositions.set(address, position);
5552
- const refKey = typeof dataBlock.attrs.name === "string" && dataBlock.attrs.name !== "" ? dataBlock.attrs.name : tfLabelToTsLabel(dataBlock.label ?? "task");
5878
+ const refKey = placeholderKey(dataBlock);
5553
5879
  taskByAddress.set(address, { block: dataBlock, refKey });
5554
5880
  placeholderTasks.push({
5555
- name: refKey,
5881
+ name: placeholderDisplayName(dataBlock, refKey),
5556
5882
  taskType: typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown",
5557
5883
  });
5558
- rememberUnmanagedPredecessors(doc, unmanagedRef.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, new Set([unmanagedRef.label]));
5884
+ rememberUnmanagedPredecessors(doc, unmanagedRef.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, new Set([unmanagedRef.label]), placeholderKey);
5885
+ }
5886
+ // edk#3133: an unsupported step with no step after it is no task's parent,
5887
+ // so the loop above never reaches it. Its data source names this automation
5888
+ // and its local names the step it comes after, so place it there as well.
5889
+ const unplacedPlaceholders = [];
5890
+ const automationPlatformId = importPlatformId(doc, AUTOMATION_RESOURCE_TYPE, automationLabel);
5891
+ for (const [address, dataBlock] of dataBlocks) {
5892
+ if (dataBlock.type !== UNMANAGED_TASK_REFERENCE_TYPE || dataBlock.label === undefined)
5893
+ continue;
5894
+ if (unmanagedTaskPositions.has(address))
5895
+ continue;
5896
+ if (!unmanagedBelongsToAutomation(doc, dataBlock.label, automationLabel, automationPlatformId))
5897
+ continue;
5898
+ const refKey = placeholderKey(dataBlock);
5899
+ const taskType = typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown";
5900
+ const position = unmanagedSuccessorPosition(doc, dataBlock.label, ownedAddresses, addressByPlatformId);
5901
+ if (position === undefined) {
5902
+ unplacedPlaceholders.push({ name: placeholderDisplayName(dataBlock, refKey), taskType });
5903
+ continue;
5904
+ }
5905
+ unmanagedTaskPositions.set(address, position);
5906
+ taskByAddress.set(address, { block: dataBlock, refKey });
5907
+ placeholderTasks.push({ name: placeholderDisplayName(dataBlock, refKey), taskType });
5908
+ rememberUnmanagedPredecessors(doc, dataBlock.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, new Set([dataBlock.label]), placeholderKey);
5559
5909
  }
5560
5910
  const childrenByParent = new Map();
5561
5911
  for (const task of tasks) {
@@ -5605,7 +5955,11 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5605
5955
  // output terse and matches a freshly-authored default branch.
5606
5956
  ...(shape === "explicitTrueFilter" ? { defaultFilterMode: shape } : {}),
5607
5957
  ...(!isDefault && branch.attrs.filter !== undefined ? {
5608
- 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)),
5958
+ filter: UnresolvedTaskFilterRefError.within(`task ${JSON.stringify(typeof block.attrs.name === "string" ? block.attrs.name : block.label)} (${factory}) branch ${JSON.stringify(rawLabel ?? branch.label)}`, () => atRepairSite(ctx, {
5959
+ task: typeof block.attrs.name === "string" ? block.attrs.name : refKey,
5960
+ address: `${branch.type}.${branch.label}`,
5961
+ input: `${factory === "switchTask" ? "case" : "branch"} ${JSON.stringify(rawLabel ?? branch.label)} condition`,
5962
+ }, () => decodeFilter(branch.attrs.filter, ctx))),
5609
5963
  } : {}),
5610
5964
  tasks: buildTasks(`${branch.type}.${branch.label}`),
5611
5965
  };
@@ -5630,8 +5984,17 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5630
5984
  id: typeof block.attrs.id === "string" ? block.attrs.id : "",
5631
5985
  taskType: typeof block.attrs.task_type === "string" ? block.attrs.task_type : "",
5632
5986
  }
5633
- : taskArgs(block, factory, ctx, taskDiagnostics);
5634
- const call = { factory, refKey, args, ...(children ? { children } : {}), ...(typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {}), ...(hclParent !== undefined ? { hclParent } : {}) };
5987
+ : atRepairSite(ctx, { task: typeof block.attrs.name === "string" ? block.attrs.name : refKey, address, input: "" }, () => taskArgs(block, factory, ctx, taskDiagnostics));
5988
+ // A step with no name on the platform exports without `name` (the provider
5989
+ // reads "" back as null too). Its key comes from ei's fallback label
5990
+ // ("resource"), so carry an explicit null: the printer passes it and build
5991
+ // leaves `name` out instead of naming the step after its key (edk#3191).
5992
+ // An unsupported step is a data lookup whose `name` is always exported.
5993
+ const nameless = factory !== "unimplementedTask" && (block.attrs.name === undefined || block.attrs.name === "");
5994
+ const displayName = nameless
5995
+ ? { displayName: null }
5996
+ : typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {};
5997
+ const call = { factory, refKey, args, ...(children ? { children } : {}), ...displayName, ...(hclParent !== undefined ? { hclParent } : {}) };
5635
5998
  visiting.delete(address);
5636
5999
  return [call, ...buildTasks(address)];
5637
6000
  });
@@ -5645,8 +6008,16 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5645
6008
  throw new EntityTfError("invalid workflow output");
5646
6009
  // Export/provider Read emit jsonencode({fieldType, taskReference, ...});
5647
6010
  // collapse that envelope to a RefExpr the same way filter references do.
5648
- const value = decodeFilterReferenceEnvelope(output.value, ctx, output.name)
5649
- ?? decodeValue(output.value, ctx);
6011
+ const outputName = output.name;
6012
+ const value = atRepairSite(ctx, publish === undefined ? undefined : {
6013
+ address: `${publish.type}.${publish.label}`,
6014
+ input: `output ${JSON.stringify(outputName)}`,
6015
+ }, () => {
6016
+ const envelope = decodeFilterReferenceEnvelope(output.value, ctx, outputName);
6017
+ if (envelope !== undefined)
6018
+ noteTriggerReferenceSpelling(envelopeTriggerReferenceName(output.value), envelope, ctx);
6019
+ return envelope ?? decodeValue(output.value, ctx);
6020
+ });
5650
6021
  const raw = isTfExpr(output.value) && output.value.$expr === "jsonencode"
5651
6022
  ? output.value.value
5652
6023
  : output.value;
@@ -5706,10 +6077,11 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5706
6077
  ast,
5707
6078
  blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])],
5708
6079
  adoptionAddressAliases,
5709
- ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0 || outputDiagnostics.length > 0 || taskDiagnostics.length > 0 || groupsMissingFromOrg.size > 0 || optionIdWarnings.size > 0 || undeclaredScriptOutputFieldReads.size > 0) && {
6080
+ ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0 || unplacedPlaceholders.length > 0 || outputDiagnostics.length > 0 || taskDiagnostics.length > 0 || groupsMissingFromOrg.size > 0 || optionIdWarnings.size > 0 || undeclaredScriptOutputFieldReads.size > 0) && {
5710
6081
  diagnostics: [
5711
6082
  ...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`),
5712
6083
  ...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`),
6084
+ ...unplacedPlaceholders.map(({ name, taskType }) => `automation "${automationLabel}" uses platform task type "${taskType}" ("${name}"), which EDK doesn't implement, and pull couldn't tell where it sits, so this source leaves it out; apply doesn't change or remove it in the platform`),
5713
6085
  ...outputDiagnostics,
5714
6086
  ...taskDiagnostics.map((message) => `automation "${automationLabel}": ${message}`),
5715
6087
  ...[...optionIdWarnings].map((message) => `automation "${automationLabel}": ${message}`),
@@ -5720,6 +6092,17 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5720
6092
  ],
5721
6093
  }),
5722
6094
  ...(stringifiedValueReferences.unresolved ? { stringifiedValueReferences: true } : {}),
6095
+ ...(triggerReferenceRepairs.found.length > 0 && {
6096
+ triggerReferenceRepairs: triggerReferenceRepairs.found.map(({ task, address, input, declared }) => ({
6097
+ automation: typeof automation.attrs.name === "string" ? automation.attrs.name : automationLabel,
6098
+ automationAddress: `${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`,
6099
+ ...(task !== undefined && { task }),
6100
+ address,
6101
+ input,
6102
+ declared,
6103
+ normalized: normalizeOnDemandParamKey(declared),
6104
+ })),
6105
+ }),
5723
6106
  };
5724
6107
  }
5725
6108
  export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth) {