@elementumai/edk 0.10.2 → 0.10.4

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 (127) 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 +69 -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 +2 -1
  18. package/dist-sdk/src/engine/tf/index.js +2 -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/tf/scan.d.ts +22 -0
  23. package/dist-sdk/src/engine/tf/scan.js +123 -0
  24. package/dist-sdk/src/engine/workspace/backend.d.ts +34 -0
  25. package/dist-sdk/src/engine/workspace/backend.js +104 -0
  26. package/dist-sdk/src/engine/workspace/generated-file.d.ts +3 -0
  27. package/dist-sdk/src/engine/workspace/generated-file.js +6 -0
  28. package/dist-sdk/src/engine/workspace/loader.d.ts +8 -0
  29. package/dist-sdk/src/engine/workspace/loader.js +22 -2
  30. package/dist-sdk/src/entities/agent/to-tf.d.ts +13 -11
  31. package/dist-sdk/src/entities/agent/to-tf.js +17 -12
  32. package/dist-sdk/src/entities/agent-tool/from-tf.js +2 -2
  33. package/dist-sdk/src/entities/agent-tool/to-tf.js +10 -1
  34. package/dist-sdk/src/entities/app/build.d.ts +36 -4
  35. package/dist-sdk/src/entities/app/build.js +67 -4
  36. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +18 -0
  37. package/dist-sdk/src/entities/app/from-tf.js +17 -9
  38. package/dist-sdk/src/entities/app/module.js +1 -0
  39. package/dist-sdk/src/entities/app/stage-keys.d.ts +82 -0
  40. package/dist-sdk/src/entities/app/stage-keys.js +160 -0
  41. package/dist-sdk/src/entities/app/to-tf.js +17 -21
  42. package/dist-sdk/src/entities/approval-chain/from-tf.d.ts +9 -1
  43. package/dist-sdk/src/entities/approval-chain/from-tf.js +31 -3
  44. package/dist-sdk/src/entities/approval-chain/module.js +12 -4
  45. package/dist-sdk/src/entities/approval-chain/to-tf.d.ts +1 -0
  46. package/dist-sdk/src/entities/approval-chain/to-tf.js +6 -1
  47. package/dist-sdk/src/entities/automation/build.js +25 -8
  48. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +3 -0
  49. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +5 -3
  50. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +90 -17
  51. package/dist-sdk/src/entities/automation/from-tf.d.ts +28 -6
  52. package/dist-sdk/src/entities/automation/from-tf.js +140 -23
  53. package/dist-sdk/src/entities/automation/module.js +158 -44
  54. package/dist-sdk/src/entities/automation/output-field-types.d.ts +8 -0
  55. package/dist-sdk/src/entities/automation/output-field-types.js +20 -0
  56. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +2 -0
  57. package/dist-sdk/src/entities/automation/output-key-wire-name.js +18 -0
  58. package/dist-sdk/src/entities/automation/to-tf.d.ts +10 -1
  59. package/dist-sdk/src/entities/automation/to-tf.js +200 -38
  60. package/dist-sdk/src/entities/automation/triggers.d.ts +2 -0
  61. package/dist-sdk/src/entities/automation/triggers.js +1 -0
  62. package/dist-sdk/src/entities/chart/from-tf.d.ts +6 -0
  63. package/dist-sdk/src/entities/chart/from-tf.js +9 -1
  64. package/dist-sdk/src/entities/dashboard/from-tf.js +51 -4
  65. package/dist-sdk/src/entities/dynamic-layout/from-tf.d.ts +3 -0
  66. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +48 -4
  67. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +2 -0
  68. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +7 -2
  69. package/dist-sdk/src/entities/element/build.js +1 -1
  70. package/dist-sdk/src/entities/element/from-tf.d.ts +12 -6
  71. package/dist-sdk/src/entities/element/from-tf.js +26 -8
  72. package/dist-sdk/src/entities/element/module.js +3 -2
  73. package/dist-sdk/src/entities/element/to-tf.d.ts +3 -2
  74. package/dist-sdk/src/entities/element/to-tf.js +32 -25
  75. package/dist-sdk/src/entities/field/allow-list.d.ts +18 -0
  76. package/dist-sdk/src/entities/field/allow-list.js +42 -0
  77. package/dist-sdk/src/entities/field/build.d.ts +38 -3
  78. package/dist-sdk/src/entities/field/build.js +7 -2
  79. package/dist-sdk/src/entities/field/from-tf.js +178 -20
  80. package/dist-sdk/src/entities/field/module.js +2 -0
  81. package/dist-sdk/src/entities/field/options.d.ts +2 -0
  82. package/dist-sdk/src/entities/field/order.d.ts +9 -0
  83. package/dist-sdk/src/entities/field/order.js +33 -0
  84. package/dist-sdk/src/entities/field/to-tf.d.ts +6 -0
  85. package/dist-sdk/src/entities/field/to-tf.js +87 -0
  86. package/dist-sdk/src/entities/field/types.js +3 -0
  87. package/dist-sdk/src/entities/relationship/build.d.ts +3 -3
  88. package/dist-sdk/src/entities/relationship/from-tf.js +4 -2
  89. package/dist-sdk/src/entities/relationship/to-tf.js +3 -1
  90. package/dist-sdk/src/entities/service-account/workspace-owner.d.ts +8 -3
  91. package/dist-sdk/src/entities/service-account/workspace-owner.js +12 -4
  92. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +5 -0
  93. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +13 -0
  94. package/dist-sdk/src/entities/shared/filters/ast.d.ts +7 -0
  95. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +1 -1
  96. package/dist-sdk/src/entities/skill/module.js +28 -2
  97. package/dist-sdk/src/entities/skill/to-tf.js +19 -14
  98. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  99. package/dist-sdk/src/entities/skill-tool/from-tf.js +3 -0
  100. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +6 -1
  101. package/dist-sdk/src/entities/skill-tool/to-tf.js +6 -1
  102. package/dist-sdk/src/entities/task/build.js +1 -1
  103. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +2 -0
  104. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +6 -2
  105. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.d.ts +11 -0
  106. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +13 -38
  107. package/dist-sdk/src/entities/view/custom-view-validate.d.ts +29 -0
  108. package/dist-sdk/src/entities/view/custom-view-validate.js +293 -0
  109. package/dist-sdk/src/entities/view/from-tf.d.ts +10 -0
  110. package/dist-sdk/src/entities/view/from-tf.js +164 -26
  111. package/dist-sdk/src/entities/view/to-tf.d.ts +6 -0
  112. package/dist-sdk/src/entities/view/to-tf.js +14 -6
  113. package/dist-sdk/src/entities/visual-flow/from-tf.d.ts +2 -1
  114. package/dist-sdk/src/entities/visual-flow/from-tf.js +11 -2
  115. package/dist-sdk/src/entities/visual-flow/module.js +15 -5
  116. package/dist-sdk/src/entities/visual-flow/to-tf.d.ts +2 -0
  117. package/dist-sdk/src/entities/visual-flow/to-tf.js +1 -1
  118. package/dist-sdk/src/entities/widget/build.d.ts +8 -1
  119. package/dist-sdk/src/entities/widget/from-tf.js +12 -6
  120. package/dist-sdk/src/entities/widget/to-tf.d.ts +1 -0
  121. package/dist-sdk/src/entities/widget/to-tf.js +16 -0
  122. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +8 -2
  123. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  124. package/dist-sdk/src/graph/index.d.ts +6 -0
  125. package/dist-sdk/src/graph/index.js +1 -0
  126. package/dist-sdk/src/graph/types.d.ts +66 -2
  127. package/package.json +2 -17
