@elementumai/edk 0.10.2 → 0.10.3

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 (114) hide show
  1. package/README.md +7 -7
  2. package/dist-sdk/src/catalog/org.d.ts +7 -5
  3. package/dist-sdk/src/catalog/org.js +14 -9
  4. package/dist-sdk/src/catalog/token.js +4 -0
  5. package/dist-sdk/src/core/types/app.d.ts +22 -0
  6. package/dist-sdk/src/engine/build/context.d.ts +8 -0
  7. package/dist-sdk/src/engine/build/source-context.d.ts +3 -4
  8. package/dist-sdk/src/engine/coverage-gaps.d.ts +2 -0
  9. package/dist-sdk/src/engine/coverage-gaps.js +3 -0
  10. package/dist-sdk/src/engine/ei/state.d.ts +48 -0
  11. package/dist-sdk/src/engine/ei/state.js +91 -0
  12. package/dist-sdk/src/engine/pull/authored-address.d.ts +100 -0
  13. package/dist-sdk/src/engine/pull/authored-address.js +360 -0
  14. package/dist-sdk/src/engine/pull/context.d.ts +59 -0
  15. package/dist-sdk/src/engine/tf/expr.d.ts +7 -0
  16. package/dist-sdk/src/engine/tf/expr.js +62 -18
  17. package/dist-sdk/src/engine/tf/index.d.ts +1 -1
  18. package/dist-sdk/src/engine/tf/index.js +1 -1
  19. package/dist-sdk/src/engine/tf/labels.d.ts +10 -2
  20. package/dist-sdk/src/engine/tf/labels.js +15 -2
  21. package/dist-sdk/src/engine/tf/parse.js +19 -6
  22. package/dist-sdk/src/engine/workspace/backend.d.ts +34 -0
  23. package/dist-sdk/src/engine/workspace/backend.js +104 -0
  24. package/dist-sdk/src/engine/workspace/generated-file.d.ts +3 -0
  25. package/dist-sdk/src/engine/workspace/generated-file.js +6 -0
  26. package/dist-sdk/src/engine/workspace/loader.js +2 -2
  27. package/dist-sdk/src/entities/agent-tool/to-tf.js +1 -1
  28. package/dist-sdk/src/entities/app/build.d.ts +36 -4
  29. package/dist-sdk/src/entities/app/build.js +67 -4
  30. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +12 -0
  31. package/dist-sdk/src/entities/app/from-tf.js +13 -9
  32. package/dist-sdk/src/entities/app/module.js +1 -0
  33. package/dist-sdk/src/entities/app/stage-keys.d.ts +82 -0
  34. package/dist-sdk/src/entities/app/stage-keys.js +160 -0
  35. package/dist-sdk/src/entities/app/to-tf.js +17 -21
  36. package/dist-sdk/src/entities/approval-chain/from-tf.d.ts +9 -1
  37. package/dist-sdk/src/entities/approval-chain/from-tf.js +31 -3
  38. package/dist-sdk/src/entities/approval-chain/module.js +12 -4
  39. package/dist-sdk/src/entities/approval-chain/to-tf.d.ts +1 -0
  40. package/dist-sdk/src/entities/approval-chain/to-tf.js +6 -1
  41. package/dist-sdk/src/entities/automation/build.js +13 -6
  42. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +3 -0
  43. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +5 -3
  44. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +90 -17
  45. package/dist-sdk/src/entities/automation/from-tf.d.ts +28 -6
  46. package/dist-sdk/src/entities/automation/from-tf.js +140 -23
  47. package/dist-sdk/src/entities/automation/module.js +123 -37
  48. package/dist-sdk/src/entities/automation/to-tf.d.ts +3 -1
  49. package/dist-sdk/src/entities/automation/to-tf.js +131 -20
  50. package/dist-sdk/src/entities/automation/triggers.d.ts +2 -0
  51. package/dist-sdk/src/entities/automation/triggers.js +1 -0
  52. package/dist-sdk/src/entities/chart/from-tf.d.ts +6 -0
  53. package/dist-sdk/src/entities/chart/from-tf.js +9 -1
  54. package/dist-sdk/src/entities/dashboard/from-tf.js +51 -4
  55. package/dist-sdk/src/entities/dynamic-layout/from-tf.d.ts +3 -0
  56. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +48 -4
  57. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +2 -0
  58. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +7 -2
  59. package/dist-sdk/src/entities/element/build.js +1 -1
  60. package/dist-sdk/src/entities/element/from-tf.d.ts +12 -6
  61. package/dist-sdk/src/entities/element/from-tf.js +23 -7
  62. package/dist-sdk/src/entities/element/module.js +3 -2
  63. package/dist-sdk/src/entities/element/to-tf.d.ts +3 -2
  64. package/dist-sdk/src/entities/element/to-tf.js +32 -25
  65. package/dist-sdk/src/entities/field/allow-list.d.ts +18 -0
  66. package/dist-sdk/src/entities/field/allow-list.js +42 -0
  67. package/dist-sdk/src/entities/field/build.d.ts +38 -3
  68. package/dist-sdk/src/entities/field/build.js +7 -2
  69. package/dist-sdk/src/entities/field/from-tf.js +178 -20
  70. package/dist-sdk/src/entities/field/module.js +2 -0
  71. package/dist-sdk/src/entities/field/options.d.ts +2 -0
  72. package/dist-sdk/src/entities/field/order.d.ts +9 -0
  73. package/dist-sdk/src/entities/field/order.js +33 -0
  74. package/dist-sdk/src/entities/field/to-tf.d.ts +6 -0
  75. package/dist-sdk/src/entities/field/to-tf.js +87 -0
  76. package/dist-sdk/src/entities/field/types.js +3 -0
  77. package/dist-sdk/src/entities/relationship/build.d.ts +3 -3
  78. package/dist-sdk/src/entities/relationship/from-tf.js +4 -2
  79. package/dist-sdk/src/entities/relationship/to-tf.js +3 -1
  80. package/dist-sdk/src/entities/service-account/workspace-owner.d.ts +8 -3
  81. package/dist-sdk/src/entities/service-account/workspace-owner.js +12 -4
  82. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +5 -0
  83. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +13 -0
  84. package/dist-sdk/src/entities/shared/filters/ast.d.ts +7 -0
  85. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +1 -1
  86. package/dist-sdk/src/entities/skill/to-tf.js +19 -14
  87. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  88. package/dist-sdk/src/entities/skill-tool/from-tf.js +3 -0
  89. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +6 -1
  90. package/dist-sdk/src/entities/skill-tool/to-tf.js +6 -1
  91. package/dist-sdk/src/entities/task/build.js +1 -1
  92. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.d.ts +11 -0
  93. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +13 -38
  94. package/dist-sdk/src/entities/view/custom-view-validate.d.ts +29 -0
  95. package/dist-sdk/src/entities/view/custom-view-validate.js +292 -0
  96. package/dist-sdk/src/entities/view/from-tf.d.ts +2 -0
  97. package/dist-sdk/src/entities/view/from-tf.js +40 -6
  98. package/dist-sdk/src/entities/view/to-tf.d.ts +6 -0
  99. package/dist-sdk/src/entities/view/to-tf.js +14 -6
  100. package/dist-sdk/src/entities/visual-flow/from-tf.d.ts +2 -1
  101. package/dist-sdk/src/entities/visual-flow/from-tf.js +11 -2
  102. package/dist-sdk/src/entities/visual-flow/module.js +15 -5
  103. package/dist-sdk/src/entities/visual-flow/to-tf.d.ts +2 -0
  104. package/dist-sdk/src/entities/visual-flow/to-tf.js +1 -1
  105. package/dist-sdk/src/entities/widget/build.d.ts +8 -1
  106. package/dist-sdk/src/entities/widget/from-tf.js +12 -6
  107. package/dist-sdk/src/entities/widget/to-tf.d.ts +1 -0
  108. package/dist-sdk/src/entities/widget/to-tf.js +16 -0
  109. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +8 -2
  110. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  111. package/dist-sdk/src/graph/index.d.ts +6 -0
  112. package/dist-sdk/src/graph/index.js +1 -0
  113. package/dist-sdk/src/graph/types.d.ts +59 -2
  114. package/package.json +2 -17
