@uipath/maestro-builder-sdk 6.111.0 → 6.113.0

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.
@@ -310,6 +310,7 @@ export declare const REFUSALS: {
310
310
  readonly DUP_STAGE: "lowering";
311
311
  readonly DUP_STEP: "lowering";
312
312
  readonly DUP_TASK: "lowering";
313
+ readonly ELK_UNAVAILABLE: "lowering";
313
314
  readonly EMPTY_ARM: "lint";
314
315
  readonly EMPTY_LOOP: "lint";
315
316
  readonly EMPTY_REQUIRED_FIELD: "lint";
@@ -566,6 +567,7 @@ export declare const REFUSALS: {
566
567
  readonly JSON_REF_UNREADABLE: "lowering";
567
568
  readonly JS_ESCAPE_COOKED: "lint";
568
569
  readonly JS_ESCAPE_INVALID: "lint";
570
+ readonly LAYOUT_AUTO_FAILED: "lowering";
569
571
  readonly LAYOUT_EDGE_AMBIGUOUS: "lowering";
570
572
  readonly LAYOUT_EDGE_KEY_FORM: "lowering";
571
573
  readonly LAYOUT_UNKNOWN_KEY: "lowering";
@@ -384,6 +384,7 @@ export const REFUSALS = {
384
384
  DUP_STAGE: 'lowering',
385
385
  DUP_STEP: 'lowering',
386
386
  DUP_TASK: 'lowering',
387
+ ELK_UNAVAILABLE: 'lowering',
387
388
  EMPTY_ARM: 'lint',
388
389
  EMPTY_LOOP: 'lint',
389
390
  EMPTY_REQUIRED_FIELD: 'lint',
@@ -642,6 +643,7 @@ export const REFUSALS = {
642
643
  JSON_REF_UNREADABLE: 'lowering',
643
644
  JS_ESCAPE_COOKED: 'lint',
644
645
  JS_ESCAPE_INVALID: 'lint',
646
+ LAYOUT_AUTO_FAILED: 'lowering',
645
647
  LAYOUT_EDGE_AMBIGUOUS: 'lowering',
646
648
  LAYOUT_EDGE_KEY_FORM: 'lowering',
647
649
  LAYOUT_UNKNOWN_KEY: 'lowering',
@@ -27,10 +27,16 @@
27
27
  * (`<Name>.pipeline.mjs`) that chains decompile → [edit] → compile → merge, so an
28
28
  * agent can run one script for the whole brownfield write-back loop. Pass
29
29
  * `--no-pipeline` to skip it.
30
+ *
31
+ * A decompile starts a new loop, so it first removes what an earlier loop
32
+ * compiled for the same `<Name>` into the work directory: `<Name>.baseline/`,
33
+ * `<Name>.edited/`, `<Name>.merged.flow` and the agent folders that candidate
34
+ * named (pipeline-artifacts.ts, #1995). Each is listed (`deleted` in `--json`, as
35
+ * merge reports it). A `<Name>.merged.flow` that differs from the original is kept.
30
36
  */
31
37
  import { reportResult } from './cli-result.js';
32
38
  import { mkdirSync, writeFileSync } from 'node:fs';
33
- import { basename, join, resolve } from 'node:path';
39
+ import { basename, join, relative, resolve } from 'node:path';
34
40
  import { defaultSourceOut, workDirBeside, writeSource } from './workdir.js';
35
41
  import { decompileFlowFile, readFlowFile } from './decompile-file.js';
36
42
  import { sourceDigest, stampFlowSource } from './decompile-stamp.js';
@@ -42,6 +48,7 @@ import { pipelineFrontDoor } from './registry/uip/pipeline-front-door.js';
42
48
  import { flowConnectorRequests, lackedToken } from './registry/fetch/flow-requests.js';
43
49
  import { openWithFetchedDefinitions } from './registry/fetch/with-fetched-definitions.js';
44
50
  import { fetchableNodeType } from './registry/fetch/fetch-definitions.js';
51
+ import { clearPipelineArtifacts } from './pipeline-artifacts.js';
45
52
  /** Derive a PascalCase base name from the flow name/id for the default output file. */
46
53
  function baseName(flow) {
47
54
  const src = flow.name ?? flow.id ?? 'Flow';
@@ -71,7 +78,8 @@ export async function run(argv) {
71
78
  // A `.flow` may be SPLIT across sibling files with JSON Reference — resolve
72
79
  // those into one object model before decompiling (design §5; the format's own
73
80
  // read path does the same). A single-file flow walks through untouched.
74
- const flow = readFlowFile(pos);
81
+ const inputParts = [];
82
+ const flow = readFlowFile(pos, inputParts);
75
83
  // Node-type packages the file needs: loaded only when the project trusts them
76
84
  // (package.json nodePackages, or --package), resolved from the .flow's own
77
85
  // directory (node-packages.ts). An untrusted or missing package is a warning,
@@ -135,11 +143,24 @@ export async function run(argv) {
135
143
  writeSource(out, stamped);
136
144
  console.log(`flow-decompile: wrote ${basename(out)}`);
137
145
  reportResult({ path: resolve(out) });
146
+ // The helper and the baseline/edited/merged candidates it writes are never
147
+ // shipped, so they go in the work directory even when `-o` put the source
148
+ // somewhere visible.
149
+ const workDir = workDirBeside(out);
150
+ // A new source starts a new loop: the compiles an earlier loop left for this
151
+ // flow in the work directory are stale, and inside a Flow project each `.flow`
152
+ // among them is one more deliverable to product validation (#1995). Cleared
153
+ // with or without the pipeline: `--no-pipeline` loops left them too.
154
+ // Never the file this decompile read, nor a folder holding it, nor a part file it $ref'd.
155
+ const cleared = clearPipelineArtifacts(workDir, basename(out).replace(/\.flow\.ts$|\.ts$/, ''), { keep: [pos, ...inputParts], original: flow });
156
+ for (const a of cleared.removed)
157
+ console.log(`flow-decompile: removed ${relativeShown(a.path)} (${a.reason}; this decompile starts a new loop)`);
158
+ for (const a of cleared.kept)
159
+ console.error(`flow-decompile: warning: kept ${relativeShown(a.path)}: ${a.reason}. Delete it yourself if it is an earlier loop's compile: a .flow inside the project is a deliverable`);
160
+ // `deleted`, as merge reports what it deleted; merge's `removed` is what is left for the caller.
161
+ if (cleared.removed.length > 0)
162
+ reportResult({ deleted: cleared.removed.map((a) => resolve(a.path)) });
138
163
  if (!argv.includes('--no-pipeline')) {
139
- // The helper and the baseline/edited/merged candidates it writes are never
140
- // shipped, so they go in the work directory even when `-o` put the source
141
- // somewhere visible.
142
- const workDir = workDirBeside(out);
143
164
  mkdirSync(workDir, { recursive: true });
144
165
  const pipelinePath = join(workDir, basename(out).replace(/\.flow\.ts$|\.ts$/, '') + '.pipeline.mjs');
145
166
  writeFileSync(pipelinePath, pipelineScript(resolve(pos), resolve(out), resolve(pipelinePath)));
@@ -239,4 +260,8 @@ if (!existsSync(BASELINE)) {
239
260
  }
240
261
  `;
241
262
  }
263
+ /** `path` as the user's working directory spells it. */
264
+ function relativeShown(path) {
265
+ return relative(process.cwd(), resolve(path)) || path;
266
+ }
242
267
  runWhenInvokedDirectly(import.meta.url, 'flow-decompile', run);
package/dist/decompile.js CHANGED
@@ -48,6 +48,7 @@ import { contributionPort, forwardFanOut } from './core/definition-handles.js';
48
48
  import { STICKY_NOTE_TYPE } from './core/definitionless-node-types.js';
49
49
  import { bindingValueRows, referencedBindingNames } from './core/contribution-bindings.js';
50
50
  import { builtChainSource, chainStatements } from './core/builder-chain.js';
51
+ import { isMarkedPlaceholder } from './node-placement.js';
51
52
  /**
52
53
  * The trigger id of the flow currently being decompiled, so a reference through a
53
54
  * RENAMED trigger is still recognized as `input('x')` rather than falling back to
@@ -2801,6 +2802,16 @@ function layoutSeg(flow, nodes, edges) {
2801
2802
  return ins.length > 0 && !runAbsorbed.has(id) && ins.every((e) => ARTIFACT_PORTS.has(e.sourcePort));
2802
2803
  };
2803
2804
  const nodeEntries = [];
2805
+ const uiOf = (n) => ({ ...(n.ui ?? {}), ...(hoisted[n.id] ?? {}) });
2806
+ const placed = nodes.filter((n) => n.type !== STICKY_NOTE_TYPE && !renamed(n.id) && !unspelled(n.id) && uiOf(n).position !== undefined);
2807
+ // Compile lays a scope out only when its `.layout()` names none of its nodes. So
2808
+ // the marks may stand in for positions only while EVERY node is where compile put
2809
+ // it: then the source has no entries and compile lays the scope out the same way
2810
+ // again. Once any node is someone's (dragged or added on the canvas), the scope is
2811
+ // authored, compile would put every node with no entry on its placeholder row,
2812
+ // and so every node gets its entry. Example: drag one node of a laid-out flow in
2813
+ // Studio Web; the decompiled `.layout()` then names all of them, at their positions.
2814
+ const compilePlacedScope = placed.every((n) => isMarkedPlaceholder(uiOf(n)));
2804
2815
  for (const n of nodes) {
2805
2816
  // A sticky note carries its own geometry in `.stickyNotes()`; a layout entry
2806
2817
  // for it would be a second, competing source for the same coordinates.
@@ -2808,7 +2819,9 @@ function layoutSeg(flow, nodes, edges) {
2808
2819
  continue;
2809
2820
  if (renamed(n.id) || unspelled(n.id))
2810
2821
  continue;
2811
- const ui = { ...(n.ui ?? {}), ...(hoisted[n.id] ?? {}) };
2822
+ const ui = uiOf(n);
2823
+ if (compilePlacedScope && isMarkedPlaceholder(ui))
2824
+ continue;
2812
2825
  const pos = ui.position;
2813
2826
  if (!pos || typeof pos.x !== 'number' || typeof pos.y !== 'number')
2814
2827
  continue;
@@ -586,7 +586,7 @@ export interface NodeLayout {
586
586
  x: number;
587
587
  y: number;
588
588
  };
589
- /** Node size; omit to keep compile's 96 × 96. */
589
+ /** Node size; omit for the size of the node's canvas shape (a container 560 × 320, an inline agent 288 × 96, anything else 96 × 96). */
590
590
  size?: {
591
591
  width: number;
592
592
  height: number;
@@ -601,8 +601,9 @@ export interface NodeLayout {
601
601
  * @remarks
602
602
  * Positions are canvas pixels. A child's position inside a container is relative
603
603
  * to that container, as the designer stores it; the body of a loop starts inside
604
- * the container's padding, at `at(144, 96)`. The size, {@link dim}, is needed by
605
- * a container and by an inline agent; every other node is 96 × 96.
604
+ * the container's padding, at `at(144, 96)`. Without a size, {@link dim}, compile
605
+ * writes the size of the node's canvas shape: 560 × 320 for a container, 288 × 96
606
+ * for an inline agent, 96 × 96 for anything else.
606
607
  *
607
608
  * @example
608
609
  * **Lay out a main path on one row, with a side path below it**
@@ -619,7 +620,7 @@ export interface NodeLayout {
619
620
  *
620
621
  * @param x - The node's left edge on the canvas.
621
622
  * @param y - The node's top edge on the canvas.
622
- * @param size - The node's size; omit to keep compile's 96 × 96.
623
+ * @param size - The node's size; omit for its canvas shape's size.
623
624
  * @returns A {@link NodeLayout} to put in `.layout({ nodes })`.
624
625
  */
625
626
  export declare function at(x: number, y: number, size?: NodeLayout['size']): NodeLayout;
@@ -627,11 +628,12 @@ export declare function at(x: number, y: number, size?: NodeLayout['size']): Nod
627
628
  * A node's size on the canvas, in pixels — the third argument of {@link at}.
628
629
  *
629
630
  * @remarks
630
- * Compile writes 96 × 96 on every node and the designer draws the persisted
631
- * size, so a node whose canvas shape is larger needs one: a container (a loop
632
- * or a do-while body, drawn as a box around its children; `format` makes it
633
- * 560 × 320) and an inline agent (`dim(288, 96)`). Every other node is 96 × 96
634
- * and needs none.
631
+ * Needed only for a size other than the node's canvas shape's. Compile writes
632
+ * that size on every node {@link at} places without one, as
633
+ * `uip maestro flow format` does: 560 × 320 for a container (a loop or a
634
+ * do-while body, drawn as a box around its children), 288 × 96 for an inline
635
+ * agent, 96 × 96 for anything else. A container whose body is wider or taller
636
+ * than 560 × 320 needs its `dim()`.
635
637
  *
636
638
  * @example
637
639
  * **A loop wide enough for a three-step body, then an inline agent**
@@ -1329,14 +1331,17 @@ declare class FlowBuilder extends StepList {
1329
1331
  /**
1330
1332
  * Set designer layout — node positions/sizes and edge routes — keyed by the
1331
1333
  * flow's own logical ids (step names, the trigger id, `end`). Optional pure
1332
- * metadata: nothing here changes what the flow does, and omitting it leaves
1333
- * the serializer's default arrangement. Unknown keys fail compilation rather
1334
- * than being dropped.
1335
- *
1336
- * Without a layout, compile places every node on one row in emission order,
1337
- * which reads badly in the designer once a flow has a branch, an error path or
1338
- * a loop. {@link at} writes a node's entry from two numbers, and {@link dim}
1339
- * a container's size from two more.
1334
+ * metadata: nothing here changes what the flow does. Unknown keys fail
1335
+ * compilation rather than being dropped.
1336
+ *
1337
+ * Without a layout (no node entries), compile lays the flow out the way
1338
+ * `uip maestro flow format` does: left to right, branches on their own rows,
1339
+ * loop bodies inside their container, each node at its canvas shape's size, the
1340
+ * trigger at (256, 144). Each subflow is laid out on its own. With a layout,
1341
+ * every node it names goes where it says, and a node it leaves out stays on
1342
+ * compile's one-row placeholder (`x = 256 + 288 × index`), for `merge` to place.
1343
+ * {@link at} writes a node's entry from two numbers, and {@link dim} a size other
1344
+ * than its shape's from two more.
1340
1345
  *
1341
1346
  * @example
1342
1347
  * **Main path on one row, the error handler on the row below**
package/dist/flow-sdk.js CHANGED
@@ -163,8 +163,9 @@ export function parallelFork(options) {
163
163
  * @remarks
164
164
  * Positions are canvas pixels. A child's position inside a container is relative
165
165
  * to that container, as the designer stores it; the body of a loop starts inside
166
- * the container's padding, at `at(144, 96)`. The size, {@link dim}, is needed by
167
- * a container and by an inline agent; every other node is 96 × 96.
166
+ * the container's padding, at `at(144, 96)`. Without a size, {@link dim}, compile
167
+ * writes the size of the node's canvas shape: 560 × 320 for a container, 288 × 96
168
+ * for an inline agent, 96 × 96 for anything else.
168
169
  *
169
170
  * @example
170
171
  * **Lay out a main path on one row, with a side path below it**
@@ -181,7 +182,7 @@ export function parallelFork(options) {
181
182
  *
182
183
  * @param x - The node's left edge on the canvas.
183
184
  * @param y - The node's top edge on the canvas.
184
- * @param size - The node's size; omit to keep compile's 96 × 96.
185
+ * @param size - The node's size; omit for its canvas shape's size.
185
186
  * @returns A {@link NodeLayout} to put in `.layout({ nodes })`.
186
187
  */
187
188
  export function at(x, y, size) {
@@ -191,11 +192,12 @@ export function at(x, y, size) {
191
192
  * A node's size on the canvas, in pixels — the third argument of {@link at}.
192
193
  *
193
194
  * @remarks
194
- * Compile writes 96 × 96 on every node and the designer draws the persisted
195
- * size, so a node whose canvas shape is larger needs one: a container (a loop
196
- * or a do-while body, drawn as a box around its children; `format` makes it
197
- * 560 × 320) and an inline agent (`dim(288, 96)`). Every other node is 96 × 96
198
- * and needs none.
195
+ * Needed only for a size other than the node's canvas shape's. Compile writes
196
+ * that size on every node {@link at} places without one, as
197
+ * `uip maestro flow format` does: 560 × 320 for a container (a loop or a
198
+ * do-while body, drawn as a box around its children), 288 × 96 for an inline
199
+ * agent, 96 × 96 for anything else. A container whose body is wider or taller
200
+ * than 560 × 320 needs its `dim()`.
199
201
  *
200
202
  * @example
201
203
  * **A loop wide enough for a three-step body, then an inline agent**
@@ -909,14 +911,17 @@ class FlowBuilder extends StepList {
909
911
  /**
910
912
  * Set designer layout — node positions/sizes and edge routes — keyed by the
911
913
  * flow's own logical ids (step names, the trigger id, `end`). Optional pure
912
- * metadata: nothing here changes what the flow does, and omitting it leaves
913
- * the serializer's default arrangement. Unknown keys fail compilation rather
914
- * than being dropped.
915
- *
916
- * Without a layout, compile places every node on one row in emission order,
917
- * which reads badly in the designer once a flow has a branch, an error path or
918
- * a loop. {@link at} writes a node's entry from two numbers, and {@link dim}
919
- * a container's size from two more.
914
+ * metadata: nothing here changes what the flow does. Unknown keys fail
915
+ * compilation rather than being dropped.
916
+ *
917
+ * Without a layout (no node entries), compile lays the flow out the way
918
+ * `uip maestro flow format` does: left to right, branches on their own rows,
919
+ * loop bodies inside their container, each node at its canvas shape's size, the
920
+ * trigger at (256, 144). Each subflow is laid out on its own. With a layout,
921
+ * every node it names goes where it says, and a node it leaves out stays on
922
+ * compile's one-row placeholder (`x = 256 + 288 × index`), for `merge` to place.
923
+ * {@link at} writes a node's entry from two numbers, and {@link dim} a size other
924
+ * than its shape's from two more.
920
925
  *
921
926
  * @example
922
927
  * **Main path on one row, the error handler on the row below**
package/dist/merge-cli.js CHANGED
@@ -29,7 +29,12 @@
29
29
  * The original is read as decompile reads it, `$ref`s resolved (decompile-file.ts),
30
30
  * so a split `.flow` merges as one document and is written as one file, as compile
31
31
  * writes it. Written over the original, the files its `$ref`s named are no longer
32
- * read; each is listed (`unreferenced` in `--json`), as merge does not delete files.
32
+ * read, so merge deletes each (`deleted` in `--json`) when the original is in a Flow
33
+ * project (`project.uiproj` at or above it) and no other `.flow` in that project
34
+ * reads it (compared as files, not spellings). One another `.flow` reads is kept
35
+ * (`flow-merge: kept <part>: ...`) and listed nowhere; one merge cannot prove unused
36
+ * (outside a project, an unreadable `.flow`) or could not delete is listed
37
+ * (`unreferenced`), for the caller to delete.
33
38
  *
34
39
  * `--baseline-from <original.flow>` makes merge build the baseline itself
35
40
  * (decompile + compile, nothing written), and an edited `.flow.ts` makes merge
@@ -68,9 +73,11 @@
68
73
  * `SECOND_FLOW_IN_PROJECT` (project-flows.ts).
69
74
  *
70
75
  * Agent resources (#1221): a context or tool the edit adds or changes is written
71
- * beside the merged output too. One the edit REMOVES is listed, one
72
- * `flow-merge: remove <dir>` line each (and `removed` in `--json`), because
73
- * copying the candidate over the project cannot delete a file: delete those
76
+ * beside the merged output too. One the edit REMOVES is deleted when merge
77
+ * writes over the original (`flow-merge: deleted <dir>`, `deleted` in `--json`),
78
+ * unless another `.flow` in the project still uses it (#1995). Written to a
79
+ * candidate elsewhere, or when the host refuses the delete, it is listed instead,
80
+ * one `flow-merge: remove <dir>` line each (`removed` in `--json`): delete those
74
81
  * directories from the project. When the original sits in a Flow project
75
82
  * (`project.uiproj`), the project's `bindings_v2.json` is re-derived from the
76
83
  * merged flow and its agents, as compile does, and written beside the merged
@@ -78,16 +85,16 @@
78
85
  */
79
86
  import { diagnosticLine, reportCompileRefusal, reportDiagnostics, reportResult } from './cli-result.js';
80
87
  import { writeJsonFile } from './core/json-file.js';
81
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
88
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
82
89
  import { inlineAgentResources, mergeBindingsV2, projectBindingRows, refreshInlineAgentRows } from './bindings-v2.js';
83
90
  import { readBindingsV2, readInlineAgentFiles } from './bindings-v2-files.js';
84
91
  import { readSolutionProjects } from './solution-projects-files.js';
85
92
  import { basename, dirname, join, relative, resolve } from 'node:path';
86
93
  import { MergeRefusedError, mergeFlowWithSidecars } from './merge.js';
87
94
  import { sidecarSetFromList } from './merge-sidecars.js';
88
- import { isWithin } from './path-within.js';
95
+ import { isWithin, physicalPath } from './path-within.js';
89
96
  import { flowSources, projectMainFlow, resourceSourcesOfOtherFlows } from './project-resource-users.js';
90
- import { secondFlowWarning } from './project-flows.js';
97
+ import { flowProjectOf, projectFlowFiles, secondFlowWarning } from './project-flows.js';
91
98
  import { flagValue, flagValues, runWhenInvokedDirectly } from './cli-run.js';
92
99
  import { readFlowFile } from './decompile-file.js';
93
100
  import { readFlowStamp, restampFlowSource, sourceDigest, STAMP_MARKER } from './decompile-stamp.js';
@@ -225,6 +232,91 @@ function projectBindings(projectDir, originalPath, mergedFlow, writes, removals)
225
232
  return undefined;
226
233
  return { version: '2.0', ...existing, resources: after };
227
234
  }
235
+ /**
236
+ * Delete `path`, a file or directory merge has just made unreferenced, and
237
+ * answer `undefined`; or leave it and answer why. It must be inside `root` (the
238
+ * original's directory) on disk, links followed (`physicalPath`), and not `root`
239
+ * itself; it must be what merge says it is, not a link; a directory must hold
240
+ * `marker` (a resource directory its `resource.json`).
241
+ */
242
+ function deleteUnreferenced(root, path, kind, marker) {
243
+ let realRoot;
244
+ try {
245
+ realRoot = realpathSync.native(root);
246
+ }
247
+ catch {
248
+ return `${root} could not be read`;
249
+ }
250
+ const at = physicalPath(resolve(path));
251
+ if (at === undefined || at === realRoot || !isWithin(realRoot, at))
252
+ return `it is not inside ${root}`;
253
+ let stat;
254
+ try {
255
+ stat = lstatSync(path);
256
+ }
257
+ catch {
258
+ return 'it is not there';
259
+ }
260
+ if (kind === 'file' ? !stat.isFile() : !stat.isDirectory())
261
+ return `it is not a plain ${kind}`;
262
+ if (marker !== undefined && !existsSync(join(path, marker)))
263
+ return `it holds no ${marker}`;
264
+ try {
265
+ rmSync(path, { recursive: kind === 'directory', force: true });
266
+ }
267
+ catch (error) {
268
+ return error instanceof Error ? error.message : String(error);
269
+ }
270
+ return undefined;
271
+ }
272
+ /**
273
+ * The file a path names on disk, as `dev:ino`, or `undefined` when it cannot be
274
+ * read. Two spellings of one file (`NODES.json` and `nodes.json` on a
275
+ * case-insensitive file system, a link and its target) give one key.
276
+ */
277
+ function fileKey(path) {
278
+ try {
279
+ const st = statSync(path, { bigint: true });
280
+ return `${st.dev}:${st.ino}`;
281
+ }
282
+ catch {
283
+ return undefined;
284
+ }
285
+ }
286
+ /**
287
+ * The files the `$ref`s of every OTHER `.flow` file below `dir` (the Flow
288
+ * project's root) read, every subfolder included (`sub/Q.flow` may read
289
+ * `./nodes.json`, the file `P.flow` names as `./sub/nodes.json`; `Q.flow` at the
290
+ * root may read `./flows/nodes.json`), each as {@link fileKey}. `undefined` when merge cannot be
291
+ * sure: a `.flow` there cannot be read, or the folder is larger than the scan
292
+ * reads (`projectFlowFiles`' bounds). Then no part file is provably unused.
293
+ * The walk is `projectFlowFiles` in project-flows.ts, entering dot-folders and
294
+ * nested projects: a `$ref` can come from any of them.
295
+ */
296
+ function partsOfOtherFlows(dir, self) {
297
+ const { files, complete } = projectFlowFiles(dir, { readers: false });
298
+ if (!complete)
299
+ return undefined;
300
+ const selfKey = fileKey(self);
301
+ const keys = new Set();
302
+ for (const path of files) {
303
+ if (fileKey(path) === selfKey)
304
+ continue;
305
+ const parts = [];
306
+ try {
307
+ readFlowFile(path, parts);
308
+ }
309
+ catch {
310
+ return undefined;
311
+ }
312
+ for (const part of parts) {
313
+ const key = fileKey(part);
314
+ if (key !== undefined)
315
+ keys.add(key);
316
+ }
317
+ }
318
+ return keys;
319
+ }
228
320
  /** A JSON file's contents, or `undefined` when it is missing or unreadable. */
229
321
  function readJsonOrUndefined(path) {
230
322
  try {
@@ -542,19 +634,86 @@ export async function run(argv) {
542
634
  console.log(`flow-merge: kept ${rel}: ${user} still references it`);
543
635
  return user === undefined;
544
636
  });
545
- const removed = removals.map((rel) => join(originalDir, rel));
546
- for (const dir of removed) {
547
- console.log(inPlace
548
- ? `flow-merge: remove ${dir} from the project: the edit removed this agent resource, and merge does not delete files`
549
- : `flow-merge: remove ${dir} from the project: the edit removed this agent resource, and copying the candidate cannot delete it`);
637
+ // Derived before anything is deleted: a removed resource's row is matched by
638
+ // the body read from its file.
639
+ const bindingsV2 = projectBindings(originalDir, originalPath, flow, merged.sidecars, removals);
640
+ // Written over the original, merge deletes what it has just made unreferenced
641
+ // itself (#1995): each agent resource directory the edit removed, and, for a
642
+ // split original now written as one file, its part files. Only paths it can
643
+ // prove are unreferenced, and only inside the original's directory
644
+ // (`deleteUnreferenced`). Written elsewhere (a candidate), the project is not
645
+ // touched, so they are listed for the caller to delete, as before. What it
646
+ // could not delete (a host that refuses deletes) is listed the same way.
647
+ const deleted = [];
648
+ const removed = [];
649
+ const mergedSources = new Set(flowSources(flow).map((s) => s.toLowerCase()));
650
+ for (const rel of removals) {
651
+ const dir = join(originalDir, rel);
652
+ if (!inPlace) {
653
+ removed.push(dir);
654
+ console.log(`flow-merge: remove ${dir} from the project: the edit removed this agent resource, and copying the candidate cannot delete it`);
655
+ continue;
656
+ }
657
+ // In use: kept, and not listed under `remove`, which the caller deletes.
658
+ if (mergedSources.has(basename(rel).toLowerCase())) {
659
+ console.log(`flow-merge: kept ${rel}: ${basename(out)} still names it`);
660
+ continue;
661
+ }
662
+ const refusal = deleteUnreferenced(originalDir, dir, 'directory', 'resource.json');
663
+ if (refusal === undefined) {
664
+ deleted.push(resolve(dir));
665
+ console.log(`flow-merge: deleted ${dir}: the edit removed this agent resource`);
666
+ }
667
+ else {
668
+ removed.push(dir);
669
+ console.log(`flow-merge: remove ${dir} from the project: the edit removed this agent resource, and merge did not delete it (${refusal})`);
670
+ }
550
671
  }
551
672
  // Written over a split original, the merged flow is one file, so its part files
552
- // stay on disk with nothing reading them.
553
- const unreferenced = inPlace ? originalParts : [];
554
- for (const part of unreferenced) {
555
- console.log(`flow-merge: remove ${part} from the project: ${basename(originalPath)} is now one file and no longer references it, and merge does not delete files`);
673
+ // stay on disk with nothing reading them, unless another .flow in the project reads one.
674
+ const unreferenced = [];
675
+ if (inPlace && originalParts.length > 0) {
676
+ // A reader of a part can sit anywhere in the project, above the original's folder
677
+ // too (`Q.flow` reading `./flows/nodes.json`), so the scan starts at the Flow
678
+ // project's root. Outside a project there is no top to start from: nothing is
679
+ // deleted, every part is listed.
680
+ // Found from where the original IS on disk, links followed: opened through a link
681
+ // (`ws/alias -> real/proj/flows`), the typed path climbs to a project.uiproj
682
+ // that is not the original's. A project inside another one (`Outer/Inner/`)
683
+ // can have a reader above it (`Outer/Q.flow` reading `./Inner/nodes.json`), so
684
+ // that is treated as no top either.
685
+ const real = physicalPath(resolve(originalPath));
686
+ const found = real === undefined ? undefined : flowProjectOf(real);
687
+ // `flowProjectOf` climbs from its argument's folder, so passing the project folder
688
+ // itself starts the climb at its parent.
689
+ const nested = found !== undefined && flowProjectOf(found) !== undefined;
690
+ const project = nested ? undefined : found;
691
+ const sharedParts = project === undefined ? undefined : partsOfOtherFlows(project, real ?? resolve(originalPath));
692
+ for (const part of originalParts) {
693
+ // Proven in use, or a deliverable itself: kept, and NOT listed under `remove`
694
+ // (the caller deletes every `remove` line, which would break the other flow).
695
+ const inUse = part.endsWith('.flow') ? 'it is a .flow file'
696
+ : sharedParts?.has(fileKey(part) ?? part) ? 'another .flow in the project still references it'
697
+ : undefined;
698
+ if (inUse !== undefined) {
699
+ console.log(`flow-merge: kept ${part}: ${inUse}`);
700
+ continue;
701
+ }
702
+ // Not provably unused, or the delete failed: listed for the caller, as on main.
703
+ const refusal = nested ? `${basename(originalPath)}'s Flow project sits inside another one, so a .flow above it may use the file`
704
+ : project === undefined ? `${basename(originalPath)} is in no Flow project (no project.uiproj above it), so merge cannot read every .flow that may use the file`
705
+ : sharedParts === undefined ? 'merge could not read every .flow in the project, so it cannot tell whether one uses the file'
706
+ : deleteUnreferenced(originalDir, part, 'file');
707
+ if (refusal === undefined) {
708
+ deleted.push(part);
709
+ console.log(`flow-merge: deleted ${part}: ${basename(originalPath)} is now one file and no longer references it`);
710
+ }
711
+ else {
712
+ unreferenced.push(part);
713
+ console.log(`flow-merge: remove ${part} from the project: ${basename(originalPath)} is now one file and no longer references it, and merge did not delete it (${refusal})`);
714
+ }
715
+ }
556
716
  }
557
- const bindingsV2 = projectBindings(originalDir, originalPath, flow, merged.sidecars, removals);
558
717
  if (bindingsV2 !== undefined) {
559
718
  writeJsonFile(join(outDir, 'bindings_v2.json'), bindingsV2);
560
719
  console.log('flow-merge: wrote bindings_v2.json (connection and agent resource rows, re-derived as compile does)');
@@ -597,6 +756,7 @@ export async function run(argv) {
597
756
  edges: (flow.edges ?? []).length,
598
757
  ...(stamp ? { baseline: baselinePath ? 'file' : 'derived', restamped } : {}),
599
758
  ...(targets.length > 0 ? { sidecars: targets.map((t) => t.target) } : {}),
759
+ ...(deleted.length > 0 ? { deleted } : {}),
600
760
  ...(removed.length > 0 ? { removed } : {}),
601
761
  ...(unreferenced.length > 0 ? { unreferenced } : {}),
602
762
  ...(bindingsV2 !== undefined ? { bindings: join(resolve(outDir), 'bindings_v2.json') } : {}),
package/dist/merge.js CHANGED
@@ -93,7 +93,7 @@ import { jsonClone } from './core/json-clone.js';
93
93
  import { isRecord } from './core/node-envelope.js';
94
94
  import { DEFINITIONLESS_NODE_TYPES } from './core/definitionless-node-types.js';
95
95
  import { MergeRefusedError, mergedFileFindings, roundTripFindings } from './merge-roundtrip.js';
96
- import { placeAddedNodes } from './node-placement.js';
96
+ import { placeAddedNodes, stripPlaceholderFlag } from './node-placement.js';
97
97
  import { mergeAgentSidecars } from './merge-sidecars.js';
98
98
  import { embeddedAgentFindings, isEmbeddedAgent, mergeEmbeddedAgentNode } from './merge-embedded-agent.js';
99
99
  import { mergeObject, mergeVariables, stableJson } from './merge-variables.js';
@@ -478,6 +478,13 @@ function mergeFlowFindings(original, edited, options) {
478
478
  // positions — see node-placement.ts. Root scope only: a
479
479
  // subflow is taken from `edited` whole, layout included. ──
480
480
  placeAddedNodes(finalNodes, result.edges, positionStoreOf(original) && layoutNodesOf(result), (id) => !origNodes.has(id));
481
+ // An added root node is where merge put it now, not where compile did: drop its
482
+ // mark. A subflow taken whole keeps compile's layout and its marks, so a later
483
+ // decompile still leaves it to compile; an original node keeps the original's ui.
484
+ for (const n of finalNodes.filter((n) => !origNodes.has(n.id))) {
485
+ stripPlaceholderFlag(n.ui);
486
+ stripPlaceholderFlag(layoutNodesOf(result)?.[n.id]);
487
+ }
481
488
  // ── Definitions: the (type, version) pairs used by EVERY node in the file —
482
489
  // root and subflows — original winning on conflict (its defs are the
483
490
  // tenant-resolved authority). Selecting by root nodes only dropped the
@@ -2,9 +2,11 @@
2
2
  * node-placement — where compile puts a node it has no position for, and where
3
3
  * merge moves one the edit added.
4
4
  *
5
- * Compile gives every node a placeholder from its emission index,
6
- * `x = 256 + 288 × index, y = 144` (`+160` inside a container). Merge replaces
7
- * that placeholder on each node the edit added:
5
+ * In a flow or subflow whose `.layout()` names nodes (every decompiled source
6
+ * with positions), compile gives each node it leaves out a placeholder from its
7
+ * emission index, `x = 256 + 288 × index, y = 144` (`+160` inside a container).
8
+ * A scope with no `.layout()` node entries is laid out whole instead
9
+ * (`auto-layout.ts`). Merge replaces the placeholder on each node the edit added:
8
10
  *
9
11
  * - right of its rightmost positioned predecessor in the same container, past
10
12
  * its width, on that predecessor's row; when the node leads into another
@@ -67,6 +69,29 @@ export declare function placeholderPosition(index: number, nested: boolean): Poi
67
69
  * a placeholder; that is the one ambiguity.
68
70
  */
69
71
  export declare function isPlaceholderPosition(p: Point | undefined): boolean;
72
+ /**
73
+ * The `ui` key compile writes on a node whose position it chose itself: every node of a
74
+ * flow or subflow it laid out (no `.layout()` node entries, `auto-layout.ts`). Its value
75
+ * is the position compile chose, so the mark holds only while the node is still there:
76
+ * Studio Web keeps unknown `ui` keys on save (flow-schema `extractLayout` persists "the
77
+ * full ui object (including unknown keys like zoom)"), and a drag changes `position` but
78
+ * not this key. Merge places an added node whose mark holds, and decompile writes no
79
+ * `.layout()` entry for it. The `.flow` schema's node `ui` takes extra keys
80
+ * (flow-schema `workflow-file`, `$catchall`).
81
+ *
82
+ * Example: `flow compile` of a source with no `.layout()` writes
83
+ * `{ position: { x: 448, y: 144 }, size: …, collapsed: false, placeholder: { x: 448, y: 144 } }`.
84
+ * Drag the node to (448, 304) in the designer and the mark no longer holds.
85
+ */
86
+ export declare const PLACEHOLDER_FLAG = "placeholder";
87
+ /** `ui` with {@link PLACEHOLDER_FLAG} set to its current position. */
88
+ export declare function markCompilePlaced<T extends {
89
+ position?: Point;
90
+ }>(ui: T): T;
91
+ /** Whether a node's `ui` (layout entry over `node.ui`) still sits where compile put it. */
92
+ export declare function isMarkedPlaceholder(ui: unknown): boolean;
93
+ /** Remove {@link PLACEHOLDER_FLAG} from a node's `ui`, or a `layout.nodes` entry, in place. */
94
+ export declare function stripPlaceholderFlag(ui: unknown): void;
70
95
  /** A node's `ui` (or its `layout.nodes` entry): the fields placement reads. */
71
96
  interface Ui {
72
97
  position?: Point;