@@ -111,6 +111,20 @@ export function snakeSlug(s) {
111
111
  .replace(/[^a-z0-9]+/g, "_")
112
112
  .replace(/^_+|_+$/g, "");
113
113
  }
114
+ /**
115
+ * The Terraform-label handle for a `stage_ids_by_key` index (#1136). An index
116
+ * that is already a tf label is its own handle. An imported key that keeps
117
+ * punctuation (`"enrichment_&_validation"`, `"pre-approval"`) maps to
118
+ * `snakeSlug(key)`, which is also the slug of the stage name build derives,
119
+ * so build can map the handle back to the real key. Returns `undefined` when
120
+ * no tf-label handle exists (for example a key whose slug starts with a digit).
121
+ */
122
+ export function stageHandleTfLabel(key) {
123
+ if (TF_LABEL_RE.test(key))
124
+ return key;
125
+ const slug = snakeSlug(key);
126
+ return TF_LABEL_RE.test(slug) ? slug : undefined;
127
+ }
114
128
  /** Faithful port of ei's SanitizeName: platform name → HCL identifier. */
115
129
  export function sanitizeName(name) {
116
130
  let s = splitCamelCase(name).toLowerCase();
@@ -178,8 +192,7 @@ export function appScopedResourceLabel(appTfLabel, childPart) {
178
192
  * re-pulled — the old extractor never stripped the namespace, so it left prefixed bag keys
179
193
  * (e.g. `ticketsActive`) that now over-double when rebuilt. A field FRESHLY re-extracted with
180
194
  * `childPartFromScopedLabel`'s current (also-fixed) stripping round-trips to the exact same
181
- * address ei already uses — see `__tests__/tf/labels.test.ts`'s "element-prefixed child labels
182
- * round-trip" block. Re-pull an existing element (`elementum pull element <ns>`) before your
195
+ * address ei already uses. Re-pull an existing element (`elementum pull element <ns>`) before your
183
196
  * next build/plan if it predates this fix; adoption's rename guard (board item 225,
184
197
  * `docs/design/rename-label-identity.md`) moves any address that does shift with a `moved` block.
185
198
  */
@@ -11,7 +11,7 @@
11
11
  * means something new is going on → Pause).
12
12
  */
13
13
  import { decodeTemplateEscapes } from "./escape.js";
14
- import { parseStringValue, TfExprError } from "./expr.js";
14
+ import { parseStringValue, quotedTemplateEnd, TfExprError } from "./expr.js";
15
15
  let runtimeParser;
16
16
  let batchParser;
17
17
  let packageParser;
