@elementumai/edk 0.8.1 → 0.8.2-alpha.5

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 (74) hide show
  1. package/README.md +166 -34
  2. package/dist-sdk/src/catalog/factories.js +18 -2
  3. package/dist-sdk/src/catalog/from-authoring.js +13 -1
  4. package/dist-sdk/src/catalog/org.js +51 -44
  5. package/dist-sdk/src/catalog/token.js +4 -0
  6. package/dist-sdk/src/catalog/types.d.ts +15 -0
  7. package/dist-sdk/src/core/types/app.d.ts +14 -8
  8. package/dist-sdk/src/engine/build/context.d.ts +40 -0
  9. package/dist-sdk/src/engine/build/context.js +11 -1
  10. package/dist-sdk/src/engine/tf/index.d.ts +2 -2
  11. package/dist-sdk/src/engine/tf/index.js +2 -2
  12. package/dist-sdk/src/engine/tf/labels.d.ts +29 -20
  13. package/dist-sdk/src/engine/tf/labels.js +32 -28
  14. package/dist-sdk/src/engine/tf/parse.d.ts +15 -0
  15. package/dist-sdk/src/engine/tf/parse.js +162 -0
  16. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +19 -1
  17. package/dist-sdk/src/entities/access-policy/from-tf.js +4 -6
  18. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +12 -5
  19. package/dist-sdk/src/entities/access-policy/to-tf.js +21 -6
  20. package/dist-sdk/src/entities/agent/build.d.ts +2 -0
  21. package/dist-sdk/src/entities/agent/build.js +1 -0
  22. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +60 -2
  23. package/dist-sdk/src/entities/agent/from-tf.d.ts +12 -7
  24. package/dist-sdk/src/entities/agent/from-tf.js +22 -15
  25. package/dist-sdk/src/entities/agent/module.js +7 -3
  26. package/dist-sdk/src/entities/agent/to-tf.d.ts +46 -1
  27. package/dist-sdk/src/entities/agent/to-tf.js +102 -8
  28. package/dist-sdk/src/entities/agent-a2a-skill/from-tf.d.ts +17 -0
  29. package/dist-sdk/src/entities/agent-a2a-skill/from-tf.js +64 -0
  30. package/dist-sdk/src/entities/agent-a2a-skill/module.d.ts +4 -0
  31. package/dist-sdk/src/entities/agent-a2a-skill/module.js +14 -0
  32. package/dist-sdk/src/entities/agent-a2a-skill/to-tf.d.ts +40 -0
  33. package/dist-sdk/src/entities/agent-a2a-skill/to-tf.js +47 -0
  34. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +7 -2
  35. package/dist-sdk/src/entities/agent-tool/to-tf.js +86 -26
  36. package/dist-sdk/src/entities/app/build.d.ts +35 -7
  37. package/dist-sdk/src/entities/app/build.js +19 -8
  38. package/dist-sdk/src/entities/app/from-tf.js +0 -7
  39. package/dist-sdk/src/entities/app/module.js +1 -0
  40. package/dist-sdk/src/entities/app/to-tf.js +13 -1
  41. package/dist-sdk/src/entities/automation/build.js +14 -6
  42. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +27 -4
  43. package/dist-sdk/src/entities/automation/filter.d.ts +22 -0
  44. package/dist-sdk/src/entities/automation/filter.js +42 -1
  45. package/dist-sdk/src/entities/automation/from-tf.js +127 -11
  46. package/dist-sdk/src/entities/automation/to-tf.js +176 -18
  47. package/dist-sdk/src/entities/element/build.d.ts +26 -8
  48. package/dist-sdk/src/entities/element/build.js +44 -3
  49. package/dist-sdk/src/entities/element/from-tf.js +10 -11
  50. package/dist-sdk/src/entities/element/module.js +1 -0
  51. package/dist-sdk/src/entities/element/to-tf.js +5 -0
  52. package/dist-sdk/src/entities/field/build.d.ts +9 -5
  53. package/dist-sdk/src/entities/field/calc/runtime.js +2 -2
  54. package/dist-sdk/src/entities/field/from-tf.js +10 -10
  55. package/dist-sdk/src/entities/field/to-tf.d.ts +35 -18
  56. package/dist-sdk/src/entities/field/to-tf.js +110 -6
  57. package/dist-sdk/src/entities/shared/filters/ast.d.ts +15 -0
  58. package/dist-sdk/src/entities/shared/tool-field-ref.js +15 -0
  59. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +97 -8
  60. package/dist-sdk/src/entities/skill/module.js +1 -0
  61. package/dist-sdk/src/entities/skill/to-tf.d.ts +26 -0
  62. package/dist-sdk/src/entities/skill/to-tf.js +63 -3
  63. package/dist-sdk/src/entities/skill/tools.d.ts +12 -5
  64. package/dist-sdk/src/entities/skill/tools.js +26 -1
  65. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +19 -2
  66. package/dist-sdk/src/entities/skill-tool/from-tf.js +97 -8
  67. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +11 -1
  68. package/dist-sdk/src/entities/skill-tool/to-tf.js +143 -27
  69. package/dist-sdk/src/entities/skill-tool/types.d.ts +5 -7
  70. package/dist-sdk/src/entities/skill-tool/types.js +47 -11
  71. package/dist-sdk/src/entities/view/to-tf.js +6 -0
  72. package/dist-sdk/src/graph/modules.js +2 -0
  73. package/dist-sdk/src/graph/types.d.ts +22 -2
  74. package/package.json +12 -7
