@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
@@ -1,40 +1,35 @@
1
- import type {
2
- ProcessInstance,
3
- ProcessTurnAnnotation,
4
- ProcessTurnRecord,
5
- } from "@leitwerk-dev/domain";
6
1
  import { PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPES } from "@leitwerk-dev/protocol";
7
2
  import {
8
3
  buildPrimaryPathSnapshotFromTree,
9
4
  type PrimaryPathSnapshotProjectionInput,
10
5
  } from "../primary-path-snapshot.js";
11
6
  import { resolveCurrentExecutionTurnRecordId } from "../process-execution.js";
12
- import type { ProcessSessionTreeReadResult } from "../process-session-store.js";
13
7
  import {
14
8
  mergeProcessEventWindowsAscending,
15
9
  PRIMARY_PATH_ACTIVE_TURN_EVENT_LIMIT,
16
10
  type RouteDeps,
17
11
  } from "./process-route-helpers.js";
18
12
 
19
- export type CapturedPrimaryPathState = PrimaryPathSnapshotProjectionInput;
13
+ type ProcessPrimaryPathDeps = Pick<
14
+ RouteDeps,
15
+ | "processes"
16
+ | "turnRecords"
17
+ | "turnStarts"
18
+ | "events"
19
+ | "leases"
20
+ | "turnAnnotations"
21
+ | "sessionReader"
22
+ >;
20
23
 
21
24
  export class ProcessPrimaryPathAssembler {
22
- constructor(private readonly deps: RouteDeps) {}
25
+ constructor(private readonly deps: ProcessPrimaryPathDeps) {}
23
26
 
24
- capture(
25
- instanceId: string,
26
- overrides: {
27
- process?: ProcessInstance;
28
- turnRecords?: readonly ProcessTurnRecord[];
29
- turnAnnotations?: readonly ProcessTurnAnnotation[];
30
- workerLease?: PrimaryPathSnapshotProjectionInput["workerLease"];
31
- } = {},
32
- ): CapturedPrimaryPathState | null {
33
- const process = overrides.process ?? this.deps.processes.getById(instanceId);
27
+ private capture(instanceId: string): PrimaryPathSnapshotProjectionInput | null {
28
+ const process = this.deps.processes.getById(instanceId);
34
29
  if (!process) {
35
30
  return null;
36
31
  }
37
- const turnRecords = overrides.turnRecords ?? this.deps.turnRecords.listByInstance(process.id);
32
+ const turnRecords = this.deps.turnRecords.listByInstance(process.id);
38
33
  const currentTurnRecordId = resolveCurrentExecutionTurnRecordId(process, this.deps.turnStarts);
39
34
  const activeTurnRecord = currentTurnRecordId
40
35
  ? turnRecords.find(
@@ -63,31 +58,20 @@ export class ProcessPrimaryPathAssembler {
63
58
  return {
64
59
  process,
65
60
  currentExecutionTurnRecordId: currentTurnRecordId,
66
- workerLease:
67
- overrides.workerLease !== undefined
68
- ? overrides.workerLease
69
- : this.deps.leases.getByInstance(process.id),
61
+ workerLease: this.deps.leases.getByInstance(process.id),
70
62
  turnRecords,
71
- turnAnnotations:
72
- overrides.turnAnnotations ?? this.deps.turnAnnotations.listByInstance(process.id),
63
+ turnAnnotations: this.deps.turnAnnotations.listByInstance(process.id),
73
64
  events,
74
65
  eventWindowTruncated,
75
66
  };
76
67
  }
77
68
 
78
- project(captured: CapturedPrimaryPathState, session: ProcessSessionTreeReadResult) {
79
- return buildPrimaryPathSnapshotFromTree({
80
- ...captured,
81
- tree: session.parsedTree,
82
- });
83
- }
84
-
85
69
  async assemble(instanceId: string) {
86
70
  const captured = this.capture(instanceId);
87
71
  if (!captured) {
88
72
  return null;
89
73
  }
90
74
  const session = await this.deps.sessionReader.readSessionTree(instanceId);
91
- return this.project(captured, session);
75
+ return buildPrimaryPathSnapshotFromTree({ ...captured, tree: session.parsedTree });
92
76
  }
93
77
  }
@@ -8,7 +8,6 @@ import {
8
8
  } from "@leitwerk-dev/domain";
9
9
  import type { ProcessModelSelectionServiceLike } from "@leitwerk-dev/process-sdk";
10
10
  import {
11
- type FormDefinition,
12
11
  findUiLauncherById,
13
12
  isLlmTurnDefinition,
14
13
  type OutcomeToolParameterSpec,
@@ -29,12 +28,9 @@ import {
29
28
  import type {
30
29
  LauncherModelConfigSchema,
31
30
  LauncherMutationResponseBody,
32
- ProcessActionPreviewSummary,
33
- ProcessActionSummary,
34
31
  ProcessLaunchConfigurationView,
35
32
  ProcessRunDetailsView,
36
33
  ProcessRunTurnView,
37
- ScheduledActionDetail,
38
34
  ScheduledActionMutationResponseBody,
39
35
  } from "@leitwerk-dev/protocol/http-contracts";
40
36
  import type { ToolCallRendererDefinition } from "@leitwerk-dev/protocol/tool-renderer-contract";
@@ -53,7 +49,7 @@ import type {
53
49
  } from "../future-execution/index.js";
54
50
  import {
55
51
  buildFutureExecutionListView,
56
- getScheduledActionDetailForProcess as getPresentedScheduledActionDetailForProcess,
52
+ getScheduledActionDetailForProcess,
57
53
  } from "../future-execution-presenter.js";
58
54
  import type { LaunchCoordinator } from "../launch-coordinator.js";
59
55
  import { normalizeSubmittedProcessTitle } from "../launch-title.js";
@@ -74,11 +70,7 @@ import { getProcessGraph, type ProcessGraphRegistry } from "../process-graph.js"
74
70
  import type { ServerProcessModelPolicy } from "../process-model-policy/index.js";
75
71
  import { presentLauncherModelConfigSchema } from "../process-model-policy-presenter.js";
76
72
  import type { ProcessOperationCoordinator } from "../process-operation-coordinator.js";
77
- import {
78
- getSelectedTurnSummaryForProcess,
79
- listCurrentVisibleActions,
80
- listVisibleActionsForProcess as listVisibleAttentionActionsForProcess,
81
- } from "../process-operator-attention.js";
73
+ import { getSelectedTurnSummaryForProcess } from "../process-operator-attention.js";
82
74
  import type { ProcessQuestionService } from "../process-question-service.js";
83
75
  import type { ProcessSessionReader } from "../process-session-store.js";
84
76
  import type { ProcessTitleGenerator } from "../process-title-generator.js";
@@ -117,6 +109,8 @@ export interface RouteDeps
117
109
  | "transaction"
118
110
  > {
119
111
  /** @internal */
112
+ mappedRuns?: RepositoryBundle["mappedRuns"];
113
+ /** @internal */
120
114
  startupObservations?: RepositoryBundle["startupObservations"];
121
115
  /** @public */
122
116
  externalSourceService?: Pick<
@@ -179,7 +173,7 @@ export interface RouteDeps
179
173
  sessionTransferService?: SessionTransferService;
180
174
  }
181
175
 
182
- export function routeConfig(deps: RouteDeps): LeitwerkConfig {
176
+ export function routeConfig(deps: Pick<RouteDeps, "config">): LeitwerkConfig {
183
177
  return deps.config ?? getDefaultConfig();
184
178
  }
185
179
 
@@ -256,7 +250,7 @@ export function buildProcessLaunchConfigurationView(
256
250
  }
257
251
 
258
252
  export function buildProcessRunDetailsView(
259
- deps: RouteDeps,
253
+ deps: Pick<RouteDeps, "config" | "processActionRegistry" | "processGraphs">,
260
254
  process: ProcessInstance,
261
255
  projects: readonly ProcessProject[],
262
256
  ): ProcessRunDetailsView {
@@ -340,60 +334,10 @@ export function buildProcessRunDetailsView(
340
334
  };
341
335
  }
342
336
 
343
- export function actionHasPurePlan(
344
- deps: RouteDeps,
337
+ export function processDefinesLeafOutcome(
338
+ deps: Pick<RouteDeps, "processUiRegistry">,
345
339
  process: ProcessInstance,
346
- actionId: string,
347
340
  ): boolean {
348
- const action = deps.processActionRegistry?.getAction(process.processId, actionId);
349
- return typeof action?.plan === "function";
350
- }
351
-
352
- export function buildActionSummaryForProcess(
353
- deps: RouteDeps,
354
- process: ProcessInstance,
355
- actionId: string,
356
- action: {
357
- id: string;
358
- label: string;
359
- form?: FormDefinition;
360
- },
361
- labelOverride?: string | null,
362
- overrides: { supportsScheduling?: boolean } = {},
363
- ): ProcessActionSummary {
364
- const visibleAction = listCurrentVisibleActions(deps, process).find(
365
- (candidate) => candidate.id === actionId,
366
- );
367
- const preview =
368
- visibleAction?.preview ??
369
- deps.processActionRegistry?.resolveActionPreview(process.processId, process, actionId) ??
370
- null;
371
- const supportsScheduling =
372
- overrides.supportsScheduling ??
373
- Boolean(
374
- actionHasPurePlan(deps, process, actionId) &&
375
- deps.processActionRegistry?.resolveActionScheduling(process.processId, process, actionId),
376
- );
377
- return buildProcessActionSummary(action, labelOverride ?? visibleAction?.label ?? action.label, {
378
- description: visibleAction?.description ?? null,
379
- preview: buildProcessActionPreviewSummary(deps, preview, process),
380
- supportsScheduling,
381
- supportsNextTurnModelOverride: previewSupportsNextTurnModelOverride(
382
- deps,
383
- process,
384
- actionId,
385
- preview,
386
- ),
387
- });
388
- }
389
-
390
- export function listVisibleActionsForProcess(deps: RouteDeps, process: ProcessInstance) {
391
- return listVisibleAttentionActionsForProcess(deps, process).map((action) =>
392
- buildActionSummaryForProcess(deps, process, action.id, action, action.label),
393
- );
394
- }
395
-
396
- export function processDefinesLeafOutcome(deps: RouteDeps, process: ProcessInstance): boolean {
397
341
  return deps.processUiRegistry?.getLeafOutcomeDefinition(process.processId) != null;
398
342
  }
399
343
 
@@ -602,107 +546,6 @@ export function normalizeRecoveryModelRequest(
602
546
  return parsed.ok ? { ok: true, request: parsed.request } : parsed;
603
547
  }
604
548
 
605
- export function buildProcessActionPreviewSummary(
606
- deps: RouteDeps,
607
- preview: {
608
- candidateSelectedTurnId: string | null;
609
- lifecycleStatus?: string | null;
610
- } | null,
611
- process: ProcessInstance,
612
- ): ProcessActionPreviewSummary | null {
613
- if (!preview) {
614
- return null;
615
- }
616
- if (!preview.candidateSelectedTurnId) {
617
- return {
618
- kind: "terminal",
619
- turnId: null,
620
- turnKind: null,
621
- description: preview.lifecycleStatus === "aborted" ? "Abort process" : "Complete process",
622
- };
623
- }
624
- const turnDef = deps.processActionRegistry?.getTurnDefinition(
625
- process.processId,
626
- preview.candidateSelectedTurnId,
627
- );
628
- if (!turnDef) {
629
- return null;
630
- }
631
- return {
632
- kind: "turn",
633
- turnId: preview.candidateSelectedTurnId,
634
- turnKind: turnDef.kind,
635
- description: turnDef.description,
636
- };
637
- }
638
-
639
- export function previewSupportsNextTurnModelOverride(
640
- deps: RouteDeps,
641
- process: ProcessInstance,
642
- actionId: string,
643
- preview: { candidateSelectedTurnId: string | null } | null,
644
- ): boolean {
645
- if (!preview?.candidateSelectedTurnId) {
646
- return false;
647
- }
648
- if (!actionHasPurePlan(deps, process, actionId)) {
649
- return false;
650
- }
651
- const turnDef = deps.processActionRegistry?.getTurnDefinition(
652
- process.processId,
653
- preview.candidateSelectedTurnId,
654
- );
655
- return Boolean(turnDef && isLlmTurnDefinition(turnDef));
656
- }
657
-
658
- export function buildProcessActionSummary(
659
- action: {
660
- id: string;
661
- label: string;
662
- form?: FormDefinition;
663
- },
664
- labelOverride?: string | null,
665
- opts: {
666
- description?: string | null;
667
- preview?: ProcessActionPreviewSummary | null;
668
- supportsScheduling?: boolean;
669
- supportsNextTurnModelOverride?: boolean;
670
- } = {},
671
- ): ProcessActionSummary {
672
- return {
673
- id: action.id,
674
- label: labelOverride?.trim() ? labelOverride : action.label,
675
- description: opts.description ?? null,
676
- preview: opts.preview ?? null,
677
- supportsScheduling: opts.supportsScheduling === true,
678
- supportsNextTurnModelOverride: opts.supportsNextTurnModelOverride === true,
679
- ...(action.form
680
- ? {
681
- form: {
682
- id: action.form.id,
683
- title: action.form.title,
684
- submitLabel: action.form.submitLabel,
685
- fields: action.form.fields.map((field) => ({ ...field })),
686
- },
687
- }
688
- : {}),
689
- };
690
- }
691
-
692
- export function getScheduledActionDetailForProcess(
693
- deps: RouteDeps,
694
- process: ProcessInstance,
695
- ): ScheduledActionDetail | null {
696
- return getPresentedScheduledActionDetailForProcess(
697
- {
698
- ...deps,
699
- buildActionSummaryForProcess: (process, actionId, action, labelOverride, overrides) =>
700
- buildActionSummaryForProcess(deps, process, actionId, action, labelOverride, overrides),
701
- },
702
- process,
703
- );
704
- }
705
-
706
549
  export function buildLauncherModelConfigSchema(
707
550
  deps: RouteDeps,
708
551
  processId: string,
@@ -285,36 +285,45 @@ export function createIpcHandler(deps: IpcHandlerDeps, callbacks: IpcHandlerCall
285
285
  break;
286
286
  }
287
287
  case "worker.turn_started": {
288
- void deps.commands
289
- .acceptWorkerTurnStart(instanceId, {
290
- workerLeaseId: activeLease.id,
288
+ let accepted = false;
289
+ const onRecorded = (turnRecordId: string) => {
290
+ accepted = true;
291
+ eventIngestor.noteTurnStarted(instanceId, turnRecordId);
292
+ callbacks.onWorkerTurnStartAccepted?.(instanceId, workerId, {
291
293
  startRecordId: msg.payload.startRecordId,
292
- proposedTurnRecordId: msg.payload.proposedTurnRecordId,
293
- })
294
- .then((result) => {
295
- if (!result.ok || !result.data) {
294
+ turnRecordId,
295
+ });
296
+ };
297
+ void deps.commands
298
+ .acceptWorkerTurnStart(
299
+ instanceId,
300
+ {
301
+ workerLeaseId: activeLease.id,
302
+ startRecordId: msg.payload.startRecordId,
303
+ proposedTurnRecordId: msg.payload.proposedTurnRecordId,
304
+ },
305
+ { onRecorded },
306
+ )
307
+ .then(() => {
308
+ if (!accepted) {
296
309
  callbacks.onWorkerFailed?.(instanceId, workerId, "Worker turn start was rejected");
297
310
  return;
298
311
  }
299
- eventIngestor.noteTurnStarted(instanceId, result.data.turnRecordId);
300
- // Acceptance persists the correlated turn record before launch projection.
301
312
  launchCoordinator?.refresh(instanceId);
302
- callbacks.onWorkerTurnStartAccepted?.(instanceId, workerId, {
303
- startRecordId: msg.payload.startRecordId,
304
- turnRecordId: result.data.turnRecordId,
305
- });
306
313
  })
307
- .catch(() =>
308
- callbacks.onWorkerFailed?.(instanceId, workerId, "Worker turn start failed"),
309
- );
314
+ .catch(() => {
315
+ // Delivery/projection failures do not undo durable acceptance; replay is safe.
316
+ if (!accepted)
317
+ callbacks.onWorkerFailed?.(instanceId, workerId, "Worker turn start failed");
318
+ });
310
319
  break;
311
320
  }
312
321
  case "worker.turn_outcome": {
313
- turnRecorder.recordTurnOutcome(instanceId, workerId, msg.payload);
322
+ turnRecorder.recordTurnOutcome(instanceId, workerId, activeLease.id, msg.payload);
314
323
  break;
315
324
  }
316
325
  case "worker.turn_failed": {
317
- turnRecorder.recordTurnFailed(instanceId, workerId, msg.payload);
326
+ turnRecorder.recordTurnFailed(instanceId, workerId, activeLease.id, msg.payload);
318
327
  break;
319
328
  }
320
329
  case "worker.lifecycle_parked": {
@@ -14,6 +14,7 @@ import {
14
14
  type PiResourceBundle,
15
15
  type ServerToWorkerMessage,
16
16
  verifyCanonicalPiResourceBundle,
17
+ type WorkerMappedItem,
17
18
  type WorkerRuntimeSettingsSnapshot,
18
19
  type WorkerStartPayload,
19
20
  } from "@leitwerk-dev/worker-protocol";
@@ -39,6 +40,8 @@ export interface WorkerStartPayloadBuilderDeps
39
40
  RepositoryBundle,
40
41
  "processes" | "projects" | "inputs" | "turnRecords" | "turnStarts" | "leases" | "events"
41
42
  > {
43
+ /** Required for processes that declare mapped LLM turns. @internal */
44
+ mappedRuns?: Pick<RepositoryBundle["mappedRuns"], "getById" | "getItem">;
42
45
  /** @internal */
43
46
  config: LeitwerkConfig;
44
47
  /** @internal */
@@ -219,6 +222,26 @@ function buildTurnResultMarkdownByProduct(
219
222
  return Object.keys(byProduct).length > 0 ? byProduct : undefined;
220
223
  }
221
224
 
225
+ function resolveMappedItem(
226
+ start: TurnStartRecord,
227
+ deps: Pick<WorkerStartPayloadBuilderDeps, "mappedRuns">,
228
+ ): WorkerMappedItem | undefined {
229
+ if (!start.iteration) return undefined;
230
+ const run = deps.mappedRuns?.getById(start.iteration.runId);
231
+ const item = deps.mappedRuns?.getItem(start.iteration.runId, start.iteration.itemIndex);
232
+ if (!run || !item || item.itemKey !== start.iteration.itemKey) {
233
+ throw new Error(`Mapped item for worker start '${start.id}' is unavailable`);
234
+ }
235
+ return {
236
+ runId: run.id,
237
+ itemKey: item.itemKey,
238
+ itemLabel: item.label,
239
+ itemIndex: item.itemIndex,
240
+ itemCount: run.itemCount,
241
+ item: JSON.parse(item.itemJson) as unknown,
242
+ };
243
+ }
244
+
222
245
  function resolveLlmPreparation(
223
246
  start: TurnStartRecord,
224
247
  deps: Pick<WorkerStartPayloadBuilderDeps, "events">,
@@ -320,6 +343,7 @@ export function createWorkerStartPayloadBuilder(deps: WorkerStartPayloadBuilderD
320
343
  null)
321
344
  : null;
322
345
  const contextSnapshot = buildWorkerRuntimeContextSnapshot(process, start);
346
+ const iteration = resolveMappedItem(start, deps);
323
347
  const repositoryCredentials =
324
348
  deps.resolveRepositoryCredentials?.({
325
349
  process,
@@ -380,6 +404,7 @@ export function createWorkerStartPayloadBuilder(deps: WorkerStartPayloadBuilderD
380
404
  ...(repositoryCredentials.length > 0 ? { repositoryCredentials } : {}),
381
405
  ...(dockerRegistryCredentials.length > 0 ? { dockerRegistryCredentials } : {}),
382
406
  ...(integrationTools && integrationTools.length > 0 ? { integrationTools } : {}),
407
+ ...(iteration ? { iteration } : {}),
383
408
  };
384
409
  const payload: WorkerStartPayload =
385
410
  bootstrap.kind === "llm"
@@ -82,6 +82,8 @@ export interface SupervisorDeps
82
82
  /** @internal */
83
83
  startupObservations?: RepositoryBundle["startupObservations"];
84
84
  /** @internal */
85
+ mappedRuns?: RepositoryBundle["mappedRuns"];
86
+ /** @internal */
85
87
  config: LeitwerkConfig;
86
88
  /** @internal */
87
89
  getLaunchCoordinator?: () => LaunchCoordinator | undefined;
@@ -127,6 +127,7 @@ export function createWorkerTurnIpcRecorder(
127
127
  const recoverRecordingFailure = async (input: {
128
128
  instanceId: string;
129
129
  workerId: string;
130
+ workerLeaseId: string;
130
131
  turnRecordId: string;
131
132
  terminalType: TerminalType;
132
133
  failure: unknown;
@@ -147,6 +148,7 @@ export function createWorkerTurnIpcRecorder(
147
148
  return;
148
149
  }
149
150
  const fallback = await deps.commands.recordWorkerFailure(input.instanceId, {
151
+ workerLeaseId: input.workerLeaseId,
150
152
  errorCode: details.code,
151
153
  message: `Server could not durably record worker turn ${input.terminalType}: ${details.message}`,
152
154
  errorClass: "infrastructure",
@@ -180,6 +182,7 @@ export function createWorkerTurnIpcRecorder(
180
182
  const recordTerminal = async <T>(input: {
181
183
  instanceId: string;
182
184
  workerId: string;
185
+ workerLeaseId: string;
183
186
  turnRecordId: string;
184
187
  terminalType: TerminalType;
185
188
  record: () => Promise<T>;
@@ -204,6 +207,7 @@ export function createWorkerTurnIpcRecorder(
204
207
  recordTurnOutcome(
205
208
  instanceId: string,
206
209
  workerId: string,
210
+ workerLeaseId: string,
207
211
  payload: WorkerTurnOutcomePayload,
208
212
  ): void {
209
213
  const { turnId, ...rest } = payload;
@@ -217,6 +221,7 @@ export function createWorkerTurnIpcRecorder(
217
221
  void recordTerminal({
218
222
  instanceId,
219
223
  workerId,
224
+ workerLeaseId,
220
225
  turnRecordId: rest.turnRecordId,
221
226
  terminalType: "outcome",
222
227
  record: () =>
@@ -236,12 +241,18 @@ export function createWorkerTurnIpcRecorder(
236
241
  recoveryContext: createGenericFailedTurnRecoveryContext(),
237
242
  });
238
243
  },
239
- recordTurnFailed(instanceId: string, workerId: string, payload: WorkerTurnFailedPayload): void {
244
+ recordTurnFailed(
245
+ instanceId: string,
246
+ workerId: string,
247
+ workerLeaseId: string,
248
+ payload: WorkerTurnFailedPayload,
249
+ ): void {
240
250
  const { errorClass, failureCode, failureDetails: details, ...rest } = payload;
241
251
  if (errorClass !== undefined && !isWorkerErrorClass(errorClass)) {
242
252
  void recoverRecordingFailure({
243
253
  instanceId,
244
254
  workerId,
255
+ workerLeaseId,
245
256
  turnRecordId: rest.turnRecordId,
246
257
  terminalType: "failure",
247
258
  failure: new Error(`Invalid worker error class '${errorClass}'`),
@@ -260,6 +271,7 @@ export function createWorkerTurnIpcRecorder(
260
271
  void recordTerminal({
261
272
  instanceId,
262
273
  workerId,
274
+ workerLeaseId,
263
275
  turnRecordId: rest.turnRecordId,
264
276
  terminalType: "failure",
265
277
  record: () =>
@@ -1,15 +1,33 @@
1
+ import type { ResolvedTurnStart } from "@leitwerk-dev/domain";
1
2
  import type { AppContext } from "../app.js";
2
3
 
3
4
  /** @internal */
4
- export function createAcceptedLlmTurn(
5
- ctx: AppContext | null,
6
- input: Parameters<AppContext["deps"]["turnRecords"]["create"]>[0] & {
5
+ type AcceptedTurnRepos = Pick<
6
+ AppContext["deps"],
7
+ "processes" | "turnRecords" | "turnStarts" | "leases"
8
+ >;
9
+
10
+ /** @internal */
11
+ type AcceptedTurnContext = {
12
+ /** @internal */
13
+ deps: AcceptedTurnRepos;
14
+ };
15
+
16
+ /** Compatibility name for existing LLM fixtures. @internal */
17
+ export const createAcceptedLlmTurn = createAcceptedWorkerTurn;
18
+ /** Compatibility name for existing LLM starts. @internal */
19
+ export const createAcceptedLlmTurnStart = createAcceptedWorkerTurnStart;
20
+
21
+ /** @internal */
22
+ export function createAcceptedWorkerTurn(
23
+ ctx: AcceptedTurnContext | null,
24
+ input: Parameters<AcceptedTurnRepos["turnRecords"]["create"]>[0] & {
7
25
  /** @internal */
8
26
  id: string;
9
27
  /** @internal */
10
- turnType: "llm";
28
+ turnType: "llm" | "automatic";
11
29
  },
12
- options: Parameters<typeof createAcceptedLlmTurnStart>[3] & {
30
+ options: Parameters<typeof createAcceptedWorkerTurnStart>[3] & {
13
31
  /** @internal */
14
32
  current?: boolean;
15
33
  /** @internal */
@@ -17,24 +35,25 @@ export function createAcceptedLlmTurn(
17
35
  } = {},
18
36
  ) {
19
37
  if (!ctx) throw new Error("Server context not initialized");
38
+ const { deps: repos } = ctx;
20
39
  const current = options.current ?? input.status === "running";
21
- const lease = ctx.deps.leases.create({
40
+ const lease = repos.leases.create({
22
41
  instanceId: input.instanceId,
23
42
  workerId: options.workerId ?? `wkr_${input.id}`,
24
43
  state: current ? (input.status === "failed" ? "failed" : "busy") : "exited",
25
44
  });
26
- const start = createAcceptedLlmTurnStart(ctx, input, lease.id, options);
27
- const record = ctx.deps.turnRecords.create({
45
+ const start = createAcceptedWorkerTurnStart(ctx, input, lease.id, options);
46
+ const record = repos.turnRecords.create({
28
47
  ...input,
29
48
  turnStartRecordId: start.id,
30
49
  acceptedWorkerLeaseId: lease.id,
31
50
  });
32
51
  if (current) {
33
- ctx.deps.processes.update(input.instanceId, {
52
+ repos.processes.update(input.instanceId, {
34
53
  currentExecution: { kind: "worker_start", id: start.id },
35
54
  });
36
55
  } else {
37
- ctx.deps.leases.update(lease.id, {
56
+ repos.leases.update(lease.id, {
38
57
  exitedAt: input.endedAt ?? input.startedAt ?? new Date().toISOString(),
39
58
  });
40
59
  }
@@ -42,9 +61,11 @@ export function createAcceptedLlmTurn(
42
61
  }
43
62
 
44
63
  /** @internal */
45
- export function createAcceptedLlmTurnStart(
46
- ctx: AppContext,
64
+ function createAcceptedWorkerTurnStart(
65
+ ctx: AcceptedTurnContext,
47
66
  input: {
67
+ /** @internal */
68
+ turnType?: "llm" | "automatic";
48
69
  /** @internal */
49
70
  id: string;
50
71
  /** @internal */
@@ -57,6 +78,8 @@ export function createAcceptedLlmTurnStart(
57
78
  /** @internal */
58
79
  id?: string;
59
80
  /** @internal */
81
+ preparedStart?: Extract<ResolvedTurnStart, { kind: "llm" }>;
82
+ /** @internal */
60
83
  model?: {
61
84
  /** @internal */
62
85
  profileId: string;
@@ -77,27 +100,31 @@ export function createAcceptedLlmTurnStart(
77
100
  id: options.id ?? `tsr_${input.id}`,
78
101
  instanceId: input.instanceId,
79
102
  turnId: input.turnId,
80
- turnType: "llm",
103
+ turnType: input.turnType ?? "llm",
81
104
  proposedTurnRecordId: input.id,
82
105
  startKind: "selected_turn",
83
106
  recoveryTurnRecordId: null,
84
107
  continuation: null,
85
108
  state: {
86
109
  kind: "accepted",
87
- start: {
88
- kind: "llm",
89
- model: options.model ?? {
90
- profileId: "fixture-profile",
91
- providerId: "fixture-provider",
92
- modelId: "fixture-model",
93
- thinkingLevel: "off",
94
- },
95
- providerOptions: {},
96
- providerWorkerConfig: null,
97
- piResourceSnapshotDigest: options.piResourceSnapshotDigest ?? "fixture-resource-digest",
98
- workerRuntimeProfileId: options.workerRuntimeProfileId ?? "local",
99
- piSettings: {},
100
- },
110
+ start:
111
+ input.turnType === "automatic"
112
+ ? { kind: "automatic" }
113
+ : (options.preparedStart ?? {
114
+ kind: "llm",
115
+ model: options.model ?? {
116
+ profileId: "fixture-profile",
117
+ providerId: "fixture-provider",
118
+ modelId: "fixture-model",
119
+ thinkingLevel: "off",
120
+ },
121
+ providerOptions: {},
122
+ providerWorkerConfig: null,
123
+ piResourceSnapshotDigest:
124
+ options.piResourceSnapshotDigest ?? "fixture-resource-digest",
125
+ workerRuntimeProfileId: options.workerRuntimeProfileId ?? "local",
126
+ piSettings: {},
127
+ }),
101
128
  turnRecordId: input.id,
102
129
  acceptedWorkerLeaseId,
103
130
  },