@elementumai/edk 0.10.1 → 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 (125) 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 +3 -1
  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 +21 -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.d.ts +2 -0
  42. package/dist-sdk/src/entities/automation/build.js +25 -17
  43. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +3 -0
  44. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +5 -3
  45. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +127 -31
  46. package/dist-sdk/src/entities/automation/from-tf.d.ts +28 -6
  47. package/dist-sdk/src/entities/automation/from-tf.js +172 -27
  48. package/dist-sdk/src/entities/automation/module.js +123 -37
  49. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +21 -0
  50. package/dist-sdk/src/entities/automation/output-key-wire-name.js +38 -0
  51. package/dist-sdk/src/entities/automation/to-tf.d.ts +3 -1
  52. package/dist-sdk/src/entities/automation/to-tf.js +191 -33
  53. package/dist-sdk/src/entities/automation/triggers.d.ts +2 -0
  54. package/dist-sdk/src/entities/automation/triggers.js +1 -0
  55. package/dist-sdk/src/entities/chart/from-tf.d.ts +6 -0
  56. package/dist-sdk/src/entities/chart/from-tf.js +9 -1
  57. package/dist-sdk/src/entities/dashboard/from-tf.js +51 -4
  58. package/dist-sdk/src/entities/dynamic-layout/from-tf.d.ts +3 -0
  59. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +48 -4
  60. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +2 -0
  61. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +7 -2
  62. package/dist-sdk/src/entities/element/build.js +1 -1
  63. package/dist-sdk/src/entities/element/from-tf.d.ts +12 -6
  64. package/dist-sdk/src/entities/element/from-tf.js +23 -7
  65. package/dist-sdk/src/entities/element/module.js +5 -3
  66. package/dist-sdk/src/entities/element/to-tf.d.ts +3 -2
  67. package/dist-sdk/src/entities/element/to-tf.js +36 -25
  68. package/dist-sdk/src/entities/field/allow-list.d.ts +18 -0
  69. package/dist-sdk/src/entities/field/allow-list.js +42 -0
  70. package/dist-sdk/src/entities/field/build.d.ts +38 -3
  71. package/dist-sdk/src/entities/field/build.js +7 -2
  72. package/dist-sdk/src/entities/field/from-tf.js +252 -76
  73. package/dist-sdk/src/entities/field/module.d.ts +6 -0
  74. package/dist-sdk/src/entities/field/module.js +24 -2
  75. package/dist-sdk/src/entities/field/options.d.ts +2 -0
  76. package/dist-sdk/src/entities/field/order.d.ts +25 -0
  77. package/dist-sdk/src/entities/field/order.js +74 -0
  78. package/dist-sdk/src/entities/field/to-tf.d.ts +6 -0
  79. package/dist-sdk/src/entities/field/to-tf.js +87 -0
  80. package/dist-sdk/src/entities/field/types.d.ts +5 -0
  81. package/dist-sdk/src/entities/field/types.js +8 -0
  82. package/dist-sdk/src/entities/relationship/build.d.ts +3 -3
  83. package/dist-sdk/src/entities/relationship/from-tf.js +4 -2
  84. package/dist-sdk/src/entities/relationship/to-tf.js +3 -1
  85. package/dist-sdk/src/entities/service-account/workspace-owner.d.ts +8 -3
  86. package/dist-sdk/src/entities/service-account/workspace-owner.js +12 -4
  87. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +5 -0
  88. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +13 -0
  89. package/dist-sdk/src/entities/shared/filters/ast.d.ts +7 -0
  90. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +1 -1
  91. package/dist-sdk/src/entities/skill/to-tf.js +19 -14
  92. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  93. package/dist-sdk/src/entities/skill-tool/from-tf.js +3 -0
  94. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +6 -1
  95. package/dist-sdk/src/entities/skill-tool/to-tf.js +6 -1
  96. package/dist-sdk/src/entities/task/build.js +1 -1
  97. package/dist-sdk/src/entities/task/module.js +2 -1
  98. package/dist-sdk/src/entities/task/to-tf.js +4 -0
  99. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.d.ts +11 -0
  100. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +13 -38
  101. package/dist-sdk/src/entities/view/custom-view-validate.d.ts +29 -0
  102. package/dist-sdk/src/entities/view/custom-view-validate.js +292 -0
  103. package/dist-sdk/src/entities/view/from-tf.d.ts +2 -0
  104. package/dist-sdk/src/entities/view/from-tf.js +40 -6
  105. package/dist-sdk/src/entities/view/module.js +4 -1
  106. package/dist-sdk/src/entities/view/to-tf.d.ts +6 -0
  107. package/dist-sdk/src/entities/view/to-tf.js +25 -9
  108. package/dist-sdk/src/entities/view/types.d.ts +6 -0
  109. package/dist-sdk/src/entities/view/types.js +6 -0
  110. package/dist-sdk/src/entities/visual-flow/from-tf.d.ts +2 -1
  111. package/dist-sdk/src/entities/visual-flow/from-tf.js +11 -2
  112. package/dist-sdk/src/entities/visual-flow/module.js +15 -5
  113. package/dist-sdk/src/entities/visual-flow/to-tf.d.ts +2 -0
  114. package/dist-sdk/src/entities/visual-flow/to-tf.js +1 -1
  115. package/dist-sdk/src/entities/widget/build.d.ts +8 -1
  116. package/dist-sdk/src/entities/widget/from-tf.js +12 -6
  117. package/dist-sdk/src/entities/widget/to-tf.d.ts +1 -0
  118. package/dist-sdk/src/entities/widget/to-tf.js +16 -0
  119. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +8 -2
  120. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  121. package/dist-sdk/src/graph/index.d.ts +9 -2
  122. package/dist-sdk/src/graph/index.js +4 -0
  123. package/dist-sdk/src/graph/modules.js +2 -1
  124. package/dist-sdk/src/graph/types.d.ts +72 -3
  125. package/package.json +2 -17
