@elementumai/edk 0.10.3 → 0.10.4

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 (30) hide show
  1. package/dist-sdk/src/engine/pull/context.d.ts +15 -5
  2. package/dist-sdk/src/engine/tf/index.d.ts +1 -0
  3. package/dist-sdk/src/engine/tf/index.js +1 -0
  4. package/dist-sdk/src/engine/tf/scan.d.ts +22 -0
  5. package/dist-sdk/src/engine/tf/scan.js +123 -0
  6. package/dist-sdk/src/engine/workspace/loader.d.ts +8 -0
  7. package/dist-sdk/src/engine/workspace/loader.js +20 -0
  8. package/dist-sdk/src/entities/agent/to-tf.d.ts +13 -11
  9. package/dist-sdk/src/entities/agent/to-tf.js +17 -12
  10. package/dist-sdk/src/entities/agent-tool/from-tf.js +2 -2
  11. package/dist-sdk/src/entities/agent-tool/to-tf.js +9 -0
  12. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +6 -0
  13. package/dist-sdk/src/entities/app/from-tf.js +4 -0
  14. package/dist-sdk/src/entities/automation/build.js +12 -2
  15. package/dist-sdk/src/entities/automation/module.js +39 -11
  16. package/dist-sdk/src/entities/automation/output-field-types.d.ts +8 -0
  17. package/dist-sdk/src/entities/automation/output-field-types.js +20 -0
  18. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +2 -0
  19. package/dist-sdk/src/entities/automation/output-key-wire-name.js +18 -0
  20. package/dist-sdk/src/entities/automation/to-tf.d.ts +7 -0
  21. package/dist-sdk/src/entities/automation/to-tf.js +69 -18
  22. package/dist-sdk/src/entities/element/from-tf.js +3 -1
  23. package/dist-sdk/src/entities/skill/module.js +28 -2
  24. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +2 -0
  25. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +6 -2
  26. package/dist-sdk/src/entities/view/custom-view-validate.js +6 -5
  27. package/dist-sdk/src/entities/view/from-tf.d.ts +8 -0
  28. package/dist-sdk/src/entities/view/from-tf.js +125 -21
  29. package/dist-sdk/src/graph/types.d.ts +7 -0
  30. package/package.json +1 -1
@@ -169,13 +169,14 @@ export interface FromTfContext {
169
169
  */
170
170
  readonly authoringBlockers?: AuthoringBlocker[];
171
171
  /**
172
- * Root-extracted resources that only round-trip together with an own-file
173
- * resource extracted later (a dashboard chart widget and its chart,
174
- * #1731). Once own-file extraction is done, stream-root checks each one.
172
+ * Resources that only round-trip together with an own-file resource (a
173
+ * dashboard chart widget and its chart, #1731; a skill tool and the
174
+ * automation it runs). Once own-file extraction is done, stream-root checks
175
+ * each one, so the order kinds extract in does not matter.
175
176
  * When the build will not emit it (its `requires` was skipped and no
176
177
  * authored file for it is kept, is missing from the export, or never named
177
- * a resource this pull extracts), `prune` removes it from the root, and it
178
- * is skipped and released, so the next plan never destroys it. Undefined
178
+ * a resource this pull extracts), `prune` (or `pruneOwnFile`) removes it,
179
+ * and it is skipped and released, so the next plan never destroys it. Undefined
179
180
  * for a caller that does not wire it up.
180
181
  */
181
182
  readonly requiresExtracted?: ExtractRequirement[];
@@ -209,6 +210,15 @@ export interface ExtractRequirement {
209
210
  }) => {
210
211
  readonly refName: string;
211
212
  };
213
+ /**
214
+ * A dependent printed inside an own-file item (a skill's tool) rather than
215
+ * the root: that kind's extracted items without it. `prune` then returns
216
+ * the root unchanged.
217
+ */
218
+ readonly pruneOwnFile?: {
219
+ readonly kind: EntityKindId;
220
+ readonly prune: (items: readonly unknown[]) => readonly unknown[];
221
+ };
212
222
  }
