@elementumai/edk 0.9.7 → 0.9.10

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 (152) hide show
  1. package/README.md +3 -2
  2. package/dist-sdk/src/catalog/factories.d.ts +14 -3
  3. package/dist-sdk/src/catalog/factories.js +32 -0
  4. package/dist-sdk/src/catalog/from-authoring.js +27 -33
  5. package/dist-sdk/src/catalog/index.d.ts +2 -2
  6. package/dist-sdk/src/catalog/index.js +2 -2
  7. package/dist-sdk/src/catalog/org.js +67 -29
  8. package/dist-sdk/src/catalog/token.js +10 -0
  9. package/dist-sdk/src/catalog/types.d.ts +20 -2
  10. package/dist-sdk/src/catalog/types.js +5 -0
  11. package/dist-sdk/src/core/index.d.ts +1 -1
  12. package/dist-sdk/src/core/index.js +1 -1
  13. package/dist-sdk/src/core/platform-id.d.ts +2 -0
  14. package/dist-sdk/src/core/platform-id.js +4 -0
  15. package/dist-sdk/src/core/system-fields.d.ts +14 -0
  16. package/dist-sdk/src/core/system-fields.js +6 -0
  17. package/dist-sdk/src/core/triggers/on-demand.d.ts +27 -24
  18. package/dist-sdk/src/core/triggers/on-demand.js +33 -12
  19. package/dist-sdk/src/core/types/aspect-category.d.ts +1 -0
  20. package/dist-sdk/src/core/types/aspect-category.js +1 -0
  21. package/dist-sdk/src/engine/build/context.d.ts +22 -8
  22. package/dist-sdk/src/engine/build/source-context.d.ts +14 -17
  23. package/dist-sdk/src/engine/build/source-context.js +1 -1
  24. package/dist-sdk/src/engine/pull/context.d.ts +9 -0
  25. package/dist-sdk/src/engine/pull/org.d.ts +4 -0
  26. package/dist-sdk/src/engine/pull/org.js +17 -2
  27. package/dist-sdk/src/engine/pull/procedure-refs.d.ts +16 -0
  28. package/dist-sdk/src/engine/pull/procedure-refs.js +69 -0
  29. package/dist-sdk/src/engine/tf/expr.js +1 -1
  30. package/dist-sdk/src/engine/workspace/authoring-layout.d.ts +15 -0
  31. package/dist-sdk/src/engine/workspace/authoring-layout.js +33 -1
  32. package/dist-sdk/src/engine/workspace/loader.d.ts +40 -0
  33. package/dist-sdk/src/engine/workspace/loader.js +328 -0
  34. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +4 -0
  35. package/dist-sdk/src/entities/access-policy/from-tf.js +10 -2
  36. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +1 -0
  37. package/dist-sdk/src/entities/access-policy/to-tf.js +7 -2
  38. package/dist-sdk/src/entities/agent/build.d.ts +54 -8
  39. package/dist-sdk/src/entities/agent/build.js +36 -1
  40. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +126 -2
  41. package/dist-sdk/src/entities/agent/from-tf.d.ts +7 -6
  42. package/dist-sdk/src/entities/agent/from-tf.js +176 -5
  43. package/dist-sdk/src/entities/agent/index.d.ts +2 -2
  44. package/dist-sdk/src/entities/agent/index.js +1 -1
  45. package/dist-sdk/src/entities/agent/to-tf.d.ts +4 -4
  46. package/dist-sdk/src/entities/agent/to-tf.js +185 -11
  47. package/dist-sdk/src/entities/agent/tools.d.ts +16 -5
  48. package/dist-sdk/src/entities/agent/tools.js +13 -1
  49. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +7 -0
  50. package/dist-sdk/src/entities/agent-tool/from-tf.js +29 -4
  51. package/dist-sdk/src/entities/agent-tool/to-tf.js +10 -9
  52. package/dist-sdk/src/entities/agent-tool/types.js +1 -0
  53. package/dist-sdk/src/entities/app/build.d.ts +2 -2
  54. package/dist-sdk/src/entities/app/build.js +6 -3
  55. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +5 -0
  56. package/dist-sdk/src/entities/app/display-blocks-to-layout.d.ts +45 -0
  57. package/dist-sdk/src/entities/app/display-blocks-to-layout.js +98 -0
  58. package/dist-sdk/src/entities/app/display-blocks-to-record-create-form.d.ts +55 -0
  59. package/dist-sdk/src/entities/app/display-blocks-to-record-create-form.js +99 -0
  60. package/dist-sdk/src/entities/app/from-tf.js +9 -7
  61. package/dist-sdk/src/entities/app/to-tf.d.ts +1 -1
  62. package/dist-sdk/src/entities/app/to-tf.js +17 -7
  63. package/dist-sdk/src/entities/automation/build.d.ts +8 -1
  64. package/dist-sdk/src/entities/automation/build.js +36 -5
  65. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +3 -7
  66. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +2 -0
  67. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +140 -12
  68. package/dist-sdk/src/entities/automation/from-tf.d.ts +10 -1
  69. package/dist-sdk/src/entities/automation/from-tf.js +803 -62
  70. package/dist-sdk/src/entities/automation/index.d.ts +1 -1
  71. package/dist-sdk/src/entities/automation/module.js +13 -3
  72. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +12 -4
  73. package/dist-sdk/src/entities/automation/output-key-wire-name.js +17 -6
  74. package/dist-sdk/src/entities/automation/script-code.d.ts +8 -1
  75. package/dist-sdk/src/entities/automation/script-code.js +32 -14
  76. package/dist-sdk/src/entities/automation/task-label.d.ts +2 -0
  77. package/dist-sdk/src/entities/automation/task-label.js +18 -0
  78. package/dist-sdk/src/entities/automation/tasks.d.ts +60 -9
  79. package/dist-sdk/src/entities/automation/tasks.js +16 -4
  80. package/dist-sdk/src/entities/automation/to-tf.d.ts +4 -0
  81. package/dist-sdk/src/entities/automation/to-tf.js +394 -52
  82. package/dist-sdk/src/entities/automation/triggers.d.ts +14 -5
  83. package/dist-sdk/src/entities/automation/triggers.js +1 -1
  84. package/dist-sdk/src/entities/dashboard/from-tf.js +1 -1
  85. package/dist-sdk/src/entities/dashboard/to-tf.d.ts +2 -0
  86. package/dist-sdk/src/entities/dashboard/to-tf.js +4 -0
  87. package/dist-sdk/src/entities/datamine/from-tf.js +23 -3
  88. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +1 -0
  89. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +1 -1
  90. package/dist-sdk/src/entities/element/build.d.ts +30 -7
  91. package/dist-sdk/src/entities/element/build.js +6 -3
  92. package/dist-sdk/src/entities/element/from-tf.js +7 -3
  93. package/dist-sdk/src/entities/element/index.d.ts +1 -1
  94. package/dist-sdk/src/entities/element/index.js +1 -1
  95. package/dist-sdk/src/entities/element/to-tf.js +49 -8
  96. package/dist-sdk/src/entities/field/from-tf.d.ts +6 -0
  97. package/dist-sdk/src/entities/field/from-tf.js +12 -0
  98. package/dist-sdk/src/entities/field/module.js +1 -0
  99. package/dist-sdk/src/entities/field/to-tf.d.ts +1 -1
  100. package/dist-sdk/src/entities/field/to-tf.js +19 -5
  101. package/dist-sdk/src/entities/org/category-ref.d.ts +5 -0
  102. package/dist-sdk/src/entities/org/category-ref.js +12 -0
  103. package/dist-sdk/src/entities/record-create-form/from-tf.js +3 -3
  104. package/dist-sdk/src/entities/record-create-form/to-tf.d.ts +1 -0
  105. package/dist-sdk/src/entities/record-create-form/to-tf.js +13 -5
  106. package/dist-sdk/src/entities/relationship/from-tf.js +15 -4
  107. package/dist-sdk/src/entities/role/from-tf.js +10 -4
  108. package/dist-sdk/src/entities/search-table/build.d.ts +1 -1
  109. package/dist-sdk/src/entities/search-table/from-tf.d.ts +1 -0
  110. package/dist-sdk/src/entities/search-table/from-tf.js +6 -0
  111. package/dist-sdk/src/entities/search-table/printer.js +3 -1
  112. package/dist-sdk/src/entities/search-table/to-tf.js +3 -3
  113. package/dist-sdk/src/entities/search-table/types.js +1 -0
  114. package/dist-sdk/src/entities/service-account/from-tf.js +10 -4
  115. package/dist-sdk/src/entities/service-account/to-tf.d.ts +2 -1
  116. package/dist-sdk/src/entities/service-account/to-tf.js +7 -0
  117. package/dist-sdk/src/entities/shared/filters/ast.d.ts +7 -1
  118. package/dist-sdk/src/entities/shared/filters/ast.js +3 -0
  119. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +7 -1
  120. package/dist-sdk/src/entities/shared/filters/tf-codec.js +8 -4
  121. package/dist-sdk/src/entities/shared/handle-description.d.ts +12 -0
  122. package/dist-sdk/src/entities/shared/handle-description.js +20 -0
  123. package/dist-sdk/src/entities/shared/types/field-types.d.ts +6 -1
  124. package/dist-sdk/src/entities/shared/types/field-types.js +5 -8
  125. package/dist-sdk/src/entities/skill/build.d.ts +51 -2
  126. package/dist-sdk/src/entities/skill/build.js +65 -8
  127. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +35 -3
  128. package/dist-sdk/src/entities/skill/from-tf.d.ts +11 -0
  129. package/dist-sdk/src/entities/skill/from-tf.js +39 -7
  130. package/dist-sdk/src/entities/skill/index.d.ts +1 -1
  131. package/dist-sdk/src/entities/skill/index.js +1 -1
  132. package/dist-sdk/src/entities/skill/input-coverage.d.ts +21 -0
  133. package/dist-sdk/src/entities/skill/input-coverage.js +148 -5
  134. package/dist-sdk/src/entities/skill/to-tf.d.ts +6 -25
  135. package/dist-sdk/src/entities/skill/to-tf.js +22 -38
  136. package/dist-sdk/src/entities/skill/tools.d.ts +2 -1
  137. package/dist-sdk/src/entities/skill/tools.js +3 -1
  138. package/dist-sdk/src/entities/skill-tool/from-tf.js +10 -3
  139. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +5 -5
  140. package/dist-sdk/src/entities/skill-tool/to-tf.js +5 -7
  141. package/dist-sdk/src/entities/table/to-tf.js +3 -4
  142. package/dist-sdk/src/entities/task/to-tf.js +3 -2
  143. package/dist-sdk/src/entities/view/from-tf.js +36 -10
  144. package/dist-sdk/src/entities/view/to-tf.d.ts +2 -0
  145. package/dist-sdk/src/entities/view/to-tf.js +44 -30
  146. package/dist-sdk/src/entities/widget/from-tf.js +2 -2
  147. package/dist-sdk/src/entities/widget/to-tf.d.ts +1 -0
  148. package/dist-sdk/src/entities/widget/to-tf.js +52 -23
  149. package/dist-sdk/src/graph/index.d.ts +19 -1
  150. package/dist-sdk/src/graph/index.js +20 -0
  151. package/dist-sdk/src/graph/types.d.ts +19 -0
  152. package/package.json +10 -5
@@ -1,13 +1,19 @@
1
1
  import { USER_FIELD_KEYS } from "../../catalog/types.js";
2
2
  import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEYS } from "../../core/system-fields.js";