@@ -0,0 +1,160 @@
1
+ import { EntityTfError } from "../../engine/entity.js";
2
+ import { isTfLabel, sanitizeName, snakeSlug, stageHandleTfLabel } from "../../engine/tf/index.js";
3
+ import { picklistLabel } from "../field/options.js";
4
+ /** The provider's default stages when an app authors none. */
5
+ export const DEFAULT_APP_STAGES = [
6
+ { key: "stage_1", name: "Stage 1" },
7
+ { key: "stage_2", name: "Stage 2" },
8
+ ];
9
+ /** A stage's real key: the imported alias when pull kept one, otherwise `snakeSlug(label)`. */
10
+ export function stageKeyFromPicklistValue(pv) {
11
+ const name = picklistLabel(pv);
12
+ return { key: pv.__stageKey ?? snakeSlug(name), name };
13
+ }
14
+ /**
15
+ * Every tf-label handle that authored source or pull can use for a stage,
16
+ * mapped to the stage's real `stage_ids_by_key` key (#1136). A layout bag key,
17
+ * a dynamic-layout `stage`, an approval chain `stage` or a visual-flow
18
+ * `stage` resolves through this map. Handles:
19
+ * - the real key itself, when it is a tf label. This covers renamed stages
20
+ * (`legacy_key` for "Renamed stage") and keys such as `foo__bar` that are
21
+ * legal tf labels but not the slug;
22
+ * - `snakeSlug(key)`, when the real key keeps punctuation
23
+ * (`enrichment_&_validation` -> `enrichment_validation`), which is the
24
+ * handle pull writes for it;
25
+ * - `snakeSlug(name)`, the handle authored apps use;
26
+ * - `SanitizeName(name)`, ei's classic-layout label, only where no other
27
+ * handle claimed it.
28
+ *
29
+ * A stage's own key always wins over a derived handle. When two stages
30
+ * derive the same handle, the first keeps it and a diagnostic says so,
31
+ * instead of silently rebinding. A stage left with no handle that maps to
32
+ * its own key (a punctuation key whose only handle is another stage's key,
33
+ * e.g. `pre-approval` next to `pre_approval`) is diagnosed too. Pull never
34
+ * writes another stage's handle for it: see {@link pulledStageHandle}.
35
+ */
36
+ export function stageKeyByHandle(stages, diagnostics) {
37
+ const byHandle = new Map();
38
+ for (const stage of stages) {
39
+ if (isTfLabel(stage.key) && !byHandle.has(stage.key))
40
+ byHandle.set(stage.key, stage.key);
41
+ }
42
+ const derived = new Set();
43
+ const reported = new Set();
44
+ const lostTo = new Map();
45
+ for (const stage of stages) {
46
+ const handles = new Set();
47
+ if (!isTfLabel(stage.key)) {
48
+ const handle = stageHandleTfLabel(stage.key);
49
+ if (handle !== undefined)
50
+ handles.add(handle);
51
+ }
52
+ // Only tf labels are handles: `snakeSlug("1st Review")` is `1st_review`,
53
+ // which no source can carry (its handle is `_1st_review`, below).
54
+ const nameHandle = snakeSlug(stage.name);
55
+ if (isTfLabel(nameHandle))
56
+ handles.add(nameHandle);
57
+ for (const handle of handles) {
58
+ const existing = byHandle.get(handle);
59
+ if (existing === undefined) {
60
+ byHandle.set(handle, stage.key);
61
+ derived.add(handle);
62
+ }
63
+ else if (existing !== stage.key && derived.has(handle)) {
64
+ reported.add(stage.key);
65
+ diagnostics?.push(`systemFields.stage: stages "${existing}" and "${stage.key}" both derive the handle "${handle}"; it stays bound to "${existing}". Give the other stage an explicit key to reference it; until then pull leaves references that only that handle could carry unmanaged.`);
66
+ }
67
+ else if (existing !== stage.key && !lostTo.has(stage.key)) {
68
+ lostTo.set(stage.key, { handle, owner: existing });
69
+ }
70
+ }
71
+ }
72
+ // ei labels a stage's classic layout SanitizeName(stage name), which pull
73
+ // keeps as the layout bag key when it is a handle for that stage. Add it
74
+ // last and only where free, so it never displaces a key or slug handle.
75
+ for (const stage of stages) {
76
+ const exportHandle = sanitizeName(stage.name);
77
+ if (isTfLabel(exportHandle) && !byHandle.has(exportHandle))
78
+ byHandle.set(exportHandle, stage.key);
79
+ }
80
+ const bound = new Set(byHandle.values());
81
+ for (const stage of stages) {
82
+ const lost = lostTo.get(stage.key);
83
+ if (bound.has(stage.key) || reported.has(stage.key) || lost === undefined)
84
+ continue;
85
+ diagnostics?.push(`systemFields.stage: stage "${stage.key}" has no handle of its own: its handle "${lost.handle}" is stage "${lost.owner}"'s key. Source cannot reference "${stage.key}", so pull leaves its layouts, dynamic layouts, approval chains and flows unmanaged (each one warned) instead of binding them to "${lost.owner}". Rename one of the stages so each has its own handle.`);
86
+ }
87
+ return byHandle;
88
+ }
89
+ /** {@link stageKeyByHandle} plus the real key set. */
90
+ export function stageHandleIndex(stages, diagnostics) {
91
+ return { byHandle: stageKeyByHandle(stages, diagnostics), keys: new Set(stages.map((stage) => stage.key)) };
92
+ }
93
+ /** The stage handles of an `elementum_app` block's `stages` attribute, or undefined when it has none. */
94
+ export function stageHandleIndexFromTfStages(value) {
95
+ if (!Array.isArray(value))
96
+ return undefined;
97
+ const stages = [];
98
+ for (const item of value) {
99
+ if (typeof item !== "object" || item === null)
100
+ continue;
101
+ const { key, name } = item;
102
+ if (typeof key === "string" && typeof name === "string")
103
+ stages.push({ key, name });
104
+ }
105
+ return stageHandleIndex(stages);
106
+ }
107
+ /**
108
+ * The handle pull writes for a `stage_ids_by_key` index (#1136): one that
109
+ * build maps back to this same stage. Prefers `stageHandleTfLabel(index)`,
110
+ * then any other handle bound to the stage. When the stage has none (its
111
+ * slug is another stage's own key, e.g. `pre-approval` next to
112
+ * `pre_approval`), returns `lost`: writing that handle would bind the
113
+ * reference to the other stage on build, so the caller leaves the
114
+ * reference out with a diagnostic instead. Without an index (or for an
115
+ * index that is not one of the app's stages) this is `stageHandleTfLabel`.
116
+ */
117
+ export function pulledStageHandle(index, stages) {
118
+ const preferred = stageHandleTfLabel(index);
119
+ if (stages === undefined || !stages.keys.has(index))
120
+ return preferred === undefined ? { kind: "none" } : { kind: "handle", handle: preferred };
121
+ if (preferred !== undefined && stages.byHandle.get(preferred) === index)
122
+ return { kind: "handle", handle: preferred };
123
+ for (const [handle, key] of stages.byHandle)
124
+ if (key === index && isTfLabel(handle))
125
+ return { kind: "handle", handle };
126
+ if (preferred === undefined)
127
+ return { kind: "none" };
128
+ const owner = stages.byHandle.get(preferred);
129
+ return owner === undefined ? { kind: "handle", handle: preferred } : { kind: "lost", handle: preferred, owner };
130
+ }
131
+ /**
132
+ * Thrown by an own-file extractor whose resource is left unmanaged because
133
+ * its stage lost its only handle (#1136). The extractor skips the resource
134
+ * AND releases it from state if an earlier pull adopted it, so the next plan
135
+ * does not destroy the live resource.
136
+ */
137
+ export class LostStageHandleError extends EntityTfError {
138
+ constructor(message) {
139
+ super(message);
140
+ this.name = "LostStageHandleError";
141
+ }
142
+ }
143
+ /** The per-reference warning for a `lost` {@link pulledStageHandle}. */
144
+ export function lostStageMessage(where, index, lost, outcome) {
145
+ return `${where}: stage "${index}" has no handle of its own (its handle "${lost.handle}" is stage "${lost.owner}"'s key); ${outcome} instead of binding it to "${lost.owner}" (#1136)`;
146
+ }
147
+ /** The owning app's stage handles (see {@link stageKeyByHandle}) from its built payload, for child entities. */
148
+ export function appStageKeyByHandle(payload) {
149
+ if (typeof payload !== "object" || payload === null)
150
+ return undefined;
151
+ for (const entry of payload.fields ?? []) {
152
+ for (const inner of Object.values(entry)) {
153
+ if (inner?.tags?.includes("STAGE") !== true)
154
+ continue;
155
+ const values = inner.picklistValues ?? [];
156
+ return stageKeyByHandle(values.length === 0 ? DEFAULT_APP_STAGES : values.map(stageKeyFromPicklistValue));
157
+ }
158
+ }
159
+ return stageKeyByHandle(DEFAULT_APP_STAGES);
160
+ }
@@ -14,6 +14,7 @@
14
14
  * Unsupported authoring shapes degrade through `diagnostics` — reported,
