@elementumai/edk 0.8.0-preview.11 → 0.8.1

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 (165) hide show
  1. package/README.md +378 -324
  2. package/dist-sdk/src/catalog/ai-provider-models.d.ts +30 -0
  3. package/dist-sdk/src/catalog/ai-provider-models.js +63 -0
  4. package/dist-sdk/src/catalog/factories.d.ts +56 -3
  5. package/dist-sdk/src/catalog/factories.js +65 -2
  6. package/dist-sdk/src/catalog/from-authoring.js +6 -1
  7. package/dist-sdk/src/catalog/index.d.ts +3 -2
  8. package/dist-sdk/src/catalog/index.js +3 -2
  9. package/dist-sdk/src/catalog/org.d.ts +1 -1
  10. package/dist-sdk/src/catalog/org.js +83 -6
  11. package/dist-sdk/src/catalog/render.d.ts +13 -1
  12. package/dist-sdk/src/catalog/render.js +21 -4
  13. package/dist-sdk/src/catalog/token.js +14 -0
  14. package/dist-sdk/src/catalog/types.d.ts +60 -3
  15. package/dist-sdk/src/catalog/types.js +3 -0
  16. package/dist-sdk/src/core/system-fields.d.ts +2 -0
  17. package/dist-sdk/src/core/system-fields.js +2 -0
  18. package/dist-sdk/src/core/types/ai-provider.d.ts +10 -23
  19. package/dist-sdk/src/core/types/ai-provider.js +1 -25
  20. package/dist-sdk/src/core/types/app.d.ts +20 -1
  21. package/dist-sdk/src/engine/build/context.d.ts +18 -0
  22. package/dist-sdk/src/engine/build/source-context.d.ts +45 -0
  23. package/dist-sdk/src/engine/build/source-context.js +23 -0
  24. package/dist-sdk/src/engine/pull/context.d.ts +15 -0
  25. package/dist-sdk/src/engine/pull/org.d.ts +10 -0
  26. package/dist-sdk/src/engine/pull/org.js +34 -4
  27. package/dist-sdk/src/engine/tf/index.d.ts +1 -1
  28. package/dist-sdk/src/engine/tf/index.js +1 -1
  29. package/dist-sdk/src/engine/tf/labels.d.ts +45 -0
  30. package/dist-sdk/src/engine/tf/labels.js +71 -0
  31. package/dist-sdk/src/entities/access-policy/build.d.ts +26 -0
  32. package/dist-sdk/src/entities/access-policy/build.js +7 -0
  33. package/dist-sdk/src/entities/access-policy/filter.d.ts +61 -0
  34. package/dist-sdk/src/entities/access-policy/filter.js +83 -0
  35. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +48 -0
  36. package/dist-sdk/src/entities/access-policy/from-tf.js +189 -0
  37. package/dist-sdk/src/entities/access-policy/module.d.ts +3 -0
  38. package/dist-sdk/src/entities/access-policy/module.js +17 -0
  39. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +36 -0
  40. package/dist-sdk/src/entities/access-policy/to-tf.js +149 -0
  41. package/dist-sdk/src/entities/access-policy/types.d.ts +4 -0
  42. package/dist-sdk/src/entities/access-policy/types.js +10 -0
  43. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +38 -3
  44. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +199 -32
  45. package/dist-sdk/src/entities/agent/from-tf.d.ts +18 -3
  46. package/dist-sdk/src/entities/agent/from-tf.js +135 -15
  47. package/dist-sdk/src/entities/agent/index.d.ts +1 -1
  48. package/dist-sdk/src/entities/agent/module.js +8 -2
  49. package/dist-sdk/src/entities/agent/to-tf.js +62 -10
  50. package/dist-sdk/src/entities/agent/tools.d.ts +88 -9
  51. package/dist-sdk/src/entities/agent/tools.js +46 -7
  52. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +51 -4
  53. package/dist-sdk/src/entities/agent-tool/from-tf.js +131 -35
  54. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +4 -2
  55. package/dist-sdk/src/entities/agent-tool/to-tf.js +103 -17
  56. package/dist-sdk/src/entities/agent-tool/types.d.ts +5 -4
  57. package/dist-sdk/src/entities/agent-tool/types.js +38 -6
  58. package/dist-sdk/src/entities/app/build.d.ts +63 -13
  59. package/dist-sdk/src/entities/app/build.js +48 -1
  60. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +3 -0
  61. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -1
  62. package/dist-sdk/src/entities/app/from-tf.js +32 -15
  63. package/dist-sdk/src/entities/app/index.d.ts +4 -1
  64. package/dist-sdk/src/entities/app/index.js +2 -1
  65. package/dist-sdk/src/entities/app/module.js +9 -2
  66. package/dist-sdk/src/entities/app/to-tf.d.ts +5 -0
  67. package/dist-sdk/src/entities/app/to-tf.js +33 -4
  68. package/dist-sdk/src/entities/automation/build.d.ts +57 -13
  69. package/dist-sdk/src/entities/automation/build.js +48 -36
  70. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +25 -8
  71. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +16 -1
  72. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +179 -43
  73. package/dist-sdk/src/entities/automation/filter.d.ts +15 -3
  74. package/dist-sdk/src/entities/automation/filter.js +12 -2
  75. package/dist-sdk/src/entities/automation/from-tf.d.ts +26 -27
  76. package/dist-sdk/src/entities/automation/from-tf.js +1229 -223
  77. package/dist-sdk/src/entities/automation/index.d.ts +4 -0
  78. package/dist-sdk/src/entities/automation/index.js +4 -0
  79. package/dist-sdk/src/entities/automation/module.js +29 -32
  80. package/dist-sdk/src/entities/automation/operators.d.ts +29 -2
  81. package/dist-sdk/src/entities/automation/operators.js +27 -1
  82. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +19 -0
  83. package/dist-sdk/src/entities/automation/output-key-wire-name.js +24 -0
  84. package/dist-sdk/src/entities/automation/script-code.d.ts +10 -21
  85. package/dist-sdk/src/entities/automation/script-code.js +272 -5
  86. package/dist-sdk/src/entities/automation/tasks.d.ts +125 -19
  87. package/dist-sdk/src/entities/automation/tasks.js +83 -15
  88. package/dist-sdk/src/entities/automation/to-tf.d.ts +10 -29
  89. package/dist-sdk/src/entities/automation/to-tf.js +1134 -231
  90. package/dist-sdk/src/entities/automation/triggers.d.ts +9 -1
  91. package/dist-sdk/src/entities/automation/types.d.ts +29 -4
  92. package/dist-sdk/src/entities/automation/types.js +76 -46
  93. package/dist-sdk/src/entities/element/build.d.ts +23 -10
  94. package/dist-sdk/src/entities/element/build.js +1 -0
  95. package/dist-sdk/src/entities/element/from-tf.d.ts +1 -1
  96. package/dist-sdk/src/entities/element/from-tf.js +18 -3
  97. package/dist-sdk/src/entities/element/index.d.ts +4 -1
  98. package/dist-sdk/src/entities/element/index.js +2 -1
  99. package/dist-sdk/src/entities/element/module.js +3 -1
  100. package/dist-sdk/src/entities/element/to-tf.js +21 -3
  101. package/dist-sdk/src/entities/field/build.d.ts +56 -13
  102. package/dist-sdk/src/entities/field/build.js +10 -0
  103. package/dist-sdk/src/entities/field/calc/runtime.js +4 -0
  104. package/dist-sdk/src/entities/field/from-tf.d.ts +5 -3
  105. package/dist-sdk/src/entities/field/from-tf.js +118 -7
  106. package/dist-sdk/src/entities/field/module.js +3 -2
  107. package/dist-sdk/src/entities/field/to-tf.d.ts +27 -9
  108. package/dist-sdk/src/entities/field/to-tf.js +62 -17
  109. package/dist-sdk/src/entities/field/types.d.ts +26 -0
  110. package/dist-sdk/src/entities/field/types.js +34 -12
  111. package/dist-sdk/src/entities/file-reader/build.d.ts +108 -50
  112. package/dist-sdk/src/entities/file-reader/build.js +23 -23
  113. package/dist-sdk/src/entities/file-reader/deserializer/print-file-reader.d.ts +6 -0
  114. package/dist-sdk/src/entities/file-reader/deserializer/print-file-reader.js +109 -0
  115. package/dist-sdk/src/entities/file-reader/from-tf.d.ts +13 -0
  116. package/dist-sdk/src/entities/file-reader/from-tf.js +172 -0
  117. package/dist-sdk/src/entities/file-reader/index.d.ts +8 -3
  118. package/dist-sdk/src/entities/file-reader/index.js +7 -2
  119. package/dist-sdk/src/entities/file-reader/module.d.ts +3 -0
  120. package/dist-sdk/src/entities/file-reader/module.js +115 -0
  121. package/dist-sdk/src/entities/file-reader/to-tf.d.ts +14 -0
  122. package/dist-sdk/src/entities/file-reader/to-tf.js +84 -0
  123. package/dist-sdk/src/entities/file-reader/types.d.ts +32 -0
  124. package/dist-sdk/src/entities/file-reader/types.js +30 -0
  125. package/dist-sdk/src/entities/org/ai-provider.d.ts +13 -0
  126. package/dist-sdk/src/entities/org/ai-provider.js +46 -0
  127. package/dist-sdk/src/entities/org/connector.d.ts +8 -1
  128. package/dist-sdk/src/entities/org/connector.js +12 -14
  129. package/dist-sdk/src/entities/org/group.js +10 -1
  130. package/dist-sdk/src/entities/org/index.d.ts +1 -0
  131. package/dist-sdk/src/entities/org/index.js +1 -0
  132. package/dist-sdk/src/entities/org/user.js +10 -1
  133. package/dist-sdk/src/entities/shared/filters/ast.d.ts +44 -9
  134. package/dist-sdk/src/entities/shared/filters/types.d.ts +1 -1
  135. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +17 -0
  136. package/dist-sdk/src/entities/shared/tool-field-ref.js +31 -0
  137. package/dist-sdk/src/entities/shared/types/field-types.d.ts +10 -1
  138. package/dist-sdk/src/entities/shared/types/field-types.js +9 -0
  139. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +19 -0
  140. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +36 -8
  141. package/dist-sdk/src/entities/skill/from-tf.js +4 -3
  142. package/dist-sdk/src/entities/skill/index.d.ts +1 -1
  143. package/dist-sdk/src/entities/skill/module.js +6 -1
  144. package/dist-sdk/src/entities/skill/to-tf.js +3 -2
  145. package/dist-sdk/src/entities/skill/tools.d.ts +25 -3
  146. package/dist-sdk/src/entities/skill/tools.js +17 -0
  147. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +15 -2
  148. package/dist-sdk/src/entities/skill-tool/from-tf.js +32 -11
  149. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +2 -0
  150. package/dist-sdk/src/entities/skill-tool/to-tf.js +32 -9
  151. package/dist-sdk/src/entities/view/from-tf.d.ts +6 -2
  152. package/dist-sdk/src/entities/view/from-tf.js +11 -9
  153. package/dist-sdk/src/entities/view/to-tf.d.ts +9 -7
  154. package/dist-sdk/src/entities/view/to-tf.js +33 -18
  155. package/dist-sdk/src/entities/view/types.d.ts +1 -1
  156. package/dist-sdk/src/entities/view/types.js +1 -1
  157. package/dist-sdk/src/graph/deferred-catalog-render.d.ts +0 -5
  158. package/dist-sdk/src/graph/deferred-catalog-render.js +1 -20
  159. package/dist-sdk/src/graph/index.d.ts +8 -0
  160. package/dist-sdk/src/graph/index.js +13 -9
  161. package/dist-sdk/src/graph/modules.js +6 -1
  162. package/dist-sdk/src/graph/types.d.ts +77 -3
  163. package/package.json +42 -14
  164. package/dist-sdk/src/entities/automation/value-ref-tf.d.ts +0 -76
  165. package/dist-sdk/src/entities/automation/value-ref-tf.js +0 -190