@@ -523,19 +523,32 @@ export function assertNoUnsafeIntegers(text) {
523
523
  }
524
524
  }
525
525
  }
526
+ /** Index just past the quoted string opening at `openQuote`, ignoring holes (end of text when unclosed). */
527
+ function plainStringEnd(text, openQuote) {
528
+ let j = openQuote + 1;
529
+ while (j < text.length && text[j] !== '"') {
530
+ j += text[j] === "\\" ? 2 : 1;
531
+ }
532
+ return j + 1;
533
+ }
526
534
  /** One in-order scan: strings become `""`, line comments vanish. */
527
535
  function stripStringsAndComments(text) {
528
536
  let out = "";
529
537
  let i = 0;
538
+ // Template-aware until a string fails to close; from there on, plain
539
+ // scanning keeps the rest linear. That is usually invalid HCL, but a
540
+ // heredoc holding a lone quote can trigger it too: the plain scan then
541
+ // reads the rest of the file exactly as the guard did before #1542.
542
+ let templateAware = true;
530
543
  while (i < text.length) {
531
544
  const c = text[i];
532
545
  if (c === '"') {
533
- let j = i + 1;
534
- while (j < text.length && text[j] !== '"') {
535
- j += text[j] === "\\" ? 2 : 1;
536
- }
546
+ // A quoted key inside a ${...} hole is string text, not code (#1542).
537
547
  out += '""';
538
- i = j + 1;
548
+ const end = templateAware ? quotedTemplateEnd(text, i) : undefined;
549
+ if (end === undefined)
550
+ templateAware = false;
551
+ i = end ?? plainStringEnd(text, i);
539
552
  continue;
540
553
  }
541
554
  if (c === "#" || (c === "/" && text[i + 1] === "/")) {
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Lexical line view of HCL source for the text rewriters that must leave every
3
+ * untouched byte as ei wrote it. It locates structure only; it never parses
4
+ * values. Braces, brackets, `#`, and `resource "…"` inside a quoted string,
5
+ * a heredoc body (`<<EOT` / `<<-EOT`, e.g. execute-script JavaScript), a
6
+ * `${…}` / `%{…}` template hole, or a comment are not code.
7
+ */
8
+ /** One source line. `code` keeps only top-level code, with each string or heredoc reduced to `""`. */
9
+ export interface HclCodeLine {
10
+ readonly text: string;
11
+ readonly code: string;
12
+ /** The line begins in top-level code, not inside a string, heredoc, hole, or block comment. */
13
+ readonly startsInCode: boolean;
14
+ }
15
+ export declare function hclCodeLines(text: string): HclCodeLine[];
16
+ /** `{`/`}` and `[`/`]` depth change of a line's code. */
17
+ export declare function hclDepthDelta(line: HclCodeLine): {
18
+ readonly braces: number;
19
+ readonly brackets: number;
20
+ };
21
+ /** Index of the last line of the statement starting at `start`: a value that opens a heredoc or block comment runs past its own line. */
22
+ export declare function hclStatementEnd(lines: readonly HclCodeLine[], start: number): number;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Lexical line view of HCL source for the text rewriters that must leave every
3
+ * untouched byte as ei wrote it. It locates structure only; it never parses
4
+ * values. Braces, brackets, `#`, and `resource "…"` inside a quoted string,
5
+ * a heredoc body (`<<EOT` / `<<-EOT`, e.g. execute-script JavaScript), a
6
+ * `${…}` / `%{…}` template hole, or a comment are not code.
7
+ */
8
+ const HEREDOC_OPENER = /^<<-?([A-Za-z_][A-Za-z0-9_-]*)\r?$/;
9
+ export function hclCodeLines(text) {
10
+ const stack = [];
11
+ let inBlockComment = false;
12
+ const out = [];
13
+ for (const line of text.split("\n")) {
14
+ const top = stack.at(-1);
15
+ if (top?.kind === "heredoc" && line.trim() === top.marker) {
16
+ stack.pop();
17
+ out.push({ text: line, code: "", startsInCode: false });
18
+ continue;
19
+ }
20
+ const startsInCode = stack.length === 0 && !inBlockComment;
21
+ let code = "";
22
+ let i = 0;
23
+ while (i < line.length) {
24
+ const frame = stack.at(-1);
25
+ const ch = line[i];
26
+ if (inBlockComment) {
27
+ const end = line.indexOf("*/", i);
28
+ if (end === -1)
29
+ break;
30
+ inBlockComment = false;
31
+ i = end + 2;
32
+ continue;
33
+ }
34
+ if (frame?.kind === "string" || frame?.kind === "heredoc") {
35
+ if (frame.kind === "string" && ch === "\\") {
36
+ i += 2;
37
+ continue;
38
+ }
39
+ if ((ch === "$" || ch === "%") && line[i + 1] === ch && line[i + 2] === "{") {
40
+ i += 3;
41
+ continue;
42
+ }
43
+ if ((ch === "$" || ch === "%") && line[i + 1] === "{") {
44
+ stack.push({ kind: "hole", depth: 0 });
45
+ i += 2;
46
+ continue;
47
+ }
48
+ if (frame.kind === "string" && ch === '"') {
49
+ stack.pop();
50
+ if (stack.length === 0)
51
+ code += '"';
52
+ }
53
+ i++;
54
+ continue;
55
+ }
56
+ if (ch === "#" || (ch === "/" && line[i + 1] === "/"))
57
+ break;
58
+ if (ch === "/" && line[i + 1] === "*") {
59
+ inBlockComment = true;
60
+ i += 2;
61
+ continue;
62
+ }
63
+ if (ch === '"') {
64
+ if (stack.length === 0)
65
+ code += '"';
66
+ stack.push({ kind: "string" });
67
+ i++;
68
+ continue;
69
+ }
70
+ if (ch === "<" && line[i + 1] === "<") {
71
+ const opener = HEREDOC_OPENER.exec(line.slice(i));
72
+ if (opener !== null) {
73
+ if (stack.length === 0)
74
+ code += '""';
75
+ stack.push({ kind: "heredoc", marker: opener[1] });
76
+ break;
77
+ }
78
+ }
79
+ if (frame?.kind === "hole") {
80
+ if (ch === "{")
81
+ frame.depth++;
82
+ if (ch === "}" && frame.depth-- === 0)
83
+ stack.pop();
84
+ }
85
+ else {
86
+ code += ch;
87
+ }
88
+ i++;
89
+ }
90
+ // A quoted string cannot span lines; closing it here keeps one malformed
91
+ // line from swallowing the rest of the file.
92
+ while (stack.at(-1)?.kind === "string") {
93
+ stack.pop();
94
+ if (stack.length === 0)
95
+ code += '"';
96
+ }
97
+ out.push({ text: line, code, startsInCode });
98
+ }
99
+ return out;
100
+ }
101
+ /** `{`/`}` and `[`/`]` depth change of a line's code. */
102
+ export function hclDepthDelta(line) {
103
+ let braces = 0;
104
+ let brackets = 0;
105
+ for (const ch of line.code) {
106
+ if (ch === "{")
107
+ braces++;
108
+ else if (ch === "}")
109
+ braces--;
110
+ else if (ch === "[")
111
+ brackets++;
112
+ else if (ch === "]")
113
+ brackets--;
114
+ }
115
+ return { braces, brackets };
116
+ }
117
+ /** Index of the last line of the statement starting at `start`: a value that opens a heredoc or block comment runs past its own line. */
118
+ export function hclStatementEnd(lines, start) {
119
+ let end = start;
120
+ while (end + 1 < lines.length && !lines[end + 1].startsInCode)
121
+ end++;
122
+ return end;
123
+ }
@@ -0,0 +1,34 @@
1
+ export declare const BACKEND_SOURCE_FILE = "backend.tf";
2
+ export declare const BACKEND_FINGERPRINT_FILE = "elementum-backend.sha256";
3
+ export type WorkspaceBackend = {
4
+ readonly mode: "local";
5
+ readonly type: "local";
6
+ readonly source: string;
7
+ readonly projected: string;
8
+ readonly fingerprint: string;
9
+ } | {
10
+ readonly mode: "declared";
11
+ readonly type: string;
12
+ readonly sourcePath: string;
13
+ readonly source: string;
14
+ readonly projected: string;
15
+ readonly fingerprint: string;
16
+ };
17
+ export type DeclaredWorkspaceBackend = Extract<WorkspaceBackend, {
18
+ mode: "declared";
19
+ }>;
20
+ export declare class WorkspaceBackendError extends Error {
21
+ constructor(message: string);
22
+ }
23
+ export declare function backendFingerprint(value: string): string;
24
+ export declare function loadWorkspaceBackend(orgRoot: string): Promise<WorkspaceBackend>;
25
+ /**
26
+ * Project the workspace-owned backend source into a generated Terraform
27
+ * working directory. The marker makes the copy build-owned; the org-root
28
+ * source remains the only file users edit.
29
+ */
30
+ export declare function materializeWorkspaceBackend(backend: WorkspaceBackend, tfDir: string): Promise<void>;
31
+ export declare function backendFingerprintPath(tfDir: string): string;
32
+ export declare function assertNoUnmigratedLocalState(backend: WorkspaceBackend, orgRoot: string): void;
33
+ export declare function requireWorkspaceBackend(orgRoot: string, _operation: string): Promise<WorkspaceBackend>;
34
+ export declare function assertBackendBindingUnchanged(backend: WorkspaceBackend, orgRoot: string): Promise<void>;
@@ -0,0 +1,104 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { inspectBackendHcl } from "../tf/index.js";
6
+ import { MANAGED_MARKER } from "./generated-file.js";
7
+ export const BACKEND_SOURCE_FILE = "backend.tf";
8
+ export const BACKEND_FINGERPRINT_FILE = "elementum-backend.sha256";
9
+ const LOCAL_BACKEND_SOURCE = `terraform {
10
+ backend "local" {
11
+ path = "../../terraform.tfstate"
12
+ }
13
+ }
14
+ `;
15
+ export class WorkspaceBackendError extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "WorkspaceBackendError";
19
+ }
20
+ }
21
+ export function backendFingerprint(value) {
22
+ return createHash("sha256")
23
+ .update(`elementum:declared-backend:v1\n${value}`)
24
+ .digest("hex");
25
+ }
26
+ export async function loadWorkspaceBackend(orgRoot) {
27
+ const sourcePath = join(orgRoot, BACKEND_SOURCE_FILE);
28
+ if (!existsSync(sourcePath)) {
29
+ return {
30
+ mode: "local",
31
+ type: "local",
32
+ source: LOCAL_BACKEND_SOURCE,
33
+ projected: `${MANAGED_MARKER}\n\n${LOCAL_BACKEND_SOURCE}`,
34
+ fingerprint: backendFingerprint(LOCAL_BACKEND_SOURCE),
35
+ };
36
+ }
37
+ let source;
38
+ try {
39
+ source = await readFile(sourcePath, "utf8");
40
+ }
41
+ catch (error) {
42
+ throw new WorkspaceBackendError(`could not read backend.tf at ${sourcePath}: ${error.message}`);
43
+ }
44
+ let type;
45
+ try {
46
+ type = (await inspectBackendHcl(source)).type;
47
+ }
48
+ catch (error) {
49
+ throw new WorkspaceBackendError(`invalid backend.tf at ${sourcePath}: ${error.message}`);
50
+ }
51
+ const normalized = source.endsWith("\n") ? source : `${source}\n`;
52
+ const projected = `${MANAGED_MARKER}\n\n${normalized}`;
53
+ return {
54
+ mode: "declared",
55
+ type,
56
+ sourcePath,
57
+ source,
58
+ projected,
59
+ fingerprint: backendFingerprint(normalized),
60
+ };
61
+ }
62
+ /**
63
+ * Project the workspace-owned backend source into a generated Terraform
64
+ * working directory. The marker makes the copy build-owned; the org-root
65
+ * source remains the only file users edit.
66
+ */
67
+ export async function materializeWorkspaceBackend(backend, tfDir) {
68
+ const destination = join(tfDir, BACKEND_SOURCE_FILE);
69
+ await mkdir(tfDir, { recursive: true });
70
+ if (!existsSync(destination) || (await readFile(destination, "utf8")) !== backend.projected) {
71
+ await writeFile(destination, backend.projected, "utf8");
72
+ }
73
+ }
74
+ export function backendFingerprintPath(tfDir) {
75
+ return join(tfDir, ".terraform", BACKEND_FINGERPRINT_FILE);
76
+ }
77
+ export function assertNoUnmigratedLocalState(backend, orgRoot) {
78
+ const localStatePath = join(orgRoot, "terraform.tfstate");
79
+ if (backend.mode === "declared" && existsSync(localStatePath)) {
80
+ throw new WorkspaceBackendError(`backend.tf declares remote backend "${backend.type}", but ${localStatePath} still exists — ` +
81
+ `run \`elementum migrate backend '${orgRoot}' --check\` before using remote state`);
82
+ }
83
+ }
84
+ export async function requireWorkspaceBackend(orgRoot, _operation) {
85
+ const backend = await loadWorkspaceBackend(orgRoot);
86
+ assertNoUnmigratedLocalState(backend, orgRoot);
87
+ return backend;
88
+ }
89
+ export async function assertBackendBindingUnchanged(backend, orgRoot) {
90
+ const fingerprintPath = backendFingerprintPath(join(orgRoot, ".tf", "out"));
91
+ let stored;
92
+ try {
93
+ stored = (await readFile(fingerprintPath, "utf8")).trim();
94
+ }
95
+ catch (error) {
96
+ if (error.code === "ENOENT")
97
+ return;
98
+ throw new WorkspaceBackendError(`could not read backend fingerprint at ${fingerprintPath}: ${error.message}`);
99
+ }
100
+ if (stored !== backend.fingerprint) {
101
+ throw new WorkspaceBackendError(`backend.tf changed since .tf/out was initialized — run ` +
102
+ `\`elementum migrate backend '${orgRoot}' --check\` before pull/plan/apply`);
103
+ }
104
+ }
@@ -0,0 +1,3 @@
1
+ /** Marker shared by every file owned by `elementum build`. */
2
+ export declare const MANAGED_MARKER = "# Managed by elementum build v1 \u2014 do not edit.";
3
+ export declare function isManagedFile(content: string): boolean;
@@ -0,0 +1,6 @@
1
+ /** Marker shared by every file owned by `elementum build`. */
2
+ export const MANAGED_MARKER = "# Managed by elementum build v1 — do not edit.";
3
+ const LEGACY_MANAGED_MARKER = "# Managed by edk build v1 — do not edit.";
4
+ export function isManagedFile(content) {
5
+ return content.startsWith(MANAGED_MARKER) || content.startsWith(LEGACY_MANAGED_MARKER);
6
+ }
@@ -33,6 +33,14 @@ export interface WorkspaceLoader {
33
33
  default?: unknown;
34
34
  }>;
35
35
  }