15
15
  * never silent, never thrown (plan §4.3).
16
16
  */
17
+ import { managedFieldOrderToTf } from "../field/order.js";
17
18
  import { typedCoverageGap } from "../../engine/coverage-gaps.js";
18
19
  import { autoShareToTf } from "./auto-share.js";
19
20
  import { workspaceAspectKey } from "../../engine/build/context.js";
@@ -37,6 +38,7 @@ import { appServiceAccountBlocks } from "../service-account/to-tf.js";
37
38
  import { relationshipTargetsFromBag, widgetsToTf } from "../widget/to-tf.js";
38
39
  import { viewToTf } from "../view/to-tf.js";
39
40
  import { APP_RESOURCE_TYPE } from "./module.js";
41
+ import { DEFAULT_APP_STAGES, stageKeyByHandle, stageKeyFromPicklistValue } from "./stage-keys.js";
40
42
  /**
41
43
  * The named gap for a system-field tag with no canonical key (edk#1480).
42
44
  * Defensive: every tag in SYSTEM_FIELD_TAGS maps today, so a new tag lands
@@ -136,9 +138,8 @@ export function appToTf(entity, ctx) {
136
138
  const fieldMetadata = fieldMetadataFromEntries(payload.fields);
137
139
  const fieldNames = new Map();
138
140
  let statusOptions;
139
- let stages;
140
141
  const systemFieldConfig = {};
141
- const stageTfLabels = new Set();
142
+ let stageKeys;
142
143
  const objectId = expr.resourceAttr(APP_RESOURCE_TYPE, ctx.appTfLabel, ["id"]);
143
144
  const fieldDisplayNames = new Map();
144
145
  for (const fieldEntry of payload.fields ?? []) {
@@ -207,12 +208,9 @@ export function appToTf(entity, ctx) {
207
208
  ctx.diagnostics.push(`systemFields.stage: the provider has no stage field name attribute; authored name "${name}" dropped (field stays "Stage")`);
208
209
  }
209
210
  if (inner.picklistValues !== undefined) {
210
- stages = inner.picklistValues.map((pv) => {
211
- const label = picklistLabel(pv);
212
- const key = snakeSlug(label);
213
- stageTfLabels.add(key);
214
- return { key, name: label };
215
- });
211
+ // An imported stage keeps its alias (`__stageKey`, #1136); an
212
+ // authored one derives snakeSlug(label).
213
+ stageKeys = inner.picklistValues.map(stageKeyFromPicklistValue);
216
214
  }
217
215
  break;
218
216
  default: {
@@ -241,6 +239,9 @@ export function appToTf(entity, ctx) {
241
239
  blocks.push(field.block);
242
240
  fieldAddresses.set(field.bagKey, field.address);
243
241
  }
242
+ const fieldOrder = managedFieldOrderToTf(ctx.appTfLabel, "app", objectId, fieldAddresses);
243
+ if (fieldOrder !== undefined)
244
+ blocks.push(fieldOrder);
244
245
  if (Object.keys(systemFieldConfig).length > 0) {
245
246
  appAttrs["system_field_config"] = systemFieldConfig;
246
247
  }
@@ -250,17 +251,12 @@ export function appToTf(entity, ctx) {
250
251
  appAttrs["status_options"] = statusOptions === undefined || statusOptions.length === 0
251
252
  ? DEPLOY_DEFAULT_STATUS_OPTION_VALUES.map((option) => ({ ...option, tags: [...option.tags] }))
252
253
  : statusOptions;
253
- if (stages === undefined || stages.length === 0) {
254
- appAttrs["stages"] = [
255
- { key: "stage_1", name: "Stage 1" },
256
- { key: "stage_2", name: "Stage 2" },
257
- ];
258
- stageTfLabels.add("stage_1");
259
- stageTfLabels.add("stage_2");
260
- }
261
- else {
262
- appAttrs["stages"] = stages;
263
- }
254
+ const emittedStages = stageKeys === undefined || stageKeys.length === 0 ? DEFAULT_APP_STAGES : stageKeys;
255
+ appAttrs["stages"] = emittedStages.map((stage) => ({ key: stage.key, name: stage.name }));
256
+ // Every handle a layout or dynamic layout can name a stage by → the stage's
257
+ // real stage_ids_by_key key (#1136). Membership is checked against the same map.
258
+ const stageKeyByTfLabel = stageKeyByHandle(emittedStages, ctx.diagnostics);
259
+ const stageTfLabels = new Set(stageKeyByTfLabel.keys());
264
260
  // --- View pass: layouts / list views / view order (entities/view), owner passed in.
265
261
  blocks.push(...dashboardsToTf(payload.dashboards, {
266
262
  ownerTfLabel: ctx.appTfLabel,
@@ -291,11 +287,14 @@ export function appToTf(entity, ctx) {
291
287
  ownerTfLabel: ctx.appTfLabel,
292
288
  objectId,
293
289
  stageTfLabels,
290
+ stageKeyByTfLabel,
294
291
  dashboardKeys: new Set(Object.keys(payload.dashboards ?? {})),
295
292
  orgRefs: ctx.orgRefs,
296
293
  workspaceAspects: ctx.workspaceAspects,
297
294
  diagnostics: ctx.diagnostics,
298
295
  fieldAddresses,
296
+ fieldNames,
297
+ fieldMetadata,
299
298
  widgetKeys: new Set(Object.keys(payload.widgets ?? {})),
300
299
  }, payload.customViews);
301
300
  blocks.push(...viewBlocks);
@@ -318,6 +317,7 @@ export function appToTf(entity, ctx) {
318
317
  workspaceAspects: ctx.workspaceAspects,
319
318
  fieldAddresses,
320
319
  widgetKeys: new Set(Object.keys(payload.widgets ?? {})),
320
+ stageKeyByTfLabel,
321
321
  }));
322
322
  blocks.push(...relationshipsToTf(payload.relationships, {
323
323
  ownerRefName: ctx.appRefName,
@@ -345,7 +345,7 @@ export function appToTf(entity, ctx) {
345
345
  appRefName: ctx.appRefName,
346
346
  serviceAccounts: payload.serviceAccounts,
347
347
  fieldAddresses,
348
- resolveServiceAccountApp: workspaceServiceAccountAppResolver(ctx.workspaceAspects),
348
+ resolveServiceAccountApp: workspaceServiceAccountAppResolver(ctx.workspaceAspects, { apps: ctx.outOfScopeApps, orgRefs: ctx.orgRefs }),
349
349
  });
350
350
  blocks.push(block);
351
351
  }
@@ -357,7 +357,7 @@ export function appToTf(entity, ctx) {
357
357
  serviceAccounts: payload.serviceAccounts,
358
358
  orgRefs: ctx.orgRefs,
359
359
  diagnostics: ctx.diagnostics,
360
- resolveServiceAccountApp: workspaceServiceAccountAppResolver(ctx.workspaceAspects),
360
+ resolveServiceAccountApp: workspaceServiceAccountAppResolver(ctx.workspaceAspects, { apps: ctx.outOfScopeApps, orgRefs: ctx.orgRefs }),
361
361
  }));
362
362
  blocks.push(...appServiceAccountBlocks(payload, {
363
363
  ownerTfLabel: ctx.appTfLabel,
@@ -1,5 +1,6 @@
1
1
  import { type FromTfContext } from "../../engine/pull/context.js";
2
2
  import { type TfBlock } from "../../engine/tf/index.js";
3
+ import { type StageHandleIndex } from "../app/stage-keys.js";
3
4
  export interface NormalizedApprovalChain {
4
5
  readonly refName: string;
5
6
  readonly name: string;
@@ -15,4 +16,11 @@ export interface NormalizedApprovalChain {
15
16
  readonly lockedFields: readonly string[];
16
17
  readonly unsafeLockedFieldIds?: readonly string[];
17
18
  }
18
- export declare function approvalChainFromTf(block: TfBlock, appTfLabel: string, ctx: FromTfContext): NormalizedApprovalChain;
19
+ /**
20
+ * The lost-stage warning when an approval process sits on a stage with no
21
+ * handle of its own (see `pulledStageHandle`, #1136), else undefined. Such a
22
+ * chain is left unmanaged, so anything that references it (an automation's
23
+ * approval task or trigger) cannot be authored either.
24
+ */
25
+ export declare function approvalChainLostStage(block: Pick<TfBlock, "type" | "label" | "attrs">, appTfLabel: string, stageHandles: StageHandleIndex | undefined): string | undefined;
26
+ export declare function approvalChainFromTf(block: TfBlock, appTfLabel: string, ctx: FromTfContext, stageHandles?: StageHandleIndex): NormalizedApprovalChain;
@@ -2,10 +2,27 @@ import { EntityTfError } from "../../engine/entity.js";
2
2
  import { resourceRefLabel } from "../../engine/pull/context.js";