3
3
  import { EntityTfError } from "../../engine/entity.js";
4
- import { childPartFromScopedLabel, isTfExpr, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, } from "../../engine/tf/index.js";
4
+ import { procedureDiscriminator } from "../../engine/pull/procedure-refs.js";
5
+ import { childPartFromScopedLabel, isTfExpr, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
6
+ import { SUB_TYPE_BY_RESOURCE } from "../field/types.js";
5
7
  import { IMPLEMENTED_FILE_READER_RESOURCE_TYPES } from "../file-reader/types.js";
6
8
  import { connectorIdentityFromTf } from "../shared/connector-from-tf.js";
9
+ import { fieldTypeToValueType } from "../shared/filters/index.js";
7
10
  import { UNRESOLVED_FIELD_MARKER } from "../shared/ref.js";
8
11
  import { filterFromTf as deserializeFilterFromTf } from "../shared/filters/tf-codec.js";
9
12
  import { TABLE_RESOURCE_TYPE } from "../table/module.js";
10
- import { OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
13
+ import { SEARCH_TABLE_RESOURCE_TYPES } from "../search-table/types.js";
14
+ import { outputFieldTypesFromScriptSchema } from "./output-field-types.js";
15
+ import { apiTaskRefAuthoringPath, OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
16
+ import { taskTfLabel } from "./task-label.js";
11
17
  import { ALL_AUTOMATION_TASK_TYPE_SET, AUTOMATION_BRANCH_TYPE_SET, AUTOMATION_RESOURCE_TYPE, AUTOMATION_TRIGGER_TYPE_SET, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
12
18
  const TRIGGER_KINDS = {
13
19
  elementum_record_created_trigger: "recordCreate",
@@ -57,6 +63,11 @@ const TASK_FACTORIES = {
57
63
  elementum_run_automation_task: "runAutomation",
58
64
  elementum_aspect_record_field_locking_task: "recordFieldLocking",
59
65
  elementum_ai_file_read_task: "aiFileAnalysis",
66
+ // Not a real task resource - a read-only reference to a platform task type
67
+ // EDK doesn't implement (edk#785/edk#821). Synthesized into the same tree
68
+ // walk as a real task (see buildTasks) so its downstream chain lands in its
69
+ // real position instead of being silently hoisted to the automation's top level.
70
+ elementum_unmanaged_task_reference: "unimplementedTask",
60
71
  };
61
72
  const ATTR_TO_ARG = {
62
73
  object_id: "app",
@@ -140,6 +151,20 @@ function references(value, type, label) {
140
151
  const ref = resourceRef(value);
141
152
  return ref?.type === type && ref.label === label;
142
153
  }
154
+ /**
155
+ * edk#785: a task's `parent` can be a `data.elementum_unmanaged_task_reference.*`
156
+ * reference instead of a resource reference, when its real predecessor is a
157
+ * task type EDK doesn't support at all (no HCL block ever emitted for it).
158
+ * The data source is read-only and inherently "resolved" (its id/workflow_id/
159
+ * etc. are always concrete inputs, never dependent on anything else in the
160
+ * graph), so a task pointing at one is never itself unowned/orphaned - it
161
+ * just has no real branch/case address to anchor its authored position under.
162
+ */
163
+ function unmanagedTaskRef(value) {
164
+ return isTfExpr(value) && value.$expr === "data-attr" && value.type === "elementum_unmanaged_task_reference"
165
+ ? { label: value.label }
166
+ : undefined;
167
+ }
143
168
  /**
144
169
  * Order switch_case / fork_join_branch blocks by their previous_*_id chain.
145
170
  * Falls back to depends_on index / label only when the chain is incomplete.
@@ -210,9 +235,10 @@ const TRIGGER_ATTRIBUTES = new Set([
210
235
  ]);
211
236
  const TASK_ATTRIBUTES = new Set([
212
237
  "parent", "name", "depends_on", "filter", "fields", "inputs", "output_schema",
213
- "list", "code", "variable_name", "variable_type", "variable", "value",
238
+ "list", "code", "variable_name", "variable_type", "variable_id", "variable", "value",
214
239
  "object_id", "table_id", "record_reference", "record_id", "source_record_ids",
215
240
  "approval_process_id", "requester_reference", "approver_references", "reason", "summary",
241
+ "approval_reference", "status",
216
242
  "target_record_id", "message", "message_body", "body", "from_username",
217
243
  "from_personal", "external_emails", "users", "groups", "attachments", "contents",
218
244
  "agent_id", "prompt", "output_type", "json_fields", "ai_provider_connector_id",
@@ -295,15 +321,17 @@ function pathNames(path) {
295
321
  * create-record task outputs; both use the same display-name + suffix wire
296
322
  * convention.
297
323
  */
298
- function recordFieldRefPath(wireName, ctx) {
324
+ function recordFieldRefPath(wireName, ctx, ownerRefName = ctx.appRefName, rootName = "record") {
299
325
  // Case-insensitive so exports remain readable across historical platform
300
326
  // casing while authored HCL targets the current exact live ref keys.
301
327
  const wireNameLower = wireName.toLowerCase();
302
- for (const field of ctx.fieldById.values()) {
303
- for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
304
- if (wireNameLower === `${field.name}${suffix}`.toLowerCase()) {
305
- return ["record", field.key, ...suffixPath];
306
- }
328
+ for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
329
+ if (!wireNameLower.endsWith(suffix.toLowerCase()))
330
+ continue;
331
+ const base = wireName.slice(0, wireName.length - suffix.length);
332
+ const fieldKey = lookupFieldKeyByDisplayName(ownerRefName, base, ctx);
333
+ if (fieldKey !== undefined) {
334
+ return [rootName, fieldKey, ...suffixPath];
307
335
  }
308
336
  }
309
337
  // System fields have no `*_field` resource block, so they never appear in
@@ -312,7 +340,7 @@ function recordFieldRefPath(wireName, ctx) {
312
340
  const defaultName = DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[key];
313
341
  for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
314
342
  if (wireNameLower === `${defaultName}${suffix}`.toLowerCase()) {
315
- return ["record", key, ...suffixPath];
343
+ return [rootName, key, ...suffixPath];
316
344
  }
317
345
  }
318
346
  }
@@ -335,6 +363,31 @@ function isDeclaredOnDemandParameter(trigger, wireName) {
335
363
  const parameters = trigger.attrs.parameters;
336
364
  return Array.isArray(parameters) && parameters.some((parameter) => isObject(parameter) && parameter.name === wireName);
337
365
  }
366
+ function onDemandRecordParameters(trigger) {
367
+ if (trigger.type !== "elementum_on_demand_trigger" || !Array.isArray(trigger.attrs.parameters))
368
+ return [];
369
+ return trigger.attrs.parameters.filter((parameter) => isObject(parameter) && parameter.type === "record" && typeof parameter.name === "string");
370
+ }
371
+ function prefixedOnDemandRecordRefPath(wireName, ctx) {
372
+ const recordParams = onDemandRecordParameters(ctx.trigger);
373
+ if (recordParams.length < 2)
374
+ return undefined;
375
+ const sortedParams = [...recordParams].sort((a, b) => String(b.name).length - String(a.name).length);
376
+ for (const parameter of sortedParams) {
377
+ const name = parameter.name;
378
+ const prefix = `${name} - `;
379
+ if (!wireName.startsWith(prefix))
380
+ continue;
381
+ const displayName = wireName.slice(prefix.length);
382
+ if (displayName === "Record")
383
+ return [name];
384
+ const ownerRefName = aspectOwnerRefNameFromObjectId(parameter.default_value, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames);
385
+ return ownerRefName === undefined
386
+ ? undefined
387
+ : recordFieldRefPath(displayName, ctx, ownerRefName, name);
388
+ }
389
+ return undefined;
390
+ }
338
391
  // recordSearch's own output ref names ("Records Size" -> totalCount, "All
339
392
  // found records" -> records) — deliberately NOT in WIRE_REF_SEGMENT_TO_TS,
340
393
  // which triggerRefPath also consults: a record-created/updated trigger's ref
@@ -347,6 +400,7 @@ function isDeclaredOnDemandParameter(trigger, wireName) {
347
400
  const RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS = {
348
401
  "Records Size": "totalCount",
349
402
  "All found records": "records",
403
+ Record: "record",
350
404
  };
351
405
  // aiSearchTable's own output ref name — same scoping reason as
352
406
  // RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS: "All Records" is a platform-fixed
@@ -363,6 +417,26 @@ const AI_SEARCH_TABLE_TASK_REF_SEGMENT_TO_TS = {
363
417
  const TABLE_RECORDS_SEARCH_TASK_REF_SEGMENT_TO_TS = {
364
418
  "All matching table rows": "records",
365
419
  };
420
+ /**
421
+ * Restore the public aiAgent `.result` shape from either a provider refs-map
422
+ * key (`Action Response` / authored schema field) or the nested platform
423
+ * taskReference.name carried by workflow publish envelopes.
424
+ */
425
+ function aiAgentTaskRefPath(block, name) {
426
+ if (block.type !== "elementum_ai_agent_task")
427
+ return undefined;
428
+ if (name === "Action Response" || name === "ai_agent_task_response")
429
+ return ["result"];
430
+ const nestedPrefix = "ai_agent_task_structured_output.";
431
+ const candidate = name.startsWith(nestedPrefix) ? name.slice(nestedPrefix.length) : name;
432
+ const jsonFields = block.attrs.json_fields;
433
+ if (!Array.isArray(jsonFields))
434
+ return undefined;
435
+ const schemaName = jsonFields
436
+ .flatMap((field) => isObject(field) && typeof field.name === "string" ? [field.name] : [])
437
+ .find((fieldName) => (fieldName === candidate || fieldName.toLowerCase() === candidate.toLowerCase()));
438
+ return schemaName === undefined ? undefined : ["result", schemaName];
439
+ }
366
440
  /**
367
441
  * A webhook trigger's `body`/`headers` refs come back as "Body (Plain
368
442
  * Text)"/"Headers (Content-Type)" - one wire segment naming both the
@@ -377,20 +451,64 @@ const TABLE_RECORDS_SEARCH_TASK_REF_SEGMENT_TO_TS = {
377
451
  * convention.
378
452
  */
379
453
  const WEBHOOK_REF_PATTERN = /^(Body|Headers) \((.+)\)$/;
380
- function aspectOwnerRefNameFromObjectId(objectId, appRefName, appTfLabel) {
454
+ function aspectOwnerRefNameFromObjectId(objectId, appRefName, appTfLabel, dataBlocks, foreignAppRefNames, foreignElementRefNames) {
381
455
  if (!isTfExpr(objectId))
382
456
  return undefined;
383
457
  if (objectId.$expr === "data-attr" && (objectId.type === "elementum_app" || objectId.type === "elementum_element") && objectId.path[0] === "id") {
384
- return tfLabelToTsLabel(objectId.label);
385
- }
386
- if (objectId.$expr === "resource-attr" && objectId.type === "elementum_app" && objectId.label === appTfLabel && objectId.path[0] === "id") {
387
- return appRefName;
458
+ // The data block's own tf label is an arbitrary export alias, not
459
+ // necessarily the target's real refName (confirmed live: a
460
+ // `data.elementum_element "approvals_log"` block's real namespace is
461
+ // "approvals") - resolve through its name/namespace, same as decodeValue's
462
+ // generic app/element data-attr case, falling back to the label only when
463
+ // the target hasn't itself been pulled yet.
464
+ const lookup = dataBlocks.get(`${objectId.type}.${objectId.label}`);
465
+ const identity = lookup?.attrs.name ?? lookup?.attrs.namespace;
466
+ const mapped = typeof identity === "string"
467
+ ? (objectId.type === "elementum_element" ? foreignElementRefNames : foreignAppRefNames)?.get(identity)
468
+ : undefined;
469
+ return mapped ?? tfLabelToTsLabel(objectId.label);
388
470
  }
389
- if (objectId.$expr === "resource-attr" && objectId.type === "elementum_element" && objectId.path[0] === "id") {
390
- return tfLabelToTsLabel(objectId.label);
471
+ if (objectId.$expr === "resource-attr" &&
472
+ (objectId.type === "elementum_app" || objectId.type === "elementum_element") &&
473
+ objectId.path[0] === "id") {
474
+ return objectId.type === "elementum_app" && objectId.label === appTfLabel
475
+ ? appRefName
476
+ : tfLabelToTsLabel(objectId.label);
391
477
  }
392
478
  return undefined;
393
479
  }
480
+ function aspectRefFromObjectId(objectId, ctx) {
481
+ if (!isTfExpr(objectId))
482
+ return undefined;
483
+ if (objectId.$expr === "resource-attr" &&
484
+ (objectId.type === "elementum_app" || objectId.type === "elementum_element") &&
485
+ objectId.path[0] === "id") {
486
+ return {
487
+ kind: "app",
488
+ appHandle: objectId.label === ctx.appTfLabel ? ctx.appRefName : tfLabelToTsLabel(objectId.label),
489
+ };
490
+ }
491
+ if (objectId.$expr !== "data-attr" ||
492
+ (objectId.type !== "elementum_app" && objectId.type !== "elementum_element") ||
493
+ objectId.path[0] !== "id") {
494
+ return undefined;
495
+ }
496
+ const lookup = ctx.dataBlocks.get(`${objectId.type}.${objectId.label}`);
497
+ const identity = lookup?.attrs.name ?? lookup?.attrs.namespace;
498
+ const mapped = typeof identity === "string"
499
+ ? (objectId.type === "elementum_element" ? ctx.foreignElementRefNames : ctx.foreignAppRefNames)?.get(identity)
500
+ : undefined;
501
+ if (mapped !== undefined)
502
+ return { kind: "app", appHandle: mapped };
503
+ if (typeof identity !== "string" || identity === "")
504
+ return undefined;
505
+ return {
506
+ kind: "app",
507
+ appHandle: tfLabelToTsLabel(objectId.label),
508
+ entityType: objectId.type === "elementum_element" ? "element" : "app",
509
+ name: identity,
510
+ };
511
+ }
394
512
  function lookupFieldKeyByDisplayName(ownerRefName, displayName, ctx) {
395
513
  const lower = displayName.toLowerCase();
396
514
  const foreign = ctx.fieldNamesByOwnerRefName?.get(ownerRefName)?.get(lower);
@@ -423,6 +541,105 @@ function taskRecordSearchFieldPath(taskAddress, wireName, ctx) {
423
541
  }
424
542
  return undefined;
425
543
  }
544
+ /**
545
+ * Sentinel returned by {@link approverReferenceFieldAuthoringType} for a
546
+ * field-shaped reference (matches one of the FIELD_REF_SUFFIX_FROM_WIRE
547
+ * display-name suffixes) into a FOREIGN aspect whose fields have never been
548
+ * captured locally AT ALL — not merely "this one field is unknown", but
549
+ * "this aspect has never been pulled, so nothing about its fields can be
550
+ * verified". Distinct from a real authoring-type string so callers can give
551
+ * a different diagnostic (pull the foreign aspect first) than the
552
+ * positively-wrong-type case (edk#655) below. See edk#768.
553
+ */
554
+ const UNVERIFIABLE_FOREIGN_FIELD_TYPE = "__edkUnverifiableForeignFieldType";
555
+ /**
556
+ * If `value` is a `refs["<Field> ID"]`-style reference into a field's
557
+ * output, return that field's public authoring type (e.g. "USER", "GROUP")
558
+ * so callers requiring a USER field (approvalChain's requester/approver
559
+ * references) can catch a live automation already wired to the wrong field
560
+ * type before it reaches the provider's own plan-time rejection (edk#655).
561
+ * Covers both a LOCAL field (this app's own `fieldById`) and a FOREIGN one
562
+ * (a non-recursive export never carries the foreign aspect's field
563
+ * resources, so this falls back to the cross-pull field-refs registry,
564
+ * populated once that aspect has itself been pulled at least once — see
565
+ * field-refs-registry.ts's `fieldType`).
566
+ *
567
+ * When the reference targets a FOREIGN aspect that has never been pulled at
568
+ * all, its field types are entirely unknown to the registry — genuinely
569
+ * unverifiable, not "not a field". Returns
570
+ * {@link UNVERIFIABLE_FOREIGN_FIELD_TYPE} in that case rather than silently
571
+ * treating it as safe: confirmed live (eu/sanofi purchaserequisition, edk#768)
572
+ * that letting an unverifiable foreign reference through crashes the WHOLE
573
+ * app's adoption at `ei plan` the same way a known-bad type does. A LOCAL
574
+ * non-match is never ambiguous this way — the app being pulled always
575
+ * carries its own fields exhaustively in this same export — so this fallback
576
+ * only applies to foreign owners.
577
+ */
578
+ function approverReferenceFieldAuthoringType(value, ctx) {
579
+ if (!isTfExpr(value) || value.$expr !== "resource-attr" || value.path[0] !== "refs")
580
+ return undefined;
581
+ const taskAddress = `${value.type}.${value.label}`;
582
+ const ownerRefName = ctx.taskTargetOwnerRefNameByAddress?.get(taskAddress);
583
+ if (ownerRefName === undefined)
584
+ return undefined;
585
+ const rawSegments = pathNames(value.path.slice(1));
586
+ if (rawSegments.length !== 1)
587
+ return undefined;
588
+ const wireName = rawSegments[0];
589
+ const wireNameLower = wireName.toLowerCase();
590
+ const typeForFieldKey = (fieldKey) => {
591
+ if (ownerRefName === ctx.appRefName) {
592
+ for (const field of ctx.fieldById.values()) {
593
+ if (field.key === fieldKey)
594
+ return SUB_TYPE_BY_RESOURCE.get(field.resourceType)?.authoringType;
595
+ }
596
+ }
597
+ for (const foreign of ctx.foreignFieldRefsById?.values() ?? []) {
598
+ if (foreign.ownerRefName === ownerRefName && foreign.fieldKey === fieldKey && foreign.fieldType !== undefined) {
599
+ return foreign.fieldType;
600
+ }
601
+ }
602
+ return undefined;
603
+ };
604
+ // An EXACT field display name always wins over a suffix-stripped guess: a
605
+ // field literally named "Approver ID" must never be shadowed by treating
606
+ // the wire name as the " ID" projection of a DIFFERENT field named
607
+ // "Approver" (edk#768 PR review — this exact collision let a TEXT-typed
608
+ // field through undetected because the wrong guess resolved to the base
609
+ // field's USER type). Once the wire name matches a real field's own name,
610
+ // that field's identity is settled: fall through only to the
611
+ // "unverifiable" check below if ITS type can't be resolved — never guess
612
+ // via a different field's suffix projection instead.
613
+ const exactFieldKey = lookupFieldKeyByDisplayName(ownerRefName, wireName, ctx);
614
+ if (exactFieldKey !== undefined) {
615
+ const type = typeForFieldKey(exactFieldKey);
616
+ if (type !== undefined)
617
+ return type;
618
+ return ownerRefName !== ctx.appRefName &&
619
+ ![...ctx.foreignFieldRefsById?.values() ?? []].some((foreign) => foreign.ownerRefName === ownerRefName)
620
+ ? UNVERIFIABLE_FOREIGN_FIELD_TYPE
621
+ : undefined;
622
+ }
623
+ let fieldShaped = false;
624
+ for (const [suffix] of FIELD_REF_SUFFIX_FROM_WIRE) {
625
+ if (suffix === "" || !wireNameLower.endsWith(suffix.toLowerCase()))
626
+ continue;
627
+ fieldShaped = true;
628
+ const base = wireName.slice(0, -suffix.length);
629
+ const fieldKey = lookupFieldKeyByDisplayName(ownerRefName, base, ctx);
630
+ if (fieldKey === undefined)
631
+ continue;
632
+ const type = typeForFieldKey(fieldKey);
633
+ if (type !== undefined)
634
+ return type;
635
+ }
636
+ if (fieldShaped &&
637
+ ownerRefName !== ctx.appRefName &&
638
+ ![...ctx.foreignFieldRefsById?.values() ?? []].some((foreign) => foreign.ownerRefName === ownerRefName)) {
639
+ return UNVERIFIABLE_FOREIGN_FIELD_TYPE;
640
+ }
641
+ return undefined;
642
+ }
426
643
  function decodeFieldAssignmentValue(value, ctx) {
427
644
  // Multi-Select assignments are exported as jsonencode([<option UUID>, ...])
428
645
  // rather than the options-by-label locals used for a scalar Dropdown. Walk
@@ -472,6 +689,9 @@ function triggerRefPath(path, ctx) {
472
689
  return ["triggeredBy", "name"];
473
690
  if (wireName === "Triggered By's Email")
474
691
  return ["triggeredBy", "email"];
692
+ const recordPath = prefixedOnDemandRecordRefPath(wireName, ctx);
693
+ if (recordPath !== undefined)
694
+ return recordPath;
475
695
  }
476
696
  // An on-demand parameter is an explicitly declared top-level ctx.trigger
477
697
  // property. Check this before record-field inference: a perfectly ordinary
@@ -488,8 +708,20 @@ function triggerRefPath(path, ctx) {
488
708
  // it globally intercepted that task-level case before it could ever be
489
709
  // checked (decodeValue's own dedicated "Record" handling for those task
490
710
  // types).
491
- if (wireName === "Record")
492
- return ["record"];
711
+ if (wireName === "Record") {
712
+ const recordParams = onDemandRecordParameters(ctx.trigger);
713
+ return recordParams.length === 1
714
+ ? [recordParams[0].name]
715
+ : ["record"];
716
+ }
717
+ const singleRecordParam = onDemandRecordParameters(ctx.trigger);
718
+ if (singleRecordParam.length === 1) {
719
+ const parameter = singleRecordParam[0];
720
+ const ownerRefName = aspectOwnerRefNameFromObjectId(parameter.default_value, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames);
721
+ if (ownerRefName !== undefined) {
722
+ return recordFieldRefPath(wireName, ctx, ownerRefName, parameter.name) ?? names;
723
+ }
724
+ }
493
725
  if (!RECORD_BEARING_TRIGGER_TYPES.has(ctx.trigger.type ?? ""))
494
726
  return names;
495
727
  return recordFieldRefPath(wireName, ctx) ?? names;
@@ -559,6 +791,11 @@ function resolveFieldKeyFromId(fieldId, ownerRefName, ctx) {
559
791
  }
560
792
  function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
561
793
  const { refKey, block } = resolveTaskRefKey(taskIdOrKey, ctx);
794
+ if (block !== undefined) {
795
+ const aiAgentPath = aiAgentTaskRefPath(block, pathSegments.join("."));
796
+ if (aiAgentPath !== undefined)
797
+ return { kind: "taskRef", task: refKey, path: aiAgentPath };
798
+ }
562
799
  if (block?.type === "elementum_record_search_task" && pathSegments.length >= 1) {
563
800
  const [head, ...tail] = pathSegments;
564
801
  if (head === "count") {
@@ -636,6 +873,12 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
636
873
  }
637
874
  }
638
875
  }
876
+ if (block?.type === "elementum_api_task" && pathSegments.length === 1) {
877
+ const apiPath = apiTaskRefAuthoringPath(pathSegments[0]);
878
+ if (apiPath !== undefined) {
879
+ return { kind: "taskRef", task: refKey, path: apiPath };
880
+ }
881
+ }
639
882
  const keyPath = pathSegments.map((segment) => WIRE_REF_SEGMENT_TO_TS[segment] ?? segment);
640
883
  const taskKind = block?.type !== undefined ? TASK_FACTORIES[block.type] : undefined;
641
884
  const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
@@ -682,18 +925,18 @@ function decodeReferenceString(value, ctx) {
682
925
  path: forEachItemRefPath(pieces.slice(2), ctx),
683
926
  };
684
927
  }
685
- // Any other/future value_reference shape - confirmed live: conciergeforfield's
686
- // cff_find_nearby_accounts_if_user_is_impersonating_a_sales_rep switch_case
687
- // references a workflow variable ("variable.<uuid>"); setVariable/variable_task
688
- // authoring is itself deferred (no typed construct exists yet to resolve this
689
- // to - see the automation module's header), so it can never become a real ref
690
- // today, and any future dialect growth hits the same "we don't recognize this
691
- // reference shape" situation. Degrade to the {kind:"unresolved"} placeholder
692
- // (same escape hatch fieldRef already uses for an orphaned field_id) rather
693
- // than throwing and losing the whole automation (#171) - printFilterField
694
- // marks it distinctly from a field placeholder (hint !== "field") so the BUILD
695
- // direction fails loudly instead of silently mis-rebuilding it as a field_id
696
- // (#290; a value_reference position can never round-trip through field_id).
928
+ if (pieces[0] === "variable" && pieces.length > 1) {
929
+ const varPart = pieces.slice(1).join(".");
930
+ const resolved = resolveVariableReference(varPart, varPart, undefined, ctx);
931
+ if (resolved !== undefined)
932
+ return resolved;
933
+ }
934
+ if (value.startsWith("variable|")) {
935
+ const varPart = value.slice("variable|".length);
936
+ const resolved = resolveVariableReference(varPart, varPart, undefined, ctx);
937
+ if (resolved !== undefined)
938
+ return resolved;
939
+ }
697
940
  return { kind: "unresolved", uuid: value, hint: pieces[0] ?? "reference" };
698
941
  }
699
942
  /**
@@ -808,6 +1051,84 @@ function tableColumnRefFromPath(label, path, tableName) {
808
1051
  ...(tableName !== undefined ? { tableName } : {}),
809
1052
  };
810
1053
  }
1054
+ function resolveSearchTableFromBlock(block, searchTableLabel, ctx) {
1055
+ if (block.type === SEARCH_TABLE_RESOURCE_TYPES.table) {
1056
+ const tableId = block.attrs["table_id"];
1057
+ const targetTable = resourceRef(tableId);
1058
+ const tableLabel = targetTable?.label ??
1059
+ (isTfExpr(tableId) && tableId.$expr === "data-attr" && tableId.type === TABLE_RESOURCE_TYPE ? tableId.label : undefined);
1060
+ if (tableLabel !== undefined && tableLabel !== "") {
1061
+ const tableHandle = tfLabelToTsLabel(tableLabel);
1062
+ const prefix = `tables_${tableLabel}_`;
1063
+ const tableKey = tfLabelToTsLabel(searchTableLabel.startsWith(prefix) ? searchTableLabel.slice(prefix.length) : searchTableLabel);
1064
+ return { kind: "searchTable", appHandle: `tables.${tableHandle}`, tableKey };
1065
+ }
1066
+ return undefined;
1067
+ }
1068
+ if (block.type === SEARCH_TABLE_RESOURCE_TYPES.snowflake || block.type === SEARCH_TABLE_RESOURCE_TYPES.linked) {
1069
+ const objectId = block.attrs["object_id"];
1070
+ if (!isTfExpr(objectId) || (objectId.$expr !== "resource-attr" && objectId.$expr !== "data-attr") || objectId.type !== "elementum_element")
1071
+ return undefined;
1072
+ const elementHandle = aspectOwnerRefNameFromObjectId(objectId, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames);
1073
+ if (elementHandle === undefined)
1074
+ return undefined;
1075
+ const rawElementLabel = objectId.label.startsWith("elements_") ? objectId.label.slice("elements_".length) : objectId.label;
1076
+ const elementTfLabel = tsLabelToTfLabel(elementHandle);
1077
+ const tableKey = scopedLabelToBagKey(elementTfLabel, searchTableLabel, "element") !== tfLabelToTsLabel(searchTableLabel)
1078
+ ? scopedLabelToBagKey(elementTfLabel, searchTableLabel, "element")
1079
+ : scopedLabelToBagKey(rawElementLabel, searchTableLabel, "element");
1080
+ return { kind: "searchTable", appHandle: elementHandle, tableKey };
1081
+ }
1082
+ return undefined;
1083
+ }
1084
+ function decodeSearchTableReference(value, ctx) {
1085
+ if (isTfExpr(value) && value.$expr === "data-attr" && value.type === "elementum_search_table") {
1086
+ const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1087
+ const name = typeof lookup?.attrs.name === "string" ? lookup.attrs.name : undefined;
1088
+ const objectId = lookup?.attrs.object_id ?? lookup?.attrs.aspect_id;
1089
+ const elementHandle = objectId !== undefined
1090
+ ? aspectOwnerRefNameFromObjectId(objectId, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames)
1091
+ : undefined;
1092
+ if (elementHandle !== undefined && name !== undefined) {
1093
+ const tableKey = tfLabelToTsLabel(sanitizeName(name));
1094
+ return { kind: "searchTable", appHandle: elementHandle, tableKey };
1095
+ }
1096
+ return { kind: "unresolved", uuid: `data.${value.type}.${value.label}`, hint: "search table" };
1097
+ }
1098
+ const ref = resourceRef(value);
1099
+ if (ref !== undefined &&
1100
+ (ref.type === SEARCH_TABLE_RESOURCE_TYPES.snowflake ||
1101
+ ref.type === SEARCH_TABLE_RESOURCE_TYPES.linked ||
1102
+ ref.type === SEARCH_TABLE_RESOURCE_TYPES.table)) {
1103
+ const block = ctx.resourceBlocks.get(`${ref.type}.${ref.label}`);
1104
+ if (block !== undefined) {
1105
+ const resolved = resolveSearchTableFromBlock(block, ref.label, ctx);
1106
+ if (resolved !== undefined)
1107
+ return resolved;
1108
+ }
1109
+ const uuid = ctx.resourceImportIds.get(`${ref.type}.${ref.label}`) ?? `${ref.type}.${ref.label}`;
1110
+ return { kind: "unresolved", uuid, hint: "search table" };
1111
+ }
1112
+ if (typeof value === "string") {
1113
+ for (const [address, id] of ctx.resourceImportIds) {
1114
+ if (id === value) {
1115
+ const block = ctx.resourceBlocks.get(address);
1116
+ if (block !== undefined) {
1117
+ const searchTableLabel = address.split(".").slice(1).join(".");
1118
+ const resolved = resolveSearchTableFromBlock(block, searchTableLabel, ctx);
1119
+ if (resolved !== undefined)
1120
+ return resolved;
1121
+ }
1122
+ }
1123
+ }
1124
+ return { kind: "unresolved", uuid: value, hint: "search table" };
1125
+ }
1126
+ if (isTfExpr(value) && (value.$expr === "data-attr" || value.$expr === "resource-attr")) {
1127
+ const prefix = value.$expr === "data-attr" ? "data." : "";
1128
+ return { kind: "unresolved", uuid: `${prefix}${value.type}.${value.label}`, hint: "search table" };
1129
+ }
1130
+ return { kind: "unresolved", uuid: typeof value === "string" ? value : JSON.stringify(value), hint: "search table" };
1131
+ }
811
1132
  function decodeValue(value, ctx) {
812
1133
  if (isTfExpr(value)) {
813
1134
  if (value.$expr === "template") {
@@ -832,6 +1153,12 @@ function decodeValue(value, ctx) {
832
1153
  }
833
1154
  if (task !== undefined && value.path[0] === "refs") {
834
1155
  const rawSegments = pathNames(value.path.slice(1));
1156
+ if (rawSegments.length === 1) {
1157
+ const aiAgentPath = aiAgentTaskRefPath(task.block, rawSegments[0]);
1158
+ if (aiAgentPath !== undefined) {
1159
+ return { kind: "taskRef", task: task.refKey, path: aiAgentPath };
1160
+ }
1161
+ }
835
1162
  if (task.block.type === "elementum_record_search_task" && rawSegments.length === 1 && rawSegments[0] === "First found record id") {
836
1163
  return { kind: "taskRef", task: task.refKey, path: ["record", "recordId"] };
837
1164
  }
@@ -858,14 +1185,16 @@ function decodeValue(value, ctx) {
858
1185
  return { kind: "taskRef", task: task.refKey, path: recordPath };
859
1186
  }
860
1187
  }
861
- if (task.block.type === "elementum_record_search_task" && rawSegments.length === 1) {
1188
+ if (task.block.type === "elementum_record_search_task" && rawSegments.length >= 1) {
862
1189
  const recordSearchName = RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS[rawSegments[0]];
863
1190
  if (recordSearchName !== undefined) {
864
- return { kind: "taskRef", task: task.refKey, path: [recordSearchName] };
1191
+ return { kind: "taskRef", task: task.refKey, path: [recordSearchName, ...rawSegments.slice(1)] };
865
1192
  }
866
- const recordFieldPath = taskRecordSearchFieldPath(`${value.type}.${value.label}`, rawSegments[0], ctx);
867
- if (recordFieldPath !== undefined) {
868
- return { kind: "taskRef", task: task.refKey, path: recordFieldPath };
1193
+ if (rawSegments.length === 1) {
1194
+ const recordFieldPath = taskRecordSearchFieldPath(`${value.type}.${value.label}`, rawSegments[0], ctx);
1195
+ if (recordFieldPath !== undefined) {
1196
+ return { kind: "taskRef", task: task.refKey, path: recordFieldPath };
1197
+ }
869
1198
  }
870
1199
  }
871
1200
  if (task.block.type === "elementum_ai_search_table_task" && rawSegments.length === 1) {
@@ -880,6 +1209,15 @@ function decodeValue(value, ctx) {
880
1209
  return { kind: "taskRef", task: task.refKey, path: [tableSearchName] };
881
1210
  }
882
1211
  }
1212
+ // apiRequest's refs map uses display labels ("File", "Content Type",
1213
+ // …) that don't match the lowercase authoring property names
1214
+ // (`file`, `file.contentType`) - see API_TASK_REF_AUTHORING_NAMES.
1215
+ if (task.block.type === "elementum_api_task" && rawSegments.length === 1) {
1216
+ const apiPath = apiTaskRefAuthoringPath(rawSegments[0]);
1217
+ if (apiPath !== undefined) {
1218
+ return { kind: "taskRef", task: task.refKey, path: apiPath };
1219
+ }
1220
+ }
883
1221
  const keyPath = rawSegments.flatMap((segment) => segment.split("."));
884
1222
  if (task.block.type === "elementum_variable_task") {
885
1223
  return { kind: "variableParamRef", varTask: task.refKey, name: keyPath.join(".") };
@@ -967,6 +1305,12 @@ function decodeValue(value, ctx) {
967
1305
  ...(unresolvedId !== undefined ? { unresolvedId } : {}),
968
1306
  };
969
1307
  }
1308
+ if ((value.type === SEARCH_TABLE_RESOURCE_TYPES.snowflake ||
1309
+ value.type === SEARCH_TABLE_RESOURCE_TYPES.linked ||
1310
+ value.type === SEARCH_TABLE_RESOURCE_TYPES.table) &&
1311
+ value.path[0] === "id") {
1312
+ return decodeSearchTableReference(value, ctx);
1313
+ }
970
1314
  throw new EntityTfError(`unreconstructable resource reference ${value.type}.${value.label}`);
971
1315
  }
972
1316
  if (value.$expr === "data-attr" && value.type === TABLE_RESOURCE_TYPE && value.path[0] === "id") {
@@ -983,6 +1327,26 @@ function decodeValue(value, ctx) {
983
1327
  const tableName = lookup?.attrs.name;
984
1328
  return tableColumnRefFromPath(value.label, value.path, typeof tableName === "string" ? tableName : undefined);
985
1329
  }
1330
+ if (value.$expr === "data-attr" && value.type === "elementum_datamine" && value.path[0] === "id") {
1331
+ const datamineLookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1332
+ const tableId = datamineLookup?.attrs["table_id"];
1333
+ if (tableId === undefined ||
1334
+ !isTfExpr(tableId) ||
1335
+ tableId.$expr !== "data-attr" ||
1336
+ tableId.type !== TABLE_RESOURCE_TYPE ||
1337
+ tableId.path[0] !== "id") {
1338
+ throw new EntityTfError(`data.elementum_datamine.${value.label}: table_id is not a table data reference`);
1339
+ }
1340
+ const prefix = `${tableId.label}_`;
1341
+ return {
1342
+ kind: "datamine",
1343
+ tableHandle: tfLabelToTsLabel(tableId.label),
1344
+ datamineKey: tfLabelToTsLabel(value.label.startsWith(prefix) ? value.label.slice(prefix.length) : value.label),
1345
+ };
1346
+ }
1347
+ if (value.$expr === "data-attr" && value.type === "elementum_search_table" && value.path[0] === "id") {
1348
+ return decodeSearchTableReference(value, ctx);
1349
+ }
986
1350
  if (value.$expr === "data-attr" && (value.type === "elementum_app" || value.type === "elementum_element") && value.path[0] === "id") {
987
1351
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
988
1352
  const name = lookup?.attrs.name ?? lookup?.attrs.namespace;
@@ -1055,6 +1419,51 @@ function decodeValue(value, ctx) {
1055
1419
  if (value.$expr === "data-attr" && value.type === "elementum_ai_provider_connector" && value.path[0] === "id") {
1056
1420
  return { kind: "connector", id: "", ...resolveConnectorRef(value.type, value.label, ctx) };
1057
1421
  }
1422
+ if (value.$expr === "data-attr" && value.type === "elementum_stored_function" && value.path[0] === "id") {
1423
+ const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1424
+ const name = lookup?.attrs.name;
1425
+ const cloudLinkId = lookup?.attrs.cloudlink_id;
1426
+ const databaseName = lookup?.attrs.database_name;
1427
+ const schemaName = lookup?.attrs.schema_name;
1428
+ const functionType = lookup?.attrs.type;
1429
+ const parameterTypes = lookup?.attrs.parameter_types;
1430
+ if (typeof name !== "string" || name === "") {
1431
+ throw new EntityTfError(`data.elementum_stored_function.${value.label}: name lookup is missing`);
1432
+ }
1433
+ if (functionType !== "PROCEDURE") {
1434
+ throw new EntityTfError(`data.elementum_stored_function.${value.label}: type must be PROCEDURE for an automation procedure task`);
1435
+ }
1436
+ if (!Array.isArray(parameterTypes) || !parameterTypes.every((item) => typeof item === "string")) {
1437
+ throw new EntityTfError(`data.elementum_stored_function.${value.label}: parameter_types must carry the exact procedure signature`);
1438
+ }
1439
+ if (typeof databaseName !== "string" || databaseName === "" || typeof schemaName !== "string" || schemaName === "") {
1440
+ throw new EntityTfError(`data.elementum_stored_function.${value.label}: database_name and schema_name must identify the procedure location`);
1441
+ }
1442
+ if (cloudLinkId === undefined ||
1443
+ !isTfExpr(cloudLinkId) ||
1444
+ cloudLinkId.$expr !== "data-attr" ||
1445
+ cloudLinkId.type !== "elementum_cloudlink" ||
1446
+ cloudLinkId.path[0] !== "id") {
1447
+ throw new EntityTfError(`data.elementum_stored_function.${value.label}: cloudlink_id is not a resolvable CloudLink data reference`);
1448
+ }
1449
+ // Two procedures can share a sanitized name within one CloudLink
1450
+ // (overloads) — org.ts disambiguates them with a numeric suffix
1451
+ // assigned across the WHOLE procedure list, a decision this single
1452
+ // data block can't reconstruct alone. Resolve the exact bag key from
1453
+ // the already-pulled org catalog by the same discriminator
1454
+ // (CloudLink + name + database + schema + ordered parameter types);
1455
+ // fall back to the base sanitized key, which is already correct
1456
+ // whenever there's no overload to disambiguate.
1457
+ const cloudLinkName = ctx.dataBlocks.get(`${cloudLinkId.type}.${cloudLinkId.label}`)?.attrs.name;
1458
+ const resolvedKey = typeof cloudLinkName === "string"
1459
+ ? ctx.procedureKeysByDiscriminator?.get(procedureDiscriminator(cloudLinkName, name, databaseName, schemaName, parameterTypes))
1460
+ : undefined;
1461
+ return {
1462
+ kind: "procedure",
1463
+ cloudLinkKey: tfLabelToTsLabel(cloudLinkId.label),
1464
+ procedureKey: resolvedKey ?? tfLabelToTsLabel(sanitizeName(name)),
1465
+ };
1466
+ }
1058
1467
  if (value.$expr === "data-attr" && value.type === "elementum_cloudlink" && value.path[0] === "id") {
1059
1468
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1060
1469
  const name = lookup?.attrs.name;
@@ -1237,7 +1646,8 @@ function decodeCalculationFormula(value, ctx) {
1237
1646
  if (index > cursor)
1238
1647
  parts.push(value.slice(cursor, index));
1239
1648
  if (match[3] !== undefined) {
1240
- parts.push({ kind: "unresolved", uuid: `variable.${match[3]}`, hint: "variable" });
1649
+ const resolved = resolveVariableReference(match[3], match[3], undefined, ctx);
1650
+ parts.push(resolved ?? { kind: "unresolved", uuid: `variable.${match[3]}`, hint: "variable" });
1241
1651
  cursor = index + match[0].length;
1242
1652
  continue;
1243
1653
  }
@@ -1279,6 +1689,11 @@ function decodeCalculationTaskMustache(taskId, wireName, ctx) {
1279
1689
  if (refKey === undefined) {
1280
1690
  return { kind: "unresolved", uuid: `task.${taskId}.${wireName}`, hint: "calculation-reference" };
1281
1691
  }
1692
+ if (taskBlock !== undefined) {
1693
+ const aiAgentPath = aiAgentTaskRefPath(taskBlock, wireName);
1694
+ if (aiAgentPath !== undefined)
1695
+ return { kind: "taskRef", task: refKey, path: aiAgentPath };
1696
+ }
1282
1697
  if (taskBlock?.type === "elementum_record_search_task") {
1283
1698
  const recordSearchName = RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS[wireName];
1284
1699
  if (recordSearchName !== undefined) {
@@ -1304,6 +1719,12 @@ function decodeCalculationTaskMustache(taskId, wireName, ctx) {
1304
1719
  return { kind: "taskRef", task: refKey, path: [tableSearchName] };
1305
1720
  }
1306
1721
  }
1722
+ if (taskBlock?.type === "elementum_api_task") {
1723
+ const apiPath = apiTaskRefAuthoringPath(wireName);
1724
+ if (apiPath !== undefined) {
1725
+ return { kind: "taskRef", task: refKey, path: apiPath };
1726
+ }
1727
+ }
1307
1728
  const keyPath = wireName.split(".");
1308
1729
  const taskKind = taskBlock?.type !== undefined ? TASK_FACTORIES[taskBlock.type] : undefined;
1309
1730
  const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
@@ -1334,8 +1755,49 @@ function pulledRawCalculation(formula, outputType, multiple) {
1334
1755
  const resultType = PULLED_CALCULATION_RESULT_TYPES[outputType];
1335
1756
  return resultType === undefined ? undefined : { kind: "calculationRaw", text: formula, resultType };
1336
1757
  }
1337
- function decodeFilterReferenceEnvelope(value, ctx) {
1338
- const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
1758
+ function resolveVariableReference(rawId, rawName, outputName, ctx) {
1759
+ const variableTasks = [];
1760
+ for (const [, task] of ctx.taskByAddress) {
1761
+ if (task.block.type === "elementum_variable_task") {
1762
+ const varName = typeof task.block.attrs.variable_name === "string"
1763
+ ? task.block.attrs.variable_name
1764
+ : (typeof task.block.attrs.name === "string" ? task.block.attrs.name : task.refKey);
1765
+ const varId = typeof task.block.attrs.variable_id === "string"
1766
+ ? task.block.attrs.variable_id
1767
+ : undefined;
1768
+ variableTasks.push({ refKey: task.refKey, varName, varId });
1769
+ }
1770
+ }
1771
+ if (variableTasks.length === 0)
1772
+ return undefined;
1773
+ // 1. By variable ID if available on the variable task block
1774
+ if (rawId !== undefined) {
1775
+ const byId = variableTasks.find((vt) => vt.varId === rawId);
1776
+ if (byId !== undefined) {
1777
+ return { kind: "variableParamRef", varTask: byId.refKey, name: byId.varName };
1778
+ }
1779
+ }
1780
+ // 2. By variable name or refKey if rawName is not a synthetic variable|<uuid> name
1781
+ if (rawName !== undefined && !rawName.startsWith("variable|") && !rawName.startsWith("variable.")) {
1782
+ const byName = variableTasks.find((vt) => vt.varName === rawName || vt.refKey === rawName);
1783
+ if (byName !== undefined) {
1784
+ return { kind: "variableParamRef", varTask: byName.refKey, name: byName.varName };
1785
+ }
1786
+ }
1787
+ // 3. By target output name (only for workflow_publish outputs where outputName is provided)
1788
+ if (outputName !== undefined) {
1789
+ const byOutput = variableTasks.find((vt) => vt.varName === outputName || vt.refKey === outputName);
1790
+ if (byOutput !== undefined) {
1791
+ return { kind: "variableParamRef", varTask: byOutput.refKey, name: byOutput.varName };
1792
+ }
1793
+ }
1794
+ return undefined;
1795
+ }
1796
+ function decodeFilterReferenceEnvelope(value, ctx, outputName) {
1797
+ let raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
1798
+ while (isObject(raw) && "value" in raw && Object.keys(raw).length === 1) {
1799
+ raw = raw.value;
1800
+ }
1339
1801
  if (!isObject(raw))
1340
1802
  return undefined;
1341
1803
  const taskRef = raw.taskReference;
@@ -1350,8 +1812,26 @@ function decodeFilterReferenceEnvelope(value, ctx) {
1350
1812
  return decodeReferenceString(`trigger.${triggerRef.name}`, ctx);
1351
1813
  }
1352
1814
  const variableRef = raw.variableReference;
1353
- if (isObject(variableRef) && typeof variableRef.id === "string") {
1354
- return { kind: "unresolved", uuid: `variable.${variableRef.id}`, hint: "variable" };
1815
+ if (isObject(variableRef)) {
1816
+ let rawId = typeof variableRef.id === "string" && variableRef.id !== "" ? variableRef.id : undefined;
1817
+ let rawName = typeof variableRef.name === "string" && variableRef.name !== "" ? variableRef.name : undefined;
1818
+ if (rawName !== undefined) {
1819
+ if (rawName.startsWith("variable|")) {
1820
+ const afterPrefix = rawName.slice("variable|".length);
1821
+ if (rawId === undefined)
1822
+ rawId = afterPrefix;
1823
+ }
1824
+ else if (rawName.startsWith("variable.")) {
1825
+ const afterPrefix = rawName.slice("variable.".length);
1826
+ if (rawId === undefined)
1827
+ rawId = afterPrefix;
1828
+ }
1829
+ }
1830
+ const resolved = resolveVariableReference(rawId, rawName, outputName, ctx);
1831
+ if (resolved !== undefined)
1832
+ return resolved;
1833
+ const fallbackUuid = rawId ?? (rawName !== undefined ? rawName.replace(/^variable[|.]/, "") : "unknown");
1834
+ return { kind: "unresolved", uuid: `variable.${fallbackUuid}`, hint: "variable" };
1355
1835
  }
1356
1836
  return undefined;
1357
1837
  }
@@ -1378,6 +1858,26 @@ function filterReference(value, ctx) {
1378
1858
  ?? decodeTemplateTaskRef(value, ctx)
1379
1859
  ?? decodeValue(value, ctx);
1380
1860
  }
1861
+ function filterReferenceType(value, fallback, ctx) {
1862
+ const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
1863
+ if (!isObject(raw))
1864
+ return fallback;
1865
+ const taskRef = raw.taskReference;
1866
+ if (isObject(taskRef) && typeof taskRef.name === "string") {
1867
+ const taskIdOrKey = workflowOutputTaskIdOrKey(taskRef.taskId, ctx);
1868
+ const task = taskIdOrKey === undefined ? undefined : resolveTaskRefKey(taskIdOrKey, ctx).block;
1869
+ if (task?.type === "elementum_execute_script_task") {
1870
+ const schemaValue = task.attrs.output_schema;
1871
+ const schema = isTfExpr(schemaValue) && schemaValue.$expr === "jsonencode"
1872
+ ? schemaValue.value
1873
+ : schemaValue;
1874
+ const declared = outputFieldTypesFromScriptSchema(schema)?.get(taskRef.name);
1875
+ if (declared !== undefined)
1876
+ return fieldTypeToValueType(declared.fieldType);
1877
+ }
1878
+ }
1879
+ return typeof raw.fieldType === "string" ? fieldTypeToValueType(raw.fieldType) : fallback;
1880
+ }
1381
1881
  function decodeFilter(value, ctx, fieldScope = "app") {
1382
1882
  return deserializeFilterFromTf(value, {
1383
1883
  field: (fieldValue, scope) => {
@@ -1385,6 +1885,7 @@ function decodeFilter(value, ctx, fieldScope = "app") {
1385
1885
  return field ?? { kind: "unresolved", uuid: String(fieldValue), hint: "field" };
1386
1886
  },
1387
1887
  reference: (reference) => filterReference(reference, ctx),
1888
+ referenceType: (reference, fallback) => filterReferenceType(reference, fallback, ctx),
1388
1889
  literal: (literal) => picklistOptionLabel(literal) ?? stageFilterName(literal, ctx) ?? literal,
1389
1890
  }, fieldScope);
1390
1891
  }
@@ -1409,7 +1910,22 @@ function triggerFromBlock(block, ctx) {
1409
1910
  // source uses a type-checkable alias instead of a raw wire string
1410
1911
  // "attachment" that TriggerFieldTypeAlias doesn't accept.
1411
1912
  const type = parameter.type === "attachment" ? "attachmentId" : parameter.type;
1412
- return { name: parameter.name, type, ...(parameter.required === true ? { required: true } : {}), ...(parameter.multiple === true ? { multiple: true } : {}), ...(parameter.default_value !== undefined ? { defaultValue: parameter.default_value } : {}), ...(typeof parameter.description === "string" ? { description: parameter.description } : {}) };
1913
+ const record = type === "record";
1914
+ const recordApp = record
1915
+ ? aspectRefFromObjectId(parameter.default_value, ctx)
1916
+ : undefined;
1917
+ if (record && recordApp === undefined) {
1918
+ throw new EntityTfError(`on-demand record parameter "${parameter.name}" has no resolvable app/element default_value`);
1919
+ }
1920
+ return {
1921
+ name: parameter.name,
1922
+ type,
1923
+ ...(recordApp !== undefined ? { app: recordApp } : {}),
1924
+ ...(parameter.required === true ? { required: true } : {}),
1925
+ ...(parameter.multiple === true ? { multiple: true } : {}),
1926
+ ...(!record && parameter.default_value !== undefined ? { defaultValue: parameter.default_value } : {}),
1927
+ ...(typeof parameter.description === "string" ? { description: parameter.description } : {}),
1928
+ };
1413
1929
  }), ...(block.attrs.show_triggered_by === true ? { showTriggeredBy: true } : {})
1414
1930
  };
1415
1931
  }
@@ -1436,8 +1952,13 @@ function triggerFromBlock(block, ctx) {
1436
1952
  ...(block.attrs.custom_response !== undefined ? { customResponse: decodeCustomResponse(block.attrs.custom_response, ctx) } : {}),
1437
1953
  };
1438
1954
  case "approvalProcessStatusUpdated": {
1439
- if (block.attrs.approval_chain_template_id === undefined || typeof block.attrs.status !== "string")
1955
+ if (typeof block.attrs.status !== "string")
1440
1956
  throw new EntityTfError("approval trigger is incomplete");
1957
+ // approval_chain_template_id is genuinely omittable on the platform
1958
+ // (edk#712) - a null/never-set template means "any", not "unresolved".
1959
+ if (block.attrs.approval_chain_template_id === undefined) {
1960
+ return { kind, app, status: block.attrs.status };
1961
+ }
1441
1962
  const approvalChain = typeof block.attrs.approval_chain_template_id === "string"
1442
1963
  ? block.attrs.approval_chain_template_id
1443
1964
  : decodeValue(block.attrs.approval_chain_template_id, ctx);
@@ -1642,6 +2163,10 @@ function taskArgs(block, factory, ctx) {
1642
2163
  : decodeValue(value, ctx);
1643
2164
  continue;
1644
2165
  }
2166
+ if (attr === "search_table_id" && factory === "aiSearchTable") {
2167
+ args.table = decodeSearchTableReference(value, ctx);
2168
+ continue;
2169
+ }
1645
2170
  if (factory === "approvalChain" && attr === "approval_process_id") {
1646
2171
  args.approvalProcess = decodeValue(value, ctx);
1647
2172
  continue;
@@ -1651,12 +2176,34 @@ function taskArgs(block, factory, ctx) {
1651
2176
  continue;
1652
2177
  }
1653
2178
  if (factory === "approvalChain" && attr === "requester_reference") {
2179
+ const fieldType = approverReferenceFieldAuthoringType(value, ctx);
2180
+ if (fieldType === UNVERIFIABLE_FOREIGN_FIELD_TYPE) {
2181
+ throw new EntityTfError(`${block.type}.${block.label}: requester_reference targets a field on a foreign aspect that has never been ` +
2182
+ "pulled locally — its type cannot be verified against the platform's required USER_ID reference; pull that " +
2183
+ "aspect first (`elementum pull app`/`pull element`), then re-pull this app (edk#768)");
2184
+ }
2185
+ if (fieldType !== undefined && fieldType !== "USER") {
2186
+ throw new EntityTfError(`${block.type}.${block.label}: requester_reference targets a "${fieldType}" field, not a USER field — ` +
2187
+ `the platform's approval-chain validation requires a USER_ID type reference (edk#655)`);
2188
+ }
1654
2189
  args.requester = decodeValue(value, ctx);
1655
2190
  continue;
1656
2191
  }
1657
2192
  if (factory === "approvalChain" && attr === "approver_references") {
1658
2193
  if (!Array.isArray(value))
1659
2194
  throw new EntityTfError(`${block.type}.${block.label}: approver_references must be an array`);
2195
+ for (const item of value) {
2196
+ const fieldType = approverReferenceFieldAuthoringType(item, ctx);
2197
+ if (fieldType === UNVERIFIABLE_FOREIGN_FIELD_TYPE) {
2198
+ throw new EntityTfError(`${block.type}.${block.label}: approver_references targets a field on a foreign aspect that has never been ` +
2199
+ "pulled locally — its type cannot be verified against the platform's required USER_ID reference; pull that " +
2200
+ "aspect first (`elementum pull app`/`pull element`), then re-pull this app (edk#768)");
2201
+ }
2202
+ if (fieldType !== undefined && fieldType !== "USER") {
2203
+ throw new EntityTfError(`${block.type}.${block.label}: approver_references targets a "${fieldType}" field, not a USER field — ` +
2204
+ `the platform's approval-chain validation requires a USER_ID type reference (edk#655)`);
2205
+ }
2206
+ }
1660
2207
  args.approvers = value.map((item) => decodeValue(item, ctx));
1661
2208
  continue;
1662
2209
  }
@@ -1681,6 +2228,29 @@ function taskArgs(block, factory, ctx) {
1681
2228
  args.outputType = typeof value === "string" ? value.toLowerCase() : decodeValue(value, ctx);
1682
2229
  continue;
1683
2230
  }
2231
+ if (attr === "json_fields" && factory === "aiAgent") {
2232
+ const outputType = block.attrs.output_type;
2233
+ if (typeof outputType !== "string" || outputType.toLowerCase() !== "json")
2234
+ continue;
2235
+ if (!Array.isArray(value))
2236
+ throw new EntityTfError(`${block.type}.${block.label}: json_fields must be an array`);
2237
+ args.schema = Object.fromEntries(value.map((field) => {
2238
+ if (!isObject(field) || typeof field.name !== "string" || typeof field.type !== "string") {
2239
+ throw new EntityTfError(`${block.type}.${block.label}: invalid json_fields entry`);
2240
+ }
2241
+ return [
2242
+ field.name,
2243
+ {
2244
+ type: field.type.toLowerCase(),
2245
+ ...(typeof field.description === "string" && field.description !== ""
2246
+ ? { description: field.description }
2247
+ : {}),
2248
+ ...(typeof field.required === "boolean" ? { required: field.required } : {}),
2249
+ },
2250
+ ];
2251
+ }));
2252
+ continue;
2253
+ }
1684
2254
  // procedure()'s wire shape wraps each positional argument as
1685
2255
  // `{index, value}` (see tasks.ts's procedure()); ProcedureOptions.parameters
1686
2256
  // is a plain, position-ordered array - unwrap rather than round-tripping
@@ -1825,6 +2395,18 @@ function taskArgs(block, factory, ctx) {
1825
2395
  args.relatedApp = args.app ?? appRef(ctx.appRefName);
1826
2396
  delete args.app;
1827
2397
  }
2398
+ if (factory === "procedure") {
2399
+ const procedure = args.procedureId;
2400
+ if (isObject(procedure) && procedure.kind === "procedure") {
2401
+ const cloudLink = args.cloudLinkId;
2402
+ if (!isObject(cloudLink) || cloudLink.kind !== "cloudLink" || cloudLink.handle !== procedure.cloudLinkKey) {
2403
+ throw new EntityTfError(`${block.type}.${block.label}: stored function and task cloudlink_id refer to different CloudLinks`);
2404
+ }
2405
+ args.procedure = procedure;
2406
+ delete args.procedureId;
2407
+ delete args.cloudLinkId;
2408
+ }
2409
+ }
1828
2410
  if (factory === "setVariable") {
1829
2411
  if (block.type === "elementum_variable_task") {
1830
2412
  if (typeof block.attrs.variable_name !== "string" || typeof block.attrs.variable_type !== "string")
@@ -1838,10 +2420,62 @@ function taskArgs(block, factory, ctx) {
1838
2420
  }
1839
2421
  return args;
1840
2422
  }
1841
- function parentAddress(block) {
2423
+ /**
2424
+ * Resolve an `elementum_unmanaged_task_reference` data block's OWN real
2425
+ * position in the task tree from its `operator_child_id`/`operator_task_id`/
2426
+ * `parent_is_trigger` attributes (edk#821) - the platform already records
2427
+ * exactly which switch case / fork-join branch / forEach body (or the
2428
+ * trigger) the unsupported task sits in; this was previously discarded
2429
+ * entirely in favor of always anchoring to the trigger. Returns `undefined`
2430
+ * when none of those attributes resolve to an address this automation
2431
+ * actually owns, so the caller can fall back to the trigger-anchor + diagnostic
2432
+ * safety net rather than pointing at an address nothing will ever visit.
2433
+ */
2434
+ function resolveUnmanagedTaskPosition(dataBlock, triggerAddress, ownedAddresses) {
2435
+ if (dataBlock.attrs.parent_is_trigger === true)
2436
+ return triggerAddress;
2437
+ const operatorRef = resourceRef(dataBlock.attrs.operator_task_id);
2438
+ if (operatorRef?.type === "elementum_for_each_task") {
2439
+ const inner = `${operatorRef.type}.${operatorRef.label}.inner`;
2440
+ return ownedAddresses.has(`${operatorRef.type}.${operatorRef.label}`) ? inner : undefined;
2441
+ }
2442
+ const childRef = resourceRef(dataBlock.attrs.operator_child_id);
2443
+ if (childRef !== undefined) {
2444
+ const address = `${childRef.type}.${childRef.label}`;
2445
+ return ownedAddresses.has(address) ? address : undefined;
2446
+ }
2447
+ if (operatorRef !== undefined) {
2448
+ const address = `${operatorRef.type}.${operatorRef.label}`;
2449
+ return ownedAddresses.has(address) ? address : undefined;
2450
+ }
2451
+ return undefined;
2452
+ }
2453
+ /**
2454
+ * `triggerAddress`/`onUnmanagedParent` are the fallback of last resort: a
2455
+ * task whose real predecessor is an unsupported task type, when that
2456
+ * predecessor's own position couldn't be resolved either (see
2457
+ * `resolveUnmanagedTaskPosition`), is anchored to the trigger instead - not
2458
+ * its true live position, but keeps it (and anything chained after it) from
2459
+ * being silently dropped from the authored source. `unmanagedTaskPositions`
2460
+ * maps each such data block's OWN address to its resolved position (edk#821)
2461
+ * - when present, the downstream task anchors onto the placeholder's own
2462
+ * address (its position in the tree), not the placeholder's resolved
2463
+ * position directly, so `buildTasks`'s normal flat-chain recursion picks up
2464
+ * the whole downstream chain from there.
2465
+ */
2466
+ function parentAddress(block, triggerAddress, unmanagedTaskPositions, onUnmanagedParent) {
1842
2467
  const parent = resourceRef(block.attrs.parent);
1843
- if (parent === undefined)
2468
+ if (parent === undefined) {
2469
+ const unmanagedRef = unmanagedTaskRef(block.attrs.parent);
2470
+ if (unmanagedRef !== undefined) {
2471
+ const address = `elementum_unmanaged_task_reference.${unmanagedRef.label}`;
2472
+ if (unmanagedTaskPositions.has(address))
2473
+ return address;
2474
+ onUnmanagedParent?.(block);
2475
+ return triggerAddress;
2476
+ }
1844
2477
  throw new EntityTfError(`${block.type}.${block.label}: missing or invalid parent`);
2478
+ }
1845
2479
  const suffix = parent.path.length > 0 ? `.${pathNames(parent.path).join(".")}` : "";
1846
2480
  return `${parent.type}.${parent.label}${suffix}`;
1847
2481
  }
@@ -1852,6 +2486,18 @@ function taskRefKey(block, automationLabel, appTfLabel) {
1852
2486
  const taskName = typeof block.attrs.name === "string" ? block.attrs.name : undefined;
1853
2487
  if (taskName !== undefined) {
1854
2488
  const sanitized = sanitizeName(taskName);
2489
+ // The platform can export created-variable tasks under generated positional
2490
+ // names such as "lookup_result_state 1" even though current-API authoring
2491
+ // keys them by the variable they create. Restrict this reconciliation to
2492
+ // that positional export shape: named tasks such as "set_variable_task"
2493
+ // remain valid action identities used by workflow outputs.
2494
+ if (block.type === "elementum_variable_task" &&
2495
+ typeof block.attrs.variable_name === "string" &&
2496
+ block.attrs.variable_name !== "" &&
2497
+ /(?:\s|-)\d+$/.test(taskName.trim()) &&
2498
+ (sanitized === tail || sanitized === `_${tail}`)) {
2499
+ return block.attrs.variable_name;
2500
+ }
1855
2501
  // ei sanitizes `<automation>_<task>` as ONE combined string
1856
2502
  // (imports.go), so the digit-leading guard only ever sees the
1857
2503
  // automation's own first character - a task name that itself starts
@@ -1931,7 +2577,7 @@ function unresolvedAuthoringValues(doc) {
1931
2577
  return values;
1932
2578
  }
1933
2579
  /** Extract one app-owned automation graph from an ei app export. */
1934
- function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames) {
2580
+ function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames, procedureKeysByDiscriminator) {
1935
2581
  const automation = doc.blocks.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE && block.label === automationLabel);
1936
2582
  if (automation === undefined)
1937
2583
  throw new EntityTfError(`automation resource "${automationLabel}" not found`);
@@ -1957,6 +2603,15 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1957
2603
  const branches = doc.blocks.filter((block) => block.kind === "resource" && AUTOMATION_BRANCH_TYPE_SET.has(block.type ?? ""));
1958
2604
  const taskCandidates = doc.blocks.filter((block) => block.kind === "resource" && ALL_AUTOMATION_TASK_TYPE_SET.has(block.type ?? ""));
1959
2605
  const resourceBlocks = new Map(doc.blocks.filter((block) => block.kind === "resource" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
2606
+ // edk#785: workflow_publish.depends_on is this automation's own manifest of
2607
+ // everything it owns (Go's build emits exactly one entry per task/trigger/
2608
+ // branch belonging to it) - the only reliable way to scope a task back to
2609
+ // THIS automation, since taskCandidates spans the whole app (doc.blocks is
2610
+ // every automation's blocks combined) and task labels carry no ownership
2611
+ // guarantee of their own.
2612
+ const publishDependencyAddresses = new Set(Array.isArray(publish?.attrs.depends_on)
2613
+ ? publish.attrs.depends_on.map((value) => resourceRef(value)).filter((ref) => ref !== undefined).map((ref) => `${ref.type}.${ref.label}`)
2614
+ : []);
1960
2615
  const owned = new Set([`${trigger.type}.${trigger.label}`]);
1961
2616
  let changed = true;
1962
2617
  while (changed) {
@@ -1974,6 +2629,12 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
1974
2629
  owned.add(`${task.type}.${task.label}`);
1975
2630
  changed = true;
1976
2631
  }
2632
+ // edk#785: a data-source parent is always "resolved" (see unmanagedTaskRef) -
2633
+ // doesn't need its target to already be owned the way a resource-attr parent does.
2634
+ else if (!parent && unmanagedTaskRef(task.attrs.parent) && publishDependencyAddresses.has(`${task.type}.${task.label}`) && !owned.has(`${task.type}.${task.label}`)) {
2635
+ owned.add(`${task.type}.${task.label}`);
2636
+ changed = true;
2637
+ }
1977
2638
  }
1978
2639
  }
1979
2640
  const tasks = taskCandidates.filter((block) => owned.has(`${block.type}.${block.label}`));
@@ -2023,17 +2684,31 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
2023
2684
  }
2024
2685
  for (const task of tasks) {
2025
2686
  const parent = resourceRef(task.attrs.parent);
2026
- if (parent === undefined || !owned.has(`${parent.type}.${parent.label}`))
2687
+ if (parent === undefined) {
2688
+ if (unmanagedTaskRef(task.attrs.parent) !== undefined)
2689
+ continue; // edk#785: always resolved, see unmanagedTaskRef
2690
+ throw new EntityTfError(`${task.type}.${task.label}: unresolved parent`);
2691
+ }
2692
+ if (!owned.has(`${parent.type}.${parent.label}`))
2027
2693
  throw new EntityTfError(`${task.type}.${task.label}: unresolved parent`);
2028
2694
  if (parent.path.length > 0 && !(parent.type === "elementum_for_each_task" && parent.path.length === 1 && parent.path[0] === "inner")) {
2029
2695
  throw new EntityTfError(`${task.type}.${task.label}: unsupported parent path`);
2030
2696
  }
2031
2697
  }
2032
2698
  const appTfLabel = app.label;
2699
+ const dataBlocks = new Map(doc.blocks.filter((block) => block.kind === "data" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
2033
2700
  const taskByAddress = new Map(tasks.map((block) => [`${block.type}.${block.label}`, { block, refKey: taskRefKey(block, automationLabel, appTfLabel) }]));
2701
+ const adoptionAddressAliases = [...taskByAddress.entries()].flatMap(([from, { block, refKey }]) => {
2702
+ if (block.type !== "elementum_variable_task" ||
2703
+ typeof block.attrs.variable_name !== "string" ||
2704
+ block.attrs.variable_name === "")
2705
+ return [];
2706
+ const to = `${block.type}.${taskTfLabel(automationLabel, refKey)}`;
2707
+ return to === from ? [] : [{ from, to }];
2708
+ });
2034
2709
  const taskTargetOwnerRefNameByAddress = new Map();
2035
2710
  for (const [address, { block }] of taskByAddress) {
2036
- const ownerRefName = aspectOwnerRefNameFromObjectId(block.attrs.object_id, appRefName, appTfLabel);
2711
+ const ownerRefName = aspectOwnerRefNameFromObjectId(block.attrs.object_id, appRefName, appTfLabel, dataBlocks, foreignAppRefNames, foreignElementRefNames);
2037
2712
  if (ownerRefName !== undefined)
2038
2713
  taskTargetOwnerRefNameByAddress.set(address, ownerRefName);
2039
2714
  }
@@ -2056,9 +2731,9 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
2056
2731
  fieldById.set(id, {
2057
2732
  key: scopedLabelToBagKey(appTfLabel, block.label ?? ""),
2058
2733
  name: typeof block.attrs.name === "string" ? block.attrs.name : block.label,
2734
+ resourceType: block.type,
2059
2735
  });
2060
2736
  }
2061
- const dataBlocks = new Map(doc.blocks.filter((block) => block.kind === "data" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
2062
2737
  const stagesByKey = new Map();
2063
2738
  const stagesAttr = resourceBlocks.get(`elementum_app.${app.label}`)?.attrs["stages"];
2064
2739
  if (Array.isArray(stagesAttr)) {
@@ -2085,6 +2760,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
2085
2760
  ...(taskTargetOwnerRefNameByAddress.size > 0 && { taskTargetOwnerRefNameByAddress }),
2086
2761
  ...(foreignAppRefNames !== undefined && { foreignAppRefNames }),
2087
2762
  ...(foreignElementRefNames !== undefined && { foreignElementRefNames }),
2763
+ ...(procedureKeysByDiscriminator !== undefined && { procedureKeysByDiscriminator }),
2088
2764
  };
2089
2765
  let serviceAccountName;
2090
2766
  const serviceAccountValue = automation.attrs.service_account_id;
@@ -2109,16 +2785,54 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
2109
2785
  if (publish && Array.isArray(publish.attrs.depends_on))
2110
2786
  publish.attrs.depends_on.forEach((dep, index) => { const ref = resourceRef(dep); if (ref)
2111
2787
  dependencyOrder.set(`${ref.type}.${ref.label}`, index); });
2788
+ const triggerAddress = `${trigger.type}.${trigger.label}`;
2789
+ const unrebuildableTasks = [];
2790
+ // edk#821: resolve each elementum_unmanaged_task_reference this automation's
2791
+ // OWN tasks actually parent onto (never the whole doc's data blocks - a
2792
+ // sibling automation sharing this export can have its own, edk#785) to its
2793
+ // real position, and merge it into the same address space real tasks live
2794
+ // in so its downstream chain lands in the right switch case / forkJoin
2795
+ // branch / forEach body instead of being hoisted to the automation's top level.
2796
+ const ownedAddresses = new Set([
2797
+ triggerAddress,
2798
+ ...tasks.map((t) => `${t.type}.${t.label}`),
2799
+ ...ownedBranches.map((b) => `${b.type}.${b.label}`),
2800
+ ]);
2801
+ const unmanagedTaskPositions = new Map();
2802
+ const placeholderTasks = [];
2803
+ for (const task of tasks) {
2804
+ const unmanagedRef = unmanagedTaskRef(task.attrs.parent);
2805
+ if (unmanagedRef === undefined)
2806
+ continue;
2807
+ const address = `elementum_unmanaged_task_reference.${unmanagedRef.label}`;
2808
+ if (unmanagedTaskPositions.has(address))
2809
+ continue;
2810
+ const dataBlock = dataBlocks.get(address);
2811
+ const position = dataBlock !== undefined ? resolveUnmanagedTaskPosition(dataBlock, triggerAddress, ownedAddresses) : undefined;
2812
+ if (dataBlock === undefined || position === undefined)
2813
+ continue; // falls back to parentAddress's trigger-anchor + diagnostic
2814
+ unmanagedTaskPositions.set(address, position);
2815
+ const refKey = typeof dataBlock.attrs.name === "string" && dataBlock.attrs.name !== "" ? dataBlock.attrs.name : tfLabelToTsLabel(dataBlock.label ?? "task");
2816
+ taskByAddress.set(address, { block: dataBlock, refKey });
2817
+ placeholderTasks.push({
2818
+ name: refKey,
2819
+ taskType: typeof dataBlock.attrs.task_type === "string" ? dataBlock.attrs.task_type : "unknown",
2820
+ });
2821
+ }
2112
2822
  const childrenByParent = new Map();
2113
2823
  for (const task of tasks) {
2114
- const parent = parentAddress(task);
2824
+ const parent = parentAddress(task, triggerAddress, unmanagedTaskPositions, (b) => unrebuildableTasks.push(`${b.type}.${b.label}`));
2115
2825
  childrenByParent.set(parent, [...(childrenByParent.get(parent) ?? []), task]);
2116
2826
  }
2827
+ for (const [address, position] of unmanagedTaskPositions) {
2828
+ const dataBlock = taskByAddress.get(address).block;
2829
+ childrenByParent.set(position, [...(childrenByParent.get(position) ?? []), dataBlock]);
2830
+ }
2117
2831
  for (const list of childrenByParent.values())
2118
2832
  list.sort((a, b) => (dependencyOrder.get(`${a.type}.${a.label}`) ?? Number.MAX_SAFE_INTEGER) - (dependencyOrder.get(`${b.type}.${b.label}`) ?? Number.MAX_SAFE_INTEGER) || a.label.localeCompare(b.label));
2119
2833
  const visiting = new Set();
2120
2834
  const visited = new Set();
2121
- const buildTasks = (parent) => (childrenByParent.get(parent) ?? []).flatMap((block) => {
2835
+ const buildTasks = (parent) => (childrenByParent.get(parent) ?? []).flatMap((block, siblingIndex) => {
2122
2836
  const address = `${block.type}.${block.label}`;
2123
2837
  if (visiting.has(address))
2124
2838
  throw new EntityTfError(`cycle detected at ${address}`);
@@ -2158,14 +2872,31 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
2158
2872
  });
2159
2873
  }
2160
2874
  const parent = resourceRef(block.attrs.parent);
2161
- const parentTask = parent === undefined ? undefined : taskByAddress.get(`${parent.type}.${parent.label}`);
2162
- const hclParent = parent?.type === trigger.type && parent?.label === trigger.label ? "trigger" : parentTask?.refKey;
2163
- const call = { factory, refKey, args: taskArgs(block, factory, ctx), ...(children ? { children } : {}), ...(typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {}), ...(hclParent !== undefined ? { hclParent } : {}) };
2875
+ const unmanagedParentRef = parent === undefined ? unmanagedTaskRef(block.attrs.parent) : undefined;
2876
+ const parentTask = parent !== undefined
2877
+ ? taskByAddress.get(`${parent.type}.${parent.label}`)
2878
+ : unmanagedParentRef !== undefined
2879
+ ? taskByAddress.get(`elementum_unmanaged_task_reference.${unmanagedParentRef.label}`)
2880
+ : undefined;
2881
+ // A sole/first child of its real parent is exactly what buildTasks's own
2882
+ // recursion already prints immediately after that parent, so an explicit
2883
+ // anchor is redundant with implicit sequential chaining - only a 2nd+
2884
+ // sibling sharing the same real parent is actually ambiguous without one.
2885
+ const hclParent = siblingIndex === 0
2886
+ ? undefined
2887
+ : parent?.type === trigger.type && parent?.label === trigger.label ? "trigger" : parentTask?.refKey;
2888
+ const args = factory === "unimplementedTask"
2889
+ ? {
2890
+ id: typeof block.attrs.id === "string" ? block.attrs.id : "",
2891
+ taskType: typeof block.attrs.task_type === "string" ? block.attrs.task_type : "",
2892
+ }
2893
+ : taskArgs(block, factory, ctx);
2894
+ const call = { factory, refKey, args, ...(children ? { children } : {}), ...(typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {}), ...(hclParent !== undefined ? { hclParent } : {}) };
2164
2895
  visiting.delete(address);
2165
2896
  return [call, ...buildTasks(address)];
2166
2897
  });
2167
2898
  const topTasks = buildTasks(`${trigger.type}.${trigger.label}`);
2168
- if (visited.size !== tasks.length)
2899
+ if (visited.size !== tasks.length + unmanagedTaskPositions.size)
2169
2900
  throw new EntityTfError(`automation "${automationLabel}" contains an orphaned task graph`);
2170
2901
  const outputBlocks = publish?.attrs.outputs;
2171
2902
  const outputs = Array.isArray(outputBlocks) ? outputBlocks.map((output) => {
@@ -2173,7 +2904,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
2173
2904
  throw new EntityTfError("invalid workflow output");
2174
2905
  // Export/provider Read emit jsonencode({fieldType, taskReference, ...});
2175
2906
  // collapse that envelope to a RefExpr the same way filter references do.
2176
- const value = decodeFilterReferenceEnvelope(output.value, ctx)
2907
+ const value = decodeFilterReferenceEnvelope(output.value, ctx, output.name)
2177
2908
  ?? decodeValue(output.value, ctx);
2178
2909
  return { name: output.name, value };
2179
2910
  }) : undefined;
@@ -2195,10 +2926,19 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
2195
2926
  };
2196
2927
  return {
2197
2928
  refName: scopedLabelToBagKey(appTfLabel, automationLabel),
2198
- tfLabel: automationLabel, ast, blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])]
2929
+ tfLabel: automationLabel,
2930
+ ast,
2931
+ blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])],
2932
+ adoptionAddressAliases,
2933
+ ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0) && {
2934
+ diagnostics: [
2935
+ ...unrebuildableTasks.map((address) => `automation "${automationLabel}": ${address}'s real parent is a task type EDK doesn't support yet, so its authored position couldn't be reconstructed (anchored to the trigger instead) - not rebuildable from this source until that task type is supported`),
2936
+ ...placeholderTasks.map(({ name, taskType }) => `automation "${automationLabel}" uses platform task type "${taskType}" ("${name}"), which EDK doesn't implement - kept as an unimplementedTask(...) placeholder; its configuration isn't authorable, but its position and downstream chain are round-trip-safe`),
2937
+ ],
2938
+ }),
2199
2939
  };
2200
2940
  }
2201
- export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth) {
2941
+ export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh) {
2202
2942
  if (Array.isArray(first)) {
2203
2943
  const ctx = second;
2204
2944
  const automationBlock = first.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE);
@@ -2206,9 +2946,10 @@ export function automationFromTf(first, second, third, fourth, fifth, sixth, sev
2206
2946
  return { skippedReason: "automation resource not found" };
2207
2947
  }
2208
2948
  try {
2209
- return {
2210
- automation: automationFromTfDocument({ blocks: [...first] }, automationBlock.label, ctx.ownerHandle, ctx.foreignFieldRefsById, ctx.foreignFieldRefsByDataAddress, ctx.foreignTableRefsById, ctx.picklistOptionLabelById, ctx.fieldNamesByOwnerRefName, ctx.foreignAppRefNames, ctx.foreignElementRefNames).ast,
2211
- };
2949
+ const result = automationFromTfDocument({ blocks: [...first] }, automationBlock.label, ctx.ownerHandle, ctx.foreignFieldRefsById, ctx.foreignFieldRefsByDataAddress, ctx.foreignTableRefsById, ctx.picklistOptionLabelById, ctx.fieldNamesByOwnerRefName, ctx.foreignAppRefNames, ctx.foreignElementRefNames, ctx.procedureKeysByDiscriminator);
2950
+ if (result.diagnostics)
2951
+ ctx.diagnostics.push(...result.diagnostics);
2952
+ return { automation: result.ast };
2212
2953
  }
2213
2954
  catch (err) {
2214
2955
  const message = err instanceof Error ? err.message : String(err);
@@ -2216,5 +2957,5 @@ export function automationFromTf(first, second, third, fourth, fifth, sixth, sev
2216
2957
  return { skippedReason: message };
2217
2958
  }
2218
2959
  }
2219
- return automationFromTfDocument(first, second, third ?? "", fourth, fifth, sixth, seventh, eighth, ninth, tenth);
2960
+ return automationFromTfDocument(first, second, third ?? "", fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh);
2220
2961
  }