@@ -23,6 +23,7 @@
23
23
  * schema is authoring-only — at the wire boundary `resolvePayload` replaces the
24
24
  * whole token with the resolved id, discarding it.
25
25
  */
26
+ import type { AiProviderLlmModel, AiProviderType } from "./ai-provider-models.js";
26
27
  /**
27
28
  * Kinds a catalog fragment can describe:
28
29
  * - behavioral, app-owned, deployable — `automation` / `agent` / `skill`;
@@ -34,7 +35,7 @@
34
35
  * resolved to the current-version param/output id via the parent
35
36
  * automation's state binding.
36
37
  */
37
- export type CatalogRefKind = "automation" | "agent" | "skill" | "flow" | "approvalChain" | "table" | "tableColumn" | "cloudLink" | "field" | "searchTable" | "documentModel" | "documentModelField" | "connector" | "category" | "group" | "app" | "element" | "triggerParameter" | "outputProperty";
38
+ export type CatalogRefKind = "automation" | "agent" | "skill" | "flow" | "approvalChain" | "table" | "tableColumn" | "cloudLink" | "field" | "searchTable" | "documentModel" | "documentModelField" | "connector" | "aiProvider" | "category" | "group" | "app" | "element" | "triggerParameter" | "outputProperty";
38
39
  /**
39
40
  * The reference surface for a catalog entity. `handle` is the stable join key
40
41
  * (no id); `name` is for readability/diagnostics, never a match key.
@@ -65,9 +66,22 @@ export interface AutomationRef<TTrigger = unknown, TOutput = unknown> extends Ca
65
66
  readonly output?: TOutput;
66
67
  }
67
68
  export type AgentRef = CatalogRef<"agent">;
68
- export type SkillRef = CatalogRef<"skill">;
69
+ export interface SkillRef extends CatalogRef<"skill"> {
70
+ /**
71
+ * A raw platform id, when the export carries a `skill_ids`/
72
+ * `preloaded_skill_ids` entry that resolves to neither a self-app resource
73
+ * ref nor a foreign-app `data.elementum_agentic_skill` block (no name to
74
+ * key a lookup by at all) — same escape as `ApprovalChainRef`'s. Present
75
+ * only takes over resolution at build; `refName`/`name` still exist (both
76
+ * the raw id) purely to satisfy `SkillRef`'s shape.
77
+ */
78
+ readonly unresolvedId?: string;
79
+ }
69
80
  export type FlowRef = CatalogRef<"flow">;
