@leitwerk-dev/server 0.2.1 → 0.3.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 (123) hide show
  1. package/dist/{app-WfwKzrVk.d.ts → app-BuJCdkvy.d.ts} +82 -2
  2. package/dist/app-MSJXFK33.js +8 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/{chunk-ZSKM25SD.js → chunk-HK6BLLHA.js} +1702 -496
  5. package/dist/chunk-HK6BLLHA.js.map +1 -0
  6. package/dist/{chunk-CNITOV76.js → chunk-QCHS3X33.js} +546 -1132
  7. package/dist/chunk-QCHS3X33.js.map +1 -0
  8. package/dist/db/database.d.ts.map +1 -1
  9. package/dist/db/mapped-llm-run-repo.d.ts +56 -0
  10. package/dist/db/mapped-llm-run-repo.d.ts.map +1 -0
  11. package/dist/db/process-turn-record-repo.d.ts +3 -1
  12. package/dist/db/process-turn-record-repo.d.ts.map +1 -1
  13. package/dist/db/repo-helpers.d.ts +6 -0
  14. package/dist/db/repo-helpers.d.ts.map +1 -1
  15. package/dist/db/repositories.d.ts +4 -0
  16. package/dist/db/repositories.d.ts.map +1 -1
  17. package/dist/db/schema.d.ts +415 -0
  18. package/dist/db/schema.d.ts.map +1 -1
  19. package/dist/db/turn-start-record-repo.d.ts.map +1 -1
  20. package/dist/domain-logic/outcome-tools.d.ts.map +1 -1
  21. package/dist/future-execution-presenter.d.ts +4 -14
  22. package/dist/future-execution-presenter.d.ts.map +1 -1
  23. package/dist/index.js +2 -2
  24. package/dist/launch-coordinator-test-harness.d.ts.map +1 -1
  25. package/dist/main.js +3 -3
  26. package/dist/process-action-presenter.d.ts +16 -0
  27. package/dist/process-action-presenter.d.ts.map +1 -0
  28. package/dist/process-engine/mapped-turns.d.ts +45 -0
  29. package/dist/process-engine/mapped-turns.d.ts.map +1 -0
  30. package/dist/process-engine/operation.d.ts +1 -1
  31. package/dist/process-engine/operation.d.ts.map +1 -1
  32. package/dist/process-engine/ops/accept-worker-turn-start.d.ts +2 -0
  33. package/dist/process-engine/ops/accept-worker-turn-start.d.ts.map +1 -1
  34. package/dist/process-engine/ops/retry-startup.d.ts.map +1 -1
  35. package/dist/process-engine/ops/turn-outcome.d.ts.map +1 -1
  36. package/dist/process-engine/recorder.d.ts.map +1 -1
  37. package/dist/process-engine/types.d.ts +5 -0
  38. package/dist/process-engine/types.d.ts.map +1 -1
  39. package/dist/process-engine/writes/build-process-abort-writes.d.ts.map +1 -1
  40. package/dist/process-engine/writes/build-recovery-start-writes.d.ts.map +1 -1
  41. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts +8 -1
  42. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts.map +1 -1
  43. package/dist/process-engine/writes/build-turn-selection-writes.d.ts.map +1 -1
  44. package/dist/process-engine/writes/commit-writes.d.ts.map +1 -1
  45. package/dist/process-engine/writes/reserve-selected-turn-start.d.ts +5 -0
  46. package/dist/process-engine/writes/reserve-selected-turn-start.d.ts.map +1 -0
  47. package/dist/process-engine/writes/writes.d.ts +18 -0
  48. package/dist/process-engine/writes/writes.d.ts.map +1 -1
  49. package/dist/process-turn-navigation.d.ts +12 -2
  50. package/dist/process-turn-navigation.d.ts.map +1 -1
  51. package/dist/process-ui-snapshot-presenter.d.ts +2 -1
  52. package/dist/process-ui-snapshot-presenter.d.ts.map +1 -1
  53. package/dist/routes/process-actions.d.ts.map +1 -1
  54. package/dist/routes/process-diagnostics-assembler.d.ts +3 -1
  55. package/dist/routes/process-diagnostics-assembler.d.ts.map +1 -1
  56. package/dist/routes/process-primary-path-assembler.d.ts +4 -12
  57. package/dist/routes/process-primary-path-assembler.d.ts.map +1 -1
  58. package/dist/routes/process-route-helpers.d.ts +7 -32
  59. package/dist/routes/process-route-helpers.d.ts.map +1 -1
  60. package/dist/supervisor/ipc-handler.d.ts.map +1 -1
  61. package/dist/supervisor/worker-start-payload-builder.d.ts +2 -0
  62. package/dist/supervisor/worker-start-payload-builder.d.ts.map +1 -1
  63. package/dist/supervisor/worker-supervisor.d.ts +2 -0
  64. package/dist/supervisor/worker-supervisor.d.ts.map +1 -1
  65. package/dist/supervisor/worker-turn-ipc-recorder.d.ts +2 -2
  66. package/dist/supervisor/worker-turn-ipc-recorder.d.ts.map +1 -1
  67. package/dist/test-helpers/accepted-turn-start.d.ts +23 -4
  68. package/dist/test-helpers/accepted-turn-start.d.ts.map +1 -1
  69. package/dist/test-helpers/owned-test-deps.d.ts +18 -0
  70. package/dist/test-helpers/owned-test-deps.d.ts.map +1 -0
  71. package/dist/test-helpers/prepared-fixture-start.d.ts +14 -0
  72. package/dist/test-helpers/prepared-fixture-start.d.ts.map +1 -0
  73. package/dist/testing.d.ts +2 -1
  74. package/dist/testing.d.ts.map +1 -1
  75. package/dist/testing.js +72 -11
  76. package/dist/testing.js.map +1 -1
  77. package/package.json +11 -11
  78. package/src/app.ts +2 -0
  79. package/src/db/database.ts +28 -0
  80. package/src/db/mapped-llm-run-repo.ts +177 -0
  81. package/src/db/process-turn-record-repo.ts +8 -1
  82. package/src/db/repo-helpers.ts +11 -1
  83. package/src/db/repositories.ts +5 -0
  84. package/src/db/schema.ts +70 -1
  85. package/src/db/turn-start-record-repo.ts +5 -1
  86. package/src/domain-logic/outcome-tools.ts +50 -6
  87. package/src/future-execution-presenter.ts +10 -17
  88. package/src/launch-coordinator-test-harness.ts +8 -4
  89. package/src/process-action-presenter.ts +133 -0
  90. package/src/process-engine/engine.ts +2 -2
  91. package/src/process-engine/mapped-turns.ts +330 -0
  92. package/src/process-engine/operation.ts +1 -1
  93. package/src/process-engine/ops/accept-worker-turn-start.ts +6 -0
  94. package/src/process-engine/ops/retry-startup.ts +1 -0
  95. package/src/process-engine/ops/turn-outcome.ts +7 -5
  96. package/src/process-engine/recorder.ts +12 -0
  97. package/src/process-engine/runner.ts +8 -8
  98. package/src/process-engine/types.ts +6 -0
  99. package/src/process-engine/writes/build-process-abort-writes.ts +1 -0
  100. package/src/process-engine/writes/build-recovery-start-writes.ts +1 -0
  101. package/src/process-engine/writes/build-turn-outcome-writes.ts +80 -20
  102. package/src/process-engine/writes/build-turn-selection-writes.ts +2 -31
  103. package/src/process-engine/writes/commit-writes.ts +5 -0
  104. package/src/process-engine/writes/reserve-selected-turn-start.ts +44 -0
  105. package/src/process-engine/writes/writes.ts +27 -0
  106. package/src/process-turn-navigation.ts +86 -8
  107. package/src/process-ui-snapshot-presenter.ts +40 -4
  108. package/src/routes/process-actions.ts +1 -1
  109. package/src/routes/process-diagnostics-assembler.ts +32 -6
  110. package/src/routes/process-primary-path-assembler.ts +17 -33
  111. package/src/routes/process-route-helpers.ts +8 -165
  112. package/src/supervisor/ipc-handler.ts +27 -18
  113. package/src/supervisor/worker-start-payload-builder.ts +25 -0
  114. package/src/supervisor/worker-supervisor.ts +2 -0
  115. package/src/supervisor/worker-turn-ipc-recorder.ts +13 -1
  116. package/src/test-helpers/accepted-turn-start.ts +54 -27
  117. package/src/test-helpers/owned-test-deps.ts +45 -0
  118. package/src/test-helpers/prepared-fixture-start.ts +74 -0
  119. package/src/testing.ts +5 -1
  120. package/dist/app-7PKX73TU.js +0 -8
  121. package/dist/chunk-CNITOV76.js.map +0 -1
  122. package/dist/chunk-ZSKM25SD.js.map +0 -1
  123. /package/dist/{app-7PKX73TU.js.map → app-MSJXFK33.js.map} +0 -0