@@ -57,11 +57,8 @@ export function elementFromTf(elementBlock, fieldBlocks, ctx, viewBlocks = {
57
57
  if (handle === undefined) {
58
58
  ctx.diagnostics.push(`element "${label}": export stream carries no handle; derived "${label.toUpperCase()}"`);
59
59
  }
60
- for (const key of ["title_field_description", "id_field_description"]) {
61
- if (attrs[key] !== undefined) {
62
- ctx.diagnostics.push(`element "${label}": ${key} has no authoring slot yet (systemFields overrides are name only); dropped`);
63
- }
64
- }
60
+ const titleFieldDescription = optionalString(attrs, "title_field_description", `element "${label}"`, ctx);
61
+ const idFieldDescription = optionalString(attrs, "id_field_description", `element "${label}"`, ctx);
65
62
  const commentsEnabled = optionalBoolean(attrs, "comments_enabled", `element "${label}"`, ctx);
66
63
  // Snowflake cloud mapping — a LINKED element's Cloud Link + Database/Schema/
67
64
  // Table + column-name wiring. Real and round-tripped: elementToTf re-sends
@@ -113,11 +110,13 @@ export function elementFromTf(elementBlock, fieldBlocks, ctx, viewBlocks = {
113
110
  }
114
111
  const fields = [];
115
112
  const titleName = optionalString(attrs, "title_field_name", `element "${label}"`, ctx);
116
- if (titleName !== undefined)
117
- fields.push(systemEntry("title", titleName, "TEXT", "TITLE"));
113
+ if (titleName !== undefined || titleFieldDescription !== undefined) {
114
+ fields.push(systemEntry("title", titleName ?? "Title", "TEXT", "TITLE", titleFieldDescription));
115
+ }
118
116
  const idName = optionalString(attrs, "id_field_name", `element "${label}"`, ctx);
119
- if (idName !== undefined)
120
- fields.push(systemEntry("id", idName, "TEXT", "HANDLE"));
117
+ if (idName !== undefined || idFieldDescription !== undefined) {
118
+ fields.push(systemEntry("id", idName ?? "ID", "TEXT", "HANDLE", idFieldDescription));
119
+ }
121
120
  const owner = { type: ELEMENT_RESOURCE_TYPE, label, scope: "element" };
122
121
  for (const block of fieldBlocks) {
123
122
  const entry = fieldFromTf(block, owner, ctx);
@@ -165,6 +164,6 @@ export function elementFromTf(elementBlock, fieldBlocks, ctx, viewBlocks = {
165
164
  };
166
165
  return { element, ...(cloudLinkHandle !== undefined && { cloudLinkHandle }) };
167
166
  }
168
- function systemEntry(key, name, type, tag) {
169
- return { key, field: { id: "", name, type, tags: [tag] } };
167
+ function systemEntry(key, name, type, tag, description) {
168
+ return { key, field: { id: "", name, type, tags: [tag], ...(description !== undefined && { description }) } };
170
169
  }
@@ -51,6 +51,7 @@ export const elementModule = {
51
51
  appTfLabel: ctx.appTfLabel,
52
52
  orgRefs: ctx.orgRefs,
53
53
  diagnostics: ctx.diagnostics,
54
+ workspaceAspects: ctx.workspaceAspects,
54
55
  });
55
56
  return { blocks: result.blocks, fieldAddresses: result.fieldAddresses };
56
57
  },
@@ -131,10 +131,12 @@ export function elementToTf(entity, ctx) {
131
131
  }
132
132
  const field = fieldToTf(typeKey, inner, {
133
133
  ownerTfLabel: ctx.appTfLabel,
134
+ appRefName: ctx.appRefName,
134
135
  scope: "element",
135
136
  objectId,
136
137
  diagnostics: ctx.diagnostics,
137
138
  orgRefs: ctx.orgRefs,
139
+ workspaceAspects: ctx.workspaceAspects,
138
140
  });
139
141
  if (field === undefined)
140
142
  continue;
@@ -149,6 +151,9 @@ export function elementToTf(entity, ctx) {
149
151
  diagnostics: ctx.diagnostics,
150
152
  });
151
153
  blocks.push(...viewBlocks);
154
+ // Authored entries only. Creating an element also has the platform mint a
155
+ // creator policy (userIds = [you]) that is NOT in this payload — pull
156
+ // will see it; we never emit it here.
152
157
  for (const [index, entry] of (payload.accessPolicies ?? []).entries()) {
153
158
  const { block } = accessPolicyToTf(entry, index, {
154
159
  ownerTfLabel: ctx.appTfLabel,
@@ -15,7 +15,7 @@
15
15
  * AppField is accepted.
16
16
  */
17
17
  import type { AppField, AppPicklistConfig, PicklistOption } from "../app/build.js";
18
- import type { FieldRef } from "../../catalog/index.js";
18
+ import type { AspectRef, FieldRef } from "../../catalog/index.js";
19
19
  import type { Expr, ExprType } from "./calc/types.js";
20
20
  /** Options every field kind accepts (everything on {@link AppField} that isn't kind-specific). */
21
21
  export interface BaseFieldOptions {
@@ -57,12 +57,16 @@ export interface TextFieldOptions extends BaseFieldOptions {
57
57
  /**
58
58
  * Options for `relationField` — a dynamic dropdown sourced from another
59
59
  * App/Element/Task's records (`elementum_relation_field`), distinct from a
60
- * static `picklistField`. `relatedAspectId`/`relatedLabelFieldId` are raw
61
- * platform ids (see {@link RelationAppField}), not catalog tokens.
60
+ * static `picklistField`. `relatedObject`/`relatedLabelField` (see
61
+ * {@link RelationAppField}) accept a catalog token or a raw platform id. A
62
+ * token naming a SIBLING app/element authored in the same build resolves
63
+ * to a direct resource reference and does not need to already exist on the
64
+ * platform; only a token naming something genuinely outside this
65
+ * workspace needs that.
62
66
  */
63
67
  export interface RelationFieldOptions extends BaseFieldOptions {
64
- readonly relatedAspectId: string;
65
- readonly relatedLabelFieldId: string;
68
+ readonly relatedObject: AspectRef | string;
69
+ readonly relatedLabelField: FieldRef | string;
66
70
  /** Defaults to `true` on the platform. */
67
71
  readonly autoRelate?: boolean;
68
72
  }
@@ -109,8 +109,8 @@ function appFieldExprType(field) {
109
109
  `Inline the upstream expression or split the work across automation tasks.`);
110
110
  case "RELATION":
111
111
  throw new Error(`calc: cannot reference relation field "${field.name}" in a calculation — ` +
112
- `it has no scalar/comparable value of its own (relatedAspectId/relatedLabelFieldId ` +
113
- `are raw platform ids, not an expression-typed value).`);
112
+ `it has no scalar/comparable value of its own (relatedObject/relatedLabelField ` +
113
+ `are a catalog token or raw platform id, not an expression-typed value).`);
114
114
  default: {
115
115
  const _exhaustive = field;
116
116
  void _exhaustive;
@@ -96,20 +96,20 @@ export function fieldFromTf(block, owner, ctx) {
96
96
  // either missing would be invalid TypeScript (item 117) - skip the whole
97
97
  // field when either side can't be resolved, same convention as an
98
98
  // unimplemented sub-type.
99
- let relatedAspectId;
100
- let relatedLabelFieldId;
99
+ let relatedObject;
100
+ let relatedLabelField;
101
101
  let autoRelate;
102
102
  if (subType.hasRelation === true) {
103
- relatedAspectId = resolveRelatedId(attrs["related_object_id"], ctx);
104
- relatedLabelFieldId = resolveRelatedId(attrs["related_label_field_id"], ctx);
103
+ relatedObject = resolveRelatedId(attrs["related_object_id"], ctx);
104
+ relatedLabelField = resolveRelatedId(attrs["related_label_field_id"], ctx);
105
105
  if (typeof attrs["auto_relate"] === "boolean")
106
106
  autoRelate = attrs["auto_relate"];
107
- if (relatedAspectId === undefined || relatedLabelFieldId === undefined) {
107
+ if (relatedObject === undefined || relatedLabelField === undefined) {
108
108
  const missing = [
109
- relatedAspectId === undefined && "related_object_id",
110
- relatedLabelFieldId === undefined && "related_label_field_id",
109
+ relatedObject === undefined && "related_object_id",
110
+ relatedLabelField === undefined && "related_label_field_id",
111
111
  ].filter((v) => v !== false);
112
- ctx.diagnostics.push(`${where}: ${missing.join(" and ")} does not resolve to a raw platform id - a RELATION field needs both to reconstruct relatedAspectId/relatedLabelFieldId; field skipped`);
112
+ ctx.diagnostics.push(`${where}: ${missing.join(" and ")} does not resolve to a raw platform id - a RELATION field needs both to reconstruct relatedObject/relatedLabelField; field skipped`);
113
113
  ctx.skipped.push(`${block.type}.${fieldLabel}`);
114
114
  return undefined;
115
115
  }
@@ -161,8 +161,8 @@ export function fieldFromTf(block, owner, ctx) {
161
161
  !isTfExpr(attrs["default_value"]) && { defaultValue: attrs["default_value"] }),
162
162
  ...(options !== undefined && { options }),
163
163
  ...(tags !== undefined && tags.length > 0 && { tags }),
164
- ...(relatedAspectId !== undefined && { relatedAspectId }),
165
- ...(relatedLabelFieldId !== undefined && { relatedLabelFieldId }),
164
+ ...(relatedObject !== undefined && { relatedObject }),
165
+ ...(relatedLabelField !== undefined && { relatedLabelField }),
166
166
  ...(autoRelate !== undefined && { autoRelate }),
167
167
  ...(decimalPlaces !== undefined && { decimalPlaces }),
168
168
  },
@@ -9,9 +9,23 @@
9
9
  * never silent, never thrown (plan §4.3). The one hard error is a
10
10
  * non-canonical bag key: it has no well-defined terraform address.
11
11
  */
12
- import type { OrgRefLookup } from "../../engine/build/context.js";
12
+ import { type OrgRefLookup, type WorkspaceAspect } from "../../engine/build/context.js";
13
13
  import { type ChildResourceScope, type TfBlock, type TfExpr, type TfValue } from "../../engine/tf/index.js";
14
14
  import { type PicklistValueWire } from "./options.js";
15
+ /** Slim `AspectRef` token shape as it appears in a def() payload (post-`slimTokens`). */
16
+ interface AspectTokenWire {
17
+ readonly __kind?: string;
18
+ readonly refName?: string;
19
+ readonly name?: string;
20
+ }
21
+ /** Slim `FieldRef` token shape as it appears in a def() payload. */
22
+ interface FieldTokenWire {
23
+ readonly __kind?: string;
24
+ readonly refName?: string;
25
+ readonly name?: string;
26
+ readonly parent?: string;
27
+ readonly fieldType?: string;
28
+ }
15
29
  /** The authored field shape (post-`slimTokens` compose body). Deliberately loose — degrade, don't assert. */
16
30
  export interface FieldInnerWire {
17
31
  readonly name?: string;
@@ -28,9 +42,14 @@ export interface FieldInnerWire {
28
42
  readonly config?: unknown;
29
43
  readonly format?: unknown;
30
44
  readonly calculation?: unknown;
31
- /** "relation" fields only — raw platform ids, not catalog tokens (see RelationAppField). */
32
- readonly relatedAspectId?: string;
33
- readonly relatedLabelFieldId?: string;
45
+ /**
46
+ * "relation" fields only (see RelationAppField) — a catalog token when the
47
+ * target object/field has already been pulled into this workspace, or a
48
+ * raw platform id otherwise. A pulled RELATION field always has raw
49
+ * strings here; tokens only ever come from freshly authored source.
50
+ */
51
+ readonly relatedObject?: AspectTokenWire | string;
52
+ readonly relatedLabelField?: FieldTokenWire | string;
34
53
  readonly autoRelate?: boolean;
35
54
  /** "decimal" fields only. */
36
55
  readonly decimalPlaces?: number;
@@ -38,6 +57,8 @@ export interface FieldInnerWire {
38
57
  export interface FieldToTfOptions {
39
58
  /** The owning stream root's terraform label (namespace). */
40
59
  readonly ownerTfLabel: string;
60
+ /** The owning stream root's refName — needed to detect a self-targeting RELATION field. */
61
+ readonly appRefName: string;
41
62
  /** App children use `apps_<ns>_`; element children use `<ns>_`. */
42
63
  readonly scope?: ChildResourceScope;
43
64
  /** The owner's id reference, e.g. `elementum_app.<ns>.id` — computed by the owner's to-tf. */
@@ -46,6 +67,15 @@ export interface FieldToTfOptions {
46
67
  readonly diagnostics: string[];
47
68
  /** Needed to re-emit a group/user field's `default_value` as a `data.elementum_group|user` lookup (see `OrgFieldRefValue`). */
48
69
  readonly orgRefs?: OrgRefLookup;
70
+ /**
71
+ * Every app/element stream root in THIS build, keyed by
72
+ * `workspaceAspectKey` (kind+refName — an app and an element MAY share a
73
+ * refName) — lets a RELATION field's `relatedObject` tell a SIBLING being
74
+ * authored/created in this same build (a direct resource reference,
75
+ * sequenced automatically) apart from a genuinely foreign object (a
76
+ * `data` lookup, which can only ever find something already live).
77
+ */
78
+ readonly workspaceAspects?: ReadonlyMap<string, WorkspaceAspect>;
49
79
  }
50
80
  export interface FieldToTfResult {
51
81
  readonly block: TfBlock;
@@ -56,18 +86,5 @@ export interface FieldToTfResult {
56
86
  }
57
87
  /** One custom field → its resource block; undefined = degraded (diagnostic already pushed). */
58
88
  export declare function fieldToTf(typeKey: string, inner: FieldInnerWire, opts: FieldToTfOptions): FieldToTfResult | undefined;
59
- /**
60
- * A field reference `{fieldType, refName}` (the shape a `FieldRef` token
61
- * slims to) → its terraform expression — shared by anything that NAMES a
62
- * field by typed ref rather than owning it directly (skill-tool fields,
63
- * view layout/list-view field refs). A CUSTOM field resolves to
64
- * `<resourceType>.<tfLabel>.id`; a SYSTEM field (title/status/closedBy/…)
65
- * has no `elementum_<type>_field` resource of its own, only a computed
66
- * `local.<app>_<key>_field_id` alias — checked first, since a system
67
- * field's fieldType (e.g. "USER" for closedBy) can coincidentally match a
68
- * real custom-field resource type. Undefined when the authoring type has no
69
- * terraform mapping or the bag key isn't canonical; callers own the
70
- * diagnostic wording since the two failure cases usually read differently
71
- * at each call site.
72
- */
73
89
  export declare function fieldRefToTfValue(fieldType: string, refName: string, ownerTfLabel: string, scope?: ChildResourceScope): TfExpr | undefined;
90
+ export {};
@@ -10,7 +10,8 @@
10
10
  * non-canonical bag key: it has no well-defined terraform address.
11
11
  */
12
12
  import { EntityTfError } from "../../engine/entity.js";
13
- import { expr, isCanonicalTsLabel, scopedResourceLabel, snakeSlug, tsLabelToTfLabel } from "../../engine/tf/index.js";
13
+ import { workspaceAspectKey } from "../../engine/build/context.js";
14
+ import { expr, isCanonicalTsLabel, sanitizeName, scopedResourceLabel, snakeSlug, tsLabelToTfLabel } from "../../engine/tf/index.js";
14
15
  import { SYSTEM_FIELD_KEY_SET } from "../../core/system-fields.js";
15
16
  import { picklistLabel } from "./options.js";
16
17
  import { SUB_TYPE_BY_AUTHORING_TYPE, SUB_TYPE_BY_TYPE_KEY } from "./types.js";
@@ -20,6 +21,98 @@ function asOrgFieldRef(v) {
20
21
  return undefined;
21
22
  return v;
22
23
  }
24
+ /**
25
+ * `relatedObject` (RELATION fields only) → its `related_object_id` value. A
26
+ * raw string passes through literally (unchanged, backward-compatible
27
+ * behavior). An `AspectRef` token resolves, in order:
28
+ * 1. self (names the owner itself) — reuses the already-resolved `objectId`;
29
+ * 2. a SIBLING stream root in this same build (`opts.workspaceAspects`,
30
+ * keyed by kind+refName since an app and an element MAY share a
31
+ * refName — see `workspaceAspectKey`) — a direct resource reference,
32
+ * so Terraform sequences its creation automatically even if it
33
+ * doesn't exist on the platform yet;
34
+ * 3. otherwise genuinely foreign — a `data.elementum_app`/
35
+ * `data.elementum_element` lookup, registered via `opts.orgRefs`
36
+ * (mirrors agent-tool/to-tf.ts's `targetIdValue`, board #42); this is
37
+ * the ONE case that requires the target to already exist live.
38
+ */
39
+ function resolveRelatedObject(token, opts, where) {
40
+ if (typeof token === "string")
41
+ return { value: token };
42
+ const refName = token.refName ?? "";
43
+ const kind = token.__kind === "element" ? "element" : "app";
44
+ if (kind === (opts.scope ?? "app") && refName === opts.appRefName) {
45
+ return { value: opts.objectId, refName, kind, target: { kind: opts.scope ?? "app", tfLabel: opts.ownerTfLabel } };
46
+ }
47
+ const sibling = opts.workspaceAspects?.get(workspaceAspectKey(kind, refName));
48
+ if (sibling !== undefined) {
49
+ const resourceType = kind === "element" ? "elementum_element" : "elementum_app";
50
+ return { value: expr.resourceAttr(resourceType, sibling.tfLabel, ["id"]), refName, kind, target: sibling };
51
+ }
52
+ const name = token.name ?? refName;
53
+ if (name === "") {
54
+ opts.diagnostics.push(`${where}: relatedObject token has no name/refName; dropped`);
55
+ return undefined;
56
+ }
57
+ if (opts.orgRefs === undefined) {
58
+ opts.diagnostics.push(`${where}: relatedObject references a foreign object but no org context is available; dropped`);
59
+ return undefined;
60
+ }
61
+ const tfLabel = sanitizeName(name);
62
+ if (kind === "element") {
63
+ opts.orgRefs.foreignElement(tfLabel, name);
64
+ return { value: expr.dataAttr("elementum_element", tfLabel, ["id"]), refName, kind };
65
+ }
66
+ opts.orgRefs.foreignApp(tfLabel, name);
67
+ return { value: expr.dataAttr("elementum_app", tfLabel, ["id"]), refName, kind };
68
+ }
69
+ /**
70
+ * `relatedLabelField` (RELATION fields only) → its `related_label_field_id`
71
+ * value. A raw string passes through literally. A `FieldRef` token resolves
72
+ * via the shared field resolver (`fieldRefToTfValue`) when the (already-
73
+ * resolved) `relatedObject` target is known — the owner itself or a
74
+ * SIBLING stream root in this build, both real resources — a direct
75
+ * resource reference either way; otherwise it's a genuinely foreign field,
76
+ * resolved via a `data.elementum_field` lookup keyed by `object_id` (the
77
+ * already-resolved `related_object_id` value, reused verbatim) + `name` —
78
+ * the one case agent-tool/to-tf.ts's `fieldRefValue` explicitly declines
79
+ * ("cross-app field refs are not supported... yet"). The lookup LABEL
80
+ * includes the resolved object's kind (when known) — `elementum_field` is
81
+ * one shared data-source type for app- and element-owned fields alike (see
82
+ * the provider's `field_data_source.go`), so an app and an element sharing
83
+ * a refName would otherwise both register the same label and silently
84
+ * overwrite each other's `object_id` (`loadOrgRefs.record` dedupes by
85
+ * `type.tfLabel`).
86
+ */
87
+ function resolveRelatedLabelField(token, object, opts, where) {
88
+ if (typeof token === "string")
89
+ return token;
90
+ const refName = token.refName ?? "";
91
+ if (refName === "") {
92
+ opts.diagnostics.push(`${where}: relatedLabelField token has no refName; dropped`);
93
+ return undefined;
94
+ }
95
+ if (object.refName !== undefined && token.parent !== undefined && token.parent !== object.refName) {
96
+ opts.diagnostics.push(`${where}: relatedLabelField token "${refName}" belongs to "${token.parent}", not relatedObject's target "${object.refName}"; dropped`);
97
+ return undefined;
98
+ }
99
+ if (object.target !== undefined) {
100
+ const value = fieldRefToTfValue(token.fieldType ?? "", refName, object.target.tfLabel, object.target.kind);
101
+ if (value === undefined) {
102
+ opts.diagnostics.push(`${where}: relatedLabelField token "${refName}" has no terraform field resource mapping (fieldType ${JSON.stringify(token.fieldType ?? "")}); dropped`);
103
+ }
104
+ return value;
105
+ }
106
+ if (opts.orgRefs === undefined) {
107
+ opts.diagnostics.push(`${where}: relatedLabelField references a foreign field but no org context is available; dropped`);
108
+ return undefined;
109
+ }
110
+ const name = token.name ?? refName;
111
+ const parentLabel = token.parent !== undefined ? tsLabelToTfLabel(token.parent) : "related";
112
+ const tfLabel = object.kind !== undefined ? `${object.kind}_${parentLabel}_${tsLabelToTfLabel(refName)}` : `${parentLabel}_${tsLabelToTfLabel(refName)}`;
113
+ opts.orgRefs.foreignField("elementum_field", tfLabel, object.value, name);
114
+ return expr.dataAttr("elementum_field", tfLabel, ["id"]);
115
+ }
23
116
  /** One custom field → its resource block; undefined = degraded (diagnostic already pushed). */
24
117
  export function fieldToTf(typeKey, inner, opts) {
25
118
  const { ownerTfLabel, scope = "app", objectId, diagnostics } = opts;
@@ -92,12 +185,20 @@ export function fieldToTf(typeKey, inner, opts) {
92
185
  attrs["decimal_places"] = inner.decimalPlaces;
93
186
  }
94
187
  if (subType.hasRelation === true) {
95
- if (inner.relatedAspectId === undefined || inner.relatedLabelFieldId === undefined) {
96
- diagnostics.push(`field "${name}": relation fields require relatedAspectId and relatedLabelFieldId; dropped`);
188
+ if (inner.relatedObject === undefined || inner.relatedLabelField === undefined) {
189
+ diagnostics.push(`field "${name}": relation fields require relatedObject and relatedLabelField; dropped`);
97
190
  return undefined;
98
191
  }
99
- attrs["related_object_id"] = inner.relatedAspectId;
100
- attrs["related_label_field_id"] = inner.relatedLabelFieldId;
192
+ const where = `field "${name}"`;
193
+ const resolvedObject = resolveRelatedObject(inner.relatedObject, opts, where);
194
+ if (resolvedObject === undefined)
195
+ return undefined;
196
+ const relatedLabelFieldId = resolveRelatedLabelField(inner.relatedLabelField, resolvedObject, opts, where);
197
+ if (relatedLabelFieldId === undefined)
198
+ return undefined;
199
+ const relatedObjectId = resolvedObject.value;
200
+ attrs["related_object_id"] = relatedObjectId;
201
+ attrs["related_label_field_id"] = relatedLabelFieldId;
101
202
  if (inner.autoRelate !== undefined)
102
203
  attrs["auto_relate"] = inner.autoRelate;
103
204
  }
@@ -129,10 +230,13 @@ function scalarOrUndefined(v) {
129
230
  * diagnostic wording since the two failure cases usually read differently
130
231
  * at each call site.
131
232
  */
233
+ /** Elements only have `id`/`title` as real system fields (no status/stage/audit fields) — see `element/locals.ts`. */
234
+ const ELEMENT_SYSTEM_FIELD_KEYS = new Set(["id", "title"]);
132
235
  export function fieldRefToTfValue(fieldType, refName, ownerTfLabel, scope = "app") {
133
236
  if (!isCanonicalTsLabel(refName))
134
237
  return undefined;
135
- if (SYSTEM_FIELD_KEY_SET.has(refName)) {
238
+ const isSystemField = scope === "element" ? ELEMENT_SYSTEM_FIELD_KEYS.has(refName) : SYSTEM_FIELD_KEY_SET.has(refName);
239
+ if (isSystemField) {
136
240
  return expr.local(`${ownerTfLabel}_${tsLabelToTfLabel(refName)}_field_id`);
137
241
  }
138
242
  const subType = SUB_TYPE_BY_AUTHORING_TYPE.get(fieldType);
@@ -49,6 +49,21 @@ export interface FieldRefAst {
49
49
  readonly kind: "field";
50
50
  readonly appHandle: string;
51
51
  readonly fieldKey: string;
52
+ /**
53
+ * Present when the field belongs to a DIFFERENT app/element than
54
+ * `appHandle` resolves locally — a foreign `data.elementum_field` lookup,
55
+ * not a same-workspace catalog access. `appHandle` in this case is a
56
+ * best-effort refName recovered from the owner's own data-block label
57
+ * (not guaranteed to match a real local ref — same caveat as
58
+ * `AppRefAst.name`, which this mirrors).
59
+ */
60
+ readonly foreign?: {
61
+ readonly entityType: "app" | "element";
62
+ /** The owner's display name — resolves a same-name local catalog entry, same convention as `AppRefAst.name`. */
63
+ readonly name: string;
64
+ /** The field's OWN display name (the `data.elementum_field` block's `name` attr), when the stream carried it — used for the raw stub's `name:` when the owner isn't locally resolvable. */
65
+ readonly fieldName?: string;
66
+ };
52
67
  }
53
68
  /** Reference to a fixed platform user-directory attribute. */
54
69
  export interface UserFieldRefAst {
@@ -21,6 +21,21 @@ export function resolveToolFieldKey(fieldRef, scopeTfLabel, scope = "app") {
21
21
  if (isTfExpr(fieldRef) && fieldRef.$expr === "resource-attr" && FIELD_SUB_TYPE_BY_RESOURCE.has(fieldRef.type)) {
22
22
  return scopedLabelToBagKey(scopeTfLabel, fieldRef.label, scope);
23
23
  }
24
+ if (isTfExpr(fieldRef) && fieldRef.$expr === "data-attr" && fieldRef.type === "elementum_field") {
25
+ // The reverse of `agent-tool`/`skill-tool` to-tf's
26
+ // `foreignTargetFieldRefValue`: a CUSTOM field on the tool's target
27
+ // aspect, resolved via a `data.elementum_field` lookup rather than a
28
+ // resource block (the target isn't recursively exported, so it has no
29
+ // field resource of its own in this stream). `scopeTfLabel`/`scope`
30
+ // already identify the RESOLVED target (see this module's header
31
+ // comment), so the label prefix to strip is known without any extra
32
+ // lookup — mirrors `crossAppFieldToTf`'s label construction in
33
+ // `automation/to-tf.ts`.
34
+ const prefix = `${scope}_${scopeTfLabel}_`;
35
+ if (fieldRef.label.startsWith(prefix)) {
36
+ return tfLabelToTsLabel(fieldRef.label.slice(prefix.length));
37
+ }
38
+ }
24
39
  if (isTfExpr(fieldRef) && fieldRef.$expr === "local") {
25
40
  const prefix = `${scopeTfLabel}_`;
26
41
  if (fieldRef.name.startsWith(prefix) && fieldRef.name.endsWith("_field_id")) {
@@ -17,15 +17,34 @@ import { sdkPackageSpecifier } from "../../../internal/sdk-package.js";
17
17
  const TOOL_FACTORY_BY_TYPE_KEY = {
18
18
  createRecord: "skillCreateRecord",
19
19
  searchAspect: "skillSearchAspect",
20
+ updateRecord: "skillUpdateRecord",
21
+ runAgent: "skillRunAgent",
22
+ automation: "skillAutomation",
20
23
  };
24
+ function safeMember(name) {
25
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? `.${name}` : `[${quote(name)}]`;
26
+ }
27
+ function safeKey(name) {
28
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : quote(name);
29
+ }
30
+ function printRunAs(runAs) {
31
+ if (runAs["currentUser"] === true)
32
+ return "{ currentUser: true }";
33
+ if (runAs["publisher"] === true)
34
+ return "{ publisher: true }";
35
+ const serviceAccount = runAs["serviceAccount"];
36
+ return `{ serviceAccount: { serviceAccount: ${quote(String(serviceAccount?.serviceAccount ?? ""))} } }`;
37
+ }
21
38
  export function printSkillV2(skill, opts) {
22
39
  const { appRefName } = opts;
23
40
  const crossOrg = opts.crossOrg === true;
24
41
  const factories = [...new Set(skill.tools.map((t) => TOOL_FACTORY_BY_TYPE_KEY[t.typeKey]).filter(Boolean))].sort();
25
- const usesCatalog = skill.tools.some((t) => t.target.kind === "self" ||
42
+ const usesCatalog = skill.tools.some((t) => t.typeKey === "automation" ||
43
+ t.typeKey === "runAgent" ||
44
+ t.target?.kind === "self" ||
26
45
  (t.fields !== undefined && t.fields.length > 0) ||
27
- (t.target.kind === "foreignApp" && opts.foreignAppRefNames?.has(t.target.name)) ||
28
- (t.target.kind === "foreignElement" && opts.foreignElementRefNames?.has(t.target.name)));
46
+ (t.target?.kind === "foreignApp" && opts.foreignAppRefNames?.has(t.target.name)) ||
47
+ (t.target?.kind === "foreignElement" && opts.foreignElementRefNames?.has(t.target.name)));
29
48
  const lines = [];
30
49
  lines.push("/**");
31
50
  lines.push(` * ${skill.name}`);
@@ -61,6 +80,20 @@ export function printSkillV2(skill, opts) {
61
80
  lines.push("");
62
81
  return lines.join("\n");
63
82
  }
83
+ function fieldOwnerRef(tool, appRefName, foreignAppRefNames, foreignElementRefNames) {
84
+ // `fields` (and therefore this) is only ever reached for createRecord/
85
+ // searchAspect/updateRecord, which always carry a target — automation/
86
+ // runAgent tools return before this point. The undefined branch only
87
+ // exists to satisfy NormalizedSkillTool.target's now-optional type.
88
+ if (tool.target === undefined || tool.target.kind === "self")
89
+ return { kind: "catalog", expr: `catalog.${appRefName}` };
90
+ const entityKind = tool.target.kind === "foreignElement" ? "element" : "app";
91
+ const refNames = tool.target.kind === "foreignElement" ? foreignElementRefNames : foreignAppRefNames;
92
+ const foreignRefName = refNames?.get(tool.target.name);
93
+ return foreignRefName !== undefined
94
+ ? { kind: "catalog", expr: `catalog.${foreignRefName}` }
95
+ : { kind: "raw", entityType: entityKind, name: tool.target.name };
96
+ }
64
97
  function printTool(tool, appRefName, crossOrg, foreignAppRefNames, foreignElementRefNames) {
65
98
  const factory = TOOL_FACTORY_BY_TYPE_KEY[tool.typeKey] ?? "skillSearchAspect";
66
99
  const lines = [`${factory}({`];
@@ -70,10 +103,47 @@ function printTool(tool, appRefName, crossOrg, foreignAppRefNames, foreignElemen
70
103
  lines.push(` status: ${quote(tool.status)},`);
71
104
  if (tool.startMessage !== undefined)
72
105
  lines.push(` startMessage: ${quote(tool.startMessage)},`);
73
- if (tool.target.kind === "self") {
106
+ if (tool.runAs !== undefined)
107
+ lines.push(` runAs: ${printRunAs(tool.runAs)},`);
108
+ if (tool.typeKey === "runAgent") {
109
+ lines.push(` agent: catalog.${appRefName}.agents${safeMember(tool.targetAgentKey ?? "")},`);
110
+ lines.push(` workerTaskPrompt: ${quote(tool.workerTaskPrompt ?? "")},`);
111
+ lines.push("}),");
112
+ return lines;
113
+ }
114
+ if (tool.typeKey === "automation") {
115
+ lines.push(` automation: catalog.${appRefName}.automations${safeMember(tool.automationKey ?? "")},`);
116
+ if (tool.inputs !== undefined && tool.inputs.length > 0) {
117
+ lines.push(" inputs: {");
118
+ for (const input of tool.inputs) {
119
+ const parts = [];
120
+ if (input.displayName !== undefined && input.displayName !== input.parameterName) {
121
+ parts.push(`name: ${quote(input.displayName)}`);
122
+ }
123
+ parts.push(`description: ${quote(input.description ?? "")}`);
124
+ if (input.required !== undefined)
125
+ parts.push(`required: ${input.required}`);
126
+ lines.push(` ${safeKey(input.parameterName)}: { ${parts.join(", ")} },`);
127
+ }
128
+ lines.push(" },");
129
+ }
130
+ if (tool.outputs !== undefined && tool.outputs.length > 0) {
131
+ lines.push(" outputs: {");
132
+ for (const output of tool.outputs) {
133
+ const spec = output.displayName !== undefined && output.displayName !== output.workflowPropertyName
134
+ ? `{ name: ${quote(output.displayName)} }`
135
+ : "{}";
136
+ lines.push(` ${safeKey(output.workflowPropertyName)}: ${spec},`);
137
+ }
138
+ lines.push(" },");
139
+ }
140
+ lines.push("}),");
141
+ return lines;
142
+ }
143
+ if (tool.target?.kind === "self") {
74
144
  lines.push(` aspect: catalog.${appRefName},`);
75
145
  }
76
- else {
146
+ else if (tool.target !== undefined) {
77
147
  // Board issue #42: the target can be a foreign APP or a foreign
78
148
  // ELEMENT — each stub carries the right `__kind` and is looked up
79
149
  // against its own map, never conflated.
@@ -101,7 +171,11 @@ function printTool(tool, appRefName, crossOrg, foreignAppRefNames, foreignElemen
101
171
  if (tool.limit !== undefined)
102
172
  lines.push(` limit: ${tool.limit},`);
103
173
  }
174
+ if (tool.typeKey === "updateRecord") {
175
+ lines.push(` handleDescription: ${quote(tool.handleDescription ?? "")},`);
176
+ }
104
177
  if (tool.fields !== undefined && tool.fields.length > 0) {
178
+ const owner = fieldOwnerRef(tool, appRefName, foreignAppRefNames, foreignElementRefNames);
105
179
  lines.push(" fields: [");
106
180
  for (const f of tool.fields) {
107
181
  // A foreign/out-of-scope aspect's field has no field resource ei can
@@ -109,12 +183,27 @@ function printTool(tool, appRefName, crossOrg, foreignAppRefNames, foreignElemen
109
183
  // print the raw-id shape (SkillSearchRawIdField/SkillRecordRawIdField)
110
184
  // instead of a catalog token.
111
185
  const isRaw = f.key === undefined;
112
- const parts = isRaw ? [`fieldId: ${quote(f.rawFieldId ?? "")}`] : [`field: catalog.${appRefName}.fields.${f.key}`];
186
+ // A field always belongs to the tool's TARGET, not necessarily the
187
+ // owning app — `owner` (self/foreign-resolved/foreign-unresolved)
188
+ // mirrors the `aspect:` resolution above.
189
+ const parts = isRaw
190
+ ? [`fieldId: ${quote(f.rawFieldId ?? "")}`]
191
+ : owner.kind === "catalog"
192
+ ? [`field: ${owner.expr}.fields.${f.key}`]
193
+ : [
194
+ `field: { __kind: "field", refName: ${quote(f.key)}, name: ${quote(f.name ?? f.key)}, fieldType: "TEXT", ` +
195
+ `parent: ${quote(owner.name)}, parentKind: ${quote(owner.entityType)}, parentName: ${quote(owner.name)} }`,
196
+ ];
113
197
  parts.push(`name: ${quote(f.name ?? "")}`);
114
198
  parts.push(`description: ${quote(f.description ?? "")}`);
115
- if (tool.typeKey === "createRecord" && f.required !== undefined)
199
+ if ((tool.typeKey === "createRecord" || tool.typeKey === "updateRecord") && f.required !== undefined) {
116
200
  parts.push(`required: ${f.required}`);
117
- const todo = isRaw ? " // TODO: raw platform field id - the field belongs to a foreign/out-of-scope aspect ei can't resolve to a reference" : "";
201
+ }
202
+ const todo = isRaw
203
+ ? " // TODO: raw platform field id - the field belongs to a foreign/out-of-scope aspect ei can't resolve to a reference"
204
+ : owner.kind === "raw"
205
+ ? ` // TODO: foreign field — type unconfirmed (ei's elementum_field data source doesn't expose it) and refName is a best-effort guess; verify against "${owner.name}"`
206
+ : "";
118
207
  lines.push(` { ${parts.join(", ")} },${todo}`);
119
208
  }
120
209
  lines.push(" ],");
@@ -96,6 +96,7 @@ export const skillModule = {
96
96
  appTfLabel: ctx.appTfLabel,
97
97
  orgRefs: ctx.orgRefs,
98
98
  diagnostics: ctx.diagnostics,
99
+ ...(ctx.siblingEntities !== undefined && { siblingEntities: ctx.siblingEntities }),
99
100
  }),
100
101
  },
101
102
  catalog: {
@@ -23,11 +23,37 @@ export interface SkillToTfContext {
23
23
  readonly orgRefs: OrgRefLookup;
24
24
  /** Degradations land here — reported by the caller, never silent. */
25
25
  readonly diagnostics: string[];
26
+ /**
27
+ * Every skill entity discovered for this app (self included) — forwarded
28
+ * by build.ts, unordered. Used to replicate ei's cross-skill tool-label
29
+ * disambiguation (see {@link computeToolLabelSuffixes}). Absent in
30
+ * contexts that don't supply it (e.g. most unit tests): every tool then
31
+ * gets the bare label, matching the pre-#310 behavior for a single skill.
32
+ */
33
+ readonly siblingEntities?: readonly DeployableEntity[];
26
34
  }
27
35
  export interface SkillToTfResult {
28
36
  readonly blocks: readonly TfBlock[];
29
37
  /** The skill's terraform address. */
30
38
  readonly address: string;
31
39
  }
40
+ /**
41
+ * Mirrors ei's cross-skill tool-name disambiguation (`cmd/elementum/export/
42
+ * imports.go`'s `skillNames`/`toolNames` counting maps) — a same-app,
43
+ * same-named tool on two different skills is not a collision on the
44
+ * platform: ei's exporter walks `app.Skills` (each skill's tools in turn)
45
+ * and gives the first occurrence of a sanitized tool name the bare label,
46
+ * each later occurrence `_1`, `_2`, … Board issue #310's live capture
47
+ * (2026-08-18, against a deliberately-collided app) confirmed the walk
48
+ * order is ascending by the skill's display NAME — not creation order, not
49
+ * authoring-file order. Ordering of tools WITHIN one skill wasn't
50
+ * observable live (each capture skill carried only one tool); authored
51
+ * array order is assumed there pending a capture that can confirm it.
52
+ *
53
+ * Returns suffixes ("" for the first occurrence, "_1", "_2", … after)
54
+ * keyed by `${skillRefName}#${toolIndex}` — the tool's position in its own
55
+ * skill's authored `tools` array, NOT a global index.
56
+ */
57
+ export declare function computeToolLabelSuffixes(siblingSkills: readonly DeployableEntity[]): ReadonlyMap<string, string>;
32
58
  /** `elementum_agentic_skill` + one tool resource per implemented tool, in the platform's dialect. */
33
59
  export declare function skillToTf(entity: DeployableEntity, ctx: SkillToTfContext): SkillToTfResult;