@elementumai/edk 0.9.10 → 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 (124) hide show
  1. package/README.md +39 -5
  2. package/dist-sdk/src/catalog/factories.d.ts +42 -14
  3. package/dist-sdk/src/catalog/factories.js +77 -14
  4. package/dist-sdk/src/catalog/from-authoring.js +4 -4
  5. package/dist-sdk/src/catalog/index.d.ts +2 -2
  6. package/dist-sdk/src/catalog/index.js +1 -1
  7. package/dist-sdk/src/catalog/org.js +3 -2
  8. package/dist-sdk/src/catalog/token.js +4 -0
  9. package/dist-sdk/src/catalog/types.d.ts +32 -5
  10. package/dist-sdk/src/catalog/types.js +1 -0
  11. package/dist-sdk/src/core/triggers/on-demand.d.ts +4 -28
  12. package/dist-sdk/src/core/triggers/on-demand.js +2 -4
  13. package/dist-sdk/src/engine/build/context.d.ts +3 -0
  14. package/dist-sdk/src/engine/entity.d.ts +2 -0
  15. package/dist-sdk/src/engine/logging.d.ts +90 -0
  16. package/dist-sdk/src/engine/logging.js +124 -0
  17. package/dist-sdk/src/engine/progress.d.ts +119 -0
  18. package/dist-sdk/src/engine/progress.js +647 -0
  19. package/dist-sdk/src/engine/pull/result-output.d.ts +24 -0
  20. package/dist-sdk/src/engine/pull/result-output.js +48 -0
  21. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +3 -3
  22. package/dist-sdk/src/entities/access-policy/from-tf.js +27 -8
  23. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +13 -0
  24. package/dist-sdk/src/entities/access-policy/to-tf.js +34 -3
  25. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +13 -7
  26. package/dist-sdk/src/entities/agent/tools.d.ts +2 -2
  27. package/dist-sdk/src/entities/agent-tool/to-tf.js +13 -0
  28. package/dist-sdk/src/entities/app/build.d.ts +22 -2
  29. package/dist-sdk/src/entities/app/build.js +6 -0
  30. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +13 -3
  31. package/dist-sdk/src/entities/app/from-tf.js +10 -7
  32. package/dist-sdk/src/entities/app/to-tf.js +14 -14
  33. package/dist-sdk/src/entities/automation/build.d.ts +11 -16
  34. package/dist-sdk/src/entities/automation/build.js +38 -8
  35. package/dist-sdk/src/entities/automation/catalog-render.js +1 -1
  36. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +1 -2
  37. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +23 -5
  38. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +239 -34
  39. package/dist-sdk/src/entities/automation/from-tf.js +276 -19
  40. package/dist-sdk/src/entities/automation/index.d.ts +2 -2
  41. package/dist-sdk/src/entities/automation/module.js +3 -2
  42. package/dist-sdk/src/entities/automation/output-field-types.js +25 -13
  43. package/dist-sdk/src/entities/automation/script-code.d.ts +12 -4
  44. package/dist-sdk/src/entities/automation/script-code.js +659 -101
  45. package/dist-sdk/src/entities/automation/tasks.d.ts +60 -28
  46. package/dist-sdk/src/entities/automation/tasks.js +48 -15
  47. package/dist-sdk/src/entities/automation/to-tf.d.ts +8 -0
  48. package/dist-sdk/src/entities/automation/to-tf.js +514 -103
  49. package/dist-sdk/src/entities/automation/triggers.d.ts +15 -9
  50. package/dist-sdk/src/entities/automation/triggers.js +4 -2
  51. package/dist-sdk/src/entities/automation/types.js +1 -0
  52. package/dist-sdk/src/entities/chart/build.d.ts +15 -3
  53. package/dist-sdk/src/entities/chart/build.js +6 -1
  54. package/dist-sdk/src/entities/chart/from-tf.d.ts +8 -2
  55. package/dist-sdk/src/entities/chart/from-tf.js +71 -8
  56. package/dist-sdk/src/entities/chart/index.d.ts +1 -1
  57. package/dist-sdk/src/entities/chart/index.js +1 -1
  58. package/dist-sdk/src/entities/chart/printer.js +27 -7
  59. package/dist-sdk/src/entities/chart/to-tf.js +56 -2
  60. package/dist-sdk/src/entities/dashboard/from-tf.js +11 -2
  61. package/dist-sdk/src/entities/datamine/from-tf.js +11 -1
  62. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +2 -1
  63. package/dist-sdk/src/entities/dynamic-layout/dialect.d.ts +8 -0
  64. package/dist-sdk/src/entities/dynamic-layout/dialect.js +12 -0
  65. package/dist-sdk/src/entities/dynamic-layout/from-tf.d.ts +7 -0
  66. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +64 -10
  67. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +54 -6
  68. package/dist-sdk/src/entities/element/build.d.ts +8 -0
  69. package/dist-sdk/src/entities/element/from-tf.js +4 -3
  70. package/dist-sdk/src/entities/element/module.js +1 -0
  71. package/dist-sdk/src/entities/element/to-tf.d.ts +4 -1
  72. package/dist-sdk/src/entities/element/to-tf.js +28 -2
  73. package/dist-sdk/src/entities/field/build.d.ts +10 -1
  74. package/dist-sdk/src/entities/field/build.js +2 -1
  75. package/dist-sdk/src/entities/field/calc/index.js +7 -7
  76. package/dist-sdk/src/entities/field/calc/runtime.d.ts +19 -0
  77. package/dist-sdk/src/entities/field/calc/runtime.js +32 -0
  78. package/dist-sdk/src/entities/field/calc/types.d.ts +6 -0
  79. package/dist-sdk/src/entities/field/from-tf.d.ts +24 -0
  80. package/dist-sdk/src/entities/field/from-tf.js +73 -1
  81. package/dist-sdk/src/entities/field/metadata.d.ts +18 -0
  82. package/dist-sdk/src/entities/field/metadata.js +34 -0
  83. package/dist-sdk/src/entities/file-reader/to-tf.js +10 -2
  84. package/dist-sdk/src/entities/relationship/build.d.ts +27 -9
  85. package/dist-sdk/src/entities/relationship/column-contract.d.ts +24 -0
  86. package/dist-sdk/src/entities/relationship/column-contract.js +41 -0
  87. package/dist-sdk/src/entities/relationship/from-tf.js +33 -48
  88. package/dist-sdk/src/entities/relationship/to-tf.d.ts +1 -0
  89. package/dist-sdk/src/entities/relationship/to-tf.js +33 -2
  90. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +15 -0
  91. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +21 -0
  92. package/dist-sdk/src/entities/shared/context.d.ts +6 -3
  93. package/dist-sdk/src/entities/shared/context.js +19 -1
  94. package/dist-sdk/src/entities/shared/filters/index.d.ts +7 -0
  95. package/dist-sdk/src/entities/shared/filters/index.js +28 -0
  96. package/dist-sdk/src/entities/shared/filters/print.js +2 -0
  97. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +8 -1
  98. package/dist-sdk/src/entities/shared/filters/tf-codec.js +10 -6
  99. package/dist-sdk/src/entities/shared/filters/types.d.ts +1 -1
  100. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +5 -0
  101. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +52 -27
  102. package/dist-sdk/src/entities/skill/module.js +1 -0
  103. package/dist-sdk/src/entities/skill/to-tf.d.ts +1 -1
  104. package/dist-sdk/src/entities/skill/to-tf.js +17 -0
  105. package/dist-sdk/src/entities/skill/tools.d.ts +48 -12
  106. package/dist-sdk/src/entities/skill/tools.js +12 -1
  107. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +15 -12
  108. package/dist-sdk/src/entities/skill-tool/from-tf.js +50 -46
  109. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +4 -0
  110. package/dist-sdk/src/entities/skill-tool/to-tf.js +66 -7
  111. package/dist-sdk/src/entities/table/build.js +10 -2
  112. package/dist-sdk/src/entities/table/catalog-render.js +2 -1
  113. package/dist-sdk/src/entities/view/from-tf.js +9 -0
  114. package/dist-sdk/src/entities/view/to-tf.d.ts +7 -0
  115. package/dist-sdk/src/entities/view/to-tf.js +39 -12
  116. package/dist-sdk/src/entities/widget/build.d.ts +43 -7
  117. package/dist-sdk/src/entities/widget/from-tf.d.ts +1 -1
  118. package/dist-sdk/src/entities/widget/from-tf.js +162 -23
  119. package/dist-sdk/src/entities/widget/to-tf.d.ts +17 -0
  120. package/dist-sdk/src/entities/widget/to-tf.js +150 -6
  121. package/dist-sdk/src/graph/types.d.ts +13 -0
  122. package/package.json +1 -1
  123. package/dist-sdk/src/core/types/platform.d.ts +0 -2
  124. 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, snakeSlug, 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";
