@leitwerk-dev/process-sdk 0.3.1 → 0.4.1

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 (63) hide show
  1. package/dist/{chunk-GVBLXKSR.js → chunk-HT2AXXLH.js} +2 -1
  2. package/dist/chunk-HT2AXXLH.js.map +1 -0
  3. package/dist/core-capabilities.d.ts +63 -2
  4. package/dist/core-capabilities.d.ts.map +1 -1
  5. package/dist/define-process.d.ts +40 -26
  6. package/dist/define-process.d.ts.map +1 -1
  7. package/dist/{extension-api-DM-AvWOW.d.ts → extension-api-Ljc4UTZ0.d.ts} +258 -64
  8. package/dist/extension-api.d.ts +52 -0
  9. package/dist/extension-api.d.ts.map +1 -1
  10. package/dist/external-source-poll.d.ts +1 -1
  11. package/dist/external-source-poll.d.ts.map +1 -1
  12. package/dist/file-external-source.d.ts +32 -0
  13. package/dist/file-external-source.d.ts.map +1 -0
  14. package/dist/flow-mapped.typecheck.d.ts +2 -0
  15. package/dist/flow-mapped.typecheck.d.ts.map +1 -0
  16. package/dist/flow.d.ts +188 -177
  17. package/dist/flow.d.ts.map +1 -1
  18. package/dist/index.d.ts +11 -4
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +4387 -4313
  21. package/dist/index.js.map +1 -1
  22. package/dist/mapped-turn.d.ts +6 -22
  23. package/dist/mapped-turn.d.ts.map +1 -1
  24. package/dist/outcome-contract.d.ts +19 -0
  25. package/dist/outcome-contract.d.ts.map +1 -0
  26. package/dist/outcome-schema.d.ts +25 -0
  27. package/dist/outcome-schema.d.ts.map +1 -0
  28. package/dist/pi-config-public.js +1 -1
  29. package/dist/pi-config.js +1 -1
  30. package/dist/process-flow-view.d.ts +3 -14
  31. package/dist/process-flow-view.d.ts.map +1 -1
  32. package/dist/process-graph.d.ts +10 -4
  33. package/dist/process-graph.d.ts.map +1 -1
  34. package/dist/scoped-settings.d.ts +87 -0
  35. package/dist/scoped-settings.d.ts.map +1 -0
  36. package/dist/ticket-creation.d.ts +24 -0
  37. package/dist/ticket-creation.d.ts.map +1 -0
  38. package/dist/turn-semantics.d.ts +3 -3
  39. package/dist/turn-semantics.d.ts.map +1 -1
  40. package/dist/turn-wait.d.ts +53 -0
  41. package/dist/turn-wait.d.ts.map +1 -0
  42. package/dist/types.d.ts +31 -18
  43. package/dist/types.d.ts.map +1 -1
  44. package/package.json +6 -6
  45. package/src/core-capabilities.ts +87 -1
  46. package/src/define-process.ts +420 -596
  47. package/src/extension-api.ts +60 -0
  48. package/src/external-source-poll.ts +6 -24
  49. package/src/file-external-source.ts +135 -0
  50. package/src/flow-mapped.typecheck.ts +136 -0
  51. package/src/flow.ts +746 -815
  52. package/src/index.ts +48 -1
  53. package/src/mapped-turn.ts +74 -23
  54. package/src/outcome-contract.ts +119 -0
  55. package/src/outcome-schema.ts +315 -0
  56. package/src/process-flow-view.ts +84 -346
  57. package/src/process-graph.ts +95 -45
  58. package/src/scoped-settings.ts +113 -0
  59. package/src/ticket-creation.ts +113 -0
  60. package/src/turn-semantics.ts +85 -193
  61. package/src/turn-wait.ts +76 -0
  62. package/src/types.ts +30 -16
  63. package/dist/chunk-GVBLXKSR.js.map +0 -1
@@ -5,274 +5,22 @@ import {
5
5
  type ProcessFlowNode,
6
6
  type ProcessFlowView,
7
7
  type ProcessTurnTerminalLifecycleStatus,
8
- type ProcessTurnTransition,
8
+ shortestSuccessfulTurnPath,
9
9
  type TurnId,
10
10
  trimToNull,
11
11
  } from "@leitwerk-dev/domain";
12
- import type { ProcessGraphTurnView, ProcessGraphView } from "./process-graph.js";
12
+ import type { ProcessGraphView } from "./process-graph.js";
13
13
 