@@ -0,0 +1,133 @@
1
+ import type { ProcessInstance } from "@leitwerk-dev/domain";
2
+ import { type FormDefinition, isLlmTurnDefinition } from "@leitwerk-dev/process-sdk";
3
+ import type {
4
+ ProcessActionPreviewSummary,
5
+ ProcessActionSummary,
6
+ } from "@leitwerk-dev/protocol/http-contracts";
7
+ import type { VisibleProcessActionSummary } from "./process-action-registry.js";
8
+ import {
9
+ listVisibleActionsForProcess as listVisibleAttentionActionsForProcess,
10
+ type ProcessOperatorAttentionDeps,
11
+ } from "./process-operator-attention.js";
12
+
13
+ function actionHasPurePlan(
14
+ deps: Pick<ProcessOperatorAttentionDeps, "processActionRegistry">,
15
+ process: ProcessInstance,
16
+ actionId: string,
17
+ ): boolean {
18
+ const action = deps.processActionRegistry?.getAction(process.processId, actionId);
19
+ return typeof action?.plan === "function";
20
+ }
21
+
22
+ /** @internal */
23
+ export function buildActionSummaryForProcess(
24
+ deps: Pick<ProcessOperatorAttentionDeps, "processActionRegistry">,
25
+ process: ProcessInstance,
26
+ action: {
27
+ id: string;
28
+ label: string;
29
+ form?: FormDefinition;
30
+ },
31
+ visibleAction?: VisibleProcessActionSummary,
32
+ labelOverride?: string | null,
33
+ overrides: { supportsScheduling?: boolean } = {},
34
+ ): ProcessActionSummary {
35
+ const actionId = action.id;
36
+ const preview =
37
+ visibleAction?.preview ??
38
+ deps.processActionRegistry?.resolveActionPreview(process.processId, process, actionId) ??
39
+ null;
40
+ const supportsScheduling =
41
+ overrides.supportsScheduling ??
42
+ Boolean(
43
+ actionHasPurePlan(deps, process, actionId) &&
44
+ deps.processActionRegistry?.resolveActionScheduling(process.processId, process, actionId),
45
+ );
46
+ const label = labelOverride ?? visibleAction?.label ?? action.label;
47
+ return {
48
+ id: action.id,
49
+ label: label.trim() ? label : action.label,
50
+ description: visibleAction?.description ?? null,
51
+ preview: buildProcessActionPreviewSummary(deps, preview, process),
52
+ supportsScheduling,
53
+ supportsNextTurnModelOverride: previewSupportsNextTurnModelOverride(
54
+ deps,
55
+ process,
56
+ actionId,
57
+ preview,
58
+ ),
59
+ ...(action.form
60
+ ? {
61
+ form: {
62
+ id: action.form.id,
63
+ title: action.form.title,
64
+ submitLabel: action.form.submitLabel,
65
+ fields: action.form.fields.map((field) => ({ ...field })),
66
+ },
67
+ }
68
+ : {}),
69
+ };
70
+ }
71
+
72
+ /** @internal */
73
+ export function listVisibleActionsForProcess(
74
+ deps: ProcessOperatorAttentionDeps,
75
+ process: ProcessInstance,
76
+ ) {
77
+ return listVisibleAttentionActionsForProcess(deps, process).map((action) =>
78
+ buildActionSummaryForProcess(deps, process, action, action, action.label),
79
+ );
80
+ }
81
+
82
+ function buildProcessActionPreviewSummary(
83
+ deps: Pick<ProcessOperatorAttentionDeps, "processActionRegistry">,
84
+ preview: {
85
+ candidateSelectedTurnId: string | null;
86
+ lifecycleStatus?: string | null;
87
+ } | null,
88
+ process: ProcessInstance,
89
+ ): ProcessActionPreviewSummary | null {
90
+ if (!preview) {
91
+ return null;
92
+ }
93
+ if (!preview.candidateSelectedTurnId) {
94
+ return {
95
+ kind: "terminal",
96
+ turnId: null,
97
+ turnKind: null,
98
+ description: preview.lifecycleStatus === "aborted" ? "Abort process" : "Complete process",
99
+ };
100
+ }
101
+ const turnDef = deps.processActionRegistry?.getTurnDefinition(
102
+ process.processId,
103
+ preview.candidateSelectedTurnId,
104
+ );
105
+ if (!turnDef) {
106
+ return null;
107
+ }
108
+ return {
109
+ kind: "turn",
110
+ turnId: preview.candidateSelectedTurnId,
111
+ turnKind: turnDef.kind,
112
+ description: turnDef.description,
113
+ };
114
+ }
115
+
116
+ function previewSupportsNextTurnModelOverride(
117
+ deps: Pick<ProcessOperatorAttentionDeps, "processActionRegistry">,
118
+ process: ProcessInstance,
119
+ actionId: string,
120
+ preview: { candidateSelectedTurnId: string | null } | null,
121
+ ): boolean {
122
+ if (!preview?.candidateSelectedTurnId) {
123
+ return false;
124
+ }
125
+ if (!actionHasPurePlan(deps, process, actionId)) {
126
+ return false;
127
+ }
128
+ const turnDef = deps.processActionRegistry?.getTurnDefinition(
129
+ process.processId,
130
+ preview.candidateSelectedTurnId,
131
+ );
132
+ return Boolean(turnDef && isLlmTurnDefinition(turnDef));
133
+ }
@@ -183,8 +183,8 @@ export function createProcessEngine(deps: ProcessEngineDeps): ProcessEngine {
183
183
  return maybeBroadcastErrorAttentionToast(result, { errorCode: payload.errorCode });
184
184
  },
