@elementumai/edk 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +38 -6
  2. package/dist-sdk/src/core/triggers/on-demand.d.ts +2 -0
  3. package/dist-sdk/src/core/triggers/on-demand.js +3 -0
  4. package/dist-sdk/src/engine/coverage-gaps.d.ts +5 -0
  5. package/dist-sdk/src/engine/coverage-gaps.js +9 -0
  6. package/dist-sdk/src/engine/ei/run.d.ts +20 -1
  7. package/dist-sdk/src/engine/ei/run.js +102 -14
  8. package/dist-sdk/src/engine/pull/ref-only.d.ts +18 -0
  9. package/dist-sdk/src/engine/pull/ref-only.js +52 -0
  10. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +2 -1
  11. package/dist-sdk/src/entities/access-policy/from-tf.js +7 -1
  12. package/dist-sdk/src/entities/access-policy/module.js +5 -0
  13. package/dist-sdk/src/entities/app/build.d.ts +1 -1
  14. package/dist-sdk/src/entities/app/build.js +79 -4
  15. package/dist-sdk/src/entities/app/from-tf.js +1 -2
  16. package/dist-sdk/src/entities/app/stage-keys.d.ts +18 -3
  17. package/dist-sdk/src/entities/app/stage-keys.js +40 -6
  18. package/dist-sdk/src/entities/app/to-tf.js +1 -0
  19. package/dist-sdk/src/entities/automation/build.d.ts +50 -24
  20. package/dist-sdk/src/entities/automation/build.js +16 -6
  21. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +32 -3
  22. package/dist-sdk/src/entities/automation/from-tf.d.ts +13 -2
  23. package/dist-sdk/src/entities/automation/from-tf.js +269 -63
  24. package/dist-sdk/src/entities/automation/index.d.ts +1 -1
  25. package/dist-sdk/src/entities/automation/module.js +1 -1
  26. package/dist-sdk/src/entities/automation/run-target.d.ts +2 -0
  27. package/dist-sdk/src/entities/automation/run-target.js +5 -0
  28. package/dist-sdk/src/entities/automation/script-code.d.ts +2 -1
  29. package/dist-sdk/src/entities/automation/script-code.js +82 -1
  30. package/dist-sdk/src/entities/automation/script-lint.d.ts +13 -0
  31. package/dist-sdk/src/entities/automation/script-lint.js +418 -0
  32. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +1 -1
  33. package/dist-sdk/src/entities/automation/task-output-labels.js +9 -1
  34. package/dist-sdk/src/entities/automation/tasks.d.ts +47 -14
  35. package/dist-sdk/src/entities/automation/tasks.js +18 -4
  36. package/dist-sdk/src/entities/automation/to-tf.js +256 -28
  37. package/dist-sdk/src/entities/automation/triggers.d.ts +48 -15
  38. package/dist-sdk/src/entities/automation/triggers.js +9 -9
  39. package/dist-sdk/src/entities/chart/build.d.ts +9 -1
  40. package/dist-sdk/src/entities/chart/from-tf.d.ts +2 -2
  41. package/dist-sdk/src/entities/chart/from-tf.js +25 -1
  42. package/dist-sdk/src/entities/chart/index.d.ts +1 -1
  43. package/dist-sdk/src/entities/chart/printer.js +5 -2
  44. package/dist-sdk/src/entities/chart/to-tf.js +19 -1
  45. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +1 -0
  46. package/dist-sdk/src/entities/dynamic-layout/condition-keys.d.ts +48 -0
  47. package/dist-sdk/src/entities/dynamic-layout/condition-keys.js +261 -0
  48. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +1 -1
  49. package/dist-sdk/src/entities/dynamic-layout/module.js +2 -1
  50. package/dist-sdk/src/entities/element/to-tf.js +1 -0
  51. package/dist-sdk/src/entities/field/module.js +8 -2
  52. package/dist-sdk/src/entities/field/to-tf.d.ts +8 -2
  53. package/dist-sdk/src/entities/field/to-tf.js +57 -34
  54. package/dist-sdk/src/entities/org/role.js +5 -0
  55. package/dist-sdk/src/entities/service-account/module.js +5 -0
  56. package/dist-sdk/src/entities/service-account/role-fidelity.d.ts +5 -5
  57. package/dist-sdk/src/entities/service-account/role-fidelity.js +21 -13
  58. package/dist-sdk/src/entities/shared/filters/ast.d.ts +2 -0
  59. package/dist-sdk/src/entities/shared/types/field-types.d.ts +6 -3
  60. package/dist-sdk/src/entities/shared/types/field-types.js +3 -1
  61. package/dist-sdk/src/entities/skill/module.js +2 -0
  62. package/dist-sdk/src/entities/task/to-tf.js +1 -0
  63. package/dist-sdk/src/entities/view/from-tf.d.ts +8 -4
  64. package/dist-sdk/src/entities/view/from-tf.js +3 -5
  65. package/dist-sdk/src/entities/view/module.js +5 -0
  66. package/dist-sdk/src/entities/widget/from-tf.js +2 -2
  67. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +5 -3
  68. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  69. package/dist-sdk/src/graph/index.d.ts +15 -2
  70. package/dist-sdk/src/graph/index.js +12 -0
  71. package/dist-sdk/src/graph/types.d.ts +38 -0
  72. package/package.json +1 -1
@@ -116,8 +116,11 @@ type ValidatedUpdateFieldAssignments<Fields extends readonly FieldAssignment[]>
116
116
  };
117
117
  export interface UpdateFieldOptions<A extends AppOrElementOrTaskRef = AppOrElementOrTaskRef, Fields extends readonly FieldAssignment[] = readonly FieldAssignment[]> {
118
118
  readonly app: A;
119
- /** The record to update (e.g. `ctx.trigger.record` or `.record.recordId`). */
120
- readonly record: RecordReference<A>;
119
+ /**
120
+ * The record to update (e.g. `ctx.trigger.record` or `.record.recordId`),
121
+ * or every record a search found (`ctx.actions.<search>.records`).
122
+ */
123
+ readonly record: RecordReference<A> | Ref<readonly RecordShape<A>[]>;
121
124
  readonly fields: Fields & ValidatedUpdateFieldAssignments<NoInfer<Fields>>;
122
125
  }