14
- /**
15
- * Human/operator turns are routing decisions: they pick which path the process
16
- * takes but perform no work themselves. They are collapsed out of the flow graph
17
- * so the chart shows only work nodes (LLM/automatic/server) and end states, with
18
- * the operator's decision surfaced as the edge label between the real nodes.
19
- */
20
- function isRoutingTurn(turn: ProcessGraphTurnView): boolean {
21
- return turn.turnType === "human";
22
- }
23
-
24
- /**
25
- * Picks the work turn an operator decision is *about* — its anchor. A decision is
26
- * both a join (many work turns lead into it) and a split (the operator picks one
27
- * of several actions). Folding the split onto every join predecessor would invent
28
- * an N×M mesh of work→work edges that no single step actually connects (e.g. a
29
- * "review implementation → simplify" edge that does not exist in the process).
30
- *
31
- * Instead, every operator decision collapses into exactly one anchor work node:
32
- * - edges that lead *into* the decision are redirected to the anchor, and
33
- * - the decision's action edges are emitted *from* the anchor.
34
- *
35
- * That yields N+M edges around one real node instead of N×M fabricated ones, and
36
- * every surviving edge still maps to a single declared transition with one human
37
- * hop folded into the work node that owns the decision.
38
- *
39
- * The anchor is the work predecessor the decision belongs to, preferring a
40
- * predecessor on the declared happy path (earliest position), then the earliest
41
- * declared work predecessor. Decisions reached only from other decisions inherit
42
- * their predecessor decision's anchor.
43
- */
44
- function computeRoutingAnchors(
45
- graph: ProcessGraphView,
46
- routingIds: ReadonlySet<TurnId>,
47
- ): Map<TurnId, TurnId> {
48
- // Happy-path turns come first, then the remaining turns in declaration order.
49
- const preferenceIndex = new Map(
50
- [...new Set([...(graph.happyPath ?? []), ...graph.turns.keys()])].map((turnId, index) => [
51
- turnId,
52
- index,
53
- ]),
54
- );
55
-
56
- const workPredecessors = new Map<TurnId, TurnId[]>();
57
- const routingPredecessors = new Map<TurnId, TurnId[]>();
58
- for (const routingId of routingIds) {
59
- workPredecessors.set(routingId, []);
60
- routingPredecessors.set(routingId, []);
61
- }
62
- for (const [turnId, turn] of graph.turns) {
63
- for (const transition of turn.transitions) {
64
- const next = transition.nextTurnId;
65
- if (next === undefined || !routingIds.has(next) || next === turnId) {
66
- continue;
67
- }
68
- if (routingIds.has(turnId)) {
69
- routingPredecessors.get(next)?.push(turnId);
70
- } else {
71
- workPredecessors.get(next)?.push(turnId);
72
- }
73
- }
74
- }
75
-
76
- const pickPreferred = (candidates: readonly TurnId[]): TurnId | undefined => {
77
- let best: TurnId | undefined;
78
- let bestIndex = Number.POSITIVE_INFINITY;
79
- for (const candidate of candidates) {
80
- const index = preferenceIndex.get(candidate) ?? Number.POSITIVE_INFINITY;
81
- if (best === undefined || index < bestIndex) {
82
- best = candidate;
83
- bestIndex = index;
84
- }
85
- }
86
- return best;
87
- };
88
-
89
- const anchors = new Map<TurnId, TurnId>();
90
- for (const routingId of routingIds) {
91
- const preferred = pickPreferred(workPredecessors.get(routingId) ?? []);
92
- if (preferred !== undefined) {
93
- anchors.set(routingId, preferred);
94
- }
95
- }
96
-
97
- // Decisions reached only from other decisions resolve transitively to the
98
- // anchor of a predecessor decision. Iterate to a fixpoint.
99
- let changed = true;
100
- while (changed) {
101
- changed = false;
102
- for (const routingId of routingIds) {
103
- if (anchors.has(routingId)) {
104
- continue;
105
- }
106
- for (const predecessor of routingPredecessors.get(routingId) ?? []) {
107
- const predecessorAnchor = anchors.get(predecessor);
108
- if (predecessorAnchor !== undefined) {
109
- anchors.set(routingId, predecessorAnchor);
110
- changed = true;
111
- break;
112
- }
113
- }
114
- }
115
- }
116
-
117
- // Any decision still unresolved (an isolated decision-only cluster) falls back
118
- // to the first declared work turn so the graph stays connected and deterministic.
119
- const fallbackWork = [...graph.turns.keys()].find((turnId) => !routingIds.has(turnId));
120
- if (fallbackWork !== undefined) {
121
- for (const routingId of routingIds) {
122
- if (!anchors.has(routingId)) {
123
- anchors.set(routingId, fallbackWork);
124
- }
125
- }
126
- }
127
- return anchors;
128
- }
129
-
130
- function redirectTransition(
131
- transition: ProcessTurnTransition,
132
- resolveWork: (turnId: TurnId) => TurnId,
133
- ): ProcessTurnTransition {
134
- const label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
135
- if (transition.lifecycleStatus !== undefined) {
136
- return {
137
- lifecycleStatus: transition.lifecycleStatus,
138
- ...(label ? { outcome: label } : {}),
139
- };
140
- }
141
- const next = transition.nextTurnId;
142
- if (next === undefined) {
143
- return { ...(label ? { outcome: label } : {}) };
144
- }
145
- return {
146
- nextTurnId: resolveWork(next),
147
- ...(label ? { outcome: label } : {}),
148
- };
149
- }
150
-
151
- function dedupeTransitions(transitions: readonly ProcessTurnTransition[]): ProcessTurnTransition[] {
152
- const result = new Map<string, ProcessTurnTransition>();
153
- for (const transition of transitions) {
154
- const label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
155
- const key = `${transition.nextTurnId ?? ""}|${transition.lifecycleStatus ?? ""}|${label ?? ""}`;
156
- if (result.has(key)) {
157
- continue;
158
- }
159
- result.set(key, transition);
160
- }
161
- return [...result.values()];
162
- }
163
-
164
- /**
165
- * Removes routing (human) turns from a process graph by merging each one into a
166
- * single anchor work node (see {@link computeRoutingAnchors}). Edges into a
167
- * decision are redirected to its anchor, and the decision's action edges are
168
- * re-emitted from that anchor. Self-loops produced by the merge are left in place
169
- * here and dropped later during edge construction. Entry turns and the declared
170
- * happy path are remapped/filtered to stay consistent.
171
- */
172
- /** @internal */
173
- export function collapseRoutingTurns(graph: ProcessGraphView): ProcessGraphView {
174
- const routingIds = new Set<TurnId>();
175
- for (const [turnId, turn] of graph.turns) {
176
- if (isRoutingTurn(turn)) {
177
- routingIds.add(turnId);
178
- }
179
- }
180
- if (routingIds.size === 0 || routingIds.size === graph.turns.size) {
181
- return graph;
182
- }
183
-
184
- const anchors = computeRoutingAnchors(graph, routingIds);
185
- const resolveWork = (turnId: TurnId): TurnId =>
186
- routingIds.has(turnId) ? (anchors.get(turnId) ?? turnId) : turnId;
187
-
188
- // Group each decision's action transitions onto its anchor work turn.
189
- const inheritedByAnchor = new Map<TurnId, ProcessTurnTransition[]>();
190
- for (const routingId of routingIds) {
191
- const anchor = anchors.get(routingId);
192
- if (anchor === undefined) {
193
- continue;
194
- }
195
- const routingTurn = graph.turns.get(routingId);
196
- if (!routingTurn) {
197
- continue;
198
- }
199
- const bucket = inheritedByAnchor.get(anchor) ?? [];
200
- for (const transition of routingTurn.transitions) {
201
- bucket.push(redirectTransition(transition, resolveWork));
202
- }
203
- inheritedByAnchor.set(anchor, bucket);
204
- }
205
-
206
- const turns = new Map<TurnId, ProcessGraphTurnView>();
207
- for (const [turnId, turn] of graph.turns) {
208
- if (routingIds.has(turnId)) {
209
- continue;
210
- }
211
- const transitions = [
212
- ...turn.transitions.map((transition) => redirectTransition(transition, resolveWork)),
213
- ...(inheritedByAnchor.get(turnId) ?? []),
214
- ];
215
- turns.set(turnId, { ...turn, transitions: dedupeTransitions(transitions) });
216
- }
217
-
218
- const entryTurnIds = new Set<TurnId>();
219
- for (const entry of graph.entryTurnIds) {
220
- if (graph.turns.has(entry)) {
221
- entryTurnIds.add(resolveWork(entry));
222
- }
223
- }
224
-
225
- const filteredHappyPath = graph.happyPath?.filter((turnId) => !routingIds.has(turnId)) ?? null;
226
-
227
- return {
228
- id: graph.id,
229
- primaryEntryTurnId: resolveWork(graph.primaryEntryTurnId),
230
- entryTurnIds,
231
- happyPath: filteredHappyPath && filteredHappyPath.length > 0 ? filteredHappyPath : null,
232
- turns,
233
- };
234
- }
235
-
236
- /**
237
- * Best-effort spine when a process does not declare an explicit happy path.
238
- * Walks `nextTurnId` edges breadth-first from the entry turn to the nearest turn
239
- * that can reach a `completed` terminal, preferring the shortest forward path and
240
- * breaking ties by transition declaration order. Returns `[entry]` when no
241
- * completing path exists.
242
- */
243
14
  function deriveSpine(graph: ProcessGraphView, entry: TurnId): TurnId[] {
244
- const predecessor = new Map<TurnId, TurnId | null>([[entry, null]]);
245
- const queue: TurnId[] = [entry];
246
- let goal: TurnId | null = null;
247
- for (const current of queue) {
248
- const turn = graph.turns.get(current);
249
- if (!turn) {
250
- continue;
251
- }
252
- if (turn.transitions.some((transition) => transition.lifecycleStatus === "completed")) {
253
- goal = current;
254
- break;
255
- }
256
- for (const transition of turn.transitions) {
257
- const next = transition.nextTurnId;
258
- if (next === undefined || predecessor.has(next) || !graph.turns.has(next)) {
259
- continue;
260
- }
261
- predecessor.set(next, current);
262
- queue.push(next);
263
- }
264
- }
265
-
266
- if (goal === null) {
267
- return [entry];
268
- }
269
- const reversed: TurnId[] = [];
270
- let cursor: TurnId | null = goal;
271
- while (cursor !== null) {
272
- reversed.push(cursor);
273
- cursor = predecessor.get(cursor) ?? null;
274
- }
275
- return reversed.reverse();
15
+ return shortestSuccessfulTurnPath(entry, (id) =>
16
+ (graph.turns.get(id)?.transitions ?? []).flatMap((transition) =>
17
+ transition.lifecycleStatus === "completed"
18
+ ? [null]
19
+ : transition.nextTurnId !== undefined && graph.turns.has(transition.nextTurnId)
20
+ ? [transition.nextTurnId]
21
+ : [],
22
+ ),
23
+ );
276
24
  }
