@elementumai/edk 0.9.11 → 0.9.12

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 (89) hide show
  1. package/README.md +39 -5
  2. package/dist-sdk/src/catalog/factories.d.ts +35 -14
  3. package/dist-sdk/src/catalog/factories.js +64 -13
  4. package/dist-sdk/src/catalog/from-authoring.js +4 -4
  5. package/dist-sdk/src/catalog/index.d.ts +1 -1
  6. package/dist-sdk/src/catalog/org.js +3 -2
  7. package/dist-sdk/src/catalog/token.js +4 -0
  8. package/dist-sdk/src/catalog/types.d.ts +13 -3
  9. package/dist-sdk/src/core/triggers/on-demand.d.ts +4 -28
  10. package/dist-sdk/src/core/triggers/on-demand.js +2 -4
  11. package/dist-sdk/src/engine/entity.d.ts +2 -0
  12. package/dist-sdk/src/engine/logging.d.ts +90 -0
  13. package/dist-sdk/src/engine/logging.js +124 -0
  14. package/dist-sdk/src/engine/progress.d.ts +119 -0
  15. package/dist-sdk/src/engine/progress.js +647 -0
  16. package/dist-sdk/src/engine/pull/result-output.d.ts +24 -0
  17. package/dist-sdk/src/engine/pull/result-output.js +48 -0
  18. package/dist-sdk/src/entities/agent/tools.d.ts +2 -2
  19. package/dist-sdk/src/entities/app/build.d.ts +8 -1
  20. package/dist-sdk/src/entities/app/from-tf.js +4 -4
  21. package/dist-sdk/src/entities/app/to-tf.js +9 -13
  22. package/dist-sdk/src/entities/automation/build.d.ts +11 -16
  23. package/dist-sdk/src/entities/automation/build.js +38 -8
  24. package/dist-sdk/src/entities/automation/catalog-render.js +1 -1
  25. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +1 -2
  26. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +23 -5
  27. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +239 -34
  28. package/dist-sdk/src/entities/automation/from-tf.js +168 -23
  29. package/dist-sdk/src/entities/automation/index.d.ts +2 -2
  30. package/dist-sdk/src/entities/automation/module.js +2 -2
  31. package/dist-sdk/src/entities/automation/output-field-types.js +25 -13
  32. package/dist-sdk/src/entities/automation/script-code.d.ts +12 -4
  33. package/dist-sdk/src/entities/automation/script-code.js +659 -101
  34. package/dist-sdk/src/entities/automation/tasks.d.ts +60 -28
  35. package/dist-sdk/src/entities/automation/tasks.js +31 -15
  36. package/dist-sdk/src/entities/automation/to-tf.js +362 -58
  37. package/dist-sdk/src/entities/automation/triggers.d.ts +15 -9
  38. package/dist-sdk/src/entities/automation/triggers.js +4 -2
  39. package/dist-sdk/src/entities/chart/build.d.ts +15 -3
  40. package/dist-sdk/src/entities/chart/build.js +6 -1
  41. package/dist-sdk/src/entities/chart/from-tf.d.ts +8 -2
  42. package/dist-sdk/src/entities/chart/from-tf.js +71 -8
  43. package/dist-sdk/src/entities/chart/index.d.ts +1 -1
  44. package/dist-sdk/src/entities/chart/index.js +1 -1
  45. package/dist-sdk/src/entities/chart/printer.js +27 -7
  46. package/dist-sdk/src/entities/chart/to-tf.js +56 -2
  47. package/dist-sdk/src/entities/datamine/from-tf.js +11 -1
  48. package/dist-sdk/src/entities/element/build.d.ts +6 -5
  49. package/dist-sdk/src/entities/element/from-tf.js +3 -2
  50. package/dist-sdk/src/entities/element/module.js +1 -0
  51. package/dist-sdk/src/entities/element/to-tf.d.ts +3 -0
  52. package/dist-sdk/src/entities/element/to-tf.js +9 -1
  53. package/dist-sdk/src/entities/field/from-tf.d.ts +24 -0
  54. package/dist-sdk/src/entities/field/from-tf.js +73 -1
  55. package/dist-sdk/src/entities/field/metadata.d.ts +18 -0
  56. package/dist-sdk/src/entities/field/metadata.js +34 -0
  57. package/dist-sdk/src/entities/relationship/build.d.ts +17 -6
  58. package/dist-sdk/src/entities/relationship/column-contract.d.ts +24 -0
  59. package/dist-sdk/src/entities/relationship/column-contract.js +41 -0
  60. package/dist-sdk/src/entities/relationship/from-tf.js +19 -34
  61. package/dist-sdk/src/entities/relationship/to-tf.js +15 -2
  62. package/dist-sdk/src/entities/shared/context.d.ts +6 -3
  63. package/dist-sdk/src/entities/shared/context.js +19 -1
  64. package/dist-sdk/src/entities/shared/filters/index.d.ts +7 -0
  65. package/dist-sdk/src/entities/shared/filters/index.js +28 -0
  66. package/dist-sdk/src/entities/shared/filters/print.js +2 -0
  67. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +8 -1
  68. package/dist-sdk/src/entities/shared/filters/tf-codec.js +10 -6
  69. package/dist-sdk/src/entities/shared/filters/types.d.ts +1 -1
  70. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +5 -0
  71. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +36 -23
  72. package/dist-sdk/src/entities/skill/module.js +1 -0
  73. package/dist-sdk/src/entities/skill/to-tf.d.ts +1 -1
  74. package/dist-sdk/src/entities/skill/to-tf.js +17 -0
  75. package/dist-sdk/src/entities/skill/tools.d.ts +38 -12
  76. package/dist-sdk/src/entities/skill/tools.js +2 -1
  77. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +8 -12
  78. package/dist-sdk/src/entities/skill-tool/from-tf.js +28 -44
  79. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +4 -0
  80. package/dist-sdk/src/entities/skill-tool/to-tf.js +45 -7
  81. package/dist-sdk/src/entities/table/build.js +10 -2
  82. package/dist-sdk/src/entities/view/to-tf.js +5 -7
  83. package/dist-sdk/src/entities/widget/build.d.ts +26 -0
  84. package/dist-sdk/src/entities/widget/from-tf.js +30 -5
  85. package/dist-sdk/src/entities/widget/to-tf.js +111 -7
  86. package/dist-sdk/src/graph/types.d.ts +5 -0
  87. package/package.json +1 -1
  88. package/dist-sdk/src/core/types/platform.d.ts +0 -2
  89. package/dist-sdk/src/core/types/platform.js +0 -1