@@ -1,5 +1,5 @@
1
1
  /** The automation entity's registry entry (see src/graph/). */
2
- import { appScopedResourceLabel, sanitizeName, tfLabelToTsLabel, isTfExpr } from "../../engine/tf/index.js";
2
+ import { appScopedResourceLabel, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, isTfExpr } from "../../engine/tf/index.js";
3
3
  function elementOwnerHandle(payload) {
4
4
  if (payload === null || typeof payload !== "object" || !("handle" in payload))
5
5
  return undefined;
@@ -8,13 +8,13 @@ function elementOwnerHandle(payload) {
8
8
  }
9
9
  import { renderAutomationCatalogEntry } from "./catalog-render.js";
10
10
  import { hasUnresolvedForEachItem, preserveAuthoredAutomationPullMeta, printAutomationV2WithScriptFiles, SCRIPT_FILES_DIR } from "./deserializer/print-automation.js";
11
- import { reportAuthoringBlocker } from "../../engine/pull/context.js";
12
- import { recordValidations } from "../../engine/validation.js";
13
- import { automationFromTf, automationOwnedAddresses, ForEachItemOutsideLoopError, UnsupportedMultiTriggerError } from "./from-tf.js";
11
+ import { automationFromTf, automationOwnedAddresses, ForEachItemOutsideLoopError, UnresolvedForeignServiceAccountError, UnsupportedMultiTriggerError } from "./from-tf.js";
14
12
  import { scriptFileRefs } from "./script-code.js";
15
13
  import { typedCoverageGap } from "../../engine/coverage-gaps.js";
16
14
  import { TASK_OUTPUT_REFERENCE_NAMES } from "./task-output-labels.js";
17
15
  import { automationToTf } from "./to-tf.js";
16
+ import { approvalChainLostStage } from "../approval-chain/from-tf.js";
17
+ import { stageHandleIndexFromTfStages } from "../app/stage-keys.js";
18
18
  import { ALL_AUTOMATION_SUB_TYPES, AUTOMATION_RESOURCE_TYPE, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
19
19
  const AUTOMATION_MEMBER_TYPES = new Set([
20
20
  WORKFLOW_PUBLISH_RESOURCE_TYPE,
@@ -131,13 +131,66 @@ export function droppedAutomationGap(autoBlock, autoLabel, reason) {
131
131
  consequence: "it is not written to source or adopted; it keeps running on the platform unmanaged",
132
132
  });
133
133
  }
134
+ /** Addresses of the stream's approval processes that pull leaves unmanaged because their stage lost its only handle (#1136). */
135
+ function lostStageApprovalChains(stream, ctx) {
136
+ const lost = new Set();
137
+ if (ctx.parentScope !== "app")
138
+ return lost;
139
+ const stageHandles = stageHandleIndexFromTfStages(ctx.resourceByAddress?.(`elementum_app.${ctx.appTfLabel}`)?.attrs["stages"]);
140
+ if (stageHandles === undefined)
141
+ return lost;
142
+ for (const block of stream.allBlocks) {
143
+ if (block.kind !== "resource" || block.type !== "elementum_approval_process" || block.label === undefined)
144
+ continue;
145
+ if (approvalChainLostStage(block, ctx.appTfLabel, stageHandles) !== undefined)
146
+ lost.add(`${block.type}.${block.label}`);
147
+ }
148
+ return lost;
149
+ }
150
+ /** The first of `chains` that any block at `owned` references, if any. */
151
+ function referencedLostChain(stream, owned, chains) {
152
+ const ownedSet = new Set(owned);
153
+ const visit = (value) => {
154
+ if (Array.isArray(value)) {
155
+ for (const item of value) {
156
+ const hit = visit(item);
157
+ if (hit !== undefined)
158
+ return hit;
159
+ }
160
+ return undefined;
161
+ }
162
+ if (value === null || typeof value !== "object")
163
+ return undefined;
164
+ const record = value;
165
+ if (record["$expr"] === "resource-attr" && typeof record["type"] === "string" && typeof record["label"] === "string") {
166
+ const address = `${record["type"]}.${record["label"]}`;
167
+ if (chains.has(address))
168
+ return address;
169
+ }
170
+ for (const item of Object.values(record)) {
171
+ const hit = visit(item);
172
+ if (hit !== undefined)
173
+ return hit;
174
+ }
175
+ return undefined;
176
+ };
177
+ for (const block of stream.allBlocks) {
178
+ if (block.type === undefined || block.label === undefined || !ownedSet.has(`${block.type}.${block.label}`))
179
+ continue;
180
+ const hit = visit(block.attrs);
181
+ if (hit !== undefined)
182
+ return hit;
183
+ }
184
+ return undefined;
185
+ }
134
186
  function extractAutomations(ownBlocks, stream, ctx) {
135
187
  const items = [];
136
188
  const skipped = [];
137
189
  const releaseIfManaged = [];
190
+ const quarantineOwnFiles = [];
138
191
  const diagnostics = [];
139
- const validations = [];
140
192
  const adoptionAddressAliases = [];
193
+ const lostChains = lostStageApprovalChains(stream, ctx);
141
194
  for (const autoBlock of ownBlocks) {
142
195
  const autoLabel = autoBlock.label ?? "";
143
196
  const doc = { blocks: [...stream.allBlocks] };
@@ -145,8 +198,33 @@ function extractAutomations(ownBlocks, stream, ctx) {
145
198
  // somehow omits the app RefExpr still feeds --with-dependencies. Cheap
146
199
  // (one owned-address walk) relative to from-tf.
147
200
  registerForeignObjectIdDeps(doc, autoLabel, ctx);
201
+ // An approval chain on a stage with no handle of its own is left
202
+ // unmanaged (#1136), so a reference to it would dangle at build. Skip the
203
+ // automation with a warning and release an earlier adoption of it.
204
+ if (lostChains.size > 0) {
205
+ const owned = automationOwnedAddresses(doc, autoLabel);
206
+ const chain = referencedLostChain(stream, owned, lostChains);
207
+ if (chain !== undefined) {
208
+ skipped.push(...owned);
209
+ releaseIfManaged.push(...owned);
210
+ diagnostics.push(droppedAutomationGap(autoBlock, autoLabel, `it references ${chain}, which is left unmanaged because its stage has no handle of its own (#1136)`));
211
+ continue;
212
+ }
213
+ }
148
214
  try {
149
- const extracted = automationFromTf(doc, autoLabel, ctx.appRefName, ctx.foreignFieldRefsById, ctx.foreignFieldRefsByDataAddress, ctx.foreignTableRefsById, ctx.picklistOptionLabelById, ctx.fieldNamesByOwnerRefName, ctx.foreignAppRefNames, ctx.foreignElementRefNames, ctx.procedureKeysByDiscriminator, ctx.foreignTaskRefNames, ctx.groupKeysByName);
215
+ const extracted = automationFromTf(doc, autoLabel, ctx.appRefName, ctx.foreignFieldRefsById, ctx.foreignFieldRefsByDataAddress, ctx.foreignTableRefsById, ctx.picklistOptionLabelById, ctx.fieldNamesByOwnerRefName, ctx.foreignAppRefNames, ctx.foreignElementRefNames, ctx.procedureKeysByDiscriminator, ctx.foreignTaskRefNames, ctx.groupKeysByName, ctx.serviceAccountsById);
216
+ // edk#1646 / #1858: adopt when a rebuilt ctx ref matches provider Read.
217
+ // Otherwise the automation stays platform-managed. Releasing its state
218
+ // also archives the authored file, so the next plan does not create a
219
+ // second copy of the live automation.
220
+ if (extracted.stringifiedValueReferences === true) {
221
+ const owned = automationOwnedAddresses(doc, autoLabel);
222
+ skipped.push(...owned);
223
+ releaseIfManaged.push(...owned);
224
+ quarantineOwnFiles.push({ kind: "automation", refName: extracted.refName });
225
+ diagnostics.push(droppedAutomationGap(autoBlock, autoLabel, "the export embeds a stringified ValueReference that source cannot rebuild to match provider Read (edk#1646). It stays platform-managed, and its authored file is archived so the next plan does not create a duplicate."));
226
+ continue;
227
+ }
150
228
  // Keep automationFromTf's label-derived refName — agent/skill tools store
151
229
  // the same scopedLabelToBagKey as automationKey. Pushing bare AST (name
152
230
  // only) made missing-automation diagnostics false-positive on every real
@@ -156,23 +234,6 @@ function extractAutomations(ownBlocks, stream, ctx) {
156
234
  diagnostics.push(...(extracted.diagnostics ?? []).map((diagnostic) => `${autoLabel}: ${diagnostic}`));
157
235
  }
158
236
  catch (err) {
159
- // Multi-trigger is unsupported, not an extract gap. Collect every
160
- // offender and keep going. The addresses still go through `skipped` so
161
- // adoption will not import a graph that was not written, and the
162
- // message stays out of `diagnostics` (those are warnings).
163
- if (err instanceof UnsupportedMultiTriggerError) {
164
- const failure = {
165
- severity: "fatal",
166
- address: `${AUTOMATION_RESOURCE_TYPE}.${autoLabel}`,
167
- name: err.automationName,
168
- ownerKind: "automation",
169
- message: err.message,
170
- };
171
- validations.push(failure);
172
- recordValidations([failure]);
173
- skipped.push(...automationOwnedAddresses(doc, autoLabel));
174
- continue;
175
- }
176
237
  // Report the automation's FULL graph (trigger/tasks/branches/publish),
177
238
  // not just its root - otherwise those children's otherwise-adoptable
178
239
  // resource TYPES get imported into state anyway, and build (which
@@ -180,13 +241,22 @@ function extractAutomations(ownBlocks, stream, ctx) {
180
241
  // `plan` shows them as destroy-on-apply. See automationOwnedAddresses.
181
242
  const owned = automationOwnedAddresses(doc, autoLabel);
182
243
  skipped.push(...owned);
183
- // A sibling-loop item reference has no authored form at all, so an
184
- // earlier pull's state binding can never be reproduced either: release
185
- // it rather than let the next apply destroy the live automation (#1320).
186
- // That skip is a diagnostic, not a validation fatal: the automation is
187
- // not printed, so the build must not also report the placeholder.
188
- if (err instanceof ForEachItemOutsideLoopError)
244
+ // No authored form can manage these, so release an earlier adoption
245
+ // rather than let the next apply destroy the live automation:
246
+ // sibling-loop item refs (#1320) and multi-trigger (#1785 / #39).
247
+ // Soft diagnostic, not a validation fatal — the rest of the app must
248
+ // still adopt and plan clean while these stay platform-managed only.
249
+ if (err instanceof ForEachItemOutsideLoopError ||
250
+ err instanceof UnsupportedMultiTriggerError ||
251
+ err instanceof UnresolvedForeignServiceAccountError) {
189
252
  releaseIfManaged.push(...owned);
253
+ }
254
+ if (err instanceof UnresolvedForeignServiceAccountError) {
255
+ quarantineOwnFiles.push({
256
+ kind: "automation",
257
+ refName: scopedLabelToBagKey(ctx.appTfLabel, autoLabel),
258
+ });
259
+ }
190
260
  // edk#1480: name the dropped automation and say what that means, as a
191
261
  // typed gap so it counts (and fails --strict-coverage) by itself.
192
262
  diagnostics.push(droppedAutomationGap(autoBlock, autoLabel, err instanceof Error ? err.message : String(err)));
@@ -194,7 +264,10 @@ function extractAutomations(ownBlocks, stream, ctx) {
194
264
  }
195
265
  // A trigger, task, or publish with no automation resource is not in any
196
266
  // skeleton's graph. extractAutomations never sees it, and its resource type
197
- // is still adoptable, so the next plan can destroy it (#1484).
267
+ // is still adoptable, so the next plan can destroy it (#1484). Soft-skip
268
+ // rather than authoring-block the whole app: Blueprint exports sometimes
269
+ // omit a trigger (or leave a task without parent), and hard-failing hid
270
+ // the rest of the app from adoption (rfxclarificationquestion Retire Q&A).
198
271
  const doc = { blocks: [...stream.allBlocks] };
199
272
  const owned = new Set();
200
273
  for (const autoBlock of ownBlocks) {
@@ -210,14 +283,18 @@ function extractAutomations(ownBlocks, stream, ctx) {
210
283
  if (owned.has(address))
211
284
  continue;
212
285
  skipped.push(address);
213
- reportAuthoringBlocker(ctx, {
214
- address,
215
- ownFileKind: "automation",
216
- description: `${address} is not owned by an ${AUTOMATION_RESOURCE_TYPE} resource, so it cannot be pulled`,
217
- remedy: "The export is missing the automation these resources belong to. Re-export the app, or remove the orphaned automation resources, then pull again.",
218
- });
286
+ releaseIfManaged.push(address);
287
+ const display = typeof block.attrs["name"] === "string" && block.attrs["name"] !== ""
288
+ ? block.attrs["name"]
289
+ : block.label;
290
+ diagnostics.push(typedCoverageGap({
291
+ kind: "skipped",
292
+ entity: `${block.type} ${JSON.stringify(display)} (${block.label})`,
293
+ detail: "not pulled, skipped: not owned by an elementum_automation resource (export is missing the owning automation or the task has no parent chain)",
294
+ consequence: "it is not written to source or adopted; it keeps running on the platform unmanaged",
295
+ }));
219
296
  }
220
- return { items, skipped, releaseIfManaged, diagnostics, validations, adoptionAddressAliases };
297
+ return { items, skipped, releaseIfManaged, quarantineOwnFiles, diagnostics, adoptionAddressAliases };
221
298
  }
222
299
  export const automationModule = {
223
300
  kind: "automation",
@@ -311,6 +388,7 @@ export const automationModule = {
311
388
  ...(ctx.allowUnknownPicklistOptions === true ? { allowUnknownPicklistOptions: true } : {}),
312
389
  orgRefs: ctx.orgRefs,
313
390
  workspaceAspects: ctx.workspaceAspects,
391
+ ...(ctx.outOfScopeApps !== undefined && { outOfScopeApps: ctx.outOfScopeApps }),
314
392
  localsAttrs: ctx.localsAttrs,
315
393
  serviceAccounts: ctx.streamRootEntity?.payload?.serviceAccounts,
316
394
  activeAutomationRefNames: ctx.activeAutomationRefNames ?? new Set((ctx.siblingEntities ?? [])
@@ -352,6 +430,14 @@ export const automationModule = {
352
430
  localPrefix: "edk_variable_ids_",
353
431
  listField: "id",
354
432
  }],
433
+ // The provider's create_record / update_field / bulk_update_fields
434
+ // ModifyPlan equates these (`picklistValuesEquivalent`, #633), so plan
435
+ // stays clean whichever one the platform stored (#1891).
436
+ picklistLabelAssignments: [
437
+ "elementum_create_record_task",
438
+ "elementum_update_field_task",
439
+ "elementum_bulk_update_fields_task",
440
+ ].map((resourceType) => ({ resourceType, attribute: "fields", fieldAttribute: "field_id", valueAttribute: "value" })),
355
441
  },
356
442
  };
357
443
  /** The provider's `normalizeOnDemandFilterRefName`, which computes `filter_refs` at plan time. */
@@ -1,7 +1,7 @@
1
1
  import type { DeployableEntity } from "../../engine/entity.js";
2
2
  import { type ValidationFailure } from "../../engine/validation.js";
3
3
  import { type ChildResourceScope, type TfBlock, type TfExpr, type TfValue } from "../../engine/tf/index.js";
4
- import { type OrgRefLookup, type WorkspaceAspect } from "../../engine/build/context.js";
4
+ import { type ForeignRootIdentity, type OrgRefLookup, type WorkspaceAspect } from "../../engine/build/context.js";
5
5
  import type { BuildFieldMetadata } from "../../graph/types.js";
6
6
  import type { AppServiceAccount } from "../service-account/build.js";
7
7
  export interface AutomationToTfContext {
@@ -59,6 +59,8 @@ export interface AutomationToTfContext {
59
59
  * label shape from an element-owned one.
60
60
  */
61
61
  readonly workspaceAspects?: ReadonlyMap<string, WorkspaceAspect>;
62
+ /** See `ToTfContext.outOfScopeApps`. */
63
+ readonly outOfScopeApps?: ReadonlyMap<string, ForeignRootIdentity>;
62
64
  /**
63
65
  * The build's shared `locals.tf` attrs map — mutated in place so a foreign
64
66
  * field crossing through {@link crossAppFieldToTf} can contribute its own
@@ -8,6 +8,8 @@ import { workspaceAspectKey } from "../../engine/build/context.js";
8
8
  import { SEARCH_TABLE_RESOURCE_TYPES } from "../search-table/types.js";
9
9
  import { fieldRefToTfValue } from "../field/to-tf.js";
10
10
  import { SERVICE_ACCOUNT_RESOURCE_TYPE } from "../service-account/module.js";
11
+ import { serviceAccountRefToTf } from "../service-account/to-tf.js";
12
+ import { workspaceServiceAccountAppResolver } from "../service-account/workspace-owner.js";
11
13
  import { foreignFieldDataLabel, resolveForeignRef } from "../shared/foreign-ref.js";
12
14
  import { filterToTf as serializeFilterToTf } from "../shared/filters/tf-codec.js";
13
15
  import { referenceValueTypeForField } from "../shared/filters/index.js";
@@ -26,7 +28,7 @@ import { onDemandTriggerRefKey } from "./value-ref-tf.js";
26
28
  import { normalizeOnDemandParamKey } from "../../../pull/util.js";
27
29
  import { PROVIDER_FIXED_SYSTEM_FIELD_KEYS, recordFieldWireRefName } from "./system-ref-name.js";
28
30
  import { taskTfLabel } from "./task-label.js";
29
- import { isOnDemandRecordType } from "../shared/types/field-types.js";
31
+ import { FIELD_TYPE_MAP, isOnDemandRecordType } from "../shared/types/field-types.js";
30
32
  /** The context for reading records of `appRefName` (a `kind`), retargeted from the owner. */
31
33
  /**
32
34
  * Wire WorkflowFieldType -> elementum_on_demand_trigger `parameters[].type`.
@@ -2192,6 +2194,53 @@ function unresolvedForEachFailures(entity, payload, address) {
2192
2194
  "(e.g. restructure the loops, or pass the value through a variable) before this automation can build",
2193
2195
  }));
2194
2196
  }
2197
+ /**
2198
+ * An on-demand scalar whose refs key is also a record field's display name.
2199
+ * The field owns that key, so the parameter is written as the same envelope
2200
+ * export uses (`buildTriggerRefJSONFull`: fieldType, multiple, and the
2201
+ * normalized trigger name) instead of `refs["<display name>"]`.
2202
+ */
2203
+ function shadowedOnDemandParamRef(value, refs) {
2204
+ if (refs.trigger.type !== TRIGGER_RESOURCES.onDemand)
2205
+ return undefined;
2206
+ if (!isObject(value.triggerReference) || typeof value.triggerReference.name !== "string")
2207
+ return undefined;
2208
+ const inputName = onDemandTriggerRefKey(value.triggerReference.name, [...refs.triggerParamFieldTypes.keys()]);
2209
+ const input = refs.triggerParamFieldTypes.get(inputName);
2210
+ if (input === undefined ||
2211
+ refs.recordParamNames.includes(inputName) ||
2212
+ refs.userParamNames.includes(inputName))
2213
+ return undefined;
2214
+ const refsKey = triggerWireRefName(value.triggerReference.name, refs);
2215
+ let ownedByField = false;
2216
+ for (const displayName of refs.owner.fieldNames.values()) {
2217
+ if (displayName === refsKey) {
2218
+ ownedByField = true;
2219
+ break;
2220
+ }
2221
+ }
2222
+ if (!ownedByField)
2223
+ return undefined;
2224
+ const typed = typeof value.fieldType === "string"
2225
+ ? { fieldType: value.fieldType, multiple: value.multiple === true }
2226
+ : { fieldType: onDemandEnvelopeFieldType(input.fieldType), multiple: input.multiple };
2227
+ return {
2228
+ fieldType: typed.fieldType,
2229
+ multiple: typed.multiple,
2230
+ triggerReference: { name: normalizeOnDemandParamKey(inputName) },
2231
+ };
2232
+ }
2233
+ /** Authoring / HCL parameter type → the WorkflowFieldType export writes into the envelope. */
2234
+ function onDemandEnvelopeFieldType(type) {
2235
+ if (type === "attachment")
2236
+ return "ATTACHMENT_ID";
2237
+ if (type === "group")
2238
+ return "GROUP_ID";
2239
+ const mapped = FIELD_TYPE_MAP[type];
2240
+ if (mapped !== undefined)
2241
+ return mapped;
2242
+ return type;
2243
+ }
2195
2244
  /**
2196
2245
  * execute_script `inputs[].value` only. Provider Read stores the
2197
2246
  * Mobius-normalized short name (`reasonForClosingEarly`) for on-demand
@@ -2259,6 +2308,35 @@ function normalizeTriggerRecordIdEnvelopeString(raw, refs) {
2259
2308
  envelope.multiple = false;
2260
2309
  return JSON.stringify(envelope);
2261
2310
  }
2311
+ function undeclaredExecuteScriptFieldEnvelope(reference, refs, fieldType = "TEXT") {
2312
+ let value = reference;
2313
+ while (isObject(value) && "value" in value && Object.keys(value).length === 1) {
2314
+ value = value.value;
2315
+ }
2316
+ if (!isObject(value) || !isObject(value.taskReference))
2317
+ return undefined;
2318
+ const taskRef = value.taskReference;
2319
+ const taskRefKey = taskRef.taskRefKey;
2320
+ const name = taskRef.name;
2321
+ if (typeof taskRefKey !== "string" || typeof name !== "string" || !name.startsWith("result."))
2322
+ return undefined;
2323
+ const task = refs.tasks.get(taskRefKey);
2324
+ if (task?.type !== TASK_RESOURCES.executeScript)
2325
+ return undefined;
2326
+ // A declared output is a real refs["result.<key>"] entry. An undeclared one
2327
+ // (outputs omitted, or a key the schema does not list) is not in that map —
2328
+ // indexing it fails the plan. Provider Read stores the JSON envelope instead.
2329
+ if (task.outputFieldTypes !== undefined && scriptOutputReferenceIsDeclared(task.outputFieldTypes, name))
2330
+ return undefined;
2331
+ return expr.jsonencode({
2332
+ fieldType,
2333
+ multiple: false,
2334
+ taskReference: {
2335
+ name,
2336
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2337
+ },
2338
+ });
2339
+ }
2262
2340
  function valueToTf(value, refs) {
2263
2341
  const catalog = token(value);
2264
2342
  if (catalog !== undefined)
@@ -2311,6 +2389,9 @@ function valueToTf(value, refs) {
2311
2389
  if (payloadRef !== undefined)
2312
2390
  return expr.jsonencode(payloadRef);
2313
2391
  }
2392
+ const shadowedParam = shadowedOnDemandParamRef(value, refs);
2393
+ if (shadowedParam !== undefined)
2394
+ return expr.jsonencode(shadowedParam);
2314
2395
  return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: triggerWireRefName(value.triggerReference.name, refs) }]);
2315
2396
  }
2316
2397
  if (isObject(value.taskReference) && typeof value.taskReference.taskRefKey === "string" && typeof value.taskReference.name === "string") {
@@ -3026,6 +3107,12 @@ function configAttrs(kind, config, refs) {
3026
3107
  attrs.relate_to_record_reference = valueToTf(raw, refs);
3027
3108
  continue;
3028
3109
  }
3110
+ if (key === "recordReference" && kind === "elementum_update_field_task") {
3111
+ attrs.record_reference =
3112
+ undeclaredExecuteScriptFieldEnvelope(raw, refs, "ASPECT_RECORD_ID") ??
3113
+ valueToTf(raw, refs);
3114
+ continue;
3115
+ }
3029
3116
  if (key === "code" && kind === "elementum_execute_script_task") {
3030
3117
  if (typeof raw !== "string")
3031
3118
  throw new EntityTfError("executeScript code must be a string");
@@ -3347,7 +3434,11 @@ function configAttrs(kind, config, refs) {
3347
3434
  };
3348
3435
  }
3349
3436
  if (Array.isArray(staticValue)) {
3350
- if (fieldToken?.fieldType !== "MULTI_PICKLIST") {
3437
+ // An empty list on a raw platform-id field is the Multi-Select clear
3438
+ // export prints when the field's owner is outside the workspace; a
3439
+ // non-empty list still needs a typed Multi-Select field (#1707).
3440
+ const rawIdClear = fieldToken === undefined && staticValue.length === 0;
3441
+ if (fieldToken?.fieldType !== "MULTI_PICKLIST" && !rawIdClear) {
3351
3442
  throw new EntityTfError(`automation field "${fieldToken?.name ?? fieldToken?.refName ?? "unknown"}" uses an array value but is not a Multi-Select field`);
3352
3443
  }
3353
3444
  const values = staticValue.map((value) => picklistFilterValueToTf(value, fieldToken, refs) ?? valueToTf(value, refs));
@@ -3370,7 +3461,7 @@ function configAttrs(kind, config, refs) {
3370
3461
  }
3371
3462
  return {
3372
3463
  field_id: valueToTf(field.aspectFieldId, refs),
3373
- value: optionValue ?? valueToTf(reference, refs),
3464
+ value: optionValue ?? undeclaredExecuteScriptFieldEnvelope(reference, refs) ?? valueToTf(reference, refs),
3374
3465
  ...(field.operation === "ADD" ? { update_mode: "add" } : {}),
3375
3466
  };
3376
3467
  });
@@ -3564,6 +3655,9 @@ function fileReaderDependsOn(blocks) {
3564
3655
  });
3565
3656
  return deps;
3566
3657
  }
3658
+ function automationStatusPublishes(status) {
3659
+ return status === "ACTIVE" || status === "INACTIVE";
3660
+ }
3567
3661
  /** App- or element-owned `automation` entity → provider HCL blocks. */
3568
3662
  function elementHandleOf(explicit, payload) {
3569
3663
  if (explicit !== undefined && explicit !== "")
@@ -3587,6 +3681,7 @@ export function automationToTf(entity, ctx) {
3587
3681
  orgRefs: ctx.orgRefs,
3588
3682
  localsAttrs: ctx.localsAttrs,
3589
3683
  workspaceAspects: ctx.workspaceAspects,
3684
+ ...(ctx.outOfScopeApps !== undefined ? { outOfScopeApps: ctx.outOfScopeApps } : {}),
3590
3685
  diagnostics: ctx.diagnostics ?? [],
3591
3686
  activeAutomationRefNames: ctx.activeAutomationRefNames,
3592
3687
  ...(ctx.elementsWithoutAuditFields !== undefined ? { elementsWithoutAuditFields: ctx.elementsWithoutAuditFields } : {}),
@@ -3630,22 +3725,37 @@ export function automationToTf(entity, ctx) {
3630
3725
  },
3631
3726
  };
3632
3727
  if (payload.serviceAccount !== undefined) {
3633
- if (payload.serviceAccount.appRefName !== owner.appRefName) {
3634
- throw new EntityTfError(`automation "${entity.refName}" service account belongs to app "${payload.serviceAccount.appRefName}", not "${owner.appRefName}"`);
3635
- }
3636
- const local = Object.entries(ctx.serviceAccounts ?? {}).find(([, account]) => `${account.firstName} ${account.lastName}` === payload.serviceAccount.name);
3637
- if (local !== undefined) {
3638
- automation.attrs.service_account_id = expr.resourceAttr(SERVICE_ACCOUNT_RESOURCE_TYPE, appScopedResourceLabel(owner.appTfLabel, tsLabelToTfLabel(local[0])), ["id"]);
3639
- }
3640
- else if (owner.orgRefs !== undefined) {
3641
- const lookupLabel = sanitizeName(payload.serviceAccount.name);
3642
- owner.orgRefs.rawLookup(SERVICE_ACCOUNT_RESOURCE_TYPE, lookupLabel, payload.serviceAccount.name, {
3643
- app_id: expr.resourceAttr("elementum_app", owner.appTfLabel, ["id"]),
3644
- });
3645
- automation.attrs.service_account_id = expr.dataAttr(SERVICE_ACCOUNT_RESOURCE_TYPE, lookupLabel, ["id"]);
3728
+ const accountApp = payload.serviceAccount.appRefName;
3729
+ if (accountApp !== owner.appRefName) {
3730
+ // A sibling app's account uses the same resolver as roles (#1592):
3731
+ // bag key → resource ref, miss → data source. Do not guess the label
3732
+ // from the display name.
3733
+ const owning = workspaceServiceAccountAppResolver(owner.workspaceAspects, { apps: owner.outOfScopeApps, orgRefs: owner.orgRefs })(accountApp);
3734
+ if (owning === undefined || owner.orgRefs === undefined) {
3735
+ throw new EntityTfError(`automation "${entity.refName}" service account belongs to app "${accountApp}", which is not in this workspace`);
3736
+ }
3737
+ const diagnostics = [];
3738
+ const value = serviceAccountRefToTf(payload.serviceAccount, { appRefName: accountApp, ...owning, orgRefs: owner.orgRefs }, `automation "${entity.refName}" serviceAccount`, diagnostics);
3739
+ if (value === undefined) {
3740
+ throw new EntityTfError(diagnostics[0] ?? `automation "${entity.refName}" cannot resolve service account "${payload.serviceAccount.name}"`);
3741
+ }
3742
+ automation.attrs.service_account_id = value;
3646
3743
  }
3647
3744
  else {
3648
- throw new EntityTfError(`automation "${entity.refName}" cannot resolve service account "${payload.serviceAccount.name}"`);
3745
+ const local = Object.entries(ctx.serviceAccounts ?? {}).find(([, account]) => `${account.firstName} ${account.lastName}` === payload.serviceAccount.name);
3746
+ if (local !== undefined) {
3747
+ automation.attrs.service_account_id = expr.resourceAttr(SERVICE_ACCOUNT_RESOURCE_TYPE, appScopedResourceLabel(owner.appTfLabel, tsLabelToTfLabel(local[0])), ["id"]);
3748
+ }
3749
+ else if (owner.orgRefs !== undefined) {
3750
+ const lookupLabel = sanitizeName(payload.serviceAccount.name);
3751
+ owner.orgRefs.rawLookup(SERVICE_ACCOUNT_RESOURCE_TYPE, lookupLabel, payload.serviceAccount.name, {
3752
+ app_id: expr.resourceAttr("elementum_app", owner.appTfLabel, ["id"]),
3753
+ });
3754
+ automation.attrs.service_account_id = expr.dataAttr(SERVICE_ACCOUNT_RESOURCE_TYPE, lookupLabel, ["id"]);
3755
+ }
3756
+ else {
3757
+ throw new EntityTfError(`automation "${entity.refName}" cannot resolve service account "${payload.serviceAccount.name}"`);
3758
+ }
3649
3759
  }
3650
3760
  }
3651
3761
  const [triggerKey, triggerConfig] = onlyEntry(payload.trigger, `automation "${entity.refName}" trigger`);
@@ -3942,8 +4052,9 @@ export function automationToTf(entity, ctx) {
3942
4052
  const target = token(inner.targetAutomationId) ?? (isObject(inner.targetAutomationRef) ? token(inner.targetAutomationRef.value) : undefined);
3943
4053
  if (target?.__kind === "automation") {
3944
4054
  const targetLabel = scopedLabel(owner.appTfLabel, tsLabelToTfLabel(target.refName));
3945
- // A publish resource only exists for ACTIVE automations. Depending on
3946
- // a draft/inactive target's publish address produces invalid HCL.
4055
+ // Only a running (ACTIVE) target is a run dependency. A paused
4056
+ // target keeps its publish resource, but ei export does not wait
4057
+ // on it, and a draft target has none.
3947
4058
  if (ctx.activeAutomationRefNames?.has(target.refName) === true) {
3948
4059
  block.attrs.depends_on = [expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, targetLabel)];
3949
4060
  runAutomationPublishes.add(targetLabel);
@@ -4083,7 +4194,7 @@ export function automationToTf(entity, ctx) {
4083
4194
  if (fileReaderDeps.length > 0) {
4084
4195
  automation.attrs.depends_on = fileReaderDeps;
4085
4196
  }
4086
- if (payload.status === "ACTIVE") {
4197
+ if (automationStatusPublishes(payload.status)) {
4087
4198
  const outputValues = payload.outputProperties?.outputs ?? [];
4088
4199
  const publish = {
4089
4200
  kind: "resource",
@@ -123,6 +123,8 @@ export interface approvalProcessStatusUpdatedTriggerOptions<A extends AppOrEleme
123
123
  */
124
124
  readonly approvalChain?: ApprovalChainRef | UnsafePlatformId;
125
125
  readonly status: approvalProcessStatusUpdatedStatus;
126
+ /** Record filter the approval-chain trigger additionally requires. */
127
+ readonly filter?: Filter;
126
128
  }
127
129
  /** Fires when an approval chain on a record changes to the configured status. */
128
130
  export declare function approvalProcessStatusUpdated<A extends AppOrElementRef>(opts: approvalProcessStatusUpdatedTriggerOptions<A>): TriggerChain<RecordTriggerOutput<A>>;
@@ -119,6 +119,7 @@ export function approvalProcessStatusUpdated(opts) {
119
119
  aspectId: opts.app,
120
120
  ...(opts.approvalChain !== undefined ? { approvalChainTemplateId: opts.approvalChain } : {}),
121
121
  status: opts.status,
122
+ ...(opts.filter !== undefined ? { filter: opts.filter } : {}),
122
123
  type: "APPROVAL_CHAIN_UPDATE",
123
124
  },
124
125
  },
@@ -55,6 +55,12 @@ export interface NormalizedChart {
55
55
  readonly properties?: ChartProperties;
56
56
  readonly subscriptions: readonly (NormalizedChartSubscription | NormalizedChartOpaqueSubscription)[];
57
57
  }
58
+ /**
59
+ * The chart's refName, which is also its own-file name (`charts/<refName>.ts`)
60
+ * and the key a dashboard chart widget prints: the chart's TF label with the
61
+ * owning app's TF label (not its camelCase ref) stripped (#1731).
62
+ */
63
+ export declare function chartRefNameFromTfLabel(appTfLabel: string, chartTfLabel: string): string;
58
64
  export declare function chartFromTf(block: TfBlock, opts: {
59
65
  readonly appLabel: string;
60
66
  readonly appRefName: string;
@@ -329,6 +329,14 @@ function parseSubscription(value, appLabel, appRefName, ctx, where) {
329
329
  ...(stringList(rec["tags"]) !== undefined ? { tags: stringList(rec["tags"]) } : {}),
330
330
  };
331
331
  }
332
+ /**
333
+ * The chart's refName, which is also its own-file name (`charts/<refName>.ts`)
334
+ * and the key a dashboard chart widget prints: the chart's TF label with the
335
+ * owning app's TF label (not its camelCase ref) stripped (#1731).
336
+ */
337
+ export function chartRefNameFromTfLabel(appTfLabel, chartTfLabel) {
338
+ return scopedLabelToBagKey(appTfLabel, chartTfLabel, "app");
339
+ }
332
340
  export function chartFromTf(block, opts, ctx) {
333
341
  if (block.type !== CHART_RESOURCE_TYPE || block.label === undefined)
334
342
  return undefined;
@@ -356,7 +364,7 @@ export function chartFromTf(block, opts, ctx) {
356
364
  ...(typeof rawProperties["target"] === "number" ? { target: rawProperties["target"] } : {}),
357
365
  };
358
366
  return {
359
- refName: scopedLabelToBagKey(opts.appLabel, block.label, "app"), name, type,
367
+ refName: chartRefNameFromTfLabel(opts.appLabel, block.label), name, type,
360
368
  ...(typeof block.attrs["target"] === "number" ? { target: block.attrs["target"] } : {}),
361
369
  ...(properties !== undefined ? { properties } : {}), subscriptions,
362
370
  };