185
185
 
186
- acceptWorkerTurnStart(instanceId, input) {
187
- return run(AcceptWorkerTurnStart, { instanceId, ...input });
186
+ acceptWorkerTurnStart(instanceId, input, options) {
187
+ return run(AcceptWorkerTurnStart, { instanceId, ...input, onRecorded: options?.onRecorded });
188
188
  },
189
189
 
190
190
  async recordTurnOutcome(instanceId, payload, options) {
@@ -0,0 +1,330 @@
1
+ import type {
2
+ MappedTurnItemRef,
3
+ ProcessInstance,
4
+ ProcessProject,
5
+ TurnOutcomePayload,
6
+ } from "@leitwerk-dev/domain";
7
+ import {
8
+ collectMappedResults,
9
+ freezeMappedItems,
10
+ type MappedLlmTurnSpec,
11
+ type MappedTurnServerContext,
12
+ SafeOutcomePlanningError,
13
+ yieldMappedItemResult,
14
+ } from "@leitwerk-dev/process-sdk";
15
+ import { generateId } from "../db/repo-helpers.js";
16
+ import type { RepositoryBundle } from "../db/repositories.js";
17
+ import type { ProcessActionRegistry } from "../process-action-registry.js";
18
+ import type { ProcessGraphRegistry } from "../process-graph.js";
19
+ import { buildServerTransitionWrites } from "./writes/build-server-transition-writes.js";
20
+ import { reserveSelectedTurnStart } from "./writes/reserve-selected-turn-start.js";
21
+ import {
22
+ appendProcessEvent,
23
+ applyProcessPatchField,
24
+ createWrites,
25
+ isWriteBuildFailure,
26
+ mergeWrites,
27
+ type WriteBuildFailure,
28
+ type WriteBuildResult,
29
+ type Writes,
30
+ } from "./writes/writes.js";
31
+
32
+ type MappedRunRepo = RepositoryBundle["mappedRuns"];
33
+ type Registry = Pick<ProcessActionRegistry, "getTurnDefinition" | "resolveContextData">;
34
+
35
+ /** Bounds consecutive empty mapped turns routed within one decision. */
36
+ const MAX_EMPTY_MAPPED_ENTRIES = 16;
37
+
38
+ /** @internal */
39
+ export function getMappedTurnSpec(
40
+ registry: Pick<ProcessActionRegistry, "getTurnDefinition"> | undefined,
41
+ processId: string,
42
+ turnId: string | null,
43
+ ): MappedLlmTurnSpec | undefined {
44
+ if (!registry || !turnId) return undefined;
45
+ const turn = registry.getTurnDefinition(processId, turnId);
46
+ return turn?.kind === "llm" ? turn.forEach : undefined;
47
+ }
48
+
49
+ function failure(code: string, message: string): WriteBuildFailure {
50
+ return { ok: false, code, message };
51
+ }
52
+
53
+ function planningFailure(error: unknown, code: string): WriteBuildFailure {
54
+ if (error instanceof SafeOutcomePlanningError) return failure(error.code, error.message);
55
+ throw error instanceof Error ? error : new Error(`${code}: ${String(error)}`);
56
+ }
57
+
58
+ function serverContext(
59
+ registry: Registry,
60
+ process: ProcessInstance,
61
+ projects: readonly ProcessProject[],
62
+ ): MappedTurnServerContext {
63
+ const { params, state } = registry.resolveContextData(process.processId, process);
64
+ return { process, projects, params, state };
65
+ }
66
+
67
+ function appendInto(target: Writes, source: Writes): void {
68
+ Object.assign(target, mergeWrites(target, source));
69
+ }
70
+
71
+ async function collectAndRoute(input: {
72
+ processGraphs: ProcessGraphRegistry;
73
+ process: ProcessInstance;
74
+ ctx: MappedTurnServerContext;
75
+ spec: MappedLlmTurnSpec;
76
+ turnId: string;
77
+ runId: string;
78
+ resultJsons: readonly string[];
79
+ }): Promise<WriteBuildResult> {
80
+ let collected: Awaited<ReturnType<typeof collectMappedResults>>;
81
+ try {
82
+ collected = await collectMappedResults({
83
+ turnId: input.turnId,
84
+ spec: input.spec,
85
+ ctx: input.ctx,
86
+ resultJsons: input.resultJsons,
87
+ });
88
+ } catch (error) {
89
+ return planningFailure(error, "mapped_collect_failed");
90
+ }
91
+ const writes = buildServerTransitionWrites(input.processGraphs, input.process, {
92
+ turnId: collected.route.nextTurnId ?? null,
93
+ ...(collected.route.lifecycleStatus
94
+ ? { lifecycleStatus: collected.route.lifecycleStatus }
95
+ : {}),
96
+ trigger: collected.route.trigger,
97
+ state: collected.state,
98
+ });
99
+ if (isWriteBuildFailure(writes)) return writes;
100
+ appendProcessEvent(writes, input.process, {
101
+ eventType: "mapped_run_collected",
102
+ level: "info",
103
+ message: `Collected ${input.resultJsons.length} result(s) for ${input.turnId}`,
104
+ data: {
105
+ runId: input.runId,
106
+ turnId: input.turnId,
107
+ itemCount: input.resultJsons.length,
108
+ trigger: collected.route.trigger,
109
+ },
110
+ });
111
+ return writes;
112
+ }
113
+
114
+ /**
115
+ * Freezes items for every newly selected mapped turn in `writes`, before model
116
+ * preflight. A non-empty run reserves only its first item; an empty run collects
117
+ * and routes immediately. Leaving a mapped turn by any other route aborts its run.
118
+ * @internal
119
+ */
120
+ export async function planMappedTurnEntries(input: {
121
+ processGraphs: ProcessGraphRegistry;
122
+ registry: Registry | undefined;
123
+ mappedRuns: MappedRunRepo | undefined;
124
+ projects: Pick<RepositoryBundle["projects"], "listByInstance">;
125
+ process: ProcessInstance;
126
+ writes: Writes;
127
+ }): Promise<{ ok: true } | WriteBuildFailure> {
128
+ const { writes } = input;
129
+ const active = input.mappedRuns?.getActiveByInstance(input.process.id) ?? null;
130
+ let activeAborted = false;
131
+ for (let entry = 0; entry <= MAX_EMPTY_MAPPED_ENTRIES; entry += 1) {
132
+ const candidate: ProcessInstance = { ...input.process, ...writes.processPatch };
133
+ const startIndex = writes.turnStartWrites.findIndex(
134
+ (write) =>
135
+ write.kind === "create" &&
136
+ write.input.turnType === "llm" &&
137
+ write.input.startKind === "selected_turn" &&
138
+ !write.input.iteration &&
139
+ write.input.turnId === candidate.selectedTurnId,
140
+ );
141
+ const start = startIndex >= 0 ? writes.turnStartWrites[startIndex] : undefined;
142
+ const spec =
143
+ start?.kind === "create"
144
+ ? getMappedTurnSpec(input.registry, candidate.processId, start.input.turnId)
145
+ : undefined;
146
+ if (!start || start.kind !== "create" || !spec || !input.registry) {
147
+ const leavesActiveRun =
148
+ active !== null &&
149
+ !activeAborted &&
150
+ !writes.mappedRunWrites.some((write) => write.kind === "complete_item") &&
151
+ (candidate.selectedTurnId !== active.turnId ||
152
+ candidate.lifecycleStatus === "completed" ||
153
+ candidate.lifecycleStatus === "aborted");
154
+ if (leavesActiveRun) writes.mappedRunWrites.push({ kind: "abort_active" });
155
+ return { ok: true };
156
+ }
157
+ if (entry === MAX_EMPTY_MAPPED_ENTRIES) {
158
+ return failure("mapped_turn_loop", "Too many consecutive empty mapped turns");
159
+ }
160
+ if (!input.mappedRuns) {
161
+ return failure("mapped_runs_unavailable", "Mapped turn storage is not available");
162
+ }
163
+ if (active && !activeAborted) {
164
+ writes.mappedRunWrites.push({ kind: "abort_active" });
165
+ activeAborted = true;
166
+ }
167
+ const turnId = start.input.turnId;
168
+ const projects = input.projects.listByInstance(input.process.id);
169
+ let ctx = serverContext(input.registry, candidate, projects);
170
+ let frozen: ReturnType<typeof freezeMappedItems>;
171
+ try {
172
+ frozen = freezeMappedItems(turnId, spec, ctx);
173
+ } catch (error) {
174
+ return planningFailure(error, "invalid_mapped_items");
175
+ }
176
+ const runId = generateId("mlr");
177
+ writes.mappedRunWrites.push({
178
+ kind: "create",
179
+ input: {
180
+ id: runId,
181
+ instanceId: input.process.id,
182
+ turnId,
183
+ status: frozen.items.length > 0 ? "active" : "completed",
184
+ items: frozen.items.map((item) => ({
185
+ itemIndex: item.index,
186
+ itemKey: item.key,
187
+ label: item.label,
188
+ itemJson: item.itemJson,
189
+ })),
190
+ },
191
+ });
192
+ appendProcessEvent(writes, candidate, {
193
+ eventType: "mapped_run_started",
194
+ level: "info",
195
+ message: `Froze ${frozen.items.length} item(s) for ${turnId}`,
196
+ data: { runId, turnId, itemCount: frozen.items.length },
197
+ });
198
+ if (frozen.state !== undefined) {
199
+ applyProcessPatchField(writes, candidate, "stateJson", JSON.stringify(frozen.state));
200
+ ctx = { ...ctx, state: frozen.state };
201
+ }
202
+ const first = frozen.items[0];
203
+ if (first) {
204
+ start.input.iteration = { runId, itemKey: first.key, itemIndex: 0 };
205
+ return { ok: true };
206
+ }
207
+ writes.turnStartWrites.splice(startIndex, 1);
208
+ const routed = await collectAndRoute({
209
+ processGraphs: input.processGraphs,
210
+ process: { ...input.process, ...writes.processPatch },
211
+ ctx,
212
+ spec,
213
+ turnId,
214
+ runId,
215
+ resultJsons: [],
216
+ });
217
+ if (isWriteBuildFailure(routed)) return routed;
218
+ appendInto(writes, routed);
219
+ }
220
+ return failure("mapped_turn_loop", "Too many consecutive empty mapped turns");
221
+ }
222
+
223
+ /**
224
+ * Records one item's validated result. Reserves the next item's start, or,
225
+ * after the last item, collects all results in order and applies the single
226
+ * collection route.
227
+ * @internal
228
+ */
229
+ export async function buildMappedItemOutcomeWrites(input: {
230
+ processGraphs: ProcessGraphRegistry;
231
+ registry: Registry;
232
+ mappedRuns: MappedRunRepo | undefined;
233
+ process: ProcessInstance;
234
+ projects: readonly ProcessProject[];
235
+ payload: TurnOutcomePayload;
236
+ spec: MappedLlmTurnSpec;
237
+ iteration: MappedTurnItemRef | null | undefined;
238
+ prepared?: unknown;
239
+ }): Promise<WriteBuildResult> {
240
+ const { payload, iteration } = input;
241
+ if (!input.mappedRuns) {
242
+ return failure("mapped_runs_unavailable", "Mapped turn storage is not available");
243
+ }
244
+ if (!iteration) {
245
+ return failure("mapped_item_missing", `Turn '${payload.turnId}' has no active mapped item`);
246
+ }
247
+ const run = input.mappedRuns.getById(iteration.runId);
248
+ const item = input.mappedRuns.getItem(iteration.runId, iteration.itemIndex);
249
+ if (
250
+ !run ||
251
+ !item ||
252
+ run.status !== "active" ||
253
+ run.turnId !== payload.turnId ||
254
+ run.nextIndex !== iteration.itemIndex ||
255
+ item.itemKey !== iteration.itemKey ||
256
+ item.status !== "pending"
257
+ ) {
258
+ return failure(
259
+ "stale_mapped_item",
260
+ `Mapped item '${iteration.itemKey}' is no longer the current item of '${payload.turnId}'`,
261
+ );
262
+ }
263
+ const ctx = serverContext(input.registry, input.process, input.projects);
264
+ let resultJson: string;
265
+ try {
266
+ resultJson = await yieldMappedItemResult({
267
+ turnId: payload.turnId,
268
+ spec: input.spec,
269
+ ctx,
270
+ iteration: {
271
+ runId: run.id,
272
+ itemKey: item.itemKey,
273
+ itemLabel: item.label,
274
+ itemIndex: item.itemIndex,
275
+ itemCount: run.itemCount,
276
+ item: JSON.parse(item.itemJson) as unknown,
277
+ },
278
+ event: {
279
+ turnRecordId: payload.turnRecordId,
280
+ turnId: payload.turnId,
281
+ outcome: payload.outcome,
282
+ params: payload.params ?? {},
283
+ turnResultMarkdown: payload.turnResultMarkdown ?? null,
284
+ ...(input.prepared !== undefined ? { prepared: input.prepared } : {}),
285
+ },
286
+ });
287
+ } catch (error) {
288
+ return planningFailure(error, "invalid_mapped_result");
289
+ }
290
+ const writes = createWrites();
291
+ writes.mappedRunWrites.push({
292
+ kind: "complete_item",
293
+ input: {
294
+ runId: run.id,
295
+ itemIndex: item.itemIndex,
296
+ outcome: payload.outcome,
297
+ resultJson,
298
+ turnRecordId: payload.turnRecordId,
299
+ },
300
+ });
301
+ const nextIndex = item.itemIndex + 1;
302
+ if (nextIndex < run.itemCount) {
303
+ const next = input.mappedRuns.getItem(run.id, nextIndex);
304
+ if (!next) return failure("stale_mapped_item", `Mapped run '${run.id}' lost item ${nextIndex}`);
305
+ reserveSelectedTurnStart(writes, input.process, payload.turnId, "llm", {
306
+ runId: run.id,
307
+ itemKey: next.itemKey,
308
+ itemIndex: nextIndex,
309
+ });
310
+ writes.workerIntent = { kind: "reconcile" };
311
+ return writes;
312
+ }
313
+ const resultJsons = input.mappedRuns
314
+ .listItems(run.id)
315
+ .map((stored) => (stored.itemIndex === item.itemIndex ? resultJson : stored.resultJson));
316
+ if (resultJsons.some((json) => json === null)) {
317
+ return failure("stale_mapped_item", `Mapped run '${run.id}' is missing item results`);
318
+ }
319
+ const routed = await collectAndRoute({
320
+ processGraphs: input.processGraphs,
321
+ process: input.process,
322
+ ctx,
323
+ spec: input.spec,
324
+ turnId: payload.turnId,
325
+ runId: run.id,
326
+ resultJsons: resultJsons as string[],
327
+ });
328
+ if (isWriteBuildFailure(routed)) return routed;
329
+ return mergeWrites(writes, routed);
330
+ }
@@ -59,7 +59,7 @@ export interface OperationSpec<TKind extends string, TInput extends OperationInp
59
59
  /** @internal */
60
60
  decide: DecideFunction<TInput, TData>;
61
61
 
62
- /** Runs after the transaction and process lock complete, before reactions are dispatched. @internal */
62
+ /** Runs after durable recording and lock release, even if reaction derivation fails. @internal */
63
63
  afterRecord?: AfterRecordFunction<TInput, TData>;
64
64
  /** @internal */
65
65
  messages?: OperationMessages | MessageResolver<TInput>;
@@ -9,6 +9,8 @@ export interface AcceptWorkerTurnStartInput {
9
9
  workerLeaseId: string;
10
10
  startRecordId: string;
11
11
  proposedTurnRecordId: string;
12
+ /** @internal */
13
+ onRecorded?: (turnRecordId: string) => void;
12
14
  }
13
15
 
14
16
  function receiptMatchesStart(
@@ -62,6 +64,9 @@ export const AcceptWorkerTurnStart = defineOperation<
62
64
  >({
63
65
  kind: "accept_worker_turn_start",
64
66
  label: "Accept worker turn start",
67
+ afterRecord(input, data) {
68
+ input.onRecorded?.(data.turnRecordId);
69
+ },
65
70
  decide(ctx, input) {
66
71
  if (
67
72
  ctx.process.lifecycleStatus !== "active" ||
@@ -161,6 +166,7 @@ export const AcceptWorkerTurnStart = defineOperation<
161
166
  acceptedWorkerLeaseId: lease.id,
162
167
  modelProfileId: acceptedLlmStart?.model.profileId ?? null,
163
168
  modelSelectionProvenance: acceptedLlmStart?.modelSelectionProvenance ?? null,
169
+ iteration: start.iteration ?? null,
164
170
  },
165
171
  },
166
172
  ],
@@ -72,6 +72,7 @@ export const RetryStartup = defineOperation<
72
72
  recoveryTurnRecordId: failed.recoveryTurnRecordId,
73
73
  continuation: failed.continuation,
74
74
  state,
75
+ iteration: failed.iteration ?? null,
75
76
  },
76
77
  });
77
78
  applyProcessPatchField(writes, ctx.process, "currentExecution", { kind: "worker_start", id });
@@ -174,13 +174,12 @@ export const TurnOutcome = defineOperation<"turn_outcome", TurnOutcomeInput, voi
174
174
  });
