@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,292 @@
1
+ import { EntityTfError } from "../../engine/entity.js";
2
+ const CONTAINERS = new Set(["PanesBlock", "StackBlock", "RowBlock", "CardBlock"]);
3
+ const LIST_BLOCKS = new Set(["ListCollectionBlock", "DataTableBlock"]);
4
+ const FILTER_GROUPS = new Set(["AND", "OR"]);
5
+ /** The record query ignores "not" on these, so the filter silently means the opposite. */
6
+ const NOT_IGNORED = new Set(["AND", "OR", "CONSECUTIVE_RANGE", "CURRENT_RANGE"]);
7
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
8
+ const AVG_CALL = /\bAVG\(/;
9
+ const EMPTY_COUNT = /COUNT\(\s*\)/;
10
+ const SELECTION_KEYS = ["selectedId", "selectedAspectId", "selectedHandle"];
11
+ function isObj(v) {
12
+ return v !== null && typeof v === "object" && !Array.isArray(v);
13
+ }
14
+ /** Any binding shape ($state / $bindState / $item / $index). Used for state-initial scans. */
15
+ function isBinding(v) {
16
+ return isObj(v) && ("$state" in v || "$bindState" in v || "$item" in v || "$index" in v);
17
+ }
18
+ /** Selection props must be $state / $bindState — $item / $index do not drive the details pane. */
19
+ function isStateBinding(v) {
20
+ return isObj(v) && ("$state" in v || "$bindState" in v);
21
+ }
22
+ /**
23
+ * Offline Layer 1 checks that Javier's check.mjs runs before paste.
24
+ * Call only for `customViews.*.layout` (strictStructure).
25
+ * Collects every problem, then throws once (parity with Go / check.mjs).
26
+ */
27
+ export function validateCustomViewLayout(spec, where, opts = {}) {
28
+ const problems = [];
29
+ const note = (at, msg) => {
30
+ problems.push(`${at}: ${msg}`);
31
+ };
32
+ /** check.mjs warn-class issues: do not fail build/pull of live layouts. */
33
+ const warn = (at, msg) => {
34
+ opts.diagnostics?.push(`${at}: ${msg}`);
35
+ };
36
+ if (!isObj(spec)) {
37
+ throw new EntityTfError(`${where}: must be an object`);
38
+ }
39
+ const json = JSON.stringify(spec);
40
+ const leftovers = [...new Set(json.match(/\{\{[^}]+\}\}/g) ?? [])];
41
+ if (leftovers.length > 0) {
42
+ note(`${where}.placeholders`, `fill these from the app's fields: ${leftovers.slice(0, 8).join(", ")}${leftovers.length > 8 ? ", ..." : ""}`);
43
+ }
44
+ const root = spec["root"];
45
+ const elementsRaw = spec["elements"];
46
+ if (typeof root !== "string" || root === "") {
47
+ note(`${where}.root`, "must name an element");
48
+ }
49
+ if (!isObj(elementsRaw) || Object.keys(elementsRaw).length === 0) {
50
+ note(`${where}.elements`, "must have at least one element");
51
+ throwIf(problems);
52
+ return;
53
+ }
54
+ const elements = elementsRaw;
55
+ if (typeof root !== "string" || root === "") {
56
+ throwIf(problems);
57
+ return;
58
+ }
59
+ if (!(root in elements)) {
60
+ note(`${where}.root`, `"${root}" is not an element`);
61
+ throwIf(problems);
62
+ return;
63
+ }
64
+ const rootEl = elements[root];
65
+ const rootType = isObj(rootEl) && typeof rootEl["type"] === "string" ? rootEl["type"] : "";
66
+ // check.mjs warns on any non-PanesBlock root. We error only when a live list
67
+ // needs the details pane — chart/StackBlock dashboards without lists stay valid.
68
+ const hasLiveList = Object.values(elements).some((raw) => {
69
+ if (!isObj(raw) || !isObj(raw["props"]))
70
+ return false;
71
+ const t = raw["type"];
72
+ return typeof t === "string" && LIST_BLOCKS.has(t) && raw["props"]["aspectId"] !== undefined;
73
+ });
74
+ if (hasLiveList && rootType !== "PanesBlock") {
75
+ note(`${where}.root`, `"${root}" must be a PanesBlock (got ${rootType === "" ? "no type" : `"${rootType}"`}); a live list needs a panes root so rows can open the details panel`);
76
+ }
77
+ else if (rootType !== "PanesBlock") {
78
+ // check.mjs: warn('spec.root', 'the root is usually a PanesBlock ...').
79
+ opts.diagnostics?.push(`${where}.root: "${root}" is ${rootType === "" ? "untyped" : `a ${rootType}`}; the root is usually a PanesBlock (needed for record lists to open the details pane)`);
80
+ }
81
+ const state = isObj(spec["state"]) ? spec["state"] : {};
82
+ const parents = {};
83
+ for (const [id, raw] of Object.entries(elements)) {
84
+ const elWhere = `${where}.elements.${id}`;
85
+ if (!isObj(raw) || typeof raw["type"] !== "string") {
86
+ note(elWhere, "each element needs a \"type\"");
87
+ continue;
88
+ }
89
+ if (!isObj(raw["props"])) {
90
+ note(elWhere, "each element needs a \"props\" object (use {} when empty)");
91
+ continue;
92
+ }
93
+ const children = raw["children"];
94
+ if (children !== undefined) {
95
+ if (!Array.isArray(children)) {
96
+ note(elWhere, "\"children\" must be a list of element ids");
97
+ }
98
+ else {
99
+ // Intended promotion (edk#1771): check.mjs only warns here. The page does not
100
+ // render these children, so EDK fails closed, same as the Go provider.
101
+ if (children.length > 0 && !CONTAINERS.has(raw["type"])) {
102
+ note(elWhere, `${raw["type"]} does not render children; only ${[...CONTAINERS].join(", ")} do`);
103
+ }
104
+ if (raw["repeat"] !== undefined && children.length === 0) {
105
+ note(`${elWhere}.repeat`, "a repeated element needs a child element as its template; the page will fail to render this custom view");
106
+ }
107
+ for (const child of children) {
108
+ if (typeof child !== "string" || !(child in elements)) {
109
+ note(`${elWhere}.children`, `"${String(child)}" is not an element; the page will fail to render this custom view`);
110
+ }
111
+ else {
112
+ (parents[child] ??= []).push(id);
113
+ }
114
+ }
115
+ }
116
+ }
117
+ else if (raw["repeat"] !== undefined) {
118
+ note(`${elWhere}.repeat`, "a repeated element needs a child element as its template; the page will fail to render this custom view");
119
+ }
120
+ }
121
+ for (const [child, list] of Object.entries(parents)) {
122
+ if (list.length > 1) {
123
+ note(`${where}.elements.${child}`, `used by several parents (${list.join(", ")}); give each placement its own element`);
124
+ }
125
+ }
126
+ const reachable = new Set();
127
+ const visit = (id, path) => {
128
+ if (path.includes(id)) {
129
+ note(`${where}.elements.${id}`, `cycle: ${[...path, id].join(" -> ")}`);
130
+ return;
131
+ }
132
+ if (reachable.has(id) || !(id in elements))
133
+ return;
134
+ reachable.add(id);
135
+ const children = elements[id]["children"];
136
+ if (Array.isArray(children)) {
137
+ for (const child of children)
138
+ if (typeof child === "string")
139
+ visit(child, [...path, id]);
140
+ }
141
+ };
142
+ visit(root, []);
143
+ for (const id of Object.keys(elements)) {
144
+ if (!reachable.has(id)) {
145
+ warn(`${where}.elements.${id}`, "not reachable from the root, so it never renders");
146
+ }
147
+ }
148
+ const readState = (path) => {
149
+ let node = state;
150
+ for (const part of path.split("/").filter(Boolean)) {
151
+ if (!isObj(node) || !(part in node))
152
+ return { found: false };
153
+ node = node[part];
154
+ }
155
+ return { found: true, value: node };
156
+ };
157
+ const walkedState = new Set();
158
+ const walkFilter = (node, filterWhere) => {
159
+ if (node == null)
160
+ return;
161
+ if (!isObj(node)) {
162
+ note(filterWhere, "a filter must be an object");
163
+ return;
164
+ }
165
+ if (node["not"] === true && typeof node["type"] === "string" && NOT_IGNORED.has(node["type"])) {
166
+ const type = node["type"];
167
+ note(filterWhere, type === "AND" || type === "OR"
168
+ ? `"not" is ignored on ${type} groups. Negate each child instead (not A and not B, instead of not (A or B)).`
169
+ : `"not" is ignored on ${type}. For "older than N", use a positive range that ends N units ago, e.g. { "type": "CONSECUTIVE_RANGE", "count": 3650, "offset": 30, "unit": "DAY" }.`);
170
+ }
171
+ if (FILTER_GROUPS.has(node["type"])) {
172
+ if (!Array.isArray(node["children"])) {
173
+ note(filterWhere, `${node["type"]} needs a "children" list`);
174
+ return;
175
+ }
176
+ node["children"].forEach((c, i) => walkFilter(c, `${filterWhere}.children[${i}]`));
177
+ return;
178
+ }
179
+ if (typeof node["type"] !== "string") {
180
+ note(filterWhere, "filter node is missing \"type\"");
181
+ }
182
+ // Leaf filters without field / leftValue stay on the platform validator.
183
+ };
184
+ for (const [id, raw] of Object.entries(elements)) {
185
+ if (!isObj(raw) || !isObj(raw["props"]))
186
+ continue;
187
+ const elWhere = `${where}.elements.${id}`;
188
+ const props = raw["props"];
189
+ const type = raw["type"];
190
+ const scan = (value, path) => {
191
+ if (isBinding(value)) {
192
+ const target = value["$state"] ?? value["$bindState"];
193
+ if (typeof target === "string" && !target.startsWith("/host/") && !readState(target).found) {
194
+ note(`${elWhere}.${path}`, `binds to "${target}", which is not in spec.state. Add an initial value there.`);
195
+ }
196
+ return;
197
+ }
198
+ if (Array.isArray(value))
199
+ value.forEach((v, i) => scan(v, `${path}[${i}]`));
200
+ else if (isObj(value))
201
+ for (const [k, v] of Object.entries(value))
202
+ scan(v, `${path}.${k}`);
203
+ };
204
+ for (const [key, value] of Object.entries(props))
205
+ scan(value, key);
206
+ if (props["filterJson"] !== undefined) {
207
+ if (isBinding(props["filterJson"])) {
208
+ const target = props["filterJson"]["$bindState"]
209
+ ?? props["filterJson"]["$state"];
210
+ const initial = typeof target === "string" ? readState(target) : { found: false };
211
+ if (initial.found && initial.value != null && typeof target === "string" && !walkedState.has(target)) {
212
+ walkedState.add(target);
213
+ walkFilter(initial.value, `${where}.state${target.replaceAll("/", ".")}`);
214
+ }
215
+ }
216
+ else {
217
+ walkFilter(props["filterJson"], `${elWhere}.filterJson`);
218
+ }
219
+ }
220
+ if (typeof props["calc"] === "string") {
221
+ const calc = props["calc"];
222
+ if (AVG_CALL.test(calc))
223
+ note(`${elWhere}.calc`, "use AVERAGE, not AVG");
224
+ if (EMPTY_COUNT.test(calc))
225
+ note(`${elWhere}.calc`, "COUNT needs a field, e.g. COUNT(\"Title\")");
226
+ }
227
+ if (type === "ChartBlock" && (typeof props["dateFieldId"] === "string" || isObj(props["dateFieldId"]))) {
228
+ const range = props["range"];
229
+ if (typeof range === "string") {
230
+ const [a, b, extra] = range.split("/");
231
+ if (extra !== undefined || !DATE.test(a ?? "") || !DATE.test(b ?? "")) {
232
+ note(`${elWhere}.range`, `"${range}" is not a fixed date range. Relative presets like last90Days do not apply to date-series charts; use "YYYY-MM-DD/YYYY-MM-DD"`);
233
+ }
234
+ else if (a > b) {
235
+ note(`${elWhere}.range`, "start date is after end date");
236
+ }
237
+ }
238
+ }
239
+ // Live lists on a custom view need all three selection bindings as $state /
240
+ // $bindState so the details pane opens. $item / $index do not count.
241
+ // Warn-only: pulled Blueprint layouts omit these and must still build.
242
+ if (LIST_BLOCKS.has(type) && props["aspectId"] !== undefined) {
243
+ const missing = SELECTION_KEYS.filter((key) => !isStateBinding(props[key]));
244
+ if (missing.length > 0) {
245
+ warn(elWhere, `live list without selectedId/selectedAspectId/selectedHandle bindings; rows will not open the details pane (missing or not $state/$bindState: ${missing.join(", ")})`);
246
+ }
247
+ }
248
+ }
249
+ throwIf(problems);
250
+ }
251
+ function throwIf(problems) {
252
+ if (problems.length === 0)
253
+ return;
254
+ throw new EntityTfError(problems.join("\n"));
255
+ }
256
+ /** Soft version used by agent views: same tree checks as today (diagnostics, not fatal). */
257
+ export function reportStructureProblems(_root, elements, where, diagnostics) {
258
+ for (const [id, raw] of Object.entries(elements)) {
259
+ const children = isObj(raw) ? raw["children"] : undefined;
260
+ if (isObj(raw) && raw["repeat"] !== undefined && (!Array.isArray(children) || children.length === 0)) {
261
+ diagnostics.push(`${where}.elements.${id}.repeat: a repeated element needs a child element as its template; the page will fail to render this custom view`);
262
+ }
263
+ if (!Array.isArray(children))
264
+ continue;
265
+ for (const child of children) {
266
+ if (typeof child !== "string" || !(child in elements)) {
267
+ diagnostics.push(`${where}.elements.${id}.children: "${String(child)}" is not an element; the page will fail to render this custom view`);
268
+ }
269
+ }
270
+ }
271
+ const state = new Map();
272
+ let cycle;
273
+ const visit = (id, path) => {
274
+ if (cycle !== undefined || state.get(id) === "done")
275
+ return;
276
+ if (state.get(id) === "visiting") {
277
+ cycle = [...path, id].join(" → ");
278
+ return;
279
+ }
280
+ state.set(id, "visiting");
281
+ const children = isObj(elements[id]) ? elements[id]["children"] : undefined;
282
+ if (Array.isArray(children))
283
+ for (const child of children)
284
+ if (typeof child === "string" && child in elements)
285
+ visit(child, [...path, id]);
286
+ state.set(id, "done");
287
+ };
288
+ for (const id of Object.keys(elements))
289
+ visit(id, []);
290
+ if (cycle !== undefined)
291
+ diagnostics.push(`${where}: children form a cycle (${cycle}); the page will fail to render this custom view`);
292
+ }
@@ -21,6 +21,8 @@ export interface ViewOwner {
21
21
  readonly scope?: ChildResourceScope;
22
22
  /** Stage keys declared by the owning app, used when ei exports a raw stage UUID. */
23
23
  readonly stageKeys?: ReadonlySet<string>;
24
+ /** The owning app's stage handles → real stage keys (see `stageKeyByHandle`, #1136). */
25
+ readonly stageKeyByHandle?: ReadonlyMap<string, string>;
24
26
  }