277
25
 
278
26
  /**
@@ -282,43 +30,35 @@ function deriveSpine(graph: ProcessGraphView, entry: TurnId): TurnId[] {
282
30
  */
283
31
  function deriveBranchAnchors(
284
32
  graph: ProcessGraphView,
285
- spineIndexByTurn: ReadonlyMap<TurnId, number>,
33
+ spine: readonly TurnId[],
286
34
  ): Map<TurnId, TurnId> {
287
35
  const anchorByTurn = new Map<TurnId, TurnId>();
288
- const orderedSpine = [...spineIndexByTurn.entries()]
289
- .sort((left, right) => left[1] - right[1])
290
- .map(([turnId]) => turnId);
291
-
292
- for (const spineTurnId of orderedSpine) {
293
- const stack: TurnId[] = [spineTurnId];
294
- const visited = new Set<TurnId>([spineTurnId]);
295
- while (stack.length > 0) {
296
- const current = stack.pop() as TurnId;
297
- const turn = graph.turns.get(current);
298
- if (!turn) {
299
- continue;
300
- }
301
- for (const transition of turn.transitions) {
302
- const next = transition.nextTurnId;
303
- if (next === undefined || !graph.turns.has(next) || visited.has(next)) {
36
+ const spineIds = new Set(spine);
37
+ for (const spineTurnId of spine) {
38
+ const queue = [spineTurnId];
39
+ for (const current of queue) {
40
+ for (const { nextTurnId: next } of graph.turns.get(current)?.transitions ?? []) {
41
+ if (
42
+ next === undefined ||
43
+ !graph.turns.has(next) ||
44
+ spineIds.has(next) ||
45
+ anchorByTurn.has(next)
46
+ )
304
47
  continue;
305
- }
306
- visited.add(next);
307
- if (spineIndexByTurn.has(next)) {
308
- // Stop at spine nodes; do not traverse through them.
309
- continue;
310
- }
311
- if (!anchorByTurn.has(next)) {
312
- anchorByTurn.set(next, spineTurnId);
313
- }
314
- stack.push(next);
48
+ // Earlier anchors have already explored their non-spine descendants.
49
+ anchorByTurn.set(next, spineTurnId);
50
+ queue.push(next);
315
51
  }
316
52
  }
317
53
  }
318
54
  return anchorByTurn;
319
55
  }
320
56
 
321
- function transitionLabel(transition: { outcome?: string; trigger?: string }): string | null {
57
+ function transitionLabel(
58
+ transition: { outcome?: string; trigger?: string },
59
+ labels?: Readonly<Record<string, string>>,
60
+ ): string | null {
61
+ if (transition.trigger && labels?.[transition.trigger]) return labels[transition.trigger];
322
62
  // Route every operator-facing edge label through the shared humanizer so the
323
63
  // diagram shows nice Title Case names (e.g. `approve_plan` -> `Approve Plan`),
324
64
  // consistent with action forms and ready for future localization.
@@ -327,39 +67,40 @@ function transitionLabel(transition: { outcome?: string; trigger?: string }): st
327
67
  }
328
68
 
329
69
  /**
330
- * Projects a process graph into a spine-first flow view for operator-facing
331
- * diagrams. The spine is the declared happy path (or a derived best-effort path
332
- * when none is declared); every other turn hangs off the spine as a branch.
70
+ * Projects every declared turn and route. The shortest successful route defines
71
+ * the spine; operator decisions and mapped turns each count as one turn.
333
72
  * The `aborted` end state is always present because abort is reachable from any
334
73
  * active turn, even when no explicit transition targets it.
335
74
  */
336
75
  /** @internal */
337
- export function buildProcessFlowView(rawGraph: ProcessGraphView): ProcessFlowView {
338
- const graph = collapseRoutingTurns(rawGraph);
76
+ export function buildProcessFlowView(graph: ProcessGraphView): ProcessFlowView {
339
77
  const entryTurnIds = [...graph.entryTurnIds].filter((turnId) => graph.turns.has(turnId));
340
78
  const primaryEntry = graph.turns.has(graph.primaryEntryTurnId)
341
79
  ? graph.primaryEntryTurnId
342
80
  : [...graph.turns.keys()][0];
343
81
 
344
- const declaredSpine = graph.happyPath?.filter((turnId) => graph.turns.has(turnId)) ?? null;
345
- const spine =
346
- declaredSpine && declaredSpine.length > 0
347
- ? [...declaredSpine]
348
- : primaryEntry !== undefined
349
- ? deriveSpine(graph, primaryEntry)
350
- : [];
351
-
352
- const spineIndexByTurn = new Map<TurnId, number>();
353
- spine.forEach((turnId, index) => {
354
- spineIndexByTurn.set(turnId, index);
355
- });
82
+ const spine = primaryEntry !== undefined ? deriveSpine(graph, primaryEntry) : [];
356
83
 
357
- const anchorByTurn = deriveBranchAnchors(graph, spineIndexByTurn);
84
+ const spineIndexByTurn = new Map(spine.map((turnId, index) => [turnId, index]));
85
+ const anchorByTurn = deriveBranchAnchors(graph, spine);
358
86
  const entrySet = new Set(entryTurnIds);
359
87
 
360
88
  const nodes: ProcessFlowNode[] = [];
361
89
  for (const [turnId, turn] of graph.turns) {
362
90
  const spineIndex = spineIndexByTurn.get(turnId) ?? null;
91
+ const inputs = [
92
+ ...new Set([
93
+ ...(turn.consumedProducts ?? []),
94
+ ...(turn.optionalConsumedProducts ?? []),
95
+ ...(turn.reviewProduct ? [turn.reviewProduct] : []),
96
+ ]),
97
+ ];
98
+ const outputs = [
99
+ ...new Set([
100
+ ...(turn.publishedProducts ?? []),
101
+ ...(turn.publishedProduct ? [turn.publishedProduct] : []),
102
+ ]),
103
+ ];
363
104
  nodes.push({
364
105
  turnId,
365
106
  description: trimToNull(turn.description) ?? turnId,
@@ -368,6 +109,11 @@ export function buildProcessFlowView(rawGraph: ProcessGraphView): ProcessFlowVie
368
109
  spineIndex,
369
110
  anchorTurnId: spineIndex === null ? (anchorByTurn.get(turnId) ?? null) : null,
370
111
  isEntry: entrySet.has(turnId),
112
+ ...(turn.repetition ? { repetition: turn.repetition } : {}),
113
+ ...(turn.tools ? { tools: turn.tools.map((tool) => ({ ...tool })) } : {}),
114
+ ...(turn.hasDynamicTools ? { hasDynamicTools: true } : {}),
115
+ ...(inputs.length ? { inputProducts: inputs } : {}),
116
+ ...(outputs.length ? { outputProducts: outputs } : {}),
371
117
  });
372
118
  }
373
119
 
@@ -375,44 +121,36 @@ export function buildProcessFlowView(rawGraph: ProcessGraphView): ProcessFlowVie
375
121
  const terminalStatuses = new Set<ProcessTurnTerminalLifecycleStatus>();
376
122
  for (const [turnId, turn] of graph.turns) {
377
123
  for (const transition of turn.transitions) {
378
- const label = transitionLabel(transition);
379
- if (transition.lifecycleStatus !== undefined) {
380
- terminalStatuses.add(transition.lifecycleStatus);
381
- edges.push({
382
- from: turnId,
383
- to: null,
384
- lifecycleStatus: transition.lifecycleStatus,
385
- kind: "terminal",
386
- label,
387
- });
388
- continue;
389
- }
390
- const next = transition.nextTurnId;
391
- // Skip self-loops: an edge that leaves and re-enters the same box adds
392
- // clutter without conveying additional flow.
393
- if (next === undefined || next === turnId) {
394
- continue;
395
- }
124
+ const lifecycleStatus = transition.lifecycleStatus ?? null;
125
+ const next = lifecycleStatus === null ? (transition.nextTurnId ?? null) : null;
126
+ if (lifecycleStatus === null && next === null) continue;
127
+ if (lifecycleStatus !== null) terminalStatuses.add(lifecycleStatus);
396
128
  const fromIndex = spineIndexByTurn.get(turnId);
397
- const toIndex = spineIndexByTurn.get(next);
398
- let kind: ProcessFlowEdge["kind"];
399
- if (fromIndex !== undefined && toIndex !== undefined) {
400
- kind = toIndex === fromIndex + 1 ? "forward" : "loopback";
401
- } else {
402
- kind = "branch";
403
- }
404
- edges.push({ from: turnId, to: next, lifecycleStatus: null, kind, label });
405
- }
406
- }
407
-
408
- const endStates: ProcessFlowEndState[] = [];
409
- for (const status of terminalStatuses) {
410
- endStates.push({ lifecycleStatus: status, synthetic: false });
411
- }
412
- if (!terminalStatuses.has("aborted")) {
413
- endStates.push({ lifecycleStatus: "aborted", synthetic: true });
414
- }
415
- endStates.sort((left, right) => left.lifecycleStatus.localeCompare(right.lifecycleStatus));
129
+ const toIndex = next === null ? undefined : spineIndexByTurn.get(next);
130
+ edges.push({
131
+ from: turnId,
132
+ to: next,
133
+ lifecycleStatus,
134
+ kind:
135
+ lifecycleStatus !== null
136
+ ? "terminal"
137
+ : fromIndex !== undefined && toIndex !== undefined
138
+ ? toIndex > fromIndex
139
+ ? "forward"
140
+ : "loopback"
141
+ : "branch",
142
+ label: transitionLabel(transition, turn.transitionLabels),
143
+ ...(transition.condition ? { condition: { ...transition.condition } } : {}),
144
+ });
145
+ }
146
+ }
147
+
148
+ const endStates: ProcessFlowEndState[] = [...new Set([...terminalStatuses, "aborted" as const])]
149
+ .map((lifecycleStatus) => ({
150
+ lifecycleStatus,
151
+ synthetic: !terminalStatuses.has(lifecycleStatus),
152
+ }))
153
+ .sort((left, right) => left.lifecycleStatus.localeCompare(right.lifecycleStatus));
416
154
 
417
155
  return {
418
156
  processId: graph.id,
@@ -1,11 +1,14 @@
1
1
  import type {
2
+ ProcessFlowEdge,
3
+ ProcessFlowNode,
4
+ ProcessFlowTool,
2
5
  ProcessSemanticEntryRefKey,
3
6
  ProcessTurnTransition,
4
7
  ProcessTurnType,
5
8
  SerializedProcessGraph,
6
9
  TurnId,
7
10
  } from "@leitwerk-dev/domain";
8
- import { isValidProcessProductName } from "@leitwerk-dev/domain";
11
+ import { humanizeProcessLabel, isValidProcessProductName, trimToNull } from "@leitwerk-dev/domain";
9
12
  import type { TurnDefinition } from "./define-process.js";
10
13
  import type { ExtensionProcessDefinition, ProcessTurnBinding } from "./extension-api.js";
11
14
  import { getProcessTurnTransitions } from "./process-definition-internals.js";
@@ -21,8 +24,16 @@ export interface ProcessGraphTurnView {
21
24
  turnType: ProcessTurnType;
22
25
  /** @internal */
23
26
  description: string;
27
+ /** Definition-only display metadata; never evaluates turn callbacks. @internal */
28
+ repetition?: ProcessFlowNode["repetition"];
24
29
  /** @internal */
25
- transitions: readonly ProcessTurnTransition[];
30
+ tools?: ProcessFlowTool[];
31
+ /** @internal */
32
+ hasDynamicTools?: boolean;
33
+ /** @internal */
34
+ transitions: readonly (ProcessTurnTransition & Pick<ProcessFlowEdge, "condition">)[];
35
+ /** Display labels for external triggers; durable route identities remain unchanged. @internal */
36
+ transitionLabels?: Readonly<Record<string, string>>;
26
37
  /** @internal */
27
38
  reviewProduct?: string;
28
39
  /** @internal */
@@ -71,11 +82,6 @@ function turnPublishedProducts(definition: TurnDefinition<unknown, unknown>): st
71
82
  }
72
83
  }
73
84
  }
74
- for (const action of Object.values(definition.externalActions ?? {})) {
75
- if (action.publishInput) {
76
- products.add(action.publishInput.productName);
77
- }
78
- }
79
85
  } else if (definition.kind === "llm" || definition.kind === "automatic") {
80
86
  for (const outcome of Object.values(definition.outcomes ?? {})) {
81
87
  if (typeof outcome?.publishedProduct === "string") {
@@ -83,6 +89,13 @@ function turnPublishedProducts(definition: TurnDefinition<unknown, unknown>): st
83
89
  }
84
90
  }
85
91
  }
92
+ if (definition.kind !== "external") {
93
+ for (const action of Object.values(definition.externalActions ?? {})) {
94
+ if (action.publishInput) {
95
+ products.add(action.publishInput.productName);
96
+ }
97
+ }
98
+ }
86
99
  return [...products];
87
100
  }
88
101
 
@@ -91,39 +104,85 @@ function toTurnView(
91
104
  ): ProcessGraphTurnView {
92
105
  const definition = binding.definition;
93
106
  const publishedProducts = turnPublishedProducts(definition);
94
- return {
107
+ const transitionLabels =
108
+ definition.kind !== "external"
109
+ ? Object.fromEntries(
110
+ Object.entries(definition.externalActions ?? {}).flatMap(([id, action]) => {
111
+ const label = action.label ?? action.source.label;
112
+ return label ? [[`external:${id}`, label]] : [];
113
+ }),
114
+ )
115
+ : {};
116
+ const view: ProcessGraphTurnView = {
95
117
  turnType: definition.kind,
96
118
  description: definition.description,
97
- transitions: getProcessTurnTransitions(binding),
119
+ transitions: getProcessTurnTransitions(binding).map((transition) => {
120
+ const outcome =
121
+ (definition.kind === "llm" || definition.kind === "automatic") && transition.outcome
122
+ ? definition.outcomes?.[transition.outcome]
123
+ : undefined;
124
+ if (!outcome || !("branches" in outcome) || !transition.trigger) return transition;
125
+ const branch = Object.entries(outcome.branches).find(
126
+ ([id, spec]) => (spec.trigger ?? id) === transition.trigger,
127
+ )?.[1];
128
+ if (!branch) return transition;
129
+ const description = trimToNull(branch.description);
130
+ return {
131
+ ...transition,
132
+ condition: {
133
+ label: trimToNull(branch.label) ?? humanizeProcessLabel(transition.trigger),
134
+ ...(description ? { description } : {}),
135
+ },
136
+ };
137
+ }),
138
+ ...(Object.keys(transitionLabels).length ? { transitionLabels } : {}),
98
139
  ...(definition.kind === "human" && definition.reviewProduct
99
140
  ? { reviewProduct: definition.reviewProduct }
100
141
  : {}),
101
- ...(definition.kind === "llm" && definition.resultSemanticRef
102
- ? { resultSemanticRef: definition.resultSemanticRef }
103
- : {}),
104
- ...(definition.kind === "llm" && definition.publishedProduct
105
- ? { publishedProduct: definition.publishedProduct }
106
- : {}),
107
142
  ...(publishedProducts.length > 0 ? { publishedProducts } : {}),
108
- ...(definition.kind === "llm" && definition.consumedProducts?.length
109
- ? { consumedProducts: [...definition.consumedProducts] }
110
- : {}),
111
- ...(definition.kind === "llm" && definition.optionalConsumedProducts?.length
112
- ? { optionalConsumedProducts: [...definition.optionalConsumedProducts] }
113
- : {}),
114
- ...(definition.kind === "llm" && definition.requiredSemanticMarkdownRefs?.length
115
- ? { requiredSemanticMarkdownRefs: [...definition.requiredSemanticMarkdownRefs] }
116
- : {}),
117
- ...(definition.kind === "llm" && definition.optionalSemanticMarkdownRefs?.length
118
- ? { optionalSemanticMarkdownRefs: [...definition.optionalSemanticMarkdownRefs] }
119
- : {}),
120
- ...(definition.kind === "llm" &&
121
- definition.turnResultMarkdown &&
122
- "required" in definition.turnResultMarkdown &&
123
- definition.turnResultMarkdown.required === true
124
- ? { turnResultMarkdownRequired: true }
125
- : {}),
126
143
  };
144
+ if (definition.kind === "llm") {
145
+ if (definition.forEach) view.repetition = "sequential";
146
+ view.tools = declaredFlowTools(definition);
147
+ view.hasDynamicTools = definition.resolveIntegrationTools !== undefined;
148
+ if (definition.resultSemanticRef) view.resultSemanticRef = definition.resultSemanticRef;
149
+ if (definition.publishedProduct) view.publishedProduct = definition.publishedProduct;
150
+ if (definition.consumedProducts?.length)
151
+ view.consumedProducts = [...definition.consumedProducts];
152
+ if (definition.optionalConsumedProducts?.length)
153
+ view.optionalConsumedProducts = [...definition.optionalConsumedProducts];
154
+ if (definition.requiredSemanticMarkdownRefs?.length)
155
+ view.requiredSemanticMarkdownRefs = [...definition.requiredSemanticMarkdownRefs];
156
+ if (definition.optionalSemanticMarkdownRefs?.length)
157
+ view.optionalSemanticMarkdownRefs = [...definition.optionalSemanticMarkdownRefs];
158
+ if (
159
+ definition.turnResultMarkdown &&
160
+ "required" in definition.turnResultMarkdown &&
161
+ definition.turnResultMarkdown.required === true
162
+ )
163
+ view.turnResultMarkdownRequired = true;
164
+ }
165
+ return view;
166
+ }
167
+
168
+ function declaredFlowTools(
169
+ definition: Extract<TurnDefinition, { kind: "llm" }>,
170
+ ): ProcessFlowTool[] {
171
+ const tool = (
172
+ name: string,
173
+ category: ProcessFlowTool["category"],
174
+ description: string | null = null,
175
+ ): ProcessFlowTool => ({ name, category, description });
176
+ return [
177
+ ...definition.availableTools.map((name) => tool(name, "workspace")),
178
+ ...(definition.integrationTools ?? []).map((name) => tool(name, "integration")),
179
+ ...(definition.askQuestions
180
+ ? [tool("ask_questions", "question", "Ask the operator structured questions.")]
181
+ : []),
182
+ ...Object.entries(definition.outcomes ?? {}).flatMap(([name, outcome]) =>
183
+ outcome ? [tool(name, "outcome", outcome.description)] : [],
184
+ ),
185
+ ];
127
186
  }
128
187
 
129
188
  /**
@@ -211,7 +270,9 @@ export function serializeProcessGraph(
211
270
  const definition = getProcessGraph(registry, processId);
212
271
  const turnTransitions: Record<TurnId, ProcessTurnTransition[]> = {};
213
272
  for (const [turnId, turn] of definition.turns) {
214
- turnTransitions[turnId] = turn.transitions.map((transition) => ({ ...transition }));
273
+ turnTransitions[turnId] = turn.transitions.map(
274
+ ({ condition: _condition, ...transition }) => transition,
275
+ );
215
276
  }
216
277
  return {
217
278
  id: definition.id,
@@ -235,17 +296,6 @@ function isTerminalLifecycleStatus(value: string | undefined): value is "complet
235
296
  return value === "completed" || value === "aborted";
236
297
  }
237
298
 
238
- /** @internal */
239
- export function validateProcessGraphEntryTurns(graph: ProcessGraphView): readonly string[] {
240
- const errors: string[] = [];
241
- for (const turnId of graph.entryTurnIds) {
242
- if (!graph.turns.has(turnId)) {
243
- errors.push(`Entry turn '${turnId}' is not declared in turns`);
244
- }
245
- }
246
- return errors;
247
- }
248
-
249
299
  /** @internal */
250
300
  export function validateProcessGraphProducts(graph: ProcessGraphView): readonly string[] {
251
301
  const errors: string[] = [];