@leitwerk-dev/process-sdk 0.1.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.
Files changed (199) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/browser-ui-extension.d.ts +27 -0
  3. package/dist/browser-ui-extension.d.ts.map +1 -0
  4. package/dist/browser-ui-extension.js +2 -0
  5. package/dist/browser-ui-extension.js.map +1 -0
  6. package/dist/capabilities.d.ts +9 -0
  7. package/dist/capabilities.d.ts.map +1 -0
  8. package/dist/capabilities.js +7 -0
  9. package/dist/capabilities.js.map +1 -0
  10. package/dist/chunk-5RJZ2E7D.js +58 -0
  11. package/dist/chunk-5RJZ2E7D.js.map +1 -0
  12. package/dist/chunk-ITPH65G6.js +197 -0
  13. package/dist/chunk-ITPH65G6.js.map +1 -0
  14. package/dist/chunk-LIIP7FMU.js +48 -0
  15. package/dist/chunk-LIIP7FMU.js.map +1 -0
  16. package/dist/codecs.d.ts +3 -0
  17. package/dist/codecs.d.ts.map +1 -0
  18. package/dist/codecs.js +9 -0
  19. package/dist/codecs.js.map +1 -0
  20. package/dist/commit-message.d.ts +7 -0
  21. package/dist/commit-message.d.ts.map +1 -0
  22. package/dist/commit-message.js +3 -0
  23. package/dist/commit-message.js.map +1 -0
  24. package/dist/core-capabilities.d.ts +393 -0
  25. package/dist/core-capabilities.d.ts.map +1 -0
  26. package/dist/core-capabilities.js +6 -0
  27. package/dist/core-capabilities.js.map +1 -0
  28. package/dist/define-process.d.ts +269 -0
  29. package/dist/define-process.d.ts.map +1 -0
  30. package/dist/define-process.js +1040 -0
  31. package/dist/define-process.js.map +1 -0
  32. package/dist/event-bus.d.ts +3 -0
  33. package/dist/event-bus.d.ts.map +1 -0
  34. package/dist/event-bus.js +31 -0
  35. package/dist/event-bus.js.map +1 -0
  36. package/dist/extension-api-CnlL69Tu.d.ts +1281 -0
  37. package/dist/extension-api.d.ts +425 -0
  38. package/dist/extension-api.d.ts.map +1 -0
  39. package/dist/extension-api.js +5 -0
  40. package/dist/extension-api.js.map +1 -0
  41. package/dist/flow.d.ts +456 -0
  42. package/dist/flow.d.ts.map +1 -0
  43. package/dist/flow.js +1557 -0
  44. package/dist/flow.js.map +1 -0
  45. package/dist/form-contract.d.ts +2 -0
  46. package/dist/form-contract.d.ts.map +1 -0
  47. package/dist/form-contract.js +2 -0
  48. package/dist/form-contract.js.map +1 -0
  49. package/dist/fs-utils.d.ts +3 -0
  50. package/dist/fs-utils.d.ts.map +1 -0
  51. package/dist/fs-utils.js +23 -0
  52. package/dist/fs-utils.js.map +1 -0
  53. package/dist/git-binary.d.ts +11 -0
  54. package/dist/git-binary.d.ts.map +1 -0
  55. package/dist/git-binary.js +38 -0
  56. package/dist/git-binary.js.map +1 -0
  57. package/dist/graph-fragments.d.ts +23 -0
  58. package/dist/graph-fragments.d.ts.map +1 -0
  59. package/dist/graph-fragments.js +57 -0
  60. package/dist/graph-fragments.js.map +1 -0
  61. package/dist/host-capabilities.d.ts +12 -0
  62. package/dist/host-capabilities.d.ts.map +1 -0
  63. package/dist/host-capabilities.js +42 -0
  64. package/dist/host-capabilities.js.map +1 -0
  65. package/dist/index.d.ts +35 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +29 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/launcher-contract.d.ts +2 -0
  70. package/dist/launcher-contract.d.ts.map +1 -0
  71. package/dist/launcher-contract.js +2 -0
  72. package/dist/launcher-contract.js.map +1 -0
  73. package/dist/leaf-outcome-renderer.d.ts +48 -0
  74. package/dist/leaf-outcome-renderer.d.ts.map +1 -0
  75. package/dist/leaf-outcome-renderer.js +69 -0
  76. package/dist/leaf-outcome-renderer.js.map +1 -0
  77. package/dist/leaf-outcomes.d.ts +5 -0
  78. package/dist/leaf-outcomes.d.ts.map +1 -0
  79. package/dist/leaf-outcomes.js +52 -0
  80. package/dist/leaf-outcomes.js.map +1 -0
  81. package/dist/model-provider.d.ts +210 -0
  82. package/dist/model-provider.d.ts.map +1 -0
  83. package/dist/model-provider.js +171 -0
  84. package/dist/model-provider.js.map +1 -0
  85. package/dist/pi-config.d.ts +59 -0
  86. package/dist/pi-config.d.ts.map +1 -0
  87. package/dist/pi-config.js +182 -0
  88. package/dist/pi-config.js.map +1 -0
  89. package/dist/process-definition-internals.d.ts +7 -0
  90. package/dist/process-definition-internals.d.ts.map +1 -0
  91. package/dist/process-definition-internals.js +25 -0
  92. package/dist/process-definition-internals.js.map +1 -0
  93. package/dist/process-flow-view.d.ts +20 -0
  94. package/dist/process-flow-view.d.ts.map +1 -0
  95. package/dist/process-flow-view.js +418 -0
  96. package/dist/process-flow-view.js.map +1 -0
  97. package/dist/process-graph.d.ts +45 -0
  98. package/dist/process-graph.d.ts.map +1 -0
  99. package/dist/process-graph.js +213 -0
  100. package/dist/process-graph.js.map +1 -0
  101. package/dist/process-launcher-builder.d.ts +9 -0
  102. package/dist/process-launcher-builder.d.ts.map +1 -0
  103. package/dist/process-launcher-builder.js +43 -0
  104. package/dist/process-launcher-builder.js.map +1 -0
  105. package/dist/process-watcher-builder.d.ts +10 -0
  106. package/dist/process-watcher-builder.d.ts.map +1 -0
  107. package/dist/process-watcher-builder.js +40 -0
  108. package/dist/process-watcher-builder.js.map +1 -0
  109. package/dist/registry-utils.d.ts +8 -0
  110. package/dist/registry-utils.d.ts.map +1 -0
  111. package/dist/registry-utils.js +18 -0
  112. package/dist/registry-utils.js.map +1 -0
  113. package/dist/repository-git-env.d.ts +8 -0
  114. package/dist/repository-git-env.d.ts.map +1 -0
  115. package/dist/repository-git-env.js +26 -0
  116. package/dist/repository-git-env.js.map +1 -0
  117. package/dist/review-flow.d.ts +10 -0
  118. package/dist/review-flow.d.ts.map +1 -0
  119. package/dist/review-flow.js +44 -0
  120. package/dist/review-flow.js.map +1 -0
  121. package/dist/runtime-internals.d.ts +3 -0
  122. package/dist/runtime-internals.d.ts.map +1 -0
  123. package/dist/runtime-internals.js +3 -0
  124. package/dist/runtime-internals.js.map +1 -0
  125. package/dist/server-events.d.ts +84 -0
  126. package/dist/server-events.d.ts.map +1 -0
  127. package/dist/server-events.js +2 -0
  128. package/dist/server-events.js.map +1 -0
  129. package/dist/server-process-builder.d.ts +11 -0
  130. package/dist/server-process-builder.d.ts.map +1 -0
  131. package/dist/server-process-builder.js +52 -0
  132. package/dist/server-process-builder.js.map +1 -0
  133. package/dist/state-helpers.d.ts +9 -0
  134. package/dist/state-helpers.d.ts.map +1 -0
  135. package/dist/state-helpers.js +20 -0
  136. package/dist/state-helpers.js.map +1 -0
  137. package/dist/subprocess-env.d.ts +12 -0
  138. package/dist/subprocess-env.d.ts.map +1 -0
  139. package/dist/subprocess-env.js +34 -0
  140. package/dist/subprocess-env.js.map +1 -0
  141. package/dist/tool-renderers.d.ts +10 -0
  142. package/dist/tool-renderers.d.ts.map +1 -0
  143. package/dist/tool-renderers.js +63 -0
  144. package/dist/tool-renderers.js.map +1 -0
  145. package/dist/turn-semantics.d.ts +22 -0
  146. package/dist/turn-semantics.d.ts.map +1 -0
  147. package/dist/turn-semantics.js +339 -0
  148. package/dist/turn-semantics.js.map +1 -0
  149. package/dist/types.d.ts +295 -0
  150. package/dist/types.d.ts.map +1 -0
  151. package/dist/types.js +12 -0
  152. package/dist/types.js.map +1 -0
  153. package/dist/ui-process-builder.d.ts +9 -0
  154. package/dist/ui-process-builder.d.ts.map +1 -0
  155. package/dist/ui-process-builder.js +30 -0
  156. package/dist/ui-process-builder.js.map +1 -0
  157. package/dist/worker-process-builder.d.ts +10 -0
  158. package/dist/worker-process-builder.d.ts.map +1 -0
  159. package/dist/worker-process-builder.js +22 -0
  160. package/dist/worker-process-builder.js.map +1 -0
  161. package/package.json +72 -0
  162. package/src/browser-ui-extension.ts +32 -0
  163. package/src/capabilities.ts +16 -0
  164. package/src/codecs.ts +10 -0
  165. package/src/commit-message.ts +9 -0
  166. package/src/core-capabilities.ts +526 -0
  167. package/src/define-process.ts +1879 -0
  168. package/src/event-bus.ts +35 -0
  169. package/src/extension-api.ts +600 -0
  170. package/src/flow.ts +2268 -0
  171. package/src/form-contract.ts +11 -0
  172. package/src/fs-utils.ts +28 -0
  173. package/src/git-binary.ts +40 -0
  174. package/src/graph-fragments.ts +110 -0
  175. package/src/host-capabilities.ts +60 -0
  176. package/src/index.ts +468 -0
  177. package/src/launcher-contract.ts +8 -0
  178. package/src/leaf-outcome-renderer.ts +112 -0
  179. package/src/leaf-outcomes.ts +74 -0
  180. package/src/model-provider.ts +461 -0
  181. package/src/pi-config.ts +268 -0
  182. package/src/process-definition-internals.ts +46 -0
  183. package/src/process-flow-view.ts +479 -0
  184. package/src/process-graph.ts +309 -0
  185. package/src/process-launcher-builder.ts +59 -0
  186. package/src/process-watcher-builder.ts +72 -0
  187. package/src/registry-utils.ts +31 -0
  188. package/src/repository-git-env.ts +35 -0
  189. package/src/review-flow.ts +66 -0
  190. package/src/runtime-internals.ts +7 -0
  191. package/src/server-events.ts +105 -0
  192. package/src/server-process-builder.ts +90 -0
  193. package/src/state-helpers.ts +36 -0
  194. package/src/subprocess-env.ts +48 -0
  195. package/src/tool-renderers.ts +92 -0
  196. package/src/turn-semantics.ts +554 -0
  197. package/src/types.ts +391 -0
  198. package/src/ui-process-builder.ts +46 -0
  199. package/src/worker-process-builder.ts +33 -0
