@leitwerk-dev/server 0.1.8 → 0.1.9

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 (187) hide show
  1. package/dist/app.d.ts.map +1 -1
  2. package/dist/app.js +22 -6
  3. package/dist/app.js.map +1 -1
  4. package/dist/{chunk-ES5RBLAT.js → chunk-2ESDXLNE.js} +199 -95
  5. package/dist/chunk-2ESDXLNE.js.map +1 -0
  6. package/dist/{chunk-UC3OOEQ3.js → chunk-DFHOPJRZ.js} +393 -249
  7. package/dist/chunk-DFHOPJRZ.js.map +1 -0
  8. package/dist/config/config-loader.d.ts.map +1 -1
  9. package/dist/config/config-loader.js +6 -24
  10. package/dist/config/config-loader.js.map +1 -1
  11. package/dist/config/config-types.d.ts +0 -17
  12. package/dist/config/config-types.d.ts.map +1 -1
  13. package/dist/db/skill-repo.d.ts +2 -2
  14. package/dist/db/skill-repo.d.ts.map +1 -1
  15. package/dist/db/skill-repo.js +24 -32
  16. package/dist/db/skill-repo.js.map +1 -1
  17. package/dist/external-source-service.d.ts.map +1 -1
  18. package/dist/external-source-service.js +5 -2
  19. package/dist/external-source-service.js.map +1 -1
  20. package/dist/future-execution/execution.d.ts +1 -1
  21. package/dist/future-execution/execution.d.ts.map +1 -1
  22. package/dist/future-execution/execution.js +1 -13
  23. package/dist/future-execution/execution.js.map +1 -1
  24. package/dist/integration-tool-registry.js +1 -1
  25. package/dist/integration-tool-registry.js.map +1 -1
  26. package/dist/process-action-registry.d.ts +2 -4
  27. package/dist/process-action-registry.d.ts.map +1 -1
  28. package/dist/process-action-registry.js +31 -28
  29. package/dist/process-action-registry.js.map +1 -1
  30. package/dist/process-engine/engine.d.ts.map +1 -1
  31. package/dist/process-engine/engine.js +4 -4
  32. package/dist/process-engine/engine.js.map +1 -1
  33. package/dist/process-engine/operation.d.ts +4 -0
  34. package/dist/process-engine/operation.d.ts.map +1 -1
  35. package/dist/process-engine/ops/execute-action.d.ts.map +1 -1
  36. package/dist/process-engine/ops/execute-action.js +0 -3
  37. package/dist/process-engine/ops/execute-action.js.map +1 -1
  38. package/dist/process-engine/ops/worker-failure.d.ts +2 -0
  39. package/dist/process-engine/ops/worker-failure.d.ts.map +1 -1
  40. package/dist/process-engine/ops/worker-failure.js +2 -0
  41. package/dist/process-engine/ops/worker-failure.js.map +1 -1
  42. package/dist/process-engine/runner.d.ts +2 -2
  43. package/dist/process-engine/runner.d.ts.map +1 -1
  44. package/dist/process-engine/runner.js +13 -1
  45. package/dist/process-engine/runner.js.map +1 -1
  46. package/dist/process-engine/types.d.ts +10 -4
  47. package/dist/process-engine/types.d.ts.map +1 -1
  48. package/dist/process-engine/writes/build-server-transition-writes.d.ts.map +1 -1
  49. package/dist/process-engine/writes/build-server-transition-writes.js +2 -8
  50. package/dist/process-engine/writes/build-server-transition-writes.js.map +1 -1
  51. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts.map +1 -1
  52. package/dist/process-engine/writes/build-turn-outcome-writes.js +1 -2
  53. package/dist/process-engine/writes/build-turn-outcome-writes.js.map +1 -1
  54. package/dist/process-engine/writes/build-turn-selection-writes.d.ts +1 -2
  55. package/dist/process-engine/writes/build-turn-selection-writes.d.ts.map +1 -1
  56. package/dist/process-engine/writes/build-turn-selection-writes.js +1 -57
  57. package/dist/process-engine/writes/build-turn-selection-writes.js.map +1 -1
  58. package/dist/process-engine/writes/build-worker-failure-writes.d.ts +3 -1
  59. package/dist/process-engine/writes/build-worker-failure-writes.d.ts.map +1 -1
  60. package/dist/process-engine/writes/build-worker-failure-writes.js +2 -1
  61. package/dist/process-engine/writes/build-worker-failure-writes.js.map +1 -1
  62. package/dist/process-launch-executor.d.ts +6 -4
  63. package/dist/process-launch-executor.d.ts.map +1 -1
  64. package/dist/process-launch-executor.js +16 -1
  65. package/dist/process-launch-executor.js.map +1 -1
  66. package/dist/process-launch-plan.d.ts.map +1 -1
  67. package/dist/process-launch-plan.js +1 -0
  68. package/dist/process-launch-plan.js.map +1 -1
  69. package/dist/process-operator-attention.d.ts +1 -1
  70. package/dist/process-operator-attention.d.ts.map +1 -1
  71. package/dist/process-operator-attention.js +1 -1
  72. package/dist/process-operator-attention.js.map +1 -1
  73. package/dist/process-ui-snapshot-presenter.d.ts.map +1 -1
  74. package/dist/process-ui-snapshot-presenter.js +24 -3
  75. package/dist/process-ui-snapshot-presenter.js.map +1 -1
  76. package/dist/process-watcher-registry.d.ts.map +1 -1
  77. package/dist/process-watcher-registry.js +13 -5
  78. package/dist/process-watcher-registry.js.map +1 -1
  79. package/dist/routes/skills.d.ts.map +1 -1
  80. package/dist/routes/skills.js +1 -2
  81. package/dist/routes/skills.js.map +1 -1
  82. package/dist/server-automatic-turn-drainer.d.ts.map +1 -1
  83. package/dist/server-automatic-turn-drainer.js +15 -0
  84. package/dist/server-automatic-turn-drainer.js.map +1 -1
  85. package/dist/server-bootstrap/build-host-capabilities.d.ts.map +1 -1
  86. package/dist/server-bootstrap/build-host-capabilities.js +1 -0
  87. package/dist/server-bootstrap/build-host-capabilities.js.map +1 -1
  88. package/dist/skills/skill-frontmatter.d.ts +4 -0
  89. package/dist/skills/skill-frontmatter.d.ts.map +1 -0
  90. package/dist/skills/skill-frontmatter.js +13 -0
  91. package/dist/skills/skill-frontmatter.js.map +1 -0
  92. package/dist/skills/source-importer.d.ts +2 -3
  93. package/dist/skills/source-importer.d.ts.map +1 -1
  94. package/dist/skills/source-importer.js +16 -62
  95. package/dist/skills/source-importer.js.map +1 -1
  96. package/dist/supervisor/accepted-turn-start-replay.d.ts +9 -0
  97. package/dist/supervisor/accepted-turn-start-replay.d.ts.map +1 -0
  98. package/dist/supervisor/accepted-turn-start-replay.js +23 -0
  99. package/dist/supervisor/accepted-turn-start-replay.js.map +1 -0
  100. package/dist/supervisor/ipc-handler.d.ts +9 -0
  101. package/dist/supervisor/ipc-handler.d.ts.map +1 -1
  102. package/dist/supervisor/ipc-handler.js +9 -4
  103. package/dist/supervisor/ipc-handler.js.map +1 -1
  104. package/dist/supervisor/stale-heartbeat-watchdog.d.ts +1 -1
  105. package/dist/supervisor/stale-heartbeat-watchdog.d.ts.map +1 -1
  106. package/dist/supervisor/stale-heartbeat-watchdog.js +47 -5
  107. package/dist/supervisor/stale-heartbeat-watchdog.js.map +1 -1
  108. package/dist/supervisor/worker-event-ingestor.d.ts.map +1 -1
  109. package/dist/supervisor/worker-event-ingestor.js +16 -0
  110. package/dist/supervisor/worker-event-ingestor.js.map +1 -1
  111. package/dist/supervisor/worker-start-payload-builder.d.ts.map +1 -1
  112. package/dist/supervisor/worker-start-payload-builder.js +3 -1
  113. package/dist/supervisor/worker-start-payload-builder.js.map +1 -1
  114. package/dist/supervisor/worker-supervisor.d.ts +3 -1
  115. package/dist/supervisor/worker-supervisor.d.ts.map +1 -1
  116. package/dist/supervisor/worker-supervisor.js +31 -0
  117. package/dist/supervisor/worker-supervisor.js.map +1 -1
  118. package/dist/supervisor/worker-turn-ipc-recorder.d.ts +12 -3
  119. package/dist/supervisor/worker-turn-ipc-recorder.d.ts.map +1 -1
  120. package/dist/supervisor/worker-turn-ipc-recorder.js +129 -33
  121. package/dist/supervisor/worker-turn-ipc-recorder.js.map +1 -1
  122. package/dist/supervisor/worker-websocket-ipc.d.ts.map +1 -1
  123. package/dist/supervisor/worker-websocket-ipc.js +20 -10
  124. package/dist/supervisor/worker-websocket-ipc.js.map +1 -1
  125. package/dist/test-helpers/fake-worker-supervisor.d.ts.map +1 -1
  126. package/dist/test-helpers/fake-worker-supervisor.js +4 -0
  127. package/dist/test-helpers/fake-worker-supervisor.js.map +1 -1
  128. package/dist/test-helpers/ipc-handler-harness.d.ts.map +1 -1
  129. package/dist/test-helpers/ipc-handler-harness.js +1 -20
  130. package/dist/test-helpers/ipc-handler-harness.js.map +1 -1
  131. package/dist/test-helpers/process-fixtures.d.ts +1 -1
  132. package/dist/test-helpers/process-fixtures.d.ts.map +1 -1
  133. package/dist/test-helpers/process-fixtures.js +0 -6
  134. package/dist/test-helpers/process-fixtures.js.map +1 -1
  135. package/dist/turn-progress.d.ts +12 -0
  136. package/dist/turn-progress.d.ts.map +1 -0
  137. package/dist/turn-progress.js +108 -0
  138. package/dist/turn-progress.js.map +1 -0
  139. package/dist/{writes-CVXLCYce.d.ts → writes-DNXpryd0.d.ts} +29 -27
  140. package/package.json +10 -10
  141. package/src/app.ts +22 -6
  142. package/src/config/config-loader.ts +9 -24
  143. package/src/config/config-types.ts +0 -13
  144. package/src/db/skill-repo.ts +26 -36
  145. package/src/external-source-service.ts +5 -2
  146. package/src/future-execution/execution.ts +2 -13
  147. package/src/integration-tool-registry.ts +1 -1
  148. package/src/process-action-registry.ts +48 -40
  149. package/src/process-engine/engine.ts +6 -4
  150. package/src/process-engine/operation.ts +5 -0
  151. package/src/process-engine/ops/execute-action.ts +0 -3
  152. package/src/process-engine/ops/worker-failure.ts +4 -0
  153. package/src/process-engine/runner.ts +13 -0
  154. package/src/process-engine/types.ts +14 -2
  155. package/src/process-engine/writes/build-server-transition-writes.ts +1 -14
  156. package/src/process-engine/writes/build-turn-outcome-writes.ts +1 -2
  157. package/src/process-engine/writes/build-turn-selection-writes.ts +0 -75
  158. package/src/process-engine/writes/build-worker-failure-writes.ts +4 -1
  159. package/src/process-launch-executor.ts +24 -15
  160. package/src/process-launch-plan.ts +1 -0
  161. package/src/process-operator-attention.ts +7 -3
  162. package/src/process-ui-snapshot-presenter.ts +24 -6
  163. package/src/process-watcher-registry.ts +15 -5
  164. package/src/routes/skills.ts +1 -3
  165. package/src/server-automatic-turn-drainer.ts +20 -1
  166. package/src/server-bootstrap/build-host-capabilities.ts +1 -0
  167. package/src/skills/skill-frontmatter.ts +13 -0
  168. package/src/skills/source-importer.ts +20 -82
  169. package/src/supervisor/accepted-turn-start-replay.ts +40 -0
  170. package/src/supervisor/ipc-handler.ts +18 -4
  171. package/src/supervisor/stale-heartbeat-watchdog.ts +55 -6
  172. package/src/supervisor/worker-event-ingestor.ts +15 -0
  173. package/src/supervisor/worker-start-payload-builder.ts +3 -1
  174. package/src/supervisor/worker-supervisor.ts +42 -0
  175. package/src/supervisor/worker-turn-ipc-recorder.ts +185 -46
  176. package/src/supervisor/worker-websocket-ipc.ts +28 -13
  177. package/src/test-helpers/fake-worker-supervisor.ts +4 -0
  178. package/src/test-helpers/ipc-handler-harness.ts +1 -22
  179. package/src/test-helpers/process-fixtures.ts +1 -6
  180. package/src/turn-progress.ts +114 -0
  181. package/dist/chunk-ES5RBLAT.js.map +0 -1
  182. package/dist/chunk-UC3OOEQ3.js.map +0 -1
  183. package/dist/skills/catalog-sync.d.ts +0 -9
  184. package/dist/skills/catalog-sync.d.ts.map +0 -1
  185. package/dist/skills/catalog-sync.js +0 -7
  186. package/dist/skills/catalog-sync.js.map +0 -1
  187. package/src/skills/catalog-sync.ts +0 -13