175
175
  const payload = resolveEffectiveOutcomePayload({ payload: initialPayload, publication });
176
176
  const publishedProduct = publication.productName;
177
- const expected =
177
+ const currentStart =
178
178
  ctx.process.currentExecution?.kind === "worker_start"
179
- ? (() => {
180
- const state = ctx.deps.turnStarts.getById(ctx.process.currentExecution.id)?.state;
181
- return state?.kind === "accepted" ? state.turnRecordId : null;
182
- })()
179
+ ? ctx.deps.turnStarts.getById(ctx.process.currentExecution.id)
183
180
  : null;
181
+ const expected =
182
+ currentStart?.state.kind === "accepted" ? currentStart.state.turnRecordId : null;
184
183
  const correlationError = validateTurnOutcomeCorrelation(ctx.process, payload, expected);
185
184
  if (correlationError) {
186
185
  return reject(correlationError.code, correlationError.message);
@@ -353,8 +352,11 @@ export const TurnOutcome = defineOperation<"turn_outcome", TurnOutcomeInput, voi
353
352
  projects,
354
353
  payload,
355
354
  turnRecords: ctx.deps.turnRecords,
355
+ events: ctx.deps.events,
356
356
  processGraphs: ctx.deps.processGraphs,
357
357
  processActionRegistry,
358
+ mappedRuns: ctx.deps.mappedRuns,
359
+ iteration: currentStart?.iteration ?? null,
358
360
  });
359
361
  if (isWriteBuildFailure(outcomeWrites)) {
360
362
  return reject(outcomeWrites.code, outcomeWrites.message);
@@ -13,6 +13,7 @@ import { evaluateAtStableAvailabilityRevision } from "../process-model-policy/in
13
13
  import { presentProcessModelPolicyFailure } from "../process-model-policy-presenter.js";
14
14
  import type { Decision, Reaction } from "./decision.js";
15
15
  import { logProcessEngineError, publicInternalEngineFailureMessage } from "./internal-failures.js";
16
+ import { planMappedTurnEntries } from "./mapped-turns.js";
16
17
  import type {
17
18
  OperationData,
18
19
  OperationInput,
@@ -161,6 +162,17 @@ export async function record<TOp extends OperationSpec<string, OperationInputBas
161
162
  * commits all writes in one SQLite transaction, then derives a complete
162
163
  * reaction list for the post-commit stage.
163
164
  */
165
+ const mappedPlan = await planMappedTurnEntries({
166
+ processGraphs: deps.processGraphs,
167
+ registry: deps.getProcessActionRegistry?.(),
168
+ mappedRuns: deps.mappedRuns,
169
+ projects: deps.projects,
170
+ process: initialProcess,
171
+ writes: decision.writes,
172
+ });
173
+ if (!mappedPlan.ok) {
174
+ return { ok: false, stage: "pre_commit", code: mappedPlan.code, message: mappedPlan.message };
175
+ }
164
176
  const baselineWrites = structuredClone(decision.writes);
165
177
  const runModelPreparation = async (availability: ModelStatusCacheSnapshot) => {
166
178
  const candidateProcess: ProcessInstance = {
@@ -216,14 +216,6 @@ export function createEngineRunner(
216
216
  if (lockedOutcome.kind === "pre_commit_failed") {
217
217
  return mapPreCommitFailure(lockedOutcome.failure, lockedOutcome.initialProcess);
218
218
  }
219
- if (lockedOutcome.kind === "post_commit_failed") {
220
- return mapPostCommitFailure(
221
- lockedOutcome.recorded as RecordedDecision<
222
- OperationSpec<string, OperationInputBase, OperationData<TOp>>
223
- >,
224
- lockedOutcome.failure,
225
- );
226
- }
227
219
 
228
220
  const { recorded } = lockedOutcome;
229
221
  try {
@@ -237,6 +229,14 @@ export function createEngineRunner(
237
229
  code: "after_record_callback_failed",
238
230
  });
239
231
  }
232
+ if (lockedOutcome.kind === "post_commit_failed") {
233
+ return mapPostCommitFailure(
234
+ lockedOutcome.recorded as RecordedDecision<
235
+ OperationSpec<string, OperationInputBase, OperationData<TOp>>
236
+ >,
237
+ lockedOutcome.failure,
238
+ );
239
+ }
240
240
  try {
241
241
  await deps.afterRecord?.(recorded.process);
242
242
  const dispatchResult = await dispatchReactions(
@@ -76,6 +76,8 @@ export interface ProcessEngineDeps
76
76
  | "turnAnnotations"
77
77
  | "transaction"
78
78
  > {
79
+ /** Required for processes that declare mapped LLM turns. @internal */
80
+ mappedRuns?: RepositoryBundle["mappedRuns"];
79
81
  /** @internal */
80
82
  processOperations: ProcessOperationCoordinator;
81
83
  /** @internal */
@@ -375,6 +377,10 @@ export interface ProcessEngine {
375
377
  /** @internal */
376
378
  workerLeaseId: string;
377
379
  },
380
+ options?: {
381
+ /** Runs after durable acceptance and lock release, before reactions. @internal */
382
+ onRecorded?: (turnRecordId: string) => void;
383
+ },
378
384
  ): Promise<
379
385
  EngineResult<{
380
386
  /** @internal */
@@ -20,6 +20,7 @@ export function buildAbortProcessWrites(input: {
20
20
  return writes;
21
21
  }
22
22
 
23
+ writes.mappedRunWrites.push({ kind: "abort_active" });
23
24
  if (input.currentWorkerStart?.state.kind === "starting") {
24
25
  writes.turnStartWrites.push({
25
26
  kind: "cas_state",
@@ -47,6 +47,7 @@ export function buildRecoveryStartWrites(
47
47
  turnId: failedRun.turnId,
48
48
  proposedTurnRecordId: generateId("trn"),
49
49
  recoveryTurnRecordId: failedRun.id,
50
+ iteration: failedRun.iteration ?? null,
50
51
  state:
51
52
  recovery.turnType === "automatic"
52
53
  ? { kind: "starting", start: { kind: "automatic" } }