@elementumai/edk 0.13.3 → 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 (140) 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 +13 -0
  7. package/dist-sdk/src/engine/coverage-gaps.js +21 -0
  8. package/dist-sdk/src/engine/pull/context.d.ts +57 -1
  9. package/dist-sdk/src/engine/pull/context.js +9 -1
  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 +17 -1
  15. package/dist-sdk/src/engine/pull/stream-root.js +57 -4
  16. package/dist-sdk/src/engine/tf/index.d.ts +1 -0
  17. package/dist-sdk/src/engine/tf/index.js +1 -0
  18. package/dist-sdk/src/engine/tf/jsonencode.d.ts +19 -0
  19. package/dist-sdk/src/engine/tf/jsonencode.js +49 -0
  20. package/dist-sdk/src/engine/validation.d.ts +36 -1
  21. package/dist-sdk/src/engine/validation.js +56 -2
  22. package/dist-sdk/src/engine/workspace/loader.d.ts +6 -0
  23. package/dist-sdk/src/engine/workspace/loader.js +87 -2
  24. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +7 -0
  25. package/dist-sdk/src/entities/access-policy/from-tf.js +58 -17
  26. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +3 -1
  27. package/dist-sdk/src/entities/access-policy/to-tf.js +1 -1
  28. package/dist-sdk/src/entities/agent/build.d.ts +15 -0
  29. package/dist-sdk/src/entities/agent/build.js +139 -16
  30. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +3 -3
  31. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +39 -25
  32. package/dist-sdk/src/entities/agent/module.js +95 -3
  33. package/dist-sdk/src/entities/agent/to-tf.js +6 -4
  34. package/dist-sdk/src/entities/agent-evaluation/from-tf.d.ts +7 -0
  35. package/dist-sdk/src/entities/agent-evaluation/from-tf.js +14 -5
  36. package/dist-sdk/src/entities/agent-evaluation/module.js +4 -2
  37. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +11 -2
  38. package/dist-sdk/src/entities/agent-tool/from-tf.js +38 -40
  39. package/dist-sdk/src/entities/agent-tool/to-tf.js +12 -5
  40. package/dist-sdk/src/entities/app/build.d.ts +1 -1
  41. package/dist-sdk/src/entities/app/index.d.ts +1 -1
  42. package/dist-sdk/src/entities/automation/approval-trigger-refs.d.ts +20 -0
  43. package/dist-sdk/src/entities/automation/approval-trigger-refs.js +83 -0
  44. package/dist-sdk/src/entities/automation/build.d.ts +75 -42
  45. package/dist-sdk/src/entities/automation/build.js +18 -8
  46. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +14 -2
  47. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +9 -0
  48. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +64 -12
  49. package/dist-sdk/src/entities/automation/from-tf.d.ts +53 -0
  50. package/dist-sdk/src/entities/automation/from-tf.js +579 -106
  51. package/dist-sdk/src/entities/automation/index.d.ts +2 -2
  52. package/dist-sdk/src/entities/automation/index.js +1 -1
  53. package/dist-sdk/src/entities/automation/lookup-owner.d.ts +23 -0
  54. package/dist-sdk/src/entities/automation/lookup-owner.js +27 -0
  55. package/dist-sdk/src/entities/automation/module.js +265 -26
  56. package/dist-sdk/src/entities/automation/operators.d.ts +6 -2
  57. package/dist-sdk/src/entities/automation/operators.js +0 -2
  58. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +8 -0
  59. package/dist-sdk/src/entities/automation/task-output-labels.js +11 -0
  60. package/dist-sdk/src/entities/automation/tasks.d.ts +37 -2
  61. package/dist-sdk/src/entities/automation/tasks.js +38 -1
  62. package/dist-sdk/src/entities/automation/to-tf.d.ts +8 -0
  63. package/dist-sdk/src/entities/automation/to-tf.js +576 -52
  64. package/dist-sdk/src/entities/automation/triggers.d.ts +47 -1
  65. package/dist-sdk/src/entities/automation/unsafe-script-output.d.ts +10 -5
  66. package/dist-sdk/src/entities/automation/unsafe-script-output.js +10 -5
  67. package/dist-sdk/src/entities/chart/to-tf.js +18 -5
  68. package/dist-sdk/src/entities/dashboard/from-tf.js +45 -11
  69. package/dist-sdk/src/entities/dashboard-widget-order/order.d.ts +5 -3
  70. package/dist-sdk/src/entities/dashboard-widget-order/order.js +6 -4
  71. package/dist-sdk/src/entities/datamine/from-tf.js +10 -3
  72. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +38 -11
  73. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +35 -7
  74. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +101 -9
  75. package/dist-sdk/src/entities/element/build.d.ts +4 -1
  76. package/dist-sdk/src/entities/element/build.js +3 -4
  77. package/dist-sdk/src/entities/element/index.d.ts +1 -1
  78. package/dist-sdk/src/entities/field/from-tf.js +8 -1
  79. package/dist-sdk/src/entities/field/to-tf.d.ts +29 -2
  80. package/dist-sdk/src/entities/field/to-tf.js +106 -7
  81. package/dist-sdk/src/entities/phone-service/from-tf.d.ts +7 -0
  82. package/dist-sdk/src/entities/phone-service/from-tf.js +15 -7
  83. package/dist-sdk/src/entities/phone-service/module.js +4 -2
  84. package/dist-sdk/src/entities/portal/to-tf.d.ts +1 -1
  85. package/dist-sdk/src/entities/portal/to-tf.js +61 -2
  86. package/dist-sdk/src/entities/record-create-form/from-tf.js +3 -1
  87. package/dist-sdk/src/entities/relationship/from-tf.js +34 -4
  88. package/dist-sdk/src/entities/relationship/to-tf.js +24 -6
  89. package/dist-sdk/src/entities/role/from-tf.js +3 -1
  90. package/dist-sdk/src/entities/search-table/from-tf.d.ts +3 -1
  91. package/dist-sdk/src/entities/search-table/from-tf.js +6 -3
  92. package/dist-sdk/src/entities/search-table/module.js +18 -2
  93. package/dist-sdk/src/entities/search-table/to-tf.js +10 -16
  94. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +6 -1
  95. package/dist-sdk/src/entities/shared/filters/ast.d.ts +6 -0
  96. package/dist-sdk/src/entities/shared/filters/index.d.ts +21 -4
  97. package/dist-sdk/src/entities/shared/filters/index.js +27 -3
  98. package/dist-sdk/src/entities/shared/filters/print.js +23 -7
  99. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +24 -0
  100. package/dist-sdk/src/entities/shared/filters/tf-codec.js +98 -3
  101. package/dist-sdk/src/entities/shared/filters/types.d.ts +8 -1
  102. package/dist-sdk/src/entities/shared/run-automation-requirement.d.ts +15 -0
  103. package/dist-sdk/src/entities/shared/run-automation-requirement.js +28 -0
  104. package/dist-sdk/src/entities/shared/search-table-address.d.ts +17 -0
  105. package/dist-sdk/src/entities/shared/search-table-address.js +24 -0
  106. package/dist-sdk/src/entities/shared/skip-release.d.ts +49 -0
  107. package/dist-sdk/src/entities/shared/skip-release.js +74 -0
  108. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +3 -3
  109. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +11 -5
  110. package/dist-sdk/src/entities/skill/module.js +3 -25
  111. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +4 -2
  112. package/dist-sdk/src/entities/skill-tool/from-tf.js +28 -27
  113. package/dist-sdk/src/entities/skill-tool/to-tf.js +12 -5
  114. package/dist-sdk/src/entities/skill-tool/types.d.ts +1 -0
  115. package/dist-sdk/src/entities/skill-tool/types.js +2 -1
  116. package/dist-sdk/src/entities/table/catalog.d.ts +16 -0
  117. package/dist-sdk/src/entities/table/catalog.js +44 -2
  118. package/dist-sdk/src/entities/table/from-tf.js +30 -4
  119. package/dist-sdk/src/entities/table/keys.d.ts +27 -0
  120. package/dist-sdk/src/entities/table/keys.js +46 -0
  121. package/dist-sdk/src/entities/table/to-tf.js +2 -2
  122. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +12 -1
  123. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +9 -4
  124. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +215 -10
  125. package/dist-sdk/src/entities/view/agent-view-layout.d.ts +10 -4
  126. package/dist-sdk/src/entities/view/custom-view-runtime-rules.d.ts +43 -0
  127. package/dist-sdk/src/entities/view/custom-view-runtime-rules.js +285 -0
  128. package/dist-sdk/src/entities/view/custom-view-validate.d.ts +3 -1
  129. package/dist-sdk/src/entities/view/custom-view-validate.js +24 -5
  130. package/dist-sdk/src/entities/view/from-tf.js +14 -1
  131. package/dist-sdk/src/entities/widget/from-tf.js +14 -7
  132. package/dist-sdk/src/entities/widget/to-tf.js +9 -6
  133. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +4 -2
  134. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  135. package/dist-sdk/src/graph/index.d.ts +14 -1
  136. package/dist-sdk/src/graph/index.js +2 -0
  137. package/dist-sdk/src/graph/resource-types.d.ts +2 -0
  138. package/dist-sdk/src/graph/resource-types.js +3 -0
  139. package/dist-sdk/src/graph/types.d.ts +105 -0
  140. package/package.json +1 -1
