@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
@@ -189,9 +189,7 @@ function appRef(appRefName) {
189
189
  // ctx.trigger.updatedByManagerEmail, neither of which exists on the typed
190
190
  // ctx, so every pulled automation using them failed `tsc --noEmit`.
191
191
  const WIRE_REF_SEGMENT_TO_TS = {
192
- "Record": "record",
193
192
  "Changed Fields": "changedFieldIds",
194
- "All found records": "records",
195
193
  "Iteration": "iteration",
196
194
  "Slack Thread ID": "slackThreadId",
197
195
  "Slack Channel ID": "slackChannelId",
@@ -227,6 +225,19 @@ function pathNames(path) {
227
225
  return WIRE_REF_SEGMENT_TO_TS[name] ?? name;
228
226
  });
229
227
  }
228
+ // recordSearch's own output ref names ("Records Size" -> totalCount, "All
229
+ // found records" -> records) — deliberately NOT in WIRE_REF_SEGMENT_TO_TS,
230
+ // which triggerRefPath also consults: a record-created/updated trigger's ref
231
+ // path is built from a FIELD's DISPLAY NAME, and a real field could
232
+ // coincidentally be named "Records Size" — translating it globally would
233
+ // misdecode that trigger ref as the unrelated task-output name "totalCount"
234
+ // before triggerRefPath's field-name matching even runs. Scoped to
235
+ // recordSearch task refs only, where these two strings are the platform's
236
+ // fixed wire names, never a field's own display name.
237
+ const RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS = {
238
+ "Records Size": "totalCount",
239
+ "All found records": "records",
240
+ };
230
241
  /**
231
242
  * A webhook trigger's `body`/`headers` refs come back as "Body (Plain
232
243
  * Text)"/"Headers (Content-Type)" - one wire segment naming both the
@@ -251,6 +262,17 @@ function triggerRefPath(path, ctx) {
251
262
  if (webhookMatch)
252
263
  return [webhookMatch[1].toLowerCase(), webhookMatch[2]];
253
264
  }
265
+ // A trigger's own bare record reference (confirmed live via `ei refs`,
266
+ // see trigger-record-id.test.ts) — deliberately scoped to triggerRefPath,
267
+ // not the shared WIRE_REF_SEGMENT_TO_TS table: createRecord/
268
+ // findRelatedRecords TASKS also expose a wire key literally named
269
+ // "Record", but as their scalar record-ID output (ASPECT_RECORD_ID, not
270
+ // this trigger-level ASPECT_RECORD whole-record reference) — translating
271
+ // it globally intercepted that task-level case before it could ever be
272
+ // checked (decodeValue's own dedicated "Record" handling for those task
273
+ // types).
274
+ if (wireName === "Record")
275
+ return ["record"];
254
276
  // Case-insensitive: the platform re-cases "By" to "by" when building some
255
277
  // compound ref phrases (e.g. field "Created By" -> ref key "Created by
256
278
  // Email"), so a case-sensitive compare against the field's own display
@@ -302,7 +324,19 @@ function decodeReferenceString(value, ctx) {
302
324
  }
303
325
  if (pieces[0] === "task" && pieces.length > 2)
304
326
  return { kind: "taskRef", task: pieces[1], path: pieces.slice(2) };
305
- return undefined;
327
+ // Any other/future value_reference shape - confirmed live: conciergeforfield's
328
+ // cff_find_nearby_accounts_if_user_is_impersonating_a_sales_rep switch_case
329
+ // references a workflow variable ("variable.<uuid>"); setVariable/variable_task
330
+ // authoring is itself deferred (no typed construct exists yet to resolve this
331
+ // to - see the automation module's header), so it can never become a real ref
332
+ // today, and any future dialect growth hits the same "we don't recognize this
333
+ // reference shape" situation. Degrade to the {kind:"unresolved"} placeholder
334
+ // (same escape hatch fieldRef already uses for an orphaned field_id) rather
335
+ // than throwing and losing the whole automation (#171) - printFilterField
336
+ // marks it distinctly from a field placeholder (hint !== "field") so the BUILD
337
+ // direction fails loudly instead of silently mis-rebuilding it as a field_id
338
+ // (#290; a value_reference position can never round-trip through field_id).
339
+ return { kind: "unresolved", uuid: value, hint: pieces[0] ?? "reference" };
306
340
  }
307
341
  /**
308
342
  * Inverse of filterReferenceToTf's TRIGGER case (automation/to-tf.ts): a
@@ -376,7 +410,30 @@ function decodeValue(value, ctx) {
376
410
  }
377
411
  const task = ctx.taskByAddress.get(`${value.type}.${value.label}`);
378
412
  if (task !== undefined && value.path[0] === "refs") {
379
- const keyPath = pathNames(value.path.slice(1)).flatMap((segment) => segment.split("."));
413
+ const rawSegments = pathNames(value.path.slice(1));
414
+ if (task.block.type === "elementum_record_search_task" && rawSegments.length === 1 && rawSegments[0] === "First found record id") {
415
+ return { kind: "taskRef", task: task.refKey, path: ["record", "recordId"] };
416
+ }
417
+ // createRecord/findRelatedRecords' own record-id output — confirmed
418
+ // live via `ei refs`: neither task exposes a "recordId" key at all;
419
+ // "Record" (ASPECT_RECORD_ID) is the real one, matching the
420
+ // provider's own schema docs (build.ts's rewriteForwardTaskRefName
421
+ // has the full citation). Previously unhandled here entirely — a
422
+ // pulled automation referencing this output round-tripped as a raw
423
+ // `ctx.tasks.<t>.Record` property access that doesn't exist on
424
+ // either task's typed output, failing tsc.
425
+ if ((task.block.type === "elementum_create_record_task" || task.block.type === "elementum_find_related_records_task") &&
426
+ rawSegments.length === 1 &&
427
+ rawSegments[0] === "Record") {
428
+ return { kind: "taskRef", task: task.refKey, path: ["record", "recordId"] };
429
+ }
430
+ if (task.block.type === "elementum_record_search_task" && rawSegments.length === 1) {
431
+ const recordSearchName = RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS[rawSegments[0]];
432
+ if (recordSearchName !== undefined) {
433
+ return { kind: "taskRef", task: task.refKey, path: [recordSearchName] };
434
+ }
435
+ }
436
+ const keyPath = rawSegments.flatMap((segment) => segment.split("."));
380
437
  if (task.block.type === "elementum_variable_task") {
381
438
  return { kind: "variableParamRef", varTask: task.refKey, name: keyPath.join(".") };
382
439
  }
@@ -448,6 +505,37 @@ function decodeValue(value, ctx) {
448
505
  ...(typeof name === "string" ? { name } : {}),
449
506
  };
450
507
  }
508
+ if (value.$expr === "data-attr" && value.type === "elementum_field" && value.path[0] === "id") {
509
+ // The reverse of to-tf.ts's `crossAppFieldToTf`: a field belonging to a
510
+ // DIFFERENT app/element than this automation's own — resolved via the
511
+ // field's own `data.elementum_field` block, whose `object_id` names
512
+ // the owner's `data.elementum_app`/`data.elementum_element` lookup.
513
+ const fieldBlock = ctx.dataBlocks.get(`${value.type}.${value.label}`);
514
+ const objectId = fieldBlock?.attrs["object_id"];
515
+ if (objectId === undefined || !isTfExpr(objectId) || objectId.$expr !== "data-attr" || (objectId.type !== "elementum_app" && objectId.type !== "elementum_element")) {
516
+ throw new EntityTfError(`data.elementum_field.${value.label}: object_id is not a resolvable app/element data reference`);
517
+ }
518
+ const entityType = objectId.type === "elementum_element" ? "element" : "app";
519
+ const ownerLabel = objectId.label;
520
+ const kindPrefix = `${entityType}_${ownerLabel}_`;
521
+ const bareLabel = value.label.startsWith(kindPrefix)
522
+ ? value.label.slice(kindPrefix.length)
523
+ : value.label.startsWith(`${ownerLabel}_`)
524
+ ? value.label.slice(ownerLabel.length + 1)
525
+ : value.label;
526
+ const ownerName = ctx.dataBlocks.get(`${objectId.type}.${objectId.label}`)?.attrs["name"];
527
+ const fieldName = fieldBlock?.attrs["name"];
528
+ return {
529
+ kind: "field",
530
+ appHandle: tfLabelToTsLabel(ownerLabel),
531
+ fieldKey: tfLabelToTsLabel(bareLabel),
532
+ foreign: {
533
+ entityType,
534
+ name: typeof ownerName === "string" ? ownerName : tfLabelToTsLabel(ownerLabel),
535
+ ...(typeof fieldName === "string" ? { fieldName } : {}),
536
+ },
537
+ };
538
+ }
451
539
  if (value.$expr === "data-attr" && value.type === "elementum_ai_provider_connector" && value.path[0] === "id") {
452
540
  return { kind: "connector", id: "", ...resolveConnectorRef(value.type, value.label, ctx) };
453
541
  }
@@ -581,8 +669,13 @@ function filterValue(value, ctx) {
581
669
  const currentUserType = raw === "email" || raw === "domain" ? raw : "id";
582
670
  return { kind: "currentUser", currentUserType };
583
671
  }
672
+ // The provider's `filter.value` schema splits "static" from "dynamic"
673
+ // across two distinct attributes — `value` vs `value_reference` (same
674
+ // split `left_value` already respects, decoded via `value_reference`
675
+ // just below in `decodeFilter`) — so a reference-typed value's payload
676
+ // lives under `value_reference`, not `value`.
584
677
  if (type === "reference")
585
- return { kind: "reference", ref: decodeValue(value.value, ctx) };
678
+ return { kind: "reference", ref: decodeValue(value.value_reference, ctx) };
586
679
  if (["text", "number", "boolean", "uuid", "date", "datetime"].includes(type)) {
587
680
  const optionLabel = picklistOptionLabel(value.value);
588
681
  if (optionLabel !== undefined)
@@ -723,6 +816,7 @@ function taskArgs(block, factory, ctx) {
723
816
  if (!Array.isArray(value))
724
817
  throw new EntityTfError(`${block.type}.${block.label}: fields must be an array`);
725
818
  const values = {};
819
+ const unresolvable = [];
726
820
  for (const item of value) {
727
821
  if (!isObject(item) || item.field_id === undefined)
728
822
  throw new EntityTfError(`${block.type}.${block.label}: invalid field assignment`);
@@ -739,15 +833,26 @@ function taskArgs(block, factory, ctx) {
739
833
  // mismatches state on every plan. Nothing on the TS side can fix a
740
834
  // gap in ei's own export scope, so - confirmed live against
741
835
  // demoapptwo's "Create record app external" automation, whose target
742
- // field lives on a different app - throw here (same as any other
836
+ // field lives on a different app - throw (same as any other
743
837
  // unreconstructable reference) so the automation's full graph is
744
838
  // excluded from adoption via automationOwnedAddresses, rather than
745
- // permanently failing the adoption gate for the whole app.
839
+ // permanently failing the adoption gate for the whole app. A
840
+ // foreign-target task typically has EVERY field assignment
841
+ // unresolvable for the same reason (confirmed live:
842
+ // conciergeforfield's cff_analyze_agent_performance_v3 has 13) - collect
843
+ // them all before throwing instead of stopping at the first, so the
844
+ // message doesn't look like a single-field fluke (#285).
746
845
  if (field.kind !== "field") {
747
- throw new EntityTfError(`${block.type}.${block.label}: field assignment references an unresolvable field (${field.kind === "unresolved" ? field.uuid : "unknown"})`);
846
+ unresolvable.push(field.kind === "unresolved" ? field.uuid : "unknown");
847
+ continue;
748
848
  }
749
849
  values[field.fieldKey] = decodeValue(item.value, ctx);
750
850
  }
851
+ if (unresolvable.length > 0) {
852
+ throw new EntityTfError(`${block.type}.${block.label}: ${unresolvable.length} field assignment${unresolvable.length === 1 ? "" : "s"} ` +
853
+ `reference${unresolvable.length === 1 ? "s" : ""} an unresolvable field (${unresolvable.join(", ")}) — ` +
854
+ `likely a foreign object_id target the export didn't recursively discover (--recursive=false)`);
855
+ }
751
856
  args.values = values;
752
857
  continue;
753
858
  }
@@ -984,9 +1089,20 @@ function taskRefKey(block, automationLabel, appTfLabel) {
984
1089
  const taskChild = childPartFromScopedLabel(appTfLabel, block.label ?? "", "app");
985
1090
  const tail = taskChild.startsWith(`${autoChild}_`) ? taskChild.slice(autoChild.length + 1) : taskChild;
986
1091
  const taskName = typeof block.attrs.name === "string" ? block.attrs.name : undefined;
987
- if (taskName !== undefined && sanitizeName(taskName) === tail && (taskName === tail || /[_\s-]/.test(taskName)))
988
- return taskName;
989
- return tfLabelToTsLabel(tail);
1092
+ if (taskName !== undefined) {
1093
+ const sanitized = sanitizeName(taskName);
1094
+ // ei sanitizes `<automation>_<task>` as ONE combined string
1095
+ // (imports.go), so the digit-leading guard only ever sees the
1096
+ // automation's own first character - a task name that itself starts
1097
+ // with a digit loses its own underscore fix once the automation's
1098
+ // child part is stripped back off above, so `sanitized` (computed on
1099
+ // the task name alone) still carries the underscore `tail` lacks
1100
+ // (issue #79).
1101
+ const matches = sanitized === tail || sanitized === `_${tail}`;
1102
+ if (matches && (taskName === tail || /[_\s-]/.test(taskName)))
1103
+ return taskName;
1104
+ }
1105
+ return tfLabelToTsLabel(/^[0-9]/.test(tail) ? `_${tail}` : tail);
990
1106
  }
991
1107
  /**
992
1108
  * Best-effort resource footprint of one automation, used ONLY when whole-
@@ -2,7 +2,7 @@ import { EntityTfError } from "../../engine/entity.js";
2
2
  import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET } from "../../core/system-fields.js";
3
3
  import { appResourceLabelPrefix, appScopedResourceLabel, expr, isTfExpr, isUuid, sanitizeName, snakeSlug, tsLabelToTfLabel, } from "../../engine/tf/index.js";
4
4
  import { CONNECTOR_ORG_BAG } from "../org/connector.js";
5
- import { FILE_READER_SUB_TYPE_BY_TYPE_KEY } from "../file-reader/types.js";
5
+ import { FILE_READER_SUB_TYPE_BY_RESOURCE, FILE_READER_SUB_TYPE_BY_TYPE_KEY } from "../file-reader/types.js";
6
6
  import { AUTOMATION_RESOURCE_TYPE, WORKFLOW_PUBLISH_RESOURCE_TYPE } from "./types.js";
7
7
  function scopedLabel(appTfLabel, label) {
8
8
  return appScopedResourceLabel(appTfLabel, label);
@@ -36,6 +36,22 @@ const TRIGGER_RESOURCES = {
36
36
  datamine: "elementum_datamine_trigger",
37
37
  survey: "elementum_survey_trigger",
38
38
  };
39
+ /**
40
+ * setVariable tasks share one wire key ("variable") but two distinct
41
+ * resource types depending on create vs. update — TASK_RESOURCES can't
42
+ * carry both under one key. Shared by preRegister (so an explicit
43
+ * hclParent onto an update-variant task resolves to the right type — see
44
+ * edk#287) and emitTasks's own block emission, so the two can never
45
+ * disagree again.
46
+ */
47
+ function variableTaskResourceType(taskBody, refKey) {
48
+ const creates = Array.isArray(taskBody.create) ? taskBody.create : [];
49
+ const updates = Array.isArray(taskBody.update) ? taskBody.update : [];
50
+ if (creates.length + updates.length !== 1) {
51
+ throw new EntityTfError(`setVariable task "${refKey}" must contain exactly one create or update for Terraform`);
52
+ }
53
+ return creates.length === 1 ? "elementum_variable_task" : "elementum_update_variable_task";
54
+ }
39
55
  const TASK_RESOURCES = {
40
56
  message: "elementum_message_task",
41
57
  updateField: "elementum_update_field_task",
@@ -157,6 +173,76 @@ function addressExpr(address, path = ["id"]) {
157
173
  throw new EntityTfError(`invalid terraform address "${address}"`);
158
174
  return expr.resourceAttr(address.slice(0, dot), address.slice(dot + 1), [...path]);
159
175
  }
176
+ /**
177
+ * A field token whose `parent` names a DIFFERENT app/element than the one
178
+ * this automation belongs to (e.g. a `recordSearch` task's filter against
179
+ * another app's field) — resolved via a `data.elementum_field` lookup keyed
180
+ * by the owner's id + the field's display name, mirroring
181
+ * `field/to-tf.ts`'s `resolveRelatedLabelField` for a relation field's
182
+ * `relatedLabelField`. Self-contained: `parentKind`/`parentName` (stamped by
183
+ * `appCatalog`/`elementCatalog` — see `FieldRef`) carry everything needed to
184
+ * register the owner's own `data.elementum_app`/`data.elementum_element`
185
+ * lookup here too, rather than depending on that owner also appearing
186
+ * elsewhere in this same payload (e.g. as the task's own `app:` target).
187
+ * The label is kind-prefixed for the same reason `field/to-tf.ts` prefixes
188
+ * its own foreign-field label: an app and an element can share a refName,
189
+ * and `elementum_field` is one shared data-source type for both.
190
+ */
191
+ function crossAppFieldToTf(value, ctx, dataBlocks) {
192
+ const parent = value.parent;
193
+ if (parent === undefined)
194
+ throw new EntityTfError(`field ref "${value.refName}" has no parent`);
195
+ // `parentKind`/`parentName` are stamped ALONGSIDE `parent` by
196
+ // `appCatalog`/`elementCatalog` (see `FieldRef`'s doc comment) — never one
197
+ // without the other for a genuine cross-aspect ref. Defaulting either one
198
+ // here instead of failing loudly is exactly the failure mode that
199
+ // previously produced `data.elementum_app.tickets { name = "tickets" }`
200
+ // for what was actually an ELEMENT with a real display name of "Tickets"
201
+ // — a lookup that builds cleanly and misses silently at apply.
202
+ if (value.parentKind === undefined) {
203
+ throw new EntityTfError(`field ref "${value.refName}" has a parent ("${parent}") but no parentKind — incomplete foreign-field provenance; can't tell whether the owner is an app or an element`);
204
+ }
205
+ if (value.parentName === undefined) {
206
+ throw new EntityTfError(`field ref "${value.refName}" has a parent ("${parent}") but no parentName — incomplete foreign-field provenance; the owner lookup would key on the refName instead of its real display name and silently miss at apply`);
207
+ }
208
+ const fieldName = value.name ?? value.refName;
209
+ const ownerType = value.parentKind === "element" ? "elementum_element" : "elementum_app";
210
+ const ownerLabel = tsLabelToTfLabel(parent);
211
+ const objectId = expr.dataAttr(ownerType, ownerLabel, ["id"]);
212
+ const fieldLabel = `${value.parentKind}_${ownerLabel}_${tsLabelToTfLabel(value.refName)}`;
213
+ // Route through the build-wide `orgRefs` registry (same one `agent-tool`/
214
+ // `agent`/`skill`/`field` use) instead of this call's own local
215
+ // `dataBlocks` map, so two DIFFERENT automation files referencing the same
216
+ // foreign app/element/field collapse to one `data.tf` entry instead of
217
+ // each emitting its own identically-addressed `data` block into its own
218
+ // per-automation `.tf` file — a duplicate resource address OpenTofu
219
+ // rejects at `validate`/`plan`. `dataBlocks` remains the fallback for
220
+ // callers that don't supply `orgRefs` (unit tests).
221
+ if (ctx.orgRefs !== undefined) {
222
+ if (value.parentKind === "element") {
223
+ ctx.orgRefs.foreignElement(ownerLabel, value.parentName);
224
+ }
225
+ else {
226
+ ctx.orgRefs.foreignApp(ownerLabel, value.parentName);
227
+ }
228
+ ctx.orgRefs.foreignField("elementum_field", fieldLabel, objectId, fieldName);
229
+ }
230
+ else {
231
+ dataBlocks.set(`${ownerType}.${ownerLabel}`, {
232
+ kind: "data",
233
+ type: ownerType,
234
+ label: ownerLabel,
235
+ attrs: { name: value.parentName },
236
+ });
237
+ dataBlocks.set(`elementum_field.${fieldLabel}`, {
238
+ kind: "data",
239
+ type: "elementum_field",
240
+ label: fieldLabel,
241
+ attrs: { object_id: objectId, name: fieldName },
242
+ });
243
+ }
244
+ return expr.dataAttr("elementum_field", fieldLabel, ["id"]);
245
+ }
160
246
  function tokenToTf(value, ctx, dataBlocks) {
161
247
  switch (value.__kind) {
162
248
  case "userField":
@@ -168,18 +254,37 @@ function tokenToTf(value, ctx, dataBlocks) {
168
254
  throw new EntityTfError(`cross-aspect ref "${value.refName}" has no lookup name`);
169
255
  const type = value.__kind === "element" ? "elementum_element" : "elementum_app";
170
256
  const label = tsLabelToTfLabel(value.refName);
171
- dataBlocks.set(`${type}.${label}`, {
172
- kind: "data",
173
- type,
174
- label,
175
- attrs: { name: value.name },
176
- });
257
+ // See `crossAppFieldToTf`'s comment: route through the build-wide
258
+ // `orgRefs` registry so multiple automations referencing the same
259
+ // foreign app/element collapse to one `data.tf` entry instead of
260
+ // each stamping a duplicate `data` block into its own file.
261
+ if (ctx.orgRefs !== undefined) {
262
+ if (value.__kind === "element") {
263
+ ctx.orgRefs.foreignElement(label, value.name);
264
+ }
265
+ else {
266
+ ctx.orgRefs.foreignApp(label, value.name);
267
+ }
268
+ }
269
+ else {
270
+ dataBlocks.set(`${type}.${label}`, {
271
+ kind: "data",
272
+ type,
273
+ label,
274
+ attrs: { name: value.name },
275
+ });
276
+ }
177
277
  return expr.dataAttr(type, label, ["id"]);
178
278
  }
179
279
  return expr.resourceAttr("elementum_app", ctx.appTfLabel, ["id"]);
180
280
  case "field": {
181
- if (value.parent !== undefined && value.parent !== ctx.appRefName) {
182
- throw new EntityTfError(`cross-app field ref "${value.parent}.${value.refName}" is not reproducible offline`);
281
+ // `!== ctx.appRefName` alone isn't enough: an app and a FOREIGN
282
+ // ELEMENT can share a refName (workspace keys disambiguate by
283
+ // kind+refName, not refName alone), so a same-named element field
284
+ // must still resolve as foreign — the automation's own app is
285
+ // always an app (automations are app-owned only, for now).
286
+ if (value.parent !== undefined && (value.parent !== ctx.appRefName || value.parentKind === "element")) {
287
+ return crossAppFieldToTf(value, ctx, dataBlocks);
183
288
  }
184
289
  const address = ctx.fieldAddresses.get(value.refName);
185
290
  return address === undefined
@@ -424,6 +529,12 @@ function unwrapDefault(value) {
424
529
  return values.length === 1 ? values[0] : value;
425
530
  }
426
531
  function filterReferenceToTf(value, refs) {
532
+ // Raw pass-through for a filter left side the pull-time deserializer
533
+ // couldn't decode to a typed ref (filter.ts's leftDescriptor, matching the
534
+ // UNRESOLVED_REFERENCE_MARKER case) - reproduces the original value_reference
535
+ // string verbatim rather than dispatching on a type that was never captured.
536
+ if (isObject(value) && typeof value.__rawFilterReference === "string")
537
+ return value.__rawFilterReference;
427
538
  if (!isObject(value) || typeof value.type !== "string") {
428
539
  throw new EntityTfError("invalid automation filter reference");
429
540
  }
@@ -518,6 +629,17 @@ function picklistFilterValueToTf(value, field, refs) {
518
629
  return undefined;
519
630
  throw new EntityTfError(`automation filter for picklist field "${field.name ?? field.refName}" uses unknown option ${JSON.stringify(value)}; expected one of: ${field.options.map((option) => JSON.stringify(option)).join(", ")}`);
520
631
  }
632
+ if (field.parent !== undefined && (field.parent !== refs.owner.appRefName || field.parentKind === "element")) {
633
+ // The options-by-label local only exists for a field owned by THIS
634
+ // automation's own app — `appendFieldLocals` (field/locals.ts) only
635
+ // walks the current stream root's own field resources, and there is no
636
+ // `data.elementum_field`-style lookup for a foreign aspect's option
637
+ // label → id mapping. Building the same local reference here would
638
+ // point at a local that plan/apply can never resolve ("reference to
639
+ // undeclared local value") instead of failing at build time, where the
640
+ // problem is actually diagnosable.
641
+ throw new EntityTfError(`automation filter for picklist field "${field.name ?? field.refName}" belongs to a foreign ${field.parentKind ?? "app"} ("${field.parent}") — filtering a foreign picklist field by option label is not supported on the terraform path yet; filter by option id instead`);
642
+ }
521
643
  const localName = field.tags?.includes("STATUS")
522
644
  ? `${refs.owner.appTfLabel}_status_options_by_label`
523
645
  : field.tags?.includes("STAGE")
@@ -536,9 +658,17 @@ function filterValueToTf(value, refs, field) {
536
658
  result.current_user_type = value.currentUserType;
537
659
  }
538
660
  if (value.value !== undefined) {
539
- result.value = type === "reference"
540
- ? filterReferenceToTf(value.value, refs)
541
- : picklistFilterValueToTf(value.value, field, refs) ?? valueToTf(value.value, refs);
661
+ // The provider's `filter.value` schema splits "static" from "dynamic"
662
+ // across two distinct attributes — `value` vs `value_reference` — same
663
+ // split `left_value` already respects just above. A reference-typed
664
+ // value belongs under `value_reference`; the provider rejects it under
665
+ // `value` ("value_reference is required for reference type").
666
+ if (type === "reference") {
667
+ result.value_reference = filterReferenceToTf(value.value, refs);
668
+ }
669
+ else {
670
+ result.value = picklistFilterValueToTf(value.value, field, refs) ?? valueToTf(value.value, refs);
671
+ }
542
672
  }
543
673
  return result;
544
674
  }
@@ -891,6 +1021,33 @@ function configAttrs(kind, config, refs) {
891
1021
  }
892
1022
  return attrs;
893
1023
  }
1024
+ /** Bare file-reader addresses referenced by any task's `file_reader_id`.
1025
+ * Stamped onto `elementum_automation.depends_on` so destroy waits for the
1026
+ * automation itself — the task→reader edge alone lets tofu destroy the
1027
+ * reader in parallel with the automation, and the platform still treats
1028
+ * the live workflow as a document-model usage. */
1029
+ function fileReaderDependsOn(blocks) {
1030
+ const seen = new Set();
1031
+ const deps = [];
1032
+ for (const block of blocks) {
1033
+ const idRef = block.attrs.file_reader_id;
1034
+ if (!isTfExpr(idRef) || idRef.$expr !== "resource-attr")
1035
+ continue;
1036
+ if (!FILE_READER_SUB_TYPE_BY_RESOURCE.has(idRef.type))
1037
+ continue;
1038
+ const key = `${idRef.type}.${idRef.label}`;
1039
+ if (seen.has(key))
1040
+ continue;
1041
+ seen.add(key);
1042
+ deps.push(expr.resourceAttr(idRef.type, idRef.label));
1043
+ }
1044
+ deps.sort((a, b) => {
1045
+ const left = a.$expr === "resource-attr" ? `${a.type}.${a.label}` : "";
1046
+ const right = b.$expr === "resource-attr" ? `${b.type}.${b.label}` : "";
1047
+ return left.localeCompare(right);
1048
+ });
1049
+ return deps;
1050
+ }
894
1051
  function taskLabel(automationLabel, refKey) {
895
1052
  // ei's task label is `<auto>_<sanitizeName(task name)>` (CLAUDE.md), and
896
1053
  // from-tf.ts's taskRefKey either preserves the task's raw display name
@@ -953,7 +1110,7 @@ export function automationToTf(entity, ctx) {
953
1110
  if (taskRefs.has(refKey))
954
1111
  throw new EntityTfError(`duplicate task refKey "${refKey}"`);
955
1112
  const [wireType, taskBody] = onlyEntry(task.task, "task " + refKey);
956
- const resourceType = TASK_RESOURCES[wireType];
1113
+ const resourceType = wireType === "variable" ? variableTaskResourceType(taskBody, refKey) : TASK_RESOURCES[wireType];
957
1114
  if (resourceType === undefined)
958
1115
  throw new EntityTfError(`task type "${wireType}" is not supported by the provider HCL contract`);
959
1116
  const registeredLabel = taskLabel(label, refKey);
@@ -1015,16 +1172,13 @@ export function automationToTf(entity, ctx) {
1015
1172
  taskParent = expr.resourceAttr(explicitParent.type, explicitParent.label);
1016
1173
  }
1017
1174
  if (wireType === "variable") {
1175
+ const variableType = variableTaskResourceType(inner, refKey);
1176
+ const isCreate = variableType === "elementum_variable_task";
1018
1177
  const creates = Array.isArray(inner.create) ? inner.create : [];
1019
1178
  const updates = Array.isArray(inner.update) ? inner.update : [];
1020
- if (creates.length + updates.length !== 1) {
1021
- throw new EntityTfError(`setVariable task "${refKey}" must contain exactly one create or update for Terraform`);
1022
- }
1023
- const isCreate = creates.length === 1;
1024
1179
  const item = (isCreate ? creates[0] : updates[0]);
1025
1180
  if (!isObject(item))
1026
1181
  throw new EntityTfError(`invalid setVariable item on "${refKey}"`);
1027
- const variableType = isCreate ? "elementum_variable_task" : "elementum_update_variable_task";
1028
1182
  const variableAttrs = { parent: taskParent, name: displayName };
1029
1183
  if (isCreate) {
1030
1184
  if (typeof item.name !== "string" || typeof item.type !== "string")
@@ -1139,6 +1293,10 @@ export function automationToTf(entity, ctx) {
1139
1293
  return first === undefined ? undefined : { root: first, terminal: parent };
1140
1294
  };
1141
1295
  emitTasks(payload.tasks ?? [], expr.resourceAttr(triggerType, label));
1296
+ const fileReaderDeps = fileReaderDependsOn(blocks);
1297
+ if (fileReaderDeps.length > 0) {
1298
+ automation.attrs.depends_on = fileReaderDeps;
1299
+ }
1142
1300
  {
1143
1301
  const outputValues = payload.outputProperties?.outputs ?? [];
1144
1302
  const publish = {
@@ -26,8 +26,16 @@ import { type AspectRef, type CloudLinkRef, type FieldRef } from "../../catalog/
26
26
  import type { DeployableEntity, EntityDeployOptions } from "../../engine/entity.js";
27
27
  import type { AccessPolicyOptions } from "../access-policy/build.js";
28
28
  import { type DisplayBlock } from "../app/display-blocks.js";
29
- import { type AppCategory, type AppCloudOptions, type AppField, type AppFieldRefs, type AppLayout, type AppListView } from "../app/build.js";
30
- export type { AppCategory, AppField, AppLayout, AppListView, PicklistOption } from "../app/build.js";
29
+ import { type AppCategory, type AppCloudOptions, type AppField, type AppFieldRefs, type AppLayout, type AppListView, type AppSystemFieldOverride } from "../app/build.js";
30
+ export type { AppCategory, AppField, AppLayout, AppListView, AppSystemFieldOverride, PicklistOption } from "../app/build.js";
31
+ /** The system fields elements actually have (per `locals.ts`) — unlike apps, no status/stage/audit fields. */
32
+ export type ElementSystemFieldKey = "id" | "title";
33
+ export declare const ELEMENT_SYSTEM_FIELD_KEYS: readonly ElementSystemFieldKey[];
34
+ /** Overrides for an element's platform-owned `id`/`title` fields — see `AppSystemFields` for the full rationale. */
35
+ export interface ElementSystemFields {
36
+ readonly id?: AppSystemFieldOverride;
37
+ readonly title?: AppSystemFieldOverride;
38
+ }
31
39
  /**
32
40
  * The source table a LINKED element maps to — an existing table in the
33
41
  * customer's cloud database, vs. a STANDARD element (no `cloudConnection`),
@@ -72,8 +80,14 @@ export interface ElementV2Options<F extends Record<string, AppField> = Record<st
72
80
  /** Fields keyed by ref name. At least one required by the compose API. */
73
81
  readonly fields: F;
74
82
  /**
75
- * Platform-managed (system) fields that exist on every element but are not authored here — e.g.
76
- * ID, Created on. These flow into `ref().fields` so other entities can reference them by typed
83
+ * Overrides for the platform's auto-provisioned `id`/`title` fields — the
84
+ * only two system fields an element has (per `locals.ts`, unlike an app's
85
+ * fuller set). Omit entirely to keep the deploy defaults.
86
+ */
87
+ readonly systemFields?: ElementSystemFields;
88
+ /**
89
+ * Platform-managed (system) fields that exist on every element but are not authored here.
90
+ * These flow into `ref().fields` so other entities can reference them by typed
77
91
  * handle, but are **never included in the deploy payload** (the platform owns them).
78
92
  */
79
93
  readonly readonlyFields?: R;
@@ -90,7 +104,11 @@ export interface ElementV2Options<F extends Record<string, AppField> = Record<st
90
104
  readonly listViews?: Readonly<Record<string, AppListView>>;
91
105
  /** Display order of `listViews` (by key). Defaults to declaration order. */
92
106
  readonly viewOrder?: readonly string[];
93
- /** Element-level sharing & row-level-security policies (`elementum_access_policy`), in declaration order. */
107
+ /**
108
+ * Element-level sharing & row-level-security policies (`elementum_access_policy`), in declaration order.
109
+ * Creating the element also has the platform mint a separate creator policy
110
+ * (the creating user, typically `whereTrue`) that is not authored here.
111
+ */
94
112
  readonly accessPolicies?: readonly AccessPolicyOptions[];
95
113
  }
96
114
  /**
@@ -101,11 +119,11 @@ export interface ElementV2Options<F extends Record<string, AppField> = Record<st
101
119
  * default is `Record<never, never>` rather than a wide `Record<string,
102
120
  * FieldRef>` (a `string`-keyed index signature anywhere here poisons
103
121
  * `DeepRef`'s downstream re-mapping for `ctx.trigger.record`/`ctx.tasks.<t>.
104
- * record`). Elements have no synthesized system fields the way apps do, so
105
- * unlike `AppRef` there's no `Record<SystemFieldKey, FieldRef>` term here.
122
+ * record`). `id`/`title` round out the bag the same way `AppRef` folds in
123
+ * its full `SystemFieldKey` set — a finite, closed term, not a wide index.
106
124
  */
107
125
  export type ElementRef<F extends Record<string, AppField> = Record<string, AppField>, R extends Record<string, FieldRef> = Record<never, never>> = AspectRef & {
108
- readonly fields: AppFieldRefs<F> & R;
126
+ readonly fields: AppFieldRefs<F> & Record<ElementSystemFieldKey, FieldRef> & R;
109
127
  };
110
128
  /**
111
129
  * The configured result of `defineElement` — its reference surface (`ref()`)
@@ -23,8 +23,10 @@
23
23
  * them.
24
24
  */
25
25
  import { slimTokens } from "../../catalog/index.js";
26
+ import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_REQUIRED, SYSTEM_FIELD_TAG_BY_KEY } from "../../core/system-fields.js";
26
27
  import { serializeDisplayBlocks } from "../app/display-blocks.js";
27
- import { serializeField, } from "../app/build.js";
28
+ import { assertNoSystemKeyCollision, serializeField, } from "../app/build.js";
29
+ export const ELEMENT_SYSTEM_FIELD_KEYS = ["id", "title"];
28
30
  /**
29
31
  * Client-side validation for `defineElement` — the authoring-time home for
30
32
  * element validation rules, so a malformed definition fails at define time
@@ -43,6 +45,23 @@ function validateElementOptions(opts) {
43
45
  throw new Error(`defineElement "${opts.name}": namespace "${opts.namespace}" must be lowercase letters only (a–z).`);
44
46
  }
45
47
  }
48
+ /** Serialize authored `systemFields` overrides into compose entries — mirrors `serializeSystemFields` in `app/build.ts`, scoped to id/title (no picklist branch needed). */
49
+ function serializeElementSystemFields(overrides) {
50
+ if (overrides === undefined)
51
+ return [];
52
+ return ELEMENT_SYSTEM_FIELD_KEYS.filter((key) => overrides[key] !== undefined).map((key) => {
53
+ const tag = SYSTEM_FIELD_TAG_BY_KEY[key];
54
+ const override = overrides[key];
55
+ const field = {
56
+ name: override.name ?? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[key],
57
+ type: key === "id" ? "HANDLE" : "TEXT",
58
+ required: SYSTEM_FIELD_REQUIRED[key],
59
+ tags: [tag],
60
+ ...(override.description !== undefined ? { description: override.description } : {}),
61
+ };
62
+ return serializeField(field, key);
63
+ });
64
+ }
46
65
  /** Build a v2 element entity: org-owned, compose-body payload. Exposes `.ref(refName)` and `.def(refName)`. */
47
66
  export function defineElement(opts) {
48
67
  validateElementOptions(opts);
@@ -63,18 +82,37 @@ export function defineElement(opts) {
63
82
  refName: bagKey,
64
83
  name: field.name,
65
84
  parent: refName,
85
+ parentKind: "element",
86
+ parentName: opts.name,
66
87
  fieldType: field.type,
67
88
  ...(field.tags !== undefined ? { tags: field.tags } : {}),
68
89
  };
69
90
  }
70
91
  if (opts.readonlyFields !== undefined) {
71
92
  for (const [bagKey, ref] of Object.entries(opts.readonlyFields)) {
72
- fields[bagKey] = { ...ref, refName: bagKey, parent: refName };
93
+ fields[bagKey] = { ...ref, refName: bagKey, parent: refName, parentKind: "element", parentName: opts.name };
73
94
  }
74
95
  }
96
+ for (const key of ELEMENT_SYSTEM_FIELD_KEYS) {
97
+ if (fields[key] !== undefined)
98
+ continue;
99
+ const tag = SYSTEM_FIELD_TAG_BY_KEY[key];
100
+ const override = opts.systemFields?.[key];
101
+ fields[key] = {
102
+ __kind: "field",
103
+ refName: key,
104
+ name: override?.name ?? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[key],
105
+ parent: refName,
106
+ parentKind: "element",
107
+ parentName: opts.name,
108
+ fieldType: key === "id" ? "HANDLE" : "TEXT",
109
+ tags: [tag],
110
+ };
111
+ }
75
112
  return { __kind: "element", refName: refName, name: opts.name, fields };
76
113
  },
77
114
  def(refName) {
115
+ assertNoSystemKeyCollision("defineElement", opts.name, opts.fields, opts.systemFields);
78
116
  const displayBlocks = serializeDisplayBlocks(opts.displayBlocks, "LAYOUT");
79
117
  const recordCreateDisplayBlocks = serializeDisplayBlocks(opts.recordCreateDisplayBlocks, "CREATE");
80
118
  const payload = {
@@ -90,7 +128,10 @@ export function defineElement(opts) {
90
128
  ...(opts.cloudOptions !== undefined ? { cloudOptions: opts.cloudOptions } : {}),
91
129
  ...(opts.cloudConnection !== undefined ? { cloudConnection: opts.cloudConnection } : {}),
92
130
  ...(opts.commentsEnabled !== undefined ? { commentsEnabled: opts.commentsEnabled } : {}),
93
- fields: Object.entries(opts.fields).map(([bagKey, field]) => serializeField(field, bagKey)),
131
+ fields: [
132
+ ...serializeElementSystemFields(opts.systemFields),
133
+ ...Object.entries(opts.fields).map(([bagKey, field]) => serializeField(field, bagKey)),
134
+ ],
94
135
  ...(displayBlocks !== undefined ? { displayBlocks } : {}),
95
136
  ...(recordCreateDisplayBlocks !== undefined ? { recordCreateDisplayBlocks } : {}),
96
137
  ...(opts.layouts !== undefined ? { layouts: opts.layouts } : {}),