@@ -58,6 +58,7 @@ import {
58
58
  processDefinesLeafOutcome,
59
59
  publicEngineFailureMessage,
60
60
  publicInternalEngineFailureMessage,
61
+ recordTurnProgress,
61
62
  requireApiActor,
62
63
  resolveActor,
63
64
  resolveCommitMessageMetadata,
@@ -68,10 +69,11 @@ import {
68
69
  sendLauncherRequestNormalizationError,
69
70
  sendScheduledActionMutationResponse,
70
71
  serializeProcessGraph,
72
+ skillFrontmatter,
71
73
  snapshotLiveTurnProjection,
72
74
  truncateTextAtWordBoundary,
73
75
  validateConfig
74
- } from "./chunk-ES5RBLAT.js";
76
+ } from "./chunk-2ESDXLNE.js";
75
77
 
76
78
  // src/extension-ui/catalog.ts
77
79
  import { readFile, stat } from "fs/promises";
@@ -432,7 +434,6 @@ function createExtensionHost() {
432
434
 
433
435
  // src/process-engine/writes/build-turn-selection-writes.ts
434
436
  import {
435
- isWaitingTurnType,
436
437
  lifecycleStatusForSelectedTurnType
437
438
  } from "@leitwerk-dev/domain";
438
439
 
@@ -726,55 +727,6 @@ function validateTurnSelectionWorkerIntent(processGraphs, process2, targetTurnId
726
727
  }
727
728
  return null;
728
729
  }
729
- function parseReviewSubjectFromState(value) {
730
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
731
- return null;
732
- }
733
- const reviewSubject = value.reviewSubject;
734
- if (typeof reviewSubject !== "object" || reviewSubject === null || Array.isArray(reviewSubject)) {
735
- return null;
736
- }
737
- const kind = reviewSubject.kind;
738
- return typeof kind === "string" ? { kind } : null;
739
- }
740
- function parseReviewSubjectFromStateJson(stateJson) {
741
- if (!stateJson) {
742
- return null;
743
- }
744
- try {
745
- return parseReviewSubjectFromState(JSON.parse(stateJson));
746
- } catch {
747
- return null;
748
- }
749
- }
750
- function validateReviewSubjectTurnInvariant(processGraphs, process2, targetTurnId, nextState = void 0) {
751
- if (!targetTurnId) {
752
- return null;
753
- }
754
- const targetTurn = getProcessTurnGraph(processGraphs, process2.processId, targetTurnId);
755
- if (!targetTurn?.reviewSubject) {
756
- return null;
757
- }
758
- const reviewSubject = nextState === void 0 ? parseReviewSubjectFromStateJson(process2.stateJson) : parseReviewSubjectFromState(nextState);
759
- if (isWaitingTurnType(targetTurn.turnType)) {
760
- if (reviewSubject?.kind === targetTurn.reviewSubject.kind) {
761
- return null;
762
- }
763
- return {
764
- ok: false,
765
- code: "invalid_transition",
766
- message: `Transition into '${targetTurnId}' requires reviewSubject.kind '${targetTurn.reviewSubject.kind}'`
767
- };
768
- }
769
- if (reviewSubject) {
770
- return null;
771
- }
772
- return {
773
- ok: false,
774
- code: "invalid_transition",
775
- message: `Transition into '${targetTurnId}' requires a non-null reviewSubject`
776
- };
777
- }
778
730
  function deriveLifecycleStatusForSelectedTurn(processGraphs, processId, turnId) {
779
731
  const turn = getProcessTurnGraph(processGraphs, processId, turnId);
780
732
  return turn ? lifecycleStatusForSelectedTurnType(turn.turnType) : "active";
@@ -823,15 +775,6 @@ function buildTurnSelectionWrites(processGraphs, process2, input) {
823
775
  };
824
776
  }
825
777
  }
826
- const reviewSubjectValidation = validateReviewSubjectTurnInvariant(
827
- processGraphs,
828
- process2,
829
- input.toTurnId,
830
- input.state
831
- );
832
- if (reviewSubjectValidation) {
833
- return reviewSubjectValidation;
834
- }
835
778
  const writes = createWrites({ workerIntent: input.workerIntent ?? { kind: "reconcile" } });
836
779
  applyProcessPatchField(writes, process2, "selectedTurnId", input.toTurnId);
837
780
  applyProcessPatchField(writes, process2, "lifecycleStatus", targetLifecycleStatus);
