@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
package/README.md CHANGED
@@ -12,7 +12,7 @@ the bridge and OpenTofu; neither is a separate public executable or checkout.
12
12
 
13
13
  ## Installation
14
14
 
15
- Install the signed macOS toolchain:
15
+ Install the authenticated macOS or Linux x64 toolchain:
16
16
 
17
17
  ```sh
18
18
  curl -fsSL https://elementum-toolchain-distribution.vercel.app | sh
@@ -20,10 +20,8 @@ elementum init
20
20
  ```
21
21
 
22
22
  The installer places `elementum` in `~/.elementum/bin` and adds that directory
23
- to PATH via your shell profile (`~/.zprofile` for zsh). The current shell won't
24
- see it until the profile reloads, so `elementum: command not found` right after
25
- install just means you need a fresh shell — open a new terminal or run
26
- `source ~/.zprofile`.
23
+ to PATH via your shell profile (`~/.zprofile` for zsh, otherwise the applicable
24
+ profile file). The current shell won't see it until the profile reloads.
27
25
 
28
26
  Install the SDK in the package workspace that contains your Elementum org
29
27
  folders:
@@ -37,12 +35,11 @@ executable is `elementum`.
37
35
 
38
36
  ### Platform support
39
37
 
40
- The signed `elementum` toolchain currently targets **macOS only** — Apple
41
- Silicon (`darwin-arm64`) and Intel (`darwin-x64`). Linux builds are on the
42
- roadmap but not yet available. The authoring SDK (`@elementumai/edk`) is pure
43
- TypeScript and runs anywhere Node 24+ runs, so Linux CI can install the SDK and
44
- typecheck or build authored source; the platform commands (`auth`, `pull`,
45
- `plan`, `apply`) require running `elementum` on macOS for now.
38
+ The authenticated `elementum` toolchain targets macOS Apple Silicon
39
+ (`darwin-arm64`), macOS Intel (`darwin-x64`), and Linux x64
40
+ (`linux-x64`, glibc). Linux distribution work is tracked in
41
+ [#186](https://github.com/elementum-fde/edk/issues/186). The authoring SDK
42
+ (`@elementumai/edk`) remains pure TypeScript and runs anywhere Node 24+ runs.
46
43
 
47
44
  ## Authentication and profiles
48
45
 
@@ -104,7 +101,8 @@ and the Terraform input/output skeleton:
104
101
  <organization>/
105
102
  org.ts
106
103
  tsconfig.json
107
- terraform.tfstate # created by OpenTofu; commit this
104
+ backend.tf # optional locking backend; user-owned and committed
105
+ terraform.tfstate # committed local state when backend.tf is absent
108
106
  apps/
109
107
  elements/
110
108
  generated/
@@ -140,7 +138,7 @@ elementum --profile=<profile> apply
140
138
  ```
141
139
 
142
140
  `pull app` and `pull element` reconstruct editable TypeScript, regenerate the
143
- catalog, then automatically adopt the exported resources into committed
141
+ catalog, then automatically adopt the exported resources into the configured
144
142
  Terraform state. Adoption is gated to exactly the expected imports, zero
145
143
  create/update/destroy operations, and a clean follow-up plan. Use `--no-adopt`
146
144
  only when you deliberately want source without state adoption.
@@ -155,6 +153,7 @@ The TypeScript-owned command surface is:
155
153
  ```sh
156
154
  elementum init [--check] [--json]
157
155
  elementum update [--check | --dry-run] [--channel stable|preview] [--version <semver>]
156
+ elementum migrate backend [orgRoot] [--check | --dry-run | --auto-approve] [--reconfigure]
158
157
  elementum migrate provider-source [orgRoot] [--check | --dry-run | --auto-approve]
159
158
 
160
159
  elementum pull org --data-only [--root <orgRoot>]
@@ -167,8 +166,12 @@ elementum apply [orgRoot-or-nested-target] [bridge args...]
167
166
 
168
167
  elementum list apps|elements|users|groups|categories|cloud-links
169
168
  elementum list ai-provider-connectors|automations|tables
169
+ elementum new app --name "Support Tickets" --namespace support --category "Operations"
170
+ elementum new element --name "Locations" --namespace locations --category "Operations"
170
171
  elementum new agent --app <appRef> --name "Triage Bot"
171
172
  elementum new skill --app <appRef> --name "Lookup Ticket"
173
+ elementum new automation --app <appRef> --name "Escalate Ticket"
174
+ elementum generate [path] [--root <orgRoot>]
172
175
  elementum canvas <orgRoot-or-file> [--port <port>] [--no-open]
173
176
  elementum playbooks list|install|status|path|print
174
177
  ```
@@ -191,9 +194,23 @@ any directory inside the marked org workspace to omit it. The CLI always runs
191
194
  the bridge/OpenTofu pass-through from that root's `.tf/out/`; it does not scan
192
195
  or deploy an individual target file.
193
196
 
194
- `new agent` and `new skill` create offline app-owned scaffolds without
195
- overwriting an existing ref. Here, `skill` means an Elementum **agentic
196
- skill** attached to an agent. Coding-agent guidance is packaged separately as
197
+ `new app` and `new element` create offline org-root scaffolds — the initial
198
+ authoring file for a brand-new app or element with no existing platform
199
+ counterpart — and immediately register the new entity in the org's generated
200
+ catalog. `new agent`, `new skill`, and `new automation` create offline
201
+ app-owned scaffolds without overwriting an existing ref (automations are
202
+ app-owned only, for now). Here, `skill` means an Elementum
203
+ **agentic skill** attached to an agent.
204
+
205
+ `generate` resyncs `generated/catalog.ts` files with whatever authoring
206
+ source is currently on disk — the fix for hand-editing an existing file
207
+ (e.g. adding an automation's `onDemand` trigger parameter or an `.outputs()`
208
+ key) rather than running one of the `new`/`pull`/`clone` commands that
209
+ regenerate the catalog as a side effect of writing a brand-new file. Pass a
210
+ path to scope it to one app/element; omit it to resync the whole workspace.
211
+ It always refreshes the org-level barrel too.
212
+
213
+ Coding-agent guidance is packaged separately as
197
214
  **playbooks** (Agent Skills-standard `SKILL.md` directories):
198
215
 
199
216
  ```sh
@@ -254,13 +271,13 @@ source uses the same public subpaths.
254
271
 
255
272
  ## Authoring model
256
273
 
257
- EDK uses names and typed tokens in source, with Terraform state providing
258
- platform identity:
274
+ EDK uses names and typed tokens in source, with the configured OpenTofu state
275
+ backend providing platform identity:
259
276
 
260
277
  1. `pull org --data-only` writes org reference bags to `org.ts`, including
261
278
  cloud links, categories, connectors, and groups.
262
279
  2. `pull app` or `pull element` writes editable source and adopts existing
263
- resources into `terraform.tfstate`.
280
+ resources into the required locking remote backend.
264
281
  3. `generated/catalog.ts` is a pure barrel derived from the authored file tree.
265
282
  Import app/entity tokens from `@catalog`; import org tokens from `org.ts`.
266
283
  4. `build` converts TypeScript to the one supported HCL dialect in `.tf/out/`.
@@ -369,20 +386,106 @@ replacement actions just as you would in any Terraform plan.
369
386
 
370
387
  ## Identity and state recovery
371
388
 
372
- `terraform.tfstate` at the org root is the durable binding between authored
373
- labels and live platform objects. Commit it to the workspace repository.
374
- `.tf/` remains generated and ignored.
389
+ Terraform state is the durable binding between authored labels and live
390
+ platform objects. For backwards compatibility, a workspace without
391
+ `<orgRoot>/backend.tf` continues to use the committed root
392
+ `terraform.tfstate` through a generated local backend. This preserves existing
393
+ single-author workspaces, but it provides no state locking; avoid concurrent
394
+ plan/apply operations in that mode.
395
+
396
+ Shared workspaces and CI should commit one user-owned, non-secret
397
+ `<orgRoot>/backend.tf` containing a complete
398
+ `terraform { backend "TYPE" { ... } }` declaration with verified locking.
399
+ `elementum build` projects either that declaration or the compatibility local
400
+ backend into `.tf/out/backend.tf`. Never commit `.terraform/`, `.tf/`, backend
401
+ credential files, or saved plan files. After migrating to remote state, remove
402
+ and stop committing the root `terraform.tfstate`.
403
+
404
+ For example, an S3 backend with native locking can be declared as:
405
+
406
+ ```hcl
407
+ terraform {
408
+ backend "s3" {
409
+ bucket = "elementum-team-state"
410
+ key = "prod/acme/terraform.tfstate"
411
+ region = "us-east-1"
412
+ dynamodb_table = "elementum-state-locks"
413
+ encrypt = true
414
+ }
415
+ }
416
+ ```
417
+
418
+ The backend body remains native OpenTofu HCL, but EDK validates the locking
419
+ contract. Native-locking backends `azurerm`, `cos`, `gcs`, `kubernetes`, `pg`,
420
+ and `remote` are accepted. `consul` must omit `lock` (the default is true) or
421
+ set `lock = true`. `s3` must set `use_lockfile = true` or `dynamodb_table`;
422
+ `http` must set both
423
+ `lock_address` and `unlock_address`; `oss` must set both
424
+ `tablestore_endpoint` and `tablestore_table`. Optional-backend lock settings
425
+ must be literal so EDK can verify them before state access. An explicitly
426
+ authored `local` backend, unlocked/unknown backends, and configurations EDK
427
+ cannot verify fail closed; the generated local compatibility backend is the
428
+ only local exception.
429
+ The storage and locking infrastructure and access policies must already exist;
430
+ EDK does not provision them.
431
+
432
+ Backend authentication must use that backend's standard environment or
433
+ workload-identity chain: for example AWS/GCP/Azure OIDC, an IAM role, or
434
+ environment variables supplied by CI. Do not put access keys, passwords,
435
+ tokens, secret-manager data sources, or credential paths in `backend.tf`.
436
+ Backend initialization happens before providers and data sources, so it cannot
437
+ read a Terraform-managed secret. EDK does not accept `-backend-config` secrets
438
+ and never writes backend credentials into generated HCL.
439
+
440
+ OpenTofu owns locking. EDK does not implement a weaker parallel lock or disable
441
+ native locking: `plan`, `apply`, adoption imports, rename `state mv`, and
442
+ state-repair operations use the declared backend. Standard options such as
443
+ `-lock-timeout=5m` pass through:
444
+
445
+ ```sh
446
+ elementum --profile=<profile> plan <orgRoot> -lock-timeout=5m
447
+ elementum --profile=<profile> apply <orgRoot> -auto-approve -lock-timeout=5m
448
+ ```
449
+
450
+ Backend initialization is lazy and noninteractive. A per-working-directory
451
+ fingerprint prevents ordinary plan/apply/state commands from silently
452
+ re-binding a changed backend; use the guarded migration command instead.
453
+
454
+ ### Migrate committed local state to a remote backend
455
+
456
+ Create the backend infrastructure first, then add and review `backend.tf`.
457
+ The migration uses native `tofu init -migrate-state`, takes an ignored recovery
458
+ snapshot, refuses to overwrite unrelated destination state, verifies
459
+ lineage/resources, removes the obsolete root copy, and requires a final
460
+ zero-change plan:
461
+
462
+ ```sh
463
+ elementum migrate backend <orgRoot> --check
464
+ elementum migrate backend <orgRoot> --dry-run
465
+ elementum migrate backend <orgRoot> --auto-approve
466
+ elementum --profile=<profile> plan <orgRoot>
467
+ ```
375
468
 
376
- The generated `providers.tf` pins a **local** OpenTofu backend at
377
- `<orgRoot>/terraform.tfstate` and is regenerated on every `build`, so a remote
378
- backend cannot be substituted in this release. The committed `terraform.tfstate`
379
- is the source of truth; coordinate concurrent changes through your normal git
380
- workflow (single writer, review on change) rather than distributed state
381
- locking. Remote backends and state locking are candidates for a later release.
469
+ For a remote-to-remote change, edit `backend.tf` and run the same migration.
470
+ Use `--reconfigure` only to bind an already-populated destination without
471
+ copying the currently bound state. It is rejected while local committed state
472
+ still exists.
473
+
474
+ Recovery snapshots and exact rollback commands are printed on failure and kept
475
+ under `.tf/migration-backups/backend/`. The command updates `.gitignore` but
476
+ does not rewrite Git history or mutate the index. After a successful
477
+ local-to-remote migration, commit the root-state deletion with `backend.tf` and
478
+ `.gitignore`; review the diff before pushing:
479
+
480
+ ```sh
481
+ git add backend.tf .gitignore
482
+ git add -u terraform.tfstate
483
+ git commit
484
+ ```
382
485
 
383
486
  If state is lost, do not apply the built configuration: OpenTofu would see the
384
- live objects as new. Restore the state file from version control or re-adopt
385
- each stream with:
487
+ live objects as new. Restore/push the recovery snapshot or re-adopt each stream
488
+ with:
386
489
 
387
490
  ```sh
388
491
  elementum --profile=<profile> pull org --data-only
@@ -391,7 +494,7 @@ elementum --profile=<profile> pull element <namespace>
391
494
  ```
392
495
 
393
496
  After an update reports an old provider identity, inspect and explicitly
394
- migrate the committed state:
497
+ migrate the configured state:
395
498
 
396
499
  ```sh
397
500
  elementum migrate provider-source <orgRoot> --check
@@ -399,9 +502,38 @@ elementum migrate provider-source <orgRoot> --auto-approve
399
502
  elementum --profile=<profile> plan <orgRoot>
400
503
  ```
401
504
 
402
- The migration creates an ignored recovery snapshot, runs OpenTofu
403
- `state replace-provider`, refreshes generated provider configuration, and never
404
- applies infrastructure.
505
+ The migration reads the configured local or remote state, creates an ignored
506
+ recovery snapshot, runs backend-bound OpenTofu `state replace-provider`,
507
+ refreshes generated provider configuration, and never applies infrastructure.
508
+
509
+ ### CI/CD
510
+
511
+ Use a serialized protected deployment job and let the backend lock arbitrate
512
+ all writers. Supply Elementum auth through the bridge's CI profile setup and
513
+ backend auth through workload identity/environment variables. A current
514
+ GitHub Actions job (the public signed toolchain is macOS-only today) looks like:
515
+
516
+ ```yaml
517
+ jobs:
518
+ apply:
519
+ runs-on: macos-14
520
+ concurrency:
521
+ group: elementum-prod
522
+ cancel-in-progress: false
523
+ permissions:
524
+ contents: read
525
+ id-token: write
526
+ steps:
527
+ - uses: actions/checkout@v4
528
+ - run: npm ci
529
+ - run: elementum build ./us/acme
530
+ - run: elementum --profile=ci plan ./us/acme -lock-timeout=5m
531
+ - run: elementum --profile=ci apply ./us/acme -auto-approve -lock-timeout=5m
532
+ ```
533
+
534
+ The command sequence and environment contract are identical on a noninteractive
535
+ Linux runner when your organization supplies the Linux toolchain artifact;
536
+ the public installer does not yet distribute Linux binaries.
405
537
 
406
538
  ## Create and update semantics
407
539
 
@@ -156,6 +156,22 @@ function withOwnKeyAsHandle(bag, injectParent) {
156
156
  }
157
157
  return out;
158
158
  }
