@leitwerk-dev/server 0.3.0 → 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 (120) 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-KIOQNNG6.js → chunk-HK6BLLHA.js} +738 -506
  5. package/dist/chunk-HK6BLLHA.js.map +1 -0
  6. package/dist/{chunk-LK3RO6C7.js → chunk-QCHS3X33.js} +486 -136
  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 +18 -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/testing.d.ts +1 -1
  72. package/dist/testing.d.ts.map +1 -1
  73. package/dist/testing.js +13 -10
  74. package/dist/testing.js.map +1 -1
  75. package/package.json +11 -11
  76. package/src/app.ts +2 -0
  77. package/src/db/database.ts +28 -0
  78. package/src/db/mapped-llm-run-repo.ts +177 -0
  79. package/src/db/process-turn-record-repo.ts +8 -1
  80. package/src/db/repo-helpers.ts +11 -1
  81. package/src/db/repositories.ts +5 -0
  82. package/src/db/schema.ts +70 -1
  83. package/src/db/turn-start-record-repo.ts +5 -1
  84. package/src/domain-logic/outcome-tools.ts +50 -6
  85. package/src/future-execution-presenter.ts +10 -17
  86. package/src/launch-coordinator-test-harness.ts +8 -4
  87. package/src/process-action-presenter.ts +133 -0
  88. package/src/process-engine/engine.ts +2 -2
  89. package/src/process-engine/mapped-turns.ts +330 -0
  90. package/src/process-engine/operation.ts +1 -1
  91. package/src/process-engine/ops/accept-worker-turn-start.ts +6 -0
  92. package/src/process-engine/ops/retry-startup.ts +1 -0
  93. package/src/process-engine/ops/turn-outcome.ts +7 -5
  94. package/src/process-engine/recorder.ts +12 -0
  95. package/src/process-engine/runner.ts +8 -8
  96. package/src/process-engine/types.ts +6 -0
  97. package/src/process-engine/writes/build-process-abort-writes.ts +1 -0
  98. package/src/process-engine/writes/build-recovery-start-writes.ts +1 -0
  99. package/src/process-engine/writes/build-turn-outcome-writes.ts +80 -20
  100. package/src/process-engine/writes/build-turn-selection-writes.ts +2 -31
  101. package/src/process-engine/writes/commit-writes.ts +5 -0
  102. package/src/process-engine/writes/reserve-selected-turn-start.ts +44 -0
  103. package/src/process-engine/writes/writes.ts +27 -0
  104. package/src/process-turn-navigation.ts +86 -8
  105. package/src/process-ui-snapshot-presenter.ts +40 -4
  106. package/src/routes/process-actions.ts +1 -1
  107. package/src/routes/process-diagnostics-assembler.ts +32 -6
  108. package/src/routes/process-primary-path-assembler.ts +17 -33
  109. package/src/routes/process-route-helpers.ts +8 -165
  110. package/src/supervisor/ipc-handler.ts +27 -18
  111. package/src/supervisor/worker-start-payload-builder.ts +25 -0
  112. package/src/supervisor/worker-supervisor.ts +2 -0
  113. package/src/supervisor/worker-turn-ipc-recorder.ts +13 -1
  114. package/src/test-helpers/accepted-turn-start.ts +51 -27
  115. package/src/test-helpers/owned-test-deps.ts +45 -0
  116. package/src/testing.ts +4 -1
  117. package/dist/app-4QSV4FUQ.js +0 -8
  118. package/dist/chunk-KIOQNNG6.js.map +0 -1
  119. package/dist/chunk-LK3RO6C7.js.map +0 -1
  120. /package/dist/{app-4QSV4FUQ.js.map → app-MSJXFK33.js.map} +0 -0
@@ -118,7 +118,7 @@ import {
118
118
  validateCredentialStatus,
119
119
  verifyOpaqueToken,
120
120
  withTimeout
121
- } from "./chunk-KIOQNNG6.js";
121
+ } from "./chunk-HK6BLLHA.js";
122
122
 
123
123
  // src/app.ts
124
124
  import path8 from "node:path";
@@ -1086,6 +1086,37 @@ function canAbort(lifecycleStatus) {
1086
1086
  return lifecycleStatus !== "completed" && lifecycleStatus !== "aborted";
1087
1087
  }
1088
1088
 
1089
+ // src/process-engine/writes/reserve-selected-turn-start.ts
1090
+ function reserveSelectedTurnStart(writes, process2, turnId, turnType, iteration) {
1091
+ const startId = generateId("tsr");
1092
+ writes.turnStartWrites.push({
1093
+ kind: "create",
1094
+ input: {
1095
+ id: startId,
1096
+ instanceId: process2.id,
1097
+ turnId,
1098
+ turnType,
1099
+ proposedTurnRecordId: generateId("trn"),
1100
+ startKind: "selected_turn",
1101
+ recoveryTurnRecordId: null,
1102
+ continuation: null,
1103
+ state: turnType === "automatic" ? { kind: "starting", start: { kind: "automatic" } } : {
1104
+ kind: "preparation_failed",
1105
+ requestedModelProfileId: process2.selectedTurnModelProfileId ?? null,
1106
+ providerOptions: {},
1107
+ code: "model_required",
1108
+ safeSummary: "LLM start requires model preflight"
1109
+ },
1110
+ ...iteration ? { iteration } : {}
1111
+ }
1112
+ });
1113
+ applyProcessPatchField(writes, process2, "currentExecution", {
1114
+ kind: "worker_start",
1115
+ id: startId
1116
+ });
1117
+ if (turnType === "llm") applyProcessPatchField(writes, process2, "lifecycleStatus", "error");
1118
+ }
1119
+
1089
1120
  // src/process-engine/writes/build-turn-selection-writes.ts