70
- export type ApprovalChainRef = CatalogRef<"approvalChain">;
81
+ export interface ApprovalChainRef extends CatalogRef<"approvalChain"> {
82
+ /** Provider id retained only when no managed/data HCL reference exists. */
83
+ readonly unresolvedId?: string;
84
+ }
71
85
  export interface TableColumnRef extends CatalogRef<"tableColumn"> {
72
86
  /** Owning table handle. */
73
87
  readonly parent: string;
@@ -81,6 +95,27 @@ export interface TableRef extends CatalogRef<"table"> {
81
95
  }
82
96
  export type SearchTableRef = CatalogRef<"searchTable">;
83
97
  export type ConnectorRef = CatalogRef<"connector">;
98
+ /**
99
+ * An AI provider reference that also exposes its enabled connectors as a
100
+ * nested ref bag — models are referenceable *on* the provider
101
+ * (`catalog.aiProviders.<provider>.models.<model>`), the same nested-ref-bag
102
+ * shape `AutomationCatalogRef`/`FileReaderCatalogRef` already use. Reference
103
+ * only — the provider must already exist on the platform; there is no
104
+ * create/deploy path (src/CLAUDE.md). Generic over `T` so `type: "anthropic"`
105
+ * narrows which models are valid in `models` (see `AiProviderLlmModel`).
106
+ */
107
+ export interface AiProviderRef<T extends AiProviderType = AiProviderType> extends CatalogRef<"aiProvider"> {
108
+ /** Which AI provider family this is (e.g. "anthropic", "bedrock") — build maps it to the matching `elementum_<type>_ai_provider` terraform data source; authored source never names the resource type directly. */
109
+ readonly type: T;
110
+ /**
111
+ * Each entry is either a reference to an already-pulled connector
112
+ * (`connectorRef({ name })`, what `pull org` always emits) or a bare model
113
+ * literal naming a connector to create for that model — type-checked
114
+ * against `T`'s valid models. The create path has no build/authoring-
115
+ * location wiring yet; this is the type surface only.
116
+ */
117
+ readonly models?: Readonly<Record<string, ConnectorRef | AiProviderLlmModel<T>>>;
118
+ }
84
119
  export type CloudLinkRef = CatalogRef<"cloudLink">;
85
120
  /** Org-owned reference identities from `elementum pull org --data-only` (pristine-refactor). */
86
121
  export type CategoryRef = CatalogRef<"category">;
@@ -96,6 +131,21 @@ export type AspectRef = CatalogRef<"app"> | CatalogRef<"element">;
96
131
  export interface FieldRef extends CatalogRef<"field"> {
97
132
  readonly fieldType: string;
98
133
  readonly tags?: readonly string[];
134
+ readonly options?: readonly string[];
135
+ }
136
+ /** Platform-owned user attributes accepted by user-search task filters. */
137
+ export declare const USER_FIELD_KEYS: readonly ["firstName", "email", "jobTitle", "lastName"];
138
+ export type UserFieldKey = (typeof USER_FIELD_KEYS)[number];
139
+ /**
140
+ * A virtual catalog ref for the fixed user-directory schema. Unlike an app
141
+ * FieldRef, this token serializes to its literal platform key (there is no
142
+ * entity id to resolve).
143
+ */
144
+ export interface UserFieldRef {
145
+ readonly __kind: "userField";
146
+ readonly refName: UserFieldKey;
147
+ readonly name: UserFieldKey;
148
+ readonly fieldType: "TEXT";
99
149
  }
100
150
  export interface TriggerParameterRef extends CatalogRef<"triggerParameter"> {
101
151
  /**
@@ -116,6 +166,13 @@ export type DocumentModelFieldRef = CatalogRef<"documentModelField">;
116
166
  * nested ref is this document model's handle.
117
167
  */
118
168
  export interface FileReaderCatalogRef extends CatalogRef<"documentModel"> {
169
+ /**
170
+ * Which of the platform's file-reader resource types this token points at
171
+ * — `elementum_file_reader_task.file_reader_id` accepts excel/json/text
172
+ * readers only, and build needs the exact resource type (not just a name)
173
+ * to emit the right `elementum_<type>_file_reader.<label>.id` reference.
174
+ */
175
+ readonly readerType: "excel" | "json" | "text" | "xml" | "ai";
119
176
  readonly fields?: Readonly<Record<string, DocumentModelFieldRef>>;
120
177
  }
121
178
  /**
@@ -23,6 +23,8 @@
23
23
  * schema is authoring-only — at the wire boundary `resolvePayload` replaces the
24
24
  * whole token with the resolved id, discarding it.
25
25
  */
26
+ /** Platform-owned user attributes accepted by user-search task filters. */
27
+ export const USER_FIELD_KEYS = ["firstName", "email", "jobTitle", "lastName"];
26
28
  /**
27
29
  * Which scope resolves a kind's id at deploy:
28
30
  * - `"app"` — the app's v2 state (app-owned entities + fields/tables);
@@ -44,6 +46,7 @@ export const REF_SCOPE = {
44
46
  documentModel: "app",
45
47
  documentModelField: "app",
46
48
  connector: "org",
49
+ aiProvider: "org",
47
50
  category: "org",
48
51
  group: "org",
49
52
  app: "registry",
@@ -65,6 +65,8 @@ export declare const SYSTEM_FIELD_TAG_BY_KEY: {
65
65
  export type SystemFieldKey = keyof typeof SYSTEM_FIELD_TAG_BY_KEY;
66
66
  /** All canonical keys, in platform rank order (HANDLE first … CLOSED_BY last). */
67
67
  export declare const SYSTEM_FIELD_KEYS: readonly SystemFieldKey[];
68
+ /** `SYSTEM_FIELD_KEYS` as a set — for O(1) "is this key a system field?" checks (e.g. distinguishing a system field from a custom field by bag key alone). */
69
+ export declare const SYSTEM_FIELD_KEY_SET: ReadonlySet<SystemFieldKey>;
68
70
  export declare const SYSTEM_FIELD_KEY_BY_TAG: Readonly<Record<string, SystemFieldKey>>;
69
71
  /**
70
72
  * What a NO-OVERRIDE deploy produces — the terraform provider's auto-create
@@ -101,6 +101,8 @@ export const SYSTEM_FIELD_TAG_BY_KEY = {
101
101
  };
102
102
  /** All canonical keys, in platform rank order (HANDLE first … CLOSED_BY last). */
103
103
  export const SYSTEM_FIELD_KEYS = Object.keys(SYSTEM_FIELD_TAG_BY_KEY);
104
+ /** `SYSTEM_FIELD_KEYS` as a set — for O(1) "is this key a system field?" checks (e.g. distinguishing a system field from a custom field by bag key alone). */
105
+ export const SYSTEM_FIELD_KEY_SET = new Set(SYSTEM_FIELD_KEYS);
104
106
  export const SYSTEM_FIELD_KEY_BY_TAG = Object.fromEntries(Object.entries(SYSTEM_FIELD_TAG_BY_KEY).map(([k, tag]) => [tag, k]));
105
107
  /**
106
108
  * What a NO-OVERRIDE deploy produces — the terraform provider's auto-create
@@ -1,27 +1,13 @@
1
1
  /**
2
- * AI provider connector descriptor — a typed handle to a registered
3
- * AI provider connector (OpenAI, Anthropic, etc.) on the Elementum platform.
4
- *
5
- * Defined once and shared across agents so callers reference the same typed
6
- * object everywhere (mirroring the `App`, `AppAgent`, `AppAutomation` pattern),
7
- * rather than re-typing a raw `{ id }` blob at each agent site.
8
- *
9
- * ```ts
10
- * // connectors/ai-providers.ts
11
- * export const openAiGpt5 = defineAiProviderConnector({
12
- * id: "ab100edd-b301-4a16-b269-e5347449ad9b",
13
- * name: "ChatGPT 5 (OpenAI)",
14
- * model: "GPT_5",
15
- * });
16
- *
17
- * // agents/support-agent.ts
18
- * import { openAiGpt5 } from "../connectors/ai-providers.js";
19
- *
20
- * defineAgent({
21
- * aiProviderConnector: openAiGpt5,
22
- * // ...
23
- * });
24
- * ```
2
+ * @deprecated v1 authoring pattern — hand-typed with a raw platform UUID,
3
+ * exactly the "no ids in authored source" bug CLAUDE.md's Gotchas section
4
+ * warns about. Superseded by the pulled `aiProviders` catalog: providers and
5
+ * their connectors are discovered by `elementum pull org --data-only`, never
6
+ * hand-authored (they hold credentials, manually configured on the
7
+ * platform), and referenced as `catalog.aiProviders.<provider>.models.<model>`
8
+ * — e.g. `connector: catalog.aiProviders.anthropic.models.claudeOpus_4_6`.
9
+ * Kept only because it's re-exported through the published
10
+ * `@elementumai/edk/core` entry; do not use in new code.
25
11
  */
26
12
  export interface AiProviderConnector {
27
13
  readonly id: string;
@@ -29,6 +15,7 @@ export interface AiProviderConnector {
29
15
  /** Model identifier (e.g. "gpt-4o", "claude-3-5-sonnet"). Metadata only — the platform uses the connector's configured model. */
30
16
  readonly model?: string;
31
17
  }
18
+ /** @deprecated Use the pulled `catalog.aiProviders.<provider>.models.<model>` token instead — see {@link AiProviderConnector}. */
32
19
  export declare function defineAiProviderConnector(opts: {
33
20
  id: string;
34
21
  name?: string;
@@ -1,28 +1,4 @@
1
- /**
2
- * AI provider connector descriptor — a typed handle to a registered
3
- * AI provider connector (OpenAI, Anthropic, etc.) on the Elementum platform.
4
- *
5
- * Defined once and shared across agents so callers reference the same typed
6
- * object everywhere (mirroring the `App`, `AppAgent`, `AppAutomation` pattern),
7
- * rather than re-typing a raw `{ id }` blob at each agent site.
8
- *
9
- * ```ts
10
- * // connectors/ai-providers.ts
11
- * export const openAiGpt5 = defineAiProviderConnector({
12
- * id: "ab100edd-b301-4a16-b269-e5347449ad9b",
13
- * name: "ChatGPT 5 (OpenAI)",
14
- * model: "GPT_5",
15
- * });
16
- *
17
- * // agents/support-agent.ts
18
- * import { openAiGpt5 } from "../connectors/ai-providers.js";
19
- *
20
- * defineAgent({
21
- * aiProviderConnector: openAiGpt5,
22
- * // ...
23
- * });
24
- * ```
25
- */
1
+ /** @deprecated Use the pulled `catalog.aiProviders.<provider>.models.<model>` token instead — see {@link AiProviderConnector}. */
26
2
  export function defineAiProviderConnector(opts) {
27
3
  return {
28
4
  id: opts.id,
@@ -171,6 +171,8 @@ export interface NumberAppField<Scope extends FieldScope = "unscoped"> extends A
171
171
  export interface DecimalAppField<Scope extends FieldScope = "unscoped"> extends AspectFieldBase<Scope> {
172
172
  readonly type: "DECIMAL";
173
173
  readonly numericFormat?: AspectNumericFieldFormat;
174
+ /** Display/storage precision (`elementum_decimal_field.decimal_places`). */
175
+ readonly decimalPlaces?: number;
174
176
  }
175
177
  /** BOOLEAN fields. */
176
178
  export interface BooleanAppField<Scope extends FieldScope = "unscoped"> extends AspectFieldBase<Scope> {
@@ -275,6 +277,23 @@ export interface AttachmentAppField<Scope extends FieldScope = "unscoped"> exten
275
277
  readonly type: "ATTACHMENT" | "ATTACHMENT_ID";
276
278
  readonly mediaTypes?: readonly string[];
277
279
  }
280
+ /**
281
+ * RELATION fields (`elementum_relation_field`) - a dynamic dropdown whose
282
+ * options are records from another App/Element/Task, distinct from a
283
+ * static PICKLIST (no fixed `options` list at all). `relatedAspectId`/
284
+ * `relatedLabelFieldId` are raw platform ids, not catalog tokens: a
285
+ * non-recursive `ei apps export` never discovers the related aspect's own
286
+ * identity (confirmed live), so there's no catalog entry to resolve them
287
+ * against - same "round-trip the raw id verbatim" escape already used for
288
+ * other genuinely cross-scope references this SDK can't otherwise name.
289
+ */
290
+ export interface RelationAppField<Scope extends FieldScope = "unscoped"> extends AspectFieldBase<Scope> {
291
+ readonly type: "RELATION";
292
+ readonly relatedAspectId: string;
293
+ readonly relatedLabelFieldId: string;
294
+ /** Defaults to `true` on the platform. */
295
+ readonly autoRelate?: boolean;
296
+ }
278
297
  /**
279
298
  * Branded result of the `calc.*` builder. The brand is opaque on the
280
299
  * author surface — agents never construct this directly; they call
@@ -315,7 +334,7 @@ export interface CalculatedAppField<Scope extends FieldScope = "unscoped"> exten
315
334
  * NumberAppField, `picklistValues` on PicklistAppField, etc.) are
316
335
  * statically gated to the right variant.
317
336
  */
318
- export type AppField<Scope extends FieldScope = "unscoped"> = TextAppField<Scope> | HandleAppField<Scope> | NumberAppField<Scope> | DecimalAppField<Scope> | BooleanAppField<Scope> | DateAppField<Scope> | DateTimeAppField<Scope> | HtmlAppField<Scope> | JsonAppField<Scope> | PicklistAppField<Scope> | MultiPicklistAppField<Scope> | UserAppField<Scope> | GroupAppField<Scope> | AttachmentAppField<Scope> | CalculatedAppField<Scope>;
337
+ export type AppField<Scope extends FieldScope = "unscoped"> = TextAppField<Scope> | HandleAppField<Scope> | NumberAppField<Scope> | DecimalAppField<Scope> | BooleanAppField<Scope> | DateAppField<Scope> | DateTimeAppField<Scope> | HtmlAppField<Scope> | JsonAppField<Scope> | PicklistAppField<Scope> | MultiPicklistAppField<Scope> | UserAppField<Scope> | GroupAppField<Scope> | AttachmentAppField<Scope> | RelationAppField<Scope> | CalculatedAppField<Scope>;
319
338
  export interface AppAgent {
320
339
  readonly id: string;
321
340
  readonly name?: string;
@@ -39,8 +39,26 @@ export interface OrgRefLookup {
39
39
  * `foreignApp`.
40
40
  */
41
41
  foreignSkill(tfLabel: string, name: string): void;
42
+ /**
43
+ * Record an arbitrary data lookup by its EXACT captured label and
44
+ * lookup-attr value, bypassing org.ts bag validation — used when the
45
+ * reference isn't drawn from an org.ts bag at all (a group/user field's
46
+ * round-tripped `default_value`, where ei's own data block label is
47
+ * already known from extraction and must be reproduced byte-for-byte,
48
+ * unlike `byName`'s category precedent which re-derives the label from a
49
+ * hand-authored display name).
50
+ */
51
+ rawLookup(type: string, tfLabel: string, value: string): void;
52
+ /**
53
+ * Record a name-keyed `data.elementum_element` lookup for a FOREIGN
54
+ * element (e.g. a cross-aspect agent-tool target — board issue #42).
55
+ * Same discipline as `foreignApp`, distinct resource type.
56
+ */
57
+ foreignElement(tfLabel: string, name: string): void;
42
58
  }
43
59
  export interface ToTfContext {
60
+ /** The owning app's refName — its authoring directory / catalog key. */
61
+ readonly appRefName: string;
44
62
  /** The owning app's tfLabel — its namespace (immutable; ei's namespace-first rule). */
45
63
  readonly appTfLabel: string;
46
64
  readonly orgRefs: OrgRefLookup;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Generic "what file is jiti currently importing, and what's its own
3
+ * untranspiled text" context for `elementum build`'s own-file-child loader.
4
+ *
5
+ * Entity-agnostic on purpose: `engine/` may not import from `entities/`
6
+ * (`__tests__/engine/no-entity-types-in-engine.test.ts`), so this exists
7
+ * purely as plumbing — it knows nothing about automations or any other
8
+ * entity kind. An entity module (e.g. `entities/automation/script-code.ts`)
9
+ * that needs byte-exact access to its own source text — because jiti/Babel's
10
+ * transpile-then-`toString()` round trip would otherwise reformat it —
11
+ * imports {@link currentSourceText} from here (entities/ importing engine/ is
12
+ * the normal direction; only the reverse is forbidden).
13
+ *
14
+ * State lives on `globalThis` (via a `Symbol.for` registry key), not a plain
15
+ * module-scoped variable, for two independent reasons:
16
+ * - `AsyncLocalStorage` was tried first and rejected: jiti's own `.import()`
17
+ * wraps transform + a dynamic `import()` through its own internal
18
+ * scheduling, which does not reliably propagate ALS continuation context
19
+ * through to where the imported module's top-level code actually runs
20
+ * (confirmed empirically — that version silently lost context there).
21
+ * - A plain module-scoped variable has a SEPARATE failure mode: when jiti
22
+ * transforms a `.ts` file that itself imports this module (as opposed to
23
+ * already-compiled `.js`, which jiti can hand off to Node's native
24
+ * loader), jiti may instantiate its OWN, isolated copy of this module —
25
+ * a different module-registry entry than the one `elementum build`'s own
26
+ * (natively-loaded) code holds, so writes through one are invisible to
27
+ * reads through the other. `globalThis` is the one thing guaranteed
28
+ * shared across however many separate module instances end up loaded in
29
+ * the same process.
30
+ *
31
+ * `elementum build`'s own-file-child loader still imports one file at a time
32
+ * in a sequential loop (never concurrently) — see `discoverOwnFileChildren`
33
+ * in `build.ts`. Do not parallelize that loop without revisiting this.
34
+ */
35
+ export interface SourceTextContext {
36
+ readonly filePath: string;
37
+ readonly text: string;
38
+ }
39
+ /**
40
+ * Run `fn` (a jiti module import) with `filePath`'s own text available via
41
+ * {@link currentSourceText} for the duration of the returned promise.
42
+ */
43
+ export declare function withSourceText<T>(filePath: string, text: string, fn: () => Promise<T>): Promise<T>;
44
+ /** The file/text currently being imported via {@link withSourceText}, or undefined outside that context. */
45
+ export declare function currentSourceText(): SourceTextContext | undefined;
@@ -0,0 +1,23 @@
1
+ const GLOBAL_KEY = Symbol.for("elementumEdk.engine.build.currentSourceText");
2
+ function slot() {
3
+ return globalThis;
4
+ }
5
+ /**
6
+ * Run `fn` (a jiti module import) with `filePath`'s own text available via
7
+ * {@link currentSourceText} for the duration of the returned promise.
8
+ */
9
+ export async function withSourceText(filePath, text, fn) {
10
+ const g = slot();
11
+ const previous = g[GLOBAL_KEY];
12
+ g[GLOBAL_KEY] = { filePath, text };
13
+ try {
14
+ return await fn();
15
+ }
16
+ finally {
17
+ g[GLOBAL_KEY] = previous;
18
+ }
19
+ }
20
+ /** The file/text currently being imported via {@link withSourceText}, or undefined outside that context. */
21
+ export function currentSourceText() {
22
+ return slot()[GLOBAL_KEY];
23
+ }
@@ -5,14 +5,29 @@
5
5
  * resource type. (The emission-side twin is src/engine/build/context.ts.)
6
6
  */
7
7
  import { type TfValue } from "../tf/index.js";
8
+ /** A `data-attr` reference recorded on a data block in the same stream. */
9
+ export interface DataRef {
10
+ readonly resourceType: string;
11
+ readonly tfLabel: string;
12
+ }
8
13
  /** Extraction context: stream lookups + the diagnostics sink. */
9
14
  export interface FromTfContext {
10
15
  /** Lookup-attr value of a data block in the same stream: ("elementum_category", "experiments") → "Experiments". */
11
16
  dataName(type: string, label: string): string | undefined;
17
+ /** DataFacet.providerRefAttr's resolved reference on a data block in the same stream (connector's `provider_id` → its owning `elementum_<type>_ai_provider` block). */
18
+ dataRef(type: string, label: string): DataRef | undefined;
12
19
  /** Platform id recorded by the stream's import blocks, by resource address. */
13
20
  importId(address: string): string | undefined;
14
21
  /** Degradations land here — reported by the caller, never silent. */
15
22
  readonly diagnostics: string[];
23
+ /**
24
+ * Resource addresses that must NOT be adopted - nothing in authored
25
+ * source can reproduce them (e.g. a known-but-unimplemented field
26
+ * sub-type). Excluded from adoption's targeted plan even though ei's own
27
+ * export otherwise carries a valid import block for them - see
28
+ * `field/from-tf.ts`'s `implemented` check for the motivating case.
29
+ */
30
+ readonly skipped: string[];
16
31
  }
17
32
  /** `data.<type>.<label>.id` → the label; undefined for any other shape. */
18
33
  export declare function dataRefLabel(v: TfValue | undefined, type: string): string | undefined;
@@ -18,6 +18,11 @@
18
18
  * contract; changing it is an upgrade/migration event.
19
19
  */
20
20
  import type { TfDocument } from "../tf/index.js";
21
+ /** A `data-attr` reference to another org identity's own data block. */
22
+ export interface OrgIdentityRef {
23
+ readonly resourceType: string;
24
+ readonly tfLabel: string;
25
+ }
21
26
  /** One org-owned reference identity from the export stream. */
22
27
  export interface OrgIdentity {
23
28
  /** Authoring token key: tsLabel = the bijective camelCase image of tfLabel. */
@@ -29,11 +34,16 @@ export interface OrgIdentity {
29
34
  readonly name: string;
30
35
  /** The exported terraform label (in-memory provenance; equals tsLabelToTfLabel(tsLabel), never persisted). */
31
36
  readonly tfLabel: string;
37
+ /** The data block's own terraform type — a bag can span multiple types (aiProviders: 10 distinct `elementum_<type>_ai_provider` types). */
38
+ readonly resourceType: string;
39
+ /** DataFacet.providerRefAttr's resolved reference (connector's `provider_id` → its owning `elementum_<type>_ai_provider` block), when the kind has one. */
40
+ readonly providerRef?: OrgIdentityRef;
32
41
  }
33
42
  export interface OrgExtract {
34
43
  readonly cloudLinks: readonly OrgIdentity[];
35
44
  readonly categories: readonly OrgIdentity[];
36
45
  readonly connectors: readonly OrgIdentity[];
46
+ readonly aiProviders: readonly OrgIdentity[];
37
47
  readonly groups: readonly OrgIdentity[];
38
48
  /** The org app directory (namespace → platform id) from locals.org_apps. */
39
49
  readonly apps: Readonly<Record<string, string>>;
@@ -18,7 +18,7 @@
18
18
  * contract; changing it is an upgrade/migration event.
19
19
  */
20
20
  import { DATA_FACET_BY_TYPE } from "../../graph/index.js";
21
- import { tfLabelToTsLabel } from "../tf/index.js";
21
+ import { isTfExpr, tfLabelToTsLabel } from "../tf/index.js";
22
22
  export class OrgExtractError extends Error {
23
23
  constructor(message) {
24
24
  super(message);
@@ -30,21 +30,36 @@ export function extractOrg(doc) {
30
30
  cloudLinks: [],
31
31
  categories: [],
32
32
  connectors: [],
33
+ aiProviders: [],
33
34
  groups: [],
34
35
  };
35
36
  let apps;
36
37
  for (const block of doc.blocks) {
37
38
  if (block.kind === "data") {
38
- const kind = DATA_FACET_BY_TYPE.get(block.type ?? "");
39
+ const type = block.type ?? "";
40
+ const kind = DATA_FACET_BY_TYPE.get(type);
39
41
  const orgBag = kind?.data.participates === true ? kind.data.orgBag : undefined;
40
42
  // A data facet without orgBag (e.g. elementum_user, foreign app) is
41
43
  // app-stream-only — presence here is contract drift like an unknown type.
42
44
  if (orgBag === undefined || kind?.data.participates !== true) {
43
45
  throw new OrgExtractError(`unexpected data source "${block.type}" in org export stream — the M0 contract grew; extend the extractor deliberately`);
44
46
  }
47
+ const tfLabel = requireLabel(block);
45
48
  raw[orgBag].push({
46
49
  name: requireStringAttr(block, kind.data.lookupAttr),
47
- tfLabel: requireLabel(block),
50
+ tfLabel,
51
+ resourceType: type,
52
+ // `provider_id` is a REAL ref only when the connector's provider was
53
+ // also exported (`writeConnectorDataBlocks`, cmd/elementum/export/
54
+ // org_export.go) — otherwise the bridge falls back to a
55
+ // `provider_name` string, or emits neither at all for an orphaned
56
+ // connector (no provider on the platform side). So the attribute's
57
+ // mere absence is a legitimate dialect branch, not contract drift —
58
+ // only demand `requireDataRef`'s shape when the attribute is
59
+ // actually present; malformed-but-present still fails loud.
60
+ providerRef: kind.data.providerRefAttr !== undefined && block.attrs[kind.data.providerRefAttr] !== undefined
61
+ ? requireDataRef(block, kind.data.providerRefAttr, tfLabel)
62
+ : undefined,
48
63
  });
49
64
  continue;
50
65
  }
@@ -65,6 +80,7 @@ export function extractOrg(doc) {
65
80
  cloudLinks: withTsLabels(raw.cloudLinks),
66
81
  categories: withTsLabels(raw.categories),
67
82
  connectors: withTsLabels(raw.connectors),
83
+ aiProviders: withTsLabels(raw.aiProviders),
68
84
  groups: withTsLabels(raw.groups),
69
85
  apps,
70
86
  };
@@ -73,9 +89,23 @@ export function extractOrg(doc) {
73
89
  * lossless, and unique because ei's tfLabels are unique per type. */
74
90
  function withTsLabels(entities) {
75
91
  return entities
76
- .map((e) => ({ tsLabel: tfLabelToTsLabel(e.tfLabel), name: e.name, tfLabel: e.tfLabel }))
92
+ .map((e) => ({
93
+ tsLabel: tfLabelToTsLabel(e.tfLabel),
94
+ name: e.name,
95
+ tfLabel: e.tfLabel,
96
+ resourceType: e.resourceType,
97
+ providerRef: e.providerRef,
98
+ }))
77
99
  .sort((a, b) => a.tsLabel.localeCompare(b.tsLabel));
78
100
  }
101
+ /** A `providerRefAttr` value must be a `data-attr` reference's `.id` — loud otherwise (contract drift, not silent). */
102
+ function requireDataRef(block, attr, tfLabel) {
103
+ const v = block.attrs[attr];
104
+ if (isTfExpr(v) && v.$expr === "data-attr" && v.path.length === 1 && v.path[0] === "id") {
105
+ return { resourceType: v.type, tfLabel: v.label };
106
+ }
107
+ throw new OrgExtractError(`data "${block.type}" "${tfLabel}": expected "${attr}" to be a data source reference, got ${JSON.stringify(v)}`);
108
+ }
79
109
  function requireLabel(block) {
80
110
  if (!block.label) {
81
111
  throw new OrgExtractError(`data "${block.type}" block is missing its label`);
@@ -9,4 +9,4 @@ export { decodeTemplateEscapes, encodeTemplateEscapes, quoteHclString } from "./
9
9
  export { parseExpression, parseStringValue, TfExprError } from "./expr.js";
10
10
  export { assertNoUnsafeIntegers, parseHcl, TfParseError } from "./parse.js";
11
11
  export { renderBlock, renderDocument } from "./render.js";
12
- export { isCanonicalTsLabel, sanitizeName, snakeSlug, splitCamelCase, tfLabelToTsLabel, tsLabelToTfLabel } from "./labels.js";
12
+ export { appResourceLabelPrefix, appScopedResourceLabel, bareChildResourceLabel, childPartFromScopedLabel, elementResourceLabelPrefix, elementScopedResourceLabel, isCanonicalTsLabel, isUuid, ownerChildBareLabel, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, snakeSlug, splitCamelCase, tfLabelToTsLabel, tsLabelToTfLabel, type ChildResourceScope, } from "./labels.js";
@@ -8,4 +8,4 @@ export { decodeTemplateEscapes, encodeTemplateEscapes, quoteHclString } from "./
8
8
  export { parseExpression, parseStringValue, TfExprError } from "./expr.js";
9
9
  export { assertNoUnsafeIntegers, parseHcl, TfParseError } from "./parse.js";
10
10
  export { renderBlock, renderDocument } from "./render.js";
11
- export { isCanonicalTsLabel, sanitizeName, snakeSlug, splitCamelCase, tfLabelToTsLabel, tsLabelToTfLabel } from "./labels.js";
11
+ export { appResourceLabelPrefix, appScopedResourceLabel, bareChildResourceLabel, childPartFromScopedLabel, elementResourceLabelPrefix, elementScopedResourceLabel, isCanonicalTsLabel, isUuid, ownerChildBareLabel, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, snakeSlug, splitCamelCase, tfLabelToTsLabel, tsLabelToTfLabel, } from "./labels.js";
@@ -29,3 +29,48 @@ export declare function isCanonicalTsLabel(tsLabel: string): boolean;
29
29
  export declare function snakeSlug(s: string): string;
30
30
  /** Faithful port of ei's SanitizeName: platform name → HCL identifier. */
31
31
  export declare function sanitizeName(name: string): string;
32
+ /** True when `value` has the shape of a platform id (not a validity check — just the wire shape). */
33
+ export declare function isUuid(value: string): boolean;
34
+ /** Scope for child resource labels under a stream root. */
35
+ export type ChildResourceScope = "app" | "element";
36
+ /**
37
+ * Prefix for app-owned child resource labels in a shared `.tf/out/` workspace.
38
+ * Uses the platform namespace (`appTfLabel`), matching ei's `AppResourceName`.
39
+ */
40
+ export declare function appResourceLabelPrefix(appTfLabel: string): string;
41
+ /** Prefix for element-owned children in a shared `.tf/out/` workspace. */
42
+ export declare function elementResourceLabelPrefix(elementTfLabel: string): string;
43
+ /**
44
+ * Bare child label before scope prefix: `<ownerNs>_<childPart>` unless already qualified.
45
+ * Used ONLY by the element path, whose childPart already INCLUDES the namespace (element bag
46
+ * keys carry it), so the `startsWith` guard correctly avoids doubling. The app path must NOT
47
+ * use this — an app childPart omits the namespace and may legitimately begin with `<ns>_`
48
+ * (e.g. field `sourcingStatus` → `sourcing_status` under app `sourcing`), which the guard would
49
+ * misread as "already qualified", collapsing it onto the same label as a field named `status`
50
+ * (issue #115). Apps therefore always owner-prefix — see `appScopedResourceLabel`.
51
+ */
52
+ export declare function ownerChildBareLabel(ownerTfLabel: string, childPart: string): string;
53
+ /**
54
+ * App-owned child resource label: `apps_<namespace>_<namespace>_<childPart>`, ALWAYS.
55
+ * An app childPart omits the namespace, so the owner prefix is prepended unconditionally to keep
56
+ * the encoding injective — `childPartFromScopedLabel` is its exact inverse (strips `apps_<ns>_`
57
+ * then one `<ns>_`). Never collapse when the childPart already starts with `<ns>_` (issue #115).
58
+ */
59
+ export declare function appScopedResourceLabel(appTfLabel: string, childPart: string): string;
60
+ /** Element-owned child resource label: `elements_<namespace>_<namespace>_<childPart>`. */
61
+ export declare function elementScopedResourceLabel(elementTfLabel: string, childPart: string): string;
62
+ /** Emit a scoped child label for the owning stream root kind. */
63
+ export declare function scopedResourceLabel(ownerTfLabel: string, childPart: string, scope: ChildResourceScope): string;
64
+ /** Strip a scoped child label back to its bare form (no-op when unprefixed). */
65
+ export declare function bareChildResourceLabel(ownerTfLabel: string, scopedLabel: string, scope?: ChildResourceScope): string;
66
+ /**
67
+ * Child part after the owner namespace — for apps, bag keys omit the namespace
68
+ * prefix; for elements, the bare label (which includes namespace) maps directly.
69
+ *
70
+ * The app branch strips `apps_<ns>_` then exactly one `<ns>_` — the exact inverse of
71
+ * `appScopedResourceLabel`'s always-double encoding (issue #115). The `startsWith` check is
72
+ * therefore always true for a well-formed app label; it is kept only to no-op on unprefixed input.
73
+ */
74
+ export declare function childPartFromScopedLabel(ownerTfLabel: string, scopedLabel: string, scope: ChildResourceScope): string;
75
+ /** Scoped terraform label → authoring bag key / ref key. */
76
+ export declare function scopedLabelToBagKey(ownerTfLabel: string, scopedLabel: string, scope?: ChildResourceScope): string;
@@ -123,3 +123,74 @@ export function sanitizeName(name) {
123
123
  }
124
124
  return s === "" ? "resource" : s;
125
125
  }
126
+ /** Matches a raw platform id (v4-shaped, case-insensitive) — used to recognize an orphaned reference that round-trips as a bare id rather than a resolved name/label. */
127
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
128
+ /** True when `value` has the shape of a platform id (not a validity check — just the wire shape). */
129
+ export function isUuid(value) {
130
+ return UUID_RE.test(value);
131
+ }
132
+ /**
133
+ * Prefix for app-owned child resource labels in a shared `.tf/out/` workspace.
134
+ * Uses the platform namespace (`appTfLabel`), matching ei's `AppResourceName`.
135
+ */
136
+ export function appResourceLabelPrefix(appTfLabel) {
137
+ return `apps_${appTfLabel}_`;
138
+ }
139
+ /** Prefix for element-owned children in a shared `.tf/out/` workspace. */
140
+ export function elementResourceLabelPrefix(elementTfLabel) {
141
+ return `elements_${elementTfLabel}_`;
142
+ }
143
+ /**
144
+ * Bare child label before scope prefix: `<ownerNs>_<childPart>` unless already qualified.
145
+ * Used ONLY by the element path, whose childPart already INCLUDES the namespace (element bag
146
+ * keys carry it), so the `startsWith` guard correctly avoids doubling. The app path must NOT
147
+ * use this — an app childPart omits the namespace and may legitimately begin with `<ns>_`
148
+ * (e.g. field `sourcingStatus` → `sourcing_status` under app `sourcing`), which the guard would
149
+ * misread as "already qualified", collapsing it onto the same label as a field named `status`
150
+ * (issue #115). Apps therefore always owner-prefix — see `appScopedResourceLabel`.
151
+ */
152
+ export function ownerChildBareLabel(ownerTfLabel, childPart) {
153
+ return childPart.startsWith(`${ownerTfLabel}_`) ? childPart : `${ownerTfLabel}_${childPart}`;
154
+ }
155
+ /**
156
+ * App-owned child resource label: `apps_<namespace>_<namespace>_<childPart>`, ALWAYS.
157
+ * An app childPart omits the namespace, so the owner prefix is prepended unconditionally to keep
158
+ * the encoding injective — `childPartFromScopedLabel` is its exact inverse (strips `apps_<ns>_`
159
+ * then one `<ns>_`). Never collapse when the childPart already starts with `<ns>_` (issue #115).
160
+ */
161
+ export function appScopedResourceLabel(appTfLabel, childPart) {
162
+ return `${appResourceLabelPrefix(appTfLabel)}${appTfLabel}_${childPart}`;
163
+ }
164
+ /** Element-owned child resource label: `elements_<namespace>_<namespace>_<childPart>`. */
165
+ export function elementScopedResourceLabel(elementTfLabel, childPart) {
166
+ return `${elementResourceLabelPrefix(elementTfLabel)}${ownerChildBareLabel(elementTfLabel, childPart)}`;
167
+ }
168
+ /** Emit a scoped child label for the owning stream root kind. */
169
+ export function scopedResourceLabel(ownerTfLabel, childPart, scope) {
170
+ return scope === "app" ? appScopedResourceLabel(ownerTfLabel, childPart) : elementScopedResourceLabel(ownerTfLabel, childPart);
171
+ }
172
+ /** Strip a scoped child label back to its bare form (no-op when unprefixed). */
173
+ export function bareChildResourceLabel(ownerTfLabel, scopedLabel, scope = "app") {
174
+ const prefix = scope === "app" ? appResourceLabelPrefix(ownerTfLabel) : elementResourceLabelPrefix(ownerTfLabel);
175
+ return scopedLabel.startsWith(prefix) ? scopedLabel.slice(prefix.length) : scopedLabel;
176
+ }
177
+ /**
178
+ * Child part after the owner namespace — for apps, bag keys omit the namespace
179
+ * prefix; for elements, the bare label (which includes namespace) maps directly.
180
+ *
181
+ * The app branch strips `apps_<ns>_` then exactly one `<ns>_` — the exact inverse of
182
+ * `appScopedResourceLabel`'s always-double encoding (issue #115). The `startsWith` check is
183
+ * therefore always true for a well-formed app label; it is kept only to no-op on unprefixed input.
184
+ */
185
+ export function childPartFromScopedLabel(ownerTfLabel, scopedLabel, scope) {
186
+ const bare = bareChildResourceLabel(ownerTfLabel, scopedLabel, scope);
187
+ if (scope === "app") {
188
+ const nsPrefix = `${ownerTfLabel}_`;
189
+ return bare.startsWith(nsPrefix) ? bare.slice(nsPrefix.length) : bare;
190
+ }
191
+ return bare;
192
+ }
193
+ /** Scoped terraform label → authoring bag key / ref key. */
194
+ export function scopedLabelToBagKey(ownerTfLabel, scopedLabel, scope = "app") {
195
+ return tfLabelToTsLabel(childPartFromScopedLabel(ownerTfLabel, scopedLabel, scope));
196
+ }