@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
@@ -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
+ }
@@ -38,6 +38,7 @@ import { appServiceAccountBlocks } from "../service-account/to-tf.js";
38
38
  import { relationshipTargetsFromBag, widgetsToTf } from "../widget/to-tf.js";
39
39
  import { viewToTf } from "../view/to-tf.js";
40
40
  import { APP_RESOURCE_TYPE } from "./module.js";
41
+ import { DEFAULT_APP_STAGES, stageKeyByHandle, stageKeyFromPicklistValue } from "./stage-keys.js";
41
42
  /**
42
43
  * The named gap for a system-field tag with no canonical key (edk#1480).
43
44
  * Defensive: every tag in SYSTEM_FIELD_TAGS maps today, so a new tag lands
@@ -137,9 +138,8 @@ export function appToTf(entity, ctx) {
137
138
  const fieldMetadata = fieldMetadataFromEntries(payload.fields);
138
139
  const fieldNames = new Map();
139
140
  let statusOptions;
140
- let stages;
141
141
  const systemFieldConfig = {};
142
- const stageTfLabels = new Set();
142
+ let stageKeys;
143
143
  const objectId = expr.resourceAttr(APP_RESOURCE_TYPE, ctx.appTfLabel, ["id"]);
144
144
  const fieldDisplayNames = new Map();
145
145
  for (const fieldEntry of payload.fields ?? []) {
@@ -208,12 +208,9 @@ export function appToTf(entity, ctx) {
208
208
  ctx.diagnostics.push(`systemFields.stage: the provider has no stage field name attribute; authored name "${name}" dropped (field stays "Stage")`);
209
209
  }
210
210
  if (inner.picklistValues !== undefined) {
211
- stages = inner.picklistValues.map((pv) => {
212
- const label = picklistLabel(pv);
213
- const key = snakeSlug(label);
214
- stageTfLabels.add(key);
215
- return { key, name: label };
216
- });
211
+ // An imported stage keeps its alias (`__stageKey`, #1136); an
212
+ // authored one derives snakeSlug(label).
213
+ stageKeys = inner.picklistValues.map(stageKeyFromPicklistValue);
217
214
  }
218
215
  break;
219
216
  default: {
@@ -254,17 +251,12 @@ export function appToTf(entity, ctx) {
254
251
  appAttrs["status_options"] = statusOptions === undefined || statusOptions.length === 0
255
252
  ? DEPLOY_DEFAULT_STATUS_OPTION_VALUES.map((option) => ({ ...option, tags: [...option.tags] }))
256
253
  : statusOptions;
257
- if (stages === undefined || stages.length === 0) {
258
- appAttrs["stages"] = [
259
- { key: "stage_1", name: "Stage 1" },
260
- { key: "stage_2", name: "Stage 2" },
261
- ];
262
- stageTfLabels.add("stage_1");
263
- stageTfLabels.add("stage_2");
264
- }
265
- else {
266
- appAttrs["stages"] = stages;
267
- }
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());
268
260
  // --- View pass: layouts / list views / view order (entities/view), owner passed in.
269
261
  blocks.push(...dashboardsToTf(payload.dashboards, {
270
262
  ownerTfLabel: ctx.appTfLabel,
@@ -295,11 +287,14 @@ export function appToTf(entity, ctx) {
295
287
  ownerTfLabel: ctx.appTfLabel,
296
288
  objectId,
297
289
  stageTfLabels,
290
+ stageKeyByTfLabel,
298
291
  dashboardKeys: new Set(Object.keys(payload.dashboards ?? {})),
299
292
  orgRefs: ctx.orgRefs,
300
293
  workspaceAspects: ctx.workspaceAspects,
301
294
  diagnostics: ctx.diagnostics,
302
295
  fieldAddresses,
296
+ fieldNames,
297
+ fieldMetadata,
303
298
  widgetKeys: new Set(Object.keys(payload.widgets ?? {})),
304
299
  }, payload.customViews);
305
300
  blocks.push(...viewBlocks);
@@ -322,6 +317,7 @@ export function appToTf(entity, ctx) {
322
317
  workspaceAspects: ctx.workspaceAspects,
323
318
  fieldAddresses,
324
319
  widgetKeys: new Set(Object.keys(payload.widgets ?? {})),
320
+ stageKeyByTfLabel,
325
321
  }));
326
322
  blocks.push(...relationshipsToTf(payload.relationships, {
327
323
  ownerRefName: ctx.appRefName,
@@ -349,7 +345,7 @@ export function appToTf(entity, ctx) {
349
345
  appRefName: ctx.appRefName,
350
346
  serviceAccounts: payload.serviceAccounts,
351
347
  fieldAddresses,
352
- resolveServiceAccountApp: workspaceServiceAccountAppResolver(ctx.workspaceAspects),
348
+ resolveServiceAccountApp: workspaceServiceAccountAppResolver(ctx.workspaceAspects, { apps: ctx.outOfScopeApps, orgRefs: ctx.orgRefs }),
353
349
  });
354
350
  blocks.push(block);
355
351
  }
@@ -361,7 +357,7 @@ export function appToTf(entity, ctx) {
361
357
  serviceAccounts: payload.serviceAccounts,
362
358
  orgRefs: ctx.orgRefs,
363
359
  diagnostics: ctx.diagnostics,
364
- resolveServiceAccountApp: workspaceServiceAccountAppResolver(ctx.workspaceAspects),
360
+ resolveServiceAccountApp: workspaceServiceAccountAppResolver(ctx.workspaceAspects, { apps: ctx.outOfScopeApps, orgRefs: ctx.orgRefs }),
365
361
  }));
366
362
  blocks.push(...appServiceAccountBlocks(payload, {
367
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
+ }
@@ -380,8 +380,9 @@ export function rewriteCanonicalOutputRefName(taskKey, name, taskRefKey, schema)
380
380
  if (taskKey === "findRelatedRecords" && FIND_RELATED_RECORDS_COUNT_REF_NAMES.has(name.split(".")[0])) {
381
381
  throw findRelatedRecordsTotalCountError(taskRefKey);
382
382
  }
383
+ // Workflow outputs are jsonencode envelopes on the task id, not refs-map indexes.
383
384
  if (taskKey === "executeScript")
384
- assertKnownScriptOutput(name, taskRefKey, schema, true);
385
+ assertKnownScriptOutput(name, taskRefKey, schema, false);
385
386
  if (taskKey === "api" && name.startsWith("file.")) {
386
387
  // apiRequest's file SUB-refs (.file.content / .contentType / .name) have no
387
388
  // canonical service_tasks output name of their own — they resolve by the
@@ -464,10 +465,12 @@ function rewriteTaskOutputRefs(node, taskKindByRefKey, scriptSchemas,
464
465
  // platform's CANONICAL service_tasks output name (edk#835). Task inputs and
465
466
  // filters (canonical=false, the default) keep the display rewrite — #1271 owns
466
467
  // those positions.
467
- canonical = false) {
468
+ canonical = false,
469
+ // Field assignments rebuild an undeclared result.* as the value envelope.
470
+ checkDeclaredScriptResult = true) {
468
471
  if (Array.isArray(node)) {
469
472
  for (const item of node)
470
- rewriteTaskOutputRefs(item, taskKindByRefKey, scriptSchemas, canonical);
473
+ rewriteTaskOutputRefs(item, taskKindByRefKey, scriptSchemas, canonical, checkDeclaredScriptResult);
471
474
  return;
472
475
  }
473
476
  if (node === null || typeof node !== "object")
@@ -489,8 +492,11 @@ canonical = false) {
489
492
  }
490
493
  const ref = rec.taskReference;
491
494
  if (ref && typeof ref.taskRefKey === "string" && typeof ref.name === "string") {
492
- const rewrite = canonical ? rewriteCanonicalOutputRefName : rewriteForwardTaskRefName;
493
- 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);
494
500
  }
495
501
  if (rec.type === "TASK" && typeof rec.taskRefKey === "string" && typeof rec.name === "string") {
496
502
  // Filter `{type:"TASK"}` shapes never appear in a workflow OUTPUT subtree;
@@ -502,7 +508,8 @@ canonical = false) {
502
508
  // keeps the display/forward rewrite even under an output, so its decode
503
509
  // (decodeCalculationTaskMustache) stays idempotent.
504
510
  const childCanonical = key === "calculationReference" ? false : canonical;
505
- rewriteTaskOutputRefs(v, taskKindByRefKey, scriptSchemas, childCanonical);
511
+ const childCheck = key === "workflowFields" ? false : checkDeclaredScriptResult;
512
+ rewriteTaskOutputRefs(v, taskKindByRefKey, scriptSchemas, childCanonical, childCheck);
506
513
  }
507
514
  }
508
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;