@elementumai/edk 0.9.11 → 0.9.12

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 (89) 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 +119 -0
  15. package/dist-sdk/src/engine/progress.js +647 -0
  16. package/dist-sdk/src/engine/pull/result-output.d.ts +24 -0
  17. package/dist-sdk/src/engine/pull/result-output.js +48 -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 +38 -8
  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 +239 -34
  28. package/dist-sdk/src/entities/automation/from-tf.js +168 -23
  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/tasks.d.ts +60 -28
  35. package/dist-sdk/src/entities/automation/tasks.js +31 -15
  36. package/dist-sdk/src/entities/automation/to-tf.js +362 -58
  37. package/dist-sdk/src/entities/automation/triggers.d.ts +15 -9
  38. package/dist-sdk/src/entities/automation/triggers.js +4 -2
  39. package/dist-sdk/src/entities/chart/build.d.ts +15 -3
  40. package/dist-sdk/src/entities/chart/build.js +6 -1
  41. package/dist-sdk/src/entities/chart/from-tf.d.ts +8 -2
  42. package/dist-sdk/src/entities/chart/from-tf.js +71 -8
  43. package/dist-sdk/src/entities/chart/index.d.ts +1 -1
  44. package/dist-sdk/src/entities/chart/index.js +1 -1
  45. package/dist-sdk/src/entities/chart/printer.js +27 -7
  46. package/dist-sdk/src/entities/chart/to-tf.js +56 -2
  47. package/dist-sdk/src/entities/datamine/from-tf.js +11 -1
  48. package/dist-sdk/src/entities/element/build.d.ts +6 -5
  49. package/dist-sdk/src/entities/element/from-tf.js +3 -2
  50. package/dist-sdk/src/entities/element/module.js +1 -0
  51. package/dist-sdk/src/entities/element/to-tf.d.ts +3 -0
  52. package/dist-sdk/src/entities/element/to-tf.js +9 -1
  53. package/dist-sdk/src/entities/field/from-tf.d.ts +24 -0
  54. package/dist-sdk/src/entities/field/from-tf.js +73 -1
  55. package/dist-sdk/src/entities/field/metadata.d.ts +18 -0
  56. package/dist-sdk/src/entities/field/metadata.js +34 -0
  57. package/dist-sdk/src/entities/relationship/build.d.ts +17 -6
  58. package/dist-sdk/src/entities/relationship/column-contract.d.ts +24 -0
  59. package/dist-sdk/src/entities/relationship/column-contract.js +41 -0
  60. package/dist-sdk/src/entities/relationship/from-tf.js +19 -34
  61. package/dist-sdk/src/entities/relationship/to-tf.js +15 -2
  62. package/dist-sdk/src/entities/shared/context.d.ts +6 -3
  63. package/dist-sdk/src/entities/shared/context.js +19 -1
  64. package/dist-sdk/src/entities/shared/filters/index.d.ts +7 -0
  65. package/dist-sdk/src/entities/shared/filters/index.js +28 -0
  66. package/dist-sdk/src/entities/shared/filters/print.js +2 -0
  67. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +8 -1
  68. package/dist-sdk/src/entities/shared/filters/tf-codec.js +10 -6
  69. package/dist-sdk/src/entities/shared/filters/types.d.ts +1 -1
  70. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +5 -0
  71. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +36 -23
  72. package/dist-sdk/src/entities/skill/module.js +1 -0
  73. package/dist-sdk/src/entities/skill/to-tf.d.ts +1 -1
  74. package/dist-sdk/src/entities/skill/to-tf.js +17 -0
  75. package/dist-sdk/src/entities/skill/tools.d.ts +38 -12
  76. package/dist-sdk/src/entities/skill/tools.js +2 -1
  77. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +8 -12
  78. package/dist-sdk/src/entities/skill-tool/from-tf.js +28 -44
  79. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +4 -0
  80. package/dist-sdk/src/entities/skill-tool/to-tf.js +45 -7
  81. package/dist-sdk/src/entities/table/build.js +10 -2
  82. package/dist-sdk/src/entities/view/to-tf.js +5 -7
  83. package/dist-sdk/src/entities/widget/build.d.ts +26 -0
  84. package/dist-sdk/src/entities/widget/from-tf.js +30 -5
  85. package/dist-sdk/src/entities/widget/to-tf.js +111 -7
  86. package/dist-sdk/src/graph/types.d.ts +5 -0
  87. package/package.json +1 -1
  88. package/dist-sdk/src/core/types/platform.d.ts +0 -2
  89. 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,9 +1098,6 @@ 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