3
3
  import { isTfExpr, scopedLabelToBagKey, tfLabelToTsLabel } from "../../engine/tf/index.js";
4
4
  import { fieldKeyFromTfRef } from "../field/from-tf.js";
5
+ import { LostStageHandleError, lostStageMessage, pulledStageHandle } from "../app/stage-keys.js";
5
6
  import { APPROVAL_PROCESS_RESOURCE_TYPE } from "./module.js";
6
7
  const KNOWN = new Set(["id", "app_id", "name", "stage_id", "number_of_dynamic_approvers", "locked_field_ids", "managed_by_automation", "approve_button_text", "deny_button_text", "exception_button_text", "default_reason", "approval_summary"]);
7
8
  function stringAttr(attrs, key) { return typeof attrs[key] === "string" ? attrs[key] : undefined; }
8
- export function approvalChainFromTf(block, appTfLabel, ctx) {
9
+ /**
10
+ * The lost-stage warning when an approval process sits on a stage with no
11
+ * handle of its own (see `pulledStageHandle`, #1136), else undefined. Such a
12
+ * chain is left unmanaged, so anything that references it (an automation's
13
+ * approval task or trigger) cannot be authored either.
14
+ */
15
+ export function approvalChainLostStage(block, appTfLabel, stageHandles) {
16
+ const stageValue = block.attrs["stage_id"];
17
+ if (!isTfExpr(stageValue) || stageValue.$expr !== "local" || stageValue.name !== `${appTfLabel}_stage_ids_by_key`)
18
+ return undefined;
19
+ const index = stageValue.path[0];
20
+ if (typeof index !== "object")
21
+ return undefined;
22
+ const pulled = pulledStageHandle(index.index, stageHandles);
23
+ return pulled.kind === "lost" ? lostStageMessage(`${block.type}.${block.label}`, index.index, pulled, "the approval chain is left unmanaged") : undefined;
24
+ }
25
+ export function approvalChainFromTf(block, appTfLabel, ctx, stageHandles) {
9
26
  if (block.type !== APPROVAL_PROCESS_RESOURCE_TYPE || block.label === undefined)
10
27
  throw new EntityTfError(`expected ${APPROVAL_PROCESS_RESOURCE_TYPE}`);
11
28
  for (const key of Object.keys(block.attrs))
@@ -30,8 +47,19 @@ export function approvalChainFromTf(block, appTfLabel, ctx) {
30
47
  let stageId;
31
48
  if (isTfExpr(stageValue) && stageValue.$expr === "local" && stageValue.name === `${appTfLabel}_stage_ids_by_key`) {
32
49
  const index = stageValue.path[0];
33
- if (typeof index === "object")
34
- stage = tfLabelToTsLabel(index.index);
50
+ if (typeof index === "object") {
51
+ // Imported keys may keep punctuation ("approval_&_execution"); pull a
52
+ // handle that build maps back to this same stage (#1136). A stage whose
53
+ // only handle is another stage's key keeps the chain unmanaged rather
54
+ // than binding it to that stage.
55
+ const lost = approvalChainLostStage(block, appTfLabel, stageHandles);
56
+ if (lost !== undefined)
57
+ throw new LostStageHandleError(lost);
58
+ const pulled = pulledStageHandle(index.index, stageHandles);
59
+ if (pulled.kind !== "handle")
60
+ throw new EntityTfError(`${block.type}.${block.label}: stage key ${JSON.stringify(index.index)} has no terraform label handle`);
61
+ stage = tfLabelToTsLabel(pulled.handle);
62
+ }
35
63
  }
36
64
  else if (typeof stageValue === "string")
37
65
  stageId = stageValue;
@@ -2,6 +2,7 @@ import { rootParentFactoryEntry } from "../../catalog/render-helpers.js";
2
2
  import { NO_DATA } from "../../graph/types.js";
3
3
  import { approvalChainFromTf } from "./from-tf.js";
4
4
  import { printApprovalChain } from "./printer.js";
5
+ import { appStageKeyByHandle, LostStageHandleError, stageHandleIndexFromTfStages } from "../app/stage-keys.js";
5
6
  import { approvalChainToTf } from "./to-tf.js";
6
7
  export const APPROVAL_PROCESS_RESOURCE_TYPE = "elementum_approval_process";
7
8
  function stub(refName, parent) { return { __kind: "approvalChain", refName, name: refName, parent }; }
@@ -25,17 +26,24 @@ function refFromAuthoring(args) {
25
26
  function extract(blocks, _stream, ctx) {
26
27
  const items = [];
27
28
  const skipped = [];
29
+ const releaseIfManaged = [];
28
30
  const diagnostics = [];
31
+ const stageHandles = stageHandleIndexFromTfStages(ctx.resourceByAddress?.(`elementum_app.${ctx.appTfLabel}`)?.attrs["stages"]);
29
32
  for (const block of blocks) {
30
33
  try {
31
- items.push(approvalChainFromTf(block, ctx.appTfLabel, ctx));
34
+ items.push(approvalChainFromTf(block, ctx.appTfLabel, ctx, stageHandles));
32
35
  }
33
36
  catch (error) {
34
- skipped.push(`${block.type}.${block.label ?? ""}`);
37
+ const address = `${block.type}.${block.label ?? ""}`;
38
+ skipped.push(address);
39
+ // A chain on a stage with no handle of its own has no authored form:
40
+ // release an earlier adoption instead of destroying it (#1136).
41
+ if (error instanceof LostStageHandleError)
42
+ releaseIfManaged.push(address);
35
43
  diagnostics.push(error instanceof Error ? error.message : String(error));
36
44
  }
37
45
  }
38
- return { items, skipped, diagnostics };
46
+ return { items, skipped, ...(releaseIfManaged.length > 0 && { releaseIfManaged }), diagnostics };
39
47
  }
40
48
  export const approvalChainModule = {
41
49
  kind: "approval-chain", stream: { role: "streamMember" }, authoring: { unit: "ownFile", bag: "approval-chains" },
@@ -44,7 +52,7 @@ export const approvalChainModule = {
44
52
  lifecycle: {
45
53
  participates: true, extractOwnFile: extract,
46
54
  printOwnFile: (item, opts) => { const chain = item; return { refName: chain.refName, source: printApprovalChain(chain, opts.appRefName) }; },
47
- toTf: (entity, ctx) => approvalChainToTf(entity, { appRefName: ctx.appRefName, appTfLabel: ctx.appTfLabel }),
55
+ toTf: (entity, ctx) => approvalChainToTf(entity, { appRefName: ctx.appRefName, appTfLabel: ctx.appTfLabel, stageKeyByTfLabel: appStageKeyByHandle(ctx.streamRootEntity?.payload) }),
48
56
  },
49
57
  canvas: { participates: true, label: "Approval processes", glyph: "✓", component: "generic" },
50
58
  catalog: { participates: true, refKind: "approvalChain", catalogBag: "approvalChains", renderOrder: 26, catalogRoot: "app", renderEntry: rootParentFactoryEntry("approvalChainRef"), stubRef: stub, refFromAuthoring },
@@ -3,6 +3,7 @@ import { type TfBlock } from "../../engine/tf/index.js";
3
3
  export declare function approvalChainToTf(entity: DeployableEntity, ctx: {
4
4
  appRefName: string;
5
5
  appTfLabel: string;
6
+ stageKeyByTfLabel?: ReadonlyMap<string, string>;
6
7
  }): {
7
8
  blocks: readonly TfBlock[];
8
9
  address: string;
@@ -20,7 +20,7 @@ export function approvalChainToTf(entity, ctx) {
20
20
  approve_button_text: payload.approveButton ?? "Approve",
21
21
  };
22
22
  if (payload.stage !== undefined)
23
- attrs["stage_id"] = expr.local(`${ctx.appTfLabel}_stage_ids_by_key`, [{ index: tsLabelToTfLabel(payload.stage) }]);
23
+ attrs["stage_id"] = expr.local(`${ctx.appTfLabel}_stage_ids_by_key`, [{ index: stageIndex(payload.stage, ctx.stageKeyByTfLabel) }]);
24
24
  else if (payload.stageId !== undefined)
25
25
  attrs["stage_id"] = payload.stageId;
26
26
  if (payload.exceptionButton !== undefined)
@@ -44,3 +44,8 @@ export function approvalChainToTf(entity, ctx) {
44
44
  const block = { kind: "resource", type: APPROVAL_PROCESS_RESOURCE_TYPE, label, attrs };
45
45
  return { blocks: [block], address: `${APPROVAL_PROCESS_RESOURCE_TYPE}.${label}` };
46
46
  }
47
+ /** The `stage_ids_by_key` index for a stage handle; imported keys may keep punctuation (#1136). */
48
+ function stageIndex(stage, stageKeyByTfLabel) {
49
+ const tfLabel = tsLabelToTfLabel(stage);
50
+ return stageKeyByTfLabel?.get(tfLabel) ?? tfLabel;
51
+ }
@@ -234,6 +234,8 @@ interface ActionMethods<TTrigger, TActions extends Record<string, unknown>, TVar
234
234
  }, displayName?: string, hclParent?: "trigger" | string): WithAction<TMode, TItem, TTrigger, TActions, TVars, TName, {
235
235
  result: R;
236
236
  textResult: string;
237
+ stringArrayResult: readonly string[];
238
+ numberArrayResult: readonly number[];
237
239
  }>;
238
240
  /**
239
241
  * Fluent setVariable: one variable, named the same as its action — read
@@ -229,8 +229,12 @@ function assertKnownSearchOutput(taskKey, wireNames, name, taskRefKey) {
229
229
  const outputs = Object.keys(wireNames).join(", ");
230
230
  throw new EntityTfError(`${taskKey}${taskRefKey === undefined ? "" : ` task "${taskRefKey}"`} has no output "${name}"; its outputs are ${outputs}.`);
231
231
  }
232
- /** Canonical service_tasks names. They are not authoring accessors. */
233
- const EXECUTE_SCRIPT_CANONICAL_OUTPUT_NAMES = new Set(["stringArrayResult", "numberArrayResult"]);
232
+ /**
233
+ * Contract outputs that are not schema properties under `result`.
234
+ * `stringArrayResult` / `numberArrayResult` are real reads (a filter's
235
+ * `task.<id>.stringArrayResult`), not a missing `.result.` hop (#1656).
236
+ */
237
+ const EXECUTE_SCRIPT_CONTRACT_OUTPUT_NAMES = new Set(["stringArrayResult", "numberArrayResult"]);
234
238
  /**
235
239
  * Top-level property names on a wire `output_schema` object. `undefined` means
236
240
  * the script declared no schema, so a `result.<prop>` cannot be checked.
@@ -261,15 +265,12 @@ function declaredScriptResultProperties(schema) {
261
265
  * `ctx.actions.<script>.<name>` would compile to a `refs["<name>"]` key the
262
266
  * platform never sets, so apply fails with "Invalid index". When the script
263
267
  * declares an output schema, `result.<prop>` is checked against that schema
264
- * too. Authoring names are `result`, `textResult`, and `result.<prop>`.
265
- * `Text Result` is the refs-map key `textResult` rewrites to, not a name
266
- * someone authors. The canonical publish path also accepts the service_tasks
267
- * contract names.
268
+ * too. Authoring names are `result`, `textResult`, `stringArrayResult`,
269
+ * `numberArrayResult`, and `result.<prop>`. `Text Result` / `Result` /
270
+ * `Text List Result` are refs-map keys, not names someone authors (#1656).
268
271
  */
269
- function assertKnownScriptOutput(name, taskRefKey, schema, canonical, checkDeclaredResult) {
270
- if (name === "result" || name === "textResult")
271
- return;
272
- if (canonical && EXECUTE_SCRIPT_CANONICAL_OUTPUT_NAMES.has(name))
272
+ function assertKnownScriptOutput(name, taskRefKey, schema, checkDeclaredResult) {
273
+ if (name === "result" || name === "textResult" || EXECUTE_SCRIPT_CONTRACT_OUTPUT_NAMES.has(name))
273
274
  return;
274
275
  if (name.startsWith("result.")) {
275
276
  // Filter `{type:"TASK"}` shapes are not refs-map reads. A switch left_value
@@ -335,7 +336,7 @@ function rewriteForwardTaskRefName(taskKey, name, taskRefKey, schema, checkDecla
335
336
  return USER_SEARCH_REF_WIRE_NAMES[name] ?? name;
336
337
  }
337
338
  if (taskKey === "executeScript") {
338
- assertKnownScriptOutput(name, taskRefKey, schema, false, checkDeclaredScriptResult);
339
+ assertKnownScriptOutput(name, taskRefKey, schema, checkDeclaredScriptResult);
339
340
  if (name === "textResult")
340
341
  return "Text Result";
341
342
  }
@@ -379,8 +380,9 @@ export function rewriteCanonicalOutputRefName(taskKey, name, taskRefKey, schema)
379
380
  if (taskKey === "findRelatedRecords" && FIND_RELATED_RECORDS_COUNT_REF_NAMES.has(name.split(".")[0])) {
380
381
  throw findRelatedRecordsTotalCountError(taskRefKey);
381
382
  }
383
+ // Workflow outputs are jsonencode envelopes on the task id, not refs-map indexes.
382
384
  if (taskKey === "executeScript")
383
- assertKnownScriptOutput(name, taskRefKey, schema, true, true);
385
+ assertKnownScriptOutput(name, taskRefKey, schema, false);
384
386
  if (taskKey === "api" && name.startsWith("file.")) {
385
387
  // apiRequest's file SUB-refs (.file.content / .contentType / .name) have no
386
388
  // canonical service_tasks output name of their own — they resolve by the
@@ -463,10 +465,12 @@ function rewriteTaskOutputRefs(node, taskKindByRefKey, scriptSchemas,
463
465
  // platform's CANONICAL service_tasks output name (edk#835). Task inputs and
464
466
  // filters (canonical=false, the default) keep the display rewrite — #1271 owns
465
467
  // those positions.
466
- canonical = false) {
468
+ canonical = false,
469
+ // Field assignments rebuild an undeclared result.* as the value envelope.
470
+ checkDeclaredScriptResult = true) {
467
471
  if (Array.isArray(node)) {
468
472
  for (const item of node)
469
- rewriteTaskOutputRefs(item, taskKindByRefKey, scriptSchemas, canonical);
473
+ rewriteTaskOutputRefs(item, taskKindByRefKey, scriptSchemas, canonical, checkDeclaredScriptResult);
470
474
  return;
471
475
  }
472
476
  if (node === null || typeof node !== "object")
@@ -488,8 +492,11 @@ canonical = false) {
488
492
  }
489
493
  const ref = rec.taskReference;
490
494
  if (ref && typeof ref.taskRefKey === "string" && typeof ref.name === "string") {
491
- const rewrite = canonical ? rewriteCanonicalOutputRefName : rewriteForwardTaskRefName;
492
- ref.name = rewrite(taskKindByRefKey.get(ref.taskRefKey), ref.name, ref.taskRefKey, scriptSchemas.get(ref.taskRefKey));
495
+ const kind = taskKindByRefKey.get(ref.taskRefKey);
496
+ const schema = scriptSchemas.get(ref.taskRefKey);
497
+ ref.name = canonical
498
+ ? rewriteCanonicalOutputRefName(kind, ref.name, ref.taskRefKey, schema)
499
+ : rewriteForwardTaskRefName(kind, ref.name, ref.taskRefKey, schema, checkDeclaredScriptResult);
493
500
  }
494
501
  if (rec.type === "TASK" && typeof rec.taskRefKey === "string" && typeof rec.name === "string") {
495
502
  // Filter `{type:"TASK"}` shapes never appear in a workflow OUTPUT subtree;
@@ -501,7 +508,8 @@ canonical = false) {
501
508
  // keeps the display/forward rewrite even under an output, so its decode
502
509
  // (decodeCalculationTaskMustache) stays idempotent.
503
510
  const childCanonical = key === "calculationReference" ? false : canonical;
504
- rewriteTaskOutputRefs(v, taskKindByRefKey, scriptSchemas, childCanonical);
511
+ const childCheck = key === "workflowFields" ? false : checkDeclaredScriptResult;
512
+ rewriteTaskOutputRefs(v, taskKindByRefKey, scriptSchemas, childCanonical, childCheck);
505
513
  }
506
514
  }
507
515
  /**
@@ -119,6 +119,7 @@ export type TriggerAst = {
119
119
  app: AppRefAst | UnresolvedRefAst;
120
120
  approvalChain?: string | ApprovalChainRefAst;
121
121
  status: "ACTIVE" | "STEP_APPROVED" | "CANCELLED" | "DENIED" | "APPROVED";
122
+ filter?: Filter<RefExpr, RefExpr>;
122
123
  } | {
123
124
  kind: "schedule";
124
125
  frequency: "HOURLY" | "DAILY" | "WEEKLY" | "MONTHLY";
@@ -150,6 +151,8 @@ export interface AutomationAst {
150
151
  readonly triggersOtherAutomations?: boolean;
151
152
  readonly status: AutomationStatus;
152
153
  readonly serviceAccountName?: string;
154
+ /** Owning app's catalog key when the service account belongs to another app. */
155
+ readonly serviceAccountAppRefName?: string;
153
156
  readonly trigger: TriggerAst;
154
157
  readonly tasks: readonly TaskCall[];
155
158
  readonly outputs?: readonly {
@@ -41,9 +41,11 @@ import type { MergePulledSourceContext, UnresolvedReferenceDiagnostic } from "..
41
41
  * least the baseline — the state revision, or the freshly printed live revision
42
42
  * when state has no entry yet (adoption is about to import it). An older
43
43
  * authored token is replaced by that baseline. Without readable state the
44
- * pre-#1590 behaviour (always keep authored) is unchanged.
44
+ * pre-#1590 behaviour (always keep authored) is unchanged. With no existing
45
+ * source, a publish already bound in state keeps the state revision: the
46
+ * export prints `1.0.<live version>`, which Read never writes back (#1902).
45
47
  */
46
- export declare function preserveAuthoredAutomationRevision(freshSource: string, existingSource: string, context?: MergePulledSourceContext): string;
48
+ export declare function preserveAuthoredAutomationRevision(freshSource: string, existingSource: string | undefined, context?: MergePulledSourceContext): string;
47
49
  /**
48
50
  * Extract a string-literal (or `+`-concatenated literals) description from
49
51
  * authored automation source. Pull reprints often omit description entirely
@@ -77,7 +79,7 @@ export declare function extractAuthoredAutomationDescription(source: string): st
77
79
  */
78
80
  export declare function preserveAuthoredAutomationDescription(freshSource: string, existingSource: string): string;
79
81
  /** Pull merge: preserve authored revision + description across live reprint. */
80
- export declare function preserveAuthoredAutomationPullMeta(freshSource: string, existingSource: string, context?: MergePulledSourceContext): string;
82
+ export declare function preserveAuthoredAutomationPullMeta(freshSource: string, existingSource: string | undefined, context?: MergePulledSourceContext): string;
81
83
  /** A plain-JS script file printed beside the automation, relative to the automations folder. */
82
84
  export interface PrintedScriptFile {
83
85
  readonly path: string;