123
126
  /** Update fields on an existing record. `value: ""` or `value: null` clears a nullable field (including Dropdown). */
@@ -168,11 +171,23 @@ export interface RelateRecordsOptions {
168
171
  readonly target: ValueOrRef<unknown>;
169
172
  }
170
173
  export declare function relateRecords(opts: RelateRecordsOptions): ActionDef<Record<string, never>>;
171
- /** An email attachment: a literal/ref file value, or an existing record's attachment field to reuse. */
174
+ /**
175
+ * A file to attach to the email. Set exactly one key: `attachment` is an
176
+ * attachment field, `file` is a file from the trigger or an earlier task, and
177
+ * `record` attaches every file on a record.
178
+ */
172
179
  export type EmailAttachment = {
180
+ readonly attachment: ValueOrRef<unknown>;
181
+ readonly file?: never;
182
+ readonly record?: never;
183
+ } | {
173
184
  readonly file: ValueOrRef<unknown>;
185
+ readonly attachment?: never;
186
+ readonly record?: never;
174
187
  } | {
175
- readonly fromRecord: ValueOrRef<unknown>;
188
+ readonly record: ValueOrRef<unknown>;
189
+ readonly attachment?: never;
190
+ readonly file?: never;
176
191
  };
177
192
  export interface SendEmailOptions {
178
193
  readonly subject: ValueOrRef<unknown>;
@@ -185,12 +200,19 @@ export interface SendEmailOptions {
185
200
  readonly toGroups?: readonly ValueOrRef<unknown>[];
186
201
  /** Literal email addresses. */
187
202
  readonly toAddresses?: readonly ValueOrRef<unknown>[];
203
+ /** Files to attach. Omit to leave the live attachments as they are; `[]` removes them. */
188
204
  readonly attachments?: readonly EmailAttachment[];
205
+ /**
206
+ * The platform id of a DNS-verified sending domain. Omit to keep the live
207
+ * task's domain, including one chosen in the web app; omitting it does not
208
+ * reset the task to the default domain.
209
+ */
210
+ readonly emailSendDomainId?: string;
189
211
  }
190
212
  export declare function sendEmail(opts: SendEmailOptions): ActionDef<Record<string, never>>;
191
213
  export interface PostCommentOptions {
192
214
  readonly contents: ValueOrRef<unknown>;
193
- /** Conversation tags. Omit for an untagged comment — the provider's message task has no tags of its own. */
215
+ /** Channel (Select Channel): omit or `["public"]` for the Public Channel; `["consumer"]` for the Customer Channel (needs customer chat on the app's record comments). */
194
216
  readonly tags?: readonly string[];
195
217
  /** The record to comment on (required). */
196
218
  readonly record: ValueOrRef<unknown>;
@@ -316,12 +338,13 @@ type ExecuteScriptFieldValue<T extends ScriptOutputType> = T extends {
316
338
  readonly [K in keyof P]: ExecuteScriptFieldValue<P[K]>;
317
339
  } : T extends {
318
340
  readonly type: "object";
319
- } ? Record<string, unknown> : T extends "integer" | "number" | "decimal" ? number : T extends "boolean" ? boolean : string;
341
+ } | "object" ? Record<string, unknown> : T extends "integer" | "number" | "decimal" ? number : T extends "boolean" ? boolean : string;
320
342
  /** The properties of an authored `outputs` option, in either accepted form. */
321
343
  type ScriptOutputPropertiesOf<O> = O extends {
322
344
  readonly properties: ScriptOutputProperties;
323
345
  } ? O["properties"] : O extends ScriptOutputProperties ? O : undefined;
324
- type ExecuteScriptOutput<O extends ScriptOutputs | undefined> = {
346
+ /** Result shape for an executeScript whose `outputs` option is `O`. */
347
+ export type ExecuteScriptOutput<O extends ScriptOutputs | undefined> = {
325
348
  readonly result: ScriptOutputPropertiesOf<O> extends ScriptOutputProperties ? {
326
349
  readonly [K in keyof ScriptOutputPropertiesOf<O>]: ExecuteScriptFieldValue<Extract<ScriptOutputPropertiesOf<O>[K], ScriptOutputType>>;
327
350
  } : Record<string, unknown>;
@@ -354,9 +377,12 @@ export interface ExecuteScriptListInputToken {
354
377
  * can read - which fields, and under what alias. The value is a whole record
355
378
  * or a list of records (a prior task's `.records`, read per item).
356
379
  *
357
- * Inside this wrapper these deploy the whole record: a record trigger's
358
- * `ctx.trigger.record`, and the `.record` of `recordSearch`, `createRecord`
359
- * and `updateField`. Elsewhere they are the record ID a `record:` slot takes.
380
+ * Inside this wrapper a record trigger's `ctx.trigger.record` deploys the
381
+ * whole record. The `.record` of `recordSearch`, `createRecord` and
382
+ * `updateField` is the whole record in any script input, wrapped or not.
383
+ * `.record.recordId` is the ID for `recordSearch` and `createRecord`. An
384
+ * Update Field `.record.recordId` does not build. Elsewhere they are the
385
+ * record ID a `record:` slot takes.
360
386
  * An on-demand record parameter and `findRelatedRecords`' `.record` expose
361
387
  * only the record ID, so they stay the ID here too.
362
388
  */
@@ -914,7 +940,8 @@ export interface RunAutomationStaticOptions<A extends AutomationCatalogRef = Aut
914
940
  * The UI's "Dynamic Reference" mode: the automation to run is a value
915
941
  * resolved at runtime, such as a trigger parameter or an earlier step's
916
942
  * output holding an automation ID. The platform always waits for a dynamic
917
- * target, so `synchronous` must be `true`.
943
+ * target, so `synchronous` must be `true`. Its outputs don't come back today
944
+ * (see `outputs`).
918
945
  */
919
946
  export interface RunAutomationDynamicReferenceOptions<Outputs extends readonly string[] | undefined = undefined> {
920
947
  readonly automation: Ref<string>;
@@ -922,9 +949,15 @@ export interface RunAutomationDynamicReferenceOptions<Outputs extends readonly s
922
949
  /** Input mappings by the target's on-demand trigger parameter **name**. */
923
950
  readonly inputs?: readonly RunAutomationInput[];
924
951
  /**
925
- * Output names to capture from whichever automation runs. The target is
926
- * unknown at build time, so each captured name is `unknown`. Omitting
927
- * `outputs` exposes nothing on the step result.
952
+ * Output names to expose on the step result. The target is unknown at build
953
+ * time, so each name is `unknown`. Omitting `outputs` exposes nothing.
954
+ *
955
+ * The platform doesn't return a Dynamic Reference target's outputs today:
956
+ * every name listed here reads as null at run time, though the same target
957
+ * called with Select Automation returns them (edk#1869). To get a result
958
+ * back, have the target report it instead: give a separate on-demand
959
+ * automation trigger inputs for the result, and end the target with a
960
+ * Select Automation `runAutomation` to it that maps them.
928
961
  */
929
962
  readonly outputs?: Outputs;
930
963
  }
@@ -131,8 +131,18 @@ export function relateRecords(opts) {
131
131
  function refList(values) {
132
132
  return values === undefined ? undefined : values.map((v) => typeof v === "object" && v !== null && "__kind" in v && v.__kind === "user" ? v : serializeValueOrRef(v));
133
133
  }
134
+ const EMAIL_ATTACHMENT_KEYS = ["attachment", "file", "record"];
134
135
  function serializeEmailAttachment(a) {
135
- return "file" in a ? { file: serializeValueOrRef(a.file) } : { record: serializeValueOrRef(a.fromRecord) };
136
+ const unknownKeys = Object.keys(a).filter((key) => !EMAIL_ATTACHMENT_KEYS.includes(key));
137
+ if (unknownKeys.length > 0) {
138
+ throw new Error(`sendEmail attachment has unsupported key ${unknownKeys.map((k) => `"${k}"`).join(", ")}; set exactly one of attachment, file, or record.`);
139
+ }
140
+ const present = EMAIL_ATTACHMENT_KEYS.filter((key) => a[key] !== undefined);
141
+ if (present.length !== 1) {
142
+ throw new Error("sendEmail attachment must set exactly one of attachment, file, or record.");
143
+ }
144
+ const key = present[0];
145
+ return { [key]: serializeValueOrRef(a[key]) };
136
146
  }
137
147
  export function sendEmail(opts) {
138
148
  if (!opts.toUsers?.length && !opts.toGroups?.length && !opts.toAddresses?.length) {
@@ -151,6 +161,7 @@ export function sendEmail(opts) {
151
161
  ...(opts.attachments !== undefined
152
162
  ? { emailAttachments: opts.attachments.map(serializeEmailAttachment) }
153
163
  : {}),
164
+ ...(opts.emailSendDomainId !== undefined ? { emailSendDomainId: opts.emailSendDomainId } : {}),
154
165
  },
155
166
  };
156
167
  }
@@ -310,9 +321,12 @@ const EXECUTE_SCRIPT_LIST_INPUT_MARKER = "__edkExecuteScriptListInput";
310
321
  * can read - which fields, and under what alias. The value is a whole record
311
322
  * or a list of records (a prior task's `.records`, read per item).
312
323
  *
313
- * Inside this wrapper these deploy the whole record: a record trigger's
314
- * `ctx.trigger.record`, and the `.record` of `recordSearch`, `createRecord`
315
- * and `updateField`. Elsewhere they are the record ID a `record:` slot takes.
324
+ * Inside this wrapper a record trigger's `ctx.trigger.record` deploys the
325
+ * whole record. The `.record` of `recordSearch`, `createRecord` and
326
+ * `updateField` is the whole record in any script input, wrapped or not.
327
+ * `.record.recordId` is the ID for `recordSearch` and `createRecord`. An
328
+ * Update Field `.record.recordId` does not build. Elsewhere they are the
329
+ * record ID a `record:` slot takes.
316
330
  * An on-demand record parameter and `findRelatedRecords`' `.record` expose
317
331
  * only the record ID, so they stay the ID here too.
318
332
  */
@@ -7,6 +7,8 @@ import { appResourceLabelPrefix, appScopedResourceLabel, expr, isTfExpr, isUuid,
7
7
  import { workspaceAspectKey } from "../../engine/build/context.js";
8
8
  import { SEARCH_TABLE_RESOURCE_TYPES } from "../search-table/types.js";
9
9
  import { fieldRefToTfValue } from "../field/to-tf.js";
10
+ import { scriptLintFindings } from "./script-lint.js";
11
+ import { MANAGED_FIELD_ORDER_RESOURCE_TYPE } from "../field/types.js";
10
12
  import { SERVICE_ACCOUNT_RESOURCE_TYPE } from "../service-account/module.js";
11
13
  import { serviceAccountRefToTf } from "../service-account/to-tf.js";
12
14
  import { workspaceServiceAccountAppResolver } from "../service-account/workspace-owner.js";
@@ -228,7 +230,7 @@ const CONFIG_ATTRS = {
228
230
  fromUsername: "from_username",
229
231
  fromPersonal: "from_personal",
230
232
  externalEmails: "external_emails",
231
- emailAttachments: "attachments",
233
+ emailAttachments: "email_attachments",
232
234
  contentsReference: "message",
233
235
  agentId: "agent_id",
234
236
  agentPrompt: "prompt",
@@ -280,6 +282,66 @@ function onlyEntry(value, subject) {
280
282
  }
281
283
  return entries[0];
282
284
  }
285
+ /**
286
+ * Tasks whose refs carry every field of the record they search (edk#2280)
287
+ * or create (edk#2406). update_field refs carry them too and aren't covered yet.
288
+ */
289
+ const OBJECT_FIELD_REFS_TASK_TYPES = new Set([
290
+ "elementum_record_search_task",
291
+ "elementum_find_related_records_task",
292
+ "elementum_create_record_task",
293
+ ]);
294
+ /**
295
+ * Triggers whose refs were confirmed to carry every custom field of the
296
+ * owner's record (a Preston High state with 18 field types). Build sets
297
+ * `object_field_ids` on these triggers only.
298
+ */
299
+ const OBJECT_FIELD_REFS_TRIGGER_TYPES = new Set([
300
+ "elementum_record_created_trigger",
301
+ "elementum_record_updated_trigger",
302
+ "elementum_comment_added_trigger",
303
+ "elementum_attachment_added_trigger",
304
+ "elementum_agent_conversation_ended_trigger",
305
+ "elementum_on_demand_trigger",
306
+ ]);
307
+ /**
308
+ * A record-bearing task's or trigger's write-only `object_field_ids`
309
+ * (edk#2280). It is the field order of its app or element, so a field created
310
+ * in the same apply plans `refs` unknown instead of keeping refs read before
311
+ * the field existed. Only an owner whose own fields this build writes (and so
312
+ * whose `elementum_managed_field_order` it writes) gets one. ei's export sets it
313
+ * only for the exported app or element. A pull builds only that root, so the
314
+ * two agree there.
315
+ */
316
+ function objectFieldIdsAttr(objectId, fieldAddresses) {
317
+ if (fieldAddresses === undefined || fieldAddresses.size === 0)
318
+ return {};
319
+ if (objectId === undefined || !isTfExpr(objectId) || objectId.$expr !== "resource-attr" || objectId.path.length !== 1 || objectId.path[0] !== "id")
320
+ return {};
321
+ const scope = objectId.type === "elementum_app" ? "app" : objectId.type === "elementum_element" ? "element" : undefined;
322
+ if (scope === undefined)
323
+ return {};
324
+ // The addresses must be this owner's own fields, since an app and an element can share a refName.
325
+ const fieldLabelPrefix = scopedResourceLabel(objectId.label, "", scope);
326
+ const ownFields = [...fieldAddresses.values()].some((address) => address.slice(address.indexOf(".") + 1).startsWith(fieldLabelPrefix));
327
+ if (!ownFields)
328
+ return {};
329
+ return {
330
+ object_field_ids: expr.resourceAttr(MANAGED_FIELD_ORDER_RESOURCE_TYPE, scopedResourceLabel(objectId.label, "field_order", scope), ["field_ids"]),
331
+ };
332
+ }
333
+ /** The field addresses this build writes for a task's `aspectId` target. */
334
+ function taskTargetFieldAddresses(aspectId, owner) {
335
+ const target = token(aspectId);
336
+ if (target === undefined || typeof target.refName !== "string")
337
+ return undefined;
338
+ const kind = target.__kind === "element" ? "element" : target.__kind === "app" ? "app" : undefined;
339
+ if (kind === undefined)
340
+ return undefined;
341
+ if (target.refName === owner.appRefName && kind === owner.parentScope)
342
+ return owner.fieldAddresses;
343
+ return fieldNamesForAppRefName(owner.fieldAddressesByAppRefName, target.refName);
344
+ }
283
345
  function token(value) {
284
346
  if (!isObject(value) || typeof value.__kind !== "string")
285
347
  return undefined;
@@ -1225,12 +1287,37 @@ function calculationTaskRefName(targetType, name, taskRefKey, refs) {
1225
1287
  suffix.length > 0 ? `.${suffix}` : "",
1226
1288
  ];
1227
1289
  }
1228
- const refName = taskOutputReferenceName(targetType, name, refs.tasks.get(taskRefKey)) ?? name;
1290
+ // A single-output AI task's `.output` reaches here as its refs label
1291
+ // (`Response`); the calc engine resolves only the canonical name (`response`, #2405).
1292
+ const refName = taskOutputReferenceName(targetType, name, refs.tasks.get(taskRefKey)) ??
1293
+ canonicalSingleOutputName(targetType, name) ?? name;
1229
1294
  if (refName.includes('"')) {
1230
1295
  throw new EntityTfError(`calculation task output name "${refName}" contains a double quote`);
1231
1296
  }
1232
1297
  return [refName];
1233
1298
  }
1299
+ /**
1300
+ * Output → refs-map key, the inverse of TASK_OUTPUT_REFERENCE_NAMES, for the
1301
+ * tasks whose refs are keyed by display label: bulkUpdateFields (edk#2281) and
1302
+ * tableRecordsSearch (edk#2407, whose count is authored as `totalCount`).
1303
+ * Envelopes and calculations keep the output's own name.
1304
+ */
1305
+ function inverseReferenceNames(resourceType) {
1306
+ return Object.fromEntries(Object.entries(TASK_OUTPUT_REFERENCE_NAMES[resourceType] ?? {}).map(([key, name]) => [name, key]));
1307
+ }
1308
+ const BULK_UPDATE_FIELDS_REFS_INDEX = inverseReferenceNames(TASK_RESOURCES.bulkUpdateFields);
1309
+ const TABLE_RECORDS_SEARCH_REFS_INDEX = (() => {
1310
+ const index = inverseReferenceNames(TASK_RESOURCES.tableRecordsSearch);
1311
+ return { ...index, totalCount: index["count"] };
1312
+ })();
1313
+ /** refs-map key for a task output keyed by a display label (AI completion tasks, bulkUpdateFields, tableRecordsSearch), or undefined. */
1314
+ function taskOutputRefsIndex(resourceType, name) {
1315
+ if (resourceType === TASK_RESOURCES.bulkUpdateFields)
1316
+ return BULK_UPDATE_FIELDS_REFS_INDEX[name];
1317
+ if (resourceType === TASK_RESOURCES.tableRecordsSearch)
1318
+ return TABLE_RECORDS_SEARCH_REFS_INDEX[name];
1319
+ return aiCompletionRefsIndex(resourceType, name);
1320
+ }
1234
1321
  /** A refs key's WorkflowTaskReference name. An apiRequest maps only when it's JSON; FILE and CUSTOM are unconfirmed live (edk#2058). */
1235
1322
  function taskOutputReferenceName(type, wireName, task) {
1236
1323
  if (type === TASK_RESOURCES.api && task?.jsonApiResponse !== true)
@@ -1749,9 +1836,10 @@ function taskOutputWireRefKey(targetType, name, taskRefKey, refs) {
1749
1836
  if (scriptIndex !== undefined)
1750
1837
  return scriptIndex;
1751
1838
  }
1752
- const aiIndex = aiCompletionRefsIndex(targetType, name);
1753
- if (aiIndex !== undefined)
1754
- return aiIndex;
1839
+ // AI completion, bulkUpdateFields (edk#2281) and tableRecordsSearch (edk#2407) outputs are keyed by display label.
1840
+ const labelIndex = taskOutputRefsIndex(targetType, name);
1841
+ if (labelIndex !== undefined)
1842
+ return labelIndex;
1755
1843
  return taskWireRefName(name, taskRefKey, refs);
1756
1844
  }
1757
1845
  /** The platform's own on-demand "Triggered By" refs (live refs-map keys). */
@@ -2504,6 +2592,10 @@ function valueToTf(value, refs) {
2504
2592
  function snake(name) {
2505
2593
  return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/-/g, "_").toLowerCase();
2506
2594
  }
2595
+ /** The provider's `default_value` is a string: a Checkbox default is `"true"` or `"false"`, as `ei` export writes it. */
2596
+ function onDemandDefaultToTf(value) {
2597
+ return typeof value === "boolean" ? String(value) : value;
2598
+ }
2507
2599
  function unwrapDefault(value) {
2508
2600
  if (!isObject(value))
2509
2601
  return value;
@@ -2579,7 +2671,8 @@ function onDemandRecordFieldFilterReference(name, refs, operator) {
2579
2671
  /**
2580
2672
  * The canonical (`service_tasks`) name of a single-output AI task's output,
2581
2673
  * when `wireName` is that output's refs display label. The filter short form
2582
- * `task.<id>.<name>` uses it (`response`), not the label (`Response`).
2674
+ * `task.<id>.<name>` and a calculation's `{{task name="..."}}` use it
2675
+ * (`response`), not the label (`Response`, #2405).
2583
2676
  */
2584
2677
  function canonicalSingleOutputName(resourceType, wireName) {
2585
2678
  const taskKey = Object.keys(TASK_RESOURCES).find((key) => TASK_RESOURCES[key] === resourceType);
@@ -2587,6 +2680,27 @@ function canonicalSingleOutputName(resourceType, wireName) {
2587
2680
  return undefined;
2588
2681
  return OUTPUT_KEY_CANONICAL[taskKey];
2589
2682
  }
2683
+ /**
2684
+ * A Table Records Search's or AI Data Search's `.records` read as a filter
2685
+ * value, by authored name or refs key, keyed by resource type (edk#2402). The
2686
+ * filter value spells it by its output contract name, not the refs key
2687
+ * ("All matching table rows", "All Records") or Record Search's
2688
+ * `All found records`.
2689
+ */
2690
+ const SEARCH_RECORDS_FILTER_NAMES = {
2691
+ [TASK_RESOURCES.tableRecordsSearch]: { names: ["records", "All matching table rows"], contractName: "records" },
2692
+ [TASK_RESOURCES.aiSearchTable]: { names: ["records", AI_SEARCH_TABLE_OUTPUT_NAMES.records[0]], contractName: AI_SEARCH_TABLE_OUTPUT_NAMES.records[1] },
2693
+ };
2694
+ function searchRecordsContractName(resourceType, name, wireName) {
2695
+ const entry = SEARCH_RECORDS_FILTER_NAMES[resourceType];
2696
+ if (entry === undefined || !(entry.names.includes(name) || entry.names.includes(wireName)))
2697
+ return undefined;
2698
+ const executor = RESOURCE_TYPE_TO_EXECUTOR[resourceType];
2699
+ if (executor === undefined || TASK_OUTPUT_CONTRACTS[executor]?.[entry.contractName] === undefined) {
2700
+ throw new EntityTfError(`${resourceType} has no "${entry.contractName}" output contract`);
2701
+ }
2702
+ return entry.contractName;
2703
+ }
2590
2704
  const TRIGGER_REFERENCE_NAME_PATTERN = /^[a-z][A-Za-z0-9]*(?:\.[a-z][A-Za-z0-9]*)*$/;
2591
2705
  function filterReferenceToTf(value, refs, role = "value", realType, operator) {
2592
2706
  // Raw pass-through for a filter left side the pull-time deserializer
@@ -2729,9 +2843,25 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
2729
2843
  throw new EntityTfError(`unresolved task filter ref "${value.taskRefKey}"`);
2730
2844
  const isFileReaderTask = task.type === "elementum_ai_file_read_task" || task.type === "elementum_file_reader_task";
2731
2845
  const isAiAgentTask = task.type === "elementum_ai_agent_task";
2846
+ // A found record's field on the value side is spelled by field id, so
2847
+ // its refs label is never needed. That label has no form for a field
2848
+ // of the related record (`record.<field>.<related field id>`).
2849
+ const recordFieldName = role === "left"
2850
+ ? undefined
2851
+ : foundRecordFieldReferenceName(task.type, value.name, value.taskRefKey, refs);
2852
+ if (recordFieldName !== undefined) {
2853
+ return expr.template(["task.", expr.resourceAttr(task.type, task.label, ["id"]), ".", ...recordFieldName]);
2854
+ }
2855
+ // A Table Records Search switch reads its refs by display label
2856
+ // (edk#2407). Look the authored name up before taskWireRefName, whose
2857
+ // generic rewrite turns `record` into `Record`, as taskOutputWireRefKey
2858
+ // does. `records` keeps its current spelling.
2859
+ const tableSearchLabel = role === "left" && task.type === TASK_RESOURCES.tableRecordsSearch && value.name !== "records"
2860
+ ? taskOutputRefsIndex(task.type, value.name)
2861
+ : undefined;
2732
2862
  const wireName = isFileReaderTask || isAiAgentTask
2733
2863
  ? value.name
2734
- : taskWireRefName(value.name, value.taskRefKey, refs);
2864
+ : tableSearchLabel ?? taskWireRefName(value.name, value.taskRefKey, refs);
2735
2865
  // left_value (switch cases): provider Read stores the JSON envelope that
2736
2866
  // `.refs["…"]` evaluates to (#490). Emitting the short `task.<id>.…`
2737
2867
  // string matches record_search RHS state but perpetual-diffs left_value.
@@ -2823,10 +2953,14 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
2823
2953
  // flattened. A NUMBER comparison of a DECIMAL script output is the
2824
2954
  // next branch (#1618).
2825
2955
  const envelopeName = taskOutputReferenceName(task.type, wireName, task) ?? wireName;
2826
- const executor = RESOURCE_TYPE_TO_EXECUTOR[task.type];
2827
- const declared = task.outputFieldTypes?.get(wireName) ??
2828
- (executor === undefined ? undefined : TASK_OUTPUT_CONTRACTS[executor]?.[envelopeName]);
2829
- const compared = realType?.toUpperCase();
2956
+ const declared = declaredTaskOutputType(task, wireName, envelopeName);
2957
+ // This includes a Table Records Search row (TABLE_RECORD): the
2958
+ // platform stores only the condition's real_type, so a check of
2959
+ // `.record`, bare (built with real_type text) or `filter.text(…)`, is
2960
+ // read back and exported as the TEXT envelope named `record`
2961
+ // (edk#2407).
2962
+ const isTableSearchRow = task.type === TASK_RESOURCES.tableRecordsSearch && declared?.fieldType === "TABLE_RECORD" && declared.multiple !== true;
2963
+ const compared = realType?.toUpperCase() ?? (isTableSearchRow ? "TEXT" : undefined);
2830
2964
  if (compared !== undefined &&
2831
2965
  declared !== undefined &&
2832
2966
  declared.fieldType !== compared &&
@@ -2901,29 +3035,37 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
2901
3035
  }
2902
3036
  const refsIndex = task.type === TASK_RESOURCES.executeScript
2903
3037
  ? executeScriptRefsIndex(wireName) ?? wireName
2904
- : aiCompletionRefsIndex(task.type, wireName) ?? wireName;
3038
+ : taskOutputRefsIndex(task.type, wireName) ?? wireName;
2905
3039
  return expr.resourceAttr(task.type, task.label, ["refs", { index: refsIndex }]);
2906
3040
  }
2907
- const recordFieldName = foundRecordFieldReferenceName(task.type, value.name, value.taskRefKey, refs);
2908
3041
  // The short form addresses user-search outputs by path, and an AI task's
2909
3042
  // single output by its canonical name (`response`, edk#1509); only
2910
3043
  // `.refs` is keyed by their display labels. recordSearch's ASPECT_RECORD_ID
2911
3044
  // is keyed `First found record id` in refs, but filter RHS / ei export use
2912
3045
  // the canonical short name `recordId` (service_tasks) — emitting the
2913
- // display label here plans drift after every pull (edk#1524).
3046
+ // display label here plans drift after every pull (edk#1524). Its
3047
+ // `All found records` short name is `records`, and a Find Related
3048
+ // Records filter value uses that same short name. A Table Records
3049
+ // Search's or AI Data Search's `.records` uses its contract name.
3050
+ const searchRecords = searchRecordsContractName(task.type, value.name, wireName);
2914
3051
  const shortName = task.type === TASK_RESOURCES.userSearch
2915
3052
  ? USER_SEARCH_PATH_BY_WIRE_NAME.get(wireName) ?? wireName
2916
3053
  : task.type === TASK_RESOURCES.recordSearch &&
2917
3054
  (wireName === "First found record id" || value.name === "record.recordId" || value.name === "recordId")
2918
3055
  ? "recordId"
2919
- : task.type === TASK_RESOURCES.api
2920
- ? taskOutputReferenceName(task.type, wireName, task) ?? wireName
2921
- : canonicalSingleOutputName(task.type, wireName) ?? wireName;
3056
+ : (task.type === TASK_RESOURCES.recordSearch || task.type === TASK_RESOURCES.findRelatedRecords) &&
3057
+ (wireName === "All found records" || value.name === "records")
3058
+ ? "records"
3059
+ : searchRecords !== undefined
3060
+ ? searchRecords
3061
+ : task.type === TASK_RESOURCES.api
3062
+ ? taskOutputReferenceName(task.type, wireName, task) ?? wireName
3063
+ : canonicalSingleOutputName(task.type, wireName) ?? wireName;
2922
3064
  return expr.template([
2923
3065
  "task.",
2924
3066
  expr.resourceAttr(task.type, task.label, ["id"]),
2925
3067
  ".",
2926
- ...(recordFieldName ?? [shortName]),
3068
+ shortName,
2927
3069
  ]);
2928
3070
  }
2929
3071
  case "FOR_EACH": {
@@ -3098,12 +3240,53 @@ function recordRefKeyIsAmbiguous(name, wireName, taskRefKey, refs) {
3098
3240
  }
3099
3241
  return false;
3100
3242
  }
3243
+ /** A task output's declared type: from the task's own output schema, else the executor's output contract. */
3244
+ function declaredTaskOutputType(task, wireName, envelopeName) {
3245
+ const executor = RESOURCE_TYPE_TO_EXECUTOR[task.type];
3246
+ return task.outputFieldTypes?.get(wireName) ??
3247
+ (executor === undefined ? undefined : TASK_OUTPUT_CONTRACTS[executor]?.[envelopeName]);
3248
+ }
3249
+ /**
3250
+ * A switch case comparing a single BOOLEAN task output with no typed wrapper
3251
+ * (`filter.eq(ctx.actions.B.allMatchingRecordsUpdated, true)`) compares as
3252
+ * BOOLEAN, the same as `filter.boolean(...)`. Built with the operator's TEXT
3253
+ * fallback, the platform stores a text comparison, pull prints it back as
3254
+ * `filter.text(...)`, and the plan after that pull changes the envelope's
3255
+ * fieldType BOOLEAN -> TEXT (#2404). Only that fallback yields: a typed
3256
+ * wrapper (`filter.text(...)`) is explicit and never reaches this hook.
3257
+ */
3258
+ function booleanTaskOutputRealType(reference, refs, authored) {
3259
+ if (authored !== undefined && authored.toUpperCase() !== "TEXT")
3260
+ return undefined;
3261
+ if (!isObject(reference) || reference.type?.toString().toUpperCase() !== "TASK")
3262
+ return undefined;
3263
+ if (typeof reference.taskRefKey !== "string" || typeof reference.name !== "string")
3264
+ return undefined;
3265
+ const task = refs.tasks.get(reference.taskRefKey);
3266
+ // These spell their left values by their own rules in filterReferenceToTf.
3267
+ if (task === undefined ||
3268
+ task.type === "elementum_ai_file_read_task" ||
3269
+ task.type === "elementum_file_reader_task" ||
3270
+ task.type === "elementum_ai_agent_task" ||
3271
+ task.type === TASK_RESOURCES.tableRecordsSearch) {
3272
+ return undefined;
3273
+ }
3274
+ const wireName = taskWireRefName(reference.name, reference.taskRefKey, refs);
3275
+ const envelopeName = taskOutputReferenceName(task.type, wireName, task) ?? wireName;
3276
+ const declared = declaredTaskOutputType(task, wireName, envelopeName);
3277
+ return declared?.fieldType === "BOOLEAN" && declared.multiple !== true ? "BOOLEAN" : undefined;
3278
+ }
3101
3279
  function filterToTf(value, refs) {
3102
3280
  return serializeFilterToTf(value, {
3103
3281
  field: (field) => valueToTf(field, refs),
3104
3282
  fieldFromLeftValue: (left) => fieldFromFilterLeftValue(left, refs),
3105
3283
  reference: (reference, role, realType, operator) => filterReferenceToTf(reference, refs, role ?? "value", realType, operator),
3106
- referenceRealType: (reference, _role, authored) => {
3284
+ referenceRealType: (reference, role, authored) => {
3285
+ if (role === "left") {
3286
+ const booleanOutput = booleanTaskOutputRealType(reference, refs, authored);
3287
+ if (booleanOutput !== undefined)
3288
+ return booleanOutput;
3289
+ }
3107
3290
  if (!isObject(reference) || reference.type?.toString().toUpperCase() !== "TRIGGER")
3108
3291
  return authored;
3109
3292
  const parsed = triggerRecordFieldPath(reference, refs);
@@ -3147,6 +3330,22 @@ function isRunAutomationValueReference(raw) {
3147
3330
  isObject(raw.secretReference) ||
3148
3331
  isObject(raw.variableReference));
3149
3332
  }
3333
+ /**
3334
+ * #1870: the platform compiles a synchronous Dynamic Reference call to a WAIT
3335
+ * task and resumes the caller by matching that task's exact name. Inside a
3336
+ * forEach the loop suffixes the name per iteration, so the completion never
3337
+ * matches: the called automation runs, but the caller never resumes. The task
3338
+ * is still built and applied as authored (an advisory, coverage-gaps.ts).
3339
+ */
3340
+ function dynamicSyncRunInForEachWarning(refKey, config, enclosingForEach) {
3341
+ if (enclosingForEach === undefined || config.synchronous !== true || !isRunAutomationValueReference(config.targetAutomationRef)) {
3342
+ return undefined;
3343
+ }
3344
+ return `task "${refKey}" is a synchronous Dynamic Reference runAutomation inside forEach "${enclosingForEach}"; ` +
3345
+ "the platform never resumes the caller after the called automation finishes, so the steps after it never run " +
3346
+ "and the run stays parked. Move the call out of the forEach, or call a known automation by its catalog ref " +
3347
+ "(Select Automation)";
3348
+ }
3150
3349
  function configAttrs(kind, config, refs) {
3151
3350
  const attrs = {};
3152
3351
  for (const [key, raw] of Object.entries(config)) {
@@ -3490,13 +3689,13 @@ function configAttrs(kind, config, refs) {
3490
3689
  if (typeof input.type !== "string" || !ON_DEMAND_TF_PARAM_TYPES.has(input.type)) {
3491
3690
  throw new EntityTfError(`onDemand parameter ${JSON.stringify(input.name)} has type ${JSON.stringify(input.type)}, which ` +
3492
3691
  `elementum_on_demand_trigger does not support (allowed: text, number, decimal, boolean, date, ` +
3493
- `datetime, userId, attachmentId, record). Use "text" for a JSON string.`);
3692
+ `datetime, userId, groupId, attachmentId, record). Use "text" for a JSON string.`);
3494
3693
  }
3495
3694
  const mapped = Object.fromEntries(Object.entries(input)
3496
3695
  .filter(([k]) => k !== "app")
3497
3696
  .map(([k, v]) => [
3498
3697
  CONFIG_ATTRS[k] ?? snake(k),
3499
- valueToTf(k === "defaultValue" ? unwrapDefault(v) :
3698
+ valueToTf(k === "defaultValue" ? onDemandDefaultToTf(unwrapDefault(v)) :
3500
3699
  k === "type" && typeof v === "string" ? ON_DEMAND_TF_PARAM_TYPES.get(v) : v, refs),
3501
3700
  ]));
3502
3701
  if (isOnDemandRecordType(typeof input.type === "string" ? input.type : undefined)) {
@@ -4030,7 +4229,13 @@ export function automationToTf(entity, ctx) {
4030
4229
  kind: "resource",
4031
4230
  type: triggerType,
4032
4231
  label,
4033
- attrs: { automation: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label), ...triggerAttrs },
4232
+ attrs: {
4233
+ automation: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label),
4234
+ ...triggerAttrs,
4235
+ ...(OBJECT_FIELD_REFS_TRIGGER_TYPES.has(triggerType)
4236
+ ? objectFieldIdsAttr(expr.resourceAttr(owner.parentScope === "element" ? "elementum_element" : "elementum_app", owner.appTfLabel, ["id"]), owner.fieldAddresses)
4237
+ : {}),
4238
+ },
4034
4239
  };
4035
4240
  const blocks = [automation, trigger];
4036
4241
  const dependencies = [expr.resourceAttr(triggerType, label)];
@@ -4042,7 +4247,9 @@ export function automationToTf(entity, ctx) {
4042
4247
  // real sibling tasks precede the placeholder within the same case/branch
4043
4248
  // (the rolling `taskParent` chain below tracks the PRECEDING SIBLING, not
4044
4249
  // the enclosing operator, once more than one task shares a scope).
4045
- const emitTasks = (tasks, initialParent, enclosingOperator) => {
4250
+ // `enclosingForEach` is the refKey of the nearest forEach around this scope
4251
+ // at any depth (a switch or fork inside a loop body keeps it), for #1870.
4252
+ const emitTasks = (tasks, initialParent, enclosingOperator, enclosingForEach) => {
4046
4253
  let parent = initialParent;
4047
4254
  let first;
4048
4255
  for (const task of tasks) {
@@ -4091,14 +4298,16 @@ export function automationToTf(entity, ctx) {
4091
4298
  }
4092
4299
  const operatorTaskAddress = enclosingOperator?.taskAddress;
4093
4300
  const operatorChildAddress = enclosingOperator?.childAddress;
4094
- const isParentTrigger = enclosingOperator === undefined;
4301
+ // parent_is_trigger is always false on a task reference. The step this
4302
+ // placeholder comes after is a local, not this flag: the provider
4303
+ // copies the flag onto the following task (edk#2320).
4095
4304
  const extraAttrs = {
4096
4305
  id: idValue,
4097
4306
  task_type: inner.taskType,
4098
4307
  workflow_id: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label, ["workflow_id"]),
4099
4308
  app_id: expr.resourceAttr(owner.parentScope === "element" ? "elementum_element" : "elementum_app", owner.appTfLabel, ["id"]),
4100
4309
  automation_id: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label, ["id"]),
4101
- parent_is_trigger: isParentTrigger,
4310
+ parent_is_trigger: false,
4102
4311
  ...(operatorTaskAddress !== undefined && operatorTaskAddress.$expr === "resource-attr"
4103
4312
  ? { operator_task_id: expr.resourceAttr(operatorTaskAddress.type, operatorTaskAddress.label, ["id"]) }
4104
4313
  : {}),
@@ -4118,6 +4327,10 @@ export function automationToTf(entity, ctx) {
4118
4327
  });
4119
4328
  }
4120
4329
  const address = expr.dataAttr("elementum_unmanaged_task_reference", tfLabel);
4330
+ const predecessorLocal = `edk_unmanaged_predecessor_${tfLabel}`;
4331
+ if (ctx.localsAttrs !== undefined && !(predecessorLocal in ctx.localsAttrs)) {
4332
+ ctx.localsAttrs[predecessorLocal] = taskParent;
4333
+ }
4121
4334
  first ??= address;
4122
4335
  parent = address;
4123
4336
  continue;
@@ -4158,7 +4371,19 @@ export function automationToTf(entity, ctx) {
4158
4371
  const message = err instanceof Error ? err.message : String(err);
4159
4372
  throw new EntityTfError(`automation "${entity.refName}"'s task "${refKey}" (${wireType}): ${message}`);
4160
4373
  }
4161
- const attrs = { parent: taskParent, name: displayName, ...taskAttrs };
4374
+ const attrs = {
4375
+ parent: taskParent,
4376
+ name: displayName,
4377
+ ...taskAttrs,
4378
+ ...(OBJECT_FIELD_REFS_TASK_TYPES.has(resourceType)
4379
+ ? objectFieldIdsAttr(taskAttrs["object_id"], taskTargetFieldAddresses(inner.aspectId ?? inner.relatedAspectId, owner))
4380
+ : {}),
4381
+ };
4382
+ if (wireType === "executeScript") {
4383
+ for (const finding of scriptLintFindings(displayName, inner.code, inner.inputs, inner.outputSchema)) {
4384
+ owner.diagnostics.push(`automation ${owner.automationTfLabel}: ${finding}`);
4385
+ }
4386
+ }
4162
4387
  const block = { kind: "resource", type: resourceType, label: tfLabel, attrs };
4163
4388
  if (wireType === "runAutomation") {
4164
4389
  const target = token(inner.targetAutomationId) ?? (isObject(inner.targetAutomationRef) ? token(inner.targetAutomationRef.value) : undefined);
@@ -4175,6 +4400,9 @@ export function automationToTf(entity, ctx) {
4175
4400
  }
4176
4401
  // Bare-UUID / unresolved targets skip depends_on — configAttrs already
4177
4402
  // emitted target_automation_id as a literal and pushed a diagnostic.
4403
+ const warning = dynamicSyncRunInForEachWarning(refKey, inner, enclosingForEach);
4404
+ if (warning !== undefined)
4405
+ owner.diagnostics.push(`automation ${owner.automationTfLabel}: ${warning}`);
4178
4406
  }
4179
4407
  blocks.push(block);
4180
4408
  const address = expr.resourceAttr(resourceType, tfLabel);
@@ -4191,7 +4419,7 @@ export function automationToTf(entity, ctx) {
4191
4419
  const children = task.children ?? [];
4192
4420
  if (children.length !== 1)
4193
4421
  throw new EntityTfError(`forEach task "${refKey}" must have exactly one child body`);
4194
- emitTasks(children[0].tasks ?? [], expr.resourceAttr(resourceType, tfLabel, ["inner"]), { taskAddress: expr.resourceAttr(resourceType, tfLabel) });
4422
+ emitTasks(children[0].tasks ?? [], expr.resourceAttr(resourceType, tfLabel, ["inner"]), { taskAddress: expr.resourceAttr(resourceType, tfLabel) }, refKey);
4195
4423
  // The loop body is a separate operator-owned chain. A fluent sibling
4196
4424
  // authored after `forEach` continues from the for_each task itself,
4197
4425
  // not from the body's terminal task; the latter silently moves that
@@ -4292,7 +4520,7 @@ export function automationToTf(entity, ctx) {
4292
4520
  blocks.push({ kind: "resource", type: branchType, label: branchLabel, attrs: branchAttrs });
4293
4521
  const branchAddress = expr.resourceAttr(branchType, branchLabel);
4294
4522
  dependencies.push(branchAddress);
4295
- emitTasks(child.tasks ?? [], branchAddress, { taskAddress: address, childAddress: branchAddress });
4523
+ emitTasks(child.tasks ?? [], branchAddress, { taskAddress: address, childAddress: branchAddress }, enclosingForEach);
4296
4524
  previous = branchAddress;
4297
4525
  }
4298
4526
  }