@elementumai/edk 0.9.14 → 0.9.16

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 (124) hide show
  1. package/dist-sdk/pull/util.d.ts +0 -15
  2. package/dist-sdk/pull/util.js +44 -5
  3. package/dist-sdk/src/catalog/factories.d.ts +4 -2
  4. package/dist-sdk/src/catalog/factories.js +4 -0
  5. package/dist-sdk/src/catalog/from-authoring.js +5 -1
  6. package/dist-sdk/src/catalog/index.d.ts +2 -2
  7. package/dist-sdk/src/catalog/index.js +1 -1
  8. package/dist-sdk/src/catalog/token.js +2 -2
  9. package/dist-sdk/src/catalog/types.d.ts +7 -2
  10. package/dist-sdk/src/core/types/app.d.ts +4 -4
  11. package/dist-sdk/src/engine/build/context.d.ts +5 -4
  12. package/dist-sdk/src/engine/build/source-context.d.ts +2 -0
  13. package/dist-sdk/src/engine/build/source-context.js +16 -0
  14. package/dist-sdk/src/engine/progress.d.ts +19 -1
  15. package/dist-sdk/src/engine/progress.js +33 -5
  16. package/dist-sdk/src/engine/pull/context.d.ts +9 -1
  17. package/dist-sdk/src/engine/pull/ref-only.d.ts +6 -2
  18. package/dist-sdk/src/engine/pull/ref-only.js +14 -3
  19. package/dist-sdk/src/engine/workspace/loader.js +23 -2
  20. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +1 -1
  21. package/dist-sdk/src/entities/access-policy/from-tf.js +47 -12
  22. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +5 -3
  23. package/dist-sdk/src/entities/access-policy/to-tf.js +23 -1
  24. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +6 -0
  25. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +50 -4
  26. package/dist-sdk/src/entities/agent/from-tf.d.ts +1 -0
  27. package/dist-sdk/src/entities/agent/from-tf.js +18 -3
  28. package/dist-sdk/src/entities/agent/module.js +1 -0
  29. package/dist-sdk/src/entities/agent/to-tf.js +15 -0
  30. package/dist-sdk/src/entities/agent/tools.d.ts +98 -5
  31. package/dist-sdk/src/entities/agent/tools.js +12 -3
  32. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +15 -0
  33. package/dist-sdk/src/entities/agent-tool/from-tf.js +47 -4
  34. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +9 -0
  35. package/dist-sdk/src/entities/agent-tool/to-tf.js +82 -25
  36. package/dist-sdk/src/entities/app/build.d.ts +2 -2
  37. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +4 -4
  38. package/dist-sdk/src/entities/app/module.js +8 -0
  39. package/dist-sdk/src/entities/app/to-tf.js +1 -0
  40. package/dist-sdk/src/entities/approval-chain/build.d.ts +8 -1
  41. package/dist-sdk/src/entities/approval-chain/build.js +3 -0
  42. package/dist-sdk/src/entities/approval-chain/from-tf.d.ts +2 -1
  43. package/dist-sdk/src/entities/approval-chain/from-tf.js +20 -7
  44. package/dist-sdk/src/entities/approval-chain/printer.js +13 -2
  45. package/dist-sdk/src/entities/approval-chain/to-tf.js +3 -0
  46. package/dist-sdk/src/entities/automation/build.d.ts +19 -12
  47. package/dist-sdk/src/entities/automation/build.js +36 -13
  48. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +4 -0
  49. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +19 -0
  50. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +222 -65
  51. package/dist-sdk/src/entities/automation/from-tf.d.ts +86 -6
  52. package/dist-sdk/src/entities/automation/from-tf.js +360 -63
  53. package/dist-sdk/src/entities/automation/index.d.ts +3 -2
  54. package/dist-sdk/src/entities/automation/index.js +3 -2
  55. package/dist-sdk/src/entities/automation/module.js +21 -16
  56. package/dist-sdk/src/entities/automation/output-field-types.d.ts +5 -0
  57. package/dist-sdk/src/entities/automation/output-field-types.js +12 -0
  58. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +20 -0
  59. package/dist-sdk/src/entities/automation/output-key-wire-name.js +22 -0
  60. package/dist-sdk/src/entities/automation/script-code.d.ts +32 -0
  61. package/dist-sdk/src/entities/automation/script-code.js +72 -5
  62. package/dist-sdk/src/entities/automation/tasks.d.ts +60 -24
  63. package/dist-sdk/src/entities/automation/tasks.js +33 -14
  64. package/dist-sdk/src/entities/automation/to-tf.d.ts +0 -2
  65. package/dist-sdk/src/entities/automation/to-tf.js +123 -46
  66. package/dist-sdk/src/entities/automation/triggers.d.ts +5 -2
  67. package/dist-sdk/src/entities/automation/types.d.ts +2 -0
  68. package/dist-sdk/src/entities/automation/types.js +5 -0
  69. package/dist-sdk/src/entities/automation/workflow-output.d.ts +35 -0
  70. package/dist-sdk/src/entities/automation/workflow-output.js +53 -0
  71. package/dist-sdk/src/entities/chart/build.d.ts +3 -3
  72. package/dist-sdk/src/entities/chart/from-tf.d.ts +2 -2
  73. package/dist-sdk/src/entities/chart/from-tf.js +20 -13
  74. package/dist-sdk/src/entities/chart/to-tf.js +7 -5
  75. package/dist-sdk/src/entities/dashboard/from-tf.js +1 -1
  76. package/dist-sdk/src/entities/dashboard/to-tf.js +1 -0
  77. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +3 -2
  78. package/dist-sdk/src/entities/element/build.d.ts +11 -8
  79. package/dist-sdk/src/entities/element/build.js +14 -5
  80. package/dist-sdk/src/entities/element/locals.d.ts +2 -2
  81. package/dist-sdk/src/entities/element/locals.js +6 -2
  82. package/dist-sdk/src/entities/element/system-fields.d.ts +4 -0
  83. package/dist-sdk/src/entities/element/system-fields.js +12 -0
  84. package/dist-sdk/src/entities/element/to-tf.js +1 -0
  85. package/dist-sdk/src/entities/field/build.d.ts +2 -2
  86. package/dist-sdk/src/entities/field/from-tf.js +82 -4
  87. package/dist-sdk/src/entities/field/to-tf.d.ts +1 -1
  88. package/dist-sdk/src/entities/field/to-tf.js +11 -4
  89. package/dist-sdk/src/entities/record-create-form/from-tf.js +3 -2
  90. package/dist-sdk/src/entities/relationship/from-tf.js +8 -5
  91. package/dist-sdk/src/entities/relationship/to-tf.js +13 -3
  92. package/dist-sdk/src/entities/search-table/from-tf.js +6 -6
  93. package/dist-sdk/src/entities/search-table/module.js +2 -2
  94. package/dist-sdk/src/entities/search-table/types.d.ts +1 -0
  95. package/dist-sdk/src/entities/search-table/types.js +1 -0
  96. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +3 -3
  97. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +10 -6
  98. package/dist-sdk/src/entities/shared/filters/ast.d.ts +4 -2
  99. package/dist-sdk/src/entities/shared/filters/index.d.ts +12 -2
  100. package/dist-sdk/src/entities/shared/filters/index.js +17 -1
  101. package/dist-sdk/src/entities/shared/filters/print.js +25 -11
  102. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +1 -1
  103. package/dist-sdk/src/entities/shared/filters/tf-codec.js +39 -7
  104. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +1 -1
  105. package/dist-sdk/src/entities/shared/tool-field-ref.js +6 -2
  106. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +6 -0
  107. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +47 -18
  108. package/dist-sdk/src/entities/skill/module.js +10 -0
  109. package/dist-sdk/src/entities/skill/to-tf.js +19 -0
  110. package/dist-sdk/src/entities/skill/tools.d.ts +29 -7
  111. package/dist-sdk/src/entities/skill/tools.js +6 -2
  112. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +18 -0
  113. package/dist-sdk/src/entities/skill-tool/from-tf.js +77 -4
  114. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +8 -0
  115. package/dist-sdk/src/entities/skill-tool/to-tf.js +90 -46
  116. package/dist-sdk/src/entities/task/module.js +1 -1
  117. package/dist-sdk/src/entities/view/from-tf.js +30 -9
  118. package/dist-sdk/src/entities/view/to-tf.js +18 -10
  119. package/dist-sdk/src/entities/widget/from-tf.js +3 -3
  120. package/dist-sdk/src/entities/widget/to-tf.js +1 -0
  121. package/dist-sdk/src/graph/index.d.ts +15 -0
  122. package/dist-sdk/src/graph/index.js +19 -0
  123. package/dist-sdk/src/graph/types.d.ts +37 -1
  124. package/package.json +2 -1