@@ -1,11 +1,13 @@
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";
5
7
  import { EntityTfError } from "../../engine/entity.js";
6
8
  import { dataRefLabel } from "../../engine/pull/context.js";
7
9
  import { procedureDiscriminator } from "../../engine/pull/procedure-refs.js";
8
- import { appResourceLabelPrefix, childPartFromScopedLabel, elementResourceLabelPrefix, isTfExpr, isTfLabel, isUuid, ownerFromScopedChildLabel, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
10
+ import { appResourceLabelPrefix, childPartFromScopedLabel, elementResourceLabelPrefix, isTfExpr, isTfLabel, isUuid, ownerFromScopedChildLabel, renderJsonencode, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
9
11
  import { SUB_TYPE_BY_RESOURCE } from "../field/types.js";
10
12
  import { IMPLEMENTED_FILE_READER_RESOURCE_TYPES } from "../file-reader/types.js";
11
13
  import { connectorIdentityFromTf } from "../shared/connector-from-tf.js";
@@ -22,7 +24,10 @@ import { taskTfLabel } from "./task-label.js";
22
24
  import { parseTriggerAttachmentPayloadRefJson, parseTriggerWholeRecordRefJson, TASK_OUTPUT_REFERENCE_NAMES, TRIGGER_WHOLE_RECORD_REF_NAME } from "./task-output-labels.js";
23
25
  import { workflowOutputTypeFromFieldType } from "./workflow-output.js";
24
26
  import { slackMessageTriggerPathFromWire } from "./slack-message-refs.js";
27
+ import { APPROVAL_TRIGGER_OUTPUT_HEADS, approvalTriggerPathFromRefsKey } from "./approval-trigger-refs.js";
25
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";
26
31
  const TRIGGER_KINDS = {
27
32
  elementum_record_created_trigger: "recordCreate",
28
33
  elementum_record_updated_trigger: "recordUpdate",
@@ -348,7 +353,7 @@ const TASK_ATTRIBUTES = new Set([
348
353
  "parent", "name", "depends_on", "object_field_ids", "object_fields", "object_system_field_ids", "refs_read", "filter", "fields", "inputs", "output_schema",
349
354
  "list", "code", "variables", "updates", "variable", "value",
350
355
  "object_id", "table_id", "record_reference", "record_id", "source_record_ids",
351
- "approval_process_id", "requester_reference", "approver_references", "reason", "summary",
356
+ "approval_process_id", "requester_reference", "approver_references", "approvers", "reason", "summary",
352
357
  "approval_reference", "status",
353
358
  "target_record_id", "message", "message_body", "body", "from_username",
354
359
  "from_personal", "external_emails", "users", "groups", "attachments", "email_attachments",
@@ -379,6 +384,72 @@ const PUBLISH_ATTRIBUTES = new Set([
379
384
  function appRef(appRefName) {
380
385
  return { kind: "app", appHandle: appRefName };
381
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
+ }
382
453
  // Fixed, well-known ref keys ONLY - keys derived from a field's display name
383
454
  // plus a suffix (e.g. "Created By" + " Email" -> "Created By Email") must NOT
384
455
  // be added here. A hardcoded flat entry here short-circuits triggerRefPath's
@@ -716,6 +787,17 @@ const TASK_OUTPUT_LABEL_TO_TS = {
716
787
  "All found users": ["users"],
717
788
  },
718
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
+ }
719
801
  // userGroupSearch refs-map keys → authoring path; inverse of build.ts's
720
802
  // USER_GROUP_SEARCH_REF_WIRE_NAMES. "ID"/"Name" are only these outputs on
721
803
  // elementum_user_group_search_task, so the table must stay scoped to it.
@@ -1007,18 +1089,18 @@ function approverReferenceFieldAuthoringType(value, ctx) {
1007
1089
  }
1008
1090
  return undefined;
1009
1091
  }
1010
- function decodeFieldAssignmentValue(value, ctx, diagnostics, where = "field assignment") {
1092
+ function decodeFieldAssignmentValue(value, ctx, diagnostics, where = "field assignment", position = "whole") {
1011
1093
  // Multi-Select assignments are exported as jsonencode([<option UUID>, ...])
1012
1094
  // rather than the options-by-label locals used for a scalar Dropdown. Walk
1013
1095
  // that payload with the state-derived option registry so pulled source stays
1014
1096
  // portable across organizations and fresh creates.
1015
1097
  if (isTfExpr(value) && value.$expr === "jsonencode") {
1016
- return decodeFieldAssignmentValue(value.value, ctx, diagnostics, where);
1098
+ return decodeFieldAssignmentValue(value.value, ctx, diagnostics, where, position);
1017
1099
  }
1018
1100
  if (Array.isArray(value)) {
1019
- return value.map((item) => decodeFieldAssignmentValue(item, ctx, diagnostics, where));
1101
+ return value.map((item) => decodeFieldAssignmentValue(item, ctx, diagnostics, where, "item"));
1020
1102
  }
1021
- return decodeValueOrStringifiedRef(value, ctx, diagnostics, where);
1103
+ return decodeValueOrStringifiedRef(value, ctx, diagnostics, where, position);
1022
1104
  }
1023
1105
  /**
1024
1106
  * A Dropdown or Multi-Select assignment's option, printed as
@@ -1076,7 +1158,7 @@ const VALUE_REFERENCE_KEYS = ["taskReference", "triggerReference", "variableRefe
1076
1158
  * diagnostic instead of a silent literal. Returns undefined for any string
1077
1159
  * that carries no envelope.
1078
1160
  */
1079
- function decodeStringifiedValueReference(value, ctx, diagnostics, where) {
1161
+ function decodeStringifiedValueReference(value, ctx, diagnostics, where, fieldAssignment) {
1080
1162
  if (!value.includes("{") || !VALUE_REFERENCE_KEYS.some((key) => value.includes(`"${key}"`)))
1081
1163
  return undefined;
1082
1164
  const parts = [];
@@ -1129,13 +1211,22 @@ function decodeStringifiedValueReference(value, ctx, diagnostics, where) {
1129
1211
  if (start > cursor)
1130
1212
  parts.push(value.slice(cursor, start));
1131
1213
  const reference = decodeFilterReferenceEnvelope(parsed, ctx, undefined, "envelope");
1132
- if (reference === undefined || stringifiedEnvelopeCannotMatchRead(parsed, reference, ctx, where)) {
1214
+ // Build writes an undeclared script output back as this envelope only
1215
+ // as the whole value of a field assignment, and only as its own
1216
+ // jsonencode text (#3050).
1217
+ const undeclaredRebuilds = fieldAssignment === "whole" && start === 0 && end === value.length &&
1218
+ isBuiltUndeclaredScriptOutputText(parsed, value);
1219
+ if (reference === undefined || stringifiedEnvelopeCannotMatchRead(parsed, reference, ctx, where, undeclaredRebuilds)) {
1133
1220
  unresolved = true;
1134
1221
  if (ctx.stringifiedValueReferences !== undefined)
1135
1222
  ctx.stringifiedValueReferences.unresolved = true;
1136
1223
  parts.push({ kind: "unresolved", uuid: value.slice(start, end), hint: "value-reference (edk#1646)" });
1137
1224
  }
1138
1225
  else {
1226
+ if (reference.kind === "taskRef" && reference.undeclaredScriptOutput === true) {
1227
+ recordUndeclaredScriptOutputFieldRead(reference, ctx);
1228
+ }
1229
+ noteTriggerReferenceSpelling(envelopeTriggerReferenceName(parsed), reference, ctx);
1139
1230
  parts.push(reference);
1140
1231
  }
1141
1232
  cursor = end;
@@ -1169,6 +1260,53 @@ function decodeStringifiedValueReference(value, ctx, diagnostics, where) {
1169
1260
  return merged[0];
1170
1261
  return { kind: "template", parts: merged };
1171
1262
  }
1263
+ /**
1264
+ * True when `text` is exactly what build writes for an undeclared script
1265
+ * output in a field assignment: `jsonencode({ fieldType, multiple,
1266
+ * taskReference = { name, taskId } })` (`undeclaredExecuteScriptFieldEnvelope`
1267
+ * in to-tf.ts). Other text (keys in another order, other keys, unescaped
1268
+ * `&`) would plan an update after adoption, so it keeps the skip.
1269
+ */
1270
+ function isBuiltUndeclaredScriptOutputText(envelope, text) {
1271
+ const reference = envelope.taskReference;
1272
+ if (!isObject(reference) || typeof reference.name !== "string" || typeof reference.taskId !== "string" ||
1273
+ typeof envelope.fieldType !== "string" || typeof envelope.multiple !== "boolean")
1274
+ return false;
1275
+ const built = {
1276
+ fieldType: envelope.fieldType,
1277
+ multiple: envelope.multiple,
1278
+ taskReference: { name: reference.name, taskId: reference.taskId },
1279
+ };
1280
+ return renderJsonencode(built) === text;
1281
+ }
1282
+ /**
1283
+ * The platform's publish check rejects a reference to a script output the
1284
+ * script doesn't declare ("has a value reference that is no longer valid";
1285
+ * mobius #341, confirmed on ironman for a Create Record field). The automation
1286
+ * pulls and plans clean, but its next publish fails until the script
1287
+ * declares the output (#3050).
1288
+ */
1289
+ function undeclaredScriptOutputFieldWarning(reads) {
1290
+ const listed = [...reads].map(([task, outputs]) => `${JSON.stringify(task)} (${[...outputs].map((output) => JSON.stringify(output)).join(", ")})`).join("; ");
1291
+ return `record fields are set from Run Script outputs the script's outputs don't declare: ${listed}. ` +
1292
+ "Pull keeps them as unsafeScriptOutput(...), so the automation is managed and plans with no changes, " +
1293
+ "but the platform won't publish a reference to an undeclared output: the next apply that changes this " +
1294
+ "automation fails at publish, and the live version stays as it is. Add each output to its script's outputs " +
1295
+ "and read it as ctx.actions.<script>.result.<output> before changing this automation.";
1296
+ }
1297
+ /**
1298
+ * Remember a field assignment kept as an undeclared script output, for the
1299
+ * pull warning that the platform won't publish it (#3050).
1300
+ */
1301
+ function recordUndeclaredScriptOutputFieldRead(reference, ctx) {
1302
+ const reads = ctx.undeclaredScriptOutputFieldReads;
1303
+ if (reads === undefined)
1304
+ return;
1305
+ const output = reference.path.slice(1).join(".");
1306
+ const outputs = reads.get(reference.task) ?? new Set();
1307
+ outputs.add(output);
1308
+ reads.set(reference.task, outputs);
1309
+ }
1172
1310
  function stringifiedReferenceResolves(envelope, reference, ctx) {
1173
1311
  if (reference.kind === "unresolved")
1174
1312
  return false;
@@ -1185,10 +1323,10 @@ function stringifiedReferenceResolves(envelope, reference, ctx) {
1185
1323
  * script output rebuilds as TEXT, and an envelope whose fieldType or multiple
1186
1324
  * is not the type build infers would plan an update after Read (#1858).
1187
1325
  */
1188
- function stringifiedEnvelopeCannotMatchRead(envelope, reference, ctx, where) {
1326
+ function stringifiedEnvelopeCannotMatchRead(envelope, reference, ctx, where, undeclaredScriptOutputRebuilds) {
1189
1327
  if (!stringifiedReferenceResolves(envelope, reference, ctx))
1190
1328
  return true;
1191
- if (reference.kind === "taskRef" && reference.undeclaredScriptOutput === true)
1329
+ if (reference.kind === "taskRef" && reference.undeclaredScriptOutput === true && !undeclaredScriptOutputRebuilds)
1192
1330
  return true;
1193
1331
  if (typeof envelope.fieldType !== "string")
1194
1332
  return false;
@@ -1240,12 +1378,12 @@ function shadowedOnDemandParamFromEnvelope(value, ctx) {
1240
1378
  : undefined;
1241
1379
  if (!isObject(parameter) || parameter.type === "record" || parameter.type === "user")
1242
1380
  return undefined;
1243
- return declared;
1381
+ return { declared, wireName };
1244
1382
  }
1245
1383
  /** decodeValue, upgrading a stringified ValueReference envelope (edk#1646). */
1246
- function decodeValueOrStringifiedRef(value, ctx, diagnostics, where) {
1384
+ function decodeValueOrStringifiedRef(value, ctx, diagnostics, where, fieldAssignment) {
1247
1385
  if (typeof value === "string") {
1248
- const decoded = decodeStringifiedValueReference(value, ctx, diagnostics, where);
1386
+ const decoded = decodeStringifiedValueReference(value, ctx, diagnostics, where, fieldAssignment);
1249
1387
  if (decoded !== undefined)
1250
1388
  return decoded;
1251
1389
  }
@@ -1287,6 +1425,15 @@ function triggerRefPath(path, ctx) {
1287
1425
  if (wireName === "Attachment Id")
1288
1426
  return ["attachment", "id"];
1289
1427
  }
1428
+ // An approval process status trigger's own outputs (#2990): "Final
1429
+ // Approval By's id" -> approver.id, "Approval Status" -> status, ... A
1430
+ // field of the app with the same display name keeps the plain key, and the
1431
+ // output then comes as "Approval Chain Trigger - <key>".
1432
+ if (ctx.trigger.type === "elementum_approval_chain_trigger") {
1433
+ const approvalPath = approvalTriggerPathFromRefsKey(wireName, (key) => ownerFieldHasDisplayName(key, ctx));
1434
+ if (approvalPath !== undefined)
1435
+ return approvalPath;
1436
+ }
1290
1437
  // emailReceived's own trigger-output field names (EmailReceivedTriggerOutput,
1291
1438
  // triggers.ts) use snake_case matching the platform's field identifiers,
1292
1439
  // not the human display labels the platform emits in triggerReference.name
@@ -1364,8 +1511,27 @@ function triggerRefPath(path, ctx) {
1364
1511
  return names;
1365
1512
  return recordFieldRefPath(wireName, ctx) ?? names;
1366
1513
  }
1514
+ /**
1515
+ * Whether a field of this export's app or element has exactly this display
1516
+ * name: the provider keeps the plain refs key for such a field. Read from the
1517
+ * field blocks, not `fieldById`, which a `--no-imports` export leaves empty.
1518
+ */
1519
+ function ownerFieldHasDisplayName(name, ctx) {
1520
+ if (name === ctx.titleFieldName || name === ctx.idFieldName || name === ctx.statusFieldName)
1521
+ return true;
1522
+ for (const block of ctx.resourceBlocks.values()) {
1523
+ if (block.type?.endsWith("_field") !== true || block.attrs.name !== name)
1524
+ continue;
1525
+ // Only the trigger's own app or element: build checks the owner's fields alone.
1526
+ const ownerTf = (block.label !== undefined ? ownerFromScopedChildLabel(block.label)?.ownerTfLabel : undefined) ?? ctx.appTfLabel;
1527
+ if (tfLabelToTsLabel(ownerTf) === ctx.appRefName)
1528
+ return true;
1529
+ }
1530
+ return false;
1531
+ }
1367
1532
  // Top-level properties the record trigger outputs declare (RecordTriggerOutput,
1368
- // AttachmentTriggerOutput, CommentAddedTriggerOutput in triggers.ts).
1533
+ // AttachmentTriggerOutput, CommentAddedTriggerOutput,
1534
+ // ApprovalProcessStatusUpdatedTriggerOutput in triggers.ts).
1369
1535
  const RECORD_TRIGGER_OUTPUT_HEADS = new Set(["record", "changedFieldIds", "attachment", "comment"]);
1370
1536
  const UNDECLARED_HEAD_TRIGGER_TYPES = new Set([
1371
1537
  "elementum_record_created_trigger",
@@ -1381,7 +1547,8 @@ const UNDECLARED_HEAD_TRIGGER_TYPES = new Set([
1381
1547
  * signature, so pull prints it through an `as any` escape (#2643).
1382
1548
  */
1383
1549
  function undeclaredRecordTriggerHead(path, ctx) {
1384
- return UNDECLARED_HEAD_TRIGGER_TYPES.has(ctx.trigger.type ?? "") && path.length === 1 && !RECORD_TRIGGER_OUTPUT_HEADS.has(path[0]);
1550
+ const heads = ctx.trigger.type === "elementum_approval_chain_trigger" ? APPROVAL_TRIGGER_OUTPUT_HEADS : RECORD_TRIGGER_OUTPUT_HEADS;
1551
+ return UNDECLARED_HEAD_TRIGGER_TYPES.has(ctx.trigger.type ?? "") && path.length === 1 && !heads.has(path[0]);
1385
1552
  }
1386
1553
  function forEachItemOwnerRefName(loop, ctx) {
1387
1554
  const collection = loop === undefined ? undefined : resourceRef(loop.attrs.list);
@@ -1522,13 +1689,56 @@ function resolveFieldKeyFromId(fieldId, ownerRefName, ctx) {
1522
1689
  const expectedOwner = ownerRefName ?? ctx.appRefName;
1523
1690
  return state.ownerRefName === expectedOwner ? state.fieldKey : undefined;
1524
1691
  }
1525
- 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") {
1526
1726
  const { refKey, block } = resolveTaskRefKey(taskIdOrKey, ctx);
1527
1727
  if (block !== undefined) {
1528
1728
  const aiAgentPath = aiAgentTaskRefPath(block, pathSegments.join("."));
1529
1729
  if (aiAgentPath !== undefined)
1530
1730
  return { kind: "taskRef", task: refKey, path: aiAgentPath };
1531
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] };
1532
1742
  // A task's own record output can be addressed by an unresolved field UUID
1533
1743
  // (`record.<field-uuid>[.suffix]`) the same way a recordSearch task's
1534
1744
  // found-record fields already are below - an updateField task's "record"
@@ -1668,7 +1878,7 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
1668
1878
  function slackTriggerPath(path, ctx) {
1669
1879
  return ctx.trigger.type === "elementum_slack_message_trigger" ? slackMessageTriggerPathFromWire(path) : undefined;
1670
1880
  }
1671
- function decodeReferenceString(value, ctx) {
1881
+ function decodeReferenceString(value, ctx, spelling = "stored-name") {
1672
1882
  const pieces = value.split(".");
1673
1883
  if (pieces[0] === "trigger" && pieces.length > 1) {
1674
1884
  const path = pieces.slice(1);
@@ -1702,7 +1912,7 @@ function decodeReferenceString(value, ctx) {
1702
1912
  return { kind: "triggerRef", path };
1703
1913
  }
1704
1914
  if (pieces[0] === "task" && pieces.length > 2) {
1705
- return decodeTaskReferenceFromString(pieces[1], pieces.slice(2), ctx);
1915
+ return decodeTaskReferenceFromString(pieces[1], pieces.slice(2), ctx, spelling);
1706
1916
  }
1707
1917
  if (pieces[0] === "for_each" && pieces.length > 2) {
1708
1918
  const { refKey, block } = resolveTaskRefKey(pieces[1], ctx);
@@ -1775,7 +1985,7 @@ function decodeTemplateTriggerRecordFieldRef(value, ctx) {
1775
1985
  * `"task." + <task.id> + ".<wireName>"` templates so provider Read's plain
1776
1986
  * `task.<uuid>.<wireName>` strings round-trip without perpetual plan drift.
1777
1987
  */
1778
- function decodeTemplateTaskRef(value, ctx) {
1988
+ function decodeTemplateTaskRef(value, ctx, spelling = "stored-name") {
1779
1989
  if (!isTfExpr(value) || value.$expr !== "template")
1780
1990
  return undefined;
1781
1991
  const [prefix, idPart, ...nameTemplate] = mergeAdjacentTemplateStrings(value.parts);
@@ -1796,7 +2006,7 @@ function decodeTemplateTaskRef(value, ctx) {
1796
2006
  const nameParts = suffixPart.slice(1).split(".").filter((segment) => segment.length > 0);
1797
2007
  if (nameParts.length === 0)
1798
2008
  return undefined;
1799
- return decodeTaskReferenceFromString(task.refKey, nameParts, ctx);
2009
+ return decodeTaskReferenceFromString(task.refKey, nameParts, ctx, spelling);
1800
2010
  }
1801
2011
  function mergeAdjacentTemplateStrings(parts) {
1802
2012
  const out = [];
@@ -1927,7 +2137,7 @@ function fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx) {
1927
2137
  ? index.index
1928
2138
  : undefined;
1929
2139
  if (name !== undefined) {
1930
- return tfLabelToTsLabel(sanitizeName(name));
2140
+ return tableColumnKeyIn(fieldPart, name, ctx);
1931
2141
  }
1932
2142
  }
1933
2143
  return undefined;
@@ -1950,13 +2160,85 @@ function resolveConnectorRef(connectorType, connectorLabel, ctx) {
1950
2160
  });
1951
2161
  return { handle: identity.handle, ...(identity.providerKey !== undefined && { providerKey: identity.providerKey }) };
1952
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
+ }
1953
2235
  /**
1954
2236
  * `field_ids["Display Name"]` on either the managed table resource or its
1955
- * `data` lookup. The bag key is derived the same way `table/from-tf.ts` derives
1956
- * it for an out-of-stream table, so the printed token lines up with the key the
1957
- * 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).
1958
2239
  */
1959
- function tableColumnRefFromPath(label, path, tableName) {
2240
+ function tableColumnRefFromPath(value, tableName, ctx) {
2241
+ const { label, path } = value;
1960
2242
  const index = path[1];
1961
2243
  const name = typeof index === "string"
1962
2244
  ? index
@@ -1968,7 +2250,7 @@ function tableColumnRefFromPath(label, path, tableName) {
1968
2250
  return {
1969
2251
  kind: "tableColumn",
1970
2252
  tableHandle: tfLabelToTsLabel(label),
1971
- columnKey: tfLabelToTsLabel(sanitizeName(name)),
2253
+ columnKey: tableColumnKeyIn(value, name, ctx),
1972
2254
  name,
1973
2255
  ...(tableName !== undefined ? { tableName } : {}),
1974
2256
  };
@@ -2003,6 +2285,20 @@ function resolveSearchTableFromBlock(block, searchTableLabel, ctx) {
2003
2285
  }
2004
2286
  return undefined;
2005
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
+ }
2006
2302
  function decodeSearchTableReference(value, ctx) {
2007
2303
  if (isTfExpr(value) && value.$expr === "data-attr" && value.type === "elementum_search_table") {
2008
2304
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
@@ -2028,8 +2324,21 @@ function decodeSearchTableReference(value, ctx) {
2028
2324
  ? aspectOwnerRefNameFromObjectId(objectId, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames)
2029
2325
  : undefined;
2030
2326
  if (elementHandle !== undefined && name !== undefined) {
2031
- const tableKey = tfLabelToTsLabel(sanitizeName(name));
2032
- 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
+ };
2033
2342
  }
2034
2343
  return { kind: "unresolved", uuid: `data.${value.type}.${value.label}`, hint: "search table" };
2035
2344
  }
@@ -2079,8 +2388,11 @@ function decodeValue(value, ctx) {
2079
2388
  return { kind: "triggerRef", path: ["attachment", payloadKey] };
2080
2389
  }
2081
2390
  const shadowedParam = shadowedOnDemandParamFromEnvelope(value, ctx);
2082
- if (shadowedParam !== undefined)
2083
- 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
+ }
2084
2396
  if (isTfExpr(value)) {
2085
2397
  if (value.$expr === "template") {
2086
2398
  return { kind: "template", parts: value.parts.map((part) => typeof part === "string" ? part : decodeValue(part, ctx)) };
@@ -2236,7 +2548,7 @@ function decodeValue(value, ctx) {
2236
2548
  return { kind: "table", tableHandle: tfLabelToTsLabel(value.label) };
2237
2549
  }
2238
2550
  if (value.type === TABLE_RESOURCE_TYPE && value.path[0] === "field_ids") {
2239
- return tableColumnRefFromPath(value.label, value.path, undefined);
2551
+ return tableColumnRefFromPath(value, undefined, ctx);
2240
2552
  }
2241
2553
  if (value.type === "elementum_datamine" && value.path[0] === "id") {
2242
2554
  const datamineBlock = ctx.resourceBlocks.get(`elementum_datamine.${value.label}`);
@@ -2301,7 +2613,7 @@ function decodeValue(value, ctx) {
2301
2613
  if (value.$expr === "data-attr" && value.type === TABLE_RESOURCE_TYPE && value.path[0] === "field_ids") {
2302
2614
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
2303
2615
  const tableName = lookup?.attrs.name;
2304
- return tableColumnRefFromPath(value.label, value.path, typeof tableName === "string" ? tableName : undefined);
2616
+ return tableColumnRefFromPath(value, typeof tableName === "string" ? tableName : undefined, ctx);
2305
2617
  }
2306
2618
  if (value.$expr === "data-attr" && value.type === "elementum_datamine" && value.path[0] === "id") {
2307
2619
  const datamineLookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
@@ -2339,28 +2651,16 @@ function decodeValue(value, ctx) {
2339
2651
  };
2340
2652
  }
2341
2653
  if (value.$expr === "data-attr" && value.type === AUTOMATION_RESOURCE_TYPE && value.path[0] === "id") {
2342
- const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
2343
- const ownerId = lookup?.attrs["app_id"];
2344
- if (ownerId === undefined ||
2345
- !isTfExpr(ownerId) ||
2346
- ownerId.$expr !== "data-attr" ||
2347
- (ownerId.type !== "elementum_app" && ownerId.type !== "elementum_element") ||
2348
- ownerId.path[0] !== "id") {
2349
- throw new EntityTfError(`data.${AUTOMATION_RESOURCE_TYPE}.${value.label}: app_id is not a resolvable app/element data reference`);
2350
- }
2351
- const ownerLookup = ctx.dataBlocks.get(`${ownerId.type}.${ownerId.label}`);
2352
- const ownerIdentity = ownerLookup?.attrs.namespace ?? ownerLookup?.attrs.name;
2353
- const mappedHandle = typeof ownerIdentity === "string"
2354
- ? (ownerId.type === "elementum_element" ? ctx.foreignElementRefNames : ctx.foreignAppRefNames)?.get(ownerIdentity)
2355
- : undefined;
2356
- const prefix = `${ownerId.label}_`;
2357
- return {
2358
- kind: "automation",
2359
- appHandle: mappedHandle ?? tfLabelToTsLabel(ownerId.label),
2360
- automationKey: tfLabelToTsLabel(value.label.startsWith(prefix) ? value.label.slice(prefix.length) : value.label),
2361
- };
2654
+ const target = foreignAutomationTarget(value.label, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames);
2655
+ return { kind: "automation", appHandle: target.appHandle, automationKey: target.automationKey };
2362
2656
  }
2363
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;
2364
2664
  // The reverse of to-tf.ts's `crossAppFieldToTf`: a field belonging to a
2365
2665
  // DIFFERENT app/element than this automation's own — resolved via the
2366
2666
  // field's own `data.elementum_field` block, whose `object_id` names
@@ -2596,30 +2896,42 @@ function managedFieldKeyForDisplayName(foreign, ctx) {
2596
2896
  }
2597
2897
  return keys.size === 1 ? keys.values().next().value : undefined;
2598
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
+ }
2599
2931
  function fieldRef(value, ctx) {
2600
- if (isTfExpr(value) && value.$expr === "data-attr" && value.path.join(".") === "id") {
2601
- const foreign = ctx.foreignFieldRefsByDataAddress?.get(`${value.type}.${value.label}`);
2602
- if (foreign !== undefined) {
2603
- const fieldKey = managedFieldKeyForDisplayName(foreign, ctx) ?? foreign.fieldKey;
2604
- return {
2605
- kind: "field",
2606
- appHandle: foreign.ownerRefName,
2607
- fieldKey,
2608
- ...(foreign.ownerKind !== undefined || foreign.fieldName !== undefined || foreign.fieldType !== undefined
2609
- ? {
2610
- foreign: {
2611
- entityType: foreign.ownerKind ?? "app",
2612
- ...(foreign.ownerKind === undefined ? { ownerKindUnknown: true } : {}),
2613
- name: foreign.ownerName ?? foreign.ownerRefName,
2614
- ...(foreign.ownerNamespace !== undefined ? { namespace: foreign.ownerNamespace } : {}),
2615
- ...(foreign.fieldName !== undefined ? { fieldName: foreign.fieldName } : {}),
2616
- ...(foreign.fieldType !== undefined ? { fieldType: foreign.fieldType } : {}),
2617
- },
2618
- }
2619
- : {}),
2620
- };
2621
- }
2622
- }
2932
+ const refOnly = refOnlyFieldRef(value, ctx);
2933
+ if (refOnly !== undefined)
2934
+ return refOnly;
2623
2935
  const decoded = decodeValue(value, ctx);
2624
2936
  if (isObject(decoded) && decoded.kind === "field")
2625
2937
  return decoded;
@@ -2662,7 +2974,7 @@ function filterFieldRef(value, ctx) {
2662
2974
  const tableName = value.$expr === "data-attr"
2663
2975
  ? ctx.dataBlocks.get(`${value.type}.${value.label}`)?.attrs.name
2664
2976
  : undefined;
2665
- return tableColumnRefFromPath(value.label, value.path, typeof tableName === "string" ? tableName : undefined);
2977
+ return tableColumnRefFromPath(value, typeof tableName === "string" ? tableName : undefined, ctx);
2666
2978
  }
2667
2979
  return fieldRef(value, ctx);
2668
2980
  }
@@ -3056,6 +3368,8 @@ function stageFilterName(value, ctx) {
3056
3368
  * Recognized shapes:
3057
3369
  * - `{{trigger name="record.<field-uuid>"}}`
3058
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)
3059
3373
  * - `variable.<variable-uuid>` (calc-engine short form)
3060
3374
  */
3061
3375
  function decodeCalculationFormula(value, ctx) {
@@ -3063,7 +3377,7 @@ function decodeCalculationFormula(value, ctx) {
3063
3377
  return decodeValue(value, ctx);
3064
3378
  const parts = [];
3065
3379
  let cursor = 0;
3066
- const pattern = /\{\{(trigger|task)\s+([^}]*)\}\}|variable\.([a-f0-9-]{36})/g;
3380
+ const pattern = /\{\{(trigger|task|forEach)\s+([^}]*)\}\}|variable\.([a-f0-9-]{36})/g;
3067
3381
  while (cursor < value.length) {
3068
3382
  pattern.lastIndex = cursor;
3069
3383
  const match = pattern.exec(value);
@@ -3093,6 +3407,11 @@ function decodeCalculationFormula(value, ctx) {
3093
3407
  const decoded = name !== undefined ? decodeReferenceString(`trigger.${name}`, ctx) : undefined;
3094
3408
  parts.push(decoded ?? { kind: "unresolved", uuid: name ?? match[0], hint: "calculation-reference" });
3095
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
+ }
3096
3415
  else {
3097
3416
  const name = /name="([^"]*)"/.exec(attrs)?.[1];
3098
3417
  const id = /id="([^"]*)"/.exec(attrs)?.[1];
@@ -3159,6 +3478,22 @@ function nextCalculationJsonReference(value, fromIndex, ctx) {
3159
3478
  }
3160
3479
  return undefined;
3161
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
+ }
3162
3497
  function decodeCalculationTaskMustache(taskId, wireName, ctx) {
3163
3498
  if (taskId === undefined || wireName === undefined) {
3164
3499
  return { kind: "unresolved", uuid: `task:${taskId ?? "?"}:${wireName ?? "?"}`, hint: "calculation-reference" };
@@ -3325,7 +3660,9 @@ function decodeFilterReferenceEnvelope(value, ctx, outputName, role) {
3325
3660
  if (isObject(taskRef) && typeof taskRef.name === "string") {
3326
3661
  const taskIdOrKey = workflowOutputTaskIdOrKey(taskRef.taskId, ctx);
3327
3662
  if (taskIdOrKey !== undefined) {
3328
- 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);
3329
3666
  const task = resolveTaskRefKey(taskIdOrKey, ctx).block;
3330
3667
  if (decoded.kind === "taskRef" && task?.type === "elementum_execute_script_task") {
3331
3668
  const schemaValue = task.attrs.output_schema;
@@ -3401,13 +3738,22 @@ function workflowOutputTaskIdOrKey(taskId, ctx) {
3401
3738
  }
3402
3739
  function filterReference(value, ctx, role) {
3403
3740
  assertFilterTaskRefResolves(filterReferenceTaskId(value), ctx);
3404
- return markUndeclaredScriptOutput(typeof value === "string"
3405
- ? decodeReferenceString(value, ctx) ?? { kind: "unresolved", uuid: value, hint: "filter-reference" }
3406
- : decodeFilterReferenceEnvelope(value, ctx, undefined, role)
3407
- ?? decodeTemplateTriggerRecordFieldRef(value, ctx)
3408
- ?? decodeTemplateTaskRef(value, ctx)
3409
- ?? decodeTemplateForEachRef(value, ctx)
3410
- ?? 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);
3411
3757
  }
3412
3758
  /**
3413
3759
  * A filter reference to an execute-script output its schema doesn't declare
@@ -3818,7 +4164,12 @@ function triggerFromBlock(block, ctx, diagnostics) {
3818
4164
  }
3819
4165
  function taskArgs(block, factory, ctx, taskDiagnostics) {
3820
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;
3821
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
+ }
3822
4173
  // object_field_ids is build-derived from the target's field order (edk#2280),
3823
4174
  // object_fields / object_system_field_ids from the owner's fields (edk#2680 / #2692),
3824
4175
  // refs_read from the refs keys the automation reads (edk#2648).
@@ -3847,7 +4198,7 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3847
4198
  const fieldKey = field.kind === "field"
3848
4199
  ? field.fieldKey
3849
4200
  : `${UNRESOLVED_FIELD_MARKER}${field.uuid}`;
3850
- 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}`));
3851
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}`);
3852
4203
  const canonicalValue = factory === "createRecord" || factory === "updateField"
3853
4204
  ? canonicalTriggerRecordIdSlot(optionValue, ctx)
@@ -3888,7 +4239,8 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
3888
4239
  args.inputs = Object.fromEntries(value.map((item) => {
3889
4240
  if (!isObject(item) || typeof item.name !== "string")
3890
4241
  throw new EntityTfError("invalid script input");
3891
- 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));
3892
4244
  const rawMappings = item.field_mappings;
3893
4245
  // A list-valued input's field_mappings - which fields of each list
3894
4246
  // item the script can read, and under what alias. Kept as a tagged
@@ -4042,7 +4394,7 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
4042
4394
  `but the task targets ${mismatch.target}; pulled source maps ${JSON.stringify(name)} by name on the target, ` +
4043
4395
  "so build will not reproduce the exported mapping");
4044
4396
  }
4045
- return { name, value: decodeValue(item.value, ctx) };
4397
+ return { name, value: atRepairSite(ctx, repairInput(ctx, () => `input ${JSON.stringify(name)}`), () => decodeValue(item.value, ctx)) };
4046
4398
  }
4047
4399
  // ei emits bare platform parameter UUIDs when the target automation's
4048
4400
  // onDemand trigger is not in this export (foreign / undiscovered).
@@ -4053,7 +4405,7 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
4053
4405
  if (typeof parameter === "string" && parameter !== "") {
4054
4406
  return {
4055
4407
  name: parameter,
4056
- value: decodeValue(item.value, ctx),
4408
+ value: atRepairSite(ctx, repairInput(ctx, () => `input ${JSON.stringify(parameter)}`), () => decodeValue(item.value, ctx)),
4057
4409
  };
4058
4410
  }
4059
4411
  throw new EntityTfError(`${block.type}.${block.label}: input mapping parameter_id is not a named trigger parameter reference`);
@@ -4103,7 +4455,9 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
4103
4455
  if (!isObject(item) || typeof item.variable_name !== "string" || item.formula === undefined) {
4104
4456
  throw new EntityTfError(`${block.type}.${block.label}: invalid calculation entry`);
4105
4457
  }
4106
- 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));
4107
4461
  const expression = isObject(decodedExpression) && decodedExpression.kind === "literal"
4108
4462
  ? pulledRawCalculation(item.formula, item.output_type, item.multiple) ?? decodedExpression
4109
4463
  : decodedExpression;
@@ -4224,6 +4578,41 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
4224
4578
  args.approvers = value.map((item) => decodeValue(item, ctx));
4225
4579
  continue;
4226
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
+ }
4227
4616
  if (attr === "list" && factory === "forEach") {
4228
4617
  args.collection = decodeValueOrStringifiedRef(value, ctx, taskDiagnostics, `${block.type}.${block.label} list`);
4229
4618
  continue;
@@ -4258,7 +4647,8 @@ function taskArgs(block, factory, ctx, taskDiagnostics) {
4258
4647
  throw new EntityTfError(`${block.type}.${block.label}: ${kind} must set exactly one of file, attachment, or record`);
4259
4648
  }
4260
4649
  const key = present[0];
4261
- return { [key]: decodeValue(item[key], ctx) };
4650
+ const decoded = decodeValue(item[key], ctx);
4651
+ return { [key]: key === "record" ? attachmentWholeRecordPath(decoded) : decoded };
4262
4652
  });
4263
4653
  continue;
4264
4654
  }
@@ -4541,8 +4931,12 @@ function unmanagedSuccessorPosition(doc, label, ownedAddresses, addressByPlatfor
4541
4931
  return undefined;
4542
4932
  return resolveUnmanagedTaskPosition(dataBlock, ownedAddresses, addressByPlatformId);
4543
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
+ }
4544
4938
  /** Puts every earlier unsupported step of a run into the same tree as the one a managed task parents onto. */
4545
- function rememberUnmanagedPredecessors(doc, label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen) {
4939
+ function rememberUnmanagedPredecessors(doc, label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen, placeholderKey) {
4546
4940
  const predecessor = unmanagedTaskRef(documentLocals(doc)[`${UNMANAGED_PREDECESSOR_LOCAL_PREFIX}${label}`]);
4547
4941
  if (predecessor === undefined || seen.has(predecessor.label))
4548
4942
  return;
@@ -4554,16 +4948,14 @@ function rememberUnmanagedPredecessors(doc, label, ownedAddresses, addressByPlat
4554
4948
  if (dataBlock === undefined || position === undefined)
4555
4949
  return;
4556
4950
  unmanagedTaskPositions.set(address, position);
4557
- const refKey = typeof dataBlock.attrs.name === "string" && dataBlock.attrs.name !== ""
4558
- ? dataBlock.attrs.name
4559
- : tfLabelToTsLabel(dataBlock.label ?? "task");
4951
+ const refKey = placeholderKey(dataBlock);
4560
4952
  taskByAddress.set(address, { block: dataBlock, refKey });
4561
4953
  placeholderTasks.push({
4562
- name: refKey,
4954
+ name: placeholderDisplayName(dataBlock, refKey),
4563
4955
  taskType: typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown",
4564
4956
  });
4565
4957
  }
4566
- rememberUnmanagedPredecessors(doc, predecessor.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen);
4958
+ rememberUnmanagedPredecessors(doc, predecessor.label, ownedAddresses, addressByPlatformId, dataBlocks, unmanagedTaskPositions, taskByAddress, placeholderTasks, seen, placeholderKey);
4567
4959
  }
4568
4960
  function importPlatformId(doc, type, label) {
4569
4961
  for (const block of doc.blocks) {
@@ -4694,6 +5086,8 @@ function taskRefKey(block, automationLabel, appTfLabel, exportAutoChild) {
4694
5086
  }
4695
5087
  return tfLabelToTsLabel(/^[0-9]/.test(tail) ? `_${tail}` : tail);
4696
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]);
4697
5091
  /**
4698
5092
  * Best-effort resource footprint of one automation, used ONLY when whole-
4699
5093
  * automation extraction throws (module.ts's `extractAutomations` catch
@@ -4717,6 +5111,14 @@ function taskRefKey(block, automationLabel, appTfLabel, exportAutoChild) {
4717
5111
  export function automationOwnedAddresses(doc, automationLabel) {
4718
5112
  const owned = new Set([`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`]);
4719
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;
4720
5122
  if (block.kind === "resource" && block.type !== undefined && block.label !== undefined &&
4721
5123
  (references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel) ||
4722
5124
  references(block.attrs.automation_id, AUTOMATION_RESOURCE_TYPE, automationLabel))) {
@@ -5351,8 +5753,10 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5351
5753
  }
5352
5754
  }
5353
5755
  const stringifiedValueReferences = { unresolved: false };
5756
+ const undeclaredScriptOutputFieldReads = new Map();
5354
5757
  const groupsMissingFromOrg = new Set();
5355
5758
  const optionIdWarnings = new Set();
5759
+ const triggerReferenceRepairs = { site: undefined, found: [] };
5356
5760
  const ctx = {
5357
5761
  appRefName,
5358
5762
  appTfLabel: app.label,
@@ -5370,6 +5774,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5370
5774
  ...(foreignFieldRefsById !== undefined && { foreignFieldRefsById }),
5371
5775
  ...(foreignFieldRefsByDataAddress !== undefined && { foreignFieldRefsByDataAddress }),
5372
5776
  ...(foreignTableRefsById !== undefined && { foreignTableRefsById }),
5777
+ tableColumnKeys: tableColumnKeysInDocument(doc),
5373
5778
  ...(foreignFileReaderRefsById !== undefined && { foreignFileReaderRefsById }),
5374
5779
  ...(picklistOptionsByField !== undefined && { picklistOptionsByField }),
5375
5780
  ...(fieldNamesByOwnerRefName !== undefined && { fieldNamesByOwnerRefName }),
@@ -5381,8 +5786,10 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5381
5786
  ...(procedureKeysByDiscriminator !== undefined && { procedureKeysByDiscriminator }),
5382
5787
  ...(groupKeysByName !== undefined && { groupKeysByName }),
5383
5788
  stringifiedValueReferences,
5789
+ undeclaredScriptOutputFieldReads,
5384
5790
  groupsMissingFromOrg,
5385
5791
  optionIdWarnings,
5792
+ ...(trigger.type === "elementum_on_demand_trigger" && { triggerReferenceRepairs }),
5386
5793
  ...(resourceImportIds.has(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`) && {
5387
5794
  automationId: resourceImportIds.get(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`),
5388
5795
  }),
@@ -5447,6 +5854,12 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5447
5854
  ]);
5448
5855
  const unmanagedTaskPositions = new Map();
5449
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);
5450
5863
  const addressByPlatformId = taskAddressesByPlatformId(doc);
5451
5864
  for (const task of tasks) {
5452
5865
  const unmanagedRef = unmanagedTaskRef(task.attrs.parent);
@@ -5462,13 +5875,37 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5462
5875
  if (dataBlock === undefined || position === undefined)
5463
5876
  continue; // falls back to parentAddress's trigger-anchor + diagnostic
5464
5877
  unmanagedTaskPositions.set(address, position);
5465
- const refKey = typeof dataBlock.attrs.name === "string" && dataBlock.attrs.name !== "" ? dataBlock.attrs.name : tfLabelToTsLabel(dataBlock.label ?? "task");
5878
+ const refKey = placeholderKey(dataBlock);
5466
5879
  taskByAddress.set(address, { block: dataBlock, refKey });
5467
5880
  placeholderTasks.push({
5468
- name: refKey,
5881
+ name: placeholderDisplayName(dataBlock, refKey),
5469
5882
  taskType: typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown",
5470
5883
  });
5471
- 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);
5472
5909
  }
5473
5910
  const childrenByParent = new Map();
5474
5911
  for (const task of tasks) {
@@ -5518,7 +5955,11 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5518
5955
  // output terse and matches a freshly-authored default branch.
5519
5956
  ...(shape === "explicitTrueFilter" ? { defaultFilterMode: shape } : {}),
5520
5957
  ...(!isDefault && branch.attrs.filter !== undefined ? {
5521
- 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))),
5522
5963
  } : {}),
5523
5964
  tasks: buildTasks(`${branch.type}.${branch.label}`),
5524
5965
  };
@@ -5543,8 +5984,17 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5543
5984
  id: typeof block.attrs.id === "string" ? block.attrs.id : "",
5544
5985
  taskType: typeof block.attrs.task_type === "string" ? block.attrs.task_type : "",
5545
5986
  }
5546
- : taskArgs(block, factory, ctx, taskDiagnostics);
5547
- 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 } : {}) };
5548
5998
  visiting.delete(address);
5549
5999
  return [call, ...buildTasks(address)];
5550
6000
  });
@@ -5558,8 +6008,16 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5558
6008
  throw new EntityTfError("invalid workflow output");
5559
6009
  // Export/provider Read emit jsonencode({fieldType, taskReference, ...});
5560
6010
  // collapse that envelope to a RefExpr the same way filter references do.
5561
- const value = decodeFilterReferenceEnvelope(output.value, ctx, output.name)
5562
- ?? 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
+ });
5563
6021
  const raw = isTfExpr(output.value) && output.value.$expr === "jsonencode"
5564
6022
  ? output.value.value
5565
6023
  : output.value;
@@ -5619,17 +6077,32 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
5619
6077
  ast,
5620
6078
  blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])],
5621
6079
  adoptionAddressAliases,
5622
- ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0 || outputDiagnostics.length > 0 || taskDiagnostics.length > 0 || groupsMissingFromOrg.size > 0 || optionIdWarnings.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) && {
5623
6081
  diagnostics: [
5624
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`),
5625
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`),
5626
6085
  ...outputDiagnostics,
5627
6086
  ...taskDiagnostics.map((message) => `automation "${automationLabel}": ${message}`),
5628
6087
  ...[...optionIdWarnings].map((message) => `automation "${automationLabel}": ${message}`),
6088
+ ...(undeclaredScriptOutputFieldReads.size > 0
6089
+ ? [`automation ${JSON.stringify(typeof automation.attrs.name === "string" ? automation.attrs.name : automationLabel)}: ${undeclaredScriptOutputFieldWarning(undeclaredScriptOutputFieldReads)}`]
6090
+ : []),
5629
6091
  ...[...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>`),
5630
6092
  ],
5631
6093
  }),
5632
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
+ }),
5633
6106
  };
5634
6107
  }
5635
6108
  export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth) {