@@ -0,0 +1,479 @@
1
+ import {
2
+ humanizeProcessLabel,
3
+ type ProcessFlowEdge,
4
+ type ProcessFlowEndState,
5
+ type ProcessFlowNode,
6
+ type ProcessFlowView,
7
+ type ProcessTurnTerminalLifecycleStatus,
8
+ type ProcessTurnTransition,
9
+ type TurnId,
10
+ } from "@leitwerk-dev/domain";
11
+ import type { ProcessGraphTurnView, ProcessGraphView } from "./process-graph.js";
12
+
13
+ function trimToNull(value: string | undefined | null): string | null {
14
+ if (typeof value !== "string") {
15
+ return null;
16
+ }
17
+ const trimmed = value.trim();
18
+ return trimmed === "" ? null : trimmed;
19
+ }
20
+
21
+ /**
22
+ * Human/operator turns are routing decisions: they pick which path the process
23
+ * takes but perform no work themselves. They are collapsed out of the flow graph
24
+ * so the chart shows only work nodes (LLM/automatic/server) and end states, with
25
+ * the operator's decision surfaced as the edge label between the real nodes.
26
+ */
27
+ function isRoutingTurn(turn: ProcessGraphTurnView): boolean {
28
+ return turn.turnType === "human";
29
+ }
30
+
31
+ /**
32
+ * Picks the work turn an operator decision is *about* — its anchor. A decision is
33
+ * both a join (many work turns lead into it) and a split (the operator picks one
34
+ * of several actions). Folding the split onto every join predecessor would invent
35
+ * an N×M mesh of work→work edges that no single step actually connects (e.g. a
36
+ * "review implementation → simplify" edge that does not exist in the process).
37
+ *
38
+ * Instead, every operator decision collapses into exactly one anchor work node:
39
+ * - edges that lead *into* the decision are redirected to the anchor, and
40
+ * - the decision's action edges are emitted *from* the anchor.
41
+ *
42
+ * That yields N+M edges around one real node instead of N×M fabricated ones, and
43
+ * every surviving edge still maps to a single declared transition with one human
44
+ * hop folded into the work node that owns the decision.
45
+ *
46
+ * The anchor is the work predecessor the decision belongs to, preferring a
47
+ * predecessor on the declared happy path (earliest position), then the earliest
48
+ * declared work predecessor. Decisions reached only from other decisions inherit
49
+ * their predecessor decision's anchor.
50
+ */
51
+ function computeRoutingAnchors(
52
+ graph: ProcessGraphView,
53
+ routingIds: ReadonlySet<TurnId>,
54
+ ): Map<TurnId, TurnId> {
55
+ const declarationIndex = new Map<TurnId, number>();
56
+ [...graph.turns.keys()].forEach((turnId, index) => {
57
+ declarationIndex.set(turnId, index);
58
+ });
59
+
60
+ const happyIndex = new Map<TurnId, number>();
61
+ (graph.happyPath ?? []).forEach((turnId, index) => {
62
+ if (!happyIndex.has(turnId)) {
63
+ happyIndex.set(turnId, index);
64
+ }
65
+ });
66
+
67
+ const workPredecessors = new Map<TurnId, TurnId[]>();
68
+ const routingPredecessors = new Map<TurnId, TurnId[]>();
69
+ for (const routingId of routingIds) {
70
+ workPredecessors.set(routingId, []);
71
+ routingPredecessors.set(routingId, []);
72
+ }
73
+ for (const [turnId, turn] of graph.turns) {
74
+ for (const transition of turn.transitions) {
75
+ const next = transition.nextTurnId;
76
+ if (next === undefined || !routingIds.has(next) || next === turnId) {
77
+ continue;
78
+ }
79
+ if (routingIds.has(turnId)) {
80
+ routingPredecessors.get(next)?.push(turnId);
81
+ } else {
82
+ workPredecessors.get(next)?.push(turnId);
83
+ }
84
+ }
85
+ }
86
+
87
+ const preferenceKey = (turnId: TurnId): [number, number] => [
88
+ happyIndex.get(turnId) ?? Number.POSITIVE_INFINITY,
89
+ declarationIndex.get(turnId) ?? Number.POSITIVE_INFINITY,
90
+ ];
91
+ const pickPreferred = (candidates: readonly TurnId[]): TurnId | undefined => {
92
+ let best: TurnId | undefined;
93
+ let bestKey: [number, number] | undefined;
94
+ for (const candidate of candidates) {
95
+ const key = preferenceKey(candidate);
96
+ if (
97
+ bestKey === undefined ||
98
+ key[0] < bestKey[0] ||
99
+ (key[0] === bestKey[0] && key[1] < bestKey[1])
100
+ ) {
101
+ best = candidate;
102
+ bestKey = key;
103
+ }
104
+ }
105
+ return best;
106
+ };
107
+
108
+ const anchors = new Map<TurnId, TurnId>();
109
+ for (const routingId of routingIds) {
110
+ const preferred = pickPreferred(workPredecessors.get(routingId) ?? []);
111
+ if (preferred !== undefined) {
112
+ anchors.set(routingId, preferred);
113
+ }
114
+ }
115
+
116
+ // Decisions reached only from other decisions resolve transitively to the
117
+ // anchor of a predecessor decision. Iterate to a fixpoint.
118
+ let changed = true;
119
+ while (changed) {
120
+ changed = false;
121
+ for (const routingId of routingIds) {
122
+ if (anchors.has(routingId)) {
123
+ continue;
124
+ }
125
+ for (const predecessor of routingPredecessors.get(routingId) ?? []) {
126
+ const predecessorAnchor = anchors.get(predecessor);
127
+ if (predecessorAnchor !== undefined) {
128
+ anchors.set(routingId, predecessorAnchor);
129
+ changed = true;
130
+ break;
131
+ }
132
+ }
133
+ }
134
+ }
135
+
136
+ // Any decision still unresolved (an isolated decision-only cluster) falls back
137
+ // to the first declared work turn so the graph stays connected and deterministic.
138
+ const fallbackWork = [...graph.turns.keys()].find((turnId) => !routingIds.has(turnId));
139
+ if (fallbackWork !== undefined) {
140
+ for (const routingId of routingIds) {
141
+ if (!anchors.has(routingId)) {
142
+ anchors.set(routingId, fallbackWork);
143
+ }
144
+ }
145
+ }
146
+ return anchors;
147
+ }
148
+
149
+ function redirectTransition(
150
+ transition: ProcessTurnTransition,
151
+ resolveWork: (turnId: TurnId) => TurnId,
152
+ ): ProcessTurnTransition {
153
+ const label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
154
+ if (transition.lifecycleStatus !== undefined) {
155
+ return {
156
+ lifecycleStatus: transition.lifecycleStatus,
157
+ ...(label ? { outcome: label } : {}),
158
+ };
159
+ }
160
+ const next = transition.nextTurnId;
161
+ if (next === undefined) {
162
+ return { ...(label ? { outcome: label } : {}) };
163
+ }
164
+ return {
165
+ nextTurnId: resolveWork(next),
166
+ ...(label ? { outcome: label } : {}),
167
+ };
168
+ }
169
+
170
+ function dedupeTransitions(transitions: readonly ProcessTurnTransition[]): ProcessTurnTransition[] {
171
+ const seen = new Set<string>();
172
+ const result: ProcessTurnTransition[] = [];
173
+ for (const transition of transitions) {
174
+ const label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
175
+ const key = `${transition.nextTurnId ?? ""}|${transition.lifecycleStatus ?? ""}|${label ?? ""}`;
176
+ if (seen.has(key)) {
177
+ continue;
178
+ }
179
+ seen.add(key);
180
+ result.push(transition);
181
+ }
182
+ return result;
183
+ }
184
+
185
+ /**
186
+ * Removes routing (human) turns from a process graph by merging each one into a
187
+ * single anchor work node (see {@link computeRoutingAnchors}). Edges into a
188
+ * decision are redirected to its anchor, and the decision's action edges are
189
+ * re-emitted from that anchor. Self-loops produced by the merge are left in place
190
+ * here and dropped later during edge construction. Entry turns and the declared
191
+ * happy path are remapped/filtered to stay consistent.
192
+ */
193
+ export function collapseRoutingTurns(graph: ProcessGraphView): ProcessGraphView {
194
+ const routingIds = new Set<TurnId>();
195
+ for (const [turnId, turn] of graph.turns) {
196
+ if (isRoutingTurn(turn)) {
197
+ routingIds.add(turnId);
198
+ }
199
+ }
200
+ if (routingIds.size === 0) {
201
+ return graph;
202
+ }
203
+ if (routingIds.size === graph.turns.size) {
204
+ return graph;
205
+ }
206
+
207
+ const anchors = computeRoutingAnchors(graph, routingIds);
208
+ const resolveWork = (turnId: TurnId): TurnId =>
209
+ routingIds.has(turnId) ? (anchors.get(turnId) ?? turnId) : turnId;
210
+
211
+ // Group each decision's action transitions onto its anchor work turn.
212
+ const inheritedByAnchor = new Map<TurnId, ProcessTurnTransition[]>();
213
+ for (const routingId of routingIds) {
214
+ const anchor = anchors.get(routingId);
215
+ if (anchor === undefined) {
216
+ continue;
217
+ }
218
+ const routingTurn = graph.turns.get(routingId);
219
+ if (!routingTurn) {
220
+ continue;
221
+ }
222
+ const bucket = inheritedByAnchor.get(anchor) ?? [];
223
+ for (const transition of routingTurn.transitions) {
224
+ bucket.push(redirectTransition(transition, resolveWork));
225
+ }
226
+ inheritedByAnchor.set(anchor, bucket);
227
+ }
228
+
229
+ const turns = new Map<TurnId, ProcessGraphTurnView>();
230
+ for (const [turnId, turn] of graph.turns) {
231
+ if (routingIds.has(turnId)) {
232
+ continue;
233
+ }
234
+ const transitions = [
235
+ ...turn.transitions.map((transition) => redirectTransition(transition, resolveWork)),
236
+ ...(inheritedByAnchor.get(turnId) ?? []),
237
+ ];
238
+ turns.set(turnId, { ...turn, transitions: dedupeTransitions(transitions) });
239
+ }
240
+
241
+ const entryTurnIds = new Set<TurnId>();
242
+ for (const entry of graph.entryTurnIds) {
243
+ if (graph.turns.has(entry)) {
244
+ entryTurnIds.add(resolveWork(entry));
245
+ }
246
+ }
247
+
248
+ const filteredHappyPath = graph.happyPath?.filter((turnId) => !routingIds.has(turnId)) ?? null;
249
+
250
+ return {
251
+ id: graph.id,
252
+ primaryEntryTurnId: resolveWork(graph.primaryEntryTurnId),
253
+ entryTurnIds,
254
+ happyPath: filteredHappyPath && filteredHappyPath.length > 0 ? filteredHappyPath : null,
255
+ turns,
256
+ };
257
+ }
258
+
259
+ /**
260
+ * Best-effort spine when a process does not declare an explicit happy path.
261
+ * Walks `nextTurnId` edges breadth-first from the entry turn to the nearest turn
262
+ * that can reach a `completed` terminal, preferring the shortest forward path and
263
+ * breaking ties by transition declaration order. Returns `[entry]` when no
264
+ * completing path exists.
265
+ */
266
+ function deriveSpine(graph: ProcessGraphView, entry: TurnId): TurnId[] {
267
+ const turnsWithCompletedTerminal = new Set<TurnId>();
268
+ for (const [turnId, turn] of graph.turns) {
269
+ if (turn.transitions.some((transition) => transition.lifecycleStatus === "completed")) {
270
+ turnsWithCompletedTerminal.add(turnId);
271
+ }
272
+ }
273
+ if (turnsWithCompletedTerminal.size === 0) {
274
+ return [entry];
275
+ }
276
+
277
+ const predecessor = new Map<TurnId, TurnId | null>([[entry, null]]);
278
+ const queue: TurnId[] = [entry];
279
+ let goal: TurnId | null = null;
280
+ while (queue.length > 0) {
281
+ const current = queue.shift() as TurnId;
282
+ if (turnsWithCompletedTerminal.has(current)) {
283
+ goal = current;
284
+ break;
285
+ }
286
+ const turn = graph.turns.get(current);
287
+ if (!turn) {
288
+ continue;
289
+ }
290
+ for (const transition of turn.transitions) {
291
+ const next = transition.nextTurnId;
292
+ if (next === undefined || predecessor.has(next) || !graph.turns.has(next)) {
293
+ continue;
294
+ }
295
+ predecessor.set(next, current);
296
+ queue.push(next);
297
+ }
298
+ }
299
+
300
+ if (goal === null) {
301
+ return [entry];
302
+ }
303
+ const reversed: TurnId[] = [];
304
+ let cursor: TurnId | null = goal;
305
+ while (cursor !== null) {
306
+ reversed.push(cursor);
307
+ cursor = predecessor.get(cursor) ?? null;
308
+ }
309
+ return reversed.reverse();
310
+ }
311
+
312
+ /**
313
+ * Assigns each non-spine turn to the spine node it hangs off. A branch is anchored
314
+ * to the lowest-index spine node that can reach it without passing through another
315
+ * spine node, so offshoots attach to the earliest spine step that launches them.
316
+ */
317
+ function deriveBranchAnchors(
318
+ graph: ProcessGraphView,
319
+ spineIndexByTurn: ReadonlyMap<TurnId, number>,
320
+ ): Map<TurnId, TurnId> {
321
+ const anchorByTurn = new Map<TurnId, TurnId>();
322
+ const orderedSpine = [...spineIndexByTurn.entries()]
323
+ .sort((left, right) => left[1] - right[1])
324
+ .map(([turnId]) => turnId);
325
+
326
+ for (const spineTurnId of orderedSpine) {
327
+ const stack: TurnId[] = [spineTurnId];
328
+ const visited = new Set<TurnId>([spineTurnId]);
329
+ while (stack.length > 0) {
330
+ const current = stack.pop() as TurnId;
331
+ const turn = graph.turns.get(current);
332
+ if (!turn) {
333
+ continue;
334
+ }
335
+ for (const transition of turn.transitions) {
336
+ const next = transition.nextTurnId;
337
+ if (next === undefined || !graph.turns.has(next) || visited.has(next)) {
338
+ continue;
339
+ }
340
+ visited.add(next);
341
+ if (spineIndexByTurn.has(next)) {
342
+ // Stop at spine nodes; do not traverse through them.
343
+ continue;
344
+ }
345
+ if (!anchorByTurn.has(next)) {
346
+ anchorByTurn.set(next, spineTurnId);
347
+ }
348
+ stack.push(next);
349
+ }
350
+ }
351
+ }
352
+ return anchorByTurn;
353
+ }
354
+
355
+ function transitionLabel(transition: { outcome?: string; trigger?: string }): string | null {
356
+ // Route every operator-facing edge label through the shared humanizer so the
357
+ // diagram shows nice Title Case names (e.g. `approve_plan` -> `Approve Plan`),
358
+ // consistent with action forms and ready for future localization.
359
+ const raw = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
360
+ return raw === null ? null : humanizeProcessLabel(raw);
361
+ }
362
+
363
+ function buildNode(input: {
364
+ turnId: TurnId;
365
+ turn: ProcessGraphTurnView;
366
+ spineIndex: number | null;
367
+ anchorTurnId: TurnId | null;
368
+ isEntry: boolean;
369
+ }): ProcessFlowNode {
370
+ return {
371
+ turnId: input.turnId,
372
+ description: trimToNull(input.turn.description) ?? input.turnId,
373
+ turnType: input.turn.turnType,
374
+ role: input.spineIndex === null ? "branch" : "spine",
375
+ spineIndex: input.spineIndex,
376
+ anchorTurnId: input.spineIndex === null ? input.anchorTurnId : null,
377
+ isEntry: input.isEntry,
378
+ };
379
+ }
380
+
381
+ /**
382
+ * Projects a process graph into a spine-first flow view for operator-facing
383
+ * diagrams. The spine is the declared happy path (or a derived best-effort path
384
+ * when none is declared); every other turn hangs off the spine as a branch.
385
+ * The `aborted` end state is always present because abort is reachable from any
386
+ * active turn, even when no explicit transition targets it.
387
+ */
388
+ export function buildProcessFlowView(rawGraph: ProcessGraphView): ProcessFlowView {
389
+ const graph = collapseRoutingTurns(rawGraph);
390
+ const entryTurnIds = [...graph.entryTurnIds].filter((turnId) => graph.turns.has(turnId));
391
+ const primaryEntry = graph.turns.has(graph.primaryEntryTurnId)
392
+ ? graph.primaryEntryTurnId
393
+ : [...graph.turns.keys()][0];
394
+
395
+ const declaredSpine = graph.happyPath?.filter((turnId) => graph.turns.has(turnId)) ?? null;
396
+ const spine =
397
+ declaredSpine && declaredSpine.length > 0
398
+ ? [...declaredSpine]
399
+ : primaryEntry !== undefined
400
+ ? deriveSpine(graph, primaryEntry)
401
+ : [];
402
+
403
+ const spineIndexByTurn = new Map<TurnId, number>();
404
+ spine.forEach((turnId, index) => {
405
+ spineIndexByTurn.set(turnId, index);
406
+ });
407
+
408
+ const anchorByTurn = deriveBranchAnchors(graph, spineIndexByTurn);
409
+ const entrySet = new Set(entryTurnIds);
410
+
411
+ const nodes: ProcessFlowNode[] = [];
412
+ for (const [turnId, turn] of graph.turns) {
413
+ const spineIndex = spineIndexByTurn.get(turnId) ?? null;
414
+ nodes.push(
415
+ buildNode({
416
+ turnId,
417
+ turn,
418
+ spineIndex,
419
+ anchorTurnId: anchorByTurn.get(turnId) ?? null,
420
+ isEntry: entrySet.has(turnId),
421
+ }),
422
+ );
423
+ }
424
+
425
+ const edges: ProcessFlowEdge[] = [];
426
+ const terminalStatuses = new Set<ProcessTurnTerminalLifecycleStatus>();
427
+ for (const [turnId, turn] of graph.turns) {
428
+ for (const transition of turn.transitions) {
429
+ const label = transitionLabel(transition);
430
+ if (transition.lifecycleStatus !== undefined) {
431
+ terminalStatuses.add(transition.lifecycleStatus);
432
+ edges.push({
433
+ from: turnId,
434
+ to: null,
435
+ lifecycleStatus: transition.lifecycleStatus,
436
+ kind: "terminal",
437
+ label,
438
+ });
439
+ continue;
440
+ }
441
+ const next = transition.nextTurnId;
442
+ if (next === undefined) {
443
+ continue;
444
+ }
445
+ // Skip self-loops: an edge that leaves and re-enters the same box adds
446
+ // clutter without conveying additional flow.
447
+ if (next === turnId) {
448
+ continue;
449
+ }
450
+ const fromIndex = spineIndexByTurn.get(turnId);
451
+ const toIndex = spineIndexByTurn.get(next);
452
+ let kind: ProcessFlowEdge["kind"];
453
+ if (fromIndex !== undefined && toIndex !== undefined) {
454
+ kind = toIndex === fromIndex + 1 ? "forward" : "loopback";
455
+ } else {
456
+ kind = "branch";
457
+ }
458
+ edges.push({ from: turnId, to: next, lifecycleStatus: null, kind, label });
459
+ }
460
+ }
461
+
462
+ const endStates: ProcessFlowEndState[] = [];
463
+ for (const status of terminalStatuses) {
464
+ endStates.push({ lifecycleStatus: status, synthetic: false });
465
+ }
466
+ if (!terminalStatuses.has("aborted")) {
467
+ endStates.push({ lifecycleStatus: "aborted", synthetic: true });
468
+ }
469
+ endStates.sort((left, right) => left.lifecycleStatus.localeCompare(right.lifecycleStatus));
470
+
471
+ return {
472
+ processId: graph.id,
473
+ entryTurnIds,
474
+ spine,
475
+ nodes,
476
+ edges,
477
+ endStates,
478
+ };
479
+ }