@@ -37,16 +37,15 @@ import { isRefExpr } from "../../shared/filters/ast.js";
37
37
  import { printFilter as printCanonicalFilter } from "../../shared/filters/print.js";
38
38
  import { UNRESOLVED_FIELD_MARKER } from "../../shared/ref.js";
39
39
  import { UNRESOLVED_REFERENCE_MARKER } from "../filter.js";
40
- import { INJECTED_TS_IGNORE } from "../script-code.js";
40
+ import { INJECTED_TS_IGNORE, scriptFileText } from "../script-code.js";
41
41
  import { unresolvedReferenceComment } from "../../../engine/pull/ref-only.js";
42
42
  // ---------------------------------------------------------------------------
43
- // Factory name mapping — v1 AST `factory` → v2 factory function name.
43
+ // Factory name mapping — decoded task `factory` → v2 factory function name.
44
44
  //
45
- // The v1 task-deserializer emits one of a closed set of factory strings (see
46
- // `BUILDERS` in `src/automations/deserializer/task-deserializer.ts`). Each
47
- // maps to the matching v2 factory in `tasks.ts` / `operators.ts`. The handful
48
- // of name differences (groupSearch → userGroupSearch, switchTask → switch,
49
- // recordFieldLocking → recordFieldLocking) are spelled out here.
45
+ // `from-tf.ts` (`TASK_FACTORIES`, resource-type → factory) emits one of a
46
+ // closed set of factory strings. Each maps to the matching v2 factory in
47
+ // `tasks.ts` / `operators.ts` — usually an identity mapping, with the
48
+ // occasional rename (e.g. `documentModel → readFile`) captured here.
50
49
  // ---------------------------------------------------------------------------