213
223
  /**
214
224
  * Live configuration authored source cannot reproduce unchanged. Only its
@@ -9,4 +9,5 @@ export { decodeTemplateEscapes, encodeTemplateEscapes, quoteHclString } from "./
9
9
  export { parseExpression, parseStringValue, TfExprError } from "./expr.js";
10
10
  export { assertNoUnsafeIntegers, inspectBackendHcl, parseHcl, parseHclDocuments, TfParseError, type BackendHclInspection, } from "./parse.js";
11
11
  export { renderBlock, renderDocument } from "./render.js";
12
+ export { hclCodeLines, hclDepthDelta, hclStatementEnd, type HclCodeLine } from "./scan.js";
12
13
  export { appResourceLabelPrefix, appScopedResourceLabel, bareChildResourceLabel, childPartFromScopedLabel, elementResourceLabelPrefix, elementScopedResourceLabel, isCanonicalTsLabel, isTfLabel, isUuid, ownerFromScopedChildLabel, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, snakeSlug, splitCamelCase, stageHandleTfLabel, stableIdSuffix, tfLabelToTsLabel, tsLabelToTfLabel, taskResourceLabelPrefix, type ChildResourceScope, type FieldOwnerScope, } from "./labels.js";
@@ -8,4 +8,5 @@ export { decodeTemplateEscapes, encodeTemplateEscapes, quoteHclString } from "./
8
8
  export { parseExpression, parseStringValue, TfExprError } from "./expr.js";
9
9
  export { assertNoUnsafeIntegers, inspectBackendHcl, parseHcl, parseHclDocuments, TfParseError, } from "./parse.js";
10
10
  export { renderBlock, renderDocument } from "./render.js";
11
+ export { hclCodeLines, hclDepthDelta, hclStatementEnd } from "./scan.js";
11
12
  export { appResourceLabelPrefix, appScopedResourceLabel, bareChildResourceLabel, childPartFromScopedLabel, elementResourceLabelPrefix, elementScopedResourceLabel, isCanonicalTsLabel, isTfLabel, isUuid, ownerFromScopedChildLabel, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, snakeSlug, splitCamelCase, stageHandleTfLabel, stableIdSuffix, tfLabelToTsLabel, tsLabelToTfLabel, taskResourceLabelPrefix, } from "./labels.js";
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Lexical line view of HCL source for the text rewriters that must leave every
3
+ * untouched byte as ei wrote it. It locates structure only; it never parses
4
+ * values. Braces, brackets, `#`, and `resource "…"` inside a quoted string,
5
+ * a heredoc body (`<<EOT` / `<<-EOT`, e.g. execute-script JavaScript), a
6
+ * `${…}` / `%{…}` template hole, or a comment are not code.
7
+ */
8
+ /** One source line. `code` keeps only top-level code, with each string or heredoc reduced to `""`. */
9
+ export interface HclCodeLine {
10
+ readonly text: string;
11
+ readonly code: string;
12
+ /** The line begins in top-level code, not inside a string, heredoc, hole, or block comment. */
13
+ readonly startsInCode: boolean;
14
+ }
15
+ export declare function hclCodeLines(text: string): HclCodeLine[];
16
+ /** `{`/`}` and `[`/`]` depth change of a line's code. */
17
+ export declare function hclDepthDelta(line: HclCodeLine): {
18
+ readonly braces: number;
19
+ readonly brackets: number;
20
+ };
21
+ /** Index of the last line of the statement starting at `start`: a value that opens a heredoc or block comment runs past its own line. */
22
+ export declare function hclStatementEnd(lines: readonly HclCodeLine[], start: number): number;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Lexical line view of HCL source for the text rewriters that must leave every
3
+ * untouched byte as ei wrote it. It locates structure only; it never parses
4
+ * values. Braces, brackets, `#`, and `resource "…"` inside a quoted string,
5
+ * a heredoc body (`<<EOT` / `<<-EOT`, e.g. execute-script JavaScript), a
6
+ * `${…}` / `%{…}` template hole, or a comment are not code.
7
+ */
8
+ const HEREDOC_OPENER = /^<<-?([A-Za-z_][A-Za-z0-9_-]*)\r?$/;
9
+ export function hclCodeLines(text) {
10
+ const stack = [];
11
+ let inBlockComment = false;
12
+ const out = [];
13
+ for (const line of text.split("\n")) {
14
+ const top = stack.at(-1);
15
+ if (top?.kind === "heredoc" && line.trim() === top.marker) {
16
+ stack.pop();
17
+ out.push({ text: line, code: "", startsInCode: false });
18
+ continue;
19
+ }
20
+ const startsInCode = stack.length === 0 && !inBlockComment;
21
+ let code = "";
22
+ let i = 0;
23
+ while (i < line.length) {
24
+ const frame = stack.at(-1);
25
+ const ch = line[i];
26
+ if (inBlockComment) {
27
+ const end = line.indexOf("*/", i);
28
+ if (end === -1)
29
+ break;
30
+ inBlockComment = false;
31
+ i = end + 2;
32
+ continue;
33
+ }
34
+ if (frame?.kind === "string" || frame?.kind === "heredoc") {
35
+ if (frame.kind === "string" && ch === "\\") {
36
+ i += 2;
37
+ continue;
38
+ }
39
+ if ((ch === "$" || ch === "%") && line[i + 1] === ch && line[i + 2] === "{") {
40
+ i += 3;
41
+ continue;
42
+ }
43
+ if ((ch === "$" || ch === "%") && line[i + 1] === "{") {
44
+ stack.push({ kind: "hole", depth: 0 });
45
+ i += 2;
46
+ continue;
47
+ }
48
+ if (frame.kind === "string" && ch === '"') {
49
+ stack.pop();
50
+ if (stack.length === 0)
51
+ code += '"';
52
+ }
53
+ i++;
54
+ continue;
55
+ }
56
+ if (ch === "#" || (ch === "/" && line[i + 1] === "/"))
57
+ break;
58
+ if (ch === "/" && line[i + 1] === "*") {
59
+ inBlockComment = true;
60
+ i += 2;
61
+ continue;
62
+ }
63
+ if (ch === '"') {
64
+ if (stack.length === 0)
65
+ code += '"';
66
+ stack.push({ kind: "string" });
67
+ i++;
68
+ continue;
69
+ }
70
+ if (ch === "<" && line[i + 1] === "<") {
71
+ const opener = HEREDOC_OPENER.exec(line.slice(i));
72
+ if (opener !== null) {
73
+ if (stack.length === 0)
74
+ code += '""';
75
+ stack.push({ kind: "heredoc", marker: opener[1] });
76
+ break;
77
+ }
78
+ }
79
+ if (frame?.kind === "hole") {
80
+ if (ch === "{")
81
+ frame.depth++;
82
+ if (ch === "}" && frame.depth-- === 0)
83
+ stack.pop();
84
+ }
85
+ else {
86
+ code += ch;
87
+ }
88
+ i++;
89
+ }
90
+ // A quoted string cannot span lines; closing it here keeps one malformed
91
+ // line from swallowing the rest of the file.
92
+ while (stack.at(-1)?.kind === "string") {
93
+ stack.pop();
94
+ if (stack.length === 0)
95
+ code += '"';
96
+ }
97
+ out.push({ text: line, code, startsInCode });
98
+ }
99
+ return out;
100
+ }
101
+ /** `{`/`}` and `[`/`]` depth change of a line's code. */
102
+ export function hclDepthDelta(line) {
103
+ let braces = 0;
104
+ let brackets = 0;
105
+ for (const ch of line.code) {
106
+ if (ch === "{")
107
+ braces++;
108
+ else if (ch === "}")
109
+ braces--;
110
+ else if (ch === "[")
111
+ brackets++;
112
+ else if (ch === "]")
113
+ brackets--;
114
+ }
115
+ return { braces, brackets };
116
+ }
117
+ /** Index of the last line of the statement starting at `start`: a value that opens a heredoc or block comment runs past its own line. */
118
+ export function hclStatementEnd(lines, start) {
119
+ let end = start;
120
+ while (end + 1 < lines.length && !lines[end + 1].startsInCode)
121
+ end++;
122
+ return end;
123
+ }
@@ -33,6 +33,14 @@ export interface WorkspaceLoader {
33
33
  default?: unknown;
34
34
  }>;
35
35
  }
36
+ export declare function setWorkspaceLoadGuard(guard: ((orgRoot: string) => void) | undefined): void;
37
+ /**
38
+ * Run the workspace load guard on `orgRoot` now, without loading anything.
39
+ * A command that loads source calls this before its first write (edk#1737):
40
+ * a guard failure inside a best-effort load can be caught and only logged,
41
+ * and by then the command may already have written files.
42
+ */
43
+ export declare function assertWorkspaceLoadable(orgRoot: string): void;
36
44
  /**
37
45
  * A loader scoped to one org root and one generation. Create one per build —
38
46
  * that is what makes a rebuild see edited files.
@@ -352,12 +352,32 @@ function createJitiLoader(root) {
352
352
  },
353
353
  };
354
354
  }
355
+ /**
356
+ * A check run on an org root before any of its source is loaded (edk#1737).
357
+ * The CLI sets it to the installed-SDK compatibility check; it throws to stop
358
+ * the load. Set from outside because this module can only import `node:`
359
+ * builtins (see IMPORTING_FILE_KEY).
360
+ */
361
+ let workspaceLoadGuard;
362
+ export function setWorkspaceLoadGuard(guard) {
363
+ workspaceLoadGuard = guard;
364
+ }
365
+ /**
366
+ * Run the workspace load guard on `orgRoot` now, without loading anything.
367
+ * A command that loads source calls this before its first write (edk#1737):
368
+ * a guard failure inside a best-effort load can be caught and only logged,
369
+ * and by then the command may already have written files.
370
+ */
371
+ export function assertWorkspaceLoadable(orgRoot) {
372
+ workspaceLoadGuard?.(canonical(resolve(orgRoot)));
373
+ }
355
374
  /**
356
375
  * A loader scoped to one org root and one generation. Create one per build —
357
376
  * that is what makes a rebuild see edited files.
358
377
  */
359
378
  export function createWorkspaceLoader(orgRoot) {
360
379
  const root = canonical(resolve(orgRoot));
380
+ workspaceLoadGuard?.(root);
361
381
  if (registerHooks === undefined)
362
382
  return createJitiLoader(root);
363
383
  activeRoots.add(root);
@@ -53,17 +53,19 @@ export interface AgentToTfResult {
53
53
  * first occurrence of a sanitized name the bare label, each later
54
54
  * occurrence `_1`, `_2`, …
55
55
  *
56
- * Ascending-by-agent-NAME confirmed live 2026-08-18 against real committed
57
- * state on a deployed app (two identically-named a2a skills added via the
58
- * platform UI to two different agents): "Default agent 2" landed at the
59
- * bare label, "test agent" at `_1` — `D` < `t`, matching the assumed sort.
60
- * A weaker signal than #310's skill-tool capture (that one deliberately
61
- * reordered 3 skills' creation vs. name to rule out creation-order as an
62
- * alternative explanation; this one only has 2 agents, so an
63
- * agent-creation-order coincidence can't be fully excluded) — but real
64
- * evidence from `ei`'s own exporter/import-address generation, not a
65
- * guess. If a future capture contradicts it, only this function's sort
66
- * needs to change — the suffix-assignment mechanics stay the same.
56
+ * The order is shared with ei: agent name by UTF-16 code unit, then (for
57
+ * identical names) refName here and the agent's own label in ei, whose `_N`
58
+ * tails sort alike. The Go comparator is in the a2a loop of
59
+ * `cmd/elementum/export/imports.go` (`compareUTF16`, `agentChildParts`),
60
+ * and the two must stay in sync; changing one without the other moves
61
+ * `agent_id` and replaces skills on the first plan after a pull (edk#1728).
62
+ * Before edk#1728 ei walked agents in id order.
63
+ *
64
+ * The 2026-08-18 two-agent live capture ("Default agent 2" at the bare
65
+ * label, "test agent" at `_1`) is not evidence for name order: id order
66
+ * and name order happened to agree there, which edk#1728 disproved. The
67
+ * contract above is what fixes the order.
68
+ *
67
69
  * Ordering of a2a skills WITHIN one agent is still assumed to be authored
68
70
  * array order, unconfirmed live either way.
69
71
  *
@@ -255,17 +255,19 @@ function toSortableAgents(entities) {
255
255
  * first occurrence of a sanitized name the bare label, each later
256
256
  * occurrence `_1`, `_2`, …
257
257
  *
258
- * Ascending-by-agent-NAME confirmed live 2026-08-18 against real committed
259
- * state on a deployed app (two identically-named a2a skills added via the
260
- * platform UI to two different agents): "Default agent 2" landed at the
261
- * bare label, "test agent" at `_1` — `D` < `t`, matching the assumed sort.
262
- * A weaker signal than #310's skill-tool capture (that one deliberately
263
- * reordered 3 skills' creation vs. name to rule out creation-order as an
264
- * alternative explanation; this one only has 2 agents, so an
265
- * agent-creation-order coincidence can't be fully excluded) — but real
266
- * evidence from `ei`'s own exporter/import-address generation, not a
267
- * guess. If a future capture contradicts it, only this function's sort
268
- * needs to change — the suffix-assignment mechanics stay the same.
258
+ * The order is shared with ei: agent name by UTF-16 code unit, then (for
259
+ * identical names) refName here and the agent's own label in ei, whose `_N`
260
+ * tails sort alike. The Go comparator is in the a2a loop of
261
+ * `cmd/elementum/export/imports.go` (`compareUTF16`, `agentChildParts`),
262
+ * and the two must stay in sync; changing one without the other moves
263
+ * `agent_id` and replaces skills on the first plan after a pull (edk#1728).
264
+ * Before edk#1728 ei walked agents in id order.
265
+ *
266
+ * The 2026-08-18 two-agent live capture ("Default agent 2" at the bare
267
+ * label, "test agent" at `_1`) is not evidence for name order: id order
268
+ * and name order happened to agree there, which edk#1728 disproved. The
269
+ * contract above is what fixes the order.
270
+ *
269
271
  * Ordering of a2a skills WITHIN one agent is still assumed to be authored
270
272
  * array order, unconfirmed live either way.
271
273
  *
@@ -281,7 +283,10 @@ function toSortableAgents(entities) {
281
283
  * the #294 case this disambiguates.
282
284
  */
283
285
  export function computeA2ASkillLabelSuffixes(siblingAgents) {
284
- const sorted = toSortableAgents(siblingAgents).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
286
+ // Ties (identical agent names) break on refName, whose `_N` tail is the
287
+ // export label's; ei breaks them on that label (edk#1728).
288
+ const order = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
289
+ const sorted = toSortableAgents(siblingAgents).sort((a, b) => order(a.name, b.name) || order(a.refName, b.refName));
285
290
  const counts = new Map();
286
291
  const suffixes = new Map();
287
292
  for (const agent of sorted) {
@@ -452,7 +452,7 @@ function executeWorkflowFromTf(block, name, where, owner, ctx) {
452
452
  }
453
453
  inputs.push({
454
454
  parameterName: rec["parameter_name"],
455
- ...(typeof rec["name"] === "string" && { name: rec["name"] }),
455
+ ...(typeof rec["display_name"] === "string" && { name: rec["display_name"] }),
456
456
  ...(typeof rec["description"] === "string" && { description: rec["description"] }),
457
457
  ...(typeof rec["required"] === "boolean" && { required: rec["required"] }),
458
458
  });
@@ -466,7 +466,7 @@ function executeWorkflowFromTf(block, name, where, owner, ctx) {
466
466
  }
467
467
  outputs.push({
468
468
  workflowPropertyName: rec["workflow_property_name"],
469
- ...(typeof rec["name"] === "string" && { name: rec["name"] }),
469
+ ...(typeof rec["display_name"] === "string" && { name: rec["display_name"] }),
470
470
  ...(typeof rec["description"] === "string" && { description: rec["description"] }),
471
471
  });
472
472
  }
@@ -255,6 +255,12 @@ export function toolToTf(entry, ctx) {
255
255
  if (inner.inputs !== undefined && inner.inputs.length > 0) {
256
256
  attrs["inputs"] = inner.inputs.map((i) => ({
257
257
  parameter_name: i.triggerParameterId?.name ?? "",
258
+ // The provider reads display_name back only when the agent-facing
259
+ // name differs from the parameter name (null otherwise), so emit it
260
+ // under the same rule or the plan drops the rename (#1734).
261
+ ...(i.name !== undefined &&
262
+ i.name !== "" &&
263
+ i.name !== i.triggerParameterId?.name && { display_name: i.name }),
258
264
  ...(i.description !== undefined && i.description !== "" && { description: i.description }),
259
265
  ...(i.required !== undefined && { required: i.required }),
260
266
  }));
@@ -262,6 +268,9 @@ export function toolToTf(entry, ctx) {
262
268
  if (inner.outputs !== undefined && inner.outputs.length > 0) {
263
269
  attrs["outputs"] = inner.outputs.map((o) => ({
264
270
  workflow_property_name: o.workflowPropertyName ?? "",
271
+ ...(o.name !== undefined &&
272
+ o.name !== "" &&
273
+ o.name !== o.workflowPropertyName && { display_name: o.name }),
265
274
  ...(o.description !== undefined && o.description !== "" && { description: o.description }),
266
275
  }));
267
276
  }
@@ -387,6 +387,12 @@ export interface NormalizedApp {
387
387
  readonly layouts?: readonly NormalizedLayout[];
388
388
  /** Saved list views (`elementum_list_view`). */
389
389
  readonly listViews?: readonly NormalizedListView[];
390
+ /**
391
+ * Platform ids pull kept in view field references because it did not
392
+ * extract their field (#1736). Print marks them as intentional instead of
393
+ * #1178's "replace with a real ref" TODO, which would drop the column.
394
+ */
395
+ readonly unextractedFieldIds?: readonly string[];
390
396
  /** Calendar views (`elementum_calendar_view`). */
391
397
  readonly calendarViews?: readonly NormalizedCalendarView[];
392
398
  /** Kanban views (`elementum_kanban_view`). */
@@ -216,10 +216,13 @@ export function appFromTf(appBlock, fieldBlocks, ctx, viewBlocks = { layoutBlock
216
216
  const stageHandles = stageHandleIndex(stages.map((stage) => ({ key: stage.key, name: stage.stage.name })), ctx.diagnostics);
217
217
  // --- View pass: layouts / list views / view order (entities/view), owner passed in.
218
218
  const dashboards = dashboardsFromTf(viewBlocks.dashboardBlocks, viewBlocks.dashboardWidgetBlocks, { type: APP_RESOURCE_TYPE, label, ownerTfLabel: refName, ownerRefName: refName, scope: "app", ownerType: "APP_ASPECT" }, ctx);
219
+ const unextractedFieldIds = new Set();
219
220
  const { layouts, listViews, calendarViews, kanbanViews, dashboardViews, agentViews, customViews, viewOrder } = viewsFromTf(viewBlocks.layoutBlocks, viewBlocks.listViewBlocks, viewBlocks.calendarViewBlocks, viewBlocks.kanbanViewBlocks, viewBlocks.dashboardViewBlocks, viewBlocks.agentViewBlocks, viewBlocks.managedViewOrderBlocks, {
220
221
  type: APP_RESOURCE_TYPE, label, ownerTfLabel: label, scope: "app",
221
222
  stageKeys: stageHandles.keys,
222
223
  stageKeyByHandle: stageHandles.byHandle,
224
+ fieldKeys: new Set(fields.map((field) => field.key)),
225
+ unextractedFieldIds,
223
226
  }, ctx, viewBlocks.customViewBlocks);
224
227
  if (viewBlocks.recordCreateFormBlocks.length > 1) {
225
228
  ctx.diagnostics.push(`app "${label}": found ${viewBlocks.recordCreateFormBlocks.length} record create forms; only the first is used`);
@@ -268,6 +271,7 @@ export function appFromTf(appBlock, fieldBlocks, ctx, viewBlocks = { layoutBlock
268
271
  ...(autoShare !== undefined && { autoShare }),
269
272
  ...(layouts.length > 0 && { layouts }),
270
273
  ...(listViews.length > 0 && { listViews }),
274
+ ...(unextractedFieldIds.size > 0 && { unextractedFieldIds: [...unextractedFieldIds] }),
271
275
  ...(calendarViews.length > 0 && { calendarViews }),
272
276
  ...(kanbanViews.length > 0 && { kanbanViews }),
273
277
  ...(dashboardViews.length > 0 && { dashboardViews }),
@@ -29,7 +29,7 @@ import { valid as validSemver } from "semver";
29
29
  import { EntityTfError } from "../../engine/entity.js";
30
30
  import { isOnDemandRecordType } from "../shared/types/field-types.js";
31
31
  import { buildContext, createForEachItemProxy } from "../shared/context.js";
32
- import { outputFieldTypesFromScriptSchema } from "./output-field-types.js";
32
+ import { outputFieldTypesFromScriptSchema, scriptSchemaIsSingleStringArray } from "./output-field-types.js";
33
33
  import { isRef } from "../shared/ref.js";
34
34
  import { API_TASK_REF_WIRE_NAMES, OUTPUT_KEY_CANONICAL, OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
35
35
  import { extractScriptBody, inferOutputSchema, isScriptFile, readScriptFile, toPlatformScriptBody, tryExtractFromCurrentSource } from "./script-code.js";
@@ -286,8 +286,18 @@ function assertKnownScriptOutput(name, taskRefKey, schema, checkDeclaredResult)
286
286
  throw new EntityTfError(`executeScript${taskRefKey === undefined ? "" : ` task "${taskRefKey}"`} has no output "${name}"; ` +
287
287
  `declared result properties are ${listed === "" ? "(none)" : listed}.`);
288
288
  }
289
+ // Only suggest reads that exist: a `.result.<name>` the schema doesn't declare
290
+ // builds in a filter but reads nothing at runtime (#1725).
291
+ const declared = declaredScriptResultProperties(schema);
292
+ const missing = declared !== undefined && !declared.has(name.split(".")[0] ?? "");
293
+ const at = `ctx.actions.${taskRefKey ?? "<script>"}`;
294
+ const uses = missing ? [...declared].map((p) => `${at}.result.${p}`) : [`${at}.result.${name}`];
295
+ if ((missing || !name.includes(".")) && scriptSchemaIsSingleStringArray(schema))
296
+ uses.push(`${at}.stringArrayResult`);
289
297
  throw new EntityTfError(`executeScript${taskRefKey === undefined ? "" : ` task "${taskRefKey}"`} has no output "${name}"; ` +
290
- `script outputs are read under result. Use ctx.actions.${taskRefKey ?? "<script>"}.result.${name}.`);
298
+ `script outputs are read under result` +
299
+ (missing ? ` and the declared result properties are ${declared.size === 0 ? "(none)" : [...declared].join(", ")}` : "") +
300
+ (uses.length > 0 ? `. Use ${uses.join(" or ")}.` : "."));
291
301
  }
292
302
  /**
293
303
  * Forward output-name rewrites, the inverse of the deserializer's read-side
@@ -147,8 +147,8 @@ function lostStageApprovalChains(stream, ctx) {
147
147
  }
148
148
  return lost;
149
149
  }
150
- /** The first of `chains` that any block at `owned` references, if any. */
151
- function referencedLostChain(stream, owned, chains) {
150
+ /** The first of `targets` that any block at `owned` references, if any. */
151
+ function referencedAddress(stream, owned, targets) {
152
152
  const ownedSet = new Set(owned);
153
153
  const visit = (value) => {
154
154
  if (Array.isArray(value)) {
@@ -164,7 +164,7 @@ function referencedLostChain(stream, owned, chains) {
164
164
  const record = value;
165
165
  if (record["$expr"] === "resource-attr" && typeof record["type"] === "string" && typeof record["label"] === "string") {
166
166
  const address = `${record["type"]}.${record["label"]}`;
167
- if (chains.has(address))
167
+ if (targets.has(address))
168
168
  return address;
169
169
  }
170
170
  for (const item of Object.values(record)) {
@@ -190,6 +190,7 @@ function extractAutomations(ownBlocks, stream, ctx) {
190
190
  const quarantineOwnFiles = [];
191
191
  const diagnostics = [];
192
192
  const adoptionAddressAliases = [];
193
+ const extractedAutomations = [];
193
194
  const lostChains = lostStageApprovalChains(stream, ctx);
194
195
  for (const autoBlock of ownBlocks) {
195
196
  const autoLabel = autoBlock.label ?? "";
@@ -203,7 +204,7 @@ function extractAutomations(ownBlocks, stream, ctx) {
203
204
  // automation with a warning and release an earlier adoption of it.
204
205
  if (lostChains.size > 0) {
205
206
  const owned = automationOwnedAddresses(doc, autoLabel);
206
- const chain = referencedLostChain(stream, owned, lostChains);
207
+ const chain = referencedAddress(stream, owned, lostChains);
207
208
  if (chain !== undefined) {
208
209
  skipped.push(...owned);
209
210
  releaseIfManaged.push(...owned);
@@ -225,13 +226,7 @@ function extractAutomations(ownBlocks, stream, ctx) {
225
226
  diagnostics.push(droppedAutomationGap(autoBlock, autoLabel, "the export embeds a stringified ValueReference that source cannot rebuild to match provider Read (edk#1646). It stays platform-managed, and its authored file is archived so the next plan does not create a duplicate."));
226
227
  continue;
227
228
  }
228
- // Keep automationFromTf's label-derived refName — agent/skill tools store
229
- // the same scopedLabelToBagKey as automationKey. Pushing bare AST (name
230
- // only) made missing-automation diagnostics false-positive on every real
231
- // extract (issue #395 / PR #417 review).
232
- items.push({ ...extracted.ast, refName: extracted.refName });
233
- adoptionAddressAliases.push(...extracted.adoptionAddressAliases);
234
- diagnostics.push(...(extracted.diagnostics ?? []).map((diagnostic) => `${autoLabel}: ${diagnostic}`));
229
+ extractedAutomations.push({ autoBlock, autoLabel, owned: automationOwnedAddresses(doc, autoLabel), extracted });
235
230
  }
236
231
  catch (err) {
237
232
  // Report the automation's FULL graph (trigger/tasks/branches/publish),
@@ -262,6 +257,38 @@ function extractAutomations(ownBlocks, stream, ctx) {
262
257
  diagnostics.push(droppedAutomationGap(autoBlock, autoLabel, err instanceof Error ? err.message : String(err)));
263
258
  }
264
259
  }
260
+ // An automation that runs a skipped automation (or reads its trigger's
261
+ // parameter ids) would print a ref to an automation source never gets, and
262
+ // its export would keep a reference to a resource adoption strips. Skip it
263
+ // too, transitively, and release it only when its target was released.
264
+ const kept = new Set(extractedAutomations);
265
+ for (let cascaded = true; cascaded;) {
266
+ cascaded = false;
267
+ const skippedAddresses = new Set(skipped);
268
+ const releasedAddresses = new Set(releaseIfManaged);
269
+ for (const entry of kept) {
270
+ const target = referencedAddress(stream, entry.owned, skippedAddresses);
271
+ if (target === undefined)
272
+ continue;
273
+ kept.delete(entry);
274
+ cascaded = true;
275
+ skipped.push(...entry.owned);
276
+ if (releasedAddresses.has(target)) {
277
+ releaseIfManaged.push(...entry.owned);
278
+ quarantineOwnFiles.push({ kind: "automation", refName: entry.extracted.refName });
279
+ }
280
+ diagnostics.push(droppedAutomationGap(entry.autoBlock, entry.autoLabel, `it references ${target}, which is skipped, so the reference would dangle`));
281
+ }
282
+ }
283
+ for (const { autoLabel, extracted } of kept) {
284
+ // Keep automationFromTf's label-derived refName — agent/skill tools store
285
+ // the same scopedLabelToBagKey as automationKey. Pushing bare AST (name
286
+ // only) made missing-automation diagnostics false-positive on every real
287
+ // extract (issue #395 / PR #417 review).
288
+ items.push({ ...extracted.ast, refName: extracted.refName });
289
+ adoptionAddressAliases.push(...extracted.adoptionAddressAliases);
290
+ diagnostics.push(...(extracted.diagnostics ?? []).map((diagnostic) => `${autoLabel}: ${diagnostic}`));
291
+ }
265
292
  // A trigger, task, or publish with no automation resource is not in any
266
293
  // skeleton's graph. extractAutomations never sees it, and its resource type
267
294
  // is still adoptable, so the next plan can destroy it (#1484). Soft-skip
@@ -385,6 +412,7 @@ export const automationModule = {
385
412
  fieldMetadata: ctx.fieldMetadata ?? new Map(),
386
413
  ...(ctx.fieldNamesByAppRefName !== undefined ? { fieldNamesByAppRefName: ctx.fieldNamesByAppRefName } : {}),
387
414
  ...(ctx.fieldAddressesByAppRefName !== undefined ? { fieldAddressesByAppRefName: ctx.fieldAddressesByAppRefName } : {}),
415
+ ...(ctx.authoredAspectKeys !== undefined ? { authoredAspectKeys: ctx.authoredAspectKeys } : {}),
388
416
  ...(ctx.allowUnknownPicklistOptions === true ? { allowUnknownPicklistOptions: true } : {}),
389
417
  orgRefs: ctx.orgRefs,
390
418
  workspaceAspects: ctx.workspaceAspects,
@@ -10,6 +10,14 @@
10
10
  * dependency-free like `output-key-wire-name.ts` so importing it from
11
11
  * either side can never introduce a cycle.
12
12
  */
13
+ /**
14
+ * True when the schema's only top-level property is a TEXT list (a format-less
15
+ * or EMAIL/UUID4 string array). The runtime then also fills
16
+ * `stringArrayResult` with it (#1725 live repro). DATE/DATETIME and object
17
+ * arrays don't count, and an unwrapped `{ properties }` root is no schema, as
18
+ * in build's `declaredScriptResultProperties`.
19
+ */
20
+ export declare function scriptSchemaIsSingleStringArray(schema: unknown): boolean;
13
21
  /** Map executeScript output_schema properties to refs keys (`result.<name>`). */
14
22
  export declare function outputFieldTypesFromScriptSchema(schema: unknown): Map<string, {
15
23
  fieldType: string;
@@ -27,6 +27,26 @@ function stringFormatFieldType(format) {
27
27
  return format;
28
28
  return "TEXT";
29
29
  }
30
+ /**
31
+ * True when the schema's only top-level property is a TEXT list (a format-less
32
+ * or EMAIL/UUID4 string array). The runtime then also fills
33
+ * `stringArrayResult` with it (#1725 live repro). DATE/DATETIME and object
34
+ * arrays don't count, and an unwrapped `{ properties }` root is no schema, as
35
+ * in build's `declaredScriptResultProperties`.
36
+ */
37
+ export function scriptSchemaIsSingleStringArray(schema) {
38
+ if (!isObject(schema) || !isObject(schema.object))
39
+ return false;
40
+ const properties = schema.object.properties;
41
+ if (!Array.isArray(properties) || properties.length !== 1 || !isObject(properties[0]))
42
+ return false;
43
+ const array = properties[0].array;
44
+ if (!isObject(array) || !isObject(array.item) || !("string" in array.item))
45
+ return false;
46
+ const declared = [...(outputFieldTypesFromScriptSchema(schema) ?? [])].filter(([key]) => key.startsWith("result."));
47
+ const type = declared.length === 1 ? declared[0][1] : undefined;
48
+ return type?.kind === "array" && type.fieldType === "TEXT";
49
+ }
30
50
  /** Map executeScript output_schema properties to refs keys (`result.<name>`). */
31
51
  export function outputFieldTypesFromScriptSchema(schema) {
32
52
  if (!isObject(schema))
@@ -45,6 +45,8 @@ export declare const OUTPUT_KEY_CANONICAL: Readonly<Record<string, string>>;
45
45
  * onto `.output` too and rebuild it as `refs["text"]`.
46
46
  */
47
47
  export declare function matchesOutputWireKey(segment: string, wireKey: string): boolean;
48
+ /** refs-map key for one AI completion task output, or undefined when `name` is not one. */
49
+ export declare function aiCompletionRefsIndex(resourceType: string, name: string): string | undefined;
48
50
  /**
49
51
  * apiRequest task outputs in authoring use camelCase segments (`statusCode`,
50
52
  * `file.content`, …) but the provider refs map uses display labels — confirmed
@@ -56,6 +56,24 @@ export const OUTPUT_KEY_CANONICAL = {
56
56
  export function matchesOutputWireKey(segment, wireKey) {
57
57
  return segment === wireKey || segment === wireKey.toLowerCase();
58
58
  }
59
+ /**
60
+ * AI completion task outputs: canonical (`service_tasks`) name → refs-map key.
61
+ * The provider's `refs` map is Title-Case (`Response`, `Success`, and
62
+ * aiClassify's `Reason`; see {@link OUTPUT_KEY_WIRE_NAME}), but a switch
63
+ * case's stored envelope names the output in lowercase, so pull prints
64
+ * `.success` and build must index `refs["Success"]` (edk#1730: Sanofi
65
+ * conciergeforfield plan failed with "Invalid index" on `refs["success"]`).
66
+ * Exact canonical names only; a Title-Case key passes through unchanged.
67
+ */
68
+ const AI_COMPLETION_REFS_INDEX = {
69
+ elementum_ai_classify_task: { response: "Response", reason: "Reason", success: "Success" },
70
+ elementum_ai_summarize_task: { response: "Response", success: "Success" },
71
+ elementum_ai_transform_task: { response: "Response", success: "Success" },
72
+ };
73
+ /** refs-map key for one AI completion task output, or undefined when `name` is not one. */
74
+ export function aiCompletionRefsIndex(resourceType, name) {
75
+ return AI_COMPLETION_REFS_INDEX[resourceType]?.[name];
76
+ }
59
77
  /**
60
78
  * apiRequest task outputs in authoring use camelCase segments (`statusCode`,
61
79
  * `file.content`, …) but the provider refs map uses display labels — confirmed
@@ -33,6 +33,13 @@ export interface AutomationToTfContext {
33
33
  * searched aspect's own `<resource>.<label>.id` to interpolate.
34
34
  */
35
35
  readonly fieldAddressesByAppRefName?: ReadonlyMap<string, ReadonlyMap<string, string>>;
36
+ /**
37
+ * Every app/element authored in the workspace, keyed by
38
+ * `workspaceAspectKey`, including those this build leaves out (pull builds
39
+ * only the pulled root). A calculation over such a sibling's found record
40
+ * addresses the field by data lookup.
41
+ */
42
+ readonly authoredAspectKeys?: ReadonlySet<string>;
36
43
  /** Build-time tolerance for stale labels retained by pulled automations. */
37
44
  readonly allowUnknownPicklistOptions?: boolean;
38
45
  readonly orgRefs?: OrgRefLookup;