@elementumai/edk 0.9.11 → 0.9.13

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 (90) hide show
  1. package/README.md +39 -5
  2. package/dist-sdk/src/catalog/factories.d.ts +35 -14
  3. package/dist-sdk/src/catalog/factories.js +64 -13
  4. package/dist-sdk/src/catalog/from-authoring.js +4 -4
  5. package/dist-sdk/src/catalog/index.d.ts +1 -1
  6. package/dist-sdk/src/catalog/org.js +3 -2
  7. package/dist-sdk/src/catalog/token.js +4 -0
  8. package/dist-sdk/src/catalog/types.d.ts +13 -3
  9. package/dist-sdk/src/core/triggers/on-demand.d.ts +4 -28
  10. package/dist-sdk/src/core/triggers/on-demand.js +2 -4
  11. package/dist-sdk/src/engine/entity.d.ts +2 -0
  12. package/dist-sdk/src/engine/logging.d.ts +90 -0
  13. package/dist-sdk/src/engine/logging.js +124 -0
  14. package/dist-sdk/src/engine/progress.d.ts +122 -0
  15. package/dist-sdk/src/engine/progress.js +685 -0
  16. package/dist-sdk/src/engine/pull/result-output.d.ts +24 -0
  17. package/dist-sdk/src/engine/pull/result-output.js +59 -0
  18. package/dist-sdk/src/entities/agent/tools.d.ts +2 -2
  19. package/dist-sdk/src/entities/app/build.d.ts +8 -1
  20. package/dist-sdk/src/entities/app/from-tf.js +4 -4
  21. package/dist-sdk/src/entities/app/to-tf.js +9 -13
  22. package/dist-sdk/src/entities/automation/build.d.ts +11 -16
  23. package/dist-sdk/src/entities/automation/build.js +60 -16
  24. package/dist-sdk/src/entities/automation/catalog-render.js +1 -1
  25. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +1 -2
  26. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +23 -5
  27. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +247 -35
  28. package/dist-sdk/src/entities/automation/from-tf.js +181 -24
  29. package/dist-sdk/src/entities/automation/index.d.ts +2 -2
  30. package/dist-sdk/src/entities/automation/module.js +2 -2
  31. package/dist-sdk/src/entities/automation/output-field-types.js +25 -13
  32. package/dist-sdk/src/entities/automation/script-code.d.ts +12 -4
  33. package/dist-sdk/src/entities/automation/script-code.js +659 -101
  34. package/dist-sdk/src/entities/automation/task-label.js +25 -2
  35. package/dist-sdk/src/entities/automation/tasks.d.ts +60 -28
  36. package/dist-sdk/src/entities/automation/tasks.js +31 -15
  37. package/dist-sdk/src/entities/automation/to-tf.js +443 -64
  38. package/dist-sdk/src/entities/automation/triggers.d.ts +15 -9
  39. package/dist-sdk/src/entities/automation/triggers.js +4 -2
  40. package/dist-sdk/src/entities/chart/build.d.ts +15 -3
  41. package/dist-sdk/src/entities/chart/build.js +6 -1
  42. package/dist-sdk/src/entities/chart/from-tf.d.ts +8 -2
  43. package/dist-sdk/src/entities/chart/from-tf.js +71 -8
  44. package/dist-sdk/src/entities/chart/index.d.ts +1 -1
  45. package/dist-sdk/src/entities/chart/index.js +1 -1
  46. package/dist-sdk/src/entities/chart/printer.js +27 -7
  47. package/dist-sdk/src/entities/chart/to-tf.js +56 -2
  48. package/dist-sdk/src/entities/datamine/from-tf.js +11 -1
  49. package/dist-sdk/src/entities/element/build.d.ts +6 -5
  50. package/dist-sdk/src/entities/element/from-tf.js +3 -2
  51. package/dist-sdk/src/entities/element/module.js +1 -0
  52. package/dist-sdk/src/entities/element/to-tf.d.ts +3 -0
  53. package/dist-sdk/src/entities/element/to-tf.js +9 -1
  54. package/dist-sdk/src/entities/field/from-tf.d.ts +24 -0
  55. package/dist-sdk/src/entities/field/from-tf.js +73 -1
  56. package/dist-sdk/src/entities/field/metadata.d.ts +18 -0
  57. package/dist-sdk/src/entities/field/metadata.js +34 -0
  58. package/dist-sdk/src/entities/relationship/build.d.ts +17 -6
  59. package/dist-sdk/src/entities/relationship/column-contract.d.ts +24 -0
  60. package/dist-sdk/src/entities/relationship/column-contract.js +41 -0
  61. package/dist-sdk/src/entities/relationship/from-tf.js +19 -34
  62. package/dist-sdk/src/entities/relationship/to-tf.js +15 -2
  63. package/dist-sdk/src/entities/shared/context.d.ts +6 -3
  64. package/dist-sdk/src/entities/shared/context.js +19 -1
  65. package/dist-sdk/src/entities/shared/filters/index.d.ts +7 -0
  66. package/dist-sdk/src/entities/shared/filters/index.js +36 -1
  67. package/dist-sdk/src/entities/shared/filters/print.js +2 -0
  68. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +8 -1
  69. package/dist-sdk/src/entities/shared/filters/tf-codec.js +10 -6
  70. package/dist-sdk/src/entities/shared/filters/types.d.ts +2 -1
  71. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +5 -0
  72. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +36 -23
  73. package/dist-sdk/src/entities/skill/module.js +1 -0
  74. package/dist-sdk/src/entities/skill/to-tf.d.ts +1 -1
  75. package/dist-sdk/src/entities/skill/to-tf.js +17 -0
  76. package/dist-sdk/src/entities/skill/tools.d.ts +38 -12
  77. package/dist-sdk/src/entities/skill/tools.js +2 -1
  78. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +8 -12
  79. package/dist-sdk/src/entities/skill-tool/from-tf.js +28 -44
  80. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +4 -0
  81. package/dist-sdk/src/entities/skill-tool/to-tf.js +45 -7
  82. package/dist-sdk/src/entities/table/build.js +10 -2
  83. package/dist-sdk/src/entities/view/to-tf.js +5 -7
  84. package/dist-sdk/src/entities/widget/build.d.ts +26 -0
  85. package/dist-sdk/src/entities/widget/from-tf.js +30 -5
  86. package/dist-sdk/src/entities/widget/to-tf.js +111 -7
  87. package/dist-sdk/src/graph/types.d.ts +5 -0
  88. package/package.json +1 -1
  89. package/dist-sdk/src/core/types/platform.d.ts +0 -2
  90. package/dist-sdk/src/core/types/platform.js +0 -1
@@ -1,13 +1,14 @@
1
1
  import { EntityTfError, recordFieldContextOf } from "../../engine/entity.js";
2
2
  import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET } from "../../core/system-fields.js";
3
3
  import { isUnsafePlatformId } from "../../core/platform-id.js";