@@ -58,6 +59,7 @@ const TRIGGER_RESOURCES = {
58
59
  approvalChain: "elementum_approval_chain_trigger",
59
60
  datamine: "elementum_datamine_trigger",
60
61
  survey: "elementum_survey_trigger",
62
+ schedule: "elementum_schedule_trigger",
61
63
  };
62
64
  /**
63
65
  * setVariable tasks share one wire key ("variable") but two distinct
@@ -121,7 +123,6 @@ const CONFIG_ATTRS = {
121
123
  thinkUi: "think_ui",
122
124
  conversationType: "conversation_type",
123
125
  customResponse: "custom_response",
124
- showTriggeredBy: "show_triggered_by",
125
126
  datamineId: "datamine_id",
126
127
  fireOnAlert: "fire_on_alert",
127
128
  fireOnRecovery: "fire_on_recovery",
@@ -209,6 +210,80 @@ function addressExpr(address, path = ["id"]) {
209
210
  throw new EntityTfError(`invalid terraform address "${address}"`);
210
211
  return expr.resourceAttr(address.slice(0, dot), address.slice(dot + 1), [...path]);
211
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
+ }
212
287
  /**
213
288
  * A field token whose `parent` names a DIFFERENT app/element than the one
214
289
  * this automation belongs to (e.g. a `recordSearch` task's filter against
@@ -564,7 +639,12 @@ function tokenToTf(value, ctx, dataBlocks) {
564
639
  }
565
640
  else {
566
641
  const tableLabel = tsLabelToTfLabel(value.parent);
567
- const tableName = value.parent;
642
+ // value.parent is the table's refName, not its display name - the
643
+ // platform's data.elementum_table lookup keys by name, so a
644
+ // catalog-carried parentName (same escape FieldRef/TableColumnRef
645
+ // already use) must win when present, or the lookup 404s with the
646
+ // camelCase refName instead of the real table name.
647
+ const tableName = typeof value.parentName === "string" && value.parentName !== "" ? value.parentName : value.parent;
568
648
  if (ctx.orgRefs !== undefined) {
569
649
  ctx.orgRefs.rawLookup(TABLE_RESOURCE_TYPE, tableLabel, tableName);
570
650
  }
@@ -610,29 +690,22 @@ function tokenToTf(value, ctx, dataBlocks) {
610
690
  }
611
691
  case "tableColumn": {
612
692
  // Columns are addressed by DISPLAY name in `field_ids`, never by bag key.
613
- const columnName = value.name ?? value.refName;
614
693
  const owner = value.parent;
615
694
  if (owner === undefined || owner === "") {
616
695
  throw new EntityTfError(`table column ref "${value.refName}" is missing its owning table`);
617
696
  }
618
697
  const sibling = ctx.workspaceAspects?.get(workspaceAspectKey("table", owner));
619
- if (sibling !== undefined) {
620
- return expr.resourceAttr(TABLE_RESOURCE_TYPE, sibling.tfLabel, ["field_ids", { index: columnName }]);
621
- }
622
- const tableName = value.parentName ?? owner;
623
- const label = tsLabelToTfLabel(owner);
624
- if (ctx.orgRefs !== undefined) {
625
- ctx.orgRefs.rawLookup(TABLE_RESOURCE_TYPE, label, tableName);
626
- }
627
- else {
628
- dataBlocks.set(`${TABLE_RESOURCE_TYPE}.${label}`, {
629
- kind: "data",
630
- type: TABLE_RESOURCE_TYPE,
631
- label,
632
- attrs: { name: tableName },
633
- });
634
- }
635
- 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
+ });
636
709
  }
637
710
  case "searchTable": {
638
711
  // Ownership + variant contract:
@@ -689,10 +762,18 @@ function tokenToTf(value, ctx, dataBlocks) {
689
762
  throw new EntityTfError(`search table "${owner}.${value.refName}" is owned by an aspect that is not part of this build — ` +
690
763
  `a foreign search-table reference has no data-source lookup yet`);
691
764
  }
692
- case "approvalChain":
693
- return value.unresolvedId !== undefined
694
- ? value.unresolvedId
695
- : 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
+ }
696
777
  case "documentModel": {
697
778
  const subType = FILE_READER_SUB_TYPE_BY_TYPE_KEY.get(value.readerType ?? "");
698
779
  // "xml"/"ai" are declared sub-types (FILE_READER_SUB_TYPES) but don't
@@ -882,28 +963,86 @@ function calculationFormulaRefToParts(value, refs) {
882
963
  throw new EntityTfError("calculation formula is not a trigger/task/variable ref, literal, or template");
883
964
  }
884
965
  /**
885
- * Calc-engine mustache for a prior task output. Matches the live dialect
886
- * `{{task name="<wire output>" id="<task-id>"}}` (name is the refs-map key,
887
- * not the task display name). Task id interpolates from the task resource.
966
+ * Calc-engine mustache for a prior task output:
967
+ * `{{task name="<reference name>" id="<task-id>"}}`, with the task id
968
+ * interpolated from the task resource.
969
+ *
970
+ * `name` is the WorkflowTaskReference's own name, NOT the Terraform
971
+ * `refs[…]` map key. Mobius parses this mustache itself
972
+ * (`CalcParamVisitor#visitCalculatedParameter` → `ValueReference
973
+ * .ofTaskReference(id, name)`) and then resolves the reference against the
974
+ * workflow's available refs; an unknown name throws `paramNotFound` and the
975
+ * whole task create fails with "Unable to validate". The refs-map key is a
976
+ * localized DISPLAY label from mobius' `shared.json` bundle ("Records Size",
977
+ * "Triage SLA (business days)") and never resolves here.
888
978
  */