@@ -3226,17 +3169,6 @@ function buildServerTransitionWrites(processGraphs, process2, request) {
3226
3169
  const turnChanged = targetTurnId !== void 0 && targetTurnId !== process2.selectedTurnId;
3227
3170
  const effectiveTargetTurnId = targetTurnId === void 0 ? process2.selectedTurnId : targetTurnId;
3228
3171
  const effectiveTargetLifecycleStatus = targetTurnId === void 0 ? request.lifecycleStatus ?? process2.lifecycleStatus : targetLifecycleStatus;
3229
- if (effectiveTargetTurnId !== void 0) {
3230
- const reviewSubjectValidation = validateReviewSubjectTurnInvariant(
3231
- processGraphs,
3232
- process2,
3233
- effectiveTargetTurnId,
3234
- request.state
3235
- );
3236
- if (reviewSubjectValidation) {
3237
- return reviewSubjectValidation;
3238
- }
3239
- }
3240
3172
  const resolvedWorkerIntent = resolveRuntimeWorkerIntent(
3241
3173
  processGraphs,
3242
3174
  process2,
@@ -3248,7 +3180,7 @@ function buildServerTransitionWrites(processGraphs, process2, request) {
3248
3180
  if (resolvedWorkerIntent && "ok" in resolvedWorkerIntent) {
3249
3181
  return resolvedWorkerIntent;
3250
3182
  }
3251
- if (targetTurnId !== void 0 && turnChanged) {
3183
+ if (targetTurnId !== void 0) {
3252
3184
  const selectionWrites = buildTurnSelectionWrites(processGraphs, process2, {
3253
3185
  fromTurnId: process2.selectedTurnId,
3254
3186
  toTurnId: targetTurnId,
@@ -3445,7 +3377,7 @@ async function buildTurnOutcomeWrites(input) {
3445
3377
  }
3446
3378
  let writes = mergeWrites(baseWrites, effectWrites);
3447
3379
  let candidateProcess2 = { ...input.process, ...writes.processPatch };
3448
- if (candidateProcess2.selectedTurnId === input.payload.turnId && candidateProcess2.lifecycleStatus !== "completed" && candidateProcess2.lifecycleStatus !== "aborted" && !hasExplicitTurnSelectionChange(input.process, effectWrites)) {
3380
+ if (candidateProcess2.selectedTurnId === input.payload.turnId && candidateProcess2.lifecycleStatus === "active" && !hasExplicitTurnSelectionChange(input.process, effectWrites)) {
3449
3381
  const outcomeTransition = findOutcomeTransition(
3450
3382
  input.processGraphs,
3451
3383
  candidateProcess2.processId,
@@ -3520,6 +3452,9 @@ function maybeBroadcastErrorAttentionToast(deps, result, input = {}) {
3520
3452
  }
3521
3453
 
3522
3454
  // src/server-automatic-turn-drainer.ts
3455
+ import {
3456
+ failActiveTurnProgress
3457
+ } from "@leitwerk-dev/domain";
3523
3458
  import { isServerAutomaticTurnDefinition as isServerAutomaticTurnDefinition2 } from "@leitwerk-dev/process-sdk";
3524
3459
  function toErrorMessage(error) {
3525
3460
  if (error instanceof Error && error.message.trim() !== "") {
@@ -3647,6 +3582,7 @@ function createServerAutomaticTurnDrainer(deps, getService) {
3647
3582
  }
3648
3583
  const current = deps.processes.getById(instanceId) ?? process2;
3649
3584
  const { params, state } = deps.getProcessActionRegistry?.()?.resolveContextData(current.processId, current) ?? { params: {}, state: {} };
3585
+ let latestProgressReport = null;
3650
3586
  try {
3651
3587
  const result = await turnDef.run({
3652
3588
  process: current,
@@ -3658,6 +3594,10 @@ function createServerAutomaticTurnDrainer(deps, getService) {
3658
3594
  },
3659
3595
  readProductTurnResultMarkdown(productName) {
3660
3596
  return resolveProductMarkdownForServerAutomatic(deps, current, productName);
3597
+ },
3598
+ reportProgress(report) {
3599
+ latestProgressReport = report;
3600
+ recordTurnProgress(deps, { instanceId, turnRecordId, report });
3661
3601
  }
3662
3602
  });
3663
3603
  const recorded = await service.recordTurnOutcome(instanceId, {
@@ -3686,6 +3626,14 @@ function createServerAutomaticTurnDrainer(deps, getService) {
3686
3626
  return;
3687
3627
  }
3688
3628
  } catch (error) {
3629
+ const failedProgressReport = latestProgressReport;
3630
+ if (failedProgressReport) {
3631
+ recordTurnProgress(deps, {
3632
+ instanceId,
3633
+ turnRecordId,
3634
+ report: failActiveTurnProgress(failedProgressReport)
3635
+ });
3636
+ }
3689
3637
  await service.recordTurnFailed(instanceId, {
3690
3638
  instanceId,
3691
3639
  turnRecordId,
@@ -5077,7 +5025,6 @@ var ExecuteAction = defineOperation({
5077
5025
  actionId: input.actionId,
5078
5026
  actionLabel,
5079
5027
  ...sourceTurnRecordId ? { sourceTurnRecordId } : {},
5080
- ...resolvedTurnAction.reviewSubject ? { reviewSubject: resolvedTurnAction.reviewSubject.kind } : {},
5081
5028
  selectedTurnId: ctx.process.selectedTurnId,
5082
5029
  selectedTurnIdBefore: ctx.process.selectedTurnId,
5083
5030
  ...causedSelectedTurnId ? {
@@ -5982,9 +5929,10 @@ function toTurnFailedPayload(input) {
5982
5929
  turnType: input.activeTurnRecord.turnType,
5983
5930
  pathType: input.activeTurnRecord.pathType,
5984
5931
  forkPiEntryId: input.activeTurnRecord.forkPiEntryId,
5985
- resultPiEntryId: input.activeTurnRecord.resultPiEntryId,
5932
+ resultPiEntryId: input.resultPiEntryId ?? input.activeTurnRecord.resultPiEntryId,
5986
5933
  errorSummary: input.message,
5987
- errorClass: input.errorClass
5934
+ errorClass: input.errorClass,
5935
+ recoveryContext: input.recoveryContext
5988
5936
  };
5989
5937
  }
5990
5938
  function buildWorkerFailureWrites(input) {
@@ -6077,7 +6025,9 @@ var WorkerFailure = defineOperation({
6077
6025
  message: input.payload.message,
6078
6026
  errorCode: input.payload.errorCode,
6079
6027
  errorClass: input.payload.errorClass,
6080
- activeTurnRecord: runningTurnRecord
6028
+ activeTurnRecord: runningTurnRecord,
6029
+ resultPiEntryId: input.payload.resultPiEntryId,
6030
+ recoveryContext: input.payload.recoveryContext
6081
6031
  })
6082
6032
  });
6083
6033
  }
@@ -6657,7 +6607,7 @@ function mapSuccess(recorded) {
6657
6607
  };
6658
6608
  }
6659
6609
  function createEngineRunner(deps, options = {}) {
6660
- return async function run(operation, input) {
6610
+ return async function run(operation, input, runOptions = {}) {
6661
6611
  const lockedOutcome = await deps.processOperations.runExclusive(
6662
6612
  input.instanceId,
6663
6613
  async () => {
@@ -6758,6 +6708,17 @@ function createEngineRunner(deps, options = {}) {
6758
6708
  );
6759
6709
  }
6760
6710
  const { recorded } = lockedOutcome;
6711
+ try {
6712
+ runOptions.afterRecord?.(recorded.data);
6713
+ } catch (error) {
6714
+ logProcessEngineError(deps.logger, {
6715
+ err: error,
6716
+ operationKind: operation.kind,
6717
+ instanceId: input.instanceId,
6718
+ stage: "post_commit",
6719
+ code: "after_record_callback_failed"
6720
+ });
6721
+ }
6761
6722
  try {
6762
6723
  await deps.afterRecord?.(recorded.process);
6763
6724
  } catch (error) {
@@ -6942,11 +6903,13 @@ function createProcessEngine(deps) {
6942
6903
  acceptWorkerTurnStart(instanceId, input) {
6943
6904
  return run(AcceptWorkerTurnStart, { instanceId, ...input });
6944
6905
  },
6945
- async recordTurnOutcome(instanceId, payload) {
6946
- return maybeBroadcastActionRequiredToast2(await run(TurnOutcome, { instanceId, payload }));
6906
+ async recordTurnOutcome(instanceId, payload, options) {
6907
+ return maybeBroadcastActionRequiredToast2(
6908
+ await run(TurnOutcome, { instanceId, payload }, { afterRecord: options?.onRecorded })
6909
+ );
6947
6910
  },
6948
- recordTurnFailed(instanceId, payload) {
6949
- return run(TurnFailed, { instanceId, payload });
6911
+ recordTurnFailed(instanceId, payload, options) {
6912
+ return run(TurnFailed, { instanceId, payload }, { afterRecord: options?.onRecorded });
6950
6913
  },
6951
6914
  updateSemanticEntryRefs(instanceId, patch) {
6952
6915
  return run(UpdateSemanticRefs, { instanceId, patch });
@@ -8053,7 +8016,8 @@ function buildProcessLaunchPlan(input) {
8053
8016
  },
8054
8017
  titleSourceFields: input.launchConfig.titleSourceFields?.map((field) => ({ ...field })),
8055
8018
  projectInputs: normalizeProjectInputs(input.launchConfig, input.commitMessages),
8056
- startTurnId: input.launchConfig.startTurnId ?? null
8019
+ startTurnId: input.launchConfig.startTurnId ?? null,
8020
+ ...input.launchConfig.skillIds ? { skillIds: [...input.launchConfig.skillIds] } : {}
8057
8021
  };
8058
8022
  }
8059
8023
 
@@ -8064,7 +8028,7 @@ function collectProcessWatchers(processDef) {
8064
8028
  function buildLaunchPlan(watcher, launchConfig, commitMessages) {
8065
8029
  return buildProcessLaunchPlan({
8066
8030
  processDef: watcher.processDef,
8067
- launchConfig,
8031
+ launchConfig: { ...launchConfig, skillIds: watcher.launchSkillIds },
8068
8032
  launcherId: `${watcher.processId}.${watcher.definition.id}`,
8069
8033
  metadataAdditions: {
8070
8034
  processWatcherId: watcher.definition.id,
@@ -8085,6 +8049,14 @@ function parseConfiguredWatcher(input) {
8085
8049
  if (presentation.targetSummary.trim() === "") {
8086
8050
  throw new Error("presentConfig() must return a non-empty targetSummary");
8087
8051
  }
8052
+ const parsedLaunch = parsed.launchModelConfig ?? {
8053
+ defaultModelProfileId: null,
8054
+ turnConfigs: {}
8055
+ };
8056
+ const launchModelConfig = {
8057
+ defaultModelProfileId: parsedLaunch.defaultModelProfileId ?? null,
8058
+ turnConfigs: parsedLaunch.turnConfigs ?? {}
8059
+ };
8088
8060
  return {
8089
8061
  processId: input.processId,
8090
8062
  processDisplayName: input.processDisplayName,
@@ -8094,10 +8066,8 @@ function parseConfiguredWatcher(input) {
8094
8066
  enabled: parsed.enabled,
8095
8067
  presentation,
8096
8068
  configPath: input.configPath,
8097
- launchModelConfig: parsed.launchModelConfig ?? {
8098
- defaultModelProfileId: null,
8099
- turnConfigs: {}
8100
- }
8069
+ launchModelConfig,
8070
+ launchSkillIds: "skillIds" in parsedLaunch && Array.isArray(parsedLaunch.skillIds) ? parsedLaunch.skillIds : []
8101
8071
  };
8102
8072
  } catch (error) {
8103
8073
  const message = error instanceof Error ? error.message : String(error);
@@ -8484,8 +8454,18 @@ function createWorkerEventIngestor(deps) {
8484
8454
  if (!process2) {
8485
8455
  return;
8486
8456
  }
8487
- const currentTurnRecordId = (process2.currentExecution?.kind === "server_turn" ? process2.currentExecution.id : null) ?? liveTurnRecordIds.get(instanceId) ?? null;
8457
+ const currentTurnRecordId = (process2.currentExecution?.kind === "server_turn" ? process2.currentExecution.id : null) ?? liveTurnRecordIds.get(instanceId) ?? deps.turnRecords.listByInstance(instanceId).find((record3) => record3.status === "running" && record3.turnId === process2.selectedTurnId)?.id ?? null;
8488
8458
  const data = asWsEventPayloadRecord(payload.data);
8459
+ if (payload.eventType === "turn.progress") {
8460
+ const reportedTurnRecordId = readWsEventNonEmptyString(data.turnRecordId);
8461
+ if (!reportedTurnRecordId || reportedTurnRecordId !== currentTurnRecordId) return;
8462
+ recordTurnProgress(deps, {
8463
+ instanceId,
8464
+ turnRecordId: reportedTurnRecordId,
8465
+ report: data.report
8466
+ });
8467
+ return;
8468
+ }
8489
8469
  const projection = getLiveTurnProjection(instanceId, currentTurnRecordId);
8490
8470
  const appliedProjectionEvent = applyPiEventToLiveTurnProjection(projection, {
8491
8471
  eventType: payload.eventType,
@@ -8653,59 +8633,157 @@ function createWorkerInputAckHandler(deps) {
8653
8633
  }
8654
8634
 
8655
8635
  // src/supervisor/worker-turn-ipc-recorder.ts
8656
- import { isTurnFailureCode, isWorkerErrorClass } from "@leitwerk-dev/domain";
8657
- function maybeNormalizeTurnCorrelationFailure(deps, instanceId, result, eventType) {
8658
- if (result.ok) {
8659
- return;
8636
+ import {
8637
+ createGenericFailedTurnRecoveryContext,
8638
+ isTurnFailureCode,
8639
+ isWorkerErrorClass
8640
+ } from "@leitwerk-dev/domain";
8641
+ function terminalWasAlreadyRecorded(deps, turnRecordId, terminalType) {
8642
+ const record3 = deps.turnRecords.getById(turnRecordId);
8643
+ return terminalType === "outcome" ? record3?.status === "succeeded" : record3?.status === "failed";
8644
+ }
8645
+ function failureDetails(result) {
8646
+ if (result instanceof Error) {
8647
+ return { code: "turn_terminal_recording_threw", message: result.message };
8660
8648
  }
8661
- if (result.code !== "stale_turn_record" && result.code !== "missing_turn_record_id") {
8662
- return;
8649
+ if (typeof result === "object" && result !== null && "ok" in result && result.ok === false) {
8650
+ const rejected = result;
8651
+ return {
8652
+ code: typeof rejected.code === "string" ? rejected.code : "turn_terminal_recording_rejected",
8653
+ message: typeof rejected.message === "string" ? rejected.message : "Turn terminal recording was rejected"
8654
+ };
8663
8655
  }
8664
- void deps.commands.recordWorkerFailure(instanceId, {
8665
- errorCode: result.code,
8666
- message: `Worker emitted ${eventType} with invalid turn-record correlation: ${result.message}`,
8667
- errorClass: "infrastructure"
8668
- }).catch(() => {
8669
- });
8656
+ return {
8657
+ code: "turn_terminal_recording_failed",
8658
+ message: "Turn terminal recording failed"
8659
+ };
8670
8660
  }
8671
8661
  function createWorkerTurnIpcRecorder(deps, callbacks) {
8662
+ const acknowledge = (instanceId, workerId, turnRecordId) => {
8663
+ callbacks.onTurnTerminalRecorded?.(instanceId, workerId, turnRecordId);
8664
+ };
8665
+ const reportRecordingFailure = (input) => {
8666
+ try {
8667
+ callbacks.onTurnTerminalRecordingFailed?.(input);
8668
+ } catch {
8669
+ }
8670
+ };
8671
+ const recoverRecordingFailure = async (input) => {
8672
+ if (terminalWasAlreadyRecorded(deps, input.turnRecordId, input.terminalType)) {
8673
+ acknowledge(input.instanceId, input.workerId, input.turnRecordId);
8674
+ return;
8675
+ }
8676
+ const details = failureDetails(input.failure);
8677
+ reportRecordingFailure({
8678
+ instanceId: input.instanceId,
8679
+ workerId: input.workerId,
8680
+ turnRecordId: input.turnRecordId,
8681
+ terminalType: input.terminalType,
8682
+ ...details
8683
+ });
8684
+ try {
8685
+ const fallback = await deps.commands.recordWorkerFailure(input.instanceId, {
8686
+ errorCode: details.code,
8687
+ message: `Server could not durably record worker turn ${input.terminalType}: ${details.message}`,
8688
+ errorClass: "infrastructure",
8689
+ resultPiEntryId: input.resultPiEntryId,
8690
+ recoveryContext: input.recoveryContext
8691
+ });
8692
+ if (fallback.ok || terminalWasAlreadyRecorded(deps, input.turnRecordId, "failure")) {
8693
+ acknowledge(input.instanceId, input.workerId, input.turnRecordId);
8694
+ } else {
8695
+ reportRecordingFailure({
8696
+ instanceId: input.instanceId,
8697
+ workerId: input.workerId,
8698
+ turnRecordId: input.turnRecordId,
8699
+ terminalType: input.terminalType,
8700
+ code: "worker_failure_fallback_rejected",
8701
+ message: fallback.message
8702
+ });
8703
+ }
8704
+ } catch (fallbackError) {
8705
+ const fallbackDetails = failureDetails(fallbackError);
8706
+ reportRecordingFailure({
8707
+ instanceId: input.instanceId,
8708
+ workerId: input.workerId,
8709
+ turnRecordId: input.turnRecordId,
8710
+ terminalType: input.terminalType,
8711
+ code: "worker_failure_fallback_failed",
8712
+ message: fallbackDetails.message
8713
+ });
8714
+ }
8715
+ };
8716
+ const recover = (input) => (failure2) => recoverRecordingFailure({ ...input, failure: failure2 });
8717
+ const clearLiveTurn = (instanceId, turnRecordId) => {
8718
+ if (deps.eventIngestor.getLiveTurnRecordId(instanceId) === turnRecordId) {
8719
+ deps.eventIngestor.clearLiveTurnState(instanceId);
8720
+ }
8721
+ };
8672
8722
  return {
8673
- recordTurnOutcome(instanceId, payload) {
8723
+ recordTurnOutcome(instanceId, workerId, payload) {
8674
8724
  const { turnId, ...rest } = payload;
8675
- if (deps.eventIngestor.getLiveTurnRecordId(instanceId) === rest.turnRecordId) {
8676
- deps.eventIngestor.clearLiveTurnState(instanceId);
8725
+ if (terminalWasAlreadyRecorded(deps, rest.turnRecordId, "outcome")) {
8726
+ acknowledge(instanceId, workerId, rest.turnRecordId);
8727
+ return;
8677
8728
  }
8678
- void deps.commands.recordTurnOutcome(instanceId, {
8729
+ clearLiveTurn(instanceId, rest.turnRecordId);
8730
+ const recoverOutcome = recover({
8679
8731
  instanceId,
8680
- turnId,
8681
- ...rest
8682
- }).then((result) => {
8683
- if (!result.ok) {
8684
- maybeNormalizeTurnCorrelationFailure(deps, instanceId, result, "worker.turn_outcome");
8685
- return;
8686
- }
8687
- callbacks.onTurnOutcomeRecorded?.(instanceId, turnId, rest.outcome, rest.params);
8688
- }).catch(() => {
8732
+ workerId,
8733
+ turnRecordId: rest.turnRecordId,
8734
+ terminalType: "outcome",
8735
+ resultPiEntryId: rest.resultPiEntryId,
8736
+ recoveryContext: createGenericFailedTurnRecoveryContext()
8689
8737
  });
8738
+ void deps.commands.recordTurnOutcome(
8739
+ instanceId,
8740
+ {
8741
+ instanceId,
8742
+ turnId,
8743
+ ...rest
8744
+ },
8745
+ { onRecorded: () => acknowledge(instanceId, workerId, rest.turnRecordId) }
8746
+ ).then((result) => {
8747
+ if (!result.ok) return recoverOutcome(result);
8748
+ callbacks.onTurnOutcomeRecorded?.(instanceId, turnId, rest.outcome, rest.params);
8749
+ }).catch(recoverOutcome);
8690
8750
  },
8691
- recordTurnFailed(instanceId, payload) {
8692
- const { errorClass, failureCode, failureDetails, ...rest } = payload;
8751
+ recordTurnFailed(instanceId, workerId, payload) {
8752
+ const { errorClass, failureCode, failureDetails: details, ...rest } = payload;
8693
8753
  if (errorClass !== void 0 && !isWorkerErrorClass(errorClass)) {
8754
+ void recoverRecordingFailure({
8755
+ instanceId,
8756
+ workerId,
8757
+ turnRecordId: rest.turnRecordId,
8758
+ terminalType: "failure",
8759
+ failure: new Error(`Invalid worker error class '${errorClass}'`)
8760
+ });
8694
8761
  return;
8695
8762
  }
8696
- const normalizedFailureCode = failureCode && isTurnFailureCode(failureCode) ? failureCode : void 0;
8697
- if (deps.eventIngestor.getLiveTurnRecordId(instanceId) === rest.turnRecordId) {
8698
- deps.eventIngestor.clearLiveTurnState(instanceId);
8763
+ if (terminalWasAlreadyRecorded(deps, rest.turnRecordId, "failure")) {
8764
+ acknowledge(instanceId, workerId, rest.turnRecordId);
8765
+ return;
8699
8766
  }
8700
- void deps.commands.recordTurnFailed(instanceId, {
8767
+ const normalizedFailureCode = failureCode && isTurnFailureCode(failureCode) ? failureCode : void 0;
8768
+ clearLiveTurn(instanceId, rest.turnRecordId);
8769
+ const recoverFailure = recover({
8701
8770
  instanceId,
8702
- errorClass,
8703
- ...normalizedFailureCode ? { failureCode: normalizedFailureCode, failureDetails } : {},
8704
- ...rest
8705
- }).then((result) => {
8706
- maybeNormalizeTurnCorrelationFailure(deps, instanceId, result, "worker.turn_failed");
8707
- }).catch(() => {
8771
+ workerId,
8772
+ turnRecordId: rest.turnRecordId,
8773
+ terminalType: "failure",
8774
+ resultPiEntryId: rest.resultPiEntryId,
8775
+ recoveryContext: rest.recoveryContext
8708
8776
  });
8777
+ void deps.commands.recordTurnFailed(
8778
+ instanceId,
8779
+ {
8780
+ instanceId,
8781
+ errorClass,
8782
+ ...normalizedFailureCode ? { failureCode: normalizedFailureCode, failureDetails: details } : {},
8783
+ ...rest
8784
+ },
8785
+ { onRecorded: () => acknowledge(instanceId, workerId, rest.turnRecordId) }
8786
+ ).then((result) => result.ok ? void 0 : recoverFailure(result)).catch(recoverFailure);
8709
8787
  }
8710
8788
  };
8711
8789
  }
@@ -8728,11 +8806,15 @@ function createIpcHandler(deps, callbacks) {
8728
8806
  const inputAckHandler = createWorkerInputAckHandler(deps);
8729
8807
  const turnRecorder = createWorkerTurnIpcRecorder(
8730
8808
  {
8731
- processes: deps.processes,
8809
+ turnRecords: deps.turnRecords,
8732
8810
  commands: deps.commands,
8733
8811
  eventIngestor
8734
8812
  },
8735
- { onTurnOutcomeRecorded: callbacks.onTurnOutcomeRecorded }
8813
+ {
8814
+ onTurnOutcomeRecorded: callbacks.onTurnOutcomeRecorded,
8815
+ onTurnTerminalRecorded: callbacks.onTurnTerminalRecorded,
8816
+ onTurnTerminalRecordingFailed: callbacks.onTurnTerminalRecordingFailed
8817
+ }
8736
8818
  );
8737
8819
  return {
8738
8820
  handleMessage(envelope) {
@@ -8805,6 +8887,7 @@ function createIpcHandler(deps, callbacks) {
8805
8887
  }
8806
8888
  const result = observeWorkerLease("bootstrap_completed", "worker.ready");
8807
8889
  if (result.kind === "applied") {
8890
+ deps.leases.updateHeartbeat(activeLease.workerId);
8808
8891
  void deps.commands.updateSemanticEntryRefs(instanceId, {
8809
8892
  rootEntry: msg.payload.rootEntryId !== void 0 ? msg.payload.rootEntryId ? { entryId: msg.payload.rootEntryId, turnRecordId: null } : null : void 0
8810
8893
  }).catch(() => {
@@ -8863,11 +8946,11 @@ function createIpcHandler(deps, callbacks) {
8863
8946
  break;
8864
8947
  }
8865
8948
  case "worker.turn_outcome": {
8866
- turnRecorder.recordTurnOutcome(instanceId, msg.payload);
8949
+ turnRecorder.recordTurnOutcome(instanceId, workerId, msg.payload);
8867
8950
  break;
8868
8951
  }
8869
8952
  case "worker.turn_failed": {
8870
- turnRecorder.recordTurnFailed(instanceId, msg.payload);
8953
+ turnRecorder.recordTurnFailed(instanceId, workerId, msg.payload);
8871
8954
  break;
8872
8955
  }
8873
8956
  case "worker.lifecycle_parked": {
@@ -9059,6 +9142,21 @@ import {
9059
9142
  WORKER_SNAPSHOT_TOKEN_ENV
9060
9143
  } from "@leitwerk-dev/worker-protocol";
9061
9144
 
9145
+ // src/supervisor/accepted-turn-start-replay.ts
9146
+ function resolveAcceptedTurnStartReplay(deps, instanceId, workerId) {
9147
+ const lease = deps.leases.getByInstance(instanceId);
9148
+ if (!lease || lease.workerId !== workerId || lease.state !== "idle") return null;
9149
+ const process2 = deps.processes.getById(instanceId);
9150
+ if (!process2 || process2.currentExecution?.kind !== "worker_start") return null;
9151
+ const start = deps.turnStarts.getById(process2.currentExecution.id);
9152
+ if (!start || start.instanceId !== instanceId || start.state.kind !== "accepted" || start.state.acceptedWorkerLeaseId !== lease.id)
9153
+ return null;
9154
+ const turnRecord = deps.turnRecords.getById(start.state.turnRecordId);
9155
+ if (!turnRecord || turnRecord.instanceId !== instanceId || turnRecord.status !== "running" || turnRecord.acceptedWorkerLeaseId !== lease.id)
9156
+ return null;
9157
+ return { startRecordId: start.id, turnRecordId: turnRecord.id, startedAt: turnRecord.startedAt };
9158
+ }
9159
+
9062
9160
  // src/supervisor/adoption/adoption-plan.ts
9063
9161
  function workerDescriptorKey(descriptor) {
9064
9162
  return `${descriptor.namespace ?? ""}/${descriptor.unitId}`;
@@ -9647,7 +9745,7 @@ function createWorkerStartPayloadBuilder(deps) {
9647
9745
  process2.processId,
9648
9746
  start.turnId
9649
9747
  );
9650
- const integrationToolNames = selectedTurn?.kind === "llm" ? selectedTurn.integrationTools ?? [] : [];
9748
+ const integrationToolNames = selectedTurn?.kind === "llm" || selectedTurn?.kind === "automatic" ? selectedTurn.integrationTools ?? [] : [];
9651
9749
  const integrationTools = integrationToolNames.length > 0 ? deps.integrationTools?.declarations(integrationToolNames) : void 0;
9652
9750
  if (integrationToolNames.length > 0 && !integrationTools) {
9653
9751
  throw new Error(`Integration tools are unavailable for turn '${start.turnId}'`);
@@ -9793,6 +9891,24 @@ function createWorkerWebSocketIpcManager(options = {}) {
9793
9891
  return false;
9794
9892
  }
9795
9893
  }
9894
+ function queueOutbound(entry, data) {
9895
+ if (entry.outbound.length >= maxBufferedMessages) {
9896
+ entry.outbound = [];
9897
+ reportRuntimeError(
9898
+ entry,
9899
+ new WorkerOutboundBufferOverflowError(
9900
+ entry.instanceId,
9901
+ entry.workerId,
9902
+ maxBufferedMessages
9903
+ )
9904
+ );
9905
+ if (entry.socket) {
9906
+ closeSocket(entry, entry.socket, 1011, "worker websocket outbound buffer overflow");
9907
+ }
9908
+ return;
9909
+ }
9910
+ entry.outbound.push(data);
9911
+ }
9796
9912
  function flushOutbound(entry, socket) {
9797
9913
  while (entry.outbound.length > 0) {
9798
9914
  const data = entry.outbound[0];
@@ -9916,21 +10032,17 @@ function createWorkerWebSocketIpcManager(options = {}) {
9916
10032
  }
9917
10033
  const data = serializeMessage(message);
9918
10034
  if (!entry.socket || !entry.socketAuthenticated) {
9919
- if (entry.outbound.length >= maxBufferedMessages) {
9920
- entry.outbound = [];
9921
- reportRuntimeError(
9922
- entry,
9923
- new WorkerOutboundBufferOverflowError(instanceId, workerId, maxBufferedMessages)
9924
- );
9925
- if (entry.socket) {
9926
- closeSocket(entry, entry.socket, 1011, "worker websocket outbound buffer overflow");
9927
- }
9928
- return;
9929
- }
9930
- entry.outbound.push(data);
10035
+ queueOutbound(entry, data);
9931
10036
  return;
9932
10037
  }
9933
- sendNow(entry, entry.socket, data);
10038
+ const socket = entry.socket;
10039
+ if (sendNow(entry, socket, data)) {
10040
+ return;
10041
+ }
10042
+ if (entry.socket === socket) {
10043
+ closeSocket(entry, socket, 1011, "worker websocket unavailable during send");
10044
+ }
10045
+ queueOutbound(entry, data);
9934
10046
  },
9935
10047
  unregister(instanceId, workerId, reason) {
9936
10048
  const key = connectionKey(instanceId, workerId);
@@ -10125,6 +10237,16 @@ function createWorkerSupervisor(deps) {
10125
10237
  const lease = safeGetLeaseByInstance(instanceId);
10126
10238
  return lease?.workerId === workerId && (lease.state === "spawning" || lease.state === "bootstrapping");
10127
10239
  }
10240
+ function reconcileAcceptedTurnStart(instanceId, workerId) {
10241
+ if (workers.get(instanceId)?.workerId !== workerId) return false;
10242
+ const replay = resolveAcceptedTurnStartReplay(deps, instanceId, workerId);
10243
+ if (!replay) return false;
10244
+ sendToCurrentWorker(instanceId, workerId, {
10245
+ type: "worker.turn_start_accepted",
10246
+ payload: { startRecordId: replay.startRecordId, turnRecordId: replay.turnRecordId }
10247
+ });
10248
+ return true;
10249
+ }
10128
10250
  function routeEnvelope(envelope, instanceId) {
10129
10251
  const currentHandle = workers.get(instanceId);
10130
10252
  if (envelope.instanceId !== instanceId || currentHandle && envelope.workerId !== currentHandle.workerId) {
@@ -10173,6 +10295,10 @@ function createWorkerSupervisor(deps) {
10173
10295
  }
10174
10296
  if (envelope.type === "worker.heartbeat") {
10175
10297
  adoptionCoordinator.onHeartbeat(instanceId, envelope.workerId, envelope.payload);
10298
+ const reportedState = typeof envelope.payload === "object" && envelope.payload !== null && "state" in envelope.payload ? envelope.payload.state : null;
10299
+ if (reportedState === "idle") {
10300
+ reconcileAcceptedTurnStart(instanceId, envelope.workerId);
10301
+ }
10176
10302
  }
10177
10303
  if (envelope.type === "worker.ready") {
10178
10304
  adoptionCoordinator.onWorkerReady(instanceId);
@@ -10537,6 +10663,20 @@ function createWorkerSupervisor(deps) {
10537
10663
  payload: { startRecordId, turnRecordId }
10538
10664
  });
10539
10665
  },
10666
+ reconcileAcceptedTurnStart,
10667
+ acknowledgeTurnTerminal(instanceId, workerId, payload) {
10668
+ runnerRuntime.webSocketIpc.send(
10669
+ instanceId,
10670
+ workerId,
10671
+ createIpcMessage4({
10672
+ type: "worker.turn_terminal_recorded",
10673
+ payload,
10674
+ messageId: randomUUID5(),
10675
+ instanceId,
10676
+ workerId
10677
+ })
10678
+ );
10679
+ },
10540
10680
  questionResponse(instanceId, workerId, payload) {
10541
10681
  sendToCurrentWorker(instanceId, workerId, { type: "worker.question_response", payload });
10542
10682
  },
@@ -11253,10 +11393,13 @@ function createExternalSourceService(deps) {
11253
11393
  });
11254
11394
  return armed;
11255
11395
  }
11256
- if (!isHumanTurnDefinition(turnDef)) {
11396
+ if (!isHumanTurnDefinition(turnDef) && turnDef.kind !== "automatic") {
11257
11397
  return [];
11258
11398
  }
11259
11399
  for (const [externalActionId, action] of Object.entries(turnDef.externalActions ?? {})) {
11400
+ if (action.when && !action.when({ process: process2, projects, params, state })) {
11401
+ continue;
11402
+ }
11260
11403
  const id = getExternalActionArmingId({ turnId, externalActionId });
11261
11404
  armed.push({
11262
11405
  id,
@@ -11320,7 +11463,7 @@ function createExternalSourceService(deps) {
11320
11463
  }
11321
11464
  for (const [turnId, binding] of processDef.turns) {
11322
11465
  const turnDef = binding.definition;
11323
- if (isHumanTurnDefinition(turnDef)) {
11466
+ if (isHumanTurnDefinition(turnDef) || turnDef.kind === "automatic") {
11324
11467
  for (const [externalActionId, action] of Object.entries(turnDef.externalActions ?? {})) {
11325
11468
  if (getExternalActionArmingId({ turnId, externalActionId }) === armingId) {
11326
11469
  return { turnId, externalActionId, sourceKind: action.source.kind };
@@ -12275,6 +12418,20 @@ function launchStartFailure(commit, result) {
12275
12418
  };
12276
12419
  }
12277
12420
  async function createProcessFromLaunchPlanWithDisposition(deps, launchPlan, opts, futureExecutionPlan) {
12421
+ let resourceSelections = opts?.resourceSelections;
12422
+ if (!resourceSelections && launchPlan.skillIds) {
12423
+ try {
12424
+ resourceSelections = deps.skills.resolveActive(launchPlan.skillIds);
12425
+ } catch (error) {
12426
+ return {
12427
+ ok: false,
12428
+ stage: "pre_commit",
12429
+ status: 400,
12430
+ body: { error: error instanceof Error ? error.message : String(error) }
12431
+ };
12432
+ }
12433
+ }
12434
+ opts = { ...opts, resourceSelections: resourceSelections ?? [] };
12278
12435
  if (deps.repositoryCredentials) {
12279
12436
  try {
12280
12437
  deps.repositoryCredentials.validateLaunch({
@@ -12297,8 +12454,8 @@ async function createProcessFromLaunchPlanWithDisposition(deps, launchPlan, opts
12297
12454
  deps,
12298
12455
  launchPlan,
12299
12456
  futureExecutionPlan,
12300
- opts?.resourceSelections,
12301
- opts?.launchIntent
12457
+ opts.resourceSelections,
12458
+ opts.launchIntent
12302
12459
  );
12303
12460
  } catch (error) {
12304
12461
  const dedupKey = launchPlan.handoffDedupKey?.trim() || null;
@@ -12624,19 +12781,7 @@ async function executeScheduledLaunch(deps, execution) {
12624
12781
  computeNextCronRun(execution, new Date(execution.nextRunAt))
12625
12782
  ) : planConsumeFutureExecution(execution);
12626
12783
  const result = await createScheduledProcessFromLaunchPlan(
12627
- {
12628
- processes: deps.processes,
12629
- projects: deps.projects,
12630
- processSkills: deps.processSkills,
12631
- handoffDedupKeys: deps.handoffDedupKeys,
12632
- futureExecutions: deps.futureExecutions,
12633
- broadcaster: deps.broadcaster,
12634
- commands: deps.commands,
12635
- processTitles: deps.processTitles,
12636
- extensionHost: deps.extensionHost,
12637
- logger: deps.logger,
12638
- transaction: deps.transaction
12639
- },
12784
+ deps,
12640
12785
  preparedLaunchPlan.launchPlan,
12641
12786
  transitionPlan,
12642
12787
  {
@@ -13923,7 +14068,7 @@ function createIntegrationToolRequestService(input) {
13923
14068
  process2.processId,
13924
14069
  turn.turnId
13925
14070
  );
13926
- if (turnDefinition?.kind !== "llm" || !turnDefinition.integrationTools?.includes(payload.toolName)) {
14071
+ if (turnDefinition?.kind !== "llm" && turnDefinition?.kind !== "automatic" || !turnDefinition.integrationTools?.includes(payload.toolName)) {
13927
14072
  return fail(`Integration tool '${payload.toolName}' is not authorized for this turn`);
13928
14073
  }
13929
14074
  const projects = input.repos.projects.listByInstance(instanceId);
@@ -15300,6 +15445,7 @@ function buildHostCapabilities(input) {
15300
15445
  commitMessages: input.config.commit_messages,
15301
15446
  processes: input.baseDeps.processes,
15302
15447
  projects: input.baseDeps.projects,
15448
+ skills: input.baseDeps.skills,
15303
15449
  processSkills: input.baseDeps.processSkills,
15304
15450
  handoffDedupKeys: input.baseDeps.handoffDedupKeys,
15305
15451
  futureExecutions: input.baseDeps.futureExecutions,
@@ -16920,8 +17066,7 @@ function registerSkillRoutes(app, deps) {
16920
17066
  return { revisionId };
16921
17067
  } catch (error) {
16922
17068
  const message = error instanceof Error ? error.message : "Skill could not be registered";
16923
- const conflict = message.includes("conflicting") || message.includes("managed by configuration");
16924
- return reply.code(conflict ? 409 : 404).send({ error: message });
17069
+ return reply.code(message.includes("conflicting") ? 409 : 404).send({ error: message });
16925
17070
  }
16926
17071
  }
16927
17072
  );
@@ -17107,21 +17252,24 @@ function isWithin(root, candidate) {
17107
17252
  const relative = path8.relative(root, candidate);
17108
17253
  return relative === "" || relative !== ".." && !relative.startsWith(`..${path8.sep}`);
17109
17254
  }
17110
- async function importSkillDirectory(root, skill, sourceRevision) {
17255
+ async function importSkillDirectory(root, checkoutRoot, sourceRevision) {
17256
+ const skillId = path8.basename(root);
17257
+ const metadata = skillFrontmatter(await readFile5(path8.join(root, "SKILL.md"), "utf8"));
17111
17258
  const collector = new ResourceCollector();
17112
- await collector.addDirectory(path8.resolve(root), `skills/${skill.id}`, SKILL_RESOURCE_OWNER, {
17259
+ await collector.addDirectory(path8.resolve(root), `skills/${skillId}`, SKILL_RESOURCE_OWNER, {
17113
17260
  forbiddenNames: FORBIDDEN_SKILL_NAMES
17114
17261
  });
17115
17262
  const files = collector.toResourceFiles();
17116
- if (!files.some((file) => file.path === `skills/${skill.id}/SKILL.md`)) {
17117
- throw new Error(`Skill '${skill.id}' must contain a regular root SKILL.md`);
17263
+ if (!files.some((file) => file.path === `skills/${skillId}/SKILL.md`)) {
17264
+ throw new Error(`Skill '${skillId}' must contain a regular root SKILL.md`);
17118
17265
  }
17119
17266
  return {
17120
- skillId: skill.id,
17121
- label: skill.label ?? skill.id,
17122
- description: skill.description ?? null,
17267
+ skillId,
17268
+ label: metadataText(metadata.name) ?? fallbackLabel(skillId),
17269
+ description: metadataText(metadata.description),
17123
17270
  bundle: createCanonicalPiResourceBundle2(files),
17124
- sourceRevision
17271
+ sourceRevision,
17272
+ sourcePath: repositorySourcePath(checkoutRoot, root)
17125
17273
  };
17126
17274
  }
17127
17275
  async function checkoutGitSource(source, root) {
@@ -17136,12 +17284,8 @@ async function checkoutGitSource(source, root) {
17136
17284
  const { stdout } = await execFileAsync("git", ["-C", root, "rev-parse", "HEAD"]);
17137
17285
  return { root, commit: stdout.trim() };
17138
17286
  }
17139
- function metadataValue(markdown, key) {
17140
- if (!markdown.startsWith("---")) return null;
17141
- const end = markdown.indexOf("\n---", 3);
17142
- if (end < 0) return null;
17143
- const match = markdown.slice(3, end).match(new RegExp(`^${key}:\\s*["']?([^\\n"']+)["']?\\s*$`, "m"));
17144
- return match?.[1]?.trim() || null;
17287
+ function metadataText(value) {
17288
+ return typeof value === "string" ? value.trim() || null : null;
17145
17289
  }
17146
17290
  function fallbackLabel(id) {
17147
17291
  return id.split(/[-_.]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
@@ -17153,7 +17297,7 @@ async function discoverSkillRoots(catalogRoot) {
17153
17297
  (left, right) => left.name.localeCompare(right.name)
17154
17298
  );
17155
17299
  const skillId = path8.basename(directory);
17156
- if (directory !== catalogRoot && SAFE_SKILL_ID_PATTERN.test(skillId) && entries.some((entry) => entry.name === "SKILL.md" && entry.isFile())) {
17300
+ if (SAFE_SKILL_ID_PATTERN.test(skillId) && entries.some((entry) => entry.name === "SKILL.md" && entry.isFile())) {
17157
17301
  result.push(directory);
17158
17302
  return;
17159
17303
  }
@@ -17172,10 +17316,7 @@ function repositorySourcePath(checkoutRoot, skillRoot) {
17172
17316
  async function importSkillRepository(repository) {
17173
17317
  const tempRoot = await mkdtemp2(path8.join(tmpdir2(), "leitwerk-skill-repository-"));
17174
17318
  try {
17175
- const checkout = await checkoutGitSource(
17176
- { kind: "git", url: repository.url, ref: repository.ref, path: repository.path ?? "skills" },
17177
- path8.join(tempRoot, "checkout")
17178
- );
17319
+ const checkout = await checkoutGitSource(repository, path8.join(tempRoot, "checkout"));
17179
17320
  const catalogRoot = path8.resolve(checkout.root, repository.path ?? "skills");
17180
17321
  if (!isWithin(checkout.root, catalogRoot)) {
17181
17322
  throw new Error(`Skill repository '${repository.id}' path escapes its checkout`);
@@ -17194,61 +17335,13 @@ async function importSkillRepository(repository) {
17194
17335
  }
17195
17336
  const skills = [];
17196
17337
  for (const skillRoot of skillRoots) {
17197
- const skillId = path8.basename(skillRoot);
17198
- const markdown = await readFile5(path8.join(skillRoot, "SKILL.md"), "utf8");
17199
- const imported = await importSkillDirectory(
17200
- skillRoot,
17201
- {
17202
- id: skillId,
17203
- label: metadataValue(markdown, "name") ?? fallbackLabel(skillId),
17204
- description: metadataValue(markdown, "description") ?? void 0,
17205
- source: { kind: "local", path: skillRoot }
17206
- },
17207
- checkout.commit
17208
- );
17209
- skills.push({
17210
- ...imported,
17211
- sourcePath: repositorySourcePath(checkout.root, skillRoot)
17212
- });
17338
+ skills.push(await importSkillDirectory(skillRoot, checkout.root, checkout.commit));
17213
17339
  }
17214
17340
  return { commit: checkout.commit, skills };
17215
17341
  } finally {
17216
17342
  await rm3(tempRoot, { recursive: true, force: true });
17217
17343
  }
17218
17344
  }
17219
- async function importConfiguredSkills(skills, configRoot) {
17220
- let tempRoot = null;
17221
- const checkouts = /* @__PURE__ */ new Map();
17222
- try {
17223
- const result = [];
17224
- for (const skill of skills) {
17225
- if (skill.source.kind === "local") {
17226
- result.push(
17227
- await importSkillDirectory(path8.resolve(configRoot, skill.source.path), skill, null)
17228
- );
17229
- continue;
17230
- }
17231
- const key = `${skill.source.url}\0${skill.source.ref}`;
17232
- let checkout = checkouts.get(key);
17233
- if (!checkout) {
17234
- tempRoot ??= await mkdtemp2(path8.join(tmpdir2(), "leitwerk-skills-"));
17235
- checkout = await checkoutGitSource(
17236
- skill.source,
17237
- path8.join(tempRoot, String(checkouts.size))
17238
- );
17239
- checkouts.set(key, checkout);
17240
- }
17241
- const selected = path8.resolve(checkout.root, skill.source.path);
17242
- if (!isWithin(checkout.root, selected)) {
17243
- throw new Error(`Skill '${skill.id}' Git path escapes its checkout`);
17244
- }
17245
- result.push(await importSkillDirectory(selected, skill, checkout.commit));
17246
- }
17247
- return result;
17248
- } finally {
17249
- if (tempRoot) await rm3(tempRoot, { recursive: true, force: true });
17250
- }
17251
- }
17252
17345
 
17253
17346
  // src/skills/catalog-service.ts
17254
17347
  function createSkillCatalogService(input) {
@@ -17322,12 +17415,6 @@ function createSkillCatalogService(input) {
17322
17415
  };
17323
17416
  }
17324
17417
 
17325
- // src/skills/catalog-sync.ts
17326
- async function syncConfiguredSkillCatalog(input) {
17327
- const imported = await importConfiguredSkills(input.skills, input.configRoot);
17328
- input.repos.transaction((repos) => repos.skills.reconcile(imported));
17329
- }
17330
-
17331
17418
  // src/supervisor/stale-heartbeat-watchdog.ts
17332
17419
  import { parseDurationMs as parseDurationMs5 } from "@leitwerk-dev/watcher-utils";
17333
17420
  function startStaleHeartbeatWatchdog(deps) {
@@ -17336,7 +17423,9 @@ function startStaleHeartbeatWatchdog(deps) {
17336
17423
  const now2 = deps.now ?? (() => Date.now());
17337
17424
  const setIntervalImpl = deps.setIntervalImpl ?? setInterval;
17338
17425
  const clearIntervalImpl = deps.clearIntervalImpl ?? clearInterval;
17426
+ const acceptedStartReconciliations = /* @__PURE__ */ new Map();
17339
17427
  const tick = () => {
17428
+ const observedReconciliations = /* @__PURE__ */ new Set();
17340
17429
  for (const lease of deps.leases.listActive()) {
17341
17430
  if (deps.supervisor.isAdoptionPending?.(lease.instanceId)) {
17342
17431
  continue;
@@ -17344,15 +17433,48 @@ function startStaleHeartbeatWatchdog(deps) {
17344
17433
  if (lease.state !== "idle" && lease.state !== "busy" && lease.state !== "draining") {
17345
17434
  continue;
17346
17435
  }
17347
- const heartbeatAt = lease.lastHeartbeatAt ?? lease.startedAt;
17348
- const lastSeenMs = Date.parse(heartbeatAt);
17349
- if (!Number.isFinite(lastSeenMs) || now2() - lastSeenMs < timeoutMs) {
17350
- continue;
17351
- }
17352
17436
  const process2 = deps.processes.getById(lease.instanceId);
17353
17437
  if (!process2) {
17354
17438
  continue;
17355
17439
  }
17440
+ const acceptedStart = lease.state === "idle" ? resolveAcceptedTurnStartReplay(deps, lease.instanceId, lease.workerId) : null;
17441
+ const acceptedAtMs = acceptedStart ? Date.parse(acceptedStart.startedAt) : Number.NaN;
17442
+ if (acceptedStart && Number.isFinite(acceptedAtMs) && now2() - acceptedAtMs >= timeoutMs) {
17443
+ observedReconciliations.add(lease.instanceId);
17444
+ const reconciliation = acceptedStartReconciliations.get(lease.instanceId);
17445
+ if (!reconciliation || reconciliation.turnRecordId !== acceptedStart.turnRecordId) {
17446
+ if (deps.supervisor.reconcileAcceptedTurnStart(lease.instanceId, lease.workerId)) {
17447
+ acceptedStartReconciliations.set(lease.instanceId, {
17448
+ turnRecordId: acceptedStart.turnRecordId,
17449
+ startedAtMs: now2()
17450
+ });
17451
+ continue;
17452
+ }
17453
+ } else if (now2() - reconciliation.startedAtMs < timeoutMs) {
17454
+ continue;
17455
+ }
17456
+ acceptedStartReconciliations.delete(lease.instanceId);
17457
+ deps.ipcHandler.handleMessage(
17458
+ createServerObservedWorkerFailedMessage({
17459
+ instanceId: lease.instanceId,
17460
+ workerId: lease.workerId,
17461
+ state: lease.state,
17462
+ errorCode: "idle_worker_running_turn",
17463
+ message: `Worker ${lease.workerId} reported idle while turn ${acceptedStart.turnRecordId} remained running`,
17464
+ errorClass: "infrastructure",
17465
+ selectedTurnId: process2.selectedTurnId
17466
+ })
17467
+ );
17468
+ deps.supervisor.getWorker(lease.instanceId)?.kill();
17469
+ continue;
17470
+ }
17471
+ if (!lease.lastHeartbeatAt) {
17472
+ continue;
17473
+ }
17474
+ const lastSeenMs = Date.parse(lease.lastHeartbeatAt);
17475
+ if (!Number.isFinite(lastSeenMs) || now2() - lastSeenMs < timeoutMs) {
17476
+ continue;
17477
+ }
17356
17478
  deps.ipcHandler.handleMessage(
17357
17479
  createServerObservedWorkerFailedMessage({
17358
17480
  instanceId: lease.instanceId,
@@ -17366,6 +17488,11 @@ function startStaleHeartbeatWatchdog(deps) {
17366
17488
  );
17367
17489
  deps.supervisor.getWorker(lease.instanceId)?.kill();
17368
17490
  }
17491
+ for (const instanceId of acceptedStartReconciliations.keys()) {
17492
+ if (!observedReconciliations.has(instanceId)) {
17493
+ acceptedStartReconciliations.delete(instanceId);
17494
+ }
17495
+ }
17369
17496
  };
17370
17497
  const timer = setIntervalImpl(tick, intervalMs);
17371
17498
  return {
@@ -17515,12 +17642,10 @@ ${configErrors.join("\n")}`);
17515
17642
  const repos = createAllRepos(db, {
17516
17643
  ...credentialCipher ? { credentialCipher } : {}
17517
17644
  });
17518
- await syncConfiguredSkillCatalog({
17519
- skills: config.skills ?? [],
17520
- configRoot: opts.extensionLoadingStartDir ?? process.cwd(),
17521
- repos
17645
+ repos.transaction((transactionRepos) => {
17646
+ transactionRepos.skills.deactivateConfiguredSkills();
17647
+ transactionRepos.skills.backfillDependencies();
17522
17648
  });
17523
- repos.transaction((transactionRepos) => transactionRepos.skills.backfillDependencies());
17524
17649
  const skillCatalog = createSkillCatalogService({
17525
17650
  repositories: config.skill_repositories ?? [],
17526
17651
  repos
@@ -17895,6 +18020,23 @@ ${configErrors.join("\n")}`);
17895
18020
  } : void 0
17896
18021
  },
17897
18022
  {
18023
+ onTurnTerminalRecorded(instanceId, workerId, turnRecordId) {
18024
+ supervisor?.acknowledgeTurnTerminal(instanceId, workerId, { turnRecordId });
18025
+ },
18026
+ onTurnTerminalRecordingFailed(input) {
18027
+ app.log.error(input, "Worker turn terminal recording failed");
18028
+ baseDeps.events.create({
18029
+ instanceId: input.instanceId,
18030
+ eventType: "worker_terminal_recording_failed",
18031
+ data: {
18032
+ workerId: input.workerId,
18033
+ turnRecordId: input.turnRecordId,
18034
+ terminalType: input.terminalType,
18035
+ code: input.code,
18036
+ message: input.message
18037
+ }
18038
+ });
18039
+ },
17898
18040
  onWorkerTurnStartAccepted(instanceId, workerId, payload) {
17899
18041
  supervisor?.acceptTurnStart(
17900
18042
  instanceId,
@@ -18000,6 +18142,8 @@ ${configErrors.join("\n")}`);
18000
18142
  staleHeartbeatWatchdog = startStaleHeartbeatWatchdog({
18001
18143
  leases: baseDeps.leases,
18002
18144
  processes: baseDeps.processes,
18145
+ turnRecords: baseDeps.turnRecords,
18146
+ turnStarts: baseDeps.turnStarts,
18003
18147
  ipcHandler,
18004
18148
  supervisor,
18005
18149
  staleHeartbeatTimeout: config.workers.stale_heartbeat_timeout
@@ -18291,4 +18435,4 @@ export {
18291
18435
  createApp,
18292
18436
  createAppContext
18293
18437
  };
18294
- //# sourceMappingURL=chunk-UC3OOEQ3.js.map
18438
+ //# sourceMappingURL=chunk-DFHOPJRZ.js.map