159
+ /**
160
+ * Same as {@link withOwnKeyAsHandle} for a catalog root's `fields` bag, but
161
+ * also stamps `parentKind`/`parentName` (see `FieldRef`'s doc comment) — the
162
+ * two extra facts a cross-app field ref needs to resolve its owner's
163
+ * `data.elementum_app`/`data.elementum_element` lookup that `parent` (a bare
164
+ * refName) alone can't carry.
165
+ */
166
+ function stampFieldRefs(bag, identity, parentKind) {
167
+ if (bag === undefined)
168
+ return undefined;
169
+ const out = {};
170
+ for (const [refName, ref] of Object.entries(bag)) {
171
+ out[refName] = { ...ref, refName, parent: identity.refName, parentKind, parentName: identity.name };
172
+ }
173
+ return out;
174
+ }
159
175
  function stampTableRefs(bag) {
160
176
  if (bag === undefined)
161
177
  return undefined;
@@ -191,7 +207,7 @@ export function appCatalog(identity, bags) {
191
207
  refName: identity.refName,
192
208
  name: identity.name,
193
209
  ...bags,
194
- fields: withOwnKeyAsHandle(bags.fields, identity.refName) ?? {},
210
+ fields: stampFieldRefs(bags.fields, identity, "app") ?? {},
195
211
  searchTables: withOwnKeyAsHandle(bags.searchTables, identity.refName) ?? {},
196
212
  fileReaders: withOwnKeyAsHandle(bags.fileReaders, identity.refName) ?? {},
197
213
  automations: withOwnKeyAsHandle(bags.automations, identity.refName) ?? {},
@@ -206,7 +222,7 @@ export function elementCatalog(identity, bags) {
206
222
  refName: identity.refName,
207
223
  name: identity.name,
208
224
  ...bags,
209
- fields: withOwnKeyAsHandle(bags.fields, identity.refName) ?? {},
225
+ fields: stampFieldRefs(bags.fields, identity, "element") ?? {},
210
226
  searchTables: withOwnKeyAsHandle(bags.searchTables, identity.refName) ?? {},
211
227
  fileReaders: withOwnKeyAsHandle(bags.fileReaders, identity.refName) ?? {},
212
228
  automations: withOwnKeyAsHandle(bags.automations, identity.refName) ?? {},
@@ -441,9 +441,21 @@ export async function writeAppCatalog(appDir, appRefName, appName, appFile, impo
441
441
  */
442
442
  export async function regenerateAppCatalogsUnder(pathOrPaths, tenant) {
443
443
  const paths = typeof pathOrPaths === "string" ? [pathOrPaths] : pathOrPaths;
444
- const jiti = authoringJiti();
445
444
  const out = [];
446
445
  for (const file of await listEntityFilesFromPaths(paths, tenant)) {
446
+ // A root app/element file may itself `import catalog from "@catalog"`
447
+ // (e.g. a relation field referencing another workspace entity by
448
+ // token) — without this alias that import fails to resolve and the
449
+ // file is silently skipped below, exactly as if it were broken. Root
450
+ // stream-root files are always `<orgRoot>/apps|elements/<ref>/<ref>.ts`
451
+ // (two directories below the org root), so this derivation is only
452
+ // guaranteed correct for THOSE files — but that's exactly the shape
453
+ // this function's own output depends on; a wrong guess for a deeper
454
+ // own-file child (agents/, skills/, …) is harmless, since such a
455
+ // file's `ref.__kind` is never "app"/"element" and its result is
456
+ // discarded below regardless of whether it loaded at all.
457
+ const orgRoot = dirname(dirname(dirname(file)));
458
+ const jiti = authoringJiti(join(orgRoot, "generated", CATALOG_FILENAME));
447
459
  let mod;
448
460
  try {
449
461
  mod = (await jiti.import(file));
@@ -153,21 +153,50 @@ function renderAiProvidersBag(extract) {
153
153
  lines.push(" },");
154
154
  return lines;
155
155
  }
156
- /** Render generated/catalog.ts as a pure barrel over org.ts + disk-scanned catalogs. */
156
+ /**
157
+ * Render generated/catalog.ts as a pure barrel over org.ts + disk-scanned
158
+ * catalogs — every app/element/table entry is a lazy `get` accessor (a
159
+ * `require(...)` inside the getter body, type-asserted via `typeof
160
+ * import(...)` so `Ref`/autocomplete stay fully typed) rather than a
161
+ * static top-level import.
162
+ *
163
+ * This is NOT cosmetic: a relation field authored on a root app/element's
164
+ * own file can reference ANOTHER sibling via `catalog.<ref>` (see
165
+ * `entities/field/to-tf.ts`'s `workspaceAspects` sibling resolution) — the
166
+ * first real case of a root file importing `@catalog` itself. But the
167
+ * barrel unconditionally aggregates EVERY app/element, including the
168
+ * importing file's own entry, so a static import here would statically
169
+ * import that file's own per-entity catalog, which itself statically
170
+ * imports the file currently mid-evaluation — a genuine circular require
171
+ * (confirmed live: jiti/CJS semantics hand back a partial, `export
172
+ * default`-less module, and `.ref()` on it throws). A lazy getter defers
173
+ * that whole chain until the property is actually READ, by which point
174
+ * the importing file's own module evaluation has moved past the point of
175
+ * needing it (or, for a property this file never touches at all — e.g.
176
+ * `knowledge.ts` only ever reads `catalog.tickets`, never
177
+ * `catalog.knowledge` — the getter for its OWN entry is simply never
178
+ * invoked, so its self-referential chain never runs).
179
+ */
157
180
  function renderBarrel(appHandles, elementHandles, tableHandles) {
158
- const { elementKeys, tableImports, lines: importLines } = aspectImportLines(appHandles, elementHandles, tableHandles);
181
+ const elementKeys = computeElementKeys(appHandles, elementHandles);
182
+ const hasLazyEntries = appHandles.length > 0 || elementHandles.length > 0 || tableHandles.length > 0;
159
183
  const lines = [
160
184
  'import { org } from "../org.js";',
161
185
  'import { usersCatalog } from "@elementumai/edk/catalog";',
162
- ...importLines,
163
186
  "",
164
- "const catalog = {",
165
187
  ];
188
+ if (hasLazyEntries) {
189
+ // A minimal local ambient declaration rather than relying on `@types/node`
190
+ // (a consumer workspace may not have it) — the runtime `require` itself
191
+ // is provided by the loader (jiti), not by this declaration, which is
192
+ // erased entirely at compile time.
193
+ lines.push("declare const require: (id: string) => unknown;", "");
194
+ }
195
+ lines.push("const catalog = {");
166
196
  for (const h of appHandles)
167
- lines.push(` ${h},`);
197
+ lines.push(...lazyAspectGetter(h, `../apps/${h}/generated/catalog.js`, h));
168
198
  for (const h of elementHandles) {
169
- const key = elementKeys.get(h);
170
- lines.push(key === h ? ` ${h},` : ` ${key},`);
199
+ lines.push(...lazyAspectGetter(elementKeys.get(h), `../elements/${h}/generated/catalog.js`, h));
171
200
  }
172
201
  lines.push(" users: usersCatalog,");
173
202
  lines.push(" aiProviders: org.aiProviders,");
@@ -177,14 +206,25 @@ function renderBarrel(appHandles, elementHandles, tableHandles) {
177
206
  if (tableHandles.length > 0) {
178
207
  lines.push(" tables: {");
179
208
  for (const h of tableHandles)
180
- lines.push(` ${safeKey(h)}: ${tableImports.get(h)},`);
209
+ lines.push(...lazyAspectGetter(safeKey(h), `../tables/${h}/generated/catalog.js`, "default", " "));
181
210
  lines.push(" },");
182
211
  }
183
212
  lines.push("};", "", "export { org };", "export type Ref = typeof catalog;", "export default catalog;", "");
184
213
  return lines.join("\n");
185
214
  }
186
- /** Shared import-line rendering for the barrel (element collision + table alias rules). */
187
- function aspectImportLines(appHandles, elementHandles, tableHandles) {
215
+ /**
216
+ * One lazy `get <key>() { ... }` accessor: `require`s `importPath` only when
217
+ * read, type-asserted as `typeof import(importPath)` so the property's
218
+ * static type is exactly what a real `import` would have given it.
219
+ */
220
+ function lazyAspectGetter(key, importPath, exportName, indent = " ") {
221
+ const quoted = JSON.stringify(importPath);
222
+ return [
223
+ `${indent}get ${key}() { return (require(${quoted}) as typeof import(${quoted})).${exportName}; },`,
224
+ ];
225
+ }
226
+ /** An app and an element MAY share a handle — expose the element under a disambiguated key, warning once. */
227
+ function computeElementKeys(appHandles, elementHandles) {
188
228
  const used = new Set(appHandles);
189
229
  const elementKeys = new Map();
190
230
  for (const h of elementHandles) {
@@ -203,19 +243,7 @@ function aspectImportLines(appHandles, elementHandles, tableHandles) {
203
243
  used.add(candidate);
204
244
  console.error(`[elementum] warning: "${h}" names both an app and an element — the element is exposed as catalog.${candidate} (the app keeps catalog.${h}) to avoid a collision.`);
205
245
  }
206
- const tableImports = localTableNames(tableHandles, new Set([...appHandles, ...elementHandles.map((h) => `${h}$element`)]));
207
- const lines = [];
208
- for (const h of appHandles)
209
- lines.push(`import { ${h} } from "../apps/${h}/generated/catalog.js";`);
210
- for (const h of elementHandles) {
211
- const key = elementKeys.get(h);
212
- lines.push(key === h
213
- ? `import { ${h} } from "../elements/${h}/generated/catalog.js";`
214
- : `import { ${h} as ${key} } from "../elements/${h}/generated/catalog.js";`);
215
- }
216
- for (const h of tableHandles)
217
- lines.push(`import ${tableImports.get(h)} from "../tables/${h}/generated/catalog.js";`);
218
- return { elementKeys, tableImports, lines };
246
+ return elementKeys;
219
247
  }
220
248
  // ---------------------------------------------------------------------------
221
249
  // App / element / table handle discovery (dirs from orgRootOwnFileBags)
@@ -265,24 +293,3 @@ function safeKey(name) {
265
293
  ? name
266
294
  : q(name);
267
295
  }
268
- function localTableNames(handles, usedNames) {
269
- const out = new Map();
270
- for (const handle of handles) {
271
- const base = `${identifierBase(handle)}$table`;
272
- let candidate = base;
273
- let n = 2;
274
- while (usedNames.has(candidate) || RESERVED_IDENT.has(candidate)) {
275
- candidate = `${base}${n}`;
276
- n += 1;
277
- }
278
- usedNames.add(candidate);
279
- out.set(handle, candidate);
280
- }
281
- return out;
282
- }
283
- function identifierBase(handle) {
284
- const sanitized = handle.replace(/[^A-Za-z0-9_$]/g, "_");
285
- if (sanitized === "")
286
- return "_";
287
- return /^[A-Za-z_$]/.test(sanitized) ? sanitized : `_${sanitized}`;
288
- }
@@ -37,6 +37,10 @@ export function slimToken(token) {
37
37
  // type — canonical field metadata, not a barrel bag.
38
38
  if (token.__kind === "field" && typeof token.fieldType === "string")
39
39
  out.fieldType = token.fieldType;
40
+ if (token.__kind === "field" && (token.parentKind === "app" || token.parentKind === "element"))
41
+ out.parentKind = token.parentKind;
42
+ if (token.__kind === "field" && typeof token.parentName === "string")
43
+ out.parentName = token.parentName;
40
44
  // Same reasoning for a file reader: build needs to know which of the
41
45
  // excel/json/text/xml/ai resource types backs it to emit the right
42
46
  // `elementum_<type>_file_reader.<label>.id` reference - without this,
@@ -132,6 +132,21 @@ export interface FieldRef extends CatalogRef<"field"> {
132
132
  readonly fieldType: string;
133
133
  readonly tags?: readonly string[];
134
134
  readonly options?: readonly string[];
135
+ /**
136
+ * Whether `parent` names an app or an element — stamped alongside `parent`
137
+ * by `appCatalog`/`elementCatalog` (the field's own token doesn't otherwise
138
+ * say, unlike `AspectRef`'s own `__kind`). Lets a cross-app field ref pick
139
+ * `elementum_app` vs `elementum_element` for its owner lookup without
140
+ * depending on the owner also appearing elsewhere in the same payload.
141
+ */
142
+ readonly parentKind?: "app" | "element";
143
+ /**
144
+ * The parent's display NAME, stamped alongside `parent` for the same
145
+ * reason `parentKind` is — a foreign owner lookup (`data.elementum_app` /
146
+ * `data.elementum_element`) keys by display name, which `parent` (a
147
+ * refName) doesn't carry.
148
+ */
149
+ readonly parentName?: string;
135
150
  }
136
151
  /** Platform-owned user attributes accepted by user-search task filters. */
137
152
  export declare const USER_FIELD_KEYS: readonly ["firstName", "email", "jobTitle", "lastName"];
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import { type Ref, type ValueOrRef } from "../../entities/shared/ref.js";
11
11
  import type { WorkflowFieldType } from "../../entities/shared/types/field-types.js";
12
+ import type { AspectRef, FieldRef } from "../../catalog/types.js";
12
13
  import type { CloudLink } from "./cloud-link.js";
13
14
  import type { DisplayBlockBag } from "./display-block.js";
14
15
  import type { SerializedRenderTree } from "../../entities/flow/activities/render-catalog.js";
@@ -280,17 +281,22 @@ export interface AttachmentAppField<Scope extends FieldScope = "unscoped"> exten
280
281
  /**
281
282
  * RELATION fields (`elementum_relation_field`) - a dynamic dropdown whose
282
283
  * 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.
284
+ * static PICKLIST (no fixed `options` list at all). `relatedObject`/
285
+ * `relatedLabelField` accept a catalog token (`AspectRef`/`FieldRef`) or a
286
+ * raw platform id. A token naming a SIBLING app/element authored in the
287
+ * same build resolves to a direct resource reference - Terraform sequences
288
+ * its creation automatically, so it does NOT need to already exist on the
289
+ * platform. Only a token naming something genuinely outside this workspace
290
+ * resolves to a `data` lookup, which does require the target to already be
291
+ * live. Pulling a RELATION field back always yields raw ids regardless: a
292
+ * non-recursive `ei apps export` never discovers the related object's own
293
+ * identity (confirmed live), so there's nothing to resolve a token against
294
+ * on the extract side.
289
295
  */
290
296
  export interface RelationAppField<Scope extends FieldScope = "unscoped"> extends AspectFieldBase<Scope> {
291
297
  readonly type: "RELATION";
292
- readonly relatedAspectId: string;
293
- readonly relatedLabelFieldId: string;
298
+ readonly relatedObject: AspectRef | string;
299
+ readonly relatedLabelField: FieldRef | string;
294
300
  /** Defaults to `true` on the platform. */
295
301
  readonly autoRelate?: boolean;
296
302
  }
@@ -3,6 +3,7 @@
3
3
  * Entity-agnostic by definition — nothing in here may name a resource type.
4
4
  * (The extraction-side twin is src/engine/pull/context.ts.)
5
5
  */
6
+ import type { ChildResourceScope, TfValue } from "../tf/index.js";
6
7
  /**
7
8
  * Org-catalog lookups: recorded tfLabels for the data references entities emit.
8
9
  *
@@ -55,7 +56,33 @@ export interface OrgRefLookup {
55
56
  * Same discipline as `foreignApp`, distinct resource type.
56
57
  */
57
58
  foreignElement(tfLabel: string, name: string): void;
59
+ /**
60
+ * Record a field-lookup data block for a field owned by a FOREIGN (or
61
+ * otherwise not-self-resource) aspect — e.g. a relation field's
62
+ * `related_label_field_id` pointing at a field on a different app/element.
63
+ * `type` is caller-supplied (like `rawLookup`) since the engine layer
64
+ * never names a resource type. Unlike the other `foreign*` methods this
65
+ * data source needs a SECOND attribute (`object_id`, the owning aspect's
66
+ * resolved id expression) — the caller supplies it already resolved,
67
+ * since it's usually the same value also used for the sibling
68
+ * `related_object_id` attribute.
69
+ */
70
+ foreignField(type: string, tfLabel: string, objectId: TfValue, name: string): void;
58
71
  }
72
+ /** A stream root discovered elsewhere in THIS workspace build — kind + tfLabel, keyed by {@link workspaceAspectKey}. */
73
+ export interface WorkspaceAspect {
74
+ readonly kind: ChildResourceScope;
75
+ readonly tfLabel: string;
76
+ }
77
+ /**
78
+ * Key for the `workspaceAspects` map: an app and an element MAY share a
79
+ * refName (the org catalog barrel disambiguates that case by renaming the
80
+ * EXPORTED key, e.g. `catalog.tickets2` — see `src/catalog/org.ts`'s
81
+ * `computeElementKeys` — but each token's own `refName` field is untouched,
82
+ * so `refName` alone is not a unique map key). Keying by kind+refName keeps
83
+ * an app "tickets" and an element "tickets" from colliding.
84
+ */
85
+ export declare function workspaceAspectKey(kind: ChildResourceScope, refName: string): string;
59
86
  export interface ToTfContext {
60
87
  /** The owning app's refName — its authoring directory / catalog key. */
61
88
  readonly appRefName: string;
@@ -64,4 +91,17 @@ export interface ToTfContext {
64
91
  readonly orgRefs: OrgRefLookup;
65
92
  /** Degradations land here — reported by the caller, never silent. */
66
93
  readonly diagnostics: string[];
94
+ /**
95
+ * Every app/element stream root discovered in THIS build, keyed by
96
+ * {@link workspaceAspectKey} — lets a cross-aspect reference (e.g. a
97
+ * relation field's `relatedObject`) tell a SIBLING being authored/created
98
+ * in this same build apart from a genuinely foreign aspect that must
99
+ * already exist on the platform. A sibling resolves to a direct resource
100
+ * reference (Terraform sequences creation automatically); only a true
101
+ * foreign reference needs a `data` lookup, which can only ever find
102
+ * something already live. Optional so callers that don't need this (most
103
+ * `ToTfContext` construction sites, including tests) aren't forced to
104
+ * supply it.
105
+ */
106
+ readonly workspaceAspects?: ReadonlyMap<string, WorkspaceAspect>;
67
107
  }
@@ -3,4 +3,14 @@
3
3
  * Entity-agnostic by definition — nothing in here may name a resource type.
4
4
  * (The extraction-side twin is src/engine/pull/context.ts.)
5
5
  */
6
- export {};
6
+ /**
7
+ * Key for the `workspaceAspects` map: an app and an element MAY share a
8
+ * refName (the org catalog barrel disambiguates that case by renaming the
9
+ * EXPORTED key, e.g. `catalog.tickets2` — see `src/catalog/org.ts`'s
10
+ * `computeElementKeys` — but each token's own `refName` field is untouched,
11
+ * so `refName` alone is not a unique map key). Keying by kind+refName keeps
12
+ * an app "tickets" and an element "tickets" from colliding.
13
+ */
14
+ export function workspaceAspectKey(kind, refName) {
15
+ return `${kind}:${refName}`;
16
+ }
@@ -7,6 +7,6 @@ export type { PathSeg, TfBlock, TfBlockKind, TfDocument, TfExpr, TfValue } from
7
7
  export { expr, isTfExpr } from "./model.js";
8
8
  export { decodeTemplateEscapes, encodeTemplateEscapes, quoteHclString } from "./escape.js";
9
9
  export { parseExpression, parseStringValue, TfExprError } from "./expr.js";
10
- export { assertNoUnsafeIntegers, parseHcl, TfParseError } from "./parse.js";
10
+ export { assertNoUnsafeIntegers, inspectBackendHcl, parseHcl, TfParseError, type BackendHclInspection, } from "./parse.js";
11
11
  export { renderBlock, renderDocument } from "./render.js";
12
- export { appResourceLabelPrefix, appScopedResourceLabel, bareChildResourceLabel, childPartFromScopedLabel, elementResourceLabelPrefix, elementScopedResourceLabel, isCanonicalTsLabel, isUuid, ownerChildBareLabel, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, snakeSlug, splitCamelCase, tfLabelToTsLabel, tsLabelToTfLabel, type ChildResourceScope, } from "./labels.js";
12
+ export { appResourceLabelPrefix, appScopedResourceLabel, bareChildResourceLabel, childPartFromScopedLabel, elementResourceLabelPrefix, elementScopedResourceLabel, isCanonicalTsLabel, isUuid, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, snakeSlug, splitCamelCase, tfLabelToTsLabel, tsLabelToTfLabel, type ChildResourceScope, } from "./labels.js";