1101
  createdByEmail: "Created By Email",
1030
1102
  updatedByManagerEmail: "Updated By Manager Email",
1031
1103
  slackThreadId: "Slack Thread ID",
@@ -1036,6 +1108,10 @@ const TS_TRIGGER_REF_TO_WIRE = {
1036
1108
  messageContent: "Message Content",
1037
1109
  messageId: "Message ID",
1038
1110
  messageMetadata: "Message Metadata",
1111
+ sender_email: "Sender's Email Address",
1112
+ sender_name: "Sender's Name",
1113
+ body: "Body (Plain Text)",
1114
+ body_html: "Body (Rich Text)",
1039
1115
  };
1040
1116
  const DISPLAY_REF_CANONICAL_CASE = Object.fromEntries(Object.values(TS_TRIGGER_REF_TO_WIRE).map((value) => [value.toLowerCase(), value]));
1041
1117
  const FIELD_REF_SUFFIX_TO_WIRE = {
@@ -1092,11 +1168,14 @@ function wireRefName(name, ctx) {
1092
1168
  if (fieldKey.startsWith(UNRESOLVED_FIELD_MARKER)) {
1093
1169
  return `record.${fieldKey.slice(UNRESOLVED_FIELD_MARKER.length)}${parts.length > 2 ? `.${parts.slice(2).join(".")}` : ""}`;
1094
1170
  }
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.
1171
+ // System fields are keyed in ctx.fieldNames under their canonical
1172
+ // SystemFieldKey (title/id/status/…) with the app's display name —
1173
+ // including systemFields renames ("App Name"). Provider-fixed audit
1174
+ // keys (stage/createdBy/…) have no rename attribute and always use
1175
+ // DEPLOY_DEFAULT. Renamable system fields prefer fieldNames; only
1176
+ // when the map lacks the key do we fall back to DEPLOY_DEFAULT (the
1177
+ // silent Title fallback that breaks cross-app findRelatedRecords when
1178
+ // the related app renamed title and the map missed the canonical key).
1100
1179
  const systemFieldKey = SYSTEM_FIELD_KEY_SET.has(fieldKey)
1101
1180
  ? fieldKey
1102
1181
  : undefined;
@@ -1128,10 +1207,36 @@ function wireRefName(name, ctx) {
1128
1207
  const label = parts[0] === "body" ? "Body" : "Headers";
1129
1208
  return `${label} (${parts[1]})`;
1130
1209
  }
1210
+ // Bare system-field keys (title/id/…) must consult fieldNames for renames
1211
+ // — TS_REF_SEGMENT_TO_WIRE hard-codes "Title" and would ignore App Name.
1212
+ if (parts.length === 1 && SYSTEM_FIELD_KEY_SET.has(parts[0])) {
1213
+ return wireRefName(`record.${parts[0]}`, ctx);
1214
+ }
1131
1215
  parts[0] = TS_REF_SEGMENT_TO_WIRE[parts[0]] ?? parts[0];
1132
1216
  return parts.join(".");
1133
1217
  }
1134
- function forEachWireRefName(name, ctx) {
1218
+ /**
1219
+ * Task kinds whose collection output is a list of APP RECORDS. Only those
1220
+ * loops key their inner refs by field DISPLAY name; every other collection
1221
+ * (a file-reader payload, a script-built array, an API response, a nested
1222
+ * item sub-array) keys them by the item's OWN keys. Mirrors the builder's
1223
+ * `__recordApp` tagging (`RECORD_BEARING_TASK_KEYS` in build.ts) minus the
1224
+ * single-record producers, which cannot be looped over.
1225
+ */
1226
+ const RECORD_COLLECTION_TASK_WIRE_TYPES = new Set([
1227
+ "recordSearch",
1228
+ "findRelatedRecords",
1229
+ ]);
1230
+ /**
1231
+ * Loop-generic item keys the platform exposes whatever the collection holds.
1232
+ * Only `iteration` is both loop-generic and case-translated today - the rest
1233
+ * of `TS_REF_SEGMENT_TO_WIRE` is record/trigger-only and must not reach a
1234
+ * non-record item key (#952).
1235
+ */
1236
+ const TS_FOR_EACH_GENERIC_SEGMENT_TO_WIRE = {
1237
+ iteration: "Iteration",
1238
+ };
1239
+ function forEachWireRefName(name, ctx, isRecordCollection) {
1135
1240
  // A recordSearch collection's whole item and branded record identity both
1136
1241
  // point at the loop's ASPECT_RECORD_ID reference. Live provider state
1137
1242
  // exposes that reference under "Record"; "ID" is a distinct TEXT handle.
@@ -1139,8 +1244,27 @@ function forEachWireRefName(name, ctx) {
1139
1244
  return "Record";
1140
1245
  // Record fields are keyed by their platform display names, not their typed
1141
1246
  // 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.).
1247
+ // paths.
1248
+ //
1249
+ // #952: this mapping is gated on the loop's COLLECTION being record-typed.
1250
+ // Applied unconditionally it rewrote a non-record item key to a field's
1251
+ // display name whenever the two happened to collide - a file-reader or
1252
+ // script payload keyed `currency` became `refs["Currency"]` in an app
1253
+ // declaring a "Currency" field - emitting an index the loop's refs map does
1254
+ // not contain. System-field keys (`id`, `title`, `status`, ...) tripped it
1255
+ // even in an app declaring no such field, and one bad index fails `tofu
1256
+ // plan` for the WHOLE org root.
1257
+ //
1258
+ // A non-record item is keyed by the payload's OWN keys, so it deliberately
1259
+ // does NOT fall through to `wireRefName`: that path also applies the
1260
+ // record/trigger segment tables (`id` -> "ID", `title` -> "Title",
1261
+ // `records` -> "All found records", the slack/message trigger keys), every
1262
+ // one of which is a plausible JSON key on a non-record item.
1263
+ if (!isRecordCollection) {
1264
+ const parts = name.split(".");
1265
+ parts[0] = TS_FOR_EACH_GENERIC_SEGMENT_TO_WIRE[parts[0]] ?? parts[0];
1266
+ return parts.join(".");
1267
+ }
1144
1268
  const fieldKey = name.split(".")[0];
1145
1269
  if (fieldKey !== undefined &&
1146
1270
  (ctx.fieldNames.has(fieldKey) || SYSTEM_FIELD_KEY_SET.has(fieldKey))) {
@@ -1163,13 +1287,81 @@ function normalizeIndexedRecordsFieldPath(name) {
1163
1287
  * app/element when known (cross-app recordSearch / createRecord / …), falling
1164
1288
  * back to the automation owner for non-record tasks and same-app searches.
1165
1289
  */
1290
+ function assertFindRelatedRecordsHasNoCountRef(targetType, name, taskRefKey) {
1291
+ if (targetType !== "elementum_find_related_records_task")
1292
+ return;
1293
+ const head = name.split(".")[0];
1294
+ if (head !== "totalCount" && head !== "Records Size" && head !== "count")
1295
+ return;
1296
+ throw new EntityTfError(`findRelatedRecords task "${taskRefKey}" does not expose totalCount. That output is recordSearch-only ` +
1297
+ `(platform refs["Records Size"]). Use ctx.actions.<recordSearchTask>.totalCount for a match count, ` +
1298
+ `or ctx.actions.${taskRefKey}.record / .records for related rows. Do not invent a count ref.`);
1299
+ }
1300
+ /**
1301
+ * Look up a related app/element's display-name map. Exact refName first;
1302
+ * case-insensitive fallback covers catalog/root key casing drift so a
1303
+ * renamed system title still resolves instead of silently becoming
1304
+ * DEPLOY_DEFAULT "Title".
1305
+ */
1306
+ function fieldNamesForAppRefName(map, appRefName) {
1307
+ if (map === undefined)
1308
+ return undefined;
1309
+ const exact = map.get(appRefName);
1310
+ if (exact !== undefined)
1311
+ return exact;
1312
+ const lower = appRefName.toLowerCase();
1313
+ for (const [key, value] of map) {
1314
+ if (key.toLowerCase() === lower)
1315
+ return value;
1316
+ }
1317
+ return undefined;
1318
+ }
1319
+ function taskTargetKind(taskRefKey, refs) {
1320
+ const fromCtx = refs.recordFieldContext?.taskAppKindByRefKey?.[taskRefKey];
1321
+ if (fromCtx !== undefined)
1322
+ return fromCtx;
1323
+ const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
1324
+ if (taskApp === undefined || taskApp === refs.owner.appRefName)
1325
+ return refs.owner.parentScope;
1326
+ if (refs.owner.workspaceAspects?.has(workspaceAspectKey("app", taskApp)))
1327
+ return "app";
1328
+ if (refs.owner.workspaceAspects?.has(workspaceAspectKey("element", taskApp)))
1329
+ return "element";
1330
+ return undefined;
1331
+ }
1332
+ /**
1333
+ * App-related findRelatedRecords no longer exposes system Title in its live
1334
+ * refs map (Cloud Builder plan: 95 keys, no "Title"). The parent identity
1335
+ * key is HANDLE. Authored / previously pulled `.record.title` must emit the
1336
+ * live HANDLE display name, not the stale `"Title"` label. Element-related
1337
+ * FIND_PARENT still uses Title.
1338
+ */
1339
+ function findRelatedRecordsAppTitleWireKey(name, taskRefKey, refs) {
1340
+ if (refs.tasks.get(taskRefKey)?.type !== "elementum_find_related_records_task")
1341
+ return undefined;
1342
+ if (taskTargetKind(taskRefKey, refs) !== "app")
1343
+ return undefined;
1344
+ const normalized = normalizeIndexedRecordsFieldPath(name);
1345
+ const field = normalized.startsWith("record.") ? normalized.slice("record.".length) : normalized;
1346
+ if (field !== "title" && field !== "Title")
1347
+ return undefined;
1348
+ const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
1349
+ const names = taskApp !== undefined && taskApp !== refs.owner.appRefName
1350
+ ? fieldNamesForAppRefName(refs.fieldNamesByAppRefName, taskApp)
1351
+ : refs.owner.fieldNames;
1352
+ return names?.get("id") ?? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES.id;
1353
+ }
1166
1354
  function taskWireRefName(name, taskRefKey, refs) {
1355
+ assertFindRelatedRecordsHasNoCountRef(refs.tasks.get(taskRefKey)?.type, name, taskRefKey);
1356
+ const handleKey = findRelatedRecordsAppTitleWireKey(name, taskRefKey, refs);
1357
+ if (handleKey !== undefined)
1358
+ return handleKey;
1167
1359
  const normalized = normalizeIndexedRecordsFieldPath(name);
1168
1360
  const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
1169
1361
  if (taskApp === undefined || taskApp === refs.owner.appRefName) {
1170
1362
  return wireRefName(normalized, refs.owner);
1171
1363
  }
1172
- const foreignNames = refs.fieldNamesByAppRefName?.get(taskApp);
1364
+ const foreignNames = fieldNamesForAppRefName(refs.fieldNamesByAppRefName, taskApp);
1173
1365
  return wireRefName(normalized, {
1174
1366
  ...refs.owner,
1175
1367
  appRefName: taskApp,
@@ -1191,6 +1383,7 @@ function taskWireRefName(name, taskRefKey, refs) {
1191
1383
  * "Invalid index" error. Their field names pass through verbatim.
1192
1384
  */
1193
1385
  function taskOutputWireRefKey(targetType, name, taskRefKey, refs) {
1386
+ assertFindRelatedRecordsHasNoCountRef(targetType, name, taskRefKey);
1194
1387
  if (targetType === "elementum_ai_file_read_task" || targetType === "elementum_file_reader_task")
1195
1388
  return name;
1196
1389
  if (targetType === "elementum_ai_agent_task")
@@ -1237,7 +1430,7 @@ function recordParamFieldWireName(paramName, suffix, refs) {
1237
1430
  const targetRefName = target.refName;
1238
1431
  const targetFieldNames = targetRefName === refs.owner.appRefName && target.__kind === refs.owner.parentScope
1239
1432
  ? refs.owner.fieldNames
1240
- : refs.fieldNamesByAppRefName?.get(targetRefName);
1433
+ : fieldNamesForAppRefName(refs.fieldNamesByAppRefName, targetRefName);
1241
1434
  return wireRefName(`record.${suffix}`, {
1242
1435
  ...refs.owner,
1243
1436
  appRefName: targetRefName,
@@ -1446,7 +1639,8 @@ function valueToTf(value, refs) {
1446
1639
  const target = refs.tasks.get(value.forEachReference.forEachTaskRefKey);
1447
1640
  if (target === undefined)
1448
1641
  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) }]);
1642
+ const index = forEachWireRefName(value.forEachReference.name, refs.owner, refs.recordItemForEachRefKeys.has(value.forEachReference.forEachTaskRefKey));
1643
+ return expr.resourceAttr(target.type, target.label, ["inner", "refs", { index }]);
1450
1644
  }
1451
1645
  if (isObject(value.templateReference))
1452
1646
  return templateToTf(value.templateReference, refs);
@@ -1475,7 +1669,7 @@ function unwrapDefault(value) {
1475
1669
  const values = Object.values(value);
1476
1670
  return values.length === 1 ? values[0] : value;
1477
1671
  }
1478
- function filterReferenceToTf(value, refs, role = "value", realType) {
1672
+ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1479
1673
  // Raw pass-through for a filter left side the pull-time deserializer
1480
1674
  // couldn't decode to a typed ref (filter.ts's leftDescriptor, matching the
1481
1675
  // UNRESOLVED_REFERENCE_MARKER case) - reproduces the original value_reference
@@ -1499,22 +1693,43 @@ function filterReferenceToTf(value, refs, role = "value", realType) {
1499
1693
  const fieldKey = parts[1];
1500
1694
  const address = refs.owner.fieldAddresses.get(fieldKey);
1501
1695
  const suffix = parts.slice(2).join(".");
1502
- const wireSuffix = suffix === "recordId" ? "10000001-2000-4000-a000-800000000000" : suffix;
1696
+ let wireSuffix = suffix === "recordId" ? "10000001-2000-4000-a000-800000000000" : suffix;
1503
1697
  // A bare reference to a PICKLIST field (STATUS/STAGE included —
1504
1698
  // `serializeSystemFields` wire-wraps both as a picklist too) has no
1505
1699
  // valid suffix-less wire form — confirmed live via the platform's
1506
1700
  // own switch-case editor, which always sends an explicit `.id`
1507
1701
  // (compare by the chosen option's real id) or `.label` (compare by
1508
1702
  // 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).
1703
+ // Comparisons stay ambiguous (eq/in/…). Null-checks are equivalent
1704
+ // for `.id` and `.label` when no option is selected, so
1705
+ // `isNull`/`isNotNull` on a bare Dropdown emit the platform editor's
1706
+ // `.id` + uuid shape — the Accept `isNotNull(record.dropdown)` form.
1514
1707
  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.`);
1708
+ if (operator === "is_null") {
1709
+ wireSuffix = "id";
1710
+ }
1711
+ else {
1712
+ throw new EntityTfError(`filter reference to picklist field "${fieldKey}" is ambiguous — write ".id" ` +
1713
+ `(ctx.trigger.record.${fieldKey}.id, compare by the option's id) or ".label" ` +
1714
+ `(ctx.trigger.record.${fieldKey}.label, compare by display text) explicitly.`);
1715
+ }
1716
+ }
1717
+ if (refs.trigger.type === TRIGGER_RESOURCES.datamine && refs.triggerDatamineTable !== undefined) {
1718
+ const table = refs.triggerDatamineTable;
1719
+ const tableAttr = resolveTableColumnFieldExpr({
1720
+ tableRefName: table.tableRefName,
1721
+ tableName: table.tableName,
1722
+ columnKey: fieldKey,
1723
+ columnDisplayNames: table.columnDisplayNames,
1724
+ workspaceAspects: refs.owner.workspaceAspects,
1725
+ orgRefs: refs.owner.orgRefs,
1726
+ dataBlocks: refs.dataBlocks,
1727
+ });
1728
+ return expr.template([
1729
+ "trigger.record.",
1730
+ tableAttr,
1731
+ ...(wireSuffix.length > 0 ? [`.${wireSuffix}`] : []),
1732
+ ]);
1518
1733
  }
1519
1734
  if (address !== undefined) {
1520
1735
  return expr.template([
@@ -1613,7 +1828,8 @@ function filterReferenceToTf(value, refs, role = "value", realType) {
1613
1828
  const task = refs.tasks.get(value.forEachTaskRefKey);
1614
1829
  if (task === undefined)
1615
1830
  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) }]);
1831
+ const index = forEachWireRefName(value.name, refs.owner, refs.recordItemForEachRefKeys.has(value.forEachTaskRefKey));
1832
+ return expr.resourceAttr(task.type, task.label, ["inner", "refs", { index }]);
1617
1833
  }
1618
1834
  case "VALUE":
1619
1835
  return valueToTf(value.value, refs);
@@ -1694,24 +1910,28 @@ function picklistFilterValueToTf(value, field, refs) {
1694
1910
  : `${scopedLabel(refs.owner.appTfLabel, tsLabelToTfLabel(field.refName))}_options_by_label`;
1695
1911
  return expr.local(localName, [{ index: value }]);
1696
1912
  }
1913
+ function triggerRecordFieldPath(reference) {
1914
+ if (!isObject(reference) || typeof reference.name !== "string")
1915
+ return undefined;
1916
+ const path = reference.name.split(".");
1917
+ if (path[0] !== "record" || path.length < 2)
1918
+ return undefined;
1919
+ return { fieldKey: path[1], suffix: path.slice(2).join(".") };
1920
+ }
1697
1921
  function fieldFromFilterLeftValue(value, refs) {
1698
1922
  if (!isObject(value) || !isObject(value.value) || value.value.type?.toString().toUpperCase() !== "TRIGGER") {
1699
1923
  return undefined;
1700
1924
  }
1701
- const name = value.value.name;
1702
- if (typeof name !== "string")
1925
+ const parsed = triggerRecordFieldPath(value.value);
1926
+ if (parsed === undefined)
1703
1927
  return undefined;
1704
- const path = name.split(".");
1705
- if (path[0] !== "record" || path.length < 2)
1706
- return undefined;
1707
- const refName = path[1];
1928
+ const { fieldKey: refName, suffix } = parsed;
1708
1929
  // Option-id resolution (picklistFilterValueToTf) only applies to the
1709
1930
  // ".id" convention `filterReferenceToTf` now requires for a picklist
1710
1931
  // field — an explicit ".label" (or any other drill-down suffix, e.g. a
1711
1932
  // USER field's ".email") compares raw text/whatever that sub-property
1712
1933
  // actually is, and must NOT have its value silently rewritten through
1713
1934
  // the options-by-label local.
1714
- const suffix = path.slice(2).join(".");
1715
1935
  if (suffix !== "" && suffix !== "id")
1716
1936
  return undefined;
1717
1937
  const metadata = refs.owner.fieldMetadata.get(refName);
@@ -1723,7 +1943,23 @@ function filterToTf(value, refs) {
1723
1943
  return serializeFilterToTf(value, {
1724
1944
  field: (field) => valueToTf(field, refs),
1725
1945
  fieldFromLeftValue: (left) => fieldFromFilterLeftValue(left, refs),
1726
- reference: (reference, role, realType) => filterReferenceToTf(reference, refs, role ?? "value", realType),
1946
+ reference: (reference, role, realType, operator) => filterReferenceToTf(reference, refs, role ?? "value", realType, operator),
1947
+ referenceRealType: (reference, _role, authored) => {
1948
+ const parsed = triggerRecordFieldPath(reference);
1949
+ if (parsed === undefined)
1950
+ return authored;
1951
+ const metadata = refs.owner.fieldMetadata.get(parsed.fieldKey);
1952
+ const inferred = referenceValueTypeForField(metadata?.fieldType, parsed.suffix);
1953
+ if (inferred === undefined)
1954
+ return authored;
1955
+ // Operator fallbacks and `filter.text()` are TEXT. Field metadata is
1956
+ // the authority for a known trigger-record field (PICKLIST .id → UUID).
1957
+ // Explicit non-TEXT wrappers (`filter.uuid()`, `filter.number()`, …) win.
1958
+ const authoredNorm = authored?.toUpperCase();
1959
+ if (authoredNorm !== undefined && authoredNorm !== "TEXT")
1960
+ return authored;
1961
+ return inferred;
1962
+ },
1727
1963
  literal: (literal, field) => picklistFilterValueToTf(literal, token(field), refs) ?? valueToTf(literal, refs),
1728
1964
  });
1729
1965
  }
@@ -1864,8 +2100,23 @@ function configAttrs(kind, config, refs) {
1864
2100
  };
1865
2101
  });
1866
2102
  }
2103
+ else if (isObject(raw.dynamic)) {
2104
+ const dynamic = raw.dynamic;
2105
+ if (dynamic.aspectId === undefined || dynamic.labelFieldId === undefined) {
2106
+ throw new EntityTfError("dynamic classification category source requires aspectId and labelFieldId");
2107
+ }
2108
+ attrs.dynamic_category_source = {
2109
+ object_id: valueToTf(dynamic.aspectId, refs),
2110
+ label_field_id: valueToTf(dynamic.labelFieldId, refs),
2111
+ ...(dynamic.descriptionFieldId !== undefined
2112
+ ? { description_field_id: valueToTf(dynamic.descriptionFieldId, refs) }
2113
+ : {}),
2114
+ ...(dynamic.filter !== undefined ? { filter: filterToTf(dynamic.filter, refs) } : {}),
2115
+ ...(typeof dynamic.limit === "number" ? { limit: dynamic.limit } : {}),
2116
+ };
2117
+ }
1867
2118
  else {
1868
- attrs.category_source = valueToTf(raw, refs);
2119
+ throw new EntityTfError("classification category source must be static or dynamic");
1869
2120
  }
1870
2121
  continue;
1871
2122
  }
@@ -2002,6 +2253,17 @@ function configAttrs(kind, config, refs) {
2002
2253
  const staticValue = isObject(field.valueReference) && "value" in field.valueReference
2003
2254
  ? field.valueReference.value
2004
2255
  : undefined;
2256
+ // Empty string / null is the platform clear payload for a field
2257
+ // assignment (TEXT already used ""; picklists must not resolve ""
2258
+ // through options_by_label). The provider value attribute is a
2259
+ // required string, so emit "" rather than HCL null.
2260
+ if (staticValue === "" || staticValue === null) {
2261
+ return {
2262
+ field_id: valueToTf(field.aspectFieldId, refs),
2263
+ value: fieldToken?.fieldType === "MULTI_PICKLIST" ? expr.jsonencode([]) : "",
2264
+ ...(field.operation === "ADD" ? { update_mode: "add" } : {}),
2265
+ };
2266
+ }
2005
2267
  if (Array.isArray(staticValue)) {
2006
2268
  if (fieldToken?.fieldType !== "MULTI_PICKLIST") {
2007
2269
  throw new EntityTfError(`automation field "${fieldToken?.name ?? fieldToken?.refName ?? "unknown"}" uses an array value but is not a Multi-Select field`);
@@ -2244,6 +2506,12 @@ export function automationToTf(entity, ctx) {
2244
2506
  const taskRefs = new Map();
2245
2507
  const variableById = new Map();
2246
2508
  const usedLabels = new Map(); // tf label → the refKey that claimed it
2509
+ // #952: a forEach's inner-ref keying depends on WHAT it loops over. Collect
2510
+ // each task's wire type and each loop's collection here, then resolve once
2511
+ // the walk is complete - a loop's own refKey is registered before the tasks
2512
+ // nested inside it, so the collection's producer is not reliably known yet.
2513
+ const wireTypeByRefKey = new Map();
2514
+ const forEachCollectionByRefKey = new Map();
2247
2515
  const preRegister = (tasks) => {
2248
2516
  for (const task of tasks) {
2249
2517
  const refKey = task.refKey;
@@ -2252,6 +2520,9 @@ export function automationToTf(entity, ctx) {
2252
2520
  if (taskRefs.has(refKey))
2253
2521
  throw new EntityTfError(`duplicate task refKey "${refKey}"`);
2254
2522
  const [wireType, taskBody] = onlyEntry(task.task, "task " + refKey);
2523
+ wireTypeByRefKey.set(refKey, wireType);
2524
+ if (wireType === "forEach")
2525
+ forEachCollectionByRefKey.set(refKey, taskBody.forEach);
2255
2526
  const resourceType = wireType === "variable" ? variableTaskResourceType(taskBody, refKey) : TASK_RESOURCES[wireType];
2256
2527
  if (resourceType === undefined)
2257
2528
  throw new EntityTfError(`task type "${wireType}" is not supported by the provider HCL contract`);
@@ -2289,6 +2560,21 @@ export function automationToTf(entity, ctx) {
2289
2560
  }
2290
2561
  };
2291
2562
  preRegister(payload.tasks ?? []);
2563
+ // A collection is record-typed only when it reads a record-collection task's
2564
+ // output. Everything else - a script array, a file-reader payload, an API
2565
+ // response, a variable, a nested item sub-array - keys its items by their
2566
+ // own keys, so their names pass through untouched.
2567
+ const recordItemForEachRefKeys = new Set([...forEachCollectionByRefKey].flatMap(([refKey, collection]) => {
2568
+ if (!isObject(collection) || !isObject(collection.taskReference))
2569
+ return [];
2570
+ const sourceRefKey = collection.taskReference.taskRefKey;
2571
+ if (typeof sourceRefKey !== "string")
2572
+ return [];
2573
+ const sourceWireType = wireTypeByRefKey.get(sourceRefKey);
2574
+ return sourceWireType !== undefined && RECORD_COLLECTION_TASK_WIRE_TYPES.has(sourceWireType)
2575
+ ? [refKey]
2576
+ : [];
2577
+ }));
2292
2578
  const dataBlocks = new Map();
2293
2579
  const recordFieldContext = recordFieldContextOf(entity);
2294
2580
  const triggerParamNames = triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
@@ -2311,6 +2597,22 @@ export function automationToTf(entity, ctx) {
2311
2597
  : [];
2312
2598
  })
2313
2599
  : []);
2600
+ let triggerDatamineTable;
2601
+ if (triggerKey === "datamine" && isObject(triggerConfig)) {
2602
+ const rawDatamine = triggerConfig.datamineId ?? triggerConfig.datamine ?? triggerConfig.datamine_id;
2603
+ const datamine = token(rawDatamine);
2604
+ if (datamine !== undefined && datamine.__kind === "datamine" && typeof datamine.parent === "string" && datamine.parent !== "") {
2605
+ const tableRefName = datamine.parent;
2606
+ const sibling = ctx.workspaceAspects?.get(workspaceAspectKey("table", tableRefName));
2607
+ const tableName = datamine.parentName ?? sibling?.streamRootEntity?.payload?.name ?? tableRefName;
2608
+ const columnDisplayNames = extractTableColumnDisplayNames(sibling, datamine.columnNames);
2609
+ triggerDatamineTable = {
2610
+ tableRefName,
2611
+ tableName,
2612
+ ...(columnDisplayNames.size > 0 ? { columnDisplayNames } : {}),
2613
+ };
2614
+ }
2615
+ }
2314
2616
  const refs = {
2315
2617
  trigger: { type: triggerType, label },
2316
2618
  triggerParamNames,
@@ -2320,10 +2622,12 @@ export function automationToTf(entity, ctx) {
2320
2622
  owner,
2321
2623
  dataBlocks,
2322
2624
  variableById,
2625
+ recordItemForEachRefKeys,
2323
2626
  ...(recordFieldContext !== undefined ? { recordFieldContext } : {}),
2324
2627
  ...(ctx.fieldNamesByAppRefName !== undefined ? { fieldNamesByAppRefName: ctx.fieldNamesByAppRefName } : {}),
2325
2628
  ...(ctx.fieldAddressesByAppRefName !== undefined ? { fieldAddressesByAppRefName: ctx.fieldAddressesByAppRefName } : {}),
2326
2629
  ...(ctx.allowUnknownPicklistOptions === true ? { allowUnknownPicklistOptions: true } : {}),
2630
+ ...(triggerDatamineTable !== undefined ? { triggerDatamineTable } : {}),
2327
2631
  };
2328
2632
  let triggerAttrs;
2329
2633
  try {