4
- import { appResourceLabelPrefix, appScopedResourceLabel, expr, isTfExpr, isUuid, sanitizeName, scopedResourceLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
4
+ import { appResourceLabelPrefix, appScopedResourceLabel, expr, isTfExpr, isUuid, sanitizeName, scopedResourceLabel, tfLabelToTsLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
5
5
  import { workspaceAspectKey } from "../../engine/build/context.js";
6
6
  import { SEARCH_TABLE_RESOURCE_TYPES } from "../search-table/types.js";
7
7
  import { fieldRefToTfValue } from "../field/to-tf.js";
8
8
  import { SERVICE_ACCOUNT_RESOURCE_TYPE } from "../service-account/module.js";
9
9
  import { resolveForeignRef } from "../shared/foreign-ref.js";
10
10
  import { filterToTf as serializeFilterToTf } from "../shared/filters/tf-codec.js";
11
+ import { referenceValueTypeForField } from "../shared/filters/index.js";
11
12
  import { API_TASK_REF_AUTHORING_NAMES, API_TASK_REF_WIRE_NAMES } from "./output-key-wire-name.js";
12
13
  import { outputFieldTypesFromScriptSchema } from "./output-field-types.js";
13
14
  import { CONNECTOR_ORG_BAG } from "../org/connector.js";
@@ -122,7 +123,6 @@ const CONFIG_ATTRS = {
122
123
  thinkUi: "think_ui",
123
124
  conversationType: "conversation_type",
124
125
  customResponse: "custom_response",
125
- showTriggeredBy: "show_triggered_by",
126
126
  datamineId: "datamine_id",
127
127
  fireOnAlert: "fire_on_alert",
128
128
  fireOnRecovery: "fire_on_recovery",
@@ -210,6 +210,80 @@ function addressExpr(address, path = ["id"]) {
210
210
  throw new EntityTfError(`invalid terraform address "${address}"`);
211
211
  return expr.resourceAttr(address.slice(0, dot), address.slice(dot + 1), [...path]);
212
212
  }
213
+ function resolveColumnDisplayName(columnKey, displayNames) {
214
+ if (displayNames === undefined || displayNames.size === 0) {
215
+ return columnKey;
216
+ }
217
+ const exact = displayNames.get(columnKey);
218
+ if (exact !== undefined) {
219
+ return exact;
220
+ }
221
+ const lower = columnKey.toLowerCase();
222
+ for (const [k, v] of displayNames) {
223
+ if (k.toLowerCase() === lower) {
224
+ return v;
225
+ }
226
+ }
227
+ return columnKey;
228
+ }
229
+ function tableColumnNameOf(input) {
230
+ if (!isObject(input))
231
+ return undefined;
232
+ const col = input;
233
+ return col.cloud?.name ?? col.calculation?.name ?? col.reference?.name ?? input.name;
234
+ }
235
+ function extractTableColumnDisplayNames(sibling, extraNames) {
236
+ const displayNames = new Map();
237
+ if (sibling?.streamRootEntity?.payload !== undefined && isObject(sibling.streamRootEntity.payload)) {
238
+ const payload = sibling.streamRootEntity.payload;
239
+ const tableCols = isObject(payload.columns)
240
+ ? payload.columns
241
+ : undefined;
242
+ if (tableCols !== undefined) {
243
+ for (const [colKey, colInput] of Object.entries(tableCols)) {
244
+ if (isObject(colInput)) {
245
+ const name = tableColumnNameOf(colInput);
246
+ if (typeof name === "string" && name !== "") {
247
+ displayNames.set(colKey, name);
248
+ displayNames.set(tfLabelToTsLabel(sanitizeName(name)), name);
249
+ displayNames.set(name, name);
250
+ }
251
+ }
252
+ }
253
+ }
254
+ }
255
+ if (extraNames !== undefined && isObject(extraNames)) {
256
+ for (const [colKey, colName] of Object.entries(extraNames)) {
257
+ if (typeof colName === "string" && colName !== "") {
258
+ displayNames.set(colKey, colName);
259
+ displayNames.set(tfLabelToTsLabel(sanitizeName(colName)), colName);
260
+ displayNames.set(colName, colName);
261
+ }
262
+ }
263
+ }
264
+ return displayNames;
265
+ }
266
+ function resolveTableColumnFieldExpr(opts) {
267
+ const columnName = resolveColumnDisplayName(opts.columnKey, opts.columnDisplayNames);
268
+ const sibling = opts.workspaceAspects?.get(workspaceAspectKey("table", opts.tableRefName));
269
+ if (sibling !== undefined) {
270
+ return expr.resourceAttr(TABLE_RESOURCE_TYPE, sibling.tfLabel, ["field_ids", { index: columnName }]);
271
+ }
272
+ const label = tsLabelToTfLabel(opts.tableRefName);
273
+ const tableName = opts.tableName ?? opts.tableRefName;
274
+ if (opts.orgRefs !== undefined) {
275
+ opts.orgRefs.rawLookup(TABLE_RESOURCE_TYPE, label, tableName);
276
+ }
277
+ else {
278
+ opts.dataBlocks.set(`${TABLE_RESOURCE_TYPE}.${label}`, {
279
+ kind: "data",
280
+ type: TABLE_RESOURCE_TYPE,
281
+ label,
282
+ attrs: { name: tableName },
283
+ });
284
+ }
285
+ return expr.dataAttr(TABLE_RESOURCE_TYPE, label, ["field_ids", { index: columnName }]);
286
+ }
213
287
  /**
214
288
  * A field token whose `parent` names a DIFFERENT app/element than the one
215
289
  * this automation belongs to (e.g. a `recordSearch` task's filter against
@@ -616,29 +690,22 @@ function tokenToTf(value, ctx, dataBlocks) {
616
690
  }
617
691
  case "tableColumn": {
618
692
  // Columns are addressed by DISPLAY name in `field_ids`, never by bag key.
619
- const columnName = value.name ?? value.refName;
620
693
  const owner = value.parent;
621
694
  if (owner === undefined || owner === "") {
622
695
  throw new EntityTfError(`table column ref "${value.refName}" is missing its owning table`);
623
696
  }
624
697
  const sibling = ctx.workspaceAspects?.get(workspaceAspectKey("table", owner));
625
- if (sibling !== undefined) {
626
- return expr.resourceAttr(TABLE_RESOURCE_TYPE, sibling.tfLabel, ["field_ids", { index: columnName }]);
627
- }
628
- const tableName = value.parentName ?? owner;
629
- const label = tsLabelToTfLabel(owner);
630
- if (ctx.orgRefs !== undefined) {
631
- ctx.orgRefs.rawLookup(TABLE_RESOURCE_TYPE, label, tableName);
632
- }
633
- else {
634
- dataBlocks.set(`${TABLE_RESOURCE_TYPE}.${label}`, {
635
- kind: "data",
636
- type: TABLE_RESOURCE_TYPE,
637
- label,
638
- attrs: { name: tableName },
639
- });
640
- }
641
- return expr.dataAttr(TABLE_RESOURCE_TYPE, label, ["field_ids", { index: columnName }]);
698
+ const displayNames = extractTableColumnDisplayNames(sibling);
699
+ const rawColName = value.name ?? value.refName;
700
+ return resolveTableColumnFieldExpr({
701
+ tableRefName: owner,
702
+ tableName: value.parentName,
703
+ columnKey: rawColName,
704
+ columnDisplayNames: displayNames,
705
+ workspaceAspects: ctx.workspaceAspects,
706
+ orgRefs: ctx.orgRefs,
707
+ dataBlocks,
708
+ });
642
709
  }
643
710
  case "searchTable": {
644
711
  // Ownership + variant contract:
@@ -695,10 +762,18 @@ function tokenToTf(value, ctx, dataBlocks) {
695
762
  throw new EntityTfError(`search table "${owner}.${value.refName}" is owned by an aspect that is not part of this build — ` +
696
763
  `a foreign search-table reference has no data-source lookup yet`);
697
764
  }
698
- case "approvalChain":
699
- return value.unresolvedId !== undefined
700
- ? value.unresolvedId
701
- : expr.resourceAttr("elementum_approval_process", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
765
+ case "approvalChain": {
766
+ // Prefer a managed resource ref whenever refName is known. unresolvedId is
767
+ // a last-resort escape for tokens that never resolved to a catalog/import
768
+ // label (see ApprovalChainRef); preferring it rewrote live pulls to UUIDs.
769
+ const refName = typeof value.refName === "string" ? value.refName.trim() : "";
770
+ if (refName !== "") {
771
+ return expr.resourceAttr("elementum_approval_process", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(refName)), ["id"]);
772
+ }
773
+ if (value.unresolvedId !== undefined)
774
+ return value.unresolvedId;
775
+ throw new EntityTfError("approvalChain token has neither refName nor unresolvedId");
776
+ }
702
777
  case "documentModel": {
703
778
  const subType = FILE_READER_SUB_TYPE_BY_TYPE_KEY.get(value.readerType ?? "");
704
779
  // "xml"/"ai" are declared sub-types (FILE_READER_SUB_TYPES) but don't
@@ -1023,11 +1098,12 @@ const TS_TRIGGER_REF_TO_WIRE = {
1023
1098
  // onto FIELD_REF_SUFFIX_TO_WIRE — that table's `id` suffix is " ID", which
1024
1099
  // would emit the wrong wire key "Attachment ID" and fail live validation.
1025
1100
  "attachment.id": "Attachment Id",
1026
- "triggeredBy.id": "Triggered By's Id",
1027
- "triggeredBy.name": "Triggered By's Name",
1028
- "triggeredBy.email": "Triggered By's Email",
1029
- createdByEmail: "Created By Email",
1030
- updatedByManagerEmail: "Updated By Manager Email",
1101
+ // NOT createdByEmail/updatedByManagerEmail: the real record-field path
1102
+ // ("record.createdBy.email") never reaches this flat lookup table (see
1103
+ // from-tf.ts's matching comment) — this table is for genuine trigger-level
1104
+ // pseudo-fields only, keyed by the DIRECT ts accessor name, not a dotted
1105
+ // record path. The audit-email casing exception lives in
1106
+ // AUDIT_FIELD_EMAIL_WIRE_NAME, next to the code that actually builds it.
1031
1107
  slackThreadId: "Slack Thread ID",
1032
1108
  slackChannelId: "Slack Channel ID",
1033
1109
  messageAuthorEmail: "Message Author Email",
@@ -1036,6 +1112,10 @@ const TS_TRIGGER_REF_TO_WIRE = {
1036
1112
  messageContent: "Message Content",
1037
1113
  messageId: "Message ID",
1038
1114
  messageMetadata: "Message Metadata",
1115
+ sender_email: "Sender's Email Address",
1116
+ sender_name: "Sender's Name",
1117
+ body: "Body (Plain Text)",
1118
+ body_html: "Body (Rich Text)",
1039
1119
  };
1040
1120
  const DISPLAY_REF_CANONICAL_CASE = Object.fromEntries(Object.values(TS_TRIGGER_REF_TO_WIRE).map((value) => [value.toLowerCase(), value]));
1041
1121
  const FIELD_REF_SUFFIX_TO_WIRE = {
@@ -1060,6 +1140,13 @@ const FIELD_REF_SUFFIX_TO_WIRE = {
1060
1140
  "employee.manager.email": " Manager Email",
1061
1141
  "employee.manager.name": " Manager Name",
1062
1142
  };
1143
+ // Confirmed live on demoapptwo: the "...Email"/"...Manager Email" audit refs
1144
+ // lowercase "by", unlike every other audit-field ref suffix. Only these two
1145
+ // keys/suffixes are overridden; closedBy is not confirmed and is left alone.
1146
+ const AUDIT_FIELD_EMAIL_WIRE_NAME = {
1147
+ createdBy: "Created by",
1148
+ updatedBy: "Updated by",
1149
+ };
1063
1150
  const PROVIDER_FIXED_SYSTEM_FIELD_KEYS = new Set([
1064
1151
  "stage",
1065
1152
  "createdAt",
@@ -1092,11 +1179,14 @@ function wireRefName(name, ctx) {
1092
1179
  if (fieldKey.startsWith(UNRESOLVED_FIELD_MARKER)) {
1093
1180
  return `record.${fieldKey.slice(UNRESOLVED_FIELD_MARKER.length)}${parts.length > 2 ? `.${parts.slice(2).join(".")}` : ""}`;
1094
1181
  }
1095
- // System fields (title/status/stage/createdBy/...) have no entry in
1096
- // ctx.fieldNames - that map only carries the app's custom fields bag.
1097
- // Fall back to the provider's default display name for them; a renamed
1098
- // system field won't match and still throws below, same as an unknown
1099
- // custom field key would.
1182
+ // System fields are keyed in ctx.fieldNames under their canonical
1183
+ // SystemFieldKey (title/id/status/…) with the app's display name —
1184
+ // including systemFields renames ("App Name"). Provider-fixed audit
1185
+ // keys (stage/createdBy/…) have no rename attribute and always use
1186
+ // DEPLOY_DEFAULT. Renamable system fields prefer fieldNames; only
1187
+ // when the map lacks the key do we fall back to DEPLOY_DEFAULT (the
1188
+ // silent Title fallback that breaks cross-app findRelatedRecords when
1189
+ // the related app renamed title and the map missed the canonical key).
1100
1190
  const systemFieldKey = SYSTEM_FIELD_KEY_SET.has(fieldKey)
1101
1191
  ? fieldKey
1102
1192
  : undefined;
@@ -1115,8 +1205,15 @@ function wireRefName(name, ctx) {
1115
1205
  // Build must reproduce the live refs[] key's exact casing because the
1116
1206
  // Terraform map lookup is case-sensitive. The current provider emits
1117
1207
  // compound audit refs with the system field's display casing intact
1118
- // (for example "Created By ID").
1119
- return `${fieldName}${wireSuffix}`;
1208
+ // (for example "Created By ID") — EXCEPT the "...Email"/"...Manager
1209
+ // Email" audit refs, which lowercase "by" (confirmed live on
1210
+ // demoapptwo: "Created by Email", "Updated by Manager Email"). Only
1211
+ // override those two confirmed suffixes; every other suffix (and every
1212
+ // other system field) keeps the field's own display casing.
1213
+ const auditEmailName = systemFieldKey !== undefined && (wireSuffix === " Email" || wireSuffix === " Manager Email")
1214
+ ? AUDIT_FIELD_EMAIL_WIRE_NAME[systemFieldKey]
1215
+ : undefined;
1216
+ return `${auditEmailName ?? fieldName}${wireSuffix}`;
1120
1217
  }
1121
1218
  // A webhook trigger's body/headers refs (ctx.trigger.body["X"]) can only
1122
1219
  // type-check against DeepRefs<WebhookTriggerOutput>, so parts[0] being
@@ -1128,10 +1225,36 @@ function wireRefName(name, ctx) {
1128
1225
  const label = parts[0] === "body" ? "Body" : "Headers";
1129
1226
  return `${label} (${parts[1]})`;
1130
1227
  }
1228
+ // Bare system-field keys (title/id/…) must consult fieldNames for renames
1229
+ // — TS_REF_SEGMENT_TO_WIRE hard-codes "Title" and would ignore App Name.
1230
+ if (parts.length === 1 && SYSTEM_FIELD_KEY_SET.has(parts[0])) {
1231
+ return wireRefName(`record.${parts[0]}`, ctx);
1232
+ }
1131
1233
  parts[0] = TS_REF_SEGMENT_TO_WIRE[parts[0]] ?? parts[0];
1132
1234
  return parts.join(".");
1133
1235
  }
1134
- function forEachWireRefName(name, ctx) {
1236
+ /**
1237
+ * Task kinds whose collection output is a list of APP RECORDS. Only those
1238
+ * loops key their inner refs by field DISPLAY name; every other collection
1239
+ * (a file-reader payload, a script-built array, an API response, a nested
1240
+ * item sub-array) keys them by the item's OWN keys. Mirrors the builder's
1241
+ * `__recordApp` tagging (`RECORD_BEARING_TASK_KEYS` in build.ts) minus the
1242
+ * single-record producers, which cannot be looped over.
1243
+ */
1244
+ const RECORD_COLLECTION_TASK_WIRE_TYPES = new Set([
1245
+ "recordSearch",
1246
+ "findRelatedRecords",
1247
+ ]);
1248
+ /**
1249
+ * Loop-generic item keys the platform exposes whatever the collection holds.
1250
+ * Only `iteration` is both loop-generic and case-translated today - the rest
1251
+ * of `TS_REF_SEGMENT_TO_WIRE` is record/trigger-only and must not reach a
1252
+ * non-record item key (#952).
1253
+ */
1254
+ const TS_FOR_EACH_GENERIC_SEGMENT_TO_WIRE = {
1255
+ iteration: "Iteration",
1256
+ };
1257
+ function forEachWireRefName(name, ctx, isRecordCollection) {
1135
1258
  // A recordSearch collection's whole item and branded record identity both
1136
1259
  // point at the loop's ASPECT_RECORD_ID reference. Live provider state
1137
1260
  // exposes that reference under "Record"; "ID" is a distinct TEXT handle.
@@ -1139,8 +1262,27 @@ function forEachWireRefName(name, ctx) {
1139
1262
  return "Record";
1140
1263
  // Record fields are keyed by their platform display names, not their typed
1141
1264
  // catalog handles. Reuse the same field/suffix mapping as trigger record
1142
- // paths, while preserving the generic forEach keys used by non-record
1143
- // collections (File, Iteration, etc.).
1265
+ // paths.
1266
+ //
1267
+ // #952: this mapping is gated on the loop's COLLECTION being record-typed.
1268
+ // Applied unconditionally it rewrote a non-record item key to a field's
1269
+ // display name whenever the two happened to collide - a file-reader or
1270
+ // script payload keyed `currency` became `refs["Currency"]` in an app
1271
+ // declaring a "Currency" field - emitting an index the loop's refs map does
1272
+ // not contain. System-field keys (`id`, `title`, `status`, ...) tripped it
1273
+ // even in an app declaring no such field, and one bad index fails `tofu
1274
+ // plan` for the WHOLE org root.
1275
+ //
1276
+ // A non-record item is keyed by the payload's OWN keys, so it deliberately
1277
+ // does NOT fall through to `wireRefName`: that path also applies the
1278
+ // record/trigger segment tables (`id` -> "ID", `title` -> "Title",
1279
+ // `records` -> "All found records", the slack/message trigger keys), every
1280
+ // one of which is a plausible JSON key on a non-record item.
1281
+ if (!isRecordCollection) {
1282
+ const parts = name.split(".");
1283
+ parts[0] = TS_FOR_EACH_GENERIC_SEGMENT_TO_WIRE[parts[0]] ?? parts[0];
1284
+ return parts.join(".");
1285
+ }
1144
1286
  const fieldKey = name.split(".")[0];
1145
1287
  if (fieldKey !== undefined &&
1146
1288
  (ctx.fieldNames.has(fieldKey) || SYSTEM_FIELD_KEY_SET.has(fieldKey))) {
@@ -1163,13 +1305,81 @@ function normalizeIndexedRecordsFieldPath(name) {
1163
1305
  * app/element when known (cross-app recordSearch / createRecord / …), falling
1164
1306
  * back to the automation owner for non-record tasks and same-app searches.
1165
1307
  */
1308
+ function assertFindRelatedRecordsHasNoCountRef(targetType, name, taskRefKey) {
1309
+ if (targetType !== "elementum_find_related_records_task")
1310
+ return;
1311
+ const head = name.split(".")[0];
1312
+ if (head !== "totalCount" && head !== "Records Size" && head !== "count")
1313
+ return;
1314
+ throw new EntityTfError(`findRelatedRecords task "${taskRefKey}" does not expose totalCount. That output is recordSearch-only ` +
1315
+ `(platform refs["Records Size"]). Use ctx.actions.<recordSearchTask>.totalCount for a match count, ` +
1316
+ `or ctx.actions.${taskRefKey}.record / .records for related rows. Do not invent a count ref.`);
1317
+ }
1318
+ /**
1319
+ * Look up a related app/element's display-name map. Exact refName first;
1320
+ * case-insensitive fallback covers catalog/root key casing drift so a
1321
+ * renamed system title still resolves instead of silently becoming
1322
+ * DEPLOY_DEFAULT "Title".
1323
+ */
1324
+ function fieldNamesForAppRefName(map, appRefName) {
1325
+ if (map === undefined)
1326
+ return undefined;
1327
+ const exact = map.get(appRefName);
1328
+ if (exact !== undefined)
1329
+ return exact;
1330
+ const lower = appRefName.toLowerCase();
1331
+ for (const [key, value] of map) {
1332
+ if (key.toLowerCase() === lower)
1333
+ return value;
1334
+ }
1335
+ return undefined;
1336
+ }
1337
+ function taskTargetKind(taskRefKey, refs) {
1338
+ const fromCtx = refs.recordFieldContext?.taskAppKindByRefKey?.[taskRefKey];
1339
+ if (fromCtx !== undefined)
1340
+ return fromCtx;
1341
+ const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
1342
+ if (taskApp === undefined || taskApp === refs.owner.appRefName)
1343
+ return refs.owner.parentScope;
1344
+ if (refs.owner.workspaceAspects?.has(workspaceAspectKey("app", taskApp)))
1345
+ return "app";
1346
+ if (refs.owner.workspaceAspects?.has(workspaceAspectKey("element", taskApp)))
1347
+ return "element";
1348
+ return undefined;
1349
+ }
1350
+ /**
1351
+ * App-related findRelatedRecords no longer exposes system Title in its live
1352
+ * refs map (Cloud Builder plan: 95 keys, no "Title"). The parent identity
1353
+ * key is HANDLE. Authored / previously pulled `.record.title` must emit the
1354
+ * live HANDLE display name, not the stale `"Title"` label. Element-related
1355
+ * FIND_PARENT still uses Title.
1356
+ */
1357
+ function findRelatedRecordsAppTitleWireKey(name, taskRefKey, refs) {
1358
+ if (refs.tasks.get(taskRefKey)?.type !== "elementum_find_related_records_task")
1359
+ return undefined;
1360
+ if (taskTargetKind(taskRefKey, refs) !== "app")
1361
+ return undefined;
1362
+ const normalized = normalizeIndexedRecordsFieldPath(name);
1363
+ const field = normalized.startsWith("record.") ? normalized.slice("record.".length) : normalized;
1364
+ if (field !== "title" && field !== "Title")
1365
+ return undefined;
1366
+ const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
1367
+ const names = taskApp !== undefined && taskApp !== refs.owner.appRefName
1368
+ ? fieldNamesForAppRefName(refs.fieldNamesByAppRefName, taskApp)
1369
+ : refs.owner.fieldNames;
1370
+ return names?.get("id") ?? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES.id;
1371
+ }
1166
1372
  function taskWireRefName(name, taskRefKey, refs) {
1373
+ assertFindRelatedRecordsHasNoCountRef(refs.tasks.get(taskRefKey)?.type, name, taskRefKey);
1374
+ const handleKey = findRelatedRecordsAppTitleWireKey(name, taskRefKey, refs);
1375
+ if (handleKey !== undefined)
1376
+ return handleKey;
1167
1377
  const normalized = normalizeIndexedRecordsFieldPath(name);
1168
1378
  const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
1169
1379
  if (taskApp === undefined || taskApp === refs.owner.appRefName) {
1170
1380
  return wireRefName(normalized, refs.owner);
1171
1381
  }
1172
- const foreignNames = refs.fieldNamesByAppRefName?.get(taskApp);
1382
+ const foreignNames = fieldNamesForAppRefName(refs.fieldNamesByAppRefName, taskApp);
1173
1383
  return wireRefName(normalized, {
1174
1384
  ...refs.owner,
1175
1385
  appRefName: taskApp,
@@ -1191,6 +1401,7 @@ function taskWireRefName(name, taskRefKey, refs) {
1191
1401
  * "Invalid index" error. Their field names pass through verbatim.
1192
1402
  */
1193
1403
  function taskOutputWireRefKey(targetType, name, taskRefKey, refs) {
1404
+ assertFindRelatedRecordsHasNoCountRef(targetType, name, taskRefKey);
1194
1405
  if (targetType === "elementum_ai_file_read_task" || targetType === "elementum_file_reader_task")
1195
1406
  return name;
1196
1407
  if (targetType === "elementum_ai_agent_task")
@@ -1237,7 +1448,7 @@ function recordParamFieldWireName(paramName, suffix, refs) {
1237
1448
  const targetRefName = target.refName;
1238
1449
  const targetFieldNames = targetRefName === refs.owner.appRefName && target.__kind === refs.owner.parentScope
1239
1450
  ? refs.owner.fieldNames
1240
- : refs.fieldNamesByAppRefName?.get(targetRefName);
1451
+ : fieldNamesForAppRefName(refs.fieldNamesByAppRefName, targetRefName);
1241
1452
  return wireRefName(`record.${suffix}`, {
1242
1453
  ...refs.owner,
1243
1454
  appRefName: targetRefName,
@@ -1274,6 +1485,44 @@ function workflowPublishOutputValueToTf(value, refs) {
1274
1485
  }
1275
1486
  return valueToTf(value, refs);
1276
1487
  }
1488
+ /**
1489
+ * A `createRecord` task's own output record's field, embedded as a LIVE
1490
+ * field resource `.id` reference instead of a resolved display name.
1491
+ * Confirmed live (demoapptwo, #1066): the platform stores this specific
1492
+ * reference shape as `"record.<field-platform-id>.<suffix>"` — the SAME raw
1493
+ * form the unresolved-field escape hatch above already reproduces for a
1494
+ * field EDK can't resolve AT ALL — even though this field genuinely
1495
+ * resolves. Unlike a TRIGGER's record (`wireRefName`, fixed for the
1496
+ * audit-email casing in #1062), the platform never re-derives a
1497
+ * display-name form for a task's own JUST-CREATED record; a fresh `ei`
1498
+ * export of this exact automation still has the raw id form, so building
1499
+ * the resolved-name string here is not one-time drift, it is simply wrong.
1500
+ *
1501
+ * `expr.template` gives the field's CURRENT id at plan/apply time (same
1502
+ * pattern as `taskId`/`variableReference.name` just below), so this stays
1503
+ * correct even across a field id change, unlike a literal string would.
1504
+ *
1505
+ * Scoped to createRecord and to the SAME app as the automation owner — the
1506
+ * only case confirmed live. A cross-app createRecord output, or a
1507
+ * recordSearch/findRelatedRecords field access on an EXISTING (not
1508
+ * just-created) record, is left on the existing display-name path until
1509
+ * confirmed either way; returning `undefined` here falls through to it.
1510
+ */
1511
+ function createRecordOwnFieldRefTfValue(target, name, refs) {
1512
+ if (target?.type !== "elementum_create_record_task")
1513
+ return undefined;
1514
+ const match = /^record\.([^.]+)\.(.+)$/.exec(name);
1515
+ if (match === null)
1516
+ return undefined;
1517
+ const [, fieldKey, suffix] = match;
1518
+ const fieldType = refs.owner.fieldMetadata.get(fieldKey)?.fieldType;
1519
+ if (fieldType === undefined)
1520
+ return undefined;
1521
+ const fieldId = fieldRefToTfValue(fieldType, fieldKey, refs.owner.appTfLabel, refs.owner.parentScope, refs.owner.fieldAddresses);
1522
+ if (fieldId === undefined)
1523
+ return undefined;
1524
+ return expr.template(["record.", fieldId, `.${suffix}`]);
1525
+ }
1277
1526
  function workflowPublishOutputEnvelope(value, refs) {
1278
1527
  if (!isObject(value))
1279
1528
  return undefined;
@@ -1299,9 +1548,10 @@ function workflowPublishOutputEnvelope(value, refs) {
1299
1548
  ? "All matching table rows"
1300
1549
  : "records"
1301
1550
  : taskWireRefName(value.taskReference.name, value.taskReference.taskRefKey, refs);
1302
- const platformRefName = isAiAgentTask
1551
+ const ownRecordFieldRef = createRecordOwnFieldRefTfValue(target, value.taskReference.name, refs);
1552
+ const platformRefName = ownRecordFieldRef ?? (isAiAgentTask
1303
1553
  ? aiAgentPlatformRefName(refsKey)
1304
- : refsKey;
1554
+ : refsKey);
1305
1555
  const typed = publishOutputType(value, target, refsKey);
1306
1556
  return {
1307
1557
  fieldType: typed.fieldType,
@@ -1446,7 +1696,8 @@ function valueToTf(value, refs) {
1446
1696
  const target = refs.tasks.get(value.forEachReference.forEachTaskRefKey);
1447
1697
  if (target === undefined)
1448
1698
  throw new EntityTfError(`unresolved forEach ref "${value.forEachReference.forEachTaskRefKey}"`);
1449
- return expr.resourceAttr(target.type, target.label, ["inner", "refs", { index: forEachWireRefName(value.forEachReference.name, refs.owner) }]);
1699
+ const index = forEachWireRefName(value.forEachReference.name, refs.owner, refs.recordItemForEachRefKeys.has(value.forEachReference.forEachTaskRefKey));
1700
+ return expr.resourceAttr(target.type, target.label, ["inner", "refs", { index }]);
1450
1701
  }
1451
1702
  if (isObject(value.templateReference))
1452
1703
  return templateToTf(value.templateReference, refs);
@@ -1475,7 +1726,7 @@ function unwrapDefault(value) {
1475
1726
  const values = Object.values(value);
1476
1727
  return values.length === 1 ? values[0] : value;
1477
1728
  }
1478
- function filterReferenceToTf(value, refs, role = "value", realType) {
1729
+ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1479
1730
  // Raw pass-through for a filter left side the pull-time deserializer
1480
1731
  // couldn't decode to a typed ref (filter.ts's leftDescriptor, matching the
1481
1732
  // UNRESOLVED_REFERENCE_MARKER case) - reproduces the original value_reference
@@ -1499,22 +1750,43 @@ function filterReferenceToTf(value, refs, role = "value", realType) {
1499
1750
  const fieldKey = parts[1];
1500
1751
  const address = refs.owner.fieldAddresses.get(fieldKey);
1501
1752
  const suffix = parts.slice(2).join(".");
1502
- const wireSuffix = suffix === "recordId" ? "10000001-2000-4000-a000-800000000000" : suffix;
1753
+ let wireSuffix = suffix === "recordId" ? "10000001-2000-4000-a000-800000000000" : suffix;
1503
1754
  // A bare reference to a PICKLIST field (STATUS/STAGE included —
1504
1755
  // `serializeSystemFields` wire-wraps both as a picklist too) has no
1505
1756
  // valid suffix-less wire form — confirmed live via the platform's
1506
1757
  // own switch-case editor, which always sends an explicit `.id`
1507
1758
  // (compare by the chosen option's real id) or `.label` (compare by
1508
1759
  // display text, unvalidated) and never a bare `record.<fieldId>`.
1509
- // Force the author to say which one they mean rather than guessing:
1510
- // a silent default reads as correct right up until the platform
1511
- // evaluates the two conventions differently, and there is no
1512
- // apply-time signal to catch that (the wire string is opaque to
1513
- // the provider).
1760
+ // Comparisons stay ambiguous (eq/in/…). Null-checks are equivalent
1761
+ // for `.id` and `.label` when no option is selected, so
1762
+ // `isNull`/`isNotNull` on a bare Dropdown emit the platform editor's
1763
+ // `.id` + uuid shape — the Accept `isNotNull(record.dropdown)` form.
1514
1764
  if (suffix.length === 0 && refs.owner.fieldMetadata.get(fieldKey)?.fieldType === "PICKLIST") {
1515
- throw new EntityTfError(`filter reference to picklist field "${fieldKey}" is ambiguous — write ".id" ` +
1516
- `(ctx.trigger.record.${fieldKey}.id, compare by the option's id) or ".label" ` +
1517
- `(ctx.trigger.record.${fieldKey}.label, compare by display text) explicitly.`);
1765
+ if (operator === "is_null") {
1766
+ wireSuffix = "id";
1767
+ }
1768
+ else {
1769
+ throw new EntityTfError(`filter reference to picklist field "${fieldKey}" is ambiguous — write ".id" ` +
1770
+ `(ctx.trigger.record.${fieldKey}.id, compare by the option's id) or ".label" ` +
1771
+ `(ctx.trigger.record.${fieldKey}.label, compare by display text) explicitly.`);
1772
+ }
1773
+ }
1774
+ if (refs.trigger.type === TRIGGER_RESOURCES.datamine && refs.triggerDatamineTable !== undefined) {
1775
+ const table = refs.triggerDatamineTable;
1776
+ const tableAttr = resolveTableColumnFieldExpr({
1777
+ tableRefName: table.tableRefName,
1778
+ tableName: table.tableName,
1779
+ columnKey: fieldKey,
1780
+ columnDisplayNames: table.columnDisplayNames,
1781
+ workspaceAspects: refs.owner.workspaceAspects,
1782
+ orgRefs: refs.owner.orgRefs,
1783
+ dataBlocks: refs.dataBlocks,
1784
+ });
1785
+ return expr.template([
1786
+ "trigger.record.",
1787
+ tableAttr,
1788
+ ...(wireSuffix.length > 0 ? [`.${wireSuffix}`] : []),
1789
+ ]);
1518
1790
  }
1519
1791
  if (address !== undefined) {
1520
1792
  return expr.template([
@@ -1613,10 +1885,29 @@ function filterReferenceToTf(value, refs, role = "value", realType) {
1613
1885
  const task = refs.tasks.get(value.forEachTaskRefKey);
1614
1886
  if (task === undefined)
1615
1887
  throw new EntityTfError(`unresolved forEach filter ref "${value.forEachTaskRefKey}"`);
1616
- return expr.resourceAttr(task.type, task.label, ["inner", "refs", { index: forEachWireRefName(value.name, refs.owner) }]);
1888
+ const index = forEachWireRefName(value.name, refs.owner, refs.recordItemForEachRefKeys.has(value.forEachTaskRefKey));
1889
+ return expr.resourceAttr(task.type, task.label, ["inner", "refs", { index }]);
1617
1890
  }
1618
1891
  case "VALUE":
1619
1892
  return valueToTf(value.value, refs);
1893
+ case "VARIABLE": {
1894
+ // Build finalize (resolveVariableParamMarkers) resolves the authored
1895
+ // variableTaskRefKey to this build's minted `variable.create` id, which
1896
+ // keys `variableById` → the owning `elementum_variable_task`. ei encodes a
1897
+ // variable filter value as `variable.<uuid>` (live-captured, #1045) in both
1898
+ // the value (recordSearch RHS) and left_value (switch) slots.
1899
+ //
1900
+ // INTERPOLATE the live `variable_id`, never bake in the minted id: the
1901
+ // client-minted uuid is never the variable's deploy-time platform id, so a
1902
+ // literal always mismatches live state on the very next plan (identical
1903
+ // reasoning to the ordinary variableReference path above). The template
1904
+ // resolves to `variable.<live variable_id>`, byte-identical to ei's export.
1905
+ const target = typeof value.variableId === "string" ? refs.variableById.get(value.variableId) : undefined;
1906
+ if (target === undefined) {
1907
+ throw new EntityTfError("variable filter reference could not be resolved to a variable task — the referenced workflow variable must be created by a setVariable task in the same automation");
1908
+ }
1909
+ return expr.template(["variable.", expr.resourceAttr(target.type, target.label, ["variable_id"])]);
1910
+ }
1620
1911
  default:
1621
1912
  throw new EntityTfError(`unsupported filter reference type "${value.type}"`);
1622
1913
  }
@@ -1694,24 +1985,28 @@ function picklistFilterValueToTf(value, field, refs) {
1694
1985
  : `${scopedLabel(refs.owner.appTfLabel, tsLabelToTfLabel(field.refName))}_options_by_label`;
1695
1986
  return expr.local(localName, [{ index: value }]);
1696
1987
  }
1988
+ function triggerRecordFieldPath(reference) {
1989
+ if (!isObject(reference) || typeof reference.name !== "string")
1990
+ return undefined;
1991
+ const path = reference.name.split(".");
1992
+ if (path[0] !== "record" || path.length < 2)
1993
+ return undefined;
1994
+ return { fieldKey: path[1], suffix: path.slice(2).join(".") };
1995
+ }
1697
1996
  function fieldFromFilterLeftValue(value, refs) {
1698
1997
  if (!isObject(value) || !isObject(value.value) || value.value.type?.toString().toUpperCase() !== "TRIGGER") {
1699
1998
  return undefined;
1700
1999
  }
1701
- const name = value.value.name;
1702
- if (typeof name !== "string")
1703
- return undefined;
1704
- const path = name.split(".");
1705
- if (path[0] !== "record" || path.length < 2)
2000
+ const parsed = triggerRecordFieldPath(value.value);
2001
+ if (parsed === undefined)
1706
2002
  return undefined;
1707
- const refName = path[1];
2003
+ const { fieldKey: refName, suffix } = parsed;
1708
2004
  // Option-id resolution (picklistFilterValueToTf) only applies to the
1709
2005
  // ".id" convention `filterReferenceToTf` now requires for a picklist
1710
2006
  // field — an explicit ".label" (or any other drill-down suffix, e.g. a
1711
2007
  // USER field's ".email") compares raw text/whatever that sub-property
1712
2008
  // actually is, and must NOT have its value silently rewritten through
1713
2009
  // the options-by-label local.
1714
- const suffix = path.slice(2).join(".");
1715
2010
  if (suffix !== "" && suffix !== "id")
1716
2011
  return undefined;
1717
2012
  const metadata = refs.owner.fieldMetadata.get(refName);
@@ -1723,7 +2018,23 @@ function filterToTf(value, refs) {
1723
2018
  return serializeFilterToTf(value, {
1724
2019
  field: (field) => valueToTf(field, refs),
1725
2020
  fieldFromLeftValue: (left) => fieldFromFilterLeftValue(left, refs),
1726
- reference: (reference, role, realType) => filterReferenceToTf(reference, refs, role ?? "value", realType),
2021
+ reference: (reference, role, realType, operator) => filterReferenceToTf(reference, refs, role ?? "value", realType, operator),
2022
+ referenceRealType: (reference, _role, authored) => {
2023
+ const parsed = triggerRecordFieldPath(reference);
2024
+ if (parsed === undefined)
2025
+ return authored;
2026
+ const metadata = refs.owner.fieldMetadata.get(parsed.fieldKey);
2027
+ const inferred = referenceValueTypeForField(metadata?.fieldType, parsed.suffix);
2028
+ if (inferred === undefined)
2029
+ return authored;
2030
+ // Operator fallbacks and `filter.text()` are TEXT. Field metadata is
2031
+ // the authority for a known trigger-record field (PICKLIST .id → UUID).
2032
+ // Explicit non-TEXT wrappers (`filter.uuid()`, `filter.number()`, …) win.
2033
+ const authoredNorm = authored?.toUpperCase();
2034
+ if (authoredNorm !== undefined && authoredNorm !== "TEXT")
2035
+ return authored;
2036
+ return inferred;
2037
+ },
1727
2038
  literal: (literal, field) => picklistFilterValueToTf(literal, token(field), refs) ?? valueToTf(literal, refs),
1728
2039
  });
1729
2040
  }
@@ -1864,8 +2175,23 @@ function configAttrs(kind, config, refs) {
1864
2175
  };
1865
2176
  });
1866
2177
  }
2178
+ else if (isObject(raw.dynamic)) {
2179
+ const dynamic = raw.dynamic;
2180
+ if (dynamic.aspectId === undefined || dynamic.labelFieldId === undefined) {
2181
+ throw new EntityTfError("dynamic classification category source requires aspectId and labelFieldId");
2182
+ }
2183
+ attrs.dynamic_category_source = {
2184
+ object_id: valueToTf(dynamic.aspectId, refs),
2185
+ label_field_id: valueToTf(dynamic.labelFieldId, refs),
2186
+ ...(dynamic.descriptionFieldId !== undefined
2187
+ ? { description_field_id: valueToTf(dynamic.descriptionFieldId, refs) }
2188
+ : {}),
2189
+ ...(dynamic.filter !== undefined ? { filter: filterToTf(dynamic.filter, refs) } : {}),
2190
+ ...(typeof dynamic.limit === "number" ? { limit: dynamic.limit } : {}),
2191
+ };
2192
+ }
1867
2193
  else {
1868
- attrs.category_source = valueToTf(raw, refs);
2194
+ throw new EntityTfError("classification category source must be static or dynamic");
1869
2195
  }
1870
2196
  continue;
1871
2197
  }
@@ -2002,6 +2328,17 @@ function configAttrs(kind, config, refs) {
2002
2328
  const staticValue = isObject(field.valueReference) && "value" in field.valueReference
2003
2329
  ? field.valueReference.value
2004
2330
  : undefined;
2331
+ // Empty string / null is the platform clear payload for a field
2332
+ // assignment (TEXT already used ""; picklists must not resolve ""
2333
+ // through options_by_label). The provider value attribute is a
2334
+ // required string, so emit "" rather than HCL null.
2335
+ if (staticValue === "" || staticValue === null) {
2336
+ return {
2337
+ field_id: valueToTf(field.aspectFieldId, refs),
2338
+ value: fieldToken?.fieldType === "MULTI_PICKLIST" ? expr.jsonencode([]) : "",
2339
+ ...(field.operation === "ADD" ? { update_mode: "add" } : {}),
2340
+ };
2341
+ }
2005
2342
  if (Array.isArray(staticValue)) {
2006
2343
  if (fieldToken?.fieldType !== "MULTI_PICKLIST") {
2007
2344
  throw new EntityTfError(`automation field "${fieldToken?.name ?? fieldToken?.refName ?? "unknown"}" uses an array value but is not a Multi-Select field`);
@@ -2244,6 +2581,12 @@ export function automationToTf(entity, ctx) {
2244
2581
  const taskRefs = new Map();
2245
2582
  const variableById = new Map();
2246
2583
  const usedLabels = new Map(); // tf label → the refKey that claimed it
2584
+ // #952: a forEach's inner-ref keying depends on WHAT it loops over. Collect
2585
+ // each task's wire type and each loop's collection here, then resolve once
2586
+ // the walk is complete - a loop's own refKey is registered before the tasks
2587
+ // nested inside it, so the collection's producer is not reliably known yet.
2588
+ const wireTypeByRefKey = new Map();
2589
+ const forEachCollectionByRefKey = new Map();
2247
2590
  const preRegister = (tasks) => {
2248
2591
  for (const task of tasks) {
2249
2592
  const refKey = task.refKey;
@@ -2252,6 +2595,9 @@ export function automationToTf(entity, ctx) {
2252
2595
  if (taskRefs.has(refKey))
2253
2596
  throw new EntityTfError(`duplicate task refKey "${refKey}"`);
2254
2597
  const [wireType, taskBody] = onlyEntry(task.task, "task " + refKey);
2598
+ wireTypeByRefKey.set(refKey, wireType);
2599
+ if (wireType === "forEach")
2600
+ forEachCollectionByRefKey.set(refKey, taskBody.forEach);
2255
2601
  const resourceType = wireType === "variable" ? variableTaskResourceType(taskBody, refKey) : TASK_RESOURCES[wireType];
2256
2602
  if (resourceType === undefined)
2257
2603
  throw new EntityTfError(`task type "${wireType}" is not supported by the provider HCL contract`);
@@ -2289,6 +2635,21 @@ export function automationToTf(entity, ctx) {
2289
2635
  }
2290
2636
  };
2291
2637
  preRegister(payload.tasks ?? []);
2638
+ // A collection is record-typed only when it reads a record-collection task's
2639
+ // output. Everything else - a script array, a file-reader payload, an API
2640
+ // response, a variable, a nested item sub-array - keys its items by their
2641
+ // own keys, so their names pass through untouched.
2642
+ const recordItemForEachRefKeys = new Set([...forEachCollectionByRefKey].flatMap(([refKey, collection]) => {
2643
+ if (!isObject(collection) || !isObject(collection.taskReference))
2644
+ return [];
2645
+ const sourceRefKey = collection.taskReference.taskRefKey;
2646
+ if (typeof sourceRefKey !== "string")
2647
+ return [];
2648
+ const sourceWireType = wireTypeByRefKey.get(sourceRefKey);
2649
+ return sourceWireType !== undefined && RECORD_COLLECTION_TASK_WIRE_TYPES.has(sourceWireType)
2650
+ ? [refKey]
2651
+ : [];
2652
+ }));
2292
2653
  const dataBlocks = new Map();
2293
2654
  const recordFieldContext = recordFieldContextOf(entity);
2294
2655
  const triggerParamNames = triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
@@ -2311,6 +2672,22 @@ export function automationToTf(entity, ctx) {
2311
2672
  : [];
2312
2673
  })
2313
2674
  : []);
2675
+ let triggerDatamineTable;
2676
+ if (triggerKey === "datamine" && isObject(triggerConfig)) {
2677
+ const rawDatamine = triggerConfig.datamineId ?? triggerConfig.datamine ?? triggerConfig.datamine_id;
2678
+ const datamine = token(rawDatamine);
2679
+ if (datamine !== undefined && datamine.__kind === "datamine" && typeof datamine.parent === "string" && datamine.parent !== "") {
2680
+ const tableRefName = datamine.parent;
2681
+ const sibling = ctx.workspaceAspects?.get(workspaceAspectKey("table", tableRefName));
2682
+ const tableName = datamine.parentName ?? sibling?.streamRootEntity?.payload?.name ?? tableRefName;
2683
+ const columnDisplayNames = extractTableColumnDisplayNames(sibling, datamine.columnNames);
2684
+ triggerDatamineTable = {
2685
+ tableRefName,
2686
+ tableName,
2687
+ ...(columnDisplayNames.size > 0 ? { columnDisplayNames } : {}),
2688
+ };
2689
+ }
2690
+ }
2314
2691
  const refs = {
2315
2692
  trigger: { type: triggerType, label },
2316
2693
  triggerParamNames,
@@ -2320,10 +2697,12 @@ export function automationToTf(entity, ctx) {
2320
2697
  owner,
2321
2698
  dataBlocks,
2322
2699
  variableById,
2700
+ recordItemForEachRefKeys,
2323
2701
  ...(recordFieldContext !== undefined ? { recordFieldContext } : {}),
2324
2702
  ...(ctx.fieldNamesByAppRefName !== undefined ? { fieldNamesByAppRefName: ctx.fieldNamesByAppRefName } : {}),
2325
2703
  ...(ctx.fieldAddressesByAppRefName !== undefined ? { fieldAddressesByAppRefName: ctx.fieldAddressesByAppRefName } : {}),
2326
2704
  ...(ctx.allowUnknownPicklistOptions === true ? { allowUnknownPicklistOptions: true } : {}),
2705
+ ...(triggerDatamineTable !== undefined ? { triggerDatamineTable } : {}),
2327
2706
  };
2328
2707
  let triggerAttrs;
2329
2708
  try {