@@ -121,6 +121,95 @@ export function preserveAuthoredAutomationRevision(freshSource, existingSource)
121
121
  return freshSource;
122
122
  return freshSource.replace(REVISION_PROPERTY, (_line, prefix) => `${prefix}${JSON.stringify(authored)},`);
123
123
  }
124
+ /**
125
+ * Extract a string-literal (or `+`-concatenated literals) description from
126
+ * authored automation source. Pull reprints often omit description entirely
127
+ * because Go export cannot read it back from the platform today.
128
+ */
129
+ export function extractAuthoredAutomationDescription(source) {
130
+ const header = /(?:^|\n)[ \t]*description[ \t]*:/m.exec(source);
131
+ if (header === null || header.index === undefined)
132
+ return undefined;
133
+ let i = header.index + header[0].length;
134
+ const parts = [];
135
+ while (i < source.length) {
136
+ while (i < source.length && /\s/.test(source[i]))
137
+ i++;
138
+ const q = source[i];
139
+ if (q !== '"' && q !== "'" && q !== "`")
140
+ break;
141
+ i++;
142
+ let raw = "";
143
+ while (i < source.length) {
144
+ const ch = source[i];
145
+ if (ch === "\\") {
146
+ if (i + 1 >= source.length)
147
+ return undefined;
148
+ raw += ch + source[i + 1];
149
+ i += 2;
150
+ continue;
151
+ }
152
+ if (ch === q)
153
+ break;
154
+ raw += ch;
155
+ i++;
156
+ }
157
+ if (source[i] !== q)
158
+ return undefined;
159
+ i++;
160
+ try {
161
+ parts.push(q === '"' ? JSON.parse(`"${raw}"`) : q === "'" ? JSON.parse(`"${raw.replace(/\\'/g, "'").replace(/"/g, '\\"')}"`) : raw);
162
+ }
163
+ catch {
164
+ return undefined;
165
+ }
166
+ while (i < source.length && /\s/.test(source[i]))
167
+ i++;
168
+ if (source[i] === "+") {
169
+ i++;
170
+ continue;
171
+ }
172
+ break;
173
+ }
174
+ if (parts.length === 0)
175
+ return undefined;
176
+ const joined = parts.join("");
177
+ return joined === "" ? undefined : joined;
178
+ }
179
+ /**
180
+ * Keep a non-empty authored `description` across pull.
181
+ *
182
+ * Platform discovery historically omitted automation description (and the TF
183
+ * provider still does not round-trip it through GraphQL), so Go HCL export
184
+ * drops the attribute. Without this merge, pull → reprint → build clears
185
+ * description from config while state still has it, forcing an adopt update.
186
+ * Prefer a freshly pulled description when present; only reinstate the
187
+ * authored value when the fresh source omitted it.
188
+ */
189
+ export function preserveAuthoredAutomationDescription(freshSource, existingSource) {
190
+ const authored = extractAuthoredAutomationDescription(existingSource);
191
+ if (authored === undefined)
192
+ return freshSource;
193
+ if (extractAuthoredAutomationDescription(freshSource) !== undefined)
194
+ return freshSource;
195
+ const revisionLine = REVISION_PROPERTY.exec(freshSource);
196
+ if (revisionLine !== null && revisionLine.index !== undefined) {
197
+ const insertAt = revisionLine.index + revisionLine[0].length;
198
+ const indent = /^[ \t]*/.exec(revisionLine[0])?.[0] ?? " ";
199
+ return `${freshSource.slice(0, insertAt)}\n${indent}description: ${JSON.stringify(authored)},${freshSource.slice(insertAt)}`;
200
+ }
201
+ const nameLine = /^([ \t]*name[ \t]*:[ \t]*)(["'`])([^"'`\r\n]*)\2[ \t]*,?[ \t]*$/m.exec(freshSource);
202
+ if (nameLine !== null && nameLine.index !== undefined) {
203
+ const insertAt = nameLine.index + nameLine[0].length;
204
+ const indent = /^[ \t]*/.exec(nameLine[0])?.[0] ?? " ";
205
+ return `${freshSource.slice(0, insertAt)}\n${indent}description: ${JSON.stringify(authored)},${freshSource.slice(insertAt)}`;
206
+ }
207
+ return freshSource;
208
+ }
209
+ /** Pull merge: preserve authored revision + description across live reprint. */
210
+ export function preserveAuthoredAutomationPullMeta(freshSource, existingSource) {
211
+ return preserveAuthoredAutomationDescription(preserveAuthoredAutomationRevision(freshSource, existingSource), existingSource);
212
+ }
124
213
  function emptyImports() {
125
214
  return {
126
215
  filterOps: new Set(),
@@ -131,8 +220,39 @@ function emptyImports() {
131
220
  usesUnsafePlatformId: false,
132
221
  usesOrg: false,
133
222
  usesScriptInput: false,
223
+ usesRefType: false,
134
224
  };
135
225
  }
226
+ /** Reprint extract-time owner handles as the authored catalog key. */
227
+ function catalogOwnerHandle(state, appHandle) {
228
+ if (appHandle === state.ownerHandle || appHandle === state.appRefName)
229
+ return state.appRefName;
230
+ return appHandle;
231
+ }
232
+ /** Task kinds whose output is an unschematized JSON object (see #927) - a
233
+ * forEach collection sourced from one of these needs an explicit
234
+ * `as unknown as Ref<readonly Record<string, unknown>[]>` cast, since the
235
+ * SDK correctly can't infer an array shape from a `Ref<unknown>`. */
236
+ const GENERIC_OUTPUT_TASK_FACTORIES = new Set(["readFile", "aiTransform", "procedure"]);
237
+ function collectTaskFactories(tasks, into) {
238
+ for (const task of tasks) {
239
+ into.set(task.refKey, task.factory);
240
+ for (const child of task.children ?? []) {
241
+ collectTaskFactories(child.tasks, into);
242
+ }
243
+ }
244
+ }
245
+ function collectForkJoinBranchTaskRefKeys(tasks, into) {
246
+ for (const task of tasks) {
247
+ for (const child of task.children ?? []) {
248
+ if (task.factory === "forkJoin") {
249
+ for (const branchTask of child.tasks)
250
+ into.add(branchTask.refKey);
251
+ }
252
+ collectForkJoinBranchTaskRefKeys(child.tasks, into);
253
+ }
254
+ }
255
+ }
136
256
  const DEFAULT_CTX = { ctxName: "ctx" };
137
257
  /**
138
258
  * Register a v2 factory/trigger import and return the identifier call sites
@@ -180,10 +300,19 @@ function printAutomation(ast, opts) {
180
300
  // single call site.
181
301
  const refName = opts.refName ?? (camelCase(ast.name) || ast.name);
182
302
  const identifier = safeIdentifier(refName, "automation");
303
+ const appRefName = opts.appRefName ?? ast.ownerHandle;
304
+ const taskFactoriesByRefKey = new Map();
305
+ collectTaskFactories(ast.tasks, taskFactoriesByRefKey);
306
+ const forkJoinBranchTaskRefKeys = new Set();
307
+ collectForkJoinBranchTaskRefKeys(ast.tasks, forkJoinBranchTaskRefKeys);
183
308
  const state = {
184
309
  imports: emptyImports(),
310
+ forkJoinBranchTaskRefKeys,
311
+ ownerHandle: ast.ownerHandle,
312
+ appRefName,
185
313
  localIdentifier: refName,
186
314
  unresolvedReferences: opts.unresolvedReferences ?? [],
315
+ taskFactoriesByRefKey,
187
316
  ...(opts.foreignAppRefNames !== undefined && { foreignAppRefNames: opts.foreignAppRefNames }),
188
317
  ...(opts.foreignElementRefNames !== undefined && { foreignElementRefNames: opts.foreignElementRefNames }),
189
318
  };
@@ -207,9 +336,9 @@ function printAutomation(ast, opts) {
207
336
  if (ast.triggersOtherAutomations !== undefined) {
208
337
  body.push(` triggersOtherAutomations: ${ast.triggersOtherAutomations},`);
209
338
  }
210
- body.push(` app: catalog.${opts.appRefName ?? ast.ownerHandle},`);
339
+ body.push(` app: catalog.${appRefName},`);
211
340
  if (ast.serviceAccountName !== undefined) {
212
- body.push(` serviceAccount: serviceAccountRef({ app: catalog.${opts.appRefName ?? ast.ownerHandle}, name: ${quote(ast.serviceAccountName)} }),`);
341
+ body.push(` serviceAccount: serviceAccountRef({ app: catalog.${appRefName}, name: ${quote(ast.serviceAccountName)} }),`);
213
342
  }
214
343
  body.push(` status: automationStatus.${automationStatusKey(ast.status)},`);
215
344
  body.push(` actions: actions()`);
@@ -231,7 +360,21 @@ function printOutputs(ast, state) {
231
360
  return "";
232
361
  const pad = " ";
233
362
  const inner = " ";
234
- const entryLines = ast.outputs.map((o) => `${inner}${safeKey(o.name)}: ${printArgValue("", o.value, state, 4, DEFAULT_CTX)},`);
363
+ // Two workflow_publish outputs can share the same display name on the
364
+ // platform (#931, live-confirmed) - printing the literal duplicate key
365
+ // is a hard syntax error (TS1117), not just a type error. Disambiguate
366
+ // the SAME way withUniqueKeys (pull/util.ts) already does for other
367
+ // name collisions in this codebase, minus the camelCase step: these
368
+ // keys are printed as string literals, not identifiers.
369
+ const usedOutputNames = new Set();
370
+ const entryLines = ast.outputs.map((o) => {
371
+ let name = o.name;
372
+ let suffix = 2;
373
+ while (usedOutputNames.has(name))
374
+ name = `${o.name} ${suffix++}`;
375
+ usedOutputNames.add(name);
376
+ return `${inner}${safeKey(name)}: ${printArgValue("", o.value, state, 4, DEFAULT_CTX)},`;
377
+ });
235
378
  const objBody = `({\n${entryLines.join("\n")}\n${pad}})`;
236
379
  // Prefix the ctx param with `_` when the body never references it (all
237
380
  // literals), so the emitted lambda satisfies `noUnusedParameters`.
@@ -279,7 +422,7 @@ function renderHeader(ast, imports, _opts) {
279
422
  return alias ? `${name} as ${alias}` : name;
280
423
  });
281
424
  lines.push(`import { ${sortedSpecifiers.join(", ")} } from "${sdkPackageSpecifier("automations")}";`);
282
- if (imports.usesTemplate || imports.usesUnresolvedField || imports.usesUnsafePlatformId) {
425
+ if (imports.usesTemplate || imports.usesUnresolvedField || imports.usesUnsafePlatformId || imports.usesRefType) {
283
426
  const coreNamed = [];
284
427
  if (imports.usesTemplate)
285
428
  coreNamed.push("template");
@@ -287,6 +430,8 @@ function renderHeader(ast, imports, _opts) {
287
430
  coreNamed.push("unresolvedField");
288
431
  if (imports.usesUnsafePlatformId)
289
432
  coreNamed.push("unsafePlatformId");
433
+ if (imports.usesRefType)
434
+ coreNamed.push("type Ref");
290
435
  lines.push(`import { ${coreNamed.join(", ")} } from "${sdkPackageSpecifier("core")}";`);
291
436
  }
292
437
  lines.push(imports.usesOrg ? `import catalog, { org } from "@catalog";` : `import catalog from "@catalog";`);
@@ -299,12 +444,8 @@ function printTrigger(trigger, state) {
299
444
  switch (trigger.kind) {
300
445
  case "onDemand": {
301
446
  const onDemand = trackFactory("onDemand", state);
302
- const optionParts = [];
303
- if (trigger.showTriggeredBy === true)
304
- optionParts.push("showTriggeredBy: true");
305
- const optionsSuffix = optionParts.length > 0 ? `, { ${optionParts.join(", ")} }` : "";
306
447
  if (trigger.inputs.length === 0)
307
- return `${onDemand}({}${optionsSuffix})`;
448
+ return `${onDemand}({})`;
308
449
  const lines = trigger.inputs.map((i) => {
309
450
  const parts = [`type: ${quote(i.type)}`];
310
451
  if (i.type === "record" && i.app !== undefined) {
@@ -321,7 +462,7 @@ function printTrigger(trigger, state) {
321
462
  parts.push(`description: ${quote(i.description)}`);
322
463
  return ` ${safeKey(i.name)}: { ${parts.join(", ")} },`;
323
464
  });
324
- return `${onDemand}({\n${lines.join("\n")}\n }${optionsSuffix})`;
465
+ return `${onDemand}({\n${lines.join("\n")}\n })`;
325
466
  }
326
467
  case "recordCreate":
327
468
  case "recordUpdate": {
@@ -345,7 +486,14 @@ function printTrigger(trigger, state) {
345
486
  }
346
487
  case "conversationEnd": {
347
488
  const conversationEnd = trackFactory("conversationEnd", state);
348
- return `${conversationEnd}({ app: ${printRef(trigger.app, state, DEFAULT_CTX)}, conversationType: ${quote(trigger.conversationType)} })`;
489
+ const parts = [
490
+ `app: ${printRef(trigger.app, state, DEFAULT_CTX)}`,
491
+ `conversationType: ${quote(trigger.conversationType)}`,
492
+ ];
493
+ if (trigger.filter) {
494
+ parts.push(`filter: ${printFilter(trigger.filter, state)}`);
495
+ }
496
+ return `${conversationEnd}({ ${parts.join(", ")} })`;
349
497
  }
350
498
  case "webhook": {
351
499
  const webHook = trackFactory("webHook", state);
@@ -360,7 +508,7 @@ function printTrigger(trigger, state) {
360
508
  case "temporal": {
361
509
  const temporal = trackFactory("temporal", state);
362
510
  const fieldExpr = trigger.app.kind === "app"
363
- ? printFieldRef(trigger.app.appHandle, trigger.fieldKey)
511
+ ? printFieldRef(trigger.app.appHandle, trigger.fieldKey, state)
364
512
  : `${quote(trigger.fieldKey.replace(/^__unresolved_/, ""))} as any /* TODO: unresolved field */`;
365
513
  const parts = [
366
514
  `app: ${printRef(trigger.app, state, DEFAULT_CTX)}`,
@@ -463,9 +611,9 @@ function recordTriggerBody(trigger, state) {
463
611
  parts.push(`thinkUi: ${trigger.thinkUi}`);
464
612
  return `{ ${parts.join(", ")} }`;
465
613
  }
466
- function printFieldRef(appHandle, fieldKey) {
614
+ function printFieldRef(appHandle, fieldKey, state) {
467
615
  if (!fieldKey.startsWith("__unresolved_")) {
468
- return `catalog.${appHandle}.fields${safeMember(fieldKey)}`;
616
+ return `catalog.${catalogOwnerHandle(state, appHandle)}.fields${safeMember(fieldKey)}`;
469
617
  }
470
618
  const uuid = fieldKey.replace(/^__unresolved_/, "");
471
619
  return `${quote(uuid)} as any /* TODO: unresolved field */`;
@@ -654,8 +802,28 @@ function formatNestedActions(tasks, state, indent, refCtx) {
654
802
  function formatForEach(task, state, indent, refCtx) {
655
803
  const pad = " ".repeat(indent);
656
804
  const configIndent = " ".repeat(indent + 1);
657
- const collectionCode = printArgValue("collection", task.args.collection, state, indent + 1, refCtx);
805
+ const rawCollectionCode = printArgValue("collection", task.args.collection, state, indent + 1, refCtx);
806
+ // A collection sourced from a generic-JSON-object task (readFile/
807
+ // aiTransform/procedure - #927) types as Ref<Record<string, unknown>> at
808
+ // the bare reference and Ref<unknown> at any named property off it - the
809
+ // SDK correctly won't infer an array shape from either without help. Cast
810
+ // through unknown to Ref<readonly Record<string, unknown>[]>, the same
811
+ // double-cast escape hatch already used elsewhere in pulled source for an
812
+ // unresolvable-but-known-to-be-an-array reference; the object-shaped item
813
+ // still supports arbitrary named property access afterward via DeepRef's
814
+ // index-signature drilling (see #934).
815
+ const collectionRef = task.args.collection;
816
+ const needsArrayCast = typeof collectionRef === "object" &&
817
+ collectionRef !== null &&
818
+ collectionRef.kind === "taskRef" &&
819
+ GENERIC_OUTPUT_TASK_FACTORIES.has(state.taskFactoriesByRefKey.get(collectionRef.task) ?? "");
820
+ const collectionCode = needsArrayCast
821
+ ? `${rawCollectionCode} as unknown as Ref<readonly Record<string, unknown>[]>`
822
+ : rawCollectionCode;
823
+ if (needsArrayCast)
824
+ state.imports.usesRefType = true;
658
825
  const childCtx = {
826
+ ...refCtx,
659
827
  ctxName: "ctx",
660
828
  selfTaskRefKeys: [...(refCtx.selfTaskRefKeys ?? []), task.refKey],
661
829
  };
@@ -695,7 +863,7 @@ function formatSwitch(task, state, indent, refCtx) {
695
863
  const isDefault = (child) => child.isDefault === true || child.label === null;
696
864
  const cases = children.filter((ch) => !isDefault(ch));
697
865
  const defaults = children.filter(isDefault);
698
- const branchCtx = { ctxName: "ctx", selfTaskRefKeys: refCtx.selfTaskRefKeys };
866
+ const branchCtx = { ...refCtx, ctxName: "ctx" };
699
867
  const caseLines = cases.map((ch) => formatSwitchCase(ch, state, indent + 2, branchCtx));
700
868
  const configParts = [];
701
869
  configParts.push(`${configIndent}cases: [\n${caseLines.join(",\n")}\n${configIndent}]`);
@@ -733,7 +901,12 @@ function formatForkJoinBranch(ch, state, indent, refCtx) {
733
901
  const parts = [];
734
902
  if (ch.label !== undefined)
735
903
  parts.push(`${innerPad}label: ${ch.label === null ? "null" : quote(ch.label)}`);
736
- parts.push(`${innerPad}actions: ${formatNestedActions(ch.tasks, state, indent + 2, refCtx)}`);
904
+ // Only THIS branch's own tasks are in scope for a same-branch reference
905
+ // (#932) - a reference to another branch's task, or the forkJoin's own
906
+ // branches referenced from outside entirely, still needs the escape.
907
+ const branchTaskRefKeys = new Set(ch.tasks.map((t) => t.refKey));
908
+ const branchRefCtx = { ...refCtx, currentForkJoinBranchTaskRefKeys: branchTaskRefKeys };
909
+ parts.push(`${innerPad}actions: ${formatNestedActions(ch.tasks, state, indent + 2, branchRefCtx)}`);
737
910
  return `${pad}{\n${parts.join(",\n")},\n${pad}}`;
738
911
  }
739
912
  // ---------------------------------------------------------------------------
@@ -804,6 +977,10 @@ function printFieldAssignments(values, appHandle, state, indent, refCtx) {
804
977
  const lines = entries.map(([fieldKey, rawValue]) => {
805
978
  let fieldExpr;
806
979
  if (appHandle && !fieldKey.startsWith(UNRESOLVED_FIELD_MARKER)) {
980
+ // `taskPrimaryAppHandle` already remapped the owner and resolved a
981
+ // pulled foreign element. Remapping again via `catalogOwnerHandle`
982
+ // would bind an unpulled same-handle foreign element's fields onto
983
+ // the owner app (see #978 / #986).
807
984
  fieldExpr = `catalog.${appHandle}.fields${safeMember(fieldKey)}`;
808
985
  }
809
986
  else {
@@ -833,11 +1010,13 @@ function taskPrimaryAppHandle(args, state) {
833
1010
  for (const k of ["app", "relatedApp"]) {
834
1011
  const v = args[k];
835
1012
  if (isRefExpr(v) && v.kind === "app") {
836
- if (v.entityType === "app" && v.name !== undefined)
837
- return state.foreignAppRefNames?.get(v.name) ?? v.appHandle;
838
- if (v.entityType === "element" && v.name !== undefined)
1013
+ if (v.entityType === "app" && v.name !== undefined) {
1014
+ return state.foreignAppRefNames?.get(v.name) ?? catalogOwnerHandle(state, v.appHandle);
1015
+ }
1016
+ if (v.entityType === "element" && v.name !== undefined) {
839
1017
  return state.foreignElementRefNames?.get(v.name) ?? v.appHandle;
840
- return v.appHandle;
1018
+ }
1019
+ return catalogOwnerHandle(state, v.appHandle);
841
1020
  }
842
1021
  }
843
1022
  return undefined;
@@ -896,6 +1075,18 @@ function printRef(ref, state, refCtx) {
896
1075
  const path = ref.path.map(safeMember).join("");
897
1076
  return `(${ctxName}.actions as any /* TODO: "${ref.task}" isn't in scope inside its own forEach body yet */)${safeMember(ref.task)}${path}`;
898
1077
  }
1078
+ // A forkJoin branch's own task is only reachable from within that SAME
1079
+ // branch (#932, live-confirmed) - the forkJoin's own name and its
1080
+ // aggregated output are what's actually in scope afterward or from a
1081
+ // sibling branch, never a branch task's name directly. Same escape
1082
+ // shape as the enclosing-forEach case above, minus the runtime-safety
1083
+ // nuance (ctx.actions really doesn't have this key at all here, not
1084
+ // just "not yet").
1085
+ if (state.forkJoinBranchTaskRefKeys.has(ref.task) &&
1086
+ !refCtx.currentForkJoinBranchTaskRefKeys?.has(ref.task)) {
1087
+ const path = ref.path.map(safeMember).join("");
1088
+ return `(${ctxName}.actions as any /* TODO: "${ref.task}" is inside a forkJoin branch, not reachable from here */)${safeMember(ref.task)}${path}`;
1089
+ }
899
1090
  // `result.<prop>` segments are output-schema property names — typed,
900
1091
  // legitimate — so print them with plain dot/bracket access; only record
901
1092
  // paths keep the unresolved-key as-any heuristic.
@@ -929,10 +1120,14 @@ function printRef(ref, state, refCtx) {
929
1120
  }
930
1121
  case "forEachRef":
931
1122
  return printPathAccess(`${ctxName}.actions${safeMember(ref.forEachTask)}`, ref.path);
932
- case "forEachItemRef": {
933
- const path = ref.path.map(safeMember).join("");
934
- return `${ctxName}.item${path}`;
935
- }
1123
+ case "forEachItemRef":
1124
+ // An unresolved field on a loop item prints as a bare raw-UUID bracket
1125
+ // index without this - printPathAccess is the same "as any" escape
1126
+ // already used for taskRef/forEachRef's own unresolved-path segments
1127
+ // (#933, live-confirmed: ctx.item["<uuid>"] next to the identical
1128
+ // ctx.actions["Existing Actions"] as any /* TODO */ pattern in the
1129
+ // same pulled file).
1130
+ return printPathAccess(`${ctxName}.item`, ref.path);
936
1131
  case "variableParamRef":
937
1132
  return `${ctxName}.variables${safeMember(ref.varTask)}${safeMember(ref.name)}`;
938
1133
  case "template": {
@@ -953,7 +1148,7 @@ function printRef(ref, state, refCtx) {
953
1148
  }
954
1149
  case "field": {
955
1150
  if (ref.foreign === undefined)
956
- return `catalog.${ref.appHandle}.fields${safeMember(ref.fieldKey)}`;
1151
+ return `catalog.${catalogOwnerHandle(state, ref.appHandle)}.fields${safeMember(ref.fieldKey)}`;
957
1152
  // Same treatment as the "app" case just below: a foreign field already
958
1153
  // pulled into this workspace (board issue #40, app-only) resolves to a
959
1154
  // typed token; otherwise a literal stub (field type is unconfirmed —
@@ -971,7 +1166,7 @@ function printRef(ref, state, refCtx) {
971
1166
  return `catalog.users.fields${safeMember(ref.fieldKey)}`;
972
1167
  case "app": {
973
1168
  if (ref.entityType === undefined || ref.name === undefined) {
974
- return `catalog.${ref.appHandle}`;
1169
+ return `catalog.${catalogOwnerHandle(state, ref.appHandle)}`;
975
1170
  }
976
1171
  const foreignRefName = ref.entityType === "element"
977
1172
  ? state.foreignElementRefNames?.get(ref.name)
@@ -981,11 +1176,11 @@ function printRef(ref, state, refCtx) {
981
1176
  return `{ __kind: ${quote(ref.entityType)}, refName: ${quote(ref.appHandle)}, name: ${quote(ref.name)} }`;
982
1177
  }
983
1178
  case "agent":
984
- return `catalog.${ref.appHandle}.agents${safeMember(ref.agentKey)}`;
1179
+ return `catalog.${catalogOwnerHandle(state, ref.appHandle)}.agents${safeMember(ref.agentKey)}`;
985
1180
  case "automation":
986
- return `catalog.${ref.appHandle}.automations${safeMember(ref.automationKey)}`;
1181
+ return `catalog.${catalogOwnerHandle(state, ref.appHandle)}.automations${safeMember(ref.automationKey)}`;
987
1182
  case "phoneService":
988
- return `catalog.${ref.appHandle}.phoneServices${safeMember(ref.phoneServiceKey)}`;
1183
+ return `catalog.${catalogOwnerHandle(state, ref.appHandle)}.phoneServices${safeMember(ref.phoneServiceKey)}`;
989
1184
  case "datamine":
990
1185
  state.imports.usesOrg = true;
991
1186
  return `org.tables.${ref.tableHandle}.datamines${safeMember(ref.datamineKey)}`;
@@ -998,18 +1193,28 @@ function printRef(ref, state, refCtx) {
998
1193
  case "tableColumn":
999
1194
  return `catalog.tables${safeMember(ref.tableHandle)}.columns${safeMember(ref.columnKey)}`;
1000
1195
  case "searchTable":
1196
+ // Search tables are element- or table-owned, never app-owned. Remapping
1197
+ // the automation owner's export handle to its authored app refName
1198
+ // would bind an unpulled same-handle foreign element's table onto the
1199
+ // owner app (see #978).
1001
1200
  return `catalog.${ref.appHandle}.searchTables${safeMember(ref.tableKey)}`;
1002
1201
  case "user":
1003
1202
  return `${trackFactory("userRef", state)}(${quote(ref.email)})`;
1004
1203
  case "documentModel":
1005
- return `catalog.${ref.appHandle}.fileReaders${safeMember(ref.documentModelKey)}`;
1204
+ return `catalog.${catalogOwnerHandle(state, ref.appHandle)}.fileReaders${safeMember(ref.documentModelKey)}`;
1006
1205
  case "documentModelField":
1007
- return `catalog.${ref.appHandle}.fileReaders${safeMember(ref.documentModelKey)}.fields${safeMember(ref.fieldKey)}`;
1008
- case "approvalChain":
1206
+ return `catalog.${catalogOwnerHandle(state, ref.appHandle)}.fileReaders${safeMember(ref.documentModelKey)}.fields${safeMember(ref.fieldKey)}`;
1207
+ case "approvalChain": {
1208
+ // Prefer catalog when we have a key; unresolvedId is last resort only.
1209
+ const key = ref.approvalChainKey?.trim() ?? "";
1210
+ if (key !== "" && key !== ref.unresolvedId) {
1211
+ return `catalog.${catalogOwnerHandle(state, ref.appHandle)}.approvalChains${safeMember(key)}`;
1212
+ }
1009
1213
  if (ref.unresolvedId !== undefined) {
1010
1214
  return `{ __kind: "approvalChain", refName: ${quote(ref.approvalChainKey)}, name: ${quote(ref.approvalChainKey)}, parent: ${quote(ref.appHandle)}, unresolvedId: ${quote(ref.unresolvedId)} }`;
1011
1215
  }
1012
- return `catalog.${ref.appHandle}.approvalChains${safeMember(ref.approvalChainKey)}`;
1216
+ return `catalog.${catalogOwnerHandle(state, ref.appHandle)}.approvalChains${safeMember(ref.approvalChainKey)}`;
1217
+ }
1013
1218
  case "connector": {
1014
1219
  // Connectors are org-level (no appHandle), nested under their owning
1015
1220
  // provider — mirrors printConnectorToken in