889
- function calculationTaskMustache(taskRefKey, wireName, refs) {
890
- if (wireName.includes('"')) {
891
- throw new EntityTfError(`calculation task output name "${wireName}" contains a double quote`);
979
+ function calculationTaskMustache(taskRefKey, name, refs) {
980
+ if (name.includes('"')) {
981
+ throw new EntityTfError(`calculation task output name "${name}" contains a double quote`);
892
982
  }
893
983
  const target = refs.tasks.get(taskRefKey);
894
984
  if (target === undefined) {
895
985
  refs.owner.diagnostics.push(`automation unresolved task ref ${JSON.stringify(taskRefKey)} preserved as a literal calculation reference`);
896
- return [`{{task name="${wireName}" id="${taskRefKey}"}}`];
897
- }
898
- if (wireName.includes('"')) {
899
- throw new EntityTfError(`calculation task output name "${wireName}" contains a double quote`);
986
+ return [`{{task name="${name}" id="${taskRefKey}"}}`];
900
987
  }
901
988
  return [
902
- `{{task name="${wireName}" id="`,
989
+ '{{task name="',
990
+ ...calculationTaskRefName(target.type, name, taskRefKey, refs),
991
+ '" id="',
903
992
  expr.resourceAttr(target.type, target.label, ["id"]),
904
993
  `"}}`,
905
994
  ];
906
995
  }
996
+ /**
997
+ * Task-own outputs whose calc-engine reference name differs from the
998
+ * refs-map key. Keys are the display labels the refs map uses (and that
999
+ * `build.ts`'s `rewriteForwardTaskRefName` already rewrote authoring names
1000
+ * into); values are the underlying reference names — captured live with
1001
+ * `ei refs --from-remote` against a real record-search task, and matching
1002
+ * mobius' `shared.json` `aspect_records_search` label table.
1003
+ */
1004
+ const CALCULATION_TASK_OUTPUT_REF_NAME = {
1005
+ elementum_record_search_task: {
1006
+ "Records Size": "count",
1007
+ "First found record id": "recordId",
1008
+ },
1009
+ };
1010
+ function calculationTaskRefName(targetType, name, taskRefKey, refs) {
1011
+ const segments = name.split(".");
1012
+ if (segments[0] === "record" && segments.length >= 2) {
1013
+ const suffix = segments.slice(2).join(".");
1014
+ return [
1015
+ "record.",
1016
+ calculationRecordFieldId(segments[1], calculationFieldScope(taskRefKey, refs)),
1017
+ suffix.length > 0 ? `.${suffix}` : "",
1018
+ ];
1019
+ }
1020
+ const refName = CALCULATION_TASK_OUTPUT_REF_NAME[targetType]?.[name] ?? name;
1021
+ if (refName.includes('"')) {
1022
+ throw new EntityTfError(`calculation task output name "${refName}" contains a double quote`);
1023
+ }
1024
+ return [refName];
1025
+ }
1026
+ /**
1027
+ * The aspect whose fields a task's `record.<field>` output belongs to. A
1028
+ * cross-aspect `recordSearch` reads the SEARCHED aspect's fields, and the
1029
+ * calc engine wants their ids, so that aspect must be part of this build —
1030
+ * a `data.elementum_app` stub carries display names but no field resources.
1031
+ */
1032
+ function calculationFieldScope(taskRefKey, refs) {
1033
+ const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
1034
+ if (taskApp === undefined || taskApp === refs.owner.appRefName)
1035
+ return refs.owner;
1036
+ const fieldAddresses = refs.fieldAddressesByAppRefName?.get(taskApp);
1037
+ if (fieldAddresses === undefined) {
1038
+ throw new EntityTfError(`automation calculation reads a field of "${taskApp}", but that app/element is not authored in ` +
1039
+ `this workspace — the calc engine addresses a found record's field by field id, which only a ` +
1040
+ `built aspect can supply`);
1041
+ }
1042
+ const aspect = refs.owner.workspaceAspects?.get(workspaceAspectKey("app", taskApp))
1043
+ ?? refs.owner.workspaceAspects?.get(workspaceAspectKey("element", taskApp));
1044
+ return { appRefName: taskApp, appTfLabel: aspect?.tfLabel ?? refs.owner.appTfLabel, fieldAddresses };
1045
+ }
907
1046
  function calculationTriggerMustache(name, refs) {
908
1047
  const parts = name.split(".");
909
1048
  if (parts[0] !== "record" || parts.length < 2) {
@@ -914,22 +1053,22 @@ function calculationTriggerMustache(name, refs) {
914
1053
  const suffixPart = suffix.length > 0 ? `.${suffix}` : "";
915
1054
  return [
916
1055
  '{{trigger name="record.',
917
- calculationRecordFieldId(fieldKey, refs),
1056
+ calculationRecordFieldId(fieldKey, refs.owner),
918
1057
  `${suffixPart}"}}`,
919
1058
  ];
920
1059
  }
921
- function calculationRecordFieldId(fieldKey, refs) {
1060
+ function calculationRecordFieldId(fieldKey, scope) {
922
1061
  if (fieldKey.startsWith(UNRESOLVED_FIELD_MARKER))
923
1062
  return fieldKey.slice(UNRESOLVED_FIELD_MARKER.length);
924
1063
  if (isUuid(fieldKey))
925
1064
  return fieldKey;
926
- const address = refs.owner.fieldAddresses.get(fieldKey);
1065
+ const address = scope.fieldAddresses.get(fieldKey);
927
1066
  if (address !== undefined)
928
1067
  return addressExpr(address, ["id"]);
929
1068
  if (SYSTEM_FIELD_KEY_SET.has(fieldKey)) {
930
- return expr.local(`${refs.owner.appTfLabel}_${tsLabelToTfLabel(fieldKey)}_field_id`);
1069
+ return expr.local(`${scope.appTfLabel}_${tsLabelToTfLabel(fieldKey)}_field_id`);
931
1070
  }
932
- throw new EntityTfError(`automation calculation targets field "${fieldKey}" which does not exist in app "${refs.owner.appRefName}"`);
1071
+ throw new EntityTfError(`automation calculation targets field "${fieldKey}" which does not exist in app "${scope.appRefName}"`);
933
1072
  }
934
1073
  function flattenAdjacentFormulaParts(parts) {
935
1074
  const out = [];
@@ -959,9 +1098,6 @@ const TS_TRIGGER_REF_TO_WIRE = {
959
1098
  // onto FIELD_REF_SUFFIX_TO_WIRE — that table's `id` suffix is " ID", which
960
1099
  // would emit the wrong wire key "Attachment ID" and fail live validation.
961
1100
  "attachment.id": "Attachment Id",
962
- "triggeredBy.id": "Triggered By's Id",
963
- "triggeredBy.name": "Triggered By's Name",
964
- "triggeredBy.email": "Triggered By's Email",
965
1101
  createdByEmail: "Created By Email",
966
1102
  updatedByManagerEmail: "Updated By Manager Email",
967
1103
  slackThreadId: "Slack Thread ID",
@@ -972,6 +1108,10 @@ const TS_TRIGGER_REF_TO_WIRE = {
972
1108
  messageContent: "Message Content",
973
1109
  messageId: "Message ID",
974
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)",
975
1115
  };
976
1116
  const DISPLAY_REF_CANONICAL_CASE = Object.fromEntries(Object.values(TS_TRIGGER_REF_TO_WIRE).map((value) => [value.toLowerCase(), value]));
977
1117
  const FIELD_REF_SUFFIX_TO_WIRE = {
@@ -1028,11 +1168,14 @@ function wireRefName(name, ctx) {
1028
1168
  if (fieldKey.startsWith(UNRESOLVED_FIELD_MARKER)) {
1029
1169
  return `record.${fieldKey.slice(UNRESOLVED_FIELD_MARKER.length)}${parts.length > 2 ? `.${parts.slice(2).join(".")}` : ""}`;
1030
1170
  }
1031
- // System fields (title/status/stage/createdBy/...) have no entry in
1032
- // ctx.fieldNames - that map only carries the app's custom fields bag.
1033
- // Fall back to the provider's default display name for them; a renamed
1034
- // system field won't match and still throws below, same as an unknown
1035
- // 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).
1036
1179
  const systemFieldKey = SYSTEM_FIELD_KEY_SET.has(fieldKey)
1037
1180
  ? fieldKey
1038
1181
  : undefined;
@@ -1064,10 +1207,36 @@ function wireRefName(name, ctx) {
1064
1207
  const label = parts[0] === "body" ? "Body" : "Headers";
1065
1208
  return `${label} (${parts[1]})`;
1066
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
+ }
1067
1215
  parts[0] = TS_REF_SEGMENT_TO_WIRE[parts[0]] ?? parts[0];
1068
1216
  return parts.join(".");
1069
1217
  }
1070
- 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) {
1071
1240
  // A recordSearch collection's whole item and branded record identity both
1072
1241
  // point at the loop's ASPECT_RECORD_ID reference. Live provider state
1073
1242
  // exposes that reference under "Record"; "ID" is a distinct TEXT handle.
@@ -1075,8 +1244,27 @@ function forEachWireRefName(name, ctx) {
1075
1244
  return "Record";
1076
1245
  // Record fields are keyed by their platform display names, not their typed
1077
1246
  // catalog handles. Reuse the same field/suffix mapping as trigger record
1078
- // paths, while preserving the generic forEach keys used by non-record
1079
- // 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
+ }
1080
1268
  const fieldKey = name.split(".")[0];
1081
1269
  if (fieldKey !== undefined &&
1082
1270
  (ctx.fieldNames.has(fieldKey) || SYSTEM_FIELD_KEY_SET.has(fieldKey))) {
@@ -1099,19 +1287,121 @@ function normalizeIndexedRecordsFieldPath(name) {
1099
1287
  * app/element when known (cross-app recordSearch / createRecord / …), falling
1100
1288
  * back to the automation owner for non-record tasks and same-app searches.
1101
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
+ }
1102
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;
1103
1359
  const normalized = normalizeIndexedRecordsFieldPath(name);
1104
1360
  const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
1105
1361
  if (taskApp === undefined || taskApp === refs.owner.appRefName) {
1106
1362
  return wireRefName(normalized, refs.owner);
1107
1363
  }
1108
- const foreignNames = refs.fieldNamesByAppRefName?.get(taskApp);
1364
+ const foreignNames = fieldNamesForAppRefName(refs.fieldNamesByAppRefName, taskApp);
1109
1365
  return wireRefName(normalized, {
1110
1366
  ...refs.owner,
1111
1367
  appRefName: taskApp,
1112
1368
  fieldNames: foreignNames ?? new Map(),
1113
1369
  });
1114
1370
  }
1371
+ /**
1372
+ * The platform refs-map key for one task output, given the emitting task's
1373
+ * resource type. Shared by `refs[…]` inputs and calculation mustaches so both
1374
+ * dialects address the same output the same way.
1375
+ *
1376
+ * aiFileAnalysis/readFile's refs are keyed by whatever arbitrary field names
1377
+ * the file reader schema itself defines (e.g. "title", "document_type") -
1378
+ * wireRefName's generic segment table (TS_REF_SEGMENT_TO_WIRE) is for a
1379
+ * DIFFERENT thing (a task's own canonical record-identity fields, e.g.
1380
+ * createRecord's generic "id"/"title"), and wrongly rewrites a reader field
1381
+ * literally named "title" into the wire key "Title", which doesn't exist in
1382
+ * these two resources' actual refs map - confirmed live via a real apply's
1383
+ * "Invalid index" error. Their field names pass through verbatim.
1384
+ */
1385
+ function taskOutputWireRefKey(targetType, name, taskRefKey, refs) {
1386
+ assertFindRelatedRecordsHasNoCountRef(targetType, name, taskRefKey);
1387
+ if (targetType === "elementum_ai_file_read_task" || targetType === "elementum_file_reader_task")
1388
+ return name;
1389
+ if (targetType === "elementum_ai_agent_task")
1390
+ return name;
1391
+ // aiSearchTable's collection is `refs["All Records"]`, not recordSearch's
1392
+ // globally-mapped `refs["All found records"]` (TS_REF_SEGMENT_TO_WIRE).
1393
+ // Accept both the authoring segment and the already-rewritten wire name
1394
+ // from rewriteForwardTaskRefName so either path emits the same key.
1395
+ if (targetType === "elementum_ai_search_table_task" && (name === "records" || name === "All Records")) {
1396
+ return "All Records";
1397
+ }
1398
+ // tableRecordsSearch uses yet another wire key: "All matching table rows".
1399
+ if (targetType === "elementum_table_records_search_task" &&
1400
+ (name === "records" || name === "All matching table rows")) {
1401
+ return "All matching table rows";
1402
+ }
1403
+ return taskWireRefName(name, taskRefKey, refs);
1404
+ }
1115
1405
  function triggerWireRefName(name, refs) {
1116
1406
  const scalarParams = refs.triggerParamNames.filter((param) => !refs.recordParamNames.includes(param));
1117
1407
  const declared = onDemandTriggerRefKey(name, scalarParams);
@@ -1140,7 +1430,7 @@ function recordParamFieldWireName(paramName, suffix, refs) {
1140
1430
  const targetRefName = target.refName;
1141
1431
  const targetFieldNames = targetRefName === refs.owner.appRefName && target.__kind === refs.owner.parentScope
1142
1432
  ? refs.owner.fieldNames
1143
- : refs.fieldNamesByAppRefName?.get(targetRefName);
1433
+ : fieldNamesForAppRefName(refs.fieldNamesByAppRefName, targetRefName);
1144
1434
  return wireRefName(`record.${suffix}`, {
1145
1435
  ...refs.owner,
1146
1436
  appRefName: targetRefName,
@@ -1230,6 +1520,32 @@ function workflowPublishOutputEnvelope(value, refs) {
1230
1520
  }
1231
1521
  if (isObject(value.variableReference)) {
1232
1522
  const id = typeof value.variableReference.id === "string" ? value.variableReference.id : undefined;
1523
+ // A freshly-authored `ctx.variables[...]` reference carries the SAME
1524
+ // randomUUID `stampAndCollectVariableIds` just minted for this build's
1525
+ // own `elementum_variable_task` create entry — that id is never the
1526
+ // variable's real (deploy-time-assigned) platform id, so baking it in as
1527
+ // a literal string here always mismatches live state on the very next
1528
+ // plan. Interpolate the live resource instead.
1529
+ //
1530
+ // `elementum_variable_task` carries TWO platform ids: `id` is the TASK's
1531
+ // id, `variable_id` is the id of the variable that task creates. A
1532
+ // publish output addresses the VARIABLE, so it must interpolate
1533
+ // `variable_id`. This differs from taskReference's `taskId:
1534
+ // expr.resourceAttr(...)` treatment just above, which does want `.id`.
1535
+ //
1536
+ // Sending the task id instead fails at the PUBLISH step
1537
+ // ("Failed to publish workflow"). The emitted shape stays
1538
+ // `{ name = "variable|<id>" }` with no sibling `id`, byte-identical to
1539
+ // ei's export — the provider recovers the id from the name when it builds
1540
+ // VariableReferenceInput (workflow_publish_resource.go).
1541
+ const target = id !== undefined ? refs.variableById.get(id) : undefined;
1542
+ if (target !== undefined) {
1543
+ return {
1544
+ taskReference: null,
1545
+ triggerReference: null,
1546
+ variableReference: { name: expr.template(["variable|", expr.resourceAttr(target.type, target.label, ["variable_id"])]) },
1547
+ };
1548
+ }
1233
1549
  const name = typeof value.variableReference.name === "string" ? value.variableReference.name : undefined;
1234
1550
  // ei export / pull shape: `variableReference = { name = "variable|<uuid>" }`
1235
1551
  // with sibling null refs — not fieldType+id. Prefer that wire form.
@@ -1316,40 +1632,15 @@ function valueToTf(value, refs) {
1316
1632
  refs.owner.diagnostics.push(`automation unresolved task ref ${JSON.stringify(value.taskReference.taskRefKey)} preserved as a literal reference`);
1317
1633
  return `{{task name="${value.taskReference.name}" id="${value.taskReference.taskRefKey}"}}`;
1318
1634
  }
1319
- // aiFileAnalysis/readFile's refs are keyed by whatever arbitrary field
1320
- // names the file reader schema itself defines (e.g. "title",
1321
- // "document_type") - wireRefName's generic segment table
1322
- // (TS_REF_SEGMENT_TO_WIRE) is for a DIFFERENT thing (a task's own
1323
- // canonical record-identity fields, e.g. createRecord's generic "id"/
1324
- // "title"), and wrongly rewrites a reader field literally named "title"
1325
- // into the wire key "Title", which doesn't exist in these two
1326
- // resources' actual refs map - confirmed live via a real apply's
1327
- // "Invalid index" error. Their field names pass through verbatim.
1328
- const isFileReaderTask = target.type === "elementum_ai_file_read_task" || target.type === "elementum_file_reader_task";
1329
- const isAiAgentTask = target.type === "elementum_ai_agent_task";
1330
- // aiSearchTable's collection is `refs["All Records"]`, not recordSearch's
1331
- // globally-mapped `refs["All found records"]` (TS_REF_SEGMENT_TO_WIRE).
1332
- // Accept both the authoring segment and the already-rewritten wire name
1333
- // from rewriteForwardTaskRefName so either path emits the same key.
1334
- const isAiSearchTableRecords = target.type === "elementum_ai_search_table_task" &&
1335
- (value.taskReference.name === "records" || value.taskReference.name === "All Records");
1336
- // tableRecordsSearch uses yet another wire key: "All matching table rows".
1337
- const isTableRecordsSearchRecords = target.type === "elementum_table_records_search_task" &&
1338
- (value.taskReference.name === "records" || value.taskReference.name === "All matching table rows");
1339
- const refKey = isFileReaderTask || isAiAgentTask
1340
- ? value.taskReference.name
1341
- : isAiSearchTableRecords
1342
- ? "All Records"
1343
- : isTableRecordsSearchRecords
1344
- ? "All matching table rows"
1345
- : taskWireRefName(value.taskReference.name, value.taskReference.taskRefKey, refs);
1635
+ const refKey = taskOutputWireRefKey(target.type, value.taskReference.name, value.taskReference.taskRefKey, refs);
1346
1636
  return expr.resourceAttr(target.type, target.label, ["refs", { index: refKey }]);
1347
1637
  }
1348
1638
  if (isObject(value.forEachReference) && typeof value.forEachReference.forEachTaskRefKey === "string" && typeof value.forEachReference.name === "string") {
1349
1639
  const target = refs.tasks.get(value.forEachReference.forEachTaskRefKey);
1350
1640
  if (target === undefined)
1351
1641
  throw new EntityTfError(`unresolved forEach ref "${value.forEachReference.forEachTaskRefKey}"`);
1352
- 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 }]);
1353
1644
  }
1354
1645
  if (isObject(value.templateReference))
1355
1646
  return templateToTf(value.templateReference, refs);
@@ -1378,7 +1669,7 @@ function unwrapDefault(value) {
1378
1669
  const values = Object.values(value);
1379
1670
  return values.length === 1 ? values[0] : value;
1380
1671
  }
1381
- function filterReferenceToTf(value, refs, role = "value", realType) {
1672
+ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1382
1673
  // Raw pass-through for a filter left side the pull-time deserializer
1383
1674
  // couldn't decode to a typed ref (filter.ts's leftDescriptor, matching the
1384
1675
  // UNRESOLVED_REFERENCE_MARKER case) - reproduces the original value_reference
@@ -1402,22 +1693,43 @@ function filterReferenceToTf(value, refs, role = "value", realType) {
1402
1693
  const fieldKey = parts[1];
1403
1694
  const address = refs.owner.fieldAddresses.get(fieldKey);
1404
1695
  const suffix = parts.slice(2).join(".");
1405
- const wireSuffix = suffix === "recordId" ? "10000001-2000-4000-a000-800000000000" : suffix;
1696
+ let wireSuffix = suffix === "recordId" ? "10000001-2000-4000-a000-800000000000" : suffix;
1406
1697
  // A bare reference to a PICKLIST field (STATUS/STAGE included —
1407
1698
  // `serializeSystemFields` wire-wraps both as a picklist too) has no
1408
1699
  // valid suffix-less wire form — confirmed live via the platform's
1409
1700
  // own switch-case editor, which always sends an explicit `.id`
1410
1701
  // (compare by the chosen option's real id) or `.label` (compare by
1411
1702
  // display text, unvalidated) and never a bare `record.<fieldId>`.
1412
- // Force the author to say which one they mean rather than guessing:
1413
- // a silent default reads as correct right up until the platform
1414
- // evaluates the two conventions differently, and there is no
1415
- // apply-time signal to catch that (the wire string is opaque to
1416
- // 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.
1417
1707
  if (suffix.length === 0 && refs.owner.fieldMetadata.get(fieldKey)?.fieldType === "PICKLIST") {
1418
- throw new EntityTfError(`filter reference to picklist field "${fieldKey}" is ambiguous — write ".id" ` +
1419
- `(ctx.trigger.record.${fieldKey}.id, compare by the option's id) or ".label" ` +
1420
- `(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
+ ]);
1421
1733
  }
1422
1734
  if (address !== undefined) {
1423
1735
  return expr.template([
@@ -1516,7 +1828,8 @@ function filterReferenceToTf(value, refs, role = "value", realType) {
1516
1828
  const task = refs.tasks.get(value.forEachTaskRefKey);
1517
1829
  if (task === undefined)
1518
1830
  throw new EntityTfError(`unresolved forEach filter ref "${value.forEachTaskRefKey}"`);
1519
- 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 }]);
1520
1833
  }
1521
1834
  case "VALUE":
1522
1835
  return valueToTf(value.value, refs);
@@ -1597,24 +1910,28 @@ function picklistFilterValueToTf(value, field, refs) {
1597
1910
  : `${scopedLabel(refs.owner.appTfLabel, tsLabelToTfLabel(field.refName))}_options_by_label`;
1598
1911
  return expr.local(localName, [{ index: value }]);
1599
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
+ }
1600
1921
  function fieldFromFilterLeftValue(value, refs) {
1601
1922
  if (!isObject(value) || !isObject(value.value) || value.value.type?.toString().toUpperCase() !== "TRIGGER") {
1602
1923
  return undefined;
1603
1924
  }
1604
- const name = value.value.name;
1605
- if (typeof name !== "string")
1606
- return undefined;
1607
- const path = name.split(".");
1608
- if (path[0] !== "record" || path.length < 2)
1925
+ const parsed = triggerRecordFieldPath(value.value);
1926
+ if (parsed === undefined)
1609
1927
  return undefined;
1610
- const refName = path[1];
1928
+ const { fieldKey: refName, suffix } = parsed;
1611
1929
  // Option-id resolution (picklistFilterValueToTf) only applies to the
1612
1930
  // ".id" convention `filterReferenceToTf` now requires for a picklist
1613
1931
  // field — an explicit ".label" (or any other drill-down suffix, e.g. a
1614
1932
  // USER field's ".email") compares raw text/whatever that sub-property
1615
1933
  // actually is, and must NOT have its value silently rewritten through
1616
1934
  // the options-by-label local.
1617
- const suffix = path.slice(2).join(".");
1618
1935
  if (suffix !== "" && suffix !== "id")
1619
1936
  return undefined;
1620
1937
  const metadata = refs.owner.fieldMetadata.get(refName);
@@ -1626,7 +1943,23 @@ function filterToTf(value, refs) {
1626
1943
  return serializeFilterToTf(value, {
1627
1944
  field: (field) => valueToTf(field, refs),
1628
1945
  fieldFromLeftValue: (left) => fieldFromFilterLeftValue(left, refs),
1629
- 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
+ },
1630
1963
  literal: (literal, field) => picklistFilterValueToTf(literal, token(field), refs) ?? valueToTf(literal, refs),
1631
1964
  });
1632
1965
  }
@@ -1635,6 +1968,15 @@ function configAttrs(kind, config, refs) {
1635
1968
  for (const [key, raw] of Object.entries(config)) {
1636
1969
  if (key === "name" || key === "type" || key === "aspectId" && kind.endsWith("_trigger"))
1637
1970
  continue;
1971
+ // Authoring-only schedule envelope (rrule / dtStart). The provider HCL
1972
+ // contract owns frequency/interval/timezone/start_at/weekdays/day_of_month
1973
+ // — the same fields WorkflowScheduleTriggerInput accepts.
1974
+ if (kind === "elementum_schedule_trigger" && (key === "rrule" || key === "dtStart"))
1975
+ continue;
1976
+ // interval defaults to 1 on the provider (Optional+Computed). Omit the
1977
+ // default so build matches export's omit-when-1 convention.
1978
+ if (kind === "elementum_schedule_trigger" && key === "interval" && raw === 1)
1979
+ continue;
1638
1980
  // A config value of exactly `undefined` almost always means the
1639
1981
  // authoring builder was called with a required option omitted (e.g. a
1640
1982
  // TS-only-enforced field that no runtime actually type-checks at
@@ -1758,8 +2100,23 @@ function configAttrs(kind, config, refs) {
1758
2100
  };
1759
2101
  });
1760
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
+ }
1761
2118
  else {
1762
- attrs.category_source = valueToTf(raw, refs);
2119
+ throw new EntityTfError("classification category source must be static or dynamic");
1763
2120
  }
1764
2121
  continue;
1765
2122
  }
@@ -1896,6 +2253,17 @@ function configAttrs(kind, config, refs) {
1896
2253
  const staticValue = isObject(field.valueReference) && "value" in field.valueReference
1897
2254
  ? field.valueReference.value
1898
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
+ }
1899
2267
  if (Array.isArray(staticValue)) {
1900
2268
  if (fieldToken?.fieldType !== "MULTI_PICKLIST") {
1901
2269
  throw new EntityTfError(`automation field "${fieldToken?.name ?? fieldToken?.refName ?? "unknown"}" uses an array value but is not a Multi-Select field`);
@@ -2138,6 +2506,12 @@ export function automationToTf(entity, ctx) {
2138
2506
  const taskRefs = new Map();
2139
2507
  const variableById = new Map();
2140
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();
2141
2515
  const preRegister = (tasks) => {
2142
2516
  for (const task of tasks) {
2143
2517
  const refKey = task.refKey;
@@ -2146,6 +2520,9 @@ export function automationToTf(entity, ctx) {
2146
2520
  if (taskRefs.has(refKey))
2147
2521
  throw new EntityTfError(`duplicate task refKey "${refKey}"`);
2148
2522
  const [wireType, taskBody] = onlyEntry(task.task, "task " + refKey);
2523
+ wireTypeByRefKey.set(refKey, wireType);
2524
+ if (wireType === "forEach")
2525
+ forEachCollectionByRefKey.set(refKey, taskBody.forEach);
2149
2526
  const resourceType = wireType === "variable" ? variableTaskResourceType(taskBody, refKey) : TASK_RESOURCES[wireType];
2150
2527
  if (resourceType === undefined)
2151
2528
  throw new EntityTfError(`task type "${wireType}" is not supported by the provider HCL contract`);
@@ -2183,6 +2560,21 @@ export function automationToTf(entity, ctx) {
2183
2560
  }
2184
2561
  };
2185
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
+ }));
2186
2578
  const dataBlocks = new Map();
2187
2579
  const recordFieldContext = recordFieldContextOf(entity);
2188
2580
  const triggerParamNames = triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
@@ -2205,6 +2597,22 @@ export function automationToTf(entity, ctx) {
2205
2597
  : [];
2206
2598
  })
2207
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
+ }
2208
2616
  const refs = {
2209
2617
  trigger: { type: triggerType, label },
2210
2618
  triggerParamNames,
@@ -2214,9 +2622,12 @@ export function automationToTf(entity, ctx) {
2214
2622
  owner,
2215
2623
  dataBlocks,
2216
2624
  variableById,
2625
+ recordItemForEachRefKeys,
2217
2626
  ...(recordFieldContext !== undefined ? { recordFieldContext } : {}),
2218
2627
  ...(ctx.fieldNamesByAppRefName !== undefined ? { fieldNamesByAppRefName: ctx.fieldNamesByAppRefName } : {}),
2628
+ ...(ctx.fieldAddressesByAppRefName !== undefined ? { fieldAddressesByAppRefName: ctx.fieldAddressesByAppRefName } : {}),
2219
2629
  ...(ctx.allowUnknownPicklistOptions === true ? { allowUnknownPicklistOptions: true } : {}),
2630
+ ...(triggerDatamineTable !== undefined ? { triggerDatamineTable } : {}),
2220
2631
  };
2221
2632
  let triggerAttrs;
2222
2633
  try {
@@ -2424,7 +2835,7 @@ export function automationToTf(entity, ctx) {
2424
2835
  // (a default branch renamed "Default Path" exports as
2425
2836
  // "..._default_path", not a hardcoded "..._default") - confirmed live.
2426
2837
  const fallbackLabel = isDefault ? "default" : `branch_${index + 1}`;
2427
- const branchLabel = `${tfLabel}_${snakeSlug(child.label ?? child.defaultLabel ?? fallbackLabel)}`;
2838
+ const branchLabel = `${tfLabel}_${sanitizeName(child.label ?? child.defaultLabel ?? fallbackLabel)}`;
2428
2839
  const branchAttrs = {
2429
2840
  [wireType === "switch" ? "switch_task" : "fork_join_task"]: address,
2430
2841
  ...(isDefault