@elementumai/edk 0.9.15 → 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 (86) 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/engine/build/context.d.ts +2 -2
  4. package/dist-sdk/src/engine/progress.d.ts +4 -0
  5. package/dist-sdk/src/engine/progress.js +16 -4
  6. package/dist-sdk/src/engine/pull/context.d.ts +5 -0
  7. package/dist-sdk/src/engine/pull/ref-only.d.ts +4 -0
  8. package/dist-sdk/src/engine/pull/ref-only.js +11 -0
  9. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +1 -1
  10. package/dist-sdk/src/entities/access-policy/from-tf.js +47 -12
  11. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +5 -3
  12. package/dist-sdk/src/entities/access-policy/to-tf.js +23 -1
  13. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +27 -2
  14. package/dist-sdk/src/entities/agent/from-tf.d.ts +1 -0
  15. package/dist-sdk/src/entities/agent/from-tf.js +18 -3
  16. package/dist-sdk/src/entities/agent/to-tf.js +14 -0
  17. package/dist-sdk/src/entities/agent/tools.d.ts +79 -2
  18. package/dist-sdk/src/entities/agent/tools.js +2 -1
  19. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +11 -0
  20. package/dist-sdk/src/entities/agent-tool/from-tf.js +45 -3
  21. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +7 -0
  22. package/dist-sdk/src/entities/agent-tool/to-tf.js +72 -20
  23. package/dist-sdk/src/entities/app/module.js +8 -0
  24. package/dist-sdk/src/entities/app/to-tf.js +1 -0
  25. package/dist-sdk/src/entities/automation/build.d.ts +12 -5
  26. package/dist-sdk/src/entities/automation/build.js +30 -11
  27. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +4 -0
  28. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +108 -23
  29. package/dist-sdk/src/entities/automation/from-tf.d.ts +73 -5
  30. package/dist-sdk/src/entities/automation/from-tf.js +255 -30
  31. package/dist-sdk/src/entities/automation/index.d.ts +2 -1
  32. package/dist-sdk/src/entities/automation/index.js +2 -1
  33. package/dist-sdk/src/entities/automation/module.js +6 -7
  34. package/dist-sdk/src/entities/automation/output-field-types.d.ts +5 -0
  35. package/dist-sdk/src/entities/automation/output-field-types.js +12 -0
  36. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +20 -0
  37. package/dist-sdk/src/entities/automation/output-key-wire-name.js +22 -0
  38. package/dist-sdk/src/entities/automation/script-code.js +13 -4
  39. package/dist-sdk/src/entities/automation/tasks.d.ts +41 -5
  40. package/dist-sdk/src/entities/automation/tasks.js +31 -9
  41. package/dist-sdk/src/entities/automation/to-tf.d.ts +0 -2
  42. package/dist-sdk/src/entities/automation/to-tf.js +85 -36
  43. package/dist-sdk/src/entities/automation/triggers.d.ts +5 -2
  44. package/dist-sdk/src/entities/automation/types.d.ts +2 -0
  45. package/dist-sdk/src/entities/automation/types.js +5 -0
  46. package/dist-sdk/src/entities/automation/workflow-output.d.ts +35 -0
  47. package/dist-sdk/src/entities/automation/workflow-output.js +53 -0
  48. package/dist-sdk/src/entities/dashboard/from-tf.js +1 -1
  49. package/dist-sdk/src/entities/dashboard/to-tf.js +1 -0
  50. package/dist-sdk/src/entities/element/build.d.ts +11 -8
  51. package/dist-sdk/src/entities/element/build.js +14 -5
  52. package/dist-sdk/src/entities/element/locals.d.ts +2 -2
  53. package/dist-sdk/src/entities/element/locals.js +6 -2
  54. package/dist-sdk/src/entities/element/system-fields.d.ts +4 -0
  55. package/dist-sdk/src/entities/element/system-fields.js +12 -0
  56. package/dist-sdk/src/entities/element/to-tf.js +1 -0
  57. package/dist-sdk/src/entities/field/from-tf.js +47 -1
  58. package/dist-sdk/src/entities/relationship/from-tf.js +2 -2
  59. package/dist-sdk/src/entities/relationship/to-tf.js +1 -0
  60. package/dist-sdk/src/entities/search-table/from-tf.js +6 -6
  61. package/dist-sdk/src/entities/search-table/module.js +2 -2
  62. package/dist-sdk/src/entities/search-table/types.d.ts +1 -0
  63. package/dist-sdk/src/entities/search-table/types.js +1 -0
  64. package/dist-sdk/src/entities/shared/filters/ast.d.ts +2 -0
  65. package/dist-sdk/src/entities/shared/filters/index.d.ts +12 -2
  66. package/dist-sdk/src/entities/shared/filters/index.js +17 -1
  67. package/dist-sdk/src/entities/shared/filters/print.js +25 -11
  68. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +1 -1
  69. package/dist-sdk/src/entities/shared/filters/tf-codec.js +39 -7
  70. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +18 -2
  71. package/dist-sdk/src/entities/skill/module.js +9 -0
  72. package/dist-sdk/src/entities/skill/to-tf.js +18 -0
  73. package/dist-sdk/src/entities/skill/tools.d.ts +18 -4
  74. package/dist-sdk/src/entities/skill/tools.js +1 -1
  75. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +12 -0
  76. package/dist-sdk/src/entities/skill-tool/from-tf.js +58 -3
  77. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +6 -0
  78. package/dist-sdk/src/entities/skill-tool/to-tf.js +78 -43
  79. package/dist-sdk/src/entities/view/from-tf.js +30 -9
  80. package/dist-sdk/src/entities/view/to-tf.js +18 -10
  81. package/dist-sdk/src/entities/widget/from-tf.js +1 -1
  82. package/dist-sdk/src/entities/widget/to-tf.js +1 -0
  83. package/dist-sdk/src/graph/index.d.ts +13 -0
  84. package/dist-sdk/src/graph/index.js +5 -0
  85. package/dist-sdk/src/graph/types.d.ts +10 -0
  86. package/package.json +2 -1
@@ -114,6 +114,17 @@ export interface NormalizedAgentTool {
114
114
  readonly searchTableKey?: string;
115
115
  /** Stable lookup name when the table is resolved through a data source. */
116
116
  readonly searchTableName?: string;
117
+ /** Table-owned search table only: the owning Table entity's display name. */
118
+ readonly searchTableOwnerName?: string;
119
+ /** Table-owned search table only: the owning Table entity's authored refName. */
120
+ readonly searchTableOwnerRefName?: string;
121
+ /**
122
+ * The search table itself could not be resolved to a name or a local
123
+ * resource at all (export retained a raw UUID) - round-trip it as an
124
+ * unsafePlatformId() escape instead of dropping the tool outright. Mirrors
125
+ * PR #894's target-id fallback, extended to this separate field.
126
+ */
127
+ readonly searchTableRawId?: string;
117
128
  /** relateRecord: the aspect whose record is related to the primary target. */
118
129
  readonly relatedTarget?: NormalizedToolTarget;
119
130
  /** runAgent: target agent bag key within the owning app. */
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { EntityTfError } from "../../engine/entity.js";
8
8
  import { dataRefLabel, optionalString, resourceRefLabel } from "../../engine/pull/context.js";
9
- import { isTfExpr, scopedLabelToBagKey, scopedResourceLabel, tsLabelToTfLabel } from "../../engine/tf/index.js";
9
+ import { isTfExpr, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, tfLabelToTsLabel, tsLabelToTfLabel } from "../../engine/tf/index.js";
10
10
  import { resolveToolFieldKey } from "../shared/tool-field-ref.js";
11
11
  import { dataAspectDisplayName } from "../shared/aspect-target-from-tf.js";
12
12
  import { KNOWN_TOOL_ATTRS, TOOL_SUB_TYPE_BY_RESOURCE } from "./types.js";
@@ -276,8 +276,23 @@ export function toolFromTf(block, owner, ctx) {
276
276
  else if (rawReturnFields !== undefined) {
277
277
  ctx.diagnostics.push(`${where}: return_fields is not a list; dropped`);
278
278
  }
279
+ // The provider schema doesn't validate that `fields`/`return_fields` are
280
+ // exclusive, and its read path can leave a stale `return_fields` on a
281
+ // resource whose `fields` was set later - so a real export CAN carry
282
+ // both, even though only `fields` (the newer, primary dialect) is
283
+ // actually effective. Printing both would emit a call the authoring
284
+ // type rejects (fields/returnFields are a closed either/or union there),
285
+ // failing the pulled workspace's own typecheck for a state the provider
286
+ // itself allows (review feedback, PR #1099, jj-deloitte).
287
+ if (searchTableFields !== undefined && returnFields !== undefined) {
288
+ ctx.diagnostics.push(`${where}: has both fields and return_fields; return_fields is the deprecated dialect and is ineffective once fields is set, so it's dropped`);
289
+ returnFields = undefined;
290
+ }
279
291
  let searchTableKey;
280
292
  let searchTableName;
293
+ let searchTableOwnerName;
294
+ let searchTableOwnerRefName;
295
+ let searchTableRawId;
281
296
  if (subType.typeKey === "searchTable") {
282
297
  const value = attrs["search_table_id"];
283
298
  const resourceTypes = ["elementum_ai_search_table", "elementum_linked_ai_search_table", "elementum_table_search_table"];
@@ -289,18 +304,42 @@ export function toolFromTf(block, owner, ctx) {
289
304
  // carries the `elements_<ns>_` prefix — decoding it with app scope leaves
290
305
  // the prefix in place and camel-cases the whole label into a bag key that
291
306
  // matches nothing. The table variant keeps its existing app-scope
292
- // handling: a table-owned search table reached through a tool is not
293
- // modelled end to end yet.
307
+ // handling.
294
308
  const scope = matched.type === "elementum_table_search_table" ? "app" : "element";
295
309
  searchTableKey = scopedLabelToBagKey(owner.ownerTfLabel, matched.label, scope);
296
310
  }
297
311
  else if (isTfExpr(value) && value.$expr === "data-attr" && value.type === "elementum_search_table") {
298
312
  searchTableName = ctx.dataName(value.type, value.label);
313
+ // The generic search-table data source is used for both aspect-owned
314
+ // and table-owned tables. The presence of table_id is the only
315
+ // portable discriminator available in the HCL stream (mirrors
316
+ // skill-tool/from-tf.ts's identical handling).
317
+ const tableLabel = dataRefLabel(ctx.dataAttrs?.(value.type, value.label)?.["table_id"], "elementum_table");
318
+ if (tableLabel !== undefined) {
319
+ searchTableOwnerName = ctx.dataName("elementum_table", tableLabel);
320
+ if (searchTableOwnerName !== undefined) {
321
+ searchTableOwnerRefName = [...(ctx.foreignTableRefsById?.values() ?? [])].find((identity) => identity.name === searchTableOwnerName)?.tableRefName ?? tfLabelToTsLabel(sanitizeName(searchTableOwnerName));
322
+ }
323
+ }
299
324
  if (searchTableName === undefined) {
300
325
  ctx.diagnostics.push(`${where}: search_table_id references data.${value.type}.${value.label} without a matching name lookup; skipped`);
301
326
  return undefined;
302
327
  }
303
328
  }
329
+ else if (typeof value === "string" && value !== "") {
330
+ // The search table's own identity couldn't be resolved to a name or a
331
+ // local resource at all - the org-ref layer already fell back to a raw
332
+ // UUID here (live-confirmed on conciergeforfield, sanofi/us: several
333
+ // account-planning tools' search tables have no portable lookup).
334
+ // Round-trip it as unsafePlatformId() instead of silently dropping a
335
+ // live tool - a rebuild-and-plan on the dropped tool would otherwise
336
+ // DESTROY it. Same diagnostic style as aspectTargetFromTf's matching
337
+ // "kept as unresolved" case, so a pull summary surfaces this
338
+ // unmanaged id instead of the tool silently having a stand-in
339
+ // reference the author never sees (review feedback, PR #1099).
340
+ ctx.diagnostics.push(`${where}: search_table_id could not be resolved to a portable reference ("${value}"); kept as unresolved`);
341
+ searchTableRawId = value;
342
+ }
304
343
  else {
305
344
  ctx.diagnostics.push(`${where}: search_table_id is not a supported search-table reference; skipped`);
306
345
  return undefined;
@@ -337,6 +376,9 @@ export function toolFromTf(block, owner, ctx) {
337
376
  }),
338
377
  ...(searchTableKey !== undefined && { searchTableKey }),
339
378
  ...(searchTableName !== undefined && { searchTableName }),
379
+ ...(searchTableOwnerName !== undefined && { searchTableOwnerName }),
380
+ ...(searchTableOwnerRefName !== undefined && { searchTableOwnerRefName }),
381
+ ...(searchTableRawId !== undefined && { searchTableRawId }),
340
382
  };
341
383
  }
342
384
  function aspectTargetFromTf(value, attrName, owner, ctx, where) {
@@ -38,6 +38,13 @@ export interface ToolToTfContext {
38
38
  readonly workspaceAspects?: ReadonlyMap<string, WorkspaceAspect>;
39
39
  /** Records an app-scoped service-account lookup by name. */
40
40
  serviceAccountRef?(tfLabel: string, name: string): TfValue | void;
41
+ /**
42
+ * Resolves a table-owned search table not present in this workspace
43
+ * (`table.parent` names a Table entity with no local `workspaceAspects`
44
+ * entry): records the `data.elementum_table`/`data.elementum_search_table`
45
+ * lookups and returns the search table's id reference.
46
+ */
47
+ tableSearchTableRef?(tfLabel: string, tableRefName: string, tableName: string, searchTableName: string): TfValue | void;
41
48
  /** App-local automations whose publish resource will be emitted in this build. */
42
49
  readonly activeAutomationRefNames?: ReadonlySet<string>;
43
50
  /** Degradations land here — reported by the caller, never silent. */
@@ -343,30 +343,82 @@ export function toolToTf(entry, ctx) {
343
343
  }
344
344
  if (typeKey === "searchTable") {
345
345
  const table = inner.searchTableId;
346
- if (table?.refName === undefined || table.refName === "") {
347
- ctx.diagnostics.push(`${where}: no search table token; dropped`);
348
- return undefined;
346
+ // The search table itself (not its owner - that's the __variant/parent
347
+ // fallback below) has no portable lookup at all: unsafePlatformId()
348
+ // round-trips it as a raw id directly, before the refName check below,
349
+ // which would otherwise treat this escape as "no search table token"
350
+ // and drop a live tool. Scoped to a token with NO refName - one that
351
+ // still carries a refName has a real portable lookup available and
352
+ // must go through the normal parent-mismatch check + resolution below,
353
+ // not be short-circuited here just because it also happens to carry an
354
+ // __unsafe marker.
355
+ if (table?.__unsafe === "platformId" && table.refName === undefined && typeof table.value === "string" && table.value !== "") {
356
+ attrs["search_table_id"] = table.value;
349
357
  }
350
- if (target !== undefined && table.parent !== undefined && table.parent !== "" && table.parent !== target.refName) {
351
- ctx.diagnostics.push(`${where}: search table belongs to "${table.parent}", not target "${target.refName}"; dropped`);
358
+ else if (table?.refName === undefined || table.refName === "") {
359
+ ctx.diagnostics.push(`${where}: no search table token; dropped`);
352
360
  return undefined;
353
361
  }
354
- if (target?.localTfLabel !== undefined) {
355
- const resourceType = table.__variant === "linked"
356
- ? "elementum_linked_ai_search_table"
357
- : table.__variant === "table"
358
- ? "elementum_table_search_table"
359
- : "elementum_ai_search_table";
360
- attrs["search_table_id"] = expr.resourceAttr(resourceType, scopedResourceLabel(target.localTfLabel, tsLabelToTfLabel(table.refName), target.kind === "element" ? "element" : "app"), ["id"]);
361
- }
362
- else if (target !== undefined) {
363
- const lookupLabel = sanitizeName(`${target.foreignTfLabel}_${table.name ?? table.refName}`);
364
- ctx.foreignFieldRef("elementum_search_table", lookupLabel, target.value, table.name ?? table.refName);
365
- attrs["search_table_id"] = expr.dataAttr("elementum_search_table", lookupLabel, ["id"]);
366
- }
367
362
  else {
368
- ctx.diagnostics.push(`${where}: search table has no target aspect; dropped`);
369
- return undefined;
363
+ if (target !== undefined && table.parent !== undefined && table.parent !== "" && table.parent !== target.refName) {
364
+ ctx.diagnostics.push(`${where}: search table belongs to "${table.parent}", not target "${target.refName}"; dropped`);
365
+ return undefined;
366
+ }
367
+ if (target === undefined) {
368
+ if (table.__variant !== "table") {
369
+ ctx.diagnostics.push(`${where}: missing target aspect is only valid for a table-owned search table; dropped`);
370
+ return undefined;
371
+ }
372
+ const workspaceTable = table.parent === undefined
373
+ ? undefined
374
+ : ctx.workspaceAspects?.get(workspaceAspectKey("table", table.parent));
375
+ if (workspaceTable !== undefined) {
376
+ // sanitizeName, not tsLabelToTfLabel: table.refName here always comes
377
+ // from a search-table token factory (searchTableRef/
378
+ // tableSearchTableRef), which sets refName straight from the raw
379
+ // display name (ei's own labeling convention) - it's never a clean
380
+ // bijective camelCase identifier the way an authored bag key is.
381
+ attrs["search_table_id"] = expr.resourceAttr("elementum_table_search_table", `tables_${workspaceTable.tfLabel}_${sanitizeName(table.name ?? table.refName)}`, ["id"]);
382
+ }
383
+ else if (ctx.tableSearchTableRef !== undefined && table.parent !== undefined && table.parent !== "") {
384
+ // sanitizeName(table.parentName ?? table.parent), not
385
+ // sanitizeName(table.parent): table.parent is the camelCase
386
+ // refName, but ei labels the export from the table's DISPLAY name,
387
+ // and sanitizeName doesn't split a capital before a digit the way
388
+ // a camelCase refName needs to reverse that - "hcpLookupV2"
389
+ // sanitizes to "hcp_lookupv2" while ei's own label for "HCP Lookup
390
+ // v2" is "hcp_lookup_v2", a perpetual plan diff (review feedback,
391
+ // PR #1095, msivraj).
392
+ const lookup = ctx.tableSearchTableRef(`${sanitizeName(table.parentName ?? table.parent)}_${sanitizeName(table.name ?? table.refName)}`, table.parent, table.parentName ?? table.parent, table.name ?? table.refName);
393
+ if (lookup !== undefined)
394
+ attrs["search_table_id"] = lookup;
395
+ else {
396
+ ctx.diagnostics.push(`${where}: table-owned search table lookup could not be materialized; dropped`);
397
+ return undefined;
398
+ }
399
+ }
400
+ else {
401
+ // A __unsafe fallback here is unreachable: the top-level guard
402
+ // above already handles any token with no refName, and this
403
+ // branch only runs when table.refName IS set (review feedback,
404
+ // PR #1099 - cursor[bot]).
405
+ ctx.diagnostics.push(`${where}: table-owned search table has no portable lookup; dropped`);
406
+ return undefined;
407
+ }
408
+ }
409
+ else if (target.localTfLabel !== undefined) {
410
+ const resourceType = table.__variant === "linked"
411
+ ? "elementum_linked_ai_search_table"
412
+ : table.__variant === "table"
413
+ ? "elementum_table_search_table"
414
+ : "elementum_ai_search_table";
415
+ attrs["search_table_id"] = expr.resourceAttr(resourceType, scopedResourceLabel(target.localTfLabel, tsLabelToTfLabel(table.refName), target.kind === "element" ? "element" : "app"), ["id"]);
416
+ }
417
+ else {
418
+ const lookupLabel = sanitizeName(`${target.foreignTfLabel}_${table.name ?? table.refName}`);
419
+ ctx.foreignFieldRef("elementum_search_table", lookupLabel, target.value, table.name ?? table.refName);
420
+ attrs["search_table_id"] = expr.dataAttr("elementum_search_table", lookupLabel, ["id"]);
421
+ }
370
422
  }
371
423
  }
372
424
  if (inner.fields !== undefined && inner.fields.length > 0) {
@@ -88,5 +88,13 @@ export const appModule = {
88
88
  }
89
89
  },
90
90
  },
91
+ roundtrip: {
92
+ referenceAliases: [],
93
+ omittedAttributeDefaults: [
94
+ { attribute: "id_field_name", value: "ID" },
95
+ { attribute: "status_field_name", value: "Status" },
96
+ { attribute: "title_field_name", value: "Title" },
97
+ ],
98
+ },
91
99
  catalog: NO_CATALOG,
92
100
  };
@@ -309,6 +309,7 @@ export function appToTf(entity, ctx) {
309
309
  for (const [index, entry] of (payload.accessPolicies ?? []).entries()) {
310
310
  const { block } = accessPolicyToTf(entry, index, {
311
311
  ownerTfLabel: ctx.appTfLabel,
312
+ ownerRefName: ctx.appRefName,
312
313
  scope: "app",
313
314
  objectId,
314
315
  orgRefs: ctx.orgRefs,
@@ -6,7 +6,9 @@ import { type Context, type ForEachItem } from "../shared/context.js";
6
6
  import { type Ref, type Simplify, type ValueOrRef } from "../shared/ref.js";
7
7
  import type { Filter } from "./filter.js";
8
8
  import { type ScriptFile, type ScriptInput } from "./script-code.js";
9
+ import * as actionFactories from "./tasks.js";
9
10
  import type { ScriptOutputs } from "./tasks.js";
11
+ import { type WorkflowOutputDeclaration } from "./workflow-output.js";
10
12
  /** Structural empty object — neutral element for the accumulated action map. */
11
13
  type EmptyObject = {
12
14
  [K in never]: never;
@@ -128,11 +130,16 @@ export interface ActionChain {
128
130
  */
129
131
  __executeScriptOutputSchemas(): ReadonlyMap<string, unknown>;
130
132
  }
131
- /** A value an output property can carry: a typed ctx ref, or a literal. */
132
- type OutputValue = Ref<unknown> | string | number | boolean | null;
133
- /** `Ref<T>` values resolve to `T` by the time the platform hands them to a script. */
133
+ /** A value an output property can carry: a typed ctx ref, a literal, or an explicit typed ref. */
134
+ type BareOutputValue = Ref<unknown> | string | number | boolean | null;
135
+ type OutputValue = BareOutputValue | WorkflowOutputDeclaration;
136
+ /**
137
+ * `Ref<T>` values resolve to `T` by the time the platform hands them to a
138
+ * script; a `withFieldMappings(...)`-wrapped list input resolves to an array
139
+ * of alias-keyed field values (one object per list item).
140
+ */
134
141
  type ResolvedRefs<I> = {
135
- [K in keyof I]: I[K] extends Ref<infer T> ? T : I[K];
142
+ [K in keyof I]: I[K] extends actionFactories.ExecuteScriptListInputToken ? readonly Record<string, unknown>[] : I[K] extends Ref<infer T> ? T : I[K];
136
143
  };
137
144
  /** Static options or options computed from the typed outputs available so far. */
138
145
  export type ActionOptions<TTrigger, TActions extends Record<string, unknown>, TVars extends Record<string, unknown>, TOptions> = TOptions | ((ctx: Context<TTrigger, TActions, TVars>) => TOptions);
@@ -171,7 +178,7 @@ interface ActionMethods<TTrigger, TActions extends Record<string, unknown>, TVar
171
178
  * carries no `output_schema`, so a rebuild doesn't invent one and drift
172
179
  * from state.
173
180
  */
174
- executeScript<TName extends string, I extends Record<string, ValueOrRef<unknown>>, R extends Record<string, unknown> = Record<string, unknown>>(name: TName, opts: {
181
+ executeScript<TName extends string, I extends Record<string, ValueOrRef<unknown> | actionFactories.ExecuteScriptListInputToken>, R extends Record<string, unknown> = Record<string, unknown>>(name: TName, opts: {
175
182
  readonly inputs?: (ctx: NestedActionContext<TTrigger, TActions, TVars, TItem>) => I;
176
183
  readonly code: ((input: ScriptInput<ResolvedRefs<NoInfer<I>>>) => R) | ScriptFile;
177
184
  /**
@@ -39,6 +39,7 @@ import { serializeNode } from "./serialize.js";
39
39
  // automations call the direct fluent methods declared on ActionBuilder.
40
40
  import * as operatorFactories from "./operators.js";
41
41
  import * as actionFactories from "./tasks.js";
42
+ import { isWorkflowOutputDeclaration, workflowOutputFieldType, } from "./workflow-output.js";
42
43
  /** Placeholder `forEachTaskRefKey` the forEach item proxy emits; replaced with the real refKey. */
43
44
  export const FOR_EACH_PLACEHOLDER = "__forEach__";
44
45
  /**
@@ -128,23 +129,24 @@ function collectExecuteScriptOutputSchemas(tasks) {
128
129
  visit(tasks);
129
130
  return out;
130
131
  }
131
- /**
132
- * Schema kinds `outputFieldTypesFromScriptSchema` maps to an EXACT field
133
- * type — as opposed to its own catch-all default (`"TEXT"` for anything
134
- * unrecognized, including `"object"`), which is real for the wire's own
135
- * default but would be a wrong guess if promoted to `OutputPropertyRef.valueType`.
136
- */
137
132
  /**
138
133
  * Resolve an automation-level output's `valueType` from its (already
139
- * serialized) value: only when it's a plain ref to an executeScript task's
140
- * `result.<prop>` whose declared schema has an EXACT (not catch-all-guessed)
141
- * kind for that property. Anything else — a literal, a trigger/variable ref,
142
- * a non-executeScript task, or an unmodeled schema kind (e.g. `object`) —
143
- * returns `undefined` (unknown, not a guess).
134
+ * serialized) value. Explicit workflowOutput metadata wins. Otherwise, infer
135
+ * only a plain executeScript `result.<prop>` whose declared schema has an
136
+ * exact kind; the schema reader's catch-all TEXT default is not enough to
137
+ * stamp a catalog type. Anything else returns `undefined` (unknown, not a
138
+ * guess).
144
139
  */
145
140
  function resolveOutputValueType(value, scriptSchemas) {
146
141
  if (value === null || typeof value !== "object")
147
142
  return undefined;
143
+ const explicitFieldType = value.fieldType;
144
+ if (typeof explicitFieldType === "string") {
145
+ return {
146
+ fieldType: explicitFieldType,
147
+ multiple: value.multiple === true,
148
+ };
149
+ }
148
150
  const ref = value.taskReference;
149
151
  if (ref === null || typeof ref !== "object")
150
152
  return undefined;
@@ -372,6 +374,23 @@ function resolveVariableParamMarkers(node, idMap) {
372
374
  resolveVariableParamMarkers(v, idMap);
373
375
  }
374
376
  function serializeOutputValue(value) {
377
+ if (isWorkflowOutputDeclaration(value)) {
378
+ if (!isRef(value.value)) {
379
+ throw new EntityTfError("workflowOutput value must be a typed automation reference");
380
+ }
381
+ const serialized = serializeNode(value.value);
382
+ if (serialized === null || typeof serialized !== "object" || Array.isArray(serialized)) {
383
+ throw new EntityTfError("workflowOutput reference did not serialize to an object");
384
+ }
385
+ if (!("taskReference" in serialized) && !("triggerReference" in serialized)) {
386
+ throw new EntityTfError("workflowOutput explicit metadata is supported only for task and trigger references");
387
+ }
388
+ return {
389
+ ...serialized,
390
+ fieldType: workflowOutputFieldType(value.type),
391
+ multiple: value.multiple,
392
+ };
393
+ }
375
394
  return isRef(value) ? serializeNode(value) : { value };
376
395
  }
377
396
  function makeActionBuilder(state, mode = "root", item) {
@@ -13,6 +13,7 @@
13
13
  import type { RefExpr, SortAst, ApprovalChainRefAst, DatamineRefAst, TableRefAst, AppRefAst, FieldRefAst, UserFieldRefAst, UnresolvedRefAst } from "../../shared/filters/ast.js";
14
14
  import type { Filter } from "../../shared/filters/types.js";
15
15
  import type { AutomationStatus } from "../build.js";
16
+ import type { WorkflowOutputType } from "../workflow-output.js";
16
17
  export type { RefExpr, SortAst, AppRefAst, ApprovalChainRefAst, DatamineRefAst, TableRefAst, FieldRefAst, UserFieldRefAst, UnresolvedRefAst, };
17
18
  /**
18
19
  * A TaskCall represents one call to a task factory like `executeScript({...})`.
@@ -154,5 +155,8 @@ export interface AutomationAst {
154
155
  readonly outputs?: readonly {
155
156
  name: string;
156
157
  value: unknown;
158
+ /** Present only when bare-reference inference cannot reproduce live metadata. */
159
+ explicitType?: WorkflowOutputType;
160
+ explicitMultiple?: boolean;
157
161
  }[];
158
162
  }
@@ -384,7 +384,13 @@ function printOutputs(ast, state) {
384
384
  while (usedOutputNames.has(name))
385
385
  name = `${o.name} ${suffix++}`;
386
386
  usedOutputNames.add(name);
387
- 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},`;
388
394
  });
389
395
  const objBody = `({\n${entryLines.join("\n")}\n${pad}})`;
390
396
  // Prefix the ctx param with `_` when the body never references it (all
@@ -609,9 +615,10 @@ function printTrigger(trigger, state) {
609
615
  }
610
616
  case "surveyResponseCreate": {
611
617
  const surveyResponseCreate = trackFactory("surveyResponseCreate", state);
618
+ state.imports.usesUnsafePlatformId = true;
612
619
  const parts = [
613
620
  `app: ${printRef(trigger.app, state, DEFAULT_CTX)}`,
614
- `survey: ${quote(trigger.survey)}`,
621
+ `survey: unsafePlatformId(${quote(trigger.survey)})${unresolvedReferenceComment(trigger.survey, state.unresolvedReferences)}`,
615
622
  ];
616
623
  return `${surveyResponseCreate}({\n ${parts.join(",\n ")}\n })`;
617
624
  }
@@ -769,7 +776,20 @@ function annotateScriptLines(body, indent) {
769
776
  const result = [];
770
777
  for (const line of lines) {
771
778
  if (line.trim().length === 0) {
772
- 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}`);
773
793
  continue;
774
794
  }
775
795
  const wasInBacktick = inBacktick;
@@ -919,7 +939,7 @@ function formatSwitchCase(ch, state, indent, refCtx) {
919
939
  // The switch case `condition:` is a `filter.*` expression evaluated in the
920
940
  // switch's outer scope; v2 takes it as a bare value (no `(app) =>` lambda).
921
941
  if (ch.filter)
922
- parts.push(`${innerPad}condition: ${printFilter(ch.filter, state)}`);
942
+ parts.push(`${innerPad}condition: ${printFilter(ch.filter, state, refCtx)}`);
923
943
  parts.push(`${innerPad}actions: ${formatNestedActions(ch.tasks, state, indent + 2, refCtx)}`);
924
944
  return `${pad}{\n${parts.join(",\n")},\n${pad}}`;
925
945
  }
@@ -1085,7 +1105,25 @@ function printArgValue(name, value, state, indent, refCtx) {
1085
1105
  if (isRefExpr(value))
1086
1106
  return printRef(value, state, refCtx);
1087
1107
  if (isFilter(value))
1088
- 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
+ }
1089
1127
  // executeScript body (AST key `code`, legacy `script`) — always function form.
1090
1128
  if ((name === "code" || name === "script") && typeof value === "string") {
1091
1129
  return printScriptCodeFn(value, indent, state);
@@ -1104,6 +1142,9 @@ function printArgValue(name, value, state, indent, refCtx) {
1104
1142
  function isPulledRawCalculation(value) {
1105
1143
  return !!value && typeof value === "object" && value.kind === "calculationRaw";
1106
1144
  }
1145
+ function isExecuteScriptListInputAst(value) {
1146
+ return !!value && typeof value === "object" && value.__edkExecuteScriptListInput === true;
1147
+ }
1107
1148
  // ---------------------------------------------------------------------------
1108
1149
  // RefExpr printer — emits v2 ctx refs + catalog handle-tokens
1109
1150
  // ---------------------------------------------------------------------------
@@ -1145,6 +1186,11 @@ function printRef(ref, state, refCtx) {
1145
1186
  // legitimate — so print them with plain dot/bracket access; only record
1146
1187
  // paths keep the unresolved-key as-any heuristic.
1147
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
+ }
1148
1194
  return `${ctxName}.actions${safeMember(ref.task)}` + ref.path.map(safeMember).join("");
1149
1195
  }
1150
1196
  return printPathAccess(`${ctxName}.actions${safeMember(ref.task)}`, ref.path);
@@ -1174,14 +1220,47 @@ function printRef(ref, state, refCtx) {
1174
1220
  }
1175
1221
  case "forEachRef":
1176
1222
  return printPathAccess(`${ctxName}.actions${safeMember(ref.forEachTask)}`, ref.path);
1177
- case "forEachItemRef":
1178
- // An unresolved field on a loop item prints as a bare raw-UUID bracket
1179
- // index without this - printPathAccess is the same "as any" escape
1180
- // already used for taskRef/forEachRef's own unresolved-path segments
1181
- // (#933, live-confirmed: ctx.item["<uuid>"] next to the identical
1182
- // ctx.actions["Existing Actions"] as any /* TODO */ pattern in the
1183
- // same pulled file).
1184
- 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
+ }
1185
1264
  case "variableParamRef":
1186
1265
  return `${ctxName}.variables${safeMember(ref.varTask)}${safeMember(ref.name)}`;
1187
1266
  case "template": {
@@ -1340,10 +1419,10 @@ function printRef(ref, state, refCtx) {
1340
1419
  // prints the LHS as either a catalog field expression or a ctx ref
1341
1420
  // expression, and both are valid arguments to the same `filter.*` function.
1342
1421
  // ---------------------------------------------------------------------------
1343
- function printFilter(filter, state) {
1422
+ function printFilter(filter, state, refCtx = DEFAULT_CTX) {
1344
1423
  return printCanonicalFilter(filter, {
1345
- field: (field) => printFilterField(field, state),
1346
- reference: (reference) => printFilterReference(reference, state),
1424
+ field: (field) => printFilterField(field, state, refCtx),
1425
+ reference: (reference) => printFilterReference(reference, state, refCtx),
1347
1426
  quote,
1348
1427
  used: (helper) => state.imports.filterOps.add(helper),
1349
1428
  });
@@ -1352,11 +1431,17 @@ function printFilter(filter, state) {
1352
1431
  * Render the left-hand side of a `filter.*` call: a `FieldRef` token
1353
1432
  * (`fieldRef` → `<handle>.fields.<key>`) when there's a field, or the ctx ref
1354
1433
  * expression (`ctx.actions.x.y`) for a row-less (task/trigger-output) LHS —
1355
- * `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.
1356
1441
  */
1357
- function printFilterField(left, state) {
1442
+ function printFilterField(left, state, refCtx = DEFAULT_CTX) {
1358
1443
  if (left.kind === "field") {
1359
- return printRef(left, state, DEFAULT_CTX);
1444
+ return printRef(left, state, refCtx);
1360
1445
  }
1361
1446
  if (left.kind === "userField") {
1362
1447
  return `catalog.users.fields${safeMember(left.fieldKey)}`;
@@ -1374,21 +1459,21 @@ function printFilterField(left, state) {
1374
1459
  }
1375
1460
  return `${quote(`${UNRESOLVED_REFERENCE_MARKER}${left.uuid}`)} as any /* TODO: unresolved ${left.hint} - re-express with a typed ref when possible */`;
1376
1461
  }
1377
- return printRef(left, state, DEFAULT_CTX);
1462
+ return printRef(left, state, refCtx);
1378
1463
  }
1379
1464
  /**
1380
1465
  * Render the RHS of a v2 filter operator. A literal value AST collapses to its
1381
1466
  * scalar; a reference RHS (`ctx.trigger.x`, `ctx.actions.y.z`) prints as the ctx
1382
1467
  * ref — the v2 filter DSL accepts refs and serializes them to the platform's
1383
- * REFERENCE value shape.
1468
+ * REFERENCE value shape. See printFilterField for `refCtx`'s default.
1384
1469
  */
1385
- function printFilterReference(reference, state) {
1470
+ function printFilterReference(reference, state, refCtx = DEFAULT_CTX) {
1386
1471
  if (reference.kind === "unresolved") {
1387
1472
  return `${quote(`${UNRESOLVED_REFERENCE_MARKER}${reference.uuid}`)} as any /* TODO: unresolved ${reference.hint} */`;
1388
1473
  }
1389
1474
  if (reference.kind === "literal")
1390
1475
  return literalJson(reference.value);
1391
- return printRef(reference, state, DEFAULT_CTX);
1476
+ return printRef(reference, state, refCtx);
1392
1477
  }
1393
1478
  function printSortArray(sorts, state, refCtx) {
1394
1479
  // v2 takes `sort` as a pre-built wire object; the slice has no sort DSL. Emit