51
50
  const TASK_FACTORY_V2 = {
52
51
  recordSearch: "recordSearch",
@@ -62,7 +61,6 @@ const TASK_FACTORY_V2 = {
62
61
  aiTransform: "aiTransform",
63
62
  documentModel: "readFile",
64
63
  notification: "notification",
65
- filterTask: "filterAction",
66
64
  runAutomation: "runAutomation",
67
65
  findRelatedRecords: "findRelatedRecords",
68
66
  recordFieldLocking: "recordFieldLocking",
@@ -223,6 +221,8 @@ function emptyImports() {
223
221
  usesRefType: false,
224
222
  };
225
223
  }
224
+ /** Folder (inside the automations folder) that holds printed script files. */
225
+ export const SCRIPT_FILES_DIR = "scripts";
226
226
  /** Reprint extract-time owner handles as the authored catalog key. */
227
227
  function catalogOwnerHandle(state, appHandle) {
228
228
  if (appHandle === state.ownerHandle || appHandle === state.appRefName)
@@ -294,7 +294,7 @@ function automationStatusKey(status) {
294
294
  case "ACTIVE": return "active";
295
295
  }
296
296
  }
297
- function printAutomation(ast, opts) {
297
+ function printAutomation(ast, opts, externalScripts) {
298
298
  // Computed up front (independent of trigger/task printing) so `trackFactory`
299
299
  // can alias any factory whose v2 name collides with it before emitting a
300
300
  // single call site.
@@ -305,9 +305,13 @@ function printAutomation(ast, opts) {
305
305
  collectTaskFactories(ast.tasks, taskFactoriesByRefKey);
306
306
  const forkJoinBranchTaskRefKeys = new Set();
307
307
  collectForkJoinBranchTaskRefKeys(ast.tasks, forkJoinBranchTaskRefKeys);
308
+ const topLevelTaskRefKeys = new Set(ast.tasks.map((t) => t.refKey));
308
309
  const state = {
309
310
  imports: emptyImports(),
311
+ ...(externalScripts && { scriptFiles: new Map() }),
312
+ scriptFileStem: refName,
310
313
  forkJoinBranchTaskRefKeys,
314
+ topLevelTaskRefKeys,
311
315
  ownerHandle: ast.ownerHandle,
312
316
  appRefName,
313
317
  localIdentifier: refName,
@@ -315,6 +319,7 @@ function printAutomation(ast, opts) {
315
319
  taskFactoriesByRefKey,
316
320
  ...(opts.foreignAppRefNames !== undefined && { foreignAppRefNames: opts.foreignAppRefNames }),
317
321
  ...(opts.foreignElementRefNames !== undefined && { foreignElementRefNames: opts.foreignElementRefNames }),
322
+ ...(opts.foreignTaskRefNames !== undefined && { foreignTaskRefNames: opts.foreignTaskRefNames }),
318
323
  };
319
324
  const triggerCode = printTrigger(ast.trigger, state);
320
325
  // The trigger/action/output chain lives on the `actions` field, nested one
@@ -347,7 +352,13 @@ function printAutomation(ast, opts) {
347
352
  body.push("");
348
353
  body.push(`export default ${identifier};`);
349
354
  const header = renderHeader(ast, state.imports, opts);
350
- return `${header}\n\n${body.join("\n")}\n`;
355
+ return {
356
+ source: `${header}\n\n${body.join("\n")}\n`,
357
+ scriptFiles: [...(state.scriptFiles ?? [])].map(([file, text]) => ({
358
+ path: `${SCRIPT_FILES_DIR}/${file}`,
359
+ content: scriptFileText(text),
360
+ })),
361
+ };
351
362
  }
352
363
  /**
353
364
  * Emit the optional `.outputs((ctx) => ({ ... }))` chain link from the AST's
@@ -373,7 +384,13 @@ function printOutputs(ast, state) {
373
384
  while (usedOutputNames.has(name))
374
385
  name = `${o.name} ${suffix++}`;
375
386
  usedOutputNames.add(name);
376
- return `${inner}${safeKey(name)}: ${printArgValue("", o.value, state, 4, DEFAULT_CTX)},`;
387
+ const value = printArgValue("", o.value, state, 4, DEFAULT_CTX);
388
+ if (o.explicitType !== undefined) {
389
+ const factory = trackFactory("workflowOutput", state);
390
+ const types = trackFactory("workflowOutputType", state);
391
+ return `${inner}${safeKey(name)}: ${factory}(${value}, { type: ${types}.${o.explicitType}, multiple: ${o.explicitMultiple === true} }),`;
392
+ }
393
+ return `${inner}${safeKey(name)}: ${value},`;
377
394
  });
378
395
  const objBody = `({\n${entryLines.join("\n")}\n${pad}})`;
379
396
  // Prefix the ctx param with `_` when the body never references it (all
@@ -385,7 +402,17 @@ function printOutputs(ast, state) {
385
402
  * printer's `printAutomationFinalized` convention.
386
403
  */
387
404
  export function printAutomationV2(ast, opts = {}) {
388
- return printAutomation(ast, opts);
405
+ return printAutomation(ast, opts, false).source;
406
+ }
407
+ /**
408
+ * Like {@link printAutomationV2}, but `executeScript` bodies print as
409
+ * `scriptFile("./scripts/<automation>.<task>.js")` references and the bodies
410
+ * come back as files to write beside the automation (relative to the
411
+ * automations folder). The bodies never enter the TypeScript source, so they
412
+ * are never type-checked, annotated or type-stripped.
413
+ */
414
+ export function printAutomationV2WithScriptFiles(ast, opts = {}) {
415
+ return printAutomation(ast, opts, true);
389
416
  }
390
417
  // ---------------------------------------------------------------------------
391
418
  // Header / imports
@@ -588,9 +615,10 @@ function printTrigger(trigger, state) {
588
615
  }
589
616
  case "surveyResponseCreate": {
590
617
  const surveyResponseCreate = trackFactory("surveyResponseCreate", state);
618
+ state.imports.usesUnsafePlatformId = true;
591
619
  const parts = [
592
620
  `app: ${printRef(trigger.app, state, DEFAULT_CTX)}`,
593
- `survey: ${quote(trigger.survey)}`,
621
+ `survey: unsafePlatformId(${quote(trigger.survey)})${unresolvedReferenceComment(trigger.survey, state.unresolvedReferences)}`,
594
622
  ];
595
623
  return `${surveyResponseCreate}({\n ${parts.join(",\n ")}\n })`;
596
624
  }
@@ -653,6 +681,16 @@ function printTask(task, state, indent, refCtx = DEFAULT_CTX) {
653
681
  const options = /\bctx\b/.test(args) ? `(ctx) => (${args})` : args;
654
682
  return `${pad}.${method}(${quote(task.refKey)}, ${options}${topLevelTaskTrailingArgs(task)})`;
655
683
  }
684
+ /** `<automationRef>.<taskKey>.js`, made unique within the automation. */
685
+ function allocateScriptFile(taskKey, body, state) {
686
+ const files = state.scriptFiles;
687
+ const stem = `${state.scriptFileStem}.${taskKey.replace(/[^A-Za-z0-9_$-]+/g, "_") || "script"}`;
688
+ let file = `${stem}.js`;
689
+ for (let n = 2; files.has(file); n++)
690
+ file = `${stem}_${n}.js`;
691
+ files.set(file, body);
692
+ return file;
693
+ }
656
694
  /** Fluent `.executeScript(name, { inputs, code, outputs? })` in any action chain. */
657
695
  function formatExecuteScript(task, state, indent, refCtx = DEFAULT_CTX) {
658
696
  const pad = " ".repeat(indent);
@@ -678,8 +716,14 @@ function formatExecuteScript(task, state, indent, refCtx = DEFAULT_CTX) {
678
716
  }
679
717
  const code = task.args.code ?? task.args.script;
680
718
  if (typeof code === "string") {
681
- lines.push(`${configPad}// @ts-ignore`);
682
- lines.push(`${configPad}code: ${printScriptCodeFn(code, indent + 1, state)},`);
719
+ if (state.scriptFiles !== undefined) {
720
+ const file = allocateScriptFile(task.refKey, code, state);
721
+ lines.push(`${configPad}code: ${trackFactory("scriptFile", state)}(${quote(`./${SCRIPT_FILES_DIR}/${file}`)}),`);
722
+ }
723
+ else {
724
+ lines.push(`${configPad}// @ts-ignore`);
725
+ lines.push(`${configPad}code: ${printScriptCodeFn(code, indent + 1, state)},`);
726
+ }
683
727
  }
684
728
  if (task.args.outputs !== undefined && task.args.outputs !== null && typeof task.args.outputs === "object") {
685
729
  lines.push(`${configPad}outputs: ${printObjectLiteral(task.args.outputs, state, indent + 1, DEFAULT_CTX)},`);
@@ -732,7 +776,20 @@ function annotateScriptLines(body, indent) {
732
776
  const result = [];
733
777
  for (const line of lines) {
734
778
  if (line.trim().length === 0) {
735
- result.push("");
779
+ // Preserve the original line's content exactly (e.g. accidental
780
+ // trailing whitespace an editor left in the deployed script) instead
781
+ // of normalizing to a bare empty string - live-confirmed on
782
+ // conciergeforfield (sanofi/us): a blank line with trailing spaces
783
+ // was silently stripped on every pull, planning a spurious `code`
784
+ // update on every rebuild even though nothing about the script
785
+ // actually changed. The pad prefix matters too, not just the content:
786
+ // build's own re-extraction (script-code.ts's dedent()) slices every
787
+ // line - including this one - by the surrounding code's common
788
+ // indent. A bare `line` with no pad is shorter than that indent and
789
+ // gets sliced away to "" right back out again; prefixing it the same
790
+ // way a real content line is prefixed below keeps enough width to
791
+ // survive that slice and land back on the original content.
792
+ result.push(`${innerPad}${line}`);
736
793
  continue;
737
794
  }
738
795
  const wasInBacktick = inBacktick;
@@ -882,7 +939,7 @@ function formatSwitchCase(ch, state, indent, refCtx) {
882
939
  // The switch case `condition:` is a `filter.*` expression evaluated in the
883
940
  // switch's outer scope; v2 takes it as a bare value (no `(app) =>` lambda).
884
941
  if (ch.filter)
885
- parts.push(`${innerPad}condition: ${printFilter(ch.filter, state)}`);
942
+ parts.push(`${innerPad}condition: ${printFilter(ch.filter, state, refCtx)}`);
886
943
  parts.push(`${innerPad}actions: ${formatNestedActions(ch.tasks, state, indent + 2, refCtx)}`);
887
944
  return `${pad}{\n${parts.join(",\n")},\n${pad}}`;
888
945
  }
@@ -890,7 +947,7 @@ function formatForkJoin(task, state, indent, refCtx) {
890
947
  const pad = " ".repeat(indent);
891
948
  const configIndent = " ".repeat(indent + 1);
892
949
  const branches = task.children ?? [];
893
- const branchCtx = { ctxName: "ctx", selfTaskRefKeys: refCtx.selfTaskRefKeys };
950
+ const branchCtx = { ...refCtx, ctxName: "ctx" };
894
951
  const branchLines = branches.map((ch) => formatForkJoinBranch(ch, state, indent + 2, branchCtx));
895
952
  const branchesBlock = branchLines.length > 0 ? `[\n${branchLines.join(",\n")}\n${configIndent}]` : `[]`;
896
953
  return `${pad}.forkJoin(${quote(task.refKey)}, {\n${configIndent}branches: ${branchesBlock},\n${pad}}${topLevelTaskTrailingArgs(task)})`;
@@ -901,10 +958,13 @@ function formatForkJoinBranch(ch, state, indent, refCtx) {
901
958
  const parts = [];
902
959
  if (ch.label !== undefined)
903
960
  parts.push(`${innerPad}label: ${ch.label === null ? "null" : quote(ch.label)}`);
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
961
+ // Only THIS branch's own tasks (and any enclosing branch's tasks) are in scope for a
962
+ // same-branch reference (#932) - a reference to another branch's task, or the forkJoin's own
906
963
  // branches referenced from outside entirely, still needs the escape.
907
- const branchTaskRefKeys = new Set(ch.tasks.map((t) => t.refKey));
964
+ const branchTaskRefKeys = new Set([
965
+ ...(refCtx.currentForkJoinBranchTaskRefKeys ?? []),
966
+ ...ch.tasks.map((t) => t.refKey),
967
+ ]);
908
968
  const branchRefCtx = { ...refCtx, currentForkJoinBranchTaskRefKeys: branchTaskRefKeys };
909
969
  parts.push(`${innerPad}actions: ${formatNestedActions(ch.tasks, state, indent + 2, branchRefCtx)}`);
910
970
  return `${pad}{\n${parts.join(",\n")},\n${pad}}`;
@@ -922,13 +982,13 @@ function formatForkJoinBranch(ch, state, indent, refCtx) {
922
982
  */
923
983
  function printTaskArgs(task, state, indent, refCtx) {
924
984
  const renames = ARG_RENAMES[task.factory] ?? {};
925
- const appHandle = taskPrimaryAppHandle(task.args, state);
985
+ const target = taskPrimaryTarget(task.args, state);
926
986
  const pad = " ".repeat(indent);
927
987
  const lines = [];
928
988
  for (const [k, v] of Object.entries(task.args)) {
929
989
  // createRecord / updateField field-value maps → v2 `fields` array.
930
990
  if (k === "values" && (task.factory === "createRecord" || task.factory === "updateField")) {
931
- lines.push(`${pad}fields: ${printFieldAssignments(v, appHandle, state, indent + 1, refCtx)},`);
991
+ lines.push(`${pad}fields: ${printFieldAssignments(v, target, state, indent + 1, refCtx)},`);
932
992
  continue;
933
993
  }
934
994
  // relateRecords.sources is always a DSL array — even when HCL used a scalar.
@@ -962,11 +1022,12 @@ function printTaskArgs(task, state, indent, refCtx) {
962
1022
  /**
963
1023
  * Render the v2 `fields: [{ field, value }]` array from the v1 AST's
964
1024
  * `values: { <fieldKey>: <RefExpr> }` map. Field keys become catalog handle
965
- * tokens off the task's app (`<appHandle>.fields.<key>`); an unresolved field
1025
+ * tokens off the task's app (`<appHandle>.fields.<key>`); task targets
1026
+ * (NO_CATALOG) become inline field stubs; an unresolved field
966
1027
  * key (`UNRESOLVED_FIELD_MARKER + <uuid>`) is preserved through the explicit
967
1028
  * `unsafePlatformId` escape hatch so a non-recursive pull remains buildable.
968
1029
  */
969
- function printFieldAssignments(values, appHandle, state, indent, refCtx) {
1030
+ function printFieldAssignments(values, target, state, indent, refCtx) {
970
1031
  if (!values || typeof values !== "object" || Array.isArray(values))
971
1032
  return "[]";
972
1033
  const entries = Object.entries(values);
@@ -975,13 +1036,27 @@ function printFieldAssignments(values, appHandle, state, indent, refCtx) {
975
1036
  const pad = " ".repeat(indent);
976
1037
  const inner = " ".repeat(indent + 1);
977
1038
  const lines = entries.map(([fieldKey, rawValue]) => {
1039
+ const assignmentRecord = rawValue && typeof rawValue === "object" && !Array.isArray(rawValue)
1040
+ ? rawValue
1041
+ : undefined;
1042
+ const assignment = assignmentRecord?.__fieldAssignment === true && "value" in assignmentRecord
1043
+ ? assignmentRecord
1044
+ : undefined;
978
1045
  let fieldExpr;
979
- if (appHandle && !fieldKey.startsWith(UNRESOLVED_FIELD_MARKER)) {
980
- // `taskPrimaryAppHandle` already remapped the owner and resolved a
1046
+ if (target?.kind === "task" || assignment?.foreignEntityType === "task") {
1047
+ const parentRef = target?.refName ?? assignment?.foreignOwnerName ?? "task";
1048
+ const parentName = target?.name ?? assignment?.foreignOwnerName ?? parentRef;
1049
+ const fieldName = assignment?.foreignFieldName ?? fieldKey;
1050
+ const fieldType = assignment?.foreignFieldType ?? "TEXT";
1051
+ fieldExpr = (`{ __kind: "field", refName: ${quote(fieldKey)}, name: ${quote(fieldName)}, fieldType: ${quote(fieldType)}, ` +
1052
+ `parent: ${quote(parentRef)}, parentKind: "task", parentName: ${quote(parentName)} }`);
1053
+ }
1054
+ else if (target && !fieldKey.startsWith(UNRESOLVED_FIELD_MARKER)) {
1055
+ // `taskPrimaryTarget` already remapped the owner and resolved a
981
1056
  // pulled foreign element. Remapping again via `catalogOwnerHandle`
982
1057
  // would bind an unpulled same-handle foreign element's fields onto
983
1058
  // the owner app (see #978 / #986).
984
- fieldExpr = `catalog.${appHandle}.fields${safeMember(fieldKey)}`;
1059
+ fieldExpr = `catalog.${target.refName}.fields${safeMember(fieldKey)}`;
985
1060
  }
986
1061
  else {
987
1062
  const uuid = fieldKey.startsWith(UNRESOLVED_FIELD_MARKER)
@@ -990,12 +1065,6 @@ function printFieldAssignments(values, appHandle, state, indent, refCtx) {
990
1065
  state.imports.usesUnsafePlatformId = true;
991
1066
  fieldExpr = `unsafePlatformId(${quote(uuid)})`;
992
1067
  }
993
- const assignmentRecord = rawValue && typeof rawValue === "object" && !Array.isArray(rawValue)
994
- ? rawValue
995
- : undefined;
996
- const assignment = assignmentRecord?.__fieldAssignment === true && "value" in assignmentRecord
997
- ? assignmentRecord
998
- : undefined;
999
1068
  const valueExpr = printArgValue("", assignment?.value ?? rawValue, state, indent + 2, refCtx);
1000
1069
  const updateMode = assignment?.updateMode === "add" ? `, updateMode: "add"` : "";
1001
1070
  return `${inner}{ field: ${fieldExpr}, value: ${valueExpr}${updateMode} },`;
@@ -1003,20 +1072,24 @@ function printFieldAssignments(values, appHandle, state, indent, refCtx) {
1003
1072
  return `[\n${lines.join("\n")}\n${pad}]`;
1004
1073
  }
1005
1074
  /**
1006
- * The task's primary app handle, used to resolve `values:` field keys to
1007
- * `<appHandle>.fields.<key>` tokens. Reads the `app` / `relatedApp` arg.
1075
+ * The task's primary target, used to resolve `values:` field keys to
1076
+ * `<target>.fields.<key>` tokens (or inline field stubs for tasks).
1077
+ * Reads the `app` / `relatedApp` arg.
1008
1078
  */
1009
- function taskPrimaryAppHandle(args, state) {
1079
+ function taskPrimaryTarget(args, state) {
1010
1080
  for (const k of ["app", "relatedApp"]) {
1011
1081
  const v = args[k];
1012
1082
  if (isRefExpr(v) && v.kind === "app") {
1013
- if (v.entityType === "app" && v.name !== undefined) {
1014
- return state.foreignAppRefNames?.get(v.name) ?? catalogOwnerHandle(state, v.appHandle);
1083
+ if (v.entityType === "task") {
1084
+ const refName = (v.name !== undefined ? state.foreignTaskRefNames?.get(v.name) : undefined) ?? v.appHandle;
1085
+ return { kind: "task", refName, name: v.name ?? refName };
1015
1086
  }
1016
- if (v.entityType === "element" && v.name !== undefined) {
1017
- return state.foreignElementRefNames?.get(v.name) ?? v.appHandle;
1087
+ if (v.entityType === "element") {
1088
+ const refName = (v.name !== undefined ? state.foreignElementRefNames?.get(v.name) : undefined) ?? v.appHandle;
1089
+ return { kind: "element", refName, name: v.name };
1018
1090
  }
1019
- return catalogOwnerHandle(state, v.appHandle);
1091
+ const refName = (v.name !== undefined ? state.foreignAppRefNames?.get(v.name) : undefined) ?? catalogOwnerHandle(state, v.appHandle);
1092
+ return { kind: "app", refName, name: v.name };
1020
1093
  }
1021
1094
  }
1022
1095
  return undefined;
@@ -1032,7 +1105,25 @@ function printArgValue(name, value, state, indent, refCtx) {
1032
1105
  if (isRefExpr(value))
1033
1106
  return printRef(value, state, refCtx);
1034
1107
  if (isFilter(value))
1035
- return printFilter(value, state);
1108
+ return printFilter(value, state, refCtx);
1109
+ if (isExecuteScriptListInputAst(value)) {
1110
+ const withFieldMappings = trackFactory("withFieldMappings", state);
1111
+ const printedValue = printArgValue(name, value.value, state, indent, refCtx);
1112
+ const printedFields = value.fields
1113
+ .map((f) => {
1114
+ // A raw-id fallback, not the generic printRef "unresolved" arm
1115
+ // (which casts `as any` — wrong here, `field` expects a real
1116
+ // FieldRef) - same escape hatch printFieldAssignments already uses
1117
+ // for the identical "field export couldn't reconstruct" case.
1118
+ if (f.field.kind === "unresolved") {
1119
+ state.imports.usesUnsafePlatformId = true;
1120
+ return `{ alias: ${quote(f.alias)}, field: unsafePlatformId(${quote(f.field.uuid)}) }`;
1121
+ }
1122
+ return `{ alias: ${quote(f.alias)}, field: ${printRef(f.field, state, refCtx)} }`;
1123
+ })
1124
+ .join(", ");
1125
+ return `${withFieldMappings}(${printedValue}, [${printedFields}])`;
1126
+ }
1036
1127
  // executeScript body (AST key `code`, legacy `script`) — always function form.
1037
1128
  if ((name === "code" || name === "script") && typeof value === "string") {
1038
1129
  return printScriptCodeFn(value, indent, state);
@@ -1051,6 +1142,9 @@ function printArgValue(name, value, state, indent, refCtx) {
1051
1142
  function isPulledRawCalculation(value) {
1052
1143
  return !!value && typeof value === "object" && value.kind === "calculationRaw";
1053
1144
  }
1145
+ function isExecuteScriptListInputAst(value) {
1146
+ return !!value && typeof value === "object" && value.__edkExecuteScriptListInput === true;
1147
+ }
1054
1148
  // ---------------------------------------------------------------------------
1055
1149
  // RefExpr printer — emits v2 ctx refs + catalog handle-tokens
1056
1150
  // ---------------------------------------------------------------------------
@@ -1083,7 +1177,8 @@ function printRef(ref, state, refCtx) {
1083
1177
  // nuance (ctx.actions really doesn't have this key at all here, not
1084
1178
  // just "not yet").
1085
1179
  if (state.forkJoinBranchTaskRefKeys.has(ref.task) &&
1086
- !refCtx.currentForkJoinBranchTaskRefKeys?.has(ref.task)) {
1180
+ !refCtx.currentForkJoinBranchTaskRefKeys?.has(ref.task) &&
1181
+ !state.topLevelTaskRefKeys.has(ref.task)) {
1087
1182
  const path = ref.path.map(safeMember).join("");
1088
1183
  return `(${ctxName}.actions as any /* TODO: "${ref.task}" is inside a forkJoin branch, not reachable from here */)${safeMember(ref.task)}${path}`;
1089
1184
  }
@@ -1091,6 +1186,11 @@ function printRef(ref, state, refCtx) {
1091
1186
  // legitimate — so print them with plain dot/bracket access; only record
1092
1187
  // paths keep the unresolved-key as-any heuristic.
1093
1188
  if (ref.path[0] === "result") {
1189
+ if (ref.undeclaredScriptOutput === true) {
1190
+ const [result, ...rest] = ref.path;
1191
+ return `(${ctxName}.actions${safeMember(ref.task)}${safeMember(result)} as any /* TODO: live automation references an execute-script output absent from its output schema */)` +
1192
+ rest.map(safeMember).join("");
1193
+ }
1094
1194
  return `${ctxName}.actions${safeMember(ref.task)}` + ref.path.map(safeMember).join("");
1095
1195
  }
1096
1196
  return printPathAccess(`${ctxName}.actions${safeMember(ref.task)}`, ref.path);
@@ -1120,14 +1220,47 @@ function printRef(ref, state, refCtx) {
1120
1220
  }
1121
1221
  case "forEachRef":
1122
1222
  return printPathAccess(`${ctxName}.actions${safeMember(ref.forEachTask)}`, ref.path);
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);
1223
+ case "forEachItemRef": {
1224
+ // `ctx.item` only ever means "the NEAREST enclosing forEach's current
1225
+ // item" - at build time it binds to whichever loop's replaceForEach
1226
+ // pass runs closest to this position, not to any outer ancestor.
1227
+ // refCtx.selfTaskRefKeys (accumulated by formatForEach on the way
1228
+ // down) holds the full ancestor chain, so checking membership alone
1229
+ // is not enough - only the LAST entry is actually addressable as
1230
+ // ctx.item here. Live-confirmed (conciergeforfield, sanofi/us): two
1231
+ // bugs of this shape. (1) A task nested inside "Matched Message"
1232
+ // referenced "Matched Product" - a SIBLING loop, not an ancestor at
1233
+ // all. (2) A task nested inside "Matched Message", itself nested
1234
+ // inside "Matched Product", referenced "Matched Product" directly -
1235
+ // a real ancestor, but not the nearest one, so `ctx.item` there binds
1236
+ // to "Matched Message" instead. Both silently attributed the
1237
+ // reference to the wrong loop (built HCL pointed at the wrong
1238
+ // for_each task's inner.refs, which doesn't carry that key: "Invalid
1239
+ // index" on every plan). EDK's authoring model has no primitive for
1240
+ // "an outer loop's current item" - same escape shape as taskRef's
1241
+ // out-of-scope cases above, not a claim that ctx.actions[...] is
1242
+ // actually valid at runtime either.
1243
+ const nearest = refCtx.selfTaskRefKeys?.[refCtx.selfTaskRefKeys.length - 1];
1244
+ if (nearest === ref.forEachTask) {
1245
+ return printPathAccess(`${ctxName}.item`, ref.path);
1246
+ }
1247
+ // Cannot route this through `ctx.actions[...]` the way the taskRef
1248
+ // out-of-scope escapes above do: `ctx.actions` is a Proxy that turns
1249
+ // ANY property access into a valid `{ kind: "task", ... }` reference,
1250
+ // `as any` comment or not. Loading the printed file and calling
1251
+ // `.def()` would then silently serialize this as a real task-output
1252
+ // reference (`refs[name]`) instead of a for-each item reference
1253
+ // (`inner.refs[name]`) - a plan with zero "Invalid index" errors that
1254
+ // still silently rewrites a live item reference to the wrong value.
1255
+ // Print a distinct marker object instead: it satisfies tsc the same
1256
+ // way, but automationToTf's valueToTf recognizes the marker and
1257
+ // fails the build loudly instead of building a different accepted
1258
+ // reference (review feedback on PR #1097, cursor[bot]).
1259
+ const relation = refCtx.selfTaskRefKeys?.includes(ref.forEachTask)
1260
+ ? "an outer ancestor forEach, not the nearest enclosing one"
1261
+ : "a sibling forEach, not an ancestor";
1262
+ return `({ __edkUnresolvedForEachItem: ${quote(ref.forEachTask)}, path: [${ref.path.map(quote).join(", ")}] } as any /* TODO: "${ref.forEachTask}" is ${relation} - EDK cannot express a reference to another loop's current item; re-express by hand before this automation can build */)`;
1263
+ }
1131
1264
  case "variableParamRef":
1132
1265
  return `${ctxName}.variables${safeMember(ref.varTask)}${safeMember(ref.name)}`;
1133
1266
  case "template": {
@@ -1155,9 +1288,23 @@ function printRef(ref, state, refCtx) {
1155
1288
  // ei's `elementum_field` data source doesn't expose it).
1156
1289
  const foreignRefName = ref.foreign.entityType === "element"
1157
1290
  ? state.foreignElementRefNames?.get(ref.foreign.name)
1158
- : state.foreignAppRefNames?.get(ref.foreign.name);
1291
+ : ref.foreign.entityType === "task"
1292
+ ? state.foreignTaskRefNames?.get(ref.foreign.name)
1293
+ : ref.foreign.entityType === "app"
1294
+ ? state.foreignAppRefNames?.get(ref.foreign.name)
1295
+ : undefined;
1296
+ if (ref.foreign.entityType === "task") {
1297
+ const parentRef = foreignRefName ?? ref.appHandle;
1298
+ const fieldType = ref.foreign.fieldType ?? "TEXT";
1299
+ const parentNamespace = ref.foreign.namespace !== undefined
1300
+ ? `, parentNamespace: ${quote(ref.foreign.namespace)}`
1301
+ : "";
1302
+ return (`{ __kind: "field", refName: ${quote(ref.fieldKey)}, name: ${quote(ref.foreign.fieldName ?? ref.fieldKey)}, fieldType: ${quote(fieldType)}, ` +
1303
+ `parent: ${quote(parentRef)}, parentKind: "task", parentName: ${quote(ref.foreign.name)}${parentNamespace} }`);
1304
+ }
1159
1305
  if (foreignRefName !== undefined)
1160
1306
  return `catalog.${foreignRefName}.fields${safeMember(ref.fieldKey)}`;
1307
+ const fieldType = ref.foreign.fieldType ?? "TEXT";
1161
1308
  // `parentNamespace` (when the owner's own data block only carried a
1162
1309
  // namespace, no display name) lets build key its owner lookup on the
1163
1310
  // real namespace instead of the `parentName` guess — see from-tf.ts's
@@ -1165,7 +1312,7 @@ function printRef(ref, state, refCtx) {
1165
1312
  const parentNamespace = ref.foreign.namespace !== undefined
1166
1313
  ? `, parentNamespace: ${quote(ref.foreign.namespace)}`
1167
1314
  : "";
1168
- return (`{ __kind: "field", refName: ${quote(ref.fieldKey)}, name: ${quote(ref.foreign.fieldName ?? ref.fieldKey)}, fieldType: "TEXT", ` +
1315
+ return (`{ __kind: "field", refName: ${quote(ref.fieldKey)}, name: ${quote(ref.foreign.fieldName ?? ref.fieldKey)}, fieldType: ${quote(fieldType)}, ` +
1169
1316
  `parent: ${quote(ref.appHandle)}, parentKind: ${quote(ref.foreign.entityType)}, parentName: ${quote(ref.foreign.name)}${parentNamespace} } ` +
1170
1317
  `/* TODO: foreign field — type unconfirmed (ei's elementum_field data source doesn't expose it) and refName is a best-effort guess; verify against "${ref.foreign.name}" */`);
1171
1318
  }
@@ -1177,7 +1324,11 @@ function printRef(ref, state, refCtx) {
1177
1324
  }
1178
1325
  const foreignRefName = ref.entityType === "element"
1179
1326
  ? state.foreignElementRefNames?.get(ref.name)
1180
- : state.foreignAppRefNames?.get(ref.name);
1327
+ : ref.entityType === "task"
1328
+ ? state.foreignTaskRefNames?.get(ref.name)
1329
+ : ref.entityType === "app"
1330
+ ? state.foreignAppRefNames?.get(ref.name)
1331
+ : undefined;
1181
1332
  if (foreignRefName !== undefined)
1182
1333
  return `catalog.${foreignRefName}`;
1183
1334
  return `{ __kind: ${quote(ref.entityType)}, refName: ${quote(ref.appHandle)}, name: ${quote(ref.name)} }`;
@@ -1268,10 +1419,10 @@ function printRef(ref, state, refCtx) {
1268
1419
  // prints the LHS as either a catalog field expression or a ctx ref
1269
1420
  // expression, and both are valid arguments to the same `filter.*` function.
1270
1421
  // ---------------------------------------------------------------------------
1271
- function printFilter(filter, state) {
1422
+ function printFilter(filter, state, refCtx = DEFAULT_CTX) {
1272
1423
  return printCanonicalFilter(filter, {
1273
- field: (field) => printFilterField(field, state),
1274
- reference: (reference) => printFilterReference(reference, state),
1424
+ field: (field) => printFilterField(field, state, refCtx),
1425
+ reference: (reference) => printFilterReference(reference, state, refCtx),
1275
1426
  quote,
1276
1427
  used: (helper) => state.imports.filterOps.add(helper),
1277
1428
  });
@@ -1280,11 +1431,17 @@ function printFilter(filter, state) {
1280
1431
  * Render the left-hand side of a `filter.*` call: a `FieldRef` token
1281
1432
  * (`fieldRef` → `<handle>.fields.<key>`) when there's a field, or the ctx ref
1282
1433
  * expression (`ctx.actions.x.y`) for a row-less (task/trigger-output) LHS —
1283
- * `filter.*` accepts either at the same argument position.
1434
+ * `filter.*` accepts either at the same argument position. `refCtx` defaults
1435
+ * to DEFAULT_CTX for trigger-level filters (never inside a forEach); a
1436
+ * task/switch-case filter passes its real scope so a `forEachItemRef` LHS
1437
+ * (e.g. `filter.eq(ctx.item.severity, ...)`) can tell an ancestor loop's
1438
+ * item from a sibling's - printFilter used to always reset to DEFAULT_CTX
1439
+ * regardless of caller, which was harmless before forEachItemRef checked
1440
+ * ancestry at all.
1284
1441
  */
1285
- function printFilterField(left, state) {
1442
+ function printFilterField(left, state, refCtx = DEFAULT_CTX) {
1286
1443
  if (left.kind === "field") {
1287
- return printRef(left, state, DEFAULT_CTX);
1444
+ return printRef(left, state, refCtx);
1288
1445
  }
1289
1446
  if (left.kind === "userField") {
1290
1447
  return `catalog.users.fields${safeMember(left.fieldKey)}`;
@@ -1302,21 +1459,21 @@ function printFilterField(left, state) {
1302
1459
  }
1303
1460
  return `${quote(`${UNRESOLVED_REFERENCE_MARKER}${left.uuid}`)} as any /* TODO: unresolved ${left.hint} - re-express with a typed ref when possible */`;
1304
1461
  }
1305
- return printRef(left, state, DEFAULT_CTX);
1462
+ return printRef(left, state, refCtx);
1306
1463
  }
1307
1464
  /**
1308
1465
  * Render the RHS of a v2 filter operator. A literal value AST collapses to its
1309
1466
  * scalar; a reference RHS (`ctx.trigger.x`, `ctx.actions.y.z`) prints as the ctx
1310
1467
  * ref — the v2 filter DSL accepts refs and serializes them to the platform's
1311
- * REFERENCE value shape.
1468
+ * REFERENCE value shape. See printFilterField for `refCtx`'s default.
1312
1469
  */
1313
- function printFilterReference(reference, state) {
1470
+ function printFilterReference(reference, state, refCtx = DEFAULT_CTX) {
1314
1471
  if (reference.kind === "unresolved") {
1315
1472
  return `${quote(`${UNRESOLVED_REFERENCE_MARKER}${reference.uuid}`)} as any /* TODO: unresolved ${reference.hint} */`;
1316
1473
  }
1317
1474
  if (reference.kind === "literal")
1318
1475
  return literalJson(reference.value);
1319
- return printRef(reference, state, DEFAULT_CTX);
1476
+ return printRef(reference, state, refCtx);
1320
1477
  }
1321
1478
  function printSortArray(sorts, state, refCtx) {
1322
1479
  // v2 takes `sort` as a pre-built wire object; the slice has no sort DSL. Emit