@elementumai/edk 0.9.14 → 0.9.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/dist-sdk/pull/util.d.ts +0 -15
  2. package/dist-sdk/pull/util.js +44 -5
  3. package/dist-sdk/src/catalog/factories.d.ts +4 -2
  4. package/dist-sdk/src/catalog/factories.js +4 -0
  5. package/dist-sdk/src/catalog/from-authoring.js +5 -1
  6. package/dist-sdk/src/catalog/index.d.ts +2 -2
  7. package/dist-sdk/src/catalog/index.js +1 -1
  8. package/dist-sdk/src/catalog/token.js +2 -2
  9. package/dist-sdk/src/catalog/types.d.ts +7 -2
  10. package/dist-sdk/src/core/types/app.d.ts +4 -4
  11. package/dist-sdk/src/engine/build/context.d.ts +5 -4
  12. package/dist-sdk/src/engine/build/source-context.d.ts +2 -0
  13. package/dist-sdk/src/engine/build/source-context.js +16 -0
  14. package/dist-sdk/src/engine/progress.d.ts +19 -1
  15. package/dist-sdk/src/engine/progress.js +33 -5
  16. package/dist-sdk/src/engine/pull/context.d.ts +9 -1
  17. package/dist-sdk/src/engine/pull/ref-only.d.ts +6 -2
  18. package/dist-sdk/src/engine/pull/ref-only.js +14 -3
  19. package/dist-sdk/src/engine/workspace/loader.js +23 -2
  20. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +1 -1
  21. package/dist-sdk/src/entities/access-policy/from-tf.js +47 -12
  22. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +5 -3
  23. package/dist-sdk/src/entities/access-policy/to-tf.js +23 -1
  24. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +6 -0
  25. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +50 -4
  26. package/dist-sdk/src/entities/agent/from-tf.d.ts +1 -0
  27. package/dist-sdk/src/entities/agent/from-tf.js +18 -3
  28. package/dist-sdk/src/entities/agent/module.js +1 -0
  29. package/dist-sdk/src/entities/agent/to-tf.js +15 -0
  30. package/dist-sdk/src/entities/agent/tools.d.ts +98 -5
  31. package/dist-sdk/src/entities/agent/tools.js +12 -3
  32. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +15 -0
  33. package/dist-sdk/src/entities/agent-tool/from-tf.js +47 -4
  34. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +9 -0
  35. package/dist-sdk/src/entities/agent-tool/to-tf.js +82 -25
  36. package/dist-sdk/src/entities/app/build.d.ts +2 -2
  37. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +4 -4
  38. package/dist-sdk/src/entities/app/module.js +8 -0
  39. package/dist-sdk/src/entities/app/to-tf.js +1 -0
  40. package/dist-sdk/src/entities/approval-chain/build.d.ts +8 -1
  41. package/dist-sdk/src/entities/approval-chain/build.js +3 -0
  42. package/dist-sdk/src/entities/approval-chain/from-tf.d.ts +2 -1
  43. package/dist-sdk/src/entities/approval-chain/from-tf.js +20 -7
  44. package/dist-sdk/src/entities/approval-chain/printer.js +13 -2
  45. package/dist-sdk/src/entities/approval-chain/to-tf.js +3 -0
  46. package/dist-sdk/src/entities/automation/build.d.ts +19 -12
  47. package/dist-sdk/src/entities/automation/build.js +36 -13
  48. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +4 -0
  49. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +19 -0
  50. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +222 -65
  51. package/dist-sdk/src/entities/automation/from-tf.d.ts +86 -6
  52. package/dist-sdk/src/entities/automation/from-tf.js +360 -63
  53. package/dist-sdk/src/entities/automation/index.d.ts +3 -2
  54. package/dist-sdk/src/entities/automation/index.js +3 -2
  55. package/dist-sdk/src/entities/automation/module.js +21 -16
  56. package/dist-sdk/src/entities/automation/output-field-types.d.ts +5 -0
  57. package/dist-sdk/src/entities/automation/output-field-types.js +12 -0
  58. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +20 -0
  59. package/dist-sdk/src/entities/automation/output-key-wire-name.js +22 -0
  60. package/dist-sdk/src/entities/automation/script-code.d.ts +32 -0
  61. package/dist-sdk/src/entities/automation/script-code.js +72 -5
  62. package/dist-sdk/src/entities/automation/tasks.d.ts +60 -24
  63. package/dist-sdk/src/entities/automation/tasks.js +33 -14
  64. package/dist-sdk/src/entities/automation/to-tf.d.ts +0 -2
  65. package/dist-sdk/src/entities/automation/to-tf.js +123 -46
  66. package/dist-sdk/src/entities/automation/triggers.d.ts +5 -2
  67. package/dist-sdk/src/entities/automation/types.d.ts +2 -0
  68. package/dist-sdk/src/entities/automation/types.js +5 -0
  69. package/dist-sdk/src/entities/automation/workflow-output.d.ts +35 -0
  70. package/dist-sdk/src/entities/automation/workflow-output.js +53 -0
  71. package/dist-sdk/src/entities/chart/build.d.ts +3 -3
  72. package/dist-sdk/src/entities/chart/from-tf.d.ts +2 -2
  73. package/dist-sdk/src/entities/chart/from-tf.js +20 -13
  74. package/dist-sdk/src/entities/chart/to-tf.js +7 -5
  75. package/dist-sdk/src/entities/dashboard/from-tf.js +1 -1
  76. package/dist-sdk/src/entities/dashboard/to-tf.js +1 -0
  77. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +3 -2
  78. package/dist-sdk/src/entities/element/build.d.ts +11 -8
  79. package/dist-sdk/src/entities/element/build.js +14 -5
  80. package/dist-sdk/src/entities/element/locals.d.ts +2 -2
  81. package/dist-sdk/src/entities/element/locals.js +6 -2
  82. package/dist-sdk/src/entities/element/system-fields.d.ts +4 -0
  83. package/dist-sdk/src/entities/element/system-fields.js +12 -0
  84. package/dist-sdk/src/entities/element/to-tf.js +1 -0
  85. package/dist-sdk/src/entities/field/build.d.ts +2 -2
  86. package/dist-sdk/src/entities/field/from-tf.js +82 -4
  87. package/dist-sdk/src/entities/field/to-tf.d.ts +1 -1
  88. package/dist-sdk/src/entities/field/to-tf.js +11 -4
  89. package/dist-sdk/src/entities/record-create-form/from-tf.js +3 -2
  90. package/dist-sdk/src/entities/relationship/from-tf.js +8 -5
  91. package/dist-sdk/src/entities/relationship/to-tf.js +13 -3
  92. package/dist-sdk/src/entities/search-table/from-tf.js +6 -6
  93. package/dist-sdk/src/entities/search-table/module.js +2 -2
  94. package/dist-sdk/src/entities/search-table/types.d.ts +1 -0
  95. package/dist-sdk/src/entities/search-table/types.js +1 -0
  96. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +3 -3
  97. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +10 -6
  98. package/dist-sdk/src/entities/shared/filters/ast.d.ts +4 -2
  99. package/dist-sdk/src/entities/shared/filters/index.d.ts +12 -2
  100. package/dist-sdk/src/entities/shared/filters/index.js +17 -1
  101. package/dist-sdk/src/entities/shared/filters/print.js +25 -11
  102. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +1 -1
  103. package/dist-sdk/src/entities/shared/filters/tf-codec.js +39 -7
  104. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +1 -1
  105. package/dist-sdk/src/entities/shared/tool-field-ref.js +6 -2
  106. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +6 -0
  107. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +47 -18
  108. package/dist-sdk/src/entities/skill/module.js +10 -0
  109. package/dist-sdk/src/entities/skill/to-tf.js +19 -0
  110. package/dist-sdk/src/entities/skill/tools.d.ts +29 -7
  111. package/dist-sdk/src/entities/skill/tools.js +6 -2
  112. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +18 -0
  113. package/dist-sdk/src/entities/skill-tool/from-tf.js +77 -4
  114. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +8 -0
  115. package/dist-sdk/src/entities/skill-tool/to-tf.js +90 -46
  116. package/dist-sdk/src/entities/task/module.js +1 -1
  117. package/dist-sdk/src/entities/view/from-tf.js +30 -9
  118. package/dist-sdk/src/entities/view/to-tf.js +18 -10
  119. package/dist-sdk/src/entities/widget/from-tf.js +3 -3
  120. package/dist-sdk/src/entities/widget/to-tf.js +1 -0
  121. package/dist-sdk/src/graph/index.d.ts +15 -0
  122. package/dist-sdk/src/graph/index.js +19 -0
  123. package/dist-sdk/src/graph/types.d.ts +37 -1
  124. package/package.json +2 -1
@@ -11,9 +11,10 @@ import { UNRESOLVED_FIELD_MARKER } from "../shared/ref.js";
11
11
  import { filterFromTf as deserializeFilterFromTf } from "../shared/filters/tf-codec.js";
12
12
  import { TABLE_RESOURCE_TYPE } from "../table/module.js";
13
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";
14
+ import { outputFieldTypesFromScriptSchema, scriptOutputReferenceIsDeclared } from "./output-field-types.js";
15
+ import { apiTaskRefAuthoringPath, matchesOutputWireKey, OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
16
16
  import { taskTfLabel } from "./task-label.js";
17
+ import { workflowOutputTypeFromFieldType } from "./workflow-output.js";
17
18
  import { ALL_AUTOMATION_TASK_TYPE_SET, AUTOMATION_BRANCH_TYPE_SET, AUTOMATION_RESOURCE_TYPE, AUTOMATION_TRIGGER_TYPE_SET, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
18
19
  const TRIGGER_KINDS = {
19
20
  elementum_record_created_trigger: "recordCreate",
@@ -466,10 +467,10 @@ function aiAgentTaskRefPath(block, name) {
466
467
  * convention.
467
468
  */
468
469
  const WEBHOOK_REF_PATTERN = /^(Body|Headers) \((.+)\)$/;
469
- function aspectOwnerRefNameFromObjectId(objectId, appRefName, appTfLabel, dataBlocks, foreignAppRefNames, foreignElementRefNames) {
470
+ function aspectOwnerRefNameFromObjectId(objectId, appRefName, appTfLabel, dataBlocks, foreignAppRefNames, foreignElementRefNames, foreignTaskRefNames) {
470
471
  if (!isTfExpr(objectId))
471
472
  return undefined;
472
- if (objectId.$expr === "data-attr" && (objectId.type === "elementum_app" || objectId.type === "elementum_element") && objectId.path[0] === "id") {
473
+ if (objectId.$expr === "data-attr" && (objectId.type === "elementum_app" || objectId.type === "elementum_element" || objectId.type === "elementum_task") && objectId.path[0] === "id") {
473
474
  // The data block's own tf label is an arbitrary export alias, not
474
475
  // necessarily the target's real refName (confirmed live: a
475
476
  // `data.elementum_element "approvals_log"` block's real namespace is
@@ -479,12 +480,12 @@ function aspectOwnerRefNameFromObjectId(objectId, appRefName, appTfLabel, dataBl
479
480
  const lookup = dataBlocks.get(`${objectId.type}.${objectId.label}`);
480
481
  const identity = lookup?.attrs.name ?? lookup?.attrs.namespace;
481
482
  const mapped = typeof identity === "string"
482
- ? (objectId.type === "elementum_element" ? foreignElementRefNames : foreignAppRefNames)?.get(identity)
483
+ ? (objectId.type === "elementum_task" ? foreignTaskRefNames : objectId.type === "elementum_element" ? foreignElementRefNames : foreignAppRefNames)?.get(identity)
483
484
  : undefined;
484
485
  return mapped ?? tfLabelToTsLabel(objectId.label);
485
486
  }
486
487
  if (objectId.$expr === "resource-attr" &&
487
- (objectId.type === "elementum_app" || objectId.type === "elementum_element") &&
488
+ (objectId.type === "elementum_app" || objectId.type === "elementum_element" || objectId.type === "elementum_task") &&
488
489
  objectId.path[0] === "id") {
489
490
  return objectId.type === "elementum_app" && objectId.label === appTfLabel
490
491
  ? appRefName
@@ -496,7 +497,7 @@ function aspectRefFromObjectId(objectId, ctx) {
496
497
  if (!isTfExpr(objectId))
497
498
  return undefined;
498
499
  if (objectId.$expr === "resource-attr" &&
499
- (objectId.type === "elementum_app" || objectId.type === "elementum_element") &&
500
+ (objectId.type === "elementum_app" || objectId.type === "elementum_element" || objectId.type === "elementum_task") &&
500
501
  objectId.path[0] === "id") {
501
502
  return {
502
503
  kind: "app",
@@ -504,23 +505,28 @@ function aspectRefFromObjectId(objectId, ctx) {
504
505
  };
505
506
  }
506
507
  if (objectId.$expr !== "data-attr" ||
507
- (objectId.type !== "elementum_app" && objectId.type !== "elementum_element") ||
508
+ (objectId.type !== "elementum_app" && objectId.type !== "elementum_element" && objectId.type !== "elementum_task") ||
508
509
  objectId.path[0] !== "id") {
509
510
  return undefined;
510
511
  }
511
512
  const lookup = ctx.dataBlocks.get(`${objectId.type}.${objectId.label}`);
512
513
  const identity = lookup?.attrs.name ?? lookup?.attrs.namespace;
513
514
  const mapped = typeof identity === "string"
514
- ? (objectId.type === "elementum_element" ? ctx.foreignElementRefNames : ctx.foreignAppRefNames)?.get(identity)
515
+ ? (objectId.type === "elementum_task" ? ctx.foreignTaskRefNames : objectId.type === "elementum_element" ? ctx.foreignElementRefNames : ctx.foreignAppRefNames)?.get(identity)
515
516
  : undefined;
516
- if (mapped !== undefined)
517
- return { kind: "app", appHandle: mapped };
517
+ if (typeof identity === "string" && mapped !== undefined) {
518
+ return {
519
+ kind: "app",
520
+ appHandle: mapped,
521
+ ...(objectId.type === "elementum_task" ? { entityType: "task", name: identity } : objectId.type === "elementum_element" ? { entityType: "element", name: identity } : {}),
522
+ };
523
+ }
518
524
  if (typeof identity !== "string" || identity === "")
519
525
  return undefined;
520
526
  return {
521
527
  kind: "app",
522
528
  appHandle: tfLabelToTsLabel(objectId.label),
523
- entityType: objectId.type === "elementum_element" ? "element" : "app",
529
+ entityType: objectId.type === "elementum_task" ? "task" : objectId.type === "elementum_element" ? "element" : "app",
524
530
  name: identity,
525
531
  };
526
532
  }
@@ -532,6 +538,8 @@ function aspectKindFromObjectId(objectId) {
532
538
  return "app";
533
539
  if (objectId.type === "elementum_element")
534
540
  return "element";
541
+ if (objectId.type === "elementum_task")
542
+ return "task";
535
543
  return undefined;
536
544
  }
537
545
  /**
@@ -798,18 +806,13 @@ function triggerRefPath(path, ctx) {
798
806
  return names;
799
807
  return recordFieldRefPath(wireName, ctx) ?? names;
800
808
  }
801
- /**
802
- * Resolve a forEach `.inner.refs["<display name>"]` key to the public record
803
- * bag key used by `ctx.item`. The provider exposes current-item fields by
804
- * display name (including system fields such as `"ID"`), while the authored
805
- * TypeScript surface uses stable keys (`id`, custom field bag keys, and typed
806
- * suffixes such as `.label`).
807
- */
808
809
  function forEachItemRefPath(path, ctx) {
809
810
  const names = pathNames(path);
810
811
  if (names.length !== 1)
811
812
  return names.flatMap((segment) => segment.split("."));
812
813
  const wireName = names[0];
814
+ if (wireName === "item")
815
+ return [];
813
816
  if (wireName === "Record")
814
817
  return ["recordId"];
815
818
  const wireNameLower = wireName.toLowerCase();
@@ -979,7 +982,7 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
979
982
  const keyPath = pathSegments.map((segment) => WIRE_REF_SEGMENT_TO_TS[segment] ?? segment);
980
983
  const taskKind = block?.type !== undefined ? TASK_FACTORIES[block.type] : undefined;
981
984
  const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
982
- const outputKeyPath = wireOutputKey !== undefined && keyPath[0] === wireOutputKey
985
+ const outputKeyPath = wireOutputKey !== undefined && keyPath[0] !== undefined && matchesOutputWireKey(keyPath[0], wireOutputKey)
983
986
  ? ["output", ...keyPath.slice(1)]
984
987
  : keyPath;
985
988
  return { kind: "taskRef", task: refKey, path: outputKeyPath };
@@ -1086,6 +1089,28 @@ function decodeTemplateTaskRef(value, ctx) {
1086
1089
  return undefined;
1087
1090
  return decodeTaskReferenceFromString(task.refKey, nameParts, ctx);
1088
1091
  }
1092
+ function decodeTemplateForEachRef(value, ctx) {
1093
+ if (!isTfExpr(value) || value.$expr !== "template")
1094
+ return undefined;
1095
+ const [prefix, idPart, suffixPart] = value.parts;
1096
+ if (prefix !== "for_each." || idPart === undefined || typeof idPart === "string")
1097
+ return undefined;
1098
+ if (typeof suffixPart !== "string" || !suffixPart.startsWith("."))
1099
+ return undefined;
1100
+ if (!isTfExpr(idPart) || idPart.$expr !== "resource-attr" || idPart.path[0] !== "id")
1101
+ return undefined;
1102
+ const task = ctx.taskByAddress.get(`${idPart.type}.${idPart.label}`);
1103
+ if (task === undefined)
1104
+ return undefined;
1105
+ const nameParts = suffixPart.slice(1).split(".").filter((segment) => segment.length > 0);
1106
+ if (nameParts.length === 0)
1107
+ return undefined;
1108
+ return {
1109
+ kind: "forEachItemRef",
1110
+ forEachTask: task.refKey,
1111
+ path: forEachItemRefPath(nameParts, ctx),
1112
+ };
1113
+ }
1089
1114
  /**
1090
1115
  * Resolve the field-id expression at the middle of a `trigger.record.<id>[.suffix]`
1091
1116
  * template. A custom field's id is a `resource-attr` (`elementum_x_field.<label>.id`);
@@ -1343,7 +1368,7 @@ function decodeValue(value, ctx) {
1343
1368
  // the generic `output` accessor its EDK factory actually exposes.
1344
1369
  const taskKind = task.block.type !== undefined ? TASK_FACTORIES[task.block.type] : undefined;
1345
1370
  const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
1346
- const outputKeyPath = wireOutputKey !== undefined && keyPath[0] === wireOutputKey
1371
+ const outputKeyPath = wireOutputKey !== undefined && keyPath[0] !== undefined && matchesOutputWireKey(keyPath[0], wireOutputKey)
1347
1372
  ? ["output", ...keyPath.slice(1)]
1348
1373
  : keyPath;
1349
1374
  return { kind: "taskRef", task: task.refKey, path: outputKeyPath };
@@ -1466,16 +1491,16 @@ function decodeValue(value, ctx) {
1466
1491
  if (value.$expr === "data-attr" && value.type === "elementum_search_table" && value.path[0] === "id") {
1467
1492
  return decodeSearchTableReference(value, ctx);
1468
1493
  }
1469
- if (value.$expr === "data-attr" && (value.type === "elementum_app" || value.type === "elementum_element") && value.path[0] === "id") {
1494
+ if (value.$expr === "data-attr" && (value.type === "elementum_app" || value.type === "elementum_element" || value.type === "elementum_task") && value.path[0] === "id") {
1470
1495
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1471
1496
  const name = lookup?.attrs.name ?? lookup?.attrs.namespace;
1472
1497
  const mappedHandle = typeof name === "string"
1473
- ? (value.type === "elementum_element" ? ctx.foreignElementRefNames : ctx.foreignAppRefNames)?.get(name)
1498
+ ? (value.type === "elementum_task" ? ctx.foreignTaskRefNames : value.type === "elementum_element" ? ctx.foreignElementRefNames : ctx.foreignAppRefNames)?.get(name)
1474
1499
  : undefined;
1475
1500
  return {
1476
1501
  kind: "app",
1477
1502
  appHandle: mappedHandle ?? tfLabelToTsLabel(value.label),
1478
- entityType: value.type === "elementum_element" ? "element" : "app",
1503
+ entityType: value.type === "elementum_task" ? "task" : value.type === "elementum_element" ? "element" : "app",
1479
1504
  ...(typeof name === "string" ? { name } : {}),
1480
1505
  };
1481
1506
  }
@@ -1508,10 +1533,13 @@ function decodeValue(value, ctx) {
1508
1533
  // the owner's `data.elementum_app`/`data.elementum_element` lookup.
1509
1534
  const fieldBlock = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1510
1535
  const objectId = fieldBlock?.attrs["object_id"];
1511
- if (objectId === undefined || !isTfExpr(objectId) || objectId.$expr !== "data-attr" || (objectId.type !== "elementum_app" && objectId.type !== "elementum_element")) {
1512
- throw new EntityTfError(`data.elementum_field.${value.label}: object_id is not a resolvable app/element data reference`);
1536
+ if (objectId === undefined ||
1537
+ !isTfExpr(objectId) ||
1538
+ objectId.$expr !== "data-attr" ||
1539
+ (objectId.type !== "elementum_app" && objectId.type !== "elementum_element" && objectId.type !== "elementum_task")) {
1540
+ throw new EntityTfError(`data.elementum_field.${value.label}: object_id is not a resolvable app/element/task data reference`);
1513
1541
  }
1514
- const entityType = objectId.type === "elementum_element" ? "element" : "app";
1542
+ const entityType = objectId.type === "elementum_task" ? "task" : objectId.type === "elementum_element" ? "element" : "app";
1515
1543
  const ownerLabel = objectId.label;
1516
1544
  const kindPrefix = `${entityType}_${ownerLabel}_`;
1517
1545
  const elementumKindPrefix = `elementum_${kindPrefix}`;
@@ -1682,8 +1710,24 @@ function decodeCustomResponse(value, ctx) {
1682
1710
  function fieldRef(value, ctx) {
1683
1711
  if (isTfExpr(value) && value.$expr === "data-attr" && value.path.join(".") === "id") {
1684
1712
  const foreign = ctx.foreignFieldRefsByDataAddress?.get(`${value.type}.${value.label}`);
1685
- if (foreign !== undefined)
1686
- return { kind: "field", appHandle: foreign.ownerRefName, fieldKey: foreign.fieldKey };
1713
+ if (foreign !== undefined) {
1714
+ return {
1715
+ kind: "field",
1716
+ appHandle: foreign.ownerRefName,
1717
+ fieldKey: foreign.fieldKey,
1718
+ ...(foreign.ownerKind !== undefined || foreign.fieldName !== undefined || foreign.fieldType !== undefined
1719
+ ? {
1720
+ foreign: {
1721
+ entityType: foreign.ownerKind ?? "app",
1722
+ name: foreign.ownerName ?? foreign.ownerRefName,
1723
+ ...(foreign.ownerNamespace !== undefined ? { namespace: foreign.ownerNamespace } : {}),
1724
+ ...(foreign.fieldName !== undefined ? { fieldName: foreign.fieldName } : {}),
1725
+ ...(foreign.fieldType !== undefined ? { fieldType: foreign.fieldType } : {}),
1726
+ },
1727
+ }
1728
+ : {}),
1729
+ };
1730
+ }
1687
1731
  }
1688
1732
  const decoded = decodeValue(value, ctx);
1689
1733
  if (isObject(decoded) && decoded.kind === "field")
@@ -1691,7 +1735,21 @@ function fieldRef(value, ctx) {
1691
1735
  if (typeof value === "string") {
1692
1736
  const foreign = ctx.foreignFieldRefsById?.get(value);
1693
1737
  if (foreign !== undefined) {
1694
- return { kind: "field", appHandle: foreign.ownerRefName, fieldKey: foreign.fieldKey };
1738
+ return {
1739
+ kind: "field",
1740
+ appHandle: foreign.ownerRefName,
1741
+ fieldKey: foreign.fieldKey,
1742
+ ...(foreign.fieldName !== undefined || foreign.fieldType !== undefined
1743
+ ? {
1744
+ foreign: {
1745
+ entityType: "app",
1746
+ name: foreign.ownerRefName,
1747
+ ...(foreign.fieldName !== undefined ? { fieldName: foreign.fieldName } : {}),
1748
+ ...(foreign.fieldType !== undefined ? { fieldType: foreign.fieldType } : {}),
1749
+ },
1750
+ }
1751
+ : {}),
1752
+ };
1695
1753
  }
1696
1754
  return { kind: "unresolved", uuid: value, hint: "field" };
1697
1755
  }
@@ -1772,14 +1830,26 @@ function decodeCalculationFormula(value, ctx) {
1772
1830
  const parts = [];
1773
1831
  let cursor = 0;
1774
1832
  const pattern = /\{\{(trigger|task)\s+([^}]*)\}\}|variable\.([a-f0-9-]{36})/g;
1775
- for (const match of value.matchAll(pattern)) {
1776
- const index = match.index ?? 0;
1833
+ while (cursor < value.length) {
1834
+ pattern.lastIndex = cursor;
1835
+ const match = pattern.exec(value);
1836
+ const jsonRef = nextCalculationJsonReference(value, cursor, ctx);
1837
+ const matchIndex = match?.index ?? Number.POSITIVE_INFINITY;
1838
+ const jsonIndex = jsonRef?.start ?? Number.POSITIVE_INFINITY;
1839
+ if (match === null && jsonRef === undefined)
1840
+ break;
1841
+ const index = Math.min(matchIndex, jsonIndex);
1777
1842
  if (index > cursor)
1778
1843
  parts.push(value.slice(cursor, index));
1844
+ if (jsonIndex < matchIndex) {
1845
+ parts.push(jsonRef.reference);
1846
+ cursor = jsonRef.end;
1847
+ continue;
1848
+ }
1779
1849
  if (match[3] !== undefined) {
1780
1850
  const resolved = resolveVariableReference(match[3], match[3], undefined, ctx);
1781
- parts.push(resolved ?? { kind: "unresolved", uuid: `variable.${match[3]}`, hint: "variable" });
1782
- cursor = index + match[0].length;
1851
+ parts.push(resolved ?? { kind: "unresolved", uuid: `variable.${match[3]}`, hint: "calculation-reference" });
1852
+ cursor = pattern.lastIndex;
1783
1853
  continue;
1784
1854
  }
1785
1855
  const kind = match[1];
@@ -1794,7 +1864,7 @@ function decodeCalculationFormula(value, ctx) {
1794
1864
  const id = /id="([^"]*)"/.exec(attrs)?.[1];
1795
1865
  parts.push(decodeCalculationTaskMustache(id, name, ctx));
1796
1866
  }
1797
- cursor = index + match[0].length;
1867
+ cursor = pattern.lastIndex;
1798
1868
  }
1799
1869
  if (parts.length === 0)
1800
1870
  return { kind: "literal", value };
@@ -1804,6 +1874,57 @@ function decodeCalculationFormula(value, ctx) {
1804
1874
  return parts[0];
1805
1875
  return { kind: "template", parts };
1806
1876
  }
1877
+ /** Resolve serialized platform ValueReference envelopes embedded in formula text. */
1878
+ function nextCalculationJsonReference(value, fromIndex, ctx) {
1879
+ for (let start = value.indexOf("{", fromIndex); start >= 0; start = value.indexOf("{", start + 1)) {
1880
+ let depth = 0;
1881
+ let inString = false;
1882
+ let escaped = false;
1883
+ let end = start;
1884
+ for (; end < value.length; end += 1) {
1885
+ const char = value[end];
1886
+ if (inString) {
1887
+ if (escaped)
1888
+ escaped = false;
1889
+ else if (char === "\\")
1890
+ escaped = true;
1891
+ else if (char === '"')
1892
+ inString = false;
1893
+ continue;
1894
+ }
1895
+ if (char === '"')
1896
+ inString = true;
1897
+ else if (char === "{")
1898
+ depth += 1;
1899
+ else if (char === "}") {
1900
+ depth -= 1;
1901
+ if (depth === 0) {
1902
+ end += 1;
1903
+ break;
1904
+ }
1905
+ }
1906
+ }
1907
+ if (depth !== 0)
1908
+ continue;
1909
+ let parsed;
1910
+ try {
1911
+ parsed = JSON.parse(value.slice(start, end));
1912
+ }
1913
+ catch {
1914
+ continue;
1915
+ }
1916
+ if (!isObject(parsed))
1917
+ continue;
1918
+ // Calculation formulas also serialize variable/task refs as JSON. Reuse
1919
+ // the same decoder as workflow values so synthetic names such as
1920
+ // `variable|<uuid>` are resolved from the task graph rather than copied
1921
+ // into the generated TypeScript source.
1922
+ const reference = decodeFilterReferenceEnvelope(parsed, ctx);
1923
+ if (reference !== undefined)
1924
+ return { start, end, reference };
1925
+ }
1926
+ return undefined;
1927
+ }
1807
1928
  function decodeCalculationTaskMustache(taskId, wireName, ctx) {
1808
1929
  if (taskId === undefined || wireName === undefined) {
1809
1930
  return { kind: "unresolved", uuid: `task:${taskId ?? "?"}:${wireName ?? "?"}`, hint: "calculation-reference" };
@@ -1869,6 +1990,15 @@ function decodeCalculationTaskMustache(taskId, wireName, ctx) {
1869
1990
  const keyPath = wireName.split(".");
1870
1991
  const taskKind = taskBlock?.type !== undefined ? TASK_FACTORIES[taskBlock.type] : undefined;
1871
1992
  const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
1993
+ // Case-SENSITIVE here, unlike the refs-map/envelope call sites: a
1994
+ // calculation mustache carries the calc-engine's own lowercase name
1995
+ // (WorkflowTaskReference, e.g. "response"), never the refs-map display
1996
+ // key ("Response") - calculationTaskMustache already documents that the
1997
+ // display label does not resolve in this dialect. Case-folding this site
1998
+ // too made "response" fold to "output" (correct) but ALSO folded any
1999
+ // other lowercase wire name that happens to match a wireOutputKey
2000
+ // case-insensitively, rewriting the mustache as {{task name="Response"}}
2001
+ // on the next build - a key the calc engine's real API never has either.
1872
2002
  const outputKeyPath = wireOutputKey !== undefined && keyPath[0] === wireOutputKey
1873
2003
  ? ["output", ...keyPath.slice(1)]
1874
2004
  : keyPath.map((segment) => WIRE_REF_SEGMENT_TO_TS[segment] ?? segment);
@@ -1952,7 +2082,7 @@ function resolveVariableReference(rawId, rawName, outputName, ctx) {
1952
2082
  }
1953
2083
  return undefined;
1954
2084
  }
1955
- function decodeFilterReferenceEnvelope(value, ctx, outputName) {
2085
+ function decodeFilterReferenceEnvelope(value, ctx, outputName, role) {
1956
2086
  let raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
1957
2087
  while (isObject(raw) && "value" in raw && Object.keys(raw).length === 1) {
1958
2088
  raw = raw.value;
@@ -1963,7 +2093,24 @@ function decodeFilterReferenceEnvelope(value, ctx, outputName) {
1963
2093
  if (isObject(taskRef) && typeof taskRef.name === "string") {
1964
2094
  const taskIdOrKey = workflowOutputTaskIdOrKey(taskRef.taskId, ctx);
1965
2095
  if (taskIdOrKey !== undefined) {
1966
- return decodeTaskReferenceFromString(taskIdOrKey, taskRef.name.split("."), ctx);
2096
+ const decoded = decodeTaskReferenceFromString(taskIdOrKey, taskRef.name.split("."), ctx);
2097
+ const task = resolveTaskRefKey(taskIdOrKey, ctx).block;
2098
+ if (decoded.kind === "taskRef" && task?.type === "elementum_execute_script_task") {
2099
+ const schemaValue = task.attrs.output_schema;
2100
+ const schema = isTfExpr(schemaValue) && schemaValue.$expr === "jsonencode"
2101
+ ? schemaValue.value
2102
+ : schemaValue;
2103
+ const outputTypes = outputFieldTypesFromScriptSchema(schema);
2104
+ const declared = scriptOutputReferenceIsDeclared(outputTypes, taskRef.name);
2105
+ if (role === "left" && !declared && taskRef.name.startsWith("result.")) {
2106
+ if (raw.multiple === true || raw.fieldType === "DECIMAL") {
2107
+ throw new EntityTfError(`execute-script reference "${taskRef.name}" is absent from its output schema and its ` +
2108
+ `${raw.multiple === true ? "multiple" : "DECIMAL"} envelope cannot round-trip losslessly`);
2109
+ }
2110
+ return { ...decoded, undeclaredScriptOutput: true };
2111
+ }
2112
+ }
2113
+ return decoded;
1967
2114
  }
1968
2115
  }
1969
2116
  const triggerRef = raw.triggerReference;
@@ -2009,12 +2156,13 @@ function workflowOutputTaskIdOrKey(taskId, ctx) {
2009
2156
  }
2010
2157
  return undefined;
2011
2158
  }
2012
- function filterReference(value, ctx) {
2159
+ function filterReference(value, ctx, role) {
2013
2160
  return typeof value === "string"
2014
2161
  ? decodeReferenceString(value, ctx) ?? { kind: "unresolved", uuid: value, hint: "filter-reference" }
2015
- : decodeFilterReferenceEnvelope(value, ctx)
2162
+ : decodeFilterReferenceEnvelope(value, ctx, undefined, role)
2016
2163
  ?? decodeTemplateTriggerRecordFieldRef(value, ctx)
2017
2164
  ?? decodeTemplateTaskRef(value, ctx)
2165
+ ?? decodeTemplateForEachRef(value, ctx)
2018
2166
  ?? decodeValue(value, ctx);
2019
2167
  }
2020
2168
  function filterReferenceType(value, fallback, ctx) {
@@ -2037,13 +2185,54 @@ function filterReferenceType(value, fallback, ctx) {
2037
2185
  }
2038
2186
  return typeof raw.fieldType === "string" ? fieldTypeToValueType(raw.fieldType) : fallback;
2039
2187
  }
2188
+ export function inferredPublishOutputType(value, ctx) {
2189
+ const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
2190
+ if (!isObject(raw) || !isObject(raw.taskReference) || typeof raw.taskReference.name !== "string") {
2191
+ return { fieldType: "TEXT", multiple: false };
2192
+ }
2193
+ const taskIdOrKey = workflowOutputTaskIdOrKey(raw.taskReference.taskId, ctx);
2194
+ const task = taskIdOrKey === undefined ? undefined : resolveTaskRefKey(taskIdOrKey, ctx).block;
2195
+ if (task?.type === "elementum_execute_script_task") {
2196
+ const schemaValue = task.attrs.output_schema;
2197
+ const schema = isTfExpr(schemaValue) && schemaValue.$expr === "jsonencode"
2198
+ ? schemaValue.value
2199
+ : schemaValue;
2200
+ const fromSchema = outputFieldTypesFromScriptSchema(schema)?.get(raw.taskReference.name);
2201
+ if (fromSchema !== undefined)
2202
+ return fromSchema;
2203
+ }
2204
+ if (task?.type === "elementum_ai_agent_task" &&
2205
+ typeof task.attrs.output_type === "string" &&
2206
+ task.attrs.output_type.toLowerCase() === "json" &&
2207
+ Array.isArray(task.attrs.json_fields)) {
2208
+ const name = raw.taskReference.name.replace(/^ai_agent_task_structured_output\./, "");
2209
+ const field = task.attrs.json_fields.find((candidate) => isObject(candidate) && candidate.name === name && typeof candidate.type === "string");
2210
+ if (isObject(field) && typeof field.type === "string") {
2211
+ return { fieldType: field.type.toUpperCase(), multiple: false };
2212
+ }
2213
+ }
2214
+ if ((task?.type === "elementum_create_record_task" || task?.type === "elementum_find_related_records_task") &&
2215
+ (raw.taskReference.name === "Record" || raw.taskReference.name === "Record ID")) {
2216
+ return { fieldType: "ASPECT_RECORD_ID", multiple: false };
2217
+ }
2218
+ if ((task?.type === "elementum_record_search_task" || task?.type === "elementum_find_related_records_task") &&
2219
+ (raw.taskReference.name === "All found records" || raw.taskReference.name === "records")) {
2220
+ return { fieldType: "ASPECT_RECORD_ID", multiple: true };
2221
+ }
2222
+ if ((task?.type === "elementum_ai_search_table_task" || task?.type === "elementum_table_records_search_task") &&
2223
+ (raw.taskReference.name === "All Records" || raw.taskReference.name === "records" ||
2224
+ raw.taskReference.name === "All matching table rows")) {
2225
+ return { fieldType: "TABLE_RECORD", multiple: true };
2226
+ }
2227
+ return { fieldType: "TEXT", multiple: false };
2228
+ }
2040
2229
  function decodeFilter(value, ctx, fieldScope = "app") {
2041
2230
  return deserializeFilterFromTf(value, {
2042
2231
  field: (fieldValue, scope) => {
2043
2232
  const field = scope === "user" ? userFieldRef(fieldValue, ctx) : filterFieldRef(fieldValue, ctx);
2044
2233
  return field ?? { kind: "unresolved", uuid: String(fieldValue), hint: "field" };
2045
2234
  },
2046
- reference: (reference) => filterReference(reference, ctx),
2235
+ reference: (reference, role) => filterReference(reference, ctx, role),
2047
2236
  referenceType: (reference, fallback) => filterReferenceType(reference, fallback, ctx),
2048
2237
  literal: (literal) => picklistOptionLabel(literal) ?? stageFilterName(literal, ctx) ?? literal,
2049
2238
  }, fieldScope);
@@ -2183,7 +2372,7 @@ function triggerFromBlock(block, ctx) {
2183
2372
  default: throw new EntityTfError(`trigger "${kind}" is outside the Terraform contract`);
2184
2373
  }
2185
2374
  }
2186
- function taskArgs(block, factory, ctx) {
2375
+ function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2187
2376
  const args = {};
2188
2377
  for (const [attr, value] of Object.entries(block.attrs)) {
2189
2378
  if (attr === "parent" || attr === "name" || attr === "depends_on")
@@ -2211,8 +2400,21 @@ function taskArgs(block, factory, ctx) {
2211
2400
  ? field.fieldKey
2212
2401
  : `${UNRESOLVED_FIELD_MARKER}${field.uuid}`;
2213
2402
  const decodedValue = decodeFieldAssignmentValue(item.value, ctx);
2214
- values[fieldKey] = item.update_mode === "add"
2215
- ? { __fieldAssignment: true, value: decodedValue, updateMode: "add" }
2403
+ const foreignInfo = field.kind === "field" && field.foreign !== undefined
2404
+ ? {
2405
+ foreignFieldName: field.foreign.fieldName,
2406
+ foreignEntityType: field.foreign.entityType,
2407
+ foreignOwnerName: field.foreign.name,
2408
+ ...(field.foreign.fieldType !== undefined ? { foreignFieldType: field.foreign.fieldType } : {}),
2409
+ }
2410
+ : undefined;
2411
+ values[fieldKey] = item.update_mode === "add" || foreignInfo !== undefined
2412
+ ? {
2413
+ __fieldAssignment: true,
2414
+ value: decodedValue,
2415
+ ...(item.update_mode === "add" ? { updateMode: "add" } : {}),
2416
+ ...(foreignInfo !== undefined ? foreignInfo : {}),
2417
+ }
2216
2418
  : decodedValue;
2217
2419
  }
2218
2420
  args.values = values;
@@ -2224,7 +2426,40 @@ function taskArgs(block, factory, ctx) {
2224
2426
  args.inputs = Object.fromEntries(value.map((item) => {
2225
2427
  if (!isObject(item) || typeof item.name !== "string")
2226
2428
  throw new EntityTfError("invalid script input");
2227
- return [item.name, decodeValue(item.value, ctx)];
2429
+ const decodedValue = decodeValue(item.value, ctx);
2430
+ const rawMappings = item.field_mappings;
2431
+ // A list-valued input's field_mappings - which fields of each list
2432
+ // item the script can read, and under what alias. Kept as a tagged
2433
+ // wrapper the printer turns into withFieldMappings(...); to-tf.ts's
2434
+ // own withFieldMappings() re-derives the exact same wire shape on
2435
+ // rebuild.
2436
+ if (Array.isArray(rawMappings) && rawMappings.length > 0) {
2437
+ const fields = [];
2438
+ for (const mapping of rawMappings) {
2439
+ if (!isObject(mapping) || typeof mapping.alias !== "string") {
2440
+ throw new EntityTfError("invalid script input field_mappings entry");
2441
+ }
2442
+ // ei's exporter (generateScriptInputsIR) keeps the alias but omits
2443
+ // field_id when the mapping's field id is empty on the platform -
2444
+ // drop just this one mapping with a diagnostic instead of
2445
+ // throwing out of taskArgs, which would drop the WHOLE automation
2446
+ // (a live-caught regression in an earlier attempt at this fix).
2447
+ if (mapping.field_id === undefined) {
2448
+ fieldMappingDiagnostics.push(`execute-script input "${item.name}" field_mappings entry ${JSON.stringify(mapping.alias)}: no field_id on the platform; dropped`);
2449
+ continue;
2450
+ }
2451
+ // A PRESENT but unreconstructable field_id (fieldRef throws) is
2452
+ // different: the export genuinely carried a binding EDK failed to
2453
+ // decode. Fail closed (propagate) rather than silently stripping
2454
+ // a real reference - matches fieldRef's own fail-closed contract
2455
+ // used elsewhere in this file.
2456
+ fields.push({ alias: mapping.alias, field: fieldRef(mapping.field_id, ctx) });
2457
+ }
2458
+ if (fields.length > 0) {
2459
+ return [item.name, { __edkExecuteScriptListInput: true, value: decodedValue, fields }];
2460
+ }
2461
+ }
2462
+ return [item.name, decodedValue];
2228
2463
  }));
2229
2464
  continue;
2230
2465
  }
@@ -2239,7 +2474,15 @@ function taskArgs(block, factory, ctx) {
2239
2474
  if (type === undefined || !isObject(definition))
2240
2475
  throw new EntityTfError("invalid script output property");
2241
2476
  if (type === "array") {
2242
- return { type: "array", items: decodeNode(definition.item) };
2477
+ const itemDefinition = isObject(definition.item) ? Object.values(definition.item)[0] : undefined;
2478
+ const itemName = isObject(itemDefinition) && typeof itemDefinition.name === "string"
2479
+ ? itemDefinition.name
2480
+ : undefined;
2481
+ return {
2482
+ type: "array",
2483
+ items: decodeNode(definition.item),
2484
+ ...(itemName !== undefined ? { itemName } : {}),
2485
+ };
2243
2486
  }
2244
2487
  if (type === "object" && Array.isArray(definition.properties)) {
2245
2488
  const properties = Object.fromEntries(definition.properties.map((child) => {
@@ -2343,13 +2586,9 @@ function taskArgs(block, factory, ctx) {
2343
2586
  : item.include_type === "PICKLIST" && item.picklist_field_id !== undefined
2344
2587
  ? { picklist: fieldRef(item.picklist_field_id, ctx) ?? decodeValue(item.picklist_field_id, ctx) }
2345
2588
  : undefined;
2346
- if (item.id !== undefined && typeof item.id !== "string") {
2347
- throw new EntityTfError(`${block.type}.${block.label}: calculation entry id must be a string`);
2348
- }
2349
- const advanced = item.id !== undefined || item.record_id !== undefined || include !== undefined;
2589
+ const advanced = item.record_id !== undefined || include !== undefined;
2350
2590
  return [item.variable_name, advanced ? {
2351
2591
  expression,
2352
- ...(typeof item.id === "string" ? { id: item.id } : {}),
2353
2592
  ...(item.record_id !== undefined ? { record: decodeValue(item.record_id, ctx) } : {}),
2354
2593
  ...(include !== undefined ? { include } : {}),
2355
2594
  } : expression];
@@ -2758,10 +2997,12 @@ function taskRefKey(block, automationLabel, appTfLabel) {
2758
2997
  * shows those addresses as destroy-on-apply (confirmed live: several
2759
2998
  * automations that failed extraction were imported into state anyway,
2760
2999
  * driving spurious destroys). Deliberately lenient - tolerant of the exact
2761
- * conditions that make real extraction fail (zero/multiple triggers, an
2762
- * unrecognized task kind) - so it over-collects rather than under-collects:
2763
- * a false positive here just leaves one more resource unmanaged, a false
2764
- * negative would silently destroy a live automation on apply.
3000
+ * conditions that make real extraction fail (zero triggers, an
3001
+ * unrecognized task kind) so it over-collects rather than under-collects.
3002
+ * More than one trigger is not one of those cases: it throws
3003
+ * {@link UnsupportedMultiTriggerError} and stops the pull. A false positive
3004
+ * here just leaves one more resource unmanaged; a false negative would
3005
+ * silently destroy a live automation on apply.
2765
3006
  */
2766
3007
  export function automationOwnedAddresses(doc, automationLabel) {
2767
3008
  const owned = new Set([`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`]);
@@ -2837,16 +3078,40 @@ function unresolvedAuthoringValues(doc) {
2837
3078
  }
2838
3079
  return values;
2839
3080
  }
3081
+ /**
3082
+ * Pull stops on this. EDK does not author multi-trigger automations; apps
3083
+ * should keep one trigger and call the shared logic with a run-automation
3084
+ * action. Callers that otherwise turn extract failures into skips must
3085
+ * rethrow it.
3086
+ */
3087
+ export class UnsupportedMultiTriggerError extends EntityTfError {
3088
+ automationName;
3089
+ triggerCount;
3090
+ constructor(automationName, triggerCount) {
3091
+ super(`EDK does not support multi-trigger automations. Automation "${automationName}" has ${triggerCount} triggers. ` +
3092
+ "Change the automation to a single trigger and use a run-automation action to invoke the shared logic from other entry points.");
3093
+ this.name = "UnsupportedMultiTriggerError";
3094
+ this.automationName = automationName;
3095
+ this.triggerCount = triggerCount;
3096
+ }
3097
+ }
2840
3098
  /** Extract one app-owned automation graph from an ei app export. */
2841
- function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames, procedureKeysByDiscriminator) {
3099
+ function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames, procedureKeysByDiscriminator, foreignTaskRefNames) {
2842
3100
  const automation = doc.blocks.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE && block.label === automationLabel);
2843
3101
  if (automation === undefined)
2844
3102
  throw new EntityTfError(`automation resource "${automationLabel}" not found`);
3103
+ const triggers = doc.blocks.filter((block) => block.kind === "resource" && AUTOMATION_TRIGGER_TYPE_SET.has(block.type ?? "") && references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel));
3104
+ // N > 1 is a product non-support, not a skippable extract gap. Fail before
3105
+ // later structural checks (owner reference, unknown children, missing
3106
+ // trigger) so a multi-trigger automation cannot be swallowed as a diagnostic.
3107
+ if (triggers.length > 1) {
3108
+ const name = typeof automation.attrs.name === "string" && automation.attrs.name !== "" ? automation.attrs.name : automationLabel;
3109
+ throw new UnsupportedMultiTriggerError(name, triggers.length);
3110
+ }
2845
3111
  assertAllowed(automation, new Set(["app_id", "name", "description", "status", "triggers_other_automations", "service_account_id", "depends_on"]));
2846
3112
  const app = resourceRef(automation.attrs.app_id);
2847
3113
  if (app === undefined || app.type !== "elementum_app" || app.path[0] !== "id")
2848
3114
  throw new EntityTfError(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}: app_id is not an app reference`);
2849
- const triggers = doc.blocks.filter((block) => block.kind === "resource" && AUTOMATION_TRIGGER_TYPE_SET.has(block.type ?? "") && references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel));
2850
3115
  const publish = doc.blocks.find((block) => block.kind === "resource" && block.type === WORKFLOW_PUBLISH_RESOURCE_TYPE && references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel));
2851
3116
  const unknownDirectChild = doc.blocks.find((block) => block.kind === "resource" &&
2852
3117
  references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel) &&
@@ -2973,7 +3238,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
2973
3238
  const taskTargetOwnerRefNameByAddress = new Map();
2974
3239
  const taskTargetOwnerKindByAddress = new Map();
2975
3240
  for (const [address, { block }] of taskByAddress) {
2976
- const ownerRefName = aspectOwnerRefNameFromObjectId(block.attrs.object_id, appRefName, appTfLabel, dataBlocks, foreignAppRefNames, foreignElementRefNames);
3241
+ const ownerRefName = aspectOwnerRefNameFromObjectId(block.attrs.object_id, appRefName, appTfLabel, dataBlocks, foreignAppRefNames, foreignElementRefNames, foreignTaskRefNames);
2977
3242
  if (ownerRefName !== undefined)
2978
3243
  taskTargetOwnerRefNameByAddress.set(address, ownerRefName);
2979
3244
  const ownerKind = aspectKindFromObjectId(block.attrs.object_id);
@@ -3029,6 +3294,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3029
3294
  ...(taskTargetOwnerKindByAddress.size > 0 && { taskTargetOwnerKindByAddress }),
3030
3295
  ...(foreignAppRefNames !== undefined && { foreignAppRefNames }),
3031
3296
  ...(foreignElementRefNames !== undefined && { foreignElementRefNames }),
3297
+ ...(foreignTaskRefNames !== undefined && { foreignTaskRefNames }),
3032
3298
  ...(procedureKeysByDiscriminator !== undefined && { procedureKeysByDiscriminator }),
3033
3299
  };
3034
3300
  let serviceAccountName;
@@ -3056,6 +3322,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3056
3322
  dependencyOrder.set(`${ref.type}.${ref.label}`, index); });
3057
3323
  const triggerAddress = `${trigger.type}.${trigger.label}`;
3058
3324
  const unrebuildableTasks = [];
3325
+ const fieldMappingDiagnostics = [];
3059
3326
  // edk#821: resolve each elementum_unmanaged_task_reference this automation's
3060
3327
  // OWN tasks actually parent onto (never the whole doc's data blocks - a
3061
3328
  // sibling automation sharing this export can have its own, edk#785) to its
@@ -3159,7 +3426,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3159
3426
  id: typeof block.attrs.id === "string" ? block.attrs.id : "",
3160
3427
  taskType: typeof block.attrs.task_type === "string" ? block.attrs.task_type : "",
3161
3428
  }
3162
- : taskArgs(block, factory, ctx);
3429
+ : taskArgs(block, factory, ctx, fieldMappingDiagnostics);
3163
3430
  const call = { factory, refKey, args, ...(children ? { children } : {}), ...(typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {}), ...(hclParent !== undefined ? { hclParent } : {}) };
3164
3431
  visiting.delete(address);
3165
3432
  return [call, ...buildTasks(address)];
@@ -3168,6 +3435,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3168
3435
  if (visited.size !== tasks.length + unmanagedTaskPositions.size)
3169
3436
  throw new EntityTfError(`automation "${automationLabel}" contains an orphaned task graph`);
3170
3437
  const outputBlocks = publish?.attrs.outputs;
3438
+ const outputDiagnostics = [];
3171
3439
  const outputs = Array.isArray(outputBlocks) ? outputBlocks.map((output) => {
3172
3440
  if (!isObject(output) || typeof output.name !== "string" || output.value === undefined)
3173
3441
  throw new EntityTfError("invalid workflow output");
@@ -3175,7 +3443,32 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3175
3443
  // collapse that envelope to a RefExpr the same way filter references do.
3176
3444
  const value = decodeFilterReferenceEnvelope(output.value, ctx, output.name)
3177
3445
  ?? decodeValue(output.value, ctx);
3178
- return { name: output.name, value };
3446
+ const raw = isTfExpr(output.value) && output.value.$expr === "jsonencode"
3447
+ ? output.value.value
3448
+ : output.value;
3449
+ const fieldType = isObject(raw) && typeof raw.fieldType === "string" ? raw.fieldType : undefined;
3450
+ const multiple = isObject(raw) && typeof raw.multiple === "boolean" ? raw.multiple : undefined;
3451
+ if (fieldType === undefined || multiple === undefined)
3452
+ return { name: output.name, value };
3453
+ const inferred = inferredPublishOutputType(output.value, ctx);
3454
+ if (inferred.fieldType === fieldType && inferred.multiple === multiple) {
3455
+ return { name: output.name, value };
3456
+ }
3457
+ const explicitType = workflowOutputTypeFromFieldType(fieldType);
3458
+ if (explicitType === undefined) {
3459
+ outputDiagnostics.push(`automation "${automationLabel}" workflow output "${output.name}" has explicit field type ` +
3460
+ `${JSON.stringify(fieldType)}, which the public workflowOutput API cannot represent; ` +
3461
+ `type metadata will be dropped while preserving the bare reference`);
3462
+ return { name: output.name, value };
3463
+ }
3464
+ if (!isObject(value) ||
3465
+ (value.kind !== "taskRef" && value.kind !== "triggerRef")) {
3466
+ outputDiagnostics.push(`automation "${automationLabel}" workflow output "${output.name}" has explicit ${fieldType}/` +
3467
+ `${multiple ? "multiple" : "single"} metadata on a reference kind workflowOutput cannot represent; ` +
3468
+ `type metadata will be dropped while preserving the bare reference`);
3469
+ return { name: output.name, value };
3470
+ }
3471
+ return { name: output.name, value, explicitType, explicitMultiple: multiple };
3179
3472
  }) : undefined;
3180
3473
  const exportedRevision = publish?.attrs.workflow_revision;
3181
3474
  if (exportedRevision !== undefined && typeof exportedRevision !== "string") {
@@ -3199,15 +3492,17 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3199
3492
  ast,
3200
3493
  blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])],
3201
3494
  adoptionAddressAliases,
3202
- ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0) && {
3495
+ ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0 || outputDiagnostics.length > 0 || fieldMappingDiagnostics.length > 0) && {
3203
3496
  diagnostics: [
3204
3497
  ...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`),
3205
3498
  ...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`),
3499
+ ...outputDiagnostics,
3500
+ ...fieldMappingDiagnostics.map((message) => `automation "${automationLabel}": ${message}`),
3206
3501
  ],
3207
3502
  }),
3208
3503
  };
3209
3504
  }
3210
- export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh) {
3505
+ export function automationFromTf(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth) {
3211
3506
  if (Array.isArray(first)) {
3212
3507
  const ctx = second;
3213
3508
  const automationBlock = first.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE);
@@ -3215,16 +3510,18 @@ export function automationFromTf(first, second, third, fourth, fifth, sixth, sev
3215
3510
  return { skippedReason: "automation resource not found" };
3216
3511
  }
3217
3512
  try {
3218
- 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);
3513
+ 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, ctx.foreignTaskRefNames);
3219
3514
  if (result.diagnostics)
3220
3515
  ctx.diagnostics.push(...result.diagnostics);
3221
3516
  return { automation: result.ast };
3222
3517
  }
3223
3518
  catch (err) {
3519
+ if (err instanceof UnsupportedMultiTriggerError)
3520
+ throw err;
3224
3521
  const message = err instanceof Error ? err.message : String(err);
3225
3522
  ctx.diagnostics.push(message);
3226
3523
  return { skippedReason: message };
3227
3524
  }
3228
3525
  }
3229
- return automationFromTfDocument(first, second, third ?? "", fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh);
3526
+ return automationFromTfDocument(first, second, third ?? "", fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth);
3230
3527
  }