25
27
  export interface ViewsFromTfResult {
26
28
  readonly layouts: readonly NormalizedLayout[];
@@ -8,14 +8,15 @@
8
8
  import { agentViewLayoutFromTf, viewBlocksFromTf, } from "./agent-view-layout-from-tf.js";
9
9
  import { dataRefLabel, optionalString, plainObject, resourceRefLabel } from "../../engine/pull/context.js";
10
10
  import { reportUnknownAttrs } from "../../engine/pull/attrs.js";
11
- import { isTfExpr, isTfLabel, scopedLabelToBagKey, tfLabelToTsLabel } from "../../engine/tf/index.js";
11
+ import { isTfExpr, scopedLabelToBagKey, tfLabelToTsLabel, tsLabelToTfLabel } from "../../engine/tf/index.js";
12
+ import { lostStageMessage, pulledStageHandle } from "../app/stage-keys.js";
12
13
  import { decodeForeignDataField, fieldKeyFromTfValue } from "../field/from-tf.js";
13
14
  import { resolveDataAspectTarget } from "../shared/aspect-target-from-tf.js";
14
15
  import { DASHBOARD_RESOURCE_TYPE } from "../dashboard/module.js";
15
16
  import { WIDGET_RESOURCE_TYPE } from "../widget/module.js";
16
17
  import { filterFromTf, principalList } from "../access-policy/from-tf.js";
17
18
  import { listViewDensity, } from "./build.js";
18
- import { AGENT_VIEW_RESOURCE_TYPE, CALENDAR_VIEW_RESOURCE_TYPE, CUSTOM_VIEW_RESOURCE_TYPE, DASHBOARD_VIEW_RESOURCE_TYPE, GROUP_SECTION_WIRE_TYPE, KNOWN_AGENT_VIEW_ATTRS, KNOWN_CALENDAR_VIEW_ATTRS, KNOWN_CUSTOM_VIEW_ATTRS, KNOWN_DASHBOARD_VIEW_ATTRS, KNOWN_KANBAN_VIEW_ATTRS, KNOWN_LAYOUT_ATTRS, KNOWN_LAYOUT_SECTION_ATTRS, KNOWN_LIST_VIEW_ATTRS, KNOWN_MANAGED_VIEW_ORDER_ATTRS, LIST_VIEW_RESOURCE_TYPE, KANBAN_VIEW_RESOURCE_TYPE, SECTION_TYPE_FROM_WIRE, SYSTEM_FIELD_KEY_BY_ID_ATTR, UPDATE_SECTION_WIRE_TYPE, } from "./types.js";
19
+ import { AGENT_VIEW_RESOURCE_TYPE, CALENDAR_VIEW_RESOURCE_TYPE, CUSTOM_VIEW_RESOURCE_TYPE, LAYOUT_RESOURCE_TYPE, DASHBOARD_VIEW_RESOURCE_TYPE, GROUP_SECTION_WIRE_TYPE, KNOWN_AGENT_VIEW_ATTRS, KNOWN_CALENDAR_VIEW_ATTRS, KNOWN_CUSTOM_VIEW_ATTRS, KNOWN_DASHBOARD_VIEW_ATTRS, KNOWN_KANBAN_VIEW_ATTRS, KNOWN_LAYOUT_ATTRS, KNOWN_LAYOUT_SECTION_ATTRS, KNOWN_LIST_VIEW_ATTRS, KNOWN_MANAGED_VIEW_ORDER_ATTRS, LIST_VIEW_RESOURCE_TYPE, KANBAN_VIEW_RESOURCE_TYPE, SECTION_TYPE_FROM_WIRE, SYSTEM_FIELD_KEY_BY_ID_ATTR, UPDATE_SECTION_WIRE_TYPE, } from "./types.js";
19
20
  function viewFilter(value, owner, where, ctx) {
20
21
  return value === undefined ? undefined : filterFromTf(value, {
21
22
  type: owner.type,
@@ -382,12 +383,45 @@ function layoutFromTf(block, owner, ctx) {
382
383
  }
383
384
  const stageIndex = stageIndexFromTf(attrs["stage_id"], owner.label);
384
385
  const labelStageKey = scopedLabelToBagKey(owner.ownerTfLabel, label, scope);
385
- // Layout bag keys are tsLabels; an index outside the tfLabel alphabet keeps
386
- // the key derived from the resource label instead.
387
- const stageKey = stageIndex !== undefined && isTfLabel(stageIndex) ? tfLabelToTsLabel(stageIndex) : undefined;
386
+ // Layout bag keys are tsLabels. An imported index that keeps punctuation
387
+ // ("pre-approval") uses its slug handle, which build maps back to the real
388
+ // key (#1136); an index with no handle keeps the resource-label key.
389
+ // ei names the layout resource SanitizeName(stage name), not the stage key.
390
+ // When that label is itself a handle for this same stage (a rename's
391
+ // `renamed_stage` for key `legacy_key`, `foo_bar` for key `foo__bar`), keep
392
+ // it as the bag key so build re-emits the same address; build still maps
393
+ // the handle back to the real key for stage_id.
394
+ const labelHandle = tsLabelToTfLabel(labelStageKey);
395
+ const labelStageOwner = owner.stageKeyByHandle?.get(labelHandle);
396
+ const labelIsStageHandle = stageIndex !== undefined && labelStageOwner === stageIndex;
397
+ const stageHandles = owner.stageKeyByHandle !== undefined && owner.stageKeys !== undefined
398
+ ? { byHandle: owner.stageKeyByHandle, keys: owner.stageKeys }
399
+ : undefined;
400
+ // Never write a handle that build maps to another stage: a stage whose only
401
+ // handle is another stage's own key (`pre-approval` next to `pre_approval`)
402
+ // keeps its live layout unmanaged, with a warning (#1136).
403
+ const pulled = stageIndex === undefined || labelIsStageHandle ? undefined : pulledStageHandle(stageIndex, stageHandles);
404
+ const unmanaged = (lost) => {
405
+ ctx.diagnostics.push(lostStageMessage(where, stageIndex ?? "", lost, "the layout is left unmanaged"));
406
+ ctx.skipped.push(`${LAYOUT_RESOURCE_TYPE}.${label}`);
407
+ // Never authorable, so release an earlier adoption rather than destroy it.
408
+ ctx.releaseIfManaged?.push(`${LAYOUT_RESOURCE_TYPE}.${label}`);
409
+ return undefined;
410
+ };
411
+ if (pulled?.kind === "lost")
412
+ return unmanaged(pulled);
413
+ const stageHandle = stageIndex === undefined ? undefined : labelIsStageHandle ? labelHandle : pulled?.kind === "handle" ? pulled.handle : undefined;
414
+ const stageKey = stageHandle === undefined ? undefined : tfLabelToTsLabel(stageHandle);
415
+ // The fallback bag key is the layout's own label; never let it name another stage.
416
+ if (stageIndex !== undefined && stageKey === undefined && labelStageOwner !== undefined && labelStageOwner !== stageIndex) {
417
+ return unmanaged({ handle: labelHandle, owner: labelStageOwner });
418
+ }
419
+ if (stageIndex !== undefined && stageHandle !== undefined && labelStageOwner !== undefined && labelStageOwner !== stageIndex) {
420
+ ctx.diagnostics.push(`${where}: the layout's label "${labelHandle}" is a handle of stage "${labelStageOwner}", but it belongs to stage "${stageIndex}"; it is re-addressed under "${stageHandle}", so the next plan destroys and recreates it (#1136)`);
421
+ }
388
422
  const canInferStageKey = typeof attrs["stage_id"] === "string" && owner.stageKeys?.has(labelStageKey) === true;
389
423
  if (stageIndex !== undefined && stageKey === undefined) {
390
- ctx.diagnostics.push(`${where}: stage key ${JSON.stringify(stageIndex)} is outside the terraform label alphabet; using the layout's own label "${label}" as the stage key`);
424
+ ctx.diagnostics.push(`${where}: stage key ${JSON.stringify(stageIndex)} has no terraform label handle; using the layout's own label "${label}" as the stage key`);
391
425
  }
392
426
  else if (stageKey === undefined && !canInferStageKey) {
393
427
  ctx.diagnostics.push(`${where}: stage_id is not a "local.${owner.label}_stage_ids_by_key[...]" reference; using the layout's own label "${label}" as the stage key (may not match the platform's real stage key)`);
@@ -1,7 +1,7 @@
1
1
  /** The view entity's registry entries (see src/graph/). */
2
2
  import { asNamedRef, namedFactoryEntry } from "../../catalog/render-helpers.js";
3
3
  import { NO_CANVAS, NO_CATALOG, NO_DATA, NO_LIFECYCLE, } from "../../graph/types.js";
4
- import { AGENT_VIEW_RESOURCE_TYPE, CALENDAR_VIEW_RESOURCE_TYPE, CUSTOM_VIEW_RESOURCE_TYPE, DASHBOARD_VIEW_RESOURCE_TYPE, KANBAN_VIEW_RESOURCE_TYPE, LAYOUT_RESOURCE_TYPE, LIST_VIEW_RESOURCE_TYPE, MANAGED_VIEW_ORDER_RESOURCE_TYPE, VIEW_DATA_RESOURCE_TYPE, } from "./types.js";
4
+ import { AGENT_VIEW_RESOURCE_TYPE, CALENDAR_VIEW_RESOURCE_TYPE, CUSTOM_VIEW_RESOURCE_TYPE, DASHBOARD_VIEW_RESOURCE_TYPE, KANBAN_VIEW_RESOURCE_TYPE, LAYOUT_RESOURCE_TYPE, LIST_VIEW_RESOURCE_TYPE, MANAGED_VIEW_ORDER_RESOURCE_TYPE, PLATFORM_DEFAULT_LIST_VIEW_NAME, VIEW_DATA_RESOURCE_TYPE, } from "./types.js";
5
5
  /**
6
6
  * Layouts + list views are stream members folded into the app authoring file
7
7
  * (inline), extracted by `appFromTf` — not own-file kinds.
@@ -77,6 +77,9 @@ export const managedViewOrderModule = {
77
77
  shape: "single",
78
78
  resourceType: MANAGED_VIEW_ORDER_RESOURCE_TYPE,
79
79
  adoptable: true,
80
+ // The provider leaves the platform's default "List" view out of an order
81
+ // whose state doesn't list it (#1598); the export always lists it (#1658).
82
+ stateScopedPlatformEntries: [{ attribute: "view_ids", name: PLATFORM_DEFAULT_LIST_VIEW_NAME }],
80
83
  },
81
84
  data: NO_DATA,
82
85
  lifecycle: NO_LIFECYCLE,
@@ -119,6 +119,8 @@ export interface ViewToTfOptions {
119
119
  readonly objectId: TfValue;
120
120
  /** App stage terraform labels declared by systemFields.stage.options. */
121
121
  readonly stageTfLabels?: ReadonlySet<string>;
122
+ /** Stage handle tfLabel → real `stage_ids_by_key` key, when they differ (#1136). */
123
+ readonly stageKeyByTfLabel?: ReadonlyMap<string, string>;
122
124
  /** Declared sibling dashboard keys, for fail-fast dashboard-view references. */
123
125
  readonly dashboardKeys?: ReadonlySet<string>;
124
126
  readonly orgRefs?: OrgRefLookup;
@@ -126,6 +128,10 @@ export interface ViewToTfOptions {
126
128
  readonly workspaceAspects?: ReadonlyMap<string, WorkspaceAspect>;
127
129
  /** Known emitted field addresses keyed by field bag key, for robust reference resolution. */
128
130
  readonly fieldAddresses?: ReadonlyMap<string, string>;
131
+ /** Field bag key → display name (custom-view calc checks). */
132
+ readonly fieldNames?: ReadonlyMap<string, string>;
133
+ /** Field bag key → metadata (custom-view tag / calc checks). */
134
+ readonly fieldMetadata?: ReadonlyMap<string, import("../../graph/types.js").BuildFieldMetadata>;
129
135
  /** Declared sibling widget keys, for typed classic-layout placement. */
130
136
  readonly widgetKeys?: ReadonlySet<string>;
131
137
  /** Degradations land here — reported by the caller, never silent. */
@@ -17,7 +17,7 @@ import { filterToTf, principalListToTf } from "../access-policy/to-tf.js";
17
17
  import { SUB_TYPE_BY_AUTHORING_TYPE } from "../field/types.js";
18
18
  import { DASHBOARD_RESOURCE_TYPE } from "../dashboard/module.js";
19
19
  import { WIDGET_RESOURCE_TYPE } from "../widget/module.js";
20
- import { AGENT_VIEW_RESOURCE_TYPE, CUSTOM_VIEW_RESOURCE_TYPE, CALENDAR_VIEW_RESOURCE_TYPE, DASHBOARD_VIEW_RESOURCE_TYPE, GROUP_SECTION_WIRE_TYPE, LAYOUT_RESOURCE_TYPE, LIST_VIEW_RESOURCE_TYPE, KANBAN_VIEW_RESOURCE_TYPE, MANAGED_VIEW_ORDER_RESOURCE_TYPE, SECTION_TYPE_TO_WIRE, SYSTEM_FIELD_ID_ATTR_BY_KEY, UPDATE_SECTION_WIRE_TYPE, } from "./types.js";
20
+ import { AGENT_VIEW_RESOURCE_TYPE, CUSTOM_VIEW_RESOURCE_TYPE, CALENDAR_VIEW_RESOURCE_TYPE, DASHBOARD_VIEW_RESOURCE_TYPE, GROUP_SECTION_WIRE_TYPE, LAYOUT_RESOURCE_TYPE, LIST_VIEW_RESOURCE_TYPE, KANBAN_VIEW_RESOURCE_TYPE, MANAGED_VIEW_ORDER_RESOURCE_TYPE, PLATFORM_DEFAULT_LIST_VIEW_NAME, SECTION_TYPE_TO_WIRE, SYSTEM_FIELD_ID_ATTR_BY_KEY, UPDATE_SECTION_WIRE_TYPE, } from "./types.js";
21
21
  function appendViewSharingAttrs(attrs, view, where, ctx) {
22
22
  const userIds = principalListToTf(view.userIds, "elementum_user", `${where}.userIds`, ctx);
23
23
  const groupIds = principalListToTf(view.groupIds, "elementum_group", `${where}.groupIds`, ctx);
@@ -49,7 +49,7 @@ export function viewToTf(layouts, listViews, calendarViews, kanbanViews, dashboa
49
49
  diagnostics.push(`layouts.${stageKey} has no matching authored stage option; dropped`);
50
50
  continue;
51
51
  }
52
- blocks.push(layoutToTf(stageKey, layout, ownerRefName, ownerTfLabel, scope, objectId, diagnostics, fieldAddresses, opts.widgetKeys));
52
+ blocks.push(layoutToTf(stageKey, layout, ownerRefName, ownerTfLabel, scope, objectId, diagnostics, fieldAddresses, opts.widgetKeys, opts.stageKeyByTfLabel?.get(stageTfLabel)));
53
53
  }
54
54
  const viewAddressByKey = new Map();
55
55
  for (const [viewKey, view] of Object.entries(listViews ?? {})) {
@@ -266,10 +266,12 @@ export function viewToTf(layouts, listViews, calendarViews, kanbanViews, dashboa
266
266
  objectId,
267
267
  diagnostics,
268
268
  fieldAddresses,
269
+ fieldNames: opts.fieldNames,
270
+ fieldMetadata: opts.fieldMetadata,
269
271
  orgRefs: opts.orgRefs,
270
272
  workspaceAspects: opts.workspaceAspects,
271
273
  resolveField: (ref, fieldWhere) => fieldRefToTfValue(ref, ownerTfLabel, scope, fieldWhere, diagnostics, fieldAddresses),
272
- }, { editorPolicy: false }));
274
+ }, { editorPolicy: false, strictStructure: true }));
273
275
  }
274
276
  else {
275
277
  // The page needs a layout document, and the platform rejects a blank
@@ -301,14 +303,22 @@ export function viewToTf(layouts, listViews, calendarViews, kanbanViews, dashboa
301
303
  }
302
304
  // Every declared list view must appear even if viewOrder omitted it —
303
305
  // otherwise the omitted view has no ordering entry and the platform
304
- // may reject or silently exclude it from the managed order.
306
+ // may reject or silently exclude it from the managed order. The exception
307
+ // is the platform's default "List" view: the platform keeps it in the order
308
+ // itself, and the provider leaves it out of an order that doesn't list it
309
+ // (#1598), so appending it would plan a change after every pull (#1658).
310
+ const viewNames = new Map([listViews, calendarViews, kanbanViews, dashboardViews, agentViews, customViews]
311
+ .flatMap((bag) => Object.entries(bag ?? {}).map(([key, view]) => [key, view.name])));
305
312
  for (const [key, address] of viewAddressByKey) {
306
313
  if (placed.has(key))
307
314
  continue;
315
+ if (viewOrder !== undefined && viewNames.get(key) === PLATFORM_DEFAULT_LIST_VIEW_NAME)
316
+ continue;
308
317
  diagnostics.push(`view "${key}" is not listed in viewOrder; appended`);
309
318
  viewIds.push(expr.resourceAttr(address.type, address.label, ["id"]));
310
319
  }
311
- if (viewIds.length > 0) {
320
+ // An explicitly empty viewOrder keeps an empty order (#1658).
321
+ if (viewIds.length > 0 || viewOrder !== undefined) {
312
322
  blocks.push({
313
323
  kind: "resource",
314
324
  type: MANAGED_VIEW_ORDER_RESOURCE_TYPE,
@@ -335,7 +345,7 @@ export function managedViewSortToTf(sort, ownerTfLabel, scope, where, diagnostic
335
345
  }
336
346
  return expr.jsonencode({ orders });
337
347
  }
338
- function layoutToTf(stageKey, layout, ownerRefName, ownerTfLabel, scope, objectId, diagnostics, fieldAddresses, widgetKeys) {
348
+ function layoutToTf(stageKey, layout, ownerRefName, ownerTfLabel, scope, objectId, diagnostics, fieldAddresses, widgetKeys, stageIdKey) {
339
349
  const sections = [];
340
350
  for (const section of layout.sections) {
341
351
  const authoringType = section.type ?? "group";
@@ -412,8 +422,14 @@ function layoutToTf(stageKey, layout, ownerRefName, ownerTfLabel, scope, objectI
412
422
  }
413
423
  const fieldIds = resolveFieldRefs(fields, ownerTfLabel, scope, where, diagnostics, fieldAddresses);
414
424
  // Insert from the back so each `at` is an index in the original field
415
- // list, not an index that earlier inserts have already shifted.
416
- for (const widget of inserted.sort((left, right) => right.at - left.at)) {
425
+ // list, not an index that earlier inserts have already shifted. When
426
+ // several widgets share the same `at`, insert later-authored ones first
427
+ // so the final order matches the authored widgets array (stable insert
428
+ // at one index would otherwise reverse them and plan a layout replace).
429
+ const ranked = inserted
430
+ .map((widget, order) => ({ ...widget, order }))
431
+ .sort((left, right) => right.at - left.at || right.order - left.order);
432
+ for (const widget of ranked) {
417
433
  const index = Math.max(0, Math.min(widget.at, fieldIds.length));
418
434
  fieldIds.splice(index, 0, widget.id);
419
435
  }
@@ -439,7 +455,7 @@ function layoutToTf(stageKey, layout, ownerRefName, ownerTfLabel, scope, objectI
439
455
  // in, instead of referencing a `<ownerTfLabel>_stage_ids_by_key` local that
440
456
  // `element/locals.ts` never defines.
441
457
  if (scope !== "element") {
442
- attrs["stage_id"] = expr.local(`${ownerTfLabel}_stage_ids_by_key`, [{ index: tfLabel }]);
458
+ attrs["stage_id"] = expr.local(`${ownerTfLabel}_stage_ids_by_key`, [{ index: stageIdKey ?? tfLabel }]);
443
459
  }
444
460
  return {
445
461
  kind: "resource",
@@ -18,6 +18,12 @@ export declare const CALENDAR_VIEW_RESOURCE_TYPE = "elementum_calendar_view";
18
18
  export declare const KANBAN_VIEW_RESOURCE_TYPE = "elementum_kanban_view";
19
19
  export declare const DASHBOARD_VIEW_RESOURCE_TYPE = "elementum_dashboard_view";
20
20
  export declare const MANAGED_VIEW_ORDER_RESOURCE_TYPE = "elementum_managed_view_order";
21
+ /**
22
+ * The name the platform gives the list view it creates on every app, element
23
+ * and task. Like the provider (`platformDefaultListViewName`), EDK recognises
24
+ * that view only by this name; the platform has no other marker for it.
25
+ */
26
+ export declare const PLATFORM_DEFAULT_LIST_VIEW_NAME = "List";
21
27
  /** Looks up a managed view by owner and name (a portal menu's view outside the workspace). */
22
28
  export declare const VIEW_DATA_RESOURCE_TYPE = "elementum_view";
23
29
  /**
@@ -20,6 +20,12 @@ export const CALENDAR_VIEW_RESOURCE_TYPE = "elementum_calendar_view";
20
20
  export const KANBAN_VIEW_RESOURCE_TYPE = "elementum_kanban_view";
21
21
  export const DASHBOARD_VIEW_RESOURCE_TYPE = "elementum_dashboard_view";
22
22
  export const MANAGED_VIEW_ORDER_RESOURCE_TYPE = "elementum_managed_view_order";
23
+ /**
24
+ * The name the platform gives the list view it creates on every app, element
25
+ * and task. Like the provider (`platformDefaultListViewName`), EDK recognises
26
+ * that view only by this name; the platform has no other marker for it.
27
+ */
28
+ export const PLATFORM_DEFAULT_LIST_VIEW_NAME = "List";
23
29
  /** Looks up a managed view by owner and name (a portal menu's view outside the workspace). */
24
30
  export const VIEW_DATA_RESOURCE_TYPE = "elementum_view";
25
31
  /**
@@ -1,4 +1,5 @@
1
1
  import { type FromTfContext } from "../../engine/pull/context.js";
2
+ import { type StageHandleIndex } from "../app/stage-keys.js";
2
3
  import { type ChildResourceScope, type TfBlock } from "../../engine/tf/index.js";
3
4
  export type NormalizedFlowObject = {
4
5
  readonly kind: "app" | "element";
@@ -60,4 +61,4 @@ export interface NormalizedVisualFlow {
60
61
  readonly refName: string;
61
62
  readonly stages: readonly NormalizedVisualFlowStage[];
62
63
  }
63
- export declare function visualFlowFromTf(block: TfBlock, ownerType: "elementum_app" | "elementum_element", ownerLabel: string, scope: ChildResourceScope, ctx: FromTfContext): NormalizedVisualFlow;
64
+ export declare function visualFlowFromTf(block: TfBlock, ownerType: "elementum_app" | "elementum_element", ownerLabel: string, scope: ChildResourceScope, ctx: FromTfContext, stageHandles?: StageHandleIndex): NormalizedVisualFlow;
@@ -1,5 +1,6 @@
1
1
  import { EntityTfError } from "../../engine/entity.js";
2
2
  import { dataRefLabel, plainObject, resourceRefLabel } from "../../engine/pull/context.js";
3
+ import { LostStageHandleError, lostStageMessage, pulledStageHandle } from "../app/stage-keys.js";
3
4
  import { isTfExpr, scopedLabelToBagKey, tfLabelToTsLabel } from "../../engine/tf/index.js";
4
5
  import { dataAspectDisplayName, dataAspectRefName } from "../shared/aspect-target-from-tf.js";
5
6
  import { DATAMINE_RESOURCE_TYPE } from "../datamine/module.js";
@@ -147,7 +148,7 @@ function nodeFromTf(value, ownerLabel, scope, ctx, where) {
147
148
  ...(target !== undefined ? { target } : {}),
148
149
  }];
149
150
  }
150
- export function visualFlowFromTf(block, ownerType, ownerLabel, scope, ctx) {
151
+ export function visualFlowFromTf(block, ownerType, ownerLabel, scope, ctx, stageHandles) {
151
152
  if (block.type !== VISUAL_FLOW_RESOURCE_TYPE || !block.label)
152
153
  throw new EntityTfError(`expected ${VISUAL_FLOW_RESOURCE_TYPE}`);
153
154
  for (const key of Object.keys(block.attrs))
@@ -170,7 +171,15 @@ export function visualFlowFromTf(block, ownerType, ownerLabel, scope, ctx) {
170
171
  const rawNodes = stage["nodes"];
171
172
  if (!Array.isArray(rawNodes))
172
173
  throw new EntityTfError(`${block.type}.${block.label}.stages[${index}]: nodes must be a list`);
173
- return { stage: tfLabelToTsLabel(entry.index), nodes: Object.fromEntries(rawNodes.map((node, nodeIndex) => nodeFromTf(node, ownerLabel, scope, ctx, `${block.type}.${block.label}.stages[${index}].nodes[${nodeIndex}]`))) };
174
+ // Imported keys may keep punctuation; pull a handle build maps back to
175
+ // this same stage. A stage whose only handle is another stage's key keeps
176
+ // the flow unmanaged rather than binding it to that stage (#1136).
177
+ const pulled = pulledStageHandle(entry.index, stageHandles);
178
+ if (pulled.kind === "lost")
179
+ throw new LostStageHandleError(lostStageMessage(`${block.type}.${block.label}.stages[${index}]`, entry.index, pulled, "the flow is left unmanaged"));
180
+ if (pulled.kind === "none")
181
+ throw new EntityTfError(`${block.type}.${block.label}.stages[${index}]: stage key ${JSON.stringify(entry.index)} has no terraform label handle`);
182
+ return { stage: tfLabelToTsLabel(pulled.handle), nodes: Object.fromEntries(rawNodes.map((node, nodeIndex) => nodeFromTf(node, ownerLabel, scope, ctx, `${block.type}.${block.label}.stages[${index}].nodes[${nodeIndex}]`))) };
174
183
  });
175
184
  return { refName: scopedLabelToBagKey(ownerLabel, block.label, scope), stages };
176
185
  }
@@ -3,6 +3,7 @@ import { APP_RESOURCE_TYPE } from "../app/module.js";
3
3
  import { ELEMENT_RESOURCE_TYPE } from "../element/module.js";
4
4
  import { visualFlowFromTf } from "./from-tf.js";
5
5
  import { printVisualFlow } from "./printer.js";
6
+ import { appStageKeyByHandle, LostStageHandleError, stageHandleIndexFromTfStages } from "../app/stage-keys.js";
6
7
  import { visualFlowToTf } from "./to-tf.js";
7
8
  export const VISUAL_FLOW_RESOURCE_TYPE = "elementum_flow";
8
9
  function extract(blocks, _stream, ctx) {
@@ -12,15 +13,24 @@ function extract(blocks, _stream, ctx) {
12
13
  if (ctx.parentScope === "table")
13
14
  return { items, skipped: blocks.map((block) => `${block.type}.${block.label ?? "?"}`), diagnostics: ["visual flows cannot belong to tables"] };
14
15
  const ownerType = ctx.parentScope === "element" ? ELEMENT_RESOURCE_TYPE : APP_RESOURCE_TYPE;
15
- for (const block of blocks)
16
+ // Elements carry no stages; an app's stage handles keep flow stages on their own stage (#1136).
17
+ const stageHandles = ownerType === APP_RESOURCE_TYPE ? stageHandleIndexFromTfStages(ctx.resourceByAddress?.(`${APP_RESOURCE_TYPE}.${ctx.appTfLabel}`)?.attrs["stages"]) : undefined;
18
+ const releaseIfManaged = [];
19
+ for (const block of blocks) {
16
20
  try {
17
- items.push(visualFlowFromTf(block, ownerType, ctx.appTfLabel, ctx.parentScope, ctx));
21
+ items.push(visualFlowFromTf(block, ownerType, ctx.appTfLabel, ctx.parentScope, ctx, stageHandles));
18
22
  }
19
23
  catch (error) {
20
- skipped.push(`${block.type}.${block.label ?? "?"}`);
24
+ const address = `${block.type}.${block.label ?? "?"}`;
25
+ skipped.push(address);
26
+ // A flow on a stage with no handle of its own has no authored form:
27
+ // release an earlier adoption instead of destroying it (#1136).
28
+ if (error instanceof LostStageHandleError)
29
+ releaseIfManaged.push(address);
21
30
  diagnostics.push(error instanceof Error ? error.message : String(error));
22
31
  }
23
- return { items, skipped, diagnostics };
32
+ }
33
+ return { items, skipped, ...(releaseIfManaged.length > 0 && { releaseIfManaged }), diagnostics };
24
34
  }
25
35
  export const visualFlowModule = {
26
36
  kind: "visual-flow", stream: { role: "streamMember" }, authoring: { unit: "ownFile", bag: "visual-flows" },
@@ -36,6 +46,6 @@ export const visualFlowModule = {
36
46
  ...(opts.foreignElementRefNames !== undefined && { foreignElementRefNames: opts.foreignElementRefNames }),
37
47
  }),
38
48
  };
39
- }, toTf: (entity, ctx) => visualFlowToTf(entity, { appRefName: ctx.appRefName, appTfLabel: ctx.appTfLabel, parentScope: ctx.parentScope, orgRefs: ctx.orgRefs, workspaceAspects: ctx.workspaceAspects, diagnostics: ctx.diagnostics }) },
49
+ }, toTf: (entity, ctx) => visualFlowToTf(entity, { appRefName: ctx.appRefName, appTfLabel: ctx.appTfLabel, parentScope: ctx.parentScope, orgRefs: ctx.orgRefs, workspaceAspects: ctx.workspaceAspects, diagnostics: ctx.diagnostics, stageKeyByTfLabel: appStageKeyByHandle(ctx.streamRootEntity?.payload) }) },
40
50
  canvas: { participates: true, label: "Visual flow", glyph: "⇢", component: "generic" }, catalog: NO_CATALOG,
41
51
  };
@@ -8,6 +8,8 @@ export interface VisualFlowToTfContext {
8
8
  readonly orgRefs: OrgRefLookup;
9
9
  readonly workspaceAspects?: ReadonlyMap<string, WorkspaceAspect>;
10
10
  readonly diagnostics?: string[];
11
+ /** Owning app's stage handle → real `stage_ids_by_key` key (#1136). */
12
+ readonly stageKeyByTfLabel?: ReadonlyMap<string, string>;
11
13
  }
12
14
  export declare function visualFlowToTf(entity: DeployableEntity, ctx: VisualFlowToTfContext): {
13
15
  blocks: readonly TfBlock[];