36
+ export declare function setWorkspaceLoadGuard(guard: ((orgRoot: string) => void) | undefined): void;
37
+ /**
38
+ * Run the workspace load guard on `orgRoot` now, without loading anything.
39
+ * A command that loads source calls this before its first write (edk#1737):
40
+ * a guard failure inside a best-effort load can be caught and only logged,
41
+ * and by then the command may already have written files.
42
+ */
43
+ export declare function assertWorkspaceLoadable(orgRoot: string): void;
36
44
  /**
37
45
  * A loader scoped to one org root and one generation. Create one per build —
38
46
  * that is what makes a rebuild see edited files.
@@ -307,8 +307,8 @@ function stamp(url, _root) {
307
307
  /**
308
308
  * This import must be Node's, not a bundler's. Vite's SSR transform rewrites
309
309
  * `import()` into its own module runner, which resolves authored files
310
- * through Vite and never consults the hooks above — so `vitest.config.ts`
311
- * externalizes this module and the suite exercises the loader the CLI ships.
310
+ * through Vite and never consults the hooks above, so any bundler must
311
+ * externalize this module to exercise the loader the CLI ships.
312
312
  */
313
313
  async function nativeImport(specifier) {
314
314
  return (await import(specifier));
@@ -352,12 +352,32 @@ function createJitiLoader(root) {
352
352
  },
353
353
  };
354
354
  }
355
+ /**
356
+ * A check run on an org root before any of its source is loaded (edk#1737).
357
+ * The CLI sets it to the installed-SDK compatibility check; it throws to stop
358
+ * the load. Set from outside because this module can only import `node:`
359
+ * builtins (see IMPORTING_FILE_KEY).
360
+ */
361
+ let workspaceLoadGuard;
362
+ export function setWorkspaceLoadGuard(guard) {
363
+ workspaceLoadGuard = guard;
364
+ }
365
+ /**
366
+ * Run the workspace load guard on `orgRoot` now, without loading anything.
367
+ * A command that loads source calls this before its first write (edk#1737):
368
+ * a guard failure inside a best-effort load can be caught and only logged,
369
+ * and by then the command may already have written files.
370
+ */
371
+ export function assertWorkspaceLoadable(orgRoot) {
372
+ workspaceLoadGuard?.(canonical(resolve(orgRoot)));
373
+ }
355
374
  /**
356
375
  * A loader scoped to one org root and one generation. Create one per build —
357
376
  * that is what makes a rebuild see edited files.
358
377
  */
359
378
  export function createWorkspaceLoader(orgRoot) {
360
379
  const root = canonical(resolve(orgRoot));
380
+ workspaceLoadGuard?.(root);
361
381
  if (registerHooks === undefined)
362
382
  return createJitiLoader(root);
363
383
  activeRoots.add(root);
@@ -53,17 +53,19 @@ export interface AgentToTfResult {
53
53
  * first occurrence of a sanitized name the bare label, each later
54
54
  * occurrence `_1`, `_2`, …
55
55
  *
56
- * Ascending-by-agent-NAME confirmed live 2026-08-18 against real committed
57
- * state on a deployed app (two identically-named a2a skills added via the
58
- * platform UI to two different agents): "Default agent 2" landed at the
59
- * bare label, "test agent" at `_1` — `D` < `t`, matching the assumed sort.
60
- * A weaker signal than #310's skill-tool capture (that one deliberately
61
- * reordered 3 skills' creation vs. name to rule out creation-order as an
62
- * alternative explanation; this one only has 2 agents, so an
63
- * agent-creation-order coincidence can't be fully excluded) — but real
64
- * evidence from `ei`'s own exporter/import-address generation, not a
65
- * guess. If a future capture contradicts it, only this function's sort
66
- * needs to change — the suffix-assignment mechanics stay the same.
56
+ * The order is shared with ei: agent name by UTF-16 code unit, then (for
57
+ * identical names) refName here and the agent's own label in ei, whose `_N`
58
+ * tails sort alike. The Go comparator is in the a2a loop of
59
+ * `cmd/elementum/export/imports.go` (`compareUTF16`, `agentChildParts`),
60
+ * and the two must stay in sync; changing one without the other moves
61
+ * `agent_id` and replaces skills on the first plan after a pull (edk#1728).
62
+ * Before edk#1728 ei walked agents in id order.
63
+ *
64
+ * The 2026-08-18 two-agent live capture ("Default agent 2" at the bare
65
+ * label, "test agent" at `_1`) is not evidence for name order: id order
66
+ * and name order happened to agree there, which edk#1728 disproved. The
67
+ * contract above is what fixes the order.
68
+ *
67
69
  * Ordering of a2a skills WITHIN one agent is still assumed to be authored
68
70
  * array order, unconfirmed live either way.
69
71
  *
@@ -255,17 +255,19 @@ function toSortableAgents(entities) {
255
255
  * first occurrence of a sanitized name the bare label, each later
256
256
  * occurrence `_1`, `_2`, …
257
257
  *
258
- * Ascending-by-agent-NAME confirmed live 2026-08-18 against real committed
259
- * state on a deployed app (two identically-named a2a skills added via the
260
- * platform UI to two different agents): "Default agent 2" landed at the
261
- * bare label, "test agent" at `_1` — `D` < `t`, matching the assumed sort.
262
- * A weaker signal than #310's skill-tool capture (that one deliberately
263
- * reordered 3 skills' creation vs. name to rule out creation-order as an
264
- * alternative explanation; this one only has 2 agents, so an
265
- * agent-creation-order coincidence can't be fully excluded) — but real
266
- * evidence from `ei`'s own exporter/import-address generation, not a
267
- * guess. If a future capture contradicts it, only this function's sort
268
- * needs to change — the suffix-assignment mechanics stay the same.
258
+ * The order is shared with ei: agent name by UTF-16 code unit, then (for
259
+ * identical names) refName here and the agent's own label in ei, whose `_N`
260
+ * tails sort alike. The Go comparator is in the a2a loop of
261
+ * `cmd/elementum/export/imports.go` (`compareUTF16`, `agentChildParts`),
262
+ * and the two must stay in sync; changing one without the other moves
263
+ * `agent_id` and replaces skills on the first plan after a pull (edk#1728).
264
+ * Before edk#1728 ei walked agents in id order.
265
+ *
266
+ * The 2026-08-18 two-agent live capture ("Default agent 2" at the bare
267
+ * label, "test agent" at `_1`) is not evidence for name order: id order
268
+ * and name order happened to agree there, which edk#1728 disproved. The
269
+ * contract above is what fixes the order.
270
+ *
269
271
  * Ordering of a2a skills WITHIN one agent is still assumed to be authored
270
272
  * array order, unconfirmed live either way.
271
273
  *
@@ -281,7 +283,10 @@ function toSortableAgents(entities) {
281
283
  * the #294 case this disambiguates.
282
284
  */
283
285
  export function computeA2ASkillLabelSuffixes(siblingAgents) {
284
- const sorted = toSortableAgents(siblingAgents).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
286
+ // Ties (identical agent names) break on refName, whose `_N` tail is the
287
+ // export label's; ei breaks them on that label (edk#1728).
288
+ const order = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
289
+ const sorted = toSortableAgents(siblingAgents).sort((a, b) => order(a.name, b.name) || order(a.refName, b.refName));
285
290
  const counts = new Map();
286
291
  const suffixes = new Map();
287
292
  for (const agent of sorted) {
@@ -452,7 +452,7 @@ function executeWorkflowFromTf(block, name, where, owner, ctx) {
452
452
  }
453
453
  inputs.push({
454
454
  parameterName: rec["parameter_name"],
455
- ...(typeof rec["name"] === "string" && { name: rec["name"] }),
455
+ ...(typeof rec["display_name"] === "string" && { name: rec["display_name"] }),
456
456
  ...(typeof rec["description"] === "string" && { description: rec["description"] }),
457
457
  ...(typeof rec["required"] === "boolean" && { required: rec["required"] }),
458
458
  });
@@ -466,7 +466,7 @@ function executeWorkflowFromTf(block, name, where, owner, ctx) {
466
466
  }
467
467
  outputs.push({
468
468
  workflowPropertyName: rec["workflow_property_name"],
469
- ...(typeof rec["name"] === "string" && { name: rec["name"] }),
469
+ ...(typeof rec["display_name"] === "string" && { name: rec["display_name"] }),
470
470
  ...(typeof rec["description"] === "string" && { description: rec["description"] }),
471
471
  });
472
472
  }
@@ -129,7 +129,7 @@ function fieldRefValue(token, where, ctx, target) {
129
129
  // `elementCatalog` (see `FieldRef`'s doc comment) — but a field's own
130
130
  // `.ref()` on ITS OWN app/element stamps `parent` (as a self-reference)
131
131
  // without `parentKind` at all (a real, common shape — see e.g.
132
- // `__tests__/extract/update-record-tool.test.ts`'s fixture literals), so
132
+ // the former update-record-tool fixture literals), so
133
133
  // only a parent naming something OTHER than the tool's owning app is
134
134
  // genuinely ambiguous. Defaulting `parentKind` to "app" THERE instead of
135
135
  // failing loudly is the same silent-miss failure mode
@@ -255,6 +255,12 @@ export function toolToTf(entry, ctx) {
255
255
  if (inner.inputs !== undefined && inner.inputs.length > 0) {
256
256
  attrs["inputs"] = inner.inputs.map((i) => ({
257
257
  parameter_name: i.triggerParameterId?.name ?? "",
258
+ // The provider reads display_name back only when the agent-facing
259
+ // name differs from the parameter name (null otherwise), so emit it
260
+ // under the same rule or the plan drops the rename (#1734).
261
+ ...(i.name !== undefined &&
262
+ i.name !== "" &&
263
+ i.name !== i.triggerParameterId?.name && { display_name: i.name }),
258
264
  ...(i.description !== undefined && i.description !== "" && { description: i.description }),
259
265
  ...(i.required !== undefined && { required: i.required }),
260
266
  }));
@@ -262,6 +268,9 @@ export function toolToTf(entry, ctx) {
262
268
  if (inner.outputs !== undefined && inner.outputs.length > 0) {
263
269
  attrs["outputs"] = inner.outputs.map((o) => ({
264
270
  workflow_property_name: o.workflowPropertyName ?? "",
271
+ ...(o.name !== undefined &&
272
+ o.name !== "" &&
273
+ o.name !== o.workflowPropertyName && { display_name: o.name }),
265
274
  ...(o.description !== undefined && o.description !== "" && { description: o.description }),
266
275
  }));
267
276
  }
@@ -26,7 +26,8 @@ import type { AppDynamicLayout } from "../dynamic-layout/build.js";
26
26
  import type { AppRelationship } from "../relationship/build.js";
27
27
  import type { AppWidget } from "../widget/build.js";
28
28
  import type { DashboardWidget } from "../dashboard/build.js";
29
- import type { AppRole } from "../role/build.js";
29
+ import type { AppRole, RoleUserRef } from "../role/build.js";
30
+ import type { GroupRef } from "../../catalog/index.js";
30
31
  import type { AppServiceAccount } from "../service-account/build.js";
31
32
  import type { Filter } from "../shared/filters/types.js";
32
33
  import { type DisplayBlock } from "./display-blocks.js";
@@ -168,6 +169,20 @@ export interface AppField {
168
169
  readonly relatedLabelField?: FieldRef | UnsafePlatformId;
169
170
  /** `RELATION` only. Defaults to `true` on the platform. */
170
171
  readonly autoRelate?: boolean;
172
+ /**
173
+ * `GROUP` / `USER` only — restrict the picker (edk#1776). On a group field,
174
+ * only these groups can be picked; on a user field, only their members.
175
+ * `[]` removes a live restriction. Leaving it out over a live restriction
176
+ * fails the plan: pull to adopt it, or clear it explicitly.
177
+ */
178
+ readonly allowedGroups?: readonly GroupRef[];
179
+ /** `USER` only — users that can be picked besides `allowedGroups` members. `[]` removes a live restriction. */
180
+ readonly allowedUsers?: readonly RoleUserRef[];
181
+ /**
182
+ * `USER` only — a group field on the same app/element. The picker then
183
+ * offers only members of the group selected there. `null` removes a live link.
184
+ */
185
+ readonly parentGroupField?: FieldRef<string, string, "GROUP" | "GROUP_ID"> | null;
171
186
  }
172
187
  /** @deprecated Use `DropdownOption` and `dropdownOption(...)`. */
173
188
  export interface PicklistOption {
@@ -224,6 +239,21 @@ export interface AppSystemFieldOverride {
224
239
  export interface AppSystemPicklistOverride extends AppSystemFieldOverride {
225
240
  readonly options: readonly (string | PicklistOption)[];
226
241
  }
242
+ /** The stage override: like {@link AppSystemPicklistOverride}, but options may carry a stage `key`. */
243
+ export interface AppStagePicklistOverride extends AppSystemFieldOverride {
244
+ readonly options: readonly (string | AppStageOption)[];
245
+ }
246
+ /**
247
+ * A stage option. `key` is the Terraform alias the stage carries in
248
+ * `stages[].key` / `stage_ids_by_key`. Omit it for authored apps (the key
249
+ * derives from the label via `snakeSlug`). Pull writes it only when an
250
+ * imported stage's existing alias differs from that derivation (e.g.
251
+ * `"approval_&_execution"` for "Approval & Execution"), so an unchanged
252
+ * imported app keeps its stage identity on rebuild (#1136).
253
+ */
254
+ export interface AppStageOption extends PicklistOption {
255
+ readonly key?: string;
256
+ }
227
257
  /**
228
258
  * Overrides for the platform's auto-provisioned system fields, keyed by their
229
259
  * canonical ref names. Every entry (and the whole bag) is optional — author
@@ -236,7 +266,7 @@ export interface AppSystemFields {
236
266
  readonly id?: AppSystemFieldOverride;
237
267
  readonly title?: AppSystemFieldOverride;
238
268
  readonly status?: AppSystemPicklistOverride;
239
- readonly stage?: AppSystemPicklistOverride;
269
+ readonly stage?: AppStagePicklistOverride;
240
270
  readonly createdAt?: AppSystemFieldOverride;
241
271
  readonly createdBy?: AppSystemFieldOverride;
242
272
  readonly updatedAt?: AppSystemFieldOverride;
@@ -542,9 +572,11 @@ interface AppV2OptionsBase<F extends Record<string, AppField> = Record<string, A
542
572
  * else. Matching on the bag key instead of `name` is what lets a field's
543
573
  * identity survive a display-`name` rename instead of being keyed by the
544
574
  * mutable `name` (#230); the bag key itself is never rewritten by a rename,
545
- * since it's just the field's fixed key in `fields: {}`.
575
+ * since it's just the field's fixed key in `fields: {}`. `owner` (e.g.
576
+ * `app "Vendor Onboarding"`) only labels authoring errors, so fields that
577
+ * share a display name in different owners can be told apart.
546
578
  */
547
- export declare function serializeField(field: AppField, refName?: string): AspectFieldInput;
579
+ export declare function serializeField(field: AppField, refName?: string, owner?: string): AspectFieldInput;
548
580
  /**
549
581
  * Reject a custom `fields:` bag key that is ALSO authored under
550
582
  * `systemFields` — the same slot provisioned twice. Keys not present in