@leitwerk-dev/workflow-graph 0.0.0-stage → 0.4.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.
package/src/layout.ts ADDED
@@ -0,0 +1,531 @@
1
+ import type {
2
+ ProcessFlowEdge,
3
+ ProcessFlowNode,
4
+ ProcessFlowView,
5
+ ProcessTurnType,
6
+ } from "@leitwerk-dev/domain";
7
+ import { shortestSuccessfulTurnPath } from "@leitwerk-dev/domain";
8
+
9
+ /** @internal */
10
+ export interface Point {
11
+ /** @internal */ x: number;
12
+ /** @internal */ y: number;
13
+ }
14
+ /** @internal */
15
+ export interface RepeatGeometry {
16
+ /** @internal */ activity: {
17
+ /** @internal */ x: number;
18
+ /** @internal */ y: number;
19
+ /** @internal */ width: number;
20
+ /** @internal */ height: number;
21
+ };
22
+ /** @internal */ collector: Point;
23
+ /** @internal */ axis: number;
24
+ /** @internal */ loopY: number;
25
+ }
26
+ /** @internal */
27
+ export interface WorkflowNode {
28
+ /** @internal */ id: string;
29
+ /** @internal */ turnId: string | null;
30
+ /** @internal */ title: string;
31
+ /** @internal */ kind: ProcessTurnType | "completed" | "aborted";
32
+ /** @internal */ definition: ProcessFlowNode | null;
33
+ /** @internal */ synthetic: boolean;
34
+ /** @internal */ column: number;
35
+ /** @internal */ lane: number;
36
+ /** @internal */ x: number;
37
+ /** @internal */ y: number;
38
+ /** @internal */ width: number;
39
+ /** @internal */ height: number;
40
+ /** @internal */ repeat: RepeatGeometry | null;
41
+ }
42
+ /** @internal */
43
+ type Side = "left" | "right" | "top" | "bottom";
44
+ /** @internal */
45
+ export interface WorkflowEdge {
46
+ /** @internal */ id: string;
47
+ /** @internal */ from: string;
48
+ /** @internal */ to: string;
49
+ /** @internal */ label: string | null;
50
+ /** @internal */ condition?: ProcessFlowEdge["condition"];
51
+ /** @internal */ kind: ProcessFlowEdge["kind"];
52
+ /** @internal */ points: Point[];
53
+ /** @internal */ labelPosition: Point;
54
+ /** @internal */ sourceSide: Side;
55
+ /** @internal */ targetSide: Side;
56
+ }
57
+ /** @internal */
58
+ export interface WorkflowLayout {
59
+ /** @internal */ width: number;
60
+ /** @internal */ height: number;
61
+ /** @internal */ nodes: WorkflowNode[];
62
+ /** @internal */ edges: WorkflowEdge[];
63
+ /** Layout node identities, including the completed terminal. @internal */ mainPath: string[];
64
+ }
65
+
66
+ const turnId = (id: string) => `turn:${id}`;
67
+ const endId = (status: string) => `end:${status}`;
68
+
69
+ /** Stable breadth-first search; abort and declared happy-path hints cannot shorten success. @internal */
70
+ export function shortestSuccessfulPath(flow: ProcessFlowView): string[] {
71
+ const ids = new Set(flow.nodes.map((node) => node.turnId));
72
+ const entry = flow.entryTurnIds.find((id) => ids.has(id)) ?? flow.nodes[0]?.turnId;
73
+ if (!entry) return [];
74
+ return shortestSuccessfulTurnPath(entry, (id) =>
75
+ flow.edges
76
+ .filter((edge) => edge.from === id)
77
+ .flatMap((edge) =>
78
+ edge.lifecycleStatus === "completed"
79
+ ? [null]
80
+ : edge.to !== null && ids.has(edge.to)
81
+ ? [edge.to]
82
+ : [],
83
+ ),
84
+ );
85
+ }
86
+
87
+ /** Labels match the Chronicle's turn-kind vocabulary. @internal */
88
+ export function turnKindLabel(kind: WorkflowNode["kind"]): string {
89
+ switch (kind) {
90
+ case "llm":
91
+ return "LLM turn";
92
+ case "automatic":
93
+ return "Automation";
94
+ case "human":
95
+ return "Operator decision";
96
+ case "external":
97
+ return "External wait";
98
+ case "completed":
99
+ return "Completed";
100
+ case "aborted":
101
+ return "Aborted";
102
+ }
103
+ }
104
+
105
+ function makeNode(definition: ProcessFlowNode): WorkflowNode {
106
+ const repeated = definition.repetition === "sequential";
107
+ const width = repeated ? 380 : definition.description.length > 50 ? 260 : 225;
108
+ const lines = Math.min(
109
+ 3,
110
+ Math.max(1, Math.ceil(definition.description.length / (repeated ? 23 : 24))),
111
+ );
112
+ const activityHeight = 85 + (lines - 1) * 21;
113
+ const height = repeated ? activityHeight + 115 : Math.max(112, 90 + lines * 21);
114
+ return {
115
+ id: turnId(definition.turnId),
116
+ turnId: definition.turnId,
117
+ title: definition.description,
118
+ kind: definition.turnType,
119
+ definition,
120
+ synthetic: false,
121
+ column: 0,
122
+ lane: 0,
123
+ x: 0,
124
+ y: 0,
125
+ width,
126
+ height,
127
+ repeat: repeated
128
+ ? {
129
+ activity: { x: 18, y: 57.5, width: 235, height: activityHeight },
130
+ collector: { x: 326, y: height / 2 },
131
+ axis: height / 2,
132
+ loopY: height - 22,
133
+ }
134
+ : null,
135
+ };
136
+ }
137
+
138
+ /** Places the shortest successful path on one line and routes every declared transition. @internal */
139
+ export function layoutWorkflow(flow: ProcessFlowView): WorkflowLayout {
140
+ const nodes = flow.nodes.map(makeNode);
141
+ const statuses = new Map(flow.endStates.map((state) => [state.lifecycleStatus, state.synthetic]));
142
+ for (const edge of flow.edges)
143
+ if (edge.lifecycleStatus) statuses.set(edge.lifecycleStatus, false);
144
+ for (const [status, synthetic] of statuses)
145
+ nodes.push({
146
+ id: endId(status),
147
+ turnId: null,
148
+ title: turnKindLabel(status),
149
+ kind: status,
150
+ definition: null,
151
+ synthetic,
152
+ column: 0,
153
+ lane: 0,
154
+ x: 0,
155
+ y: 0,
156
+ width: 190,
157
+ height: 70,
158
+ repeat: null,
159
+ });
160
+ const byId = new Map(nodes.map((node) => [node.id, node]));
161
+ const spine = shortestSuccessfulPath(flow);
162
+ const mainPath = spine.map(turnId);
163
+ if (flow.edges.some((edge) => edge.from === spine.at(-1) && edge.lifecycleStatus === "completed"))
164
+ mainPath.push(endId("completed"));
165
+ const edges: WorkflowEdge[] = flow.edges.flatMap((edge, index) => {
166
+ const from = turnId(edge.from);
167
+ const to =
168
+ edge.to !== null
169
+ ? turnId(edge.to)
170
+ : edge.lifecycleStatus
171
+ ? endId(edge.lifecycleStatus)
172
+ : null;
173
+ return to && byId.has(from) && byId.has(to)
174
+ ? [
175
+ {
176
+ id: `route-${index}`,
177
+ from,
178
+ to,
179
+ label: edge.label,
180
+ ...(edge.condition ? { condition: edge.condition } : {}),
181
+ kind: edge.kind,
182
+ points: [],
183
+ labelPosition: { x: 0, y: 0 },
184
+ sourceSide: "right" as const,
185
+ targetSide: "left" as const,
186
+ },
187
+ ]
188
+ : [];
189
+ });
190
+ const placed = new Set<string>();
191
+ const occupied = new Set<string>();
192
+ const place = (id: string, column: number, lane: number) => {
193
+ const node = byId.get(id);
194
+ if (!node || placed.has(id)) return;
195
+ while (occupied.has(`${column}:${lane}`)) lane += lane < 0 ? -1 : 1;
196
+ node.column = column;
197
+ node.lane = lane;
198
+ placed.add(id);
199
+ occupied.add(`${column}:${lane}`);
200
+ };
201
+ for (const [column, id] of mainPath.entries()) place(id, column, 0);
202
+ for (const id of placed) {
203
+ const parent = byId.get(id);
204
+ if (!parent) continue;
205
+ for (const edge of edges.filter((edge) => edge.from === id)) {
206
+ const next = byId.get(edge.to);
207
+ if (!next || placed.has(next.id)) continue;
208
+ place(
209
+ next.id,
210
+ parent.column + 1,
211
+ parent.lane || (next.kind === "human" || next.kind === "aborted" ? -1 : 1),
212
+ );
213
+ }
214
+ }
215
+ // Unreachable declarations and implicit abort remain visible without fabricated edges.
216
+ for (const node of nodes)
217
+ if (!placed.has(node.id))
218
+ place(node.id, node.synthetic ? Math.max(0, mainPath.length - 1) : 0, 1);
219
+ for (const edge of edges) {
220
+ const from = byId.get(edge.from) as WorkflowNode;
221
+ const to = byId.get(edge.to) as WorkflowNode;
222
+ // A side path may rejoin to its left without repeating any work.
223
+ if (to.column <= from.column && canReach(edge.to, edge.from, edges)) edge.kind = "loopback";
224
+ }
225
+ const columnCount = Math.max(0, ...nodes.map((node) => node.column)) + 1;
226
+ const widths = Array.from({ length: columnCount }, (_, column) =>
227
+ Math.max(225, ...nodes.filter((node) => node.column === column).map((node) => node.width)),
228
+ );
229
+ const columns: number[] = [];
230
+ let x = 50;
231
+ for (const width of widths) {
232
+ columns.push(x);
233
+ x += width + 115;
234
+ }
235
+ const lanes = [...new Set(nodes.map((node) => node.lane))].sort((a, b) => a - b);
236
+ const laneCenters = new Map<number, number>();
237
+ let y = 90 + edges.filter((edge) => edge.kind === "loopback").length * 22;
238
+ for (const lane of lanes) {
239
+ const height = Math.max(
240
+ 130,
241
+ ...nodes.filter((node) => node.lane === lane).map((node) => node.height),
242
+ );
243
+ laneCenters.set(lane, y + height / 2);
244
+ y += height + 85;
245
+ }
246
+ for (const node of nodes) {
247
+ node.x = columns[node.column] + (widths[node.column] - node.width) / 2;
248
+ node.y = (laneCenters.get(node.lane) ?? 0) - node.height / 2;
249
+ }
250
+ for (const edge of edges) {
251
+ const from = byId.get(edge.from) as WorkflowNode;
252
+ const to = byId.get(edge.to) as WorkflowNode;
253
+ if (edge.kind === "loopback") {
254
+ edge.sourceSide = "top";
255
+ edge.targetSide = "top";
256
+ } else if (from.column === to.column) {
257
+ edge.sourceSide = from.y < to.y ? "bottom" : "top";
258
+ edge.targetSide = from.y < to.y ? "top" : "bottom";
259
+ } else if (from.lane === to.lane) {
260
+ edge.sourceSide = "right";
261
+ edge.targetSide = "left";
262
+ } else if (to.lane !== 0 && from.lane === 0) {
263
+ edge.sourceSide = to.lane < from.lane ? "top" : "bottom";
264
+ edge.targetSide = "left";
265
+ } else if (from.lane !== 0 && to.lane === 0) {
266
+ edge.sourceSide = to.lane < from.lane ? "top" : "bottom";
267
+ edge.targetSide = to.lane < from.lane ? "bottom" : "top";
268
+ } else {
269
+ edge.sourceSide = to.column < from.column ? "left" : "right";
270
+ edge.targetSide = to.column < from.column ? "right" : "left";
271
+ }
272
+ }
273
+ const isMain = (edge: WorkflowEdge) =>
274
+ mainPath.indexOf(edge.from) >= 0 && mainPath[mainPath.indexOf(edge.from) + 1] === edge.to;
275
+ const port = (edge: WorkflowEdge, source: boolean): Point => {
276
+ const node = byId.get(source ? edge.from : edge.to) as WorkflowNode;
277
+ const side = source ? edge.sourceSide : edge.targetSide;
278
+ const horizontal = side === "left" || side === "right";
279
+ // Incoming and outgoing connections share one port allocation per side.
280
+ // Repeats already separate incoming activity ports from outgoing collection ports.
281
+ const peers = edges
282
+ .flatMap((other) => [
283
+ ...(other.from === node.id && other.sourceSide === side && (!node.repeat || source)
284
+ ? [{ edge: other, source: true, opposite: byId.get(other.to) as WorkflowNode }]
285
+ : []),
286
+ ...(other.to === node.id && other.targetSide === side && (!node.repeat || !source)
287
+ ? [{ edge: other, source: false, opposite: byId.get(other.from) as WorkflowNode }]
288
+ : []),
289
+ ])
290
+ .sort((a, b) => {
291
+ const first = a.opposite;
292
+ const second = b.opposite;
293
+ const distance = horizontal
294
+ ? first.y + first.height / 2 - (second.y + second.height / 2)
295
+ : first.x + first.width / 2 - (second.x + second.width / 2);
296
+ return distance || Number(a.source) - Number(b.source);
297
+ });
298
+ const primary = peers.find(({ edge: other }) => isMain(other));
299
+ const center = primary ? peers.indexOf(primary) : (peers.length - 1) / 2;
300
+ const available = horizontal
301
+ ? (node.repeat?.activity.height ?? node.height) / 2 - 16
302
+ : node.repeat
303
+ ? source
304
+ ? 28
305
+ : 10
306
+ : node.width / 2 - 52;
307
+ const spacing = Math.min(32, available / Math.max(1, center, peers.length - 1 - center));
308
+ const index = peers.findIndex((peer) => peer.edge === edge && peer.source === source);
309
+ const spread = (index - center) * spacing;
310
+ const cx =
311
+ node.x +
312
+ (node.repeat
313
+ ? source
314
+ ? 326
315
+ : 240
316
+ : node.width / 2 + (edge.from === edge.to ? (source ? 36 : -36) : 0));
317
+ const cy = node.y + node.height / 2;
318
+ if (side === "left") return { x: node.x, y: cy + spread };
319
+ if (side === "right") return { x: node.x + node.width, y: cy + spread };
320
+ return { x: cx + spread, y: side === "top" ? node.y : node.y + node.height };
321
+ };
322
+ let loopIndex = 0;
323
+ const routed: Point[][] = [];
324
+ // Main-line edges get the unobstructed central ports before side routes.
325
+ for (const edge of [...edges].sort((a, b) => Number(isMain(b)) - Number(isMain(a)))) {
326
+ const start = port(edge, true),
327
+ end = port(edge, false);
328
+ const from = escapePort(start, edge.sourceSide),
329
+ to = escapePort(end, edge.targetSide);
330
+ const rejoinsMainPath = byId.get(edge.from)?.lane !== 0 && byId.get(edge.to)?.lane === 0;
331
+ const preferredY =
332
+ edge.kind === "loopback"
333
+ ? 28 + loopIndex++ * 22
334
+ : rejoinsMainPath &&
335
+ (edge.sourceSide === "top" || edge.sourceSide === "bottom") &&
336
+ (edge.targetSide === "top" || edge.targetSide === "bottom")
337
+ ? (start.y + end.y) / 2
338
+ : undefined;
339
+ const middle = route(from, to, nodes, routed, preferredY);
340
+ edge.points = simplify([start, ...middle, end]);
341
+ routed.push(edge.points);
342
+ edge.labelPosition = routeLabel(edge.points);
343
+ }
344
+ return { width: x - 65, height: y - 35, nodes, edges, mainPath };
345
+ }
346
+
347
+ function canReach(start: string, target: string, edges: WorkflowEdge[]): boolean {
348
+ const visited = new Set([start]);
349
+ for (const id of visited) {
350
+ if (id === target) return true;
351
+ for (const edge of edges) if (edge.from === id) visited.add(edge.to);
352
+ }
353
+ return false;
354
+ }
355
+
356
+ function escapePort(point: Point, side: Side): Point {
357
+ return {
358
+ x: point.x + (side === "right" ? 20 : side === "left" ? -20 : 0),
359
+ y: point.y + (side === "bottom" ? 20 : side === "top" ? -20 : 0),
360
+ };
361
+ }
362
+ function simplify(points: Point[]): Point[] {
363
+ const result: Point[] = [];
364
+ for (const point of points) {
365
+ const last = result.at(-1),
366
+ before = result.at(-2);
367
+ if (last && last.x === point.x && last.y === point.y) continue;
368
+ if (
369
+ before &&
370
+ last &&
371
+ ((before.x === last.x && last.x === point.x) || (before.y === last.y && last.y === point.y))
372
+ )
373
+ result.pop();
374
+ result.push(point);
375
+ }
376
+ return result;
377
+ }
378
+ function strictBoundsOverlap(a: Point, b: Point, c: Point, d: Point): boolean {
379
+ return (
380
+ Math.max(a.x, b.x) > Math.min(c.x, d.x) &&
381
+ Math.min(a.x, b.x) < Math.max(c.x, d.x) &&
382
+ Math.max(a.y, b.y) > Math.min(c.y, d.y) &&
383
+ Math.min(a.y, b.y) < Math.max(c.y, d.y)
384
+ );
385
+ }
386
+ function clearSegment(a: Point, b: Point, nodes: WorkflowNode[]): boolean {
387
+ return !nodes.some((node) =>
388
+ strictBoundsOverlap(
389
+ a,
390
+ b,
391
+ { x: node.x - 10, y: node.y - 10 },
392
+ { x: node.x + node.width + 10, y: node.y + node.height + 10 },
393
+ ),
394
+ );
395
+ }
396
+ function route(
397
+ start: Point,
398
+ end: Point,
399
+ nodes: WorkflowNode[],
400
+ previous: Point[][],
401
+ preferredY?: number,
402
+ ): Point[] {
403
+ const xs = [
404
+ ...new Set([
405
+ start.x,
406
+ end.x,
407
+ ...nodes.flatMap((node) => [node.x - 25, node.x + node.width + 25]),
408
+ ]),
409
+ ];
410
+ const ys = [
411
+ ...new Set([
412
+ start.y,
413
+ end.y,
414
+ preferredY ?? 28,
415
+ ...nodes.flatMap((node) => [node.y - 25, node.y + node.height + 25]),
416
+ ]),
417
+ ];
418
+ const candidates =
419
+ preferredY !== undefined
420
+ ? [[start, { x: start.x, y: preferredY }, { x: end.x, y: preferredY }, end]]
421
+ : [
422
+ ...(start.x === end.x || start.y === end.y ? [[start, end]] : []),
423
+ [start, { x: start.x, y: end.y }, end],
424
+ [start, { x: end.x, y: start.y }, end],
425
+ ...xs.map((x) => [start, { x, y: start.y }, { x, y: end.y }, end]),
426
+ ...ys.map((y) => [start, { x: start.x, y }, { x: end.x, y }, end]),
427
+ ];
428
+ const legal = candidates
429
+ .map(simplify)
430
+ .filter((points) =>
431
+ points.slice(1).every((point, index) => clearSegment(points[index], point, nodes)),
432
+ );
433
+ const score = (points: Point[]) =>
434
+ points.slice(1).reduce((sum, point, index) => {
435
+ const before = points[index];
436
+ const crossings = previous.reduce(
437
+ (count, route) =>
438
+ count +
439
+ route.slice(1).filter((b, i) => strictBoundsOverlap(before, point, route[i], b)).length,
440
+ 0,
441
+ );
442
+ return sum + Math.abs(before.x - point.x) + Math.abs(before.y - point.y) + crossings * 80;
443
+ }, points.length * 12);
444
+ legal.sort((a, b) => score(a) - score(b));
445
+ return legal[0] ?? gridRoute(start, end, xs, ys, nodes);
446
+ }
447
+
448
+ // Unusual cross-links can require more bends than the simple candidates above.
449
+ function gridRoute(
450
+ start: Point,
451
+ end: Point,
452
+ xs: number[],
453
+ ys: number[],
454
+ nodes: WorkflowNode[],
455
+ ): Point[] {
456
+ xs.sort((a, b) => a - b);
457
+ ys.sort((a, b) => a - b);
458
+ const indexOf = (p: Point) => ys.indexOf(p.y) * xs.length + xs.indexOf(p.x);
459
+ const pointAt = (index: number) => ({
460
+ x: xs[index % xs.length],
461
+ y: ys[Math.floor(index / xs.length)],
462
+ });
463
+ const first = indexOf(start),
464
+ last = indexOf(end);
465
+ const open = new Set([first]);
466
+ const costs = new Map([[first, 0]]),
467
+ parents = new Map<number, number>();
468
+ while (open.size) {
469
+ let current = first,
470
+ best = Number.POSITIVE_INFINITY;
471
+ for (const index of open) {
472
+ const point = pointAt(index);
473
+ const cost = (costs.get(index) ?? 0) + Math.abs(point.x - end.x) + Math.abs(point.y - end.y);
474
+ if (cost < best) {
475
+ current = index;
476
+ best = cost;
477
+ }
478
+ }
479
+ if (current === last) {
480
+ const points = [end];
481
+ while (parents.has(current)) {
482
+ current = parents.get(current) as number;
483
+ points.push(pointAt(current));
484
+ }
485
+ return simplify(points.reverse());
486
+ }
487
+ open.delete(current);
488
+ const point = pointAt(current),
489
+ xi = current % xs.length,
490
+ yi = Math.floor(current / xs.length);
491
+ for (const [nx, ny] of [
492
+ [xi - 1, yi],
493
+ [xi + 1, yi],
494
+ [xi, yi - 1],
495
+ [xi, yi + 1],
496
+ ]) {
497
+ if (nx < 0 || ny < 0 || nx >= xs.length || ny >= ys.length) continue;
498
+ const next = ny * xs.length + nx,
499
+ target = pointAt(next);
500
+ if (!clearSegment(point, target, nodes)) continue;
501
+ const cost =
502
+ (costs.get(current) ?? 0) + Math.abs(point.x - target.x) + Math.abs(point.y - target.y);
503
+ if (cost >= (costs.get(next) ?? Number.POSITIVE_INFINITY)) continue;
504
+ parents.set(next, current);
505
+ costs.set(next, cost);
506
+ open.add(next);
507
+ }
508
+ }
509
+ // Every node has separated lanes and columns, so outer corridors remain open.
510
+ throw new Error("Workflow route has no clear corridor");
511
+ }
512
+ function routeLabel(points: Point[]): Point {
513
+ let longest = -1,
514
+ position = points[0] ?? { x: 0, y: 0 };
515
+ for (let index = 1; index < points.length; index++) {
516
+ const a = points[index - 1],
517
+ b = points[index],
518
+ length = Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
519
+ if (length <= longest) continue;
520
+ longest = length;
521
+ position = {
522
+ x: (a.x + b.x) / 2 + (a.x === b.x ? 44 : 0),
523
+ y: (a.y + b.y) / 2 - (a.y === b.y ? 16 : 0),
524
+ };
525
+ }
526
+ return position;
527
+ }
528
+ /** SVG polyline with no smoothing that can displace aligned ports. @internal */
529
+ export function edgePath(points: readonly Point[]): string {
530
+ return points.map((point, index) => `${index === 0 ? "M" : "L"}${point.x} ${point.y}`).join("");
531
+ }