1090
1121
  function deriveLifecycleStatusForSelectedTurn(processGraphs, processId, turnId) {
1091
1122
  const turn = getProcessTurnGraph(processGraphs, processId, turnId);
@@ -1142,33 +1173,7 @@ function buildTurnSelectionWrites(processGraphs, process2, input) {
1142
1173
  if (input.toTurnId && targetLifecycleStatus === "active") {
1143
1174
  const target = getProcessTurnGraph(processGraphs, process2.processId, input.toTurnId);
1144
1175
  if (target?.turnType === "llm" || target?.turnType === "automatic") {
1145
- const startId = generateId("tsr");
1146
- writes.turnStartWrites.push({
1147
- kind: "create",
1148
- input: {
1149
- id: startId,
1150
- instanceId: process2.id,
1151
- turnId: input.toTurnId,
1152
- turnType: target.turnType,
1153
- proposedTurnRecordId: generateId("trn"),
1154
- startKind: "selected_turn",
1155
- recoveryTurnRecordId: null,
1156
- continuation: null,
1157
- state: target.turnType === "automatic" ? { kind: "starting", start: { kind: "automatic" } } : {
1158
- kind: "preparation_failed",
1159
- requestedModelProfileId: process2.selectedTurnModelProfileId ?? null,
1160
- providerOptions: {},
1161
- code: "model_required",
1162
- safeSummary: "LLM start requires model preflight"
1163
- }
1164
- }
1165
- });
1166
- applyProcessPatchField(writes, process2, "currentExecution", {
1167
- kind: "worker_start",
1168
- id: startId
1169
- });
1170
- if (target.turnType === "llm")
1171
- applyProcessPatchField(writes, process2, "lifecycleStatus", "error");
1176
+ reserveSelectedTurnStart(writes, process2, input.toTurnId, target.turnType);
1172
1177
  }
1173
1178
  } else if (input.toTurnId === null || targetLifecycleStatus === "waiting" || targetLifecycleStatus === "completed" || targetLifecycleStatus === "aborted") {
1174
1179
  applyProcessPatchField(writes, process2, "currentExecution", null);
@@ -1934,7 +1939,7 @@ function createExternalSourceService(deps) {
1934
1939
  `External source '${input.armingId}' is stale for selected turn '${String(ctx.process.selectedTurnId)}'`
1935
1940
  );
1936
1941
  }
1937
- const failedDecision = (failure) => {
1942
+ const failedDecision = (failure2) => {
1938
1943
  const writes = createWrites();
1939
1944
  appendExternalSourceEvent(
1940
1945
  writes,
@@ -1944,11 +1949,11 @@ function createExternalSourceService(deps) {
1944
1949
  ...armingEventData(arming),
1945
1950
  provider: input.event,
1946
1951
  fireInput: input.input,
1947
- code: failure.code,
1948
- message: failure.message
1952
+ code: failure2.code,
1953
+ message: failure2.message
1949
1954
  })
1950
1955
  );
1951
- return accept({ writes, data: { ok: false, code: failure.code } });
1956
+ return accept({ writes, data: { ok: false, code: failure2.code } });
1952
1957
  };
1953
1958
  const effectWrites = await buildExternalSourceEffectWrites({
1954
1959
  arming,
@@ -3536,15 +3541,15 @@ function recoverDeduplicatedCommit(deps, dedupKey, futureExecutionPlan) {
3536
3541
  return deps.transaction((repos) => reuseDeduplicatedCommit(repos, dedupKey, futureExecutionPlan));
3537
3542
  }
3538
3543
  function launchStartFailure(commit, result) {
3539
- const failure = mapLaunchStartFailure(result);
3544
+ const failure2 = mapLaunchStartFailure(result);
3540
3545
  const process2 = result.process ?? commit.process;
3541
3546
  return {
3542
3547
  ok: false,
3543
3548
  stage: "post_commit",
3544
- status: failure.status,
3549
+ status: failure2.status,
3545
3550
  body: {
3546
- ...failure.body,
3547
- process: failure.body.process ?? process2,
3551
+ ...failure2.body,
3552
+ process: failure2.body.process ?? process2,
3548
3553
  projects: commit.projects
3549
3554
  },
3550
3555
  process: process2,
@@ -3660,12 +3665,12 @@ async function createProcessFromLaunchPlanWithDisposition(deps, launchPlan, opts
3660
3665
  reused: commit.dedupReused === true
3661
3666
  } : launchStartFailure(commit, started);
3662
3667
  } catch (error) {
3663
- const failure = toLaunchFailureBody(error, {
3668
+ const failure2 = toLaunchFailureBody(error, {
3664
3669
  createdProcess: commit.process,
3665
3670
  projects: commit.projects
3666
3671
  });
3667
3672
  return {
3668
- ...failure,
3673
+ ...failure2,
3669
3674
  stage: "post_commit",
3670
3675
  process: commit.process,
3671
3676
  projects: commit.projects
@@ -4434,22 +4439,22 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4434
4439
  const opened = deps.launchPipeline.open({ launcherId: existing.launcherId, origin: "ui" });
4435
4440
  const result = await deps.launchPipeline.run(opened.launchRunId, {
4436
4441
  async resolve() {
4437
- const failure = (value) => ({
4442
+ const failure2 = (value) => ({
4438
4443
  kind: "failed",
4439
4444
  failure: { safeSummary: "Review the launch configuration and try again.", value }
4440
4445
  });
4441
4446
  if (!deps.launcherService)
4442
- return failure({ kind: "unavailable", reason: "Launcher service is not available" });
4447
+ return failure2({ kind: "unavailable", reason: "Launcher service is not available" });
4443
4448
  const parsed = parseFutureLaunchPayloadJson3(existing.payloadJson);
4444
4449
  if (!parsed.ok)
4445
- return failure(invalidOutcome("invalid_payload", "Scheduled launch payload is invalid"));
4450
+ return failure2(invalidOutcome("invalid_payload", "Scheduled launch payload is invalid"));
4446
4451
  const launchRequest = resolveScheduledLaunchUpdateRequest(existing, request, parsed.value);
4447
- if (!launchRequest.ok) return failure({ kind: "invalid", issues: [launchRequest.issue] });
4452
+ if (!launchRequest.ok) return failure2({ kind: "invalid", issues: [launchRequest.issue] });
4448
4453
  const resolved = await deps.launcherService.resolveUiLauncher(
4449
4454
  existing.launcherId ?? parsed.value.launchPlan.launcherId,
4450
4455
  launchRequest.value.launcherInput
4451
4456
  );
4452
- if (!resolved.ok) return failure(launcherResolutionFailure(resolved));
4457
+ if (!resolved.ok) return failure2(launcherResolutionFailure(resolved));
4453
4458
  return {
4454
4459
  kind: "resolved",
4455
4460
  value: {
@@ -6026,7 +6031,7 @@ function createLaunchCoordinator(deps) {
6026
6031
  const projected = project(run);
6027
6032
  return JSON.stringify(projected) === JSON.stringify(run) ? run : mutate(run.id, () => projected);
6028
6033
  }
6029
- function failure(safeSummary, value) {
6034
+ function failure2(safeSummary, value) {
6030
6035
  return { safeSummary, value };
6031
6036
  }
6032
6037
  function existingLaunchResult(run) {
@@ -6069,7 +6074,7 @@ function createLaunchCoordinator(deps) {
6069
6074
  if (request.request.schedule.mode !== "now") {
6070
6075
  return {
6071
6076
  kind: "failed",
6072
- failure: failure("Use the scheduling controls to save a future launch.", {
6077
+ failure: failure2("Use the scheduling controls to save a future launch.", {
6073
6078
  kind: "invalid",
6074
6079
  issues: [
6075
6080
  {
@@ -6086,7 +6091,7 @@ function createLaunchCoordinator(deps) {
6086
6091
  );
6087
6092
  return resolved.ok ? { kind: "resolved", value: resolved.launcher } : {
6088
6093
  kind: "failed",
6089
- failure: failure("Review the highlighted launcher fields and try again.", {
6094
+ failure: failure2("Review the highlighted launcher fields and try again.", {
6090
6095
  kind: "invalid",
6091
6096
  issues: resolved.errors
6092
6097
  })
@@ -6129,7 +6134,7 @@ function createLaunchCoordinator(deps) {
6129
6134
  } : prepared.prepared
6130
6135
  } : {
6131
6136
  ok: false,
6132
- failure: failure("Review the launch configuration and try again.", prepared.outcome)
6137
+ failure: failure2("Review the launch configuration and try again.", prepared.outcome)
6133
6138
  };
6134
6139
  },
6135
6140
  async commit(prepared, ctx) {
@@ -6157,14 +6162,14 @@ function createLaunchCoordinator(deps) {
6157
6162
  }
6158
6163
  return {
6159
6164
  kind: "failed",
6160
- failure: failure(
6165
+ failure: failure2(
6161
6166
  "The process could not be created. Check availability and try again.",
6162
6167
  result
6163
6168
  )
6164
6169
  };
6165
6170
  },
6166
6171
  unexpectedFailure() {
6167
- return failure("The launch could not be completed. Try again.", {
6172
+ return failure2("The launch could not be completed. Try again.", {
6168
6173
  kind: "failed",
6169
6174
  issue: { code: "launch_failed", message: "The launch could not be completed" }
6170
6175
  });
@@ -6339,7 +6344,7 @@ function createLaunchCoordinator(deps) {
6339
6344
  );
6340
6345
  return prepared.ok ? { ok: true, value: prepared.launchPlan } : {
6341
6346
  ok: false,
6342
- failure: failure(
6347
+ failure: failure2(
6343
6348
  "The launch model configuration is unavailable. Review the watcher configuration.",
6344
6349
  prepared
6345
6350
  )
@@ -7283,6 +7288,7 @@ function buildAbortProcessWrites(input) {
7283
7288
  if (isWriteBuildFailure(writes)) {
7284
7289
  return writes;
7285
7290
  }
7291
+ writes.mappedRunWrites.push({ kind: "abort_active" });
7286
7292
  if (input.currentWorkerStart?.state.kind === "starting") {
7287
7293
  writes.turnStartWrites.push({
7288
7294
  kind: "cas_state",
@@ -7488,6 +7494,9 @@ function preparedStartMatchesDefinition(prepared, definition) {
7488
7494
  var AcceptWorkerTurnStart = defineOperation({
7489
7495
  kind: "accept_worker_turn_start",
7490
7496
  label: "Accept worker turn start",
7497
+ afterRecord(input, data) {
7498
+ input.onRecorded?.(data.turnRecordId);
7499
+ },
7491
7500
  decide(ctx, input) {
7492
7501
  if (ctx.process.lifecycleStatus !== "active" || ctx.process.currentExecution?.kind !== "worker_start" || ctx.process.currentExecution.id !== input.startRecordId) {
7493
7502
  return reject("stale_turn_start", "Worker start is no longer current and active");
@@ -7551,7 +7560,8 @@ var AcceptWorkerTurnStart = defineOperation({
7551
7560
  turnStartRecordId: start.id,
7552
7561
  acceptedWorkerLeaseId: lease.id,
7553
7562
  modelProfileId: acceptedLlmStart?.model.profileId ?? null,
7554
- modelSelectionProvenance: acceptedLlmStart?.modelSelectionProvenance ?? null
7563
+ modelSelectionProvenance: acceptedLlmStart?.modelSelectionProvenance ?? null,
7564
+ iteration: start.iteration ?? null
7555
7565
  }
7556
7566
  }
7557
7567
  ],
@@ -7621,6 +7631,7 @@ function buildRecoveryStartWrites({ process: process2, failedRun, acceptedStart
7621
7631
  turnId: failedRun.turnId,
7622
7632
  proposedTurnRecordId: generateId("trn"),
7623
7633
  recoveryTurnRecordId: failedRun.id,
7634
+ iteration: failedRun.iteration ?? null,
7624
7635
  state: recovery.turnType === "automatic" ? { kind: "starting", start: { kind: "automatic" } } : {
7625
7636
  kind: "preparation_failed",
7626
7637
  requestedModelProfileId: failedRun.modelProfileId,
@@ -8377,7 +8388,8 @@ var RetryStartup = defineOperation({
8377
8388
  startKind: "startup_retry",
8378
8389
  recoveryTurnRecordId: failed.recoveryTurnRecordId,
8379
8390
  continuation: failed.continuation,
8380
- state
8391
+ state,
8392
+ iteration: failed.iteration ?? null
8381
8393
  }
8382
8394
  });
8383
8395
  applyProcessPatchField(writes, ctx.process, "currentExecution", { kind: "worker_start", id });
@@ -8633,6 +8645,9 @@ async function captureLeafOutcomeSnapshot(options) {
8633
8645
  }
8634
8646
  }
8635
8647
 
8648
+ // src/process-engine/writes/build-turn-outcome-writes.ts
8649
+ import { SafeOutcomePlanningError as SafeOutcomePlanningError2 } from "@leitwerk-dev/process-sdk";
8650
+
8636
8651
  // src/domain-logic/outcome-tools.ts
8637
8652
  import {
8638
8653
  isUnknownRecord as isJsonObject,
@@ -8691,14 +8706,49 @@ var scalarParameters = {
8691
8706
  plural: "objects"
8692
8707
  }
8693
8708
  };
8709
+ function matchesNestedOutcomeSpec(spec, value) {
8710
+ switch (spec.type) {
8711
+ case "string":
8712
+ return typeof value === "string";
8713
+ case "number":
8714
+ return typeof value === "number" && Number.isFinite(value);
8715
+ case "boolean":
8716
+ return typeof value === "boolean";
8717
+ case "array": {
8718
+ const itemSpec = spec.items;
8719
+ return Array.isArray(value) && (spec.minItems === void 0 || value.length >= spec.minItems) && (!itemSpec || value.every((item) => matchesNestedOutcomeSpec(itemSpec, item)));
8720
+ }
8721
+ case "object": {
8722
+ if (!isJsonObject(value)) return false;
8723
+ const properties = spec.properties ?? {};
8724
+ if ((spec.required ?? []).some((key) => !Object.hasOwn(value, key))) return false;
8725
+ if (spec.additionalProperties === false && Object.keys(value).some((key) => !Object.hasOwn(properties, key)))
8726
+ return false;
8727
+ return Object.entries(properties).every(
8728
+ ([key, property]) => !Object.hasOwn(value, key) || matchesNestedOutcomeSpec(property, value[key])
8729
+ );
8730
+ }
8731
+ default:
8732
+ return false;
8733
+ }
8734
+ }
8694
8735
  function compileOutcomeParameterSchema(spec) {
8695
- return spec.type === "array" ? v3.array(scalarParameters[spec.items?.type ?? "string"].schema) : scalarParameters[spec.type].schema;
8736
+ if (spec.type !== "array") return scalarParameters[spec.type].schema;
8737
+ const itemSpec = spec.items ?? { type: "string" };
8738
+ return v3.custom(
8739
+ (value) => Array.isArray(value) && value.every((item) => matchesNestedOutcomeSpec(itemSpec, item)),
8740
+ "Expected an array matching its declared item schema"
8741
+ );
8696
8742
  }
8697
8743
  function effectiveArrayItemCount(spec, value) {
8698
8744
  return (spec.items?.type ?? "string") === "string" ? normalizeStringArray(value).length : value.length;
8699
8745
  }
8700
8746
  function expectedParameterLabel(spec) {
8701
- return spec.type === "array" ? `an array of ${scalarParameters[spec.items?.type ?? "string"].plural}` : scalarParameters[spec.type].label;
8747
+ if (spec.type !== "array") return scalarParameters[spec.type].label;
8748
+ if (spec.items?.type === "object")
8749
+ return spec.items.properties ? "an array of objects matching the declared schema" : "an array of objects";
8750
+ if (spec.items?.type === "array") return "an array of arrays matching the declared schema";
8751
+ return `an array of ${scalarParameters[spec.items?.type ?? "string"].plural}`;
8702
8752
  }
8703
8753
  function jsonValuesEqual(left, right) {
8704
8754
  if (left === right) {
@@ -8876,26 +8926,262 @@ function validateTurnOutcome(payload, turnDefinition, knownProjectKeys) {
8876
8926
  );
8877
8927
  }
8878
8928
 
8929
+ // src/process-engine/mapped-turns.ts
8930
+ import {
8931
+ collectMappedResults,
8932
+ freezeMappedItems,
8933
+ SafeOutcomePlanningError,
8934
+ yieldMappedItemResult
8935
+ } from "@leitwerk-dev/process-sdk";
8936
+ var MAX_EMPTY_MAPPED_ENTRIES = 16;
8937
+ function getMappedTurnSpec(registry, processId, turnId) {
8938
+ if (!registry || !turnId) return void 0;
8939
+ const turn = registry.getTurnDefinition(processId, turnId);
8940
+ return turn?.kind === "llm" ? turn.forEach : void 0;
8941
+ }
8942
+ function failure(code, message) {
8943
+ return { ok: false, code, message };
8944
+ }
8945
+ function planningFailure(error, code) {
8946
+ if (error instanceof SafeOutcomePlanningError) return failure(error.code, error.message);
8947
+ throw error instanceof Error ? error : new Error(`${code}: ${String(error)}`);
8948
+ }
8949
+ function serverContext(registry, process2, projects) {
8950
+ const { params: params2, state } = registry.resolveContextData(process2.processId, process2);
8951
+ return { process: process2, projects, params: params2, state };
8952
+ }
8953
+ function appendInto(target, source) {
8954
+ Object.assign(target, mergeWrites(target, source));
8955
+ }
8956
+ async function collectAndRoute(input) {
8957
+ let collected;
8958
+ try {
8959
+ collected = await collectMappedResults({
8960
+ turnId: input.turnId,
8961
+ spec: input.spec,
8962
+ ctx: input.ctx,
8963
+ resultJsons: input.resultJsons
8964
+ });
8965
+ } catch (error) {
8966
+ return planningFailure(error, "mapped_collect_failed");
8967
+ }
8968
+ const writes = buildServerTransitionWrites(input.processGraphs, input.process, {
8969
+ turnId: collected.route.nextTurnId ?? null,
8970
+ ...collected.route.lifecycleStatus ? { lifecycleStatus: collected.route.lifecycleStatus } : {},
8971
+ trigger: collected.route.trigger,
8972
+ state: collected.state
8973
+ });
8974
+ if (isWriteBuildFailure(writes)) return writes;
8975
+ appendProcessEvent(writes, input.process, {
8976
+ eventType: "mapped_run_collected",
8977
+ level: "info",
8978
+ message: `Collected ${input.resultJsons.length} result(s) for ${input.turnId}`,
8979
+ data: {
8980
+ runId: input.runId,
8981
+ turnId: input.turnId,
8982
+ itemCount: input.resultJsons.length,
8983
+ trigger: collected.route.trigger
8984
+ }
8985
+ });
8986
+ return writes;
8987
+ }
8988
+ async function planMappedTurnEntries(input) {
8989
+ const { writes } = input;
8990
+ const active = input.mappedRuns?.getActiveByInstance(input.process.id) ?? null;
8991
+ let activeAborted = false;
8992
+ for (let entry = 0; entry <= MAX_EMPTY_MAPPED_ENTRIES; entry += 1) {
8993
+ const candidate = { ...input.process, ...writes.processPatch };
8994
+ const startIndex = writes.turnStartWrites.findIndex(
8995
+ (write) => write.kind === "create" && write.input.turnType === "llm" && write.input.startKind === "selected_turn" && !write.input.iteration && write.input.turnId === candidate.selectedTurnId
8996
+ );
8997
+ const start = startIndex >= 0 ? writes.turnStartWrites[startIndex] : void 0;
8998
+ const spec = start?.kind === "create" ? getMappedTurnSpec(input.registry, candidate.processId, start.input.turnId) : void 0;
8999
+ if (!start || start.kind !== "create" || !spec || !input.registry) {
9000
+ const leavesActiveRun = active !== null && !activeAborted && !writes.mappedRunWrites.some((write) => write.kind === "complete_item") && (candidate.selectedTurnId !== active.turnId || candidate.lifecycleStatus === "completed" || candidate.lifecycleStatus === "aborted");
9001
+ if (leavesActiveRun) writes.mappedRunWrites.push({ kind: "abort_active" });
9002
+ return { ok: true };
9003
+ }
9004
+ if (entry === MAX_EMPTY_MAPPED_ENTRIES) {
9005
+ return failure("mapped_turn_loop", "Too many consecutive empty mapped turns");
9006
+ }
9007
+ if (!input.mappedRuns) {
9008
+ return failure("mapped_runs_unavailable", "Mapped turn storage is not available");
9009
+ }
9010
+ if (active && !activeAborted) {
9011
+ writes.mappedRunWrites.push({ kind: "abort_active" });
9012
+ activeAborted = true;
9013
+ }
9014
+ const turnId = start.input.turnId;
9015
+ const projects = input.projects.listByInstance(input.process.id);
9016
+ let ctx = serverContext(input.registry, candidate, projects);
9017
+ let frozen;
9018
+ try {
9019
+ frozen = freezeMappedItems(turnId, spec, ctx);
9020
+ } catch (error) {
9021
+ return planningFailure(error, "invalid_mapped_items");
9022
+ }
9023
+ const runId = generateId("mlr");
9024
+ writes.mappedRunWrites.push({
9025
+ kind: "create",
9026
+ input: {
9027
+ id: runId,
9028
+ instanceId: input.process.id,
9029
+ turnId,
9030
+ status: frozen.items.length > 0 ? "active" : "completed",
9031
+ items: frozen.items.map((item) => ({
9032
+ itemIndex: item.index,
9033
+ itemKey: item.key,
9034
+ label: item.label,
9035
+ itemJson: item.itemJson
9036
+ }))
9037
+ }
9038
+ });
9039
+ appendProcessEvent(writes, candidate, {
9040
+ eventType: "mapped_run_started",
9041
+ level: "info",
9042
+ message: `Froze ${frozen.items.length} item(s) for ${turnId}`,
9043
+ data: { runId, turnId, itemCount: frozen.items.length }
9044
+ });
9045
+ if (frozen.state !== void 0) {
9046
+ applyProcessPatchField(writes, candidate, "stateJson", JSON.stringify(frozen.state));
9047
+ ctx = { ...ctx, state: frozen.state };
9048
+ }
9049
+ const first = frozen.items[0];
9050
+ if (first) {
9051
+ start.input.iteration = { runId, itemKey: first.key, itemIndex: 0 };
9052
+ return { ok: true };
9053
+ }
9054
+ writes.turnStartWrites.splice(startIndex, 1);
9055
+ const routed = await collectAndRoute({
9056
+ processGraphs: input.processGraphs,
9057
+ process: { ...input.process, ...writes.processPatch },
9058
+ ctx,
9059
+ spec,
9060
+ turnId,
9061
+ runId,
9062
+ resultJsons: []
9063
+ });
9064
+ if (isWriteBuildFailure(routed)) return routed;
9065
+ appendInto(writes, routed);
9066
+ }
9067
+ return failure("mapped_turn_loop", "Too many consecutive empty mapped turns");
9068
+ }
9069
+ async function buildMappedItemOutcomeWrites(input) {
9070
+ const { payload, iteration } = input;
9071
+ if (!input.mappedRuns) {
9072
+ return failure("mapped_runs_unavailable", "Mapped turn storage is not available");
9073
+ }
9074
+ if (!iteration) {
9075
+ return failure("mapped_item_missing", `Turn '${payload.turnId}' has no active mapped item`);
9076
+ }
9077
+ const run = input.mappedRuns.getById(iteration.runId);
9078
+ const item = input.mappedRuns.getItem(iteration.runId, iteration.itemIndex);
9079
+ if (!run || !item || run.status !== "active" || run.turnId !== payload.turnId || run.nextIndex !== iteration.itemIndex || item.itemKey !== iteration.itemKey || item.status !== "pending") {
9080
+ return failure(
9081
+ "stale_mapped_item",
9082
+ `Mapped item '${iteration.itemKey}' is no longer the current item of '${payload.turnId}'`
9083
+ );
9084
+ }
9085
+ const ctx = serverContext(input.registry, input.process, input.projects);
9086
+ let resultJson;
9087
+ try {
9088
+ resultJson = await yieldMappedItemResult({
9089
+ turnId: payload.turnId,
9090
+ spec: input.spec,
9091
+ ctx,
9092
+ iteration: {
9093
+ runId: run.id,
9094
+ itemKey: item.itemKey,
9095
+ itemLabel: item.label,
9096
+ itemIndex: item.itemIndex,
9097
+ itemCount: run.itemCount,
9098
+ item: JSON.parse(item.itemJson)
9099
+ },
9100
+ event: {
9101
+ turnRecordId: payload.turnRecordId,
9102
+ turnId: payload.turnId,
9103
+ outcome: payload.outcome,
9104
+ params: payload.params ?? {},
9105
+ turnResultMarkdown: payload.turnResultMarkdown ?? null,
9106
+ ...input.prepared !== void 0 ? { prepared: input.prepared } : {}
9107
+ }
9108
+ });
9109
+ } catch (error) {
9110
+ return planningFailure(error, "invalid_mapped_result");
9111
+ }
9112
+ const writes = createWrites();
9113
+ writes.mappedRunWrites.push({
9114
+ kind: "complete_item",
9115
+ input: {
9116
+ runId: run.id,
9117
+ itemIndex: item.itemIndex,
9118
+ outcome: payload.outcome,
9119
+ resultJson,
9120
+ turnRecordId: payload.turnRecordId
9121
+ }
9122
+ });
9123
+ const nextIndex = item.itemIndex + 1;
9124
+ if (nextIndex < run.itemCount) {
9125
+ const next = input.mappedRuns.getItem(run.id, nextIndex);
9126
+ if (!next) return failure("stale_mapped_item", `Mapped run '${run.id}' lost item ${nextIndex}`);
9127
+ reserveSelectedTurnStart(writes, input.process, payload.turnId, "llm", {
9128
+ runId: run.id,
9129
+ itemKey: next.itemKey,
9130
+ itemIndex: nextIndex
9131
+ });
9132
+ writes.workerIntent = { kind: "reconcile" };
9133
+ return writes;
9134
+ }
9135
+ const resultJsons = input.mappedRuns.listItems(run.id).map((stored) => stored.itemIndex === item.itemIndex ? resultJson : stored.resultJson);
9136
+ if (resultJsons.some((json) => json === null)) {
9137
+ return failure("stale_mapped_item", `Mapped run '${run.id}' is missing item results`);
9138
+ }
9139
+ const routed = await collectAndRoute({
9140
+ processGraphs: input.processGraphs,
9141
+ process: input.process,
9142
+ ctx,
9143
+ spec: input.spec,
9144
+ turnId: payload.turnId,
9145
+ runId: run.id,
9146
+ resultJsons
9147
+ });
9148
+ if (isWriteBuildFailure(routed)) return routed;
9149
+ return mergeWrites(writes, routed);
9150
+ }
9151
+
8879
9152
  // src/process-engine/writes/build-turn-outcome-writes.ts
8880
9153
  function hasExplicitTurnSelectionChange(process2, writes) {
8881
9154
  return writes.processPatch.selectedTurnId !== void 0 && writes.processPatch.selectedTurnId !== process2.selectedTurnId;
8882
9155
  }
8883
- async function buildProcessTurnOutcomeEffectWrites(processGraphs, process2, projects, payload, processActionRegistry, turnRecords) {
9156
+ function loadPreparedData(process2, payload, events) {
9157
+ const preparationEvent = events?.listByInstanceTurnRecordEventTypes(process2.id, payload.turnRecordId, ["turn.prepared"]).at(-1);
9158
+ return preparationEvent?.data && typeof preparationEvent.data === "object" && "data" in preparationEvent.data ? preparationEvent.data.data : void 0;
9159
+ }
9160
+ async function buildProcessTurnOutcomeEffectWrites(processGraphs, process2, projects, payload, processActionRegistry, turnRecords, events) {
8884
9161
  const serverDef = processActionRegistry.getServerDefinition(process2.processId);
8885
9162
  const handlers = serverDef?.turnOutcomeHandlers.get(payload.turnId) ?? [];
8886
9163
  const { params: params2, state } = processActionRegistry.resolveContextData(process2.processId, process2);
8887
9164
  const plan = createProcessPlanCollector({ process: process2, projects, params: params2, state, turnRecords });
9165
+ const prepared = loadPreparedData(process2, payload, events);
8888
9166
  for (const handler of handlers) {
8889
- await handler(
8890
- {
8891
- turnRecordId: payload.turnRecordId,
8892
- turnId: payload.turnId,
8893
- outcome: payload.outcome,
8894
- params: payload.params ?? {},
8895
- turnResultMarkdown: payload.turnResultMarkdown ?? null
8896
- },
8897
- plan.context
8898
- );
9167
+ try {
9168
+ await handler(
9169
+ {
9170
+ turnRecordId: payload.turnRecordId,
9171
+ turnId: payload.turnId,
9172
+ outcome: payload.outcome,
9173
+ params: payload.params ?? {},
9174
+ turnResultMarkdown: payload.turnResultMarkdown ?? null,
9175
+ ...prepared !== void 0 ? { prepared } : {}
9176
+ },
9177
+ plan.context
9178
+ );
9179
+ } catch (error) {
9180
+ if (error instanceof SafeOutcomePlanningError2) {
9181
+ return { ok: false, code: error.code, message: error.message };
9182
+ }
9183
+ throw error;
9184
+ }
8899
9185
  }
8900
9186
  for (const queuedInput of plan.queuedInputs) {
8901
9187
  const validationError = validateQueuedProcessInput(queuedInput);
@@ -8964,13 +9250,41 @@ async function buildTurnOutcomeWrites(input) {
8964
9250
  );
8965
9251
  }
8966
9252
  const processForEffects = { ...input.process, ...baseWrites.processPatch };
9253
+ const outcomeEvent = createDeferredExtensionEvent(input.process.id, "turn_outcome", {
9254
+ turnRecordId: input.payload.turnRecordId,
9255
+ turnId: input.payload.turnId,
9256
+ outcome: input.payload.outcome,
9257
+ params: input.payload.params ?? {},
9258
+ turnResultMarkdown: input.payload.turnResultMarkdown ?? null
9259
+ });
9260
+ const mappedSpec = turnDefinition?.kind === "llm" ? turnDefinition.forEach : void 0;
9261
+ if (mappedSpec) {
9262
+ const mappedWrites = await buildMappedItemOutcomeWrites({
9263
+ processGraphs: input.processGraphs,
9264
+ registry: input.processActionRegistry,
9265
+ mappedRuns: input.mappedRuns,
9266
+ process: processForEffects,
9267
+ projects: input.projects,
9268
+ payload: input.payload,
9269
+ spec: mappedSpec,
9270
+ iteration: input.iteration,
9271
+ prepared: loadPreparedData(processForEffects, input.payload, input.events)
9272
+ });
9273
+ if (isWriteBuildFailure(mappedWrites)) {
9274
+ return mappedWrites;
9275
+ }
9276
+ const writes2 = mergeWrites(baseWrites, mappedWrites);
9277
+ writes2.extensionEvents.push(outcomeEvent);
9278
+ return writes2;
9279
+ }
8967
9280
  const effectWrites = await buildProcessTurnOutcomeEffectWrites(
8968
9281
  input.processGraphs,
8969
9282
  processForEffects,
8970
9283
  input.projects,
8971
9284
  input.payload,
8972
9285
  input.processActionRegistry,
8973
- input.turnRecords
9286
+ input.turnRecords,
9287
+ input.events
8974
9288
  );
8975
9289
  if (isWriteBuildFailure(effectWrites)) {
8976
9290
  return effectWrites;
@@ -8998,15 +9312,7 @@ async function buildTurnOutcomeWrites(input) {
8998
9312
  candidateProcess = { ...candidateProcess, ...transitionWrites.processPatch };
8999
9313
  }
9000
9314
  }
9001
- writes.extensionEvents.push(
9002
- createDeferredExtensionEvent(input.process.id, "turn_outcome", {
9003
- turnRecordId: input.payload.turnRecordId,
9004
- turnId: input.payload.turnId,
9005
- outcome: input.payload.outcome,
9006
- params: input.payload.params ?? {},
9007
- turnResultMarkdown: input.payload.turnResultMarkdown ?? null
9008
- })
9009
- );
9315
+ writes.extensionEvents.push(outcomeEvent);
9010
9316
  return writes;
9011
9317
  }
9012
9318
 
@@ -9138,10 +9444,8 @@ var TurnOutcome = defineOperation({
9138
9444
  });
9139
9445
  const payload = resolveEffectiveOutcomePayload({ payload: initialPayload, publication });
9140
9446
  const publishedProduct = publication.productName;
9141
- const expected = ctx.process.currentExecution?.kind === "worker_start" ? (() => {
9142
- const state = ctx.deps.turnStarts.getById(ctx.process.currentExecution.id)?.state;
9143
- return state?.kind === "accepted" ? state.turnRecordId : null;
9144
- })() : null;
9447
+ const currentStart = ctx.process.currentExecution?.kind === "worker_start" ? ctx.deps.turnStarts.getById(ctx.process.currentExecution.id) : null;
9448
+ const expected = currentStart?.state.kind === "accepted" ? currentStart.state.turnRecordId : null;
9145
9449
  const correlationError = validateTurnOutcomeCorrelation(ctx.process, payload, expected);
9146
9450
  if (correlationError) {
9147
9451
  return reject(correlationError.code, correlationError.message);
@@ -9300,8 +9604,11 @@ var TurnOutcome = defineOperation({
9300
9604
  projects,
9301
9605
  payload,
9302
9606
  turnRecords: ctx.deps.turnRecords,
9607
+ events: ctx.deps.events,
9303
9608
  processGraphs: ctx.deps.processGraphs,
9304
- processActionRegistry
9609
+ processActionRegistry,
9610
+ mappedRuns: ctx.deps.mappedRuns,
9611
+ iteration: currentStart?.iteration ?? null
9305
9612
  });
9306
9613
  if (isWriteBuildFailure(outcomeWrites)) {
9307
9614
  return reject(outcomeWrites.code, outcomeWrites.message);
@@ -9667,6 +9974,11 @@ function commitWrites(deps, instanceId, writes) {
9667
9974
  return deps.transaction((repos) => {
9668
9975
  const processBefore = repos.processes.getById(instanceId);
9669
9976
  const committedTurnRecords = [];
9977
+ for (const write of writes.mappedRunWrites) {
9978
+ if (write.kind === "create") repos.mappedRuns.create(write.input);
9979
+ else if (write.kind === "complete_item") repos.mappedRuns.completeItem(write.input);
9980
+ else repos.mappedRuns.abortActiveByInstance(instanceId);
9981
+ }
9670
9982
  for (const write of writes.turnStartWrites) {
9671
9983
  if (write.kind === "create") repos.turnStarts.create(write.input);
9672
9984
  else if (!repos.turnStarts.compareAndSetState(write)) {
@@ -9930,6 +10242,17 @@ function buildRecordedDecision(input) {
9930
10242
  };
9931
10243
  }
9932
10244
  async function record2(deps, operation, input, initialProcess, decision) {
10245
+ const mappedPlan = await planMappedTurnEntries({
10246
+ processGraphs: deps.processGraphs,
10247
+ registry: deps.getProcessActionRegistry?.(),
10248
+ mappedRuns: deps.mappedRuns,
10249
+ projects: deps.projects,
10250
+ process: initialProcess,
10251
+ writes: decision.writes
10252
+ });
10253
+ if (!mappedPlan.ok) {
10254
+ return { ok: false, stage: "pre_commit", code: mappedPlan.code, message: mappedPlan.message };
10255
+ }
9933
10256
  const baselineWrites = structuredClone(decision.writes);
9934
10257
  const runModelPreparation = async (availability) => {
9935
10258
  const candidateProcess = {
@@ -10097,27 +10420,27 @@ function resolveMessages(operation, input) {
10097
10420
  function shouldReportBestEffortFailures(operation, input) {
10098
10421
  return typeof operation.reportBestEffortFailures === "function" ? operation.reportBestEffortFailures(input) : operation.reportBestEffortFailures === true;
10099
10422
  }
10100
- function mapPreCommitFailure(failure, initialProcess) {
10423
+ function mapPreCommitFailure(failure2, initialProcess) {
10101
10424
  return {
10102
10425
  ok: false,
10103
- code: failure.code,
10426
+ code: failure2.code,
10104
10427
  message: publicEngineFailureMessage({
10105
- code: failure.code,
10106
- message: failure.message,
10428
+ code: failure2.code,
10429
+ message: failure2.message,
10107
10430
  stage: "pre_commit"
10108
10431
  }),
10109
10432
  ...initialProcess ? { process: initialProcess } : {},
10110
- ...failure.data !== void 0 ? { data: failure.data } : {},
10433
+ ...failure2.data !== void 0 ? { data: failure2.data } : {},
10111
10434
  stage: "pre_commit"
10112
10435
  };
10113
10436
  }
10114
- function mapPostCommitFailure(recorded, failure) {
10437
+ function mapPostCommitFailure(recorded, failure2) {
10115
10438
  return {
10116
10439
  ok: false,
10117
- code: failure.code,
10440
+ code: failure2.code,
10118
10441
  message: publicEngineFailureMessage({
10119
- code: failure.code,
10120
- message: failure.message,
10442
+ code: failure2.code,
10443
+ message: failure2.message,
10121
10444
  stage: "post_commit"
10122
10445
  }),
10123
10446
  process: recorded.process,
@@ -10239,12 +10562,6 @@ function createEngineRunner(deps, options = {}) {
10239
10562
  if (lockedOutcome.kind === "pre_commit_failed") {
10240
10563
  return mapPreCommitFailure(lockedOutcome.failure, lockedOutcome.initialProcess);
10241
10564
  }
10242
- if (lockedOutcome.kind === "post_commit_failed") {
10243
- return mapPostCommitFailure(
10244
- lockedOutcome.recorded,
10245
- lockedOutcome.failure
10246
- );
10247
- }
10248
10565
  const { recorded } = lockedOutcome;
10249
10566
  try {
10250
10567
  operation.afterRecord?.(input, recorded.data);
@@ -10257,6 +10574,12 @@ function createEngineRunner(deps, options = {}) {
10257
10574
  code: "after_record_callback_failed"
10258
10575
  });
10259
10576
  }
10577
+ if (lockedOutcome.kind === "post_commit_failed") {
10578
+ return mapPostCommitFailure(
10579
+ lockedOutcome.recorded,
10580
+ lockedOutcome.failure
10581
+ );
10582
+ }
10260
10583
  try {
10261
10584
  await deps.afterRecord?.(recorded.process);
10262
10585
  const dispatchResult = await dispatchReactions(
@@ -10363,8 +10686,8 @@ function createProcessEngine(deps) {
10363
10686
  activateDeferredProcess(instanceId, prepared) {
10364
10687
  return run(ActivateDeferredProcess, { instanceId, prepared });
10365
10688
  },
10366
- parkDeferredProcessActivationFailure(instanceId, failure) {
10367
- return run(ParkDeferredProcessActivationFailure, { instanceId, failure });
10689
+ parkDeferredProcessActivationFailure(instanceId, failure2) {
10690
+ return run(ParkDeferredProcessActivationFailure, { instanceId, failure: failure2 });
10368
10691
  },
10369
10692
  startProcess(instanceId, startTurnId, opts) {
10370
10693
  return run(StartProcess, { instanceId, startTurnId, actor: opts?.actor });
@@ -10406,8 +10729,8 @@ function createProcessEngine(deps) {
10406
10729
  const result = await run(WorkerFailure, { instanceId, payload });
10407
10730
  return maybeBroadcastErrorAttentionToast2(result, { errorCode: payload.errorCode });
10408
10731
  },
10409
- acceptWorkerTurnStart(instanceId, input) {
10410
- return run(AcceptWorkerTurnStart, { instanceId, ...input });
10732
+ acceptWorkerTurnStart(instanceId, input, options) {
10733
+ return run(AcceptWorkerTurnStart, { instanceId, ...input, onRecorded: options?.onRecorded });
10411
10734
  },
10412
10735
  async recordTurnOutcome(instanceId, payload, options) {
10413
10736
  return maybeBroadcastActionRequiredToast2(
@@ -13469,8 +13792,8 @@ function mapEngineFailure(result, variant) {
13469
13792
  };
13470
13793
  }
13471
13794
  function sendEngineFailure(reply, result, variant) {
13472
- const failure = mapEngineFailure(result, variant);
13473
- return reply.code(failure.status).send(failure.body);
13795
+ const failure2 = mapEngineFailure(result, variant);
13796
+ return reply.code(failure2.status).send(failure2.body);
13474
13797
  }
13475
13798
 
13476
13799
  // src/routes/process-actions.ts
@@ -13941,7 +14264,6 @@ var ProcessDiagnosticsAssembler = class {
13941
14264
  return null;
13942
14265
  }
13943
14266
  const projects = this.deps.projects.listByInstance(instanceId);
13944
- const piSessionTree = await this.deps.sessionReader.readPiSessionTree(instanceId);
13945
14267
  const recentEvents = this.deps.events.listByInstance(instanceId, 500);
13946
14268
  const retainedOperationalEvents = this.deps.events.listByInstanceEventTypes(
13947
14269
  instanceId,
@@ -13956,7 +14278,7 @@ var ProcessDiagnosticsAssembler = class {
13956
14278
  availability: this.deps.modelStatusCache.snapshot()
13957
14279
  })
13958
14280
  );
13959
- return {
14281
+ const detail = {
13960
14282
  process: process2,
13961
14283
  projects,
13962
14284
  inputs: this.deps.inputs.listByInstance(instanceId),
@@ -13968,7 +14290,6 @@ var ProcessDiagnosticsAssembler = class {
13968
14290
  processDisplayName: getProcessDisplayName(this.deps, process2.processId),
13969
14291
  processGraph: serializeProcessGraph(this.deps.processGraphs, process2.processId),
13970
14292
  processFlow: buildProcessFlowViewForProcess(this.deps.processGraphs, process2.processId),
13971
- piSessionEntries: piSessionTree.entries,
13972
14293
  definesLeafOutcome: processDefinesLeafOutcome(this.deps, process2),
13973
14294
  selectedTurn: getSelectedTurnSummaryForProcess(this.deps, process2),
13974
14295
  scheduledAction: getScheduledActionDetailForProcess(this.deps, process2),
@@ -13978,6 +14299,8 @@ var ProcessDiagnosticsAssembler = class {
13978
14299
  actions: listVisibleActionsForProcess2(this.deps, process2),
13979
14300
  toolRenderers: [...this.deps.toolRenderers?.values() ?? []]
13980
14301
  };
14302
+ const piSessionTree = await this.deps.sessionReader.readPiSessionTree(instanceId);
14303
+ return { ...detail, piSessionEntries: piSessionTree.entries };
13981
14304
  }
13982
14305
  async assembleRetryConfig(instanceId) {
13983
14306
  const process2 = this.deps.processes.getById(instanceId);
@@ -14025,12 +14348,12 @@ var ProcessPrimaryPathAssembler = class {
14025
14348
  this.deps = deps;
14026
14349
  }
14027
14350
  deps;
14028
- capture(instanceId, overrides = {}) {
14029
- const process2 = overrides.process ?? this.deps.processes.getById(instanceId);
14351
+ capture(instanceId) {
14352
+ const process2 = this.deps.processes.getById(instanceId);
14030
14353
  if (!process2) {
14031
14354
  return null;
14032
14355
  }
14033
- const turnRecords = overrides.turnRecords ?? this.deps.turnRecords.listByInstance(process2.id);
14356
+ const turnRecords = this.deps.turnRecords.listByInstance(process2.id);
14034
14357
  const currentTurnRecordId = resolveCurrentExecutionTurnRecordId(process2, this.deps.turnStarts);
14035
14358
  const activeTurnRecord = currentTurnRecordId ? turnRecords.find(
14036
14359
  (turnRecord) => turnRecord.id === currentTurnRecordId && turnRecord.status === "running"
@@ -14053,26 +14376,20 @@ var ProcessPrimaryPathAssembler = class {
14053
14376
  return {
14054
14377
  process: process2,
14055
14378
  currentExecutionTurnRecordId: currentTurnRecordId,
14056
- workerLease: overrides.workerLease !== void 0 ? overrides.workerLease : this.deps.leases.getByInstance(process2.id),
14379
+ workerLease: this.deps.leases.getByInstance(process2.id),
14057
14380
  turnRecords,
14058
- turnAnnotations: overrides.turnAnnotations ?? this.deps.turnAnnotations.listByInstance(process2.id),
14381
+ turnAnnotations: this.deps.turnAnnotations.listByInstance(process2.id),
14059
14382
  events,
14060
14383
  eventWindowTruncated
14061
14384
  };
14062
14385
  }
14063
- project(captured, session) {
14064
- return buildPrimaryPathSnapshotFromTree({
14065
- ...captured,
14066
- tree: session.parsedTree
14067
- });
14068
- }
14069
14386
  async assemble(instanceId) {
14070
14387
  const captured = this.capture(instanceId);
14071
14388
  if (!captured) {
14072
14389
  return null;
14073
14390
  }
14074
14391
  const session = await this.deps.sessionReader.readSessionTree(instanceId);
14075
- return this.project(captured, session);
14392
+ return buildPrimaryPathSnapshotFromTree({ ...captured, tree: session.parsedTree });
14076
14393
  }
14077
14394
  };
14078
14395
 
@@ -15824,6 +16141,7 @@ function createWorkerTurnIpcRecorder(deps, callbacks) {
15824
16141
  return;
15825
16142
  }
15826
16143
  const fallback = await deps.commands.recordWorkerFailure(input.instanceId, {
16144
+ workerLeaseId: input.workerLeaseId,
15827
16145
  errorCode: details.code,
15828
16146
  message: `Server could not durably record worker turn ${input.terminalType}: ${details.message}`,
15829
16147
  errorClass: "infrastructure",
@@ -15867,7 +16185,7 @@ function createWorkerTurnIpcRecorder(deps, callbacks) {
15867
16185
  }
15868
16186
  };
15869
16187
  return {
15870
- recordTurnOutcome(instanceId, workerId, payload) {
16188
+ recordTurnOutcome(instanceId, workerId, workerLeaseId, payload) {
15871
16189
  const { turnId, ...rest } = payload;
15872
16190
  if (terminalWasAlreadyRecorded(deps, rest.turnRecordId, "outcome")) {
15873
16191
  acknowledge(instanceId, workerId, rest.turnRecordId);
@@ -15879,6 +16197,7 @@ function createWorkerTurnIpcRecorder(deps, callbacks) {
15879
16197
  void recordTerminal({
15880
16198
  instanceId,
15881
16199
  workerId,
16200
+ workerLeaseId,
15882
16201
  turnRecordId: rest.turnRecordId,
15883
16202
  terminalType: "outcome",
15884
16203
  record: () => deps.commands.recordTurnOutcome(
@@ -15896,12 +16215,13 @@ function createWorkerTurnIpcRecorder(deps, callbacks) {
15896
16215
  recoveryContext: createGenericFailedTurnRecoveryContext()
15897
16216
  });
15898
16217
  },
15899
- recordTurnFailed(instanceId, workerId, payload) {
16218
+ recordTurnFailed(instanceId, workerId, workerLeaseId, payload) {
15900
16219
  const { errorClass, failureCode, failureDetails: details, ...rest } = payload;
15901
16220
  if (errorClass !== void 0 && !isWorkerErrorClass(errorClass)) {
15902
16221
  void recoverRecordingFailure({
15903
16222
  instanceId,
15904
16223
  workerId,
16224
+ workerLeaseId,
15905
16225
  turnRecordId: rest.turnRecordId,
15906
16226
  terminalType: "failure",
15907
16227
  failure: new Error(`Invalid worker error class '${errorClass}'`)
@@ -15919,6 +16239,7 @@ function createWorkerTurnIpcRecorder(deps, callbacks) {
15919
16239
  void recordTerminal({
15920
16240
  instanceId,
15921
16241
  workerId,
16242
+ workerLeaseId,
15922
16243
  turnRecordId: rest.turnRecordId,
15923
16244
  terminalType: "failure",
15924
16245
  record: () => deps.commands.recordTurnFailed(
@@ -16106,32 +16427,41 @@ function createIpcHandler(deps, callbacks) {
16106
16427
  break;
16107
16428
  }
16108
16429
  case "worker.turn_started": {
16109
- void deps.commands.acceptWorkerTurnStart(instanceId, {
16110
- workerLeaseId: activeLease.id,
16111
- startRecordId: msg.payload.startRecordId,
16112
- proposedTurnRecordId: msg.payload.proposedTurnRecordId
16113
- }).then((result) => {
16114
- if (!result.ok || !result.data) {
16430
+ let accepted = false;
16431
+ const onRecorded = (turnRecordId) => {
16432
+ accepted = true;
16433
+ eventIngestor.noteTurnStarted(instanceId, turnRecordId);
16434
+ callbacks.onWorkerTurnStartAccepted?.(instanceId, workerId, {
16435
+ startRecordId: msg.payload.startRecordId,
16436
+ turnRecordId
16437
+ });
16438
+ };
16439
+ void deps.commands.acceptWorkerTurnStart(
16440
+ instanceId,
16441
+ {
16442
+ workerLeaseId: activeLease.id,
16443
+ startRecordId: msg.payload.startRecordId,
16444
+ proposedTurnRecordId: msg.payload.proposedTurnRecordId
16445
+ },
16446
+ { onRecorded }
16447
+ ).then(() => {
16448
+ if (!accepted) {
16115
16449
  callbacks.onWorkerFailed?.(instanceId, workerId, "Worker turn start was rejected");
16116
16450
  return;
16117
16451
  }
16118
- eventIngestor.noteTurnStarted(instanceId, result.data.turnRecordId);
16119
16452
  launchCoordinator?.refresh(instanceId);
16120
- callbacks.onWorkerTurnStartAccepted?.(instanceId, workerId, {
16121
- startRecordId: msg.payload.startRecordId,
16122
- turnRecordId: result.data.turnRecordId
16123
- });
16124
- }).catch(
16125
- () => callbacks.onWorkerFailed?.(instanceId, workerId, "Worker turn start failed")
16126
- );
16453
+ }).catch(() => {
16454
+ if (!accepted)
16455
+ callbacks.onWorkerFailed?.(instanceId, workerId, "Worker turn start failed");
16456
+ });
16127
16457
  break;
16128
16458
  }
16129
16459
  case "worker.turn_outcome": {
16130
- turnRecorder.recordTurnOutcome(instanceId, workerId, msg.payload);
16460
+ turnRecorder.recordTurnOutcome(instanceId, workerId, activeLease.id, msg.payload);
16131
16461
  break;
16132
16462
  }
16133
16463
  case "worker.turn_failed": {
16134
- turnRecorder.recordTurnFailed(instanceId, workerId, msg.payload);
16464
+ turnRecorder.recordTurnFailed(instanceId, workerId, activeLease.id, msg.payload);
16135
16465
  break;
16136
16466
  }
16137
16467
  case "worker.lifecycle_parked": {
@@ -16898,6 +17228,22 @@ function buildTurnResultMarkdownByProduct(process2, deps) {
16898
17228
  }
16899
17229
  return Object.keys(byProduct).length > 0 ? byProduct : void 0;
16900
17230
  }
17231
+ function resolveMappedItem(start, deps) {
17232
+ if (!start.iteration) return void 0;
17233
+ const run = deps.mappedRuns?.getById(start.iteration.runId);
17234
+ const item = deps.mappedRuns?.getItem(start.iteration.runId, start.iteration.itemIndex);
17235
+ if (!run || !item || item.itemKey !== start.iteration.itemKey) {
17236
+ throw new Error(`Mapped item for worker start '${start.id}' is unavailable`);
17237
+ }
17238
+ return {
17239
+ runId: run.id,
17240
+ itemKey: item.itemKey,
17241
+ itemLabel: item.label,
17242
+ itemIndex: item.itemIndex,
17243
+ itemCount: run.itemCount,
17244
+ item: JSON.parse(item.itemJson)
17245
+ };
17246
+ }
16901
17247
  function resolveLlmPreparation(start, deps) {
16902
17248
  const sourceTurnRecordId = start.state.kind === "accepted" ? start.state.turnRecordId : start.startKind === "continue" ? start.recoveryTurnRecordId : null;
16903
17249
  if (!sourceTurnRecordId) return void 0;
@@ -16968,6 +17314,7 @@ function createWorkerStartPayloadBuilder(deps) {
16968
17314
  const llmPreparation = start.turnType === "llm" ? resolveLlmPreparation(start, deps) : void 0;
16969
17315
  const resumeLeafEntryId = treePaths.resume ? deps.turnRecords.getLatestSucceededPrimaryByInstance(instanceId)?.resultPiEntryId ?? null : null;
16970
17316
  const contextSnapshot = buildWorkerRuntimeContextSnapshot(process2, start);
17317
+ const iteration = resolveMappedItem(start, deps);
16971
17318
  const repositoryCredentials = deps.resolveRepositoryCredentials?.({
16972
17319
  process: process2,
16973
17320
  projects: deps.projects.listByInstance(process2.id)
@@ -17016,7 +17363,8 @@ function createWorkerStartPayloadBuilder(deps) {
17016
17363
  ...llmPreparation ? { llmPreparation } : {},
17017
17364
  ...repositoryCredentials.length > 0 ? { repositoryCredentials } : {},
17018
17365
  ...dockerRegistryCredentials.length > 0 ? { dockerRegistryCredentials } : {},
17019
- ...integrationTools && integrationTools.length > 0 ? { integrationTools } : {}
17366
+ ...integrationTools && integrationTools.length > 0 ? { integrationTools } : {},
17367
+ ...iteration ? { iteration } : {}
17020
17368
  };
17021
17369
  const payload = bootstrap.kind === "llm" ? {
17022
17370
  ...payloadBase,
@@ -18644,6 +18992,7 @@ ${configErrors.join("\n")}`);
18644
18992
  turnStarts: baseDeps.turnStarts,
18645
18993
  leases: baseDeps.leases,
18646
18994
  turnAnnotations: baseDeps.turnAnnotations,
18995
+ mappedRuns: baseDeps.mappedRuns,
18647
18996
  transaction: baseDeps.transaction,
18648
18997
  broadcaster,
18649
18998
  config,
@@ -18826,6 +19175,7 @@ ${configErrors.join("\n")}`);
18826
19175
  inputs: baseDeps.inputs,
18827
19176
  turnRecords: baseDeps.turnRecords,
18828
19177
  turnStarts: baseDeps.turnStarts,
19178
+ mappedRuns: baseDeps.mappedRuns,
18829
19179
  events: baseDeps.events,
18830
19180
  broadcaster,
18831
19181
  runnerRuntime,
@@ -19227,4 +19577,4 @@ ${configErrors.join("\n")}`);
19227
19577
  export {
19228
19578
  createAppContext
19229
19579
  };
19230
- //# sourceMappingURL=chunk-LK3RO6C7.js.map
19580
+ //# sourceMappingURL=chunk-QCHS3X33.js.map