@leitwerk-dev/server 0.3.1 → 0.4.0

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 (309) hide show
  1. package/dist/{app-BuJCdkvy.d.ts → app-CsuxFZT5.d.ts} +262 -121
  2. package/dist/app-JM4CBTND.js +8 -0
  3. package/dist/app.d.ts +9 -0
  4. package/dist/app.d.ts.map +1 -1
  5. package/dist/auth/fastify-auth.d.ts +9 -0
  6. package/dist/auth/fastify-auth.d.ts.map +1 -1
  7. package/dist/{chunk-QCHS3X33.js → chunk-FPMDWQF7.js} +2617 -562
  8. package/dist/chunk-FPMDWQF7.js.map +1 -0
  9. package/dist/{chunk-HK6BLLHA.js → chunk-MBHRCQFE.js} +2303 -1576
  10. package/dist/chunk-MBHRCQFE.js.map +1 -0
  11. package/dist/config/config-loader.d.ts +1 -1
  12. package/dist/config/config-loader.d.ts.map +1 -1
  13. package/dist/config/config-types.d.ts +14 -1
  14. package/dist/config/config-types.d.ts.map +1 -1
  15. package/dist/config/kubernetes-docker-isolation.d.ts +7 -0
  16. package/dist/config/kubernetes-docker-isolation.d.ts.map +1 -0
  17. package/dist/db/database.d.ts.map +1 -1
  18. package/dist/db/execution-inspection-repo.d.ts +15 -0
  19. package/dist/db/execution-inspection-repo.d.ts.map +1 -0
  20. package/dist/db/history-window.d.ts +11 -0
  21. package/dist/db/history-window.d.ts.map +1 -0
  22. package/dist/db/process-event-repo.d.ts +2 -0
  23. package/dist/db/process-event-repo.d.ts.map +1 -1
  24. package/dist/db/process-instance-repo.d.ts +4 -1
  25. package/dist/db/process-instance-repo.d.ts.map +1 -1
  26. package/dist/db/process-leaf-outcome-snapshot-repo.d.ts +2 -1
  27. package/dist/db/process-leaf-outcome-snapshot-repo.d.ts.map +1 -1
  28. package/dist/db/process-project-repo.d.ts +2 -0
  29. package/dist/db/process-project-repo.d.ts.map +1 -1
  30. package/dist/db/process-skill-repo.d.ts.map +1 -1
  31. package/dist/db/process-turn-annotation-repo.d.ts +4 -1
  32. package/dist/db/process-turn-annotation-repo.d.ts.map +1 -1
  33. package/dist/db/process-turn-record-repo.d.ts +4 -0
  34. package/dist/db/process-turn-record-repo.d.ts.map +1 -1
  35. package/dist/db/publication-repo.d.ts +5 -0
  36. package/dist/db/publication-repo.d.ts.map +1 -0
  37. package/dist/db/repositories.d.ts +12 -0
  38. package/dist/db/repositories.d.ts.map +1 -1
  39. package/dist/db/schema.d.ts +693 -2
  40. package/dist/db/schema.d.ts.map +1 -1
  41. package/dist/db/scoped-settings-repo.d.ts +37 -0
  42. package/dist/db/scoped-settings-repo.d.ts.map +1 -0
  43. package/dist/db/skill-repo.d.ts +3 -0
  44. package/dist/db/skill-repo.d.ts.map +1 -1
  45. package/dist/db/turn-start-record-repo.d.ts +2 -1
  46. package/dist/db/turn-start-record-repo.d.ts.map +1 -1
  47. package/dist/db/turn-summary-repo.d.ts +1 -1
  48. package/dist/db/turn-summary-repo.d.ts.map +1 -1
  49. package/dist/db/worker-lease-repo.d.ts +2 -1
  50. package/dist/db/worker-lease-repo.d.ts.map +1 -1
  51. package/dist/domain-logic/outcome-tools.d.ts.map +1 -1
  52. package/dist/external-source-service.d.ts.map +1 -1
  53. package/dist/future-execution/execution.d.ts +4 -1
  54. package/dist/future-execution/execution.d.ts.map +1 -1
  55. package/dist/future-execution/launch-lifecycle.d.ts +9 -25
  56. package/dist/future-execution/launch-lifecycle.d.ts.map +1 -1
  57. package/dist/future-execution/lifecycle.d.ts +3 -28
  58. package/dist/future-execution/lifecycle.d.ts.map +1 -1
  59. package/dist/future-execution/model-projection.d.ts.map +1 -1
  60. package/dist/future-execution/reconciliation.d.ts +1 -0
  61. package/dist/future-execution/reconciliation.d.ts.map +1 -1
  62. package/dist/future-execution-presenter.d.ts.map +1 -1
  63. package/dist/index.js +2 -2
  64. package/dist/integration-tool-registry.d.ts +11 -2
  65. package/dist/integration-tool-registry.d.ts.map +1 -1
  66. package/dist/launch-coordinator.d.ts.map +1 -1
  67. package/dist/launcher-model-config-service.d.ts +7 -1
  68. package/dist/launcher-model-config-service.d.ts.map +1 -1
  69. package/dist/leaf-outcome-snapshot-capture.d.ts +1 -0
  70. package/dist/leaf-outcome-snapshot-capture.d.ts.map +1 -1
  71. package/dist/main.js +3 -3
  72. package/dist/primary-path-snapshot.d.ts.map +1 -1
  73. package/dist/process-action-presenter.d.ts +1 -6
  74. package/dist/process-action-presenter.d.ts.map +1 -1
  75. package/dist/process-action-registry.d.ts.map +1 -1
  76. package/dist/process-engine/decision.d.ts +2 -0
  77. package/dist/process-engine/decision.d.ts.map +1 -1
  78. package/dist/process-engine/engine.d.ts.map +1 -1
  79. package/dist/process-engine/mapped-turns.d.ts.map +1 -1
  80. package/dist/process-engine/ops/continue-failed-turn.d.ts.map +1 -1
  81. package/dist/process-engine/ops/process-observation.d.ts +6 -0
  82. package/dist/process-engine/ops/process-observation.d.ts.map +1 -0
  83. package/dist/process-engine/ops/retry-failed-turn.d.ts.map +1 -1
  84. package/dist/process-engine/ops/retry-startup.d.ts.map +1 -1
  85. package/dist/process-engine/ops/start-process.d.ts +2 -0
  86. package/dist/process-engine/ops/start-process.d.ts.map +1 -1
  87. package/dist/process-engine/ops/turn-outcome.d.ts.map +1 -1
  88. package/dist/process-engine/ops/turn-wait.d.ts +30 -0
  89. package/dist/process-engine/ops/turn-wait.d.ts.map +1 -0
  90. package/dist/process-engine/ops/update-model-config.d.ts +9 -0
  91. package/dist/process-engine/ops/update-model-config.d.ts.map +1 -0
  92. package/dist/process-engine/recorder.d.ts.map +1 -1
  93. package/dist/process-engine/turn-start-preflight.d.ts +6 -0
  94. package/dist/process-engine/turn-start-preflight.d.ts.map +1 -1
  95. package/dist/process-engine/turn-wait-state.d.ts +24 -0
  96. package/dist/process-engine/turn-wait-state.d.ts.map +1 -0
  97. package/dist/process-engine/turn-worker-requirement.d.ts +2 -0
  98. package/dist/process-engine/turn-worker-requirement.d.ts.map +1 -1
  99. package/dist/process-engine/types.d.ts +5 -1
  100. package/dist/process-engine/types.d.ts.map +1 -1
  101. package/dist/process-engine/writes/build-process-abort-writes.d.ts +3 -1
  102. package/dist/process-engine/writes/build-process-abort-writes.d.ts.map +1 -1
  103. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts +2 -0
  104. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts.map +1 -1
  105. package/dist/process-engine/writes/commit-writes.d.ts +2 -0
  106. package/dist/process-engine/writes/commit-writes.d.ts.map +1 -1
  107. package/dist/process-engine/writes/writes.d.ts +28 -60
  108. package/dist/process-engine/writes/writes.d.ts.map +1 -1
  109. package/dist/process-graph.d.ts +1 -1
  110. package/dist/process-graph.d.ts.map +1 -1
  111. package/dist/process-inspection-reader.d.ts +21 -0
  112. package/dist/process-inspection-reader.d.ts.map +1 -0
  113. package/dist/process-inspection-trace.d.ts +13 -0
  114. package/dist/process-inspection-trace.d.ts.map +1 -0
  115. package/dist/process-inspection.d.ts +22 -0
  116. package/dist/process-inspection.d.ts.map +1 -0
  117. package/dist/process-instance-tree-presenter.d.ts +4 -3
  118. package/dist/process-instance-tree-presenter.d.ts.map +1 -1
  119. package/dist/process-launch-executor.d.ts +2 -0
  120. package/dist/process-launch-executor.d.ts.map +1 -1
  121. package/dist/process-launch-plan.d.ts +1 -0
  122. package/dist/process-launch-plan.d.ts.map +1 -1
  123. package/dist/process-launcher-registry.d.ts.map +1 -1
  124. package/dist/process-model-config.d.ts +19 -0
  125. package/dist/process-model-config.d.ts.map +1 -0
  126. package/dist/process-model-policy/construct.d.ts.map +1 -1
  127. package/dist/process-model-policy/evaluate.d.ts.map +1 -1
  128. package/dist/process-model-policy/index.d.ts +4 -1
  129. package/dist/process-model-policy/index.d.ts.map +1 -1
  130. package/dist/process-model-policy/project.d.ts.map +1 -1
  131. package/dist/process-model-policy/types.d.ts +18 -0
  132. package/dist/process-model-policy/types.d.ts.map +1 -1
  133. package/dist/process-model-policy-presenter.d.ts.map +1 -1
  134. package/dist/process-runtime-availability.d.ts +2 -1
  135. package/dist/process-runtime-availability.d.ts.map +1 -1
  136. package/dist/process-turn-trace.d.ts.map +1 -1
  137. package/dist/process-ui-snapshot-presenter.d.ts +14 -3
  138. package/dist/process-ui-snapshot-presenter.d.ts.map +1 -1
  139. package/dist/routes/future-executions.d.ts.map +1 -1
  140. package/dist/routes/launchers.d.ts.map +1 -1
  141. package/dist/routes/process-actions.d.ts.map +1 -1
  142. package/dist/routes/process-detail.d.ts.map +1 -1
  143. package/dist/routes/process-model-config.d.ts +4 -0
  144. package/dist/routes/process-model-config.d.ts.map +1 -0
  145. package/dist/routes/process-route-helpers.d.ts +8 -9
  146. package/dist/routes/process-route-helpers.d.ts.map +1 -1
  147. package/dist/routes/processes.d.ts.map +1 -1
  148. package/dist/routes/settings.d.ts +11 -0
  149. package/dist/routes/settings.d.ts.map +1 -0
  150. package/dist/routes/ticket-creation.d.ts.map +1 -1
  151. package/dist/scoped-settings-service.d.ts +83 -0
  152. package/dist/scoped-settings-service.d.ts.map +1 -0
  153. package/dist/server-bootstrap/build-host-capabilities.d.ts +2 -0
  154. package/dist/server-bootstrap/build-host-capabilities.d.ts.map +1 -1
  155. package/dist/server-bootstrap/register-http.d.ts.map +1 -1
  156. package/dist/session-summary-projection.d.ts.map +1 -1
  157. package/dist/skills/bundled-skills.d.ts +5 -0
  158. package/dist/skills/bundled-skills.d.ts.map +1 -0
  159. package/dist/skills/catalog-service.d.ts +1 -0
  160. package/dist/skills/catalog-service.d.ts.map +1 -1
  161. package/dist/skills/extension-importer.d.ts +11 -0
  162. package/dist/skills/extension-importer.d.ts.map +1 -0
  163. package/dist/skills/launch-skills.d.ts +11 -0
  164. package/dist/skills/launch-skills.d.ts.map +1 -0
  165. package/dist/skills/skill-frontmatter.d.ts +5 -0
  166. package/dist/skills/skill-frontmatter.d.ts.map +1 -1
  167. package/dist/skills/source-importer.d.ts +3 -0
  168. package/dist/skills/source-importer.d.ts.map +1 -1
  169. package/dist/startup-evidence.d.ts +3 -0
  170. package/dist/startup-evidence.d.ts.map +1 -1
  171. package/dist/supervisor/execution-inspection-ingestor.d.ts +9 -0
  172. package/dist/supervisor/execution-inspection-ingestor.d.ts.map +1 -0
  173. package/dist/supervisor/ipc-handler.d.ts +2 -0
  174. package/dist/supervisor/ipc-handler.d.ts.map +1 -1
  175. package/dist/supervisor/worker-event-ingestor.d.ts +1 -0
  176. package/dist/supervisor/worker-event-ingestor.d.ts.map +1 -1
  177. package/dist/supervisor/worker-start-payload-builder.d.ts.map +1 -1
  178. package/dist/supervisor/worker-supervisor.d.ts +2 -0
  179. package/dist/supervisor/worker-supervisor.d.ts.map +1 -1
  180. package/dist/test-helpers/prepared-fixture-start.d.ts.map +1 -1
  181. package/dist/test-helpers/process-model-fixtures.d.ts +1 -0
  182. package/dist/test-helpers/process-model-fixtures.d.ts.map +1 -1
  183. package/dist/test-helpers/scoped-settings-fixtures.d.ts +16 -0
  184. package/dist/test-helpers/scoped-settings-fixtures.d.ts.map +1 -0
  185. package/dist/test-helpers/skill-fixtures.d.ts +4 -0
  186. package/dist/test-helpers/skill-fixtures.d.ts.map +1 -0
  187. package/dist/testing.js +2 -1
  188. package/dist/testing.js.map +1 -1
  189. package/dist/tool-approval-gate.d.ts +3 -0
  190. package/dist/tool-approval-gate.d.ts.map +1 -1
  191. package/dist/turn-progress.d.ts.map +1 -1
  192. package/dist/turn-wait-service.d.ts +28 -0
  193. package/dist/turn-wait-service.d.ts.map +1 -0
  194. package/dist/worker-runtime-profile-selection.d.ts +2 -0
  195. package/dist/worker-runtime-profile-selection.d.ts.map +1 -1
  196. package/package.json +20 -19
  197. package/src/app.ts +115 -5
  198. package/src/auth/fastify-auth.ts +13 -0
  199. package/src/config/config-loader.ts +40 -2
  200. package/src/config/config-types.ts +14 -1
  201. package/src/config/kubernetes-docker-isolation.ts +21 -0
  202. package/src/db/database.ts +131 -40
  203. package/src/db/execution-inspection-repo.ts +163 -0
  204. package/src/db/history-window.ts +18 -0
  205. package/src/db/process-event-repo.ts +88 -10
  206. package/src/db/process-instance-repo.ts +9 -2
  207. package/src/db/process-leaf-outcome-snapshot-repo.ts +8 -2
  208. package/src/db/process-project-repo.ts +4 -0
  209. package/src/db/process-skill-repo.ts +9 -2
  210. package/src/db/process-turn-annotation-repo.ts +27 -9
  211. package/src/db/process-turn-record-repo.ts +45 -12
  212. package/src/db/publication-repo.ts +63 -0
  213. package/src/db/repositories.ts +17 -0
  214. package/src/db/schema.ts +103 -1
  215. package/src/db/scoped-settings-repo.ts +234 -0
  216. package/src/db/skill-repo.ts +89 -27
  217. package/src/db/turn-start-record-repo.ts +8 -2
  218. package/src/db/turn-summary-repo.ts +12 -3
  219. package/src/db/worker-lease-repo.ts +8 -2
  220. package/src/domain-logic/outcome-tools.ts +4 -193
  221. package/src/external-source-service.ts +33 -7
  222. package/src/future-execution/execution.ts +9 -2
  223. package/src/future-execution/launch-lifecycle.ts +87 -78
  224. package/src/future-execution/lifecycle.ts +5 -34
  225. package/src/future-execution/model-projection.ts +2 -0
  226. package/src/future-execution/reconciliation.ts +7 -0
  227. package/src/future-execution-presenter.ts +7 -8
  228. package/src/integration-tool-registry.ts +59 -26
  229. package/src/launch-coordinator.ts +10 -1
  230. package/src/launcher-model-config-service.ts +24 -3
  231. package/src/leaf-outcome-snapshot-capture.ts +2 -0
  232. package/src/primary-path-snapshot.ts +3 -4
  233. package/src/process-action-presenter.ts +22 -57
  234. package/src/process-action-registry.ts +31 -39
  235. package/src/process-engine/decision.ts +10 -0
  236. package/src/process-engine/engine.ts +11 -2
  237. package/src/process-engine/mapped-turns.ts +5 -7
  238. package/src/process-engine/ops/continue-failed-turn.ts +2 -13
  239. package/src/process-engine/ops/process-observation.ts +119 -0
  240. package/src/process-engine/ops/retry-failed-turn.ts +2 -12
  241. package/src/process-engine/ops/retry-startup.ts +9 -13
  242. package/src/process-engine/ops/start-process.ts +34 -2
  243. package/src/process-engine/ops/turn-outcome.ts +61 -60
  244. package/src/process-engine/ops/turn-wait.ts +225 -0
  245. package/src/process-engine/ops/update-model-config.ts +66 -0
  246. package/src/process-engine/recorder.ts +21 -5
  247. package/src/process-engine/turn-start-preflight.ts +168 -105
  248. package/src/process-engine/turn-wait-state.ts +126 -0
  249. package/src/process-engine/turn-worker-requirement.ts +4 -0
  250. package/src/process-engine/types.ts +9 -0
  251. package/src/process-engine/writes/build-process-abort-writes.ts +30 -20
  252. package/src/process-engine/writes/build-turn-outcome-writes.ts +39 -2
  253. package/src/process-engine/writes/commit-writes.ts +15 -2
  254. package/src/process-engine/writes/writes.ts +59 -74
  255. package/src/process-graph.ts +0 -1
  256. package/src/process-inspection-reader.ts +305 -0
  257. package/src/process-inspection-trace.ts +176 -0
  258. package/src/process-inspection.ts +169 -0
  259. package/src/process-instance-tree-presenter.ts +56 -216
  260. package/src/process-launch-executor.ts +5 -2
  261. package/src/process-launch-plan.ts +17 -2
  262. package/src/process-launcher-registry.ts +28 -16
  263. package/src/process-model-config.ts +100 -0
  264. package/src/process-model-policy/construct.ts +1 -0
  265. package/src/process-model-policy/evaluate.ts +34 -32
  266. package/src/process-model-policy/index.ts +45 -3
  267. package/src/process-model-policy/project.ts +62 -76
  268. package/src/process-model-policy/types.ts +26 -0
  269. package/src/process-model-policy-presenter.ts +7 -3
  270. package/src/process-runtime-availability.ts +9 -4
  271. package/src/process-turn-trace.ts +12 -24
  272. package/src/process-ui-snapshot-presenter.ts +210 -295
  273. package/src/routes/future-executions.ts +5 -5
  274. package/src/routes/launchers.ts +51 -1
  275. package/src/routes/process-actions.ts +9 -9
  276. package/src/routes/process-detail.ts +25 -2
  277. package/src/routes/process-model-config.ts +70 -0
  278. package/src/routes/process-route-helpers.ts +153 -162
  279. package/src/routes/processes.ts +2 -0
  280. package/src/routes/settings.ts +173 -0
  281. package/src/routes/ticket-creation.ts +28 -5
  282. package/src/scoped-settings-service.ts +736 -0
  283. package/src/server-bootstrap/build-host-capabilities.ts +42 -0
  284. package/src/server-bootstrap/register-http.ts +7 -1
  285. package/src/session-summary-projection.ts +1 -2
  286. package/src/skills/bundled-skills.ts +64 -0
  287. package/src/skills/catalog-service.ts +35 -6
  288. package/src/skills/extension-importer.ts +97 -0
  289. package/src/skills/launch-skills.ts +19 -0
  290. package/src/skills/skill-frontmatter.ts +13 -0
  291. package/src/skills/source-importer.ts +3 -0
  292. package/src/startup-evidence.ts +20 -0
  293. package/src/supervisor/execution-inspection-ingestor.ts +55 -0
  294. package/src/supervisor/ipc-handler.ts +2 -0
  295. package/src/supervisor/worker-event-ingestor.ts +30 -14
  296. package/src/supervisor/worker-start-payload-builder.ts +17 -0
  297. package/src/supervisor/worker-supervisor.ts +3 -0
  298. package/src/test-helpers/prepared-fixture-start.ts +1 -0
  299. package/src/test-helpers/process-model-fixtures.ts +2 -0
  300. package/src/test-helpers/scoped-settings-fixtures.ts +126 -0
  301. package/src/test-helpers/skill-fixtures.ts +28 -0
  302. package/src/tool-approval-gate.ts +16 -0
  303. package/src/turn-progress.ts +3 -2
  304. package/src/turn-wait-service.ts +228 -0
  305. package/src/worker-runtime-profile-selection.ts +8 -1
  306. package/dist/app-MSJXFK33.js +0 -8
  307. package/dist/chunk-HK6BLLHA.js.map +0 -1
  308. package/dist/chunk-QCHS3X33.js.map +0 -1
  309. /package/dist/{app-MSJXFK33.js.map → app-JM4CBTND.js.map} +0 -0
@@ -8,6 +8,7 @@ import {
8
8
  SKILL_RESOURCE_OWNER,
9
9
  actorForRequest,
10
10
  appendProcessEvent,
11
+ applyMetadataPatch,
11
12
  applyProcessPatchField,
12
13
  applySubmittedProcessTitleToLaunchPlan,
13
14
  authenticateBrowserRequest,
@@ -30,6 +31,7 @@ import {
30
31
  createDatabase,
31
32
  createFileBackedProcessSessionSnapshotStore,
32
33
  createInMemoryDatabase,
34
+ createInspectionLineage,
33
35
  createLaunchPipeline,
34
36
  createOpaqueToken,
35
37
  createPiResourceBundleCache,
@@ -41,6 +43,7 @@ import {
41
43
  createWorkerStorageLayout,
42
44
  createWrites,
43
45
  defaultWorkerRuntimeProfile,
46
+ deferTurnWaitStarts,
44
47
  evaluateAtStableAvailabilityRevision,
45
48
  failLaunchRun,
46
49
  finishLaunchRun,
@@ -60,7 +63,9 @@ import {
60
63
  isHttpsOrLoopbackHttpUrl,
61
64
  isInternalEngineFailureCode,
62
65
  isLoopbackHttpUrl,
66
+ isPinnedModelSelection,
63
67
  isSafeSessionInstanceId,
68
+ isSkillModelInvocable,
64
69
  isTurnAvailableForProcessGraph,
65
70
  isWriteBuildFailure,
66
71
  isoFromNow,
@@ -70,7 +75,6 @@ import {
70
75
  logProcessEngineError,
71
76
  mergeProcessEventWindowsAscending,
72
77
  mergeWrites,
73
- normalizeActionRequest,
74
78
  normalizeContinueRequest,
75
79
  normalizeExternalEventDescription,
76
80
  normalizeExternalObservation,
@@ -78,6 +82,7 @@ import {
78
82
  normalizeProcessTitleInput,
79
83
  normalizeRecoveryModelRequest,
80
84
  now,
85
+ pendingTurnWait,
81
86
  positiveBound,
82
87
  prepareCreatedTurnStarts,
83
88
  presentLaunchPlanPreparationIssues,
@@ -97,6 +102,7 @@ import {
97
102
  resolveCommitMessageMetadata,
98
103
  resolveCurrentExecutionTurnRecordId,
99
104
  resolveDockerRegistryCredentials,
105
+ resolveKubernetesDockerIsolation,
100
106
  resolveProcessStorageSize,
101
107
  resolveRegisteredProviderOptions,
102
108
  resolveWorkerPiAgentDir,
@@ -108,27 +114,33 @@ import {
108
114
  sendLauncherRequestNormalizationError,
109
115
  sendScheduledActionMutationResponse,
110
116
  serializeProcessGraph,
117
+ skillMetadata,
111
118
  stampActorOnEvents,
112
119
  stampActorOnQueuedInputs,
113
120
  tokenExpiry,
114
121
  truncateTextAtWordBoundary,
122
+ turnWaitPredicate,
115
123
  updateProcessMetadata,
116
124
  validateConfig,
117
125
  validateConfiguredProviderOptions,
118
126
  validateCredentialStatus,
119
127
  verifyOpaqueToken,
120
- withTimeout
121
- } from "./chunk-HK6BLLHA.js";
128
+ withTimeout,
129
+ writeTurnWait
130
+ } from "./chunk-MBHRCQFE.js";
122
131
 
123
132
  // src/app.ts
124
- import path8 from "node:path";
133
+ import path10 from "node:path";
125
134
  import cookie from "@fastify/cookie";
126
135
  import {
127
136
  serializeResolvedExtensionEntries,
128
137
  setupServerExtensions
129
138
  } from "@leitwerk-dev/extension-runtime";
139
+ import { scopedSettingsCapability } from "@leitwerk-dev/process-sdk";
130
140
  import { DEFAULT_SESSION_TRANSFER_LIMITS } from "@leitwerk-dev/session-transfer";
131
141
  import { createPollingCoordinator, parseDurationMs as parseDurationMs8 } from "@leitwerk-dev/watcher-utils";
142
+ import { topicWikiCapability as topicWikiCapability2 } from "@leitwerk-dev/wiki/integration";
143
+ import { createTopicWikiRepo, registerWikiTools } from "@leitwerk-dev/wiki/server";
132
144
  import {
133
145
  cleanupRetainedProcessVolumes,
134
146
  planProcessVolumeRetentionCleanup
@@ -947,11 +959,18 @@ import {
947
959
  getExternalActionArmingId,
948
960
  getExternalActionTransitionTrigger,
949
961
  getExternalSourceTransitionId,
950
- isExternalTurnDefinition,
951
- isHumanTurnDefinition
962
+ isExternalTurnDefinition
952
963
  } from "@leitwerk-dev/process-sdk";
953
964
 
954
965
  // src/process-engine/decision.ts
966
+ function modelOverrideMetadata(input = {}) {
967
+ const { nextTurnModelProfileId, providerOptions } = input;
968
+ if (nextTurnModelProfileId === void 0 && providerOptions === void 0) return void 0;
969
+ return {
970
+ ...nextTurnModelProfileId !== void 0 ? { nextTurnModelProfileId } : {},
971
+ ...providerOptions !== void 0 ? { providerOptions } : {}
972
+ };
973
+ }
955
974
  function accept(input = {}) {
956
975
  return {
957
976
  ok: true,
@@ -984,6 +1003,7 @@ function selectedTurnRequiresWorker(processGraphs, process2) {
984
1003
  if (!process2.selectedTurnId || process2.lifecycleStatus !== "active") {
985
1004
  return false;
986
1005
  }
1006
+ if (pendingTurnWait({ metadata: process2.metadata ?? null })) return false;
987
1007
  const turn = process2.processId ? processGraphs?.get(process2.processId)?.turns.get(process2.selectedTurnId)?.definition : void 0;
988
1008
  return turn ? isWorkerOwnedTurnType(turn.kind) : true;
989
1009
  }
@@ -1706,9 +1726,6 @@ function createExternalSourceService(deps) {
1706
1726
  });
1707
1727
  return armed;
1708
1728
  }
1709
- if (!isHumanTurnDefinition(turnDef) && turnDef.kind !== "automatic") {
1710
- return [];
1711
- }
1712
1729
  for (const [externalActionId, action] of Object.entries(turnDef.externalActions ?? {})) {
1713
1730
  if (action.when && !action.when({ ...context })) {
1714
1731
  continue;
@@ -1778,14 +1795,13 @@ function createExternalSourceService(deps) {
1778
1795
  }
1779
1796
  for (const [turnId, binding2] of processDef.turns) {
1780
1797
  const turnDef = binding2.definition;
1781
- if (isHumanTurnDefinition(turnDef) || turnDef.kind === "automatic") {
1798
+ if (turnDef.kind !== "external") {
1782
1799
  for (const [externalActionId, action] of Object.entries(turnDef.externalActions ?? {})) {
1783
1800
  if (getExternalActionArmingId({ turnId, externalActionId }) === armingId) {
1784
1801
  return { turnId, externalActionId, sourceKind: action.source.kind };
1785
1802
  }
1786
1803
  }
1787
- }
1788
- if (isExternalTurnDefinition(turnDef)) {
1804
+ } else {
1789
1805
  for (const [index, transition] of turnDef.transitions.entries()) {
1790
1806
  const id = getExternalSourceTransitionId({
1791
1807
  turnId,
@@ -1955,6 +1971,13 @@ function createExternalSourceService(deps) {
1955
1971
  );
1956
1972
  return accept({ writes, data: { ok: false, code: failure2.code } });
1957
1973
  };
1974
+ const targetTurn = arming.transition.to ? ctx.deps.processGraphs.get(ctx.process.processId)?.turns.get(arming.transition.to)?.definition : void 0;
1975
+ const wakesWorker = targetTurn?.kind === "llm" || targetTurn?.kind === "automatic";
1976
+ if (wakesWorker && !targetTurn.waitFor)
1977
+ return reject(
1978
+ "external_readiness_required",
1979
+ "External worker targets must declare waitFor"
1980
+ );
1958
1981
  const effectWrites = await buildExternalSourceEffectWrites({
1959
1982
  arming,
1960
1983
  fireInput: input.input,
@@ -2039,6 +2062,10 @@ function createExternalSourceService(deps) {
2039
2062
  );
2040
2063
  }
2041
2064
  }
2065
+ if (wakesWorker && !publishedInput) {
2066
+ externalWrites.turnRecordWrites = [];
2067
+ externalWrites.turnAnnotationWrites = [];
2068
+ }
2042
2069
  for (const pendingFireId of input.pendingFireIds ?? []) {
2043
2070
  externalWrites.pendingExternalSourceFireWrites.push({
2044
2071
  kind: "delete",
@@ -2118,6 +2145,21 @@ function createExternalSourceService(deps) {
2118
2145
  refreshedAt: recordedAt
2119
2146
  };
2120
2147
  const writes = createWrites();
2148
+ if (input.state !== void 0) {
2149
+ const definition = ctx.deps.processGraphs.get(ctx.process.processId);
2150
+ if (!definition) return reject("process_not_found", "Process definition is unavailable");
2151
+ try {
2152
+ const state = definition.stateCodec.parse(input.state);
2153
+ applyProcessPatchField(
2154
+ writes,
2155
+ ctx.process,
2156
+ "stateJson",
2157
+ JSON.stringify(definition.stateCodec.serialize(state))
2158
+ );
2159
+ } catch {
2160
+ return reject("invalid_process_state", "Invalid observation state");
2161
+ }
2162
+ }
2121
2163
  writes.turnAnnotationWrites.push(
2122
2164
  previous ? { kind: "update", id: previous.id, input: { payload, updatedAt: recordedAt } } : {
2123
2165
  kind: "create",
@@ -3354,6 +3396,12 @@ function createProjectMutationService(deps) {
3354
3396
  };
3355
3397
  }
3356
3398
 
3399
+ // src/skills/launch-skills.ts
3400
+ function resolveLaunchSkills(deps, processId, selectedSkillIds = []) {
3401
+ const defaults = deps.skillDefaults?.process_configs?.[processId]?.default_skills ?? deps.skillDefaults?.default_skills ?? [];
3402
+ return deps.skills.resolveActive([.../* @__PURE__ */ new Set([...defaults, ...selectedSkillIds])]);
3403
+ }
3404
+
3357
3405
  // src/process-launch-executor.ts
3358
3406
  function mapLaunchStartFailure(result) {
3359
3407
  if (isInternalEngineFailureCode(result.code)) {
@@ -3404,8 +3452,8 @@ function createLaunchProjects(deps, process2, launchPlan) {
3404
3452
  );
3405
3453
  }
3406
3454
  function isSqliteConstraintError(error) {
3407
- const record3 = error;
3408
- return record3?.code === "SQLITE_CONSTRAINT_PRIMARYKEY" || record3?.code === "SQLITE_CONSTRAINT_UNIQUE" || typeof record3?.message === "string" && /sqlite_constraint|unique constraint/i.test(record3.message);
3455
+ const record4 = error;
3456
+ return record4?.code === "SQLITE_CONSTRAINT_PRIMARYKEY" || record4?.code === "SQLITE_CONSTRAINT_UNIQUE" || typeof record4?.message === "string" && /sqlite_constraint|unique constraint/i.test(record4.message);
3409
3457
  }
3410
3458
  function toLaunchFailureBody(error, context) {
3411
3459
  const message = error instanceof Error ? error.message : "Failed to create process from launch plan";
@@ -3419,6 +3467,7 @@ function toLaunchFailureBody(error, context) {
3419
3467
  };
3420
3468
  }
3421
3469
  function commitProcessLaunch(deps, launchPlan, futureExecutionPlan, resourceSelections = [], launchIntent, launchRunId, relation, actor) {
3470
+ if (launchPlan.preview) throw new Error("Launcher previews cannot be committed");
3422
3471
  return deps.transaction((repos) => {
3423
3472
  if (launchRunId) {
3424
3473
  repos.launchRuns.saveReplay(launchRunId, {
@@ -3568,9 +3617,9 @@ async function createProcessFromLaunchPlanWithDisposition(deps, launchPlan, opts
3568
3617
  };
3569
3618
  }
3570
3619
  let resourceSelections = opts?.resourceSelections;
3571
- if (!resourceSelections && launchPlan.skillIds) {
3620
+ if (resourceSelections === void 0) {
3572
3621
  try {
3573
- resourceSelections = deps.skills.resolveActive(launchPlan.skillIds);
3622
+ resourceSelections = resolveLaunchSkills(deps, launchPlan.processId, launchPlan.skillIds);
3574
3623
  } catch (error) {
3575
3624
  return {
3576
3625
  ok: false,
@@ -3771,7 +3820,8 @@ async function projectFutureExecutionModelState(deps, execution) {
3771
3820
  return projectLaunchPlanModelState(parsed2.value.launchPlan, {
3772
3821
  policy: deps.policy,
3773
3822
  availability: deps.availability,
3774
- detectedAt: now2().toISOString()
3823
+ detectedAt: now2().toISOString(),
3824
+ existingBlockedReason: execution.blockedReason
3775
3825
  });
3776
3826
  }
3777
3827
  if (!execution.instanceId || !execution.actionId) return null;
@@ -3799,7 +3849,8 @@ async function projectFutureExecutionModelState(deps, execution) {
3799
3849
  turnId: preflight.candidateSelectedTurnId,
3800
3850
  overrideModelProfileId: parsed.value.nextTurnModelProfileId,
3801
3851
  overrideProvided: parsed.value.nextTurnModelProfileId !== null,
3802
- detectedAt: now2().toISOString()
3852
+ detectedAt: now2().toISOString(),
3853
+ existingBlockedReason: execution.blockedReason
3803
3854
  });
3804
3855
  }
3805
3856
  function sameModelPolicyState(left, right) {
@@ -4099,7 +4150,7 @@ function createFutureExecutionExecutor(deps) {
4099
4150
  if (!latest || latest.nextRunAt > asOf) {
4100
4151
  return;
4101
4152
  }
4102
- if (!latest.modelSelection && deps.processGraphs && deps.processActionRegistry && deps.turnRecords) {
4153
+ if ((!latest.modelSelection || latest.kind === "action" && !isPinnedModelSelection(latest.modelSelection)) && deps.processGraphs && deps.processActionRegistry && deps.turnRecords) {
4103
4154
  const projected = await projectFutureExecutionModelState(
4104
4155
  {
4105
4156
  processes: deps.processes,
@@ -4259,9 +4310,9 @@ function applyStoredLaunchPlanModelConfig(launchPlan, storedProcessInput) {
4259
4310
  function invalidOutcome(code, message) {
4260
4311
  return { kind: "invalid", issues: [{ code, message }] };
4261
4312
  }
4262
- function resolveSelectedSkills(skills, ids) {
4313
+ function resolveSelectedSkills(deps, processId, ids) {
4263
4314
  try {
4264
- return { ok: true, value: skills.resolveActive(ids) };
4315
+ return { ok: true, value: resolveLaunchSkills(deps, processId, ids) };
4265
4316
  } catch (error) {
4266
4317
  return {
4267
4318
  ok: false,
@@ -4295,22 +4346,47 @@ function launchFailureOutcome(result) {
4295
4346
  code: issue.code
4296
4347
  } : { kind: "failed", issue };
4297
4348
  }
4298
- function resolveScheduledLaunchUpdateRequest(execution, request, existingPayload) {
4349
+ function preservedScheduleSkills(payload, selectedSkillIds) {
4350
+ if (selectedSkillIds === void 0) return payload.resourceSelections;
4351
+ const previous = new Set(payload.selectedSkillIds);
4352
+ const selected = new Set(selectedSkillIds);
4353
+ return previous.size === selected.size && [...selected].every((id) => previous.has(id)) ? payload.resourceSelections : void 0;
4354
+ }
4355
+ function normalizeScheduledLaunchUpdate(execution, request, expectedLauncherId) {
4356
+ const parsed = parseFutureLaunchPayloadJson3(execution.payloadJson);
4357
+ if (!parsed.ok)
4358
+ return {
4359
+ ok: false,
4360
+ outcome: invalidOutcome("invalid_payload", "Scheduled launch payload is invalid")
4361
+ };
4362
+ const payload = parsed.value;
4363
+ const launcherId = execution.launcherId ?? payload.launchPlan.launcherId;
4364
+ if (expectedLauncherId !== void 0 && launcherId !== expectedLauncherId)
4365
+ return {
4366
+ ok: false,
4367
+ outcome: invalidOutcome("invalid_schedule", "Schedule belongs to another launcher")
4368
+ };
4299
4369
  const schedule = request.scheduleProvided ? { ok: true, value: request.schedule } : resolveStoredScheduleRequest(execution);
4300
- if (!schedule.ok) return schedule;
4370
+ if (!schedule.ok)
4371
+ return { ok: false, outcome: { kind: "invalid", issues: [schedule.issue] } };
4301
4372
  return {
4302
4373
  ok: true,
4303
4374
  value: {
4304
- title: request.titleProvided ? request.title : existingPayload.launchPlan.processInput.title,
4305
- titleProvided: true,
4306
- launcherInput: request.launcherInputProvided ? request.launcherInput : existingPayload.launcherInput,
4307
- launcherInputProvided: true,
4308
- skillIds: request.skillIds ?? existingPayload.selectedSkillIds,
4309
- modelConfig: request.modelConfigProvided ? request.modelConfig : existingPayload.modelConfig,
4310
- modelConfigProvided: request.modelConfigProvided,
4311
- schedule: schedule.value,
4312
- scheduleProvided: true,
4313
- actor: existingPayload.actor
4375
+ launcherId,
4376
+ request: {
4377
+ title: request.titleProvided ? request.title : payload.launchPlan.processInput.title,
4378
+ titleProvided: true,
4379
+ launcherInput: request.launcherInputProvided ? request.launcherInput : payload.launcherInput,
4380
+ launcherInputProvided: true,
4381
+ skillIds: request.skillIds ?? payload.selectedSkillIds,
4382
+ modelConfig: request.modelConfigProvided ? request.modelConfig : payload.modelConfig,
4383
+ modelConfigProvided: request.modelConfigProvided,
4384
+ schedule: schedule.value,
4385
+ scheduleProvided: true,
4386
+ actor: payload.actor
4387
+ },
4388
+ baseLaunchPlan: payload.launchPlan,
4389
+ resourceSelections: preservedScheduleSkills(payload, request.skillIds)
4314
4390
  }
4315
4391
  };
4316
4392
  }
@@ -4364,6 +4440,7 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4364
4440
  return { ok: true, launchPlan, modelState, schedule: schedule.value };
4365
4441
  }
4366
4442
  async function persistPreparedLaunch(input) {
4443
+ if (input.launchPlan.preview) throw new Error("Launcher previews cannot be committed");
4367
4444
  if (input.schedule.mode === "now") throw new Error("Immediate launches cannot be persisted");
4368
4445
  const values = {
4369
4446
  scheduleKind: input.schedule.mode,
@@ -4405,7 +4482,7 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4405
4482
  };
4406
4483
  const resolved = input.resolvedLauncher ? { ok: true, launcher: input.resolvedLauncher } : await deps.launcherService.resolveUiLauncher(input.launcherId, input.request.launcherInput);
4407
4484
  if (!resolved.ok) return { ok: false, outcome: launcherResolutionFailure(resolved) };
4408
- const resourceSelections = input.resourceSelections ? { ok: true, value: input.resourceSelections } : resolveSelectedSkills(deps.skills, input.request.skillIds ?? []);
4485
+ const resourceSelections = input.resourceSelections !== void 0 ? { ok: true, value: input.resourceSelections } : resolveSelectedSkills(deps, resolved.launcher.processId, input.request.skillIds ?? []);
4409
4486
  if (!resourceSelections.ok) return { ok: false, outcome: resourceSelections.outcome };
4410
4487
  const baseLaunchPlan = input.request.modelConfigProvided ? clearLaunchPlanModelConfig(resolved.launcher.launchPlan) : input.baseLaunchPlan ? applyStoredLaunchPlanModelConfig(
4411
4488
  resolved.launcher.launchPlan,
@@ -4445,23 +4522,19 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4445
4522
  });
4446
4523
  if (!deps.launcherService)
4447
4524
  return failure2({ kind: "unavailable", reason: "Launcher service is not available" });
4448
- const parsed = parseFutureLaunchPayloadJson3(existing.payloadJson);
4449
- if (!parsed.ok)
4450
- return failure2(invalidOutcome("invalid_payload", "Scheduled launch payload is invalid"));
4451
- const launchRequest = resolveScheduledLaunchUpdateRequest(existing, request, parsed.value);
4452
- if (!launchRequest.ok) return failure2({ kind: "invalid", issues: [launchRequest.issue] });
4525
+ const update = normalizeScheduledLaunchUpdate(existing, request);
4526
+ if (!update.ok) return failure2(update.outcome);
4453
4527
  const resolved = await deps.launcherService.resolveUiLauncher(
4454
- existing.launcherId ?? parsed.value.launchPlan.launcherId,
4455
- launchRequest.value.launcherInput
4528
+ update.value.launcherId,
4529
+ update.value.request.launcherInput
4456
4530
  );
4457
4531
  if (!resolved.ok) return failure2(launcherResolutionFailure(resolved));
4458
4532
  return {
4459
4533
  kind: "resolved",
4460
4534
  value: {
4461
- payload: parsed.value,
4462
- request: launchRequest.value,
4535
+ ...update.value,
4463
4536
  launcher: resolved.launcher,
4464
- actor: actor ?? launchRequest.value.actor ?? SYSTEM_ACTOR
4537
+ actor: actor ?? update.value.request.actor ?? SYSTEM_ACTOR
4465
4538
  }
4466
4539
  };
4467
4540
  },
@@ -4478,10 +4551,8 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4478
4551
  },
4479
4552
  async prepare(resolved) {
4480
4553
  const prepared = await prepareLaunchInternal({
4554
+ ...resolved,
4481
4555
  launcherId: resolved.launcher.launcherId,
4482
- request: resolved.request,
4483
- baseLaunchPlan: resolved.payload.launchPlan,
4484
- resourceSelections: request.skillIds ? void 0 : resolved.payload.resourceSelections,
4485
4556
  operationTime,
4486
4557
  resolvedLauncher: resolved.launcher
4487
4558
  });
@@ -4560,6 +4631,15 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4560
4631
  return {
4561
4632
  /** @internal */
4562
4633
  async prepareLaunch(launcherId, request, opts) {
4634
+ if (opts?.futureExecutionId !== void 0) {
4635
+ const existing = deps.futureExecutions.getById(opts.futureExecutionId);
4636
+ if (!existing || existing.kind !== "launch") {
4637
+ return { ok: false, outcome: { kind: "not_found", target: "launch" } };
4638
+ }
4639
+ const update = normalizeScheduledLaunchUpdate(existing, request, launcherId);
4640
+ if (!update.ok) return update;
4641
+ return prepareLaunchInternal({ ...update.value, resolvedLauncher: opts.resolvedLauncher });
4642
+ }
4563
4643
  return prepareLaunchInternal({
4564
4644
  launcherId,
4565
4645
  request,
@@ -4634,23 +4714,14 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4634
4714
  if (!existing || existing.kind !== "launch") return { kind: "not_found", target: "launch" };
4635
4715
  if (request.scheduleProvided && request.schedule.mode === "now")
4636
4716
  return launchScheduledNow(existing, request, operationTime, opts?.actor);
4637
- const parsed = parseFutureLaunchPayloadJson3(existing.payloadJson);
4638
- if (!parsed.ok)
4639
- return invalidOutcome("invalid_payload", "Scheduled launch payload is invalid");
4640
- const launchRequest = resolveScheduledLaunchUpdateRequest(existing, request, parsed.value);
4641
- if (!launchRequest.ok) return { kind: "invalid", issues: [launchRequest.issue] };
4642
- const prepared = await prepareLaunchInternal({
4643
- launcherId: existing.launcherId ?? parsed.value.launchPlan.launcherId,
4644
- request: launchRequest.value,
4645
- baseLaunchPlan: parsed.value.launchPlan,
4646
- resourceSelections: request.skillIds ? void 0 : parsed.value.resourceSelections,
4647
- operationTime
4648
- });
4717
+ const update = normalizeScheduledLaunchUpdate(existing, request);
4718
+ if (!update.ok) return update.outcome;
4719
+ const prepared = await prepareLaunchInternal({ ...update.value, operationTime });
4649
4720
  if (!prepared.ok) return prepared.outcome;
4650
4721
  return persistPreparedLaunch({
4651
4722
  ...prepared.prepared,
4652
4723
  existing,
4653
- actor: opts?.actor ?? launchRequest.value.actor ?? SYSTEM_ACTOR
4724
+ actor: opts?.actor ?? update.value.request.actor ?? SYSTEM_ACTOR
4654
4725
  });
4655
4726
  });
4656
4727
  }
@@ -4662,6 +4733,7 @@ async function reconcileFutureExecutionModelBlocks(input) {
4662
4733
  let changed = 0;
4663
4734
  const effects = [];
4664
4735
  for (const candidate of input.futureExecutions.listAll()) {
4736
+ if (input.instanceId && candidate.instanceId !== input.instanceId) continue;
4665
4737
  if (candidate.modelSelection && input.profileIds && !input.profileIds.has(candidate.modelSelection.modelProfileId)) {
4666
4738
  continue;
4667
4739
  }
@@ -4711,6 +4783,10 @@ async function reconcileFutureExecutionModelBlocks(input) {
4711
4783
  const projected = evaluation.value;
4712
4784
  if (projected && !sameModelPolicyState(current, projected)) updateCurrent(projected);
4713
4785
  };
4786
+ if (!isPinnedModelSelection(current.modelSelection)) {
4787
+ await projectCurrent();
4788
+ return;
4789
+ }
4714
4790
  if (!current.modelSelection) {
4715
4791
  await projectCurrent();
4716
4792
  if (!current.modelSelection) return;
@@ -5201,6 +5277,7 @@ function startFutureExecutionScheduler(lifecycle, options = {}) {
5201
5277
  }
5202
5278
 
5203
5279
  // src/integration-tool-registry.ts
5280
+ import { resolveJsonPointer } from "@leitwerk-dev/domain";
5204
5281
  import {
5205
5282
  bindExternalWrites
5206
5283
  } from "@leitwerk-dev/external-writes/internal";
@@ -5218,7 +5295,7 @@ import {
5218
5295
  getExternalSourceTransitionId as getExternalSourceTransitionId2,
5219
5296
  isAutomaticTurnDefinition,
5220
5297
  isExternalTurnDefinition as isExternalTurnDefinition2,
5221
- isHumanTurnDefinition as isHumanTurnDefinition2,
5298
+ isHumanTurnDefinition,
5222
5299
  resolveHumanTurnView,
5223
5300
  toProcessGraphView
5224
5301
  } from "@leitwerk-dev/process-sdk";
@@ -5250,28 +5327,6 @@ function resolveCurrentTurnForProcess(processDef, process2) {
5250
5327
  return { turnId: process2.selectedTurnId, turnDef: selectedTurn };
5251
5328
  }
5252
5329
  function listExternalTriggers(turnId, turnDef, ctx) {
5253
- if (isHumanTurnDefinition2(turnDef)) {
5254
- const view = resolveHumanTurnView({ turnId, turn: turnDef });
5255
- return [
5256
- ...view.externalTriggers.map((trigger) => ({
5257
- id: trigger.id,
5258
- kind: "human_action_external_trigger",
5259
- label: trigger.label,
5260
- description: trigger.description
5261
- })),
5262
- ...view.externalActions.filter((action) => {
5263
- const definition = turnDef.externalActions?.[action.externalActionId];
5264
- return !definition?.when || definition.when(ctx);
5265
- }).map((action) => ({
5266
- id: action.id,
5267
- externalActionId: action.externalActionId,
5268
- kind: action.sourceKind,
5269
- sourceKind: action.sourceKind,
5270
- label: action.label,
5271
- description: action.description
5272
- }))
5273
- ];
5274
- }
5275
5330
  if (isExternalTurnDefinition2(turnDef)) {
5276
5331
  return turnDef.transitions.map((transition, index) => ({
5277
5332
  id: getExternalSourceTransitionId2({ turnId, source: transition.source, index }),
@@ -5280,21 +5335,29 @@ function listExternalTriggers(turnId, turnDef, ctx) {
5280
5335
  description: transition.source.description ?? null
5281
5336
  }));
5282
5337
  }
5283
- if (isAutomaticTurnDefinition(turnDef) && ctx.process.lifecycleStatus === "waiting") {
5284
- return Object.entries(turnDef.externalActions ?? {}).filter(([, action]) => !action.when || action.when(ctx)).map(([externalActionId, action]) => ({
5338
+ if (!isHumanTurnDefinition(turnDef) && (!(isAutomaticTurnDefinition(turnDef) || turnDef.kind === "llm") || ctx.process.lifecycleStatus !== "waiting"))
5339
+ return [];
5340
+ const triggers = isHumanTurnDefinition(turnDef) ? resolveHumanTurnView({ turnId, turn: turnDef }).externalTriggers.map((trigger) => ({
5341
+ id: trigger.id,
5342
+ kind: "human_action_external_trigger",
5343
+ label: trigger.label,
5344
+ description: trigger.description
5345
+ })) : [];
5346
+ return [
5347
+ ...triggers,
5348
+ ...Object.entries(turnDef.externalActions ?? {}).filter(([, action]) => !action.when || action.when(ctx)).map(([externalActionId, action]) => ({
5285
5349
  id: getExternalActionArmingId2({ turnId, externalActionId }),
5286
5350
  externalActionId,
5287
5351
  kind: action.source.kind,
5288
5352
  sourceKind: action.source.kind,
5289
5353
  label: action.label ?? action.source.label ?? null,
5290
5354
  description: action.description ?? action.source.description ?? null
5291
- }));
5292
- }
5293
- return [];
5355
+ }))
5356
+ ];
5294
5357
  }
5295
5358
  function resolveCurrentVisibleActionForProcess(processDef, process2, actionId) {
5296
5359
  const currentTurn = resolveCurrentTurnForProcess(processDef, process2);
5297
- if (!currentTurn || !isHumanTurnDefinition2(currentTurn.turnDef)) {
5360
+ if (!currentTurn || !isHumanTurnDefinition(currentTurn.turnDef)) {
5298
5361
  return null;
5299
5362
  }
5300
5363
  const view = resolveHumanTurnView({ turnId: currentTurn.turnId, turn: currentTurn.turnDef });
@@ -5304,13 +5367,8 @@ function isTurnScopedActionForProcess(processDef, actionId) {
5304
5367
  if (!processDef) {
5305
5368
  return false;
5306
5369
  }
5307
- for (const [turnId, { definition: turnDef }] of processDef.turns) {
5308
- if (isHumanTurnDefinition2(turnDef)) {
5309
- const view = resolveHumanTurnView({ turnId, turn: turnDef });
5310
- if (view.actions.some((action) => action.actionId === actionId) || view.externalTriggers.some((trigger) => trigger.actionId === actionId)) {
5311
- return true;
5312
- }
5313
- }
5370
+ for (const { definition: turnDef } of processDef.turns.values()) {
5371
+ if (isHumanTurnDefinition(turnDef) && Object.hasOwn(turnDef.actions, actionId)) return true;
5314
5372
  }
5315
5373
  return false;
5316
5374
  }
@@ -5320,17 +5378,24 @@ function buildSelectedTurnSummaryForProcess(processDef, process2, projects = [])
5320
5378
  return null;
5321
5379
  }
5322
5380
  const { params: params2, state } = resolveProcessContextData(processDef, process2);
5381
+ const wait = pendingTurnWait(process2);
5323
5382
  return {
5324
5383
  turnId: currentTurn.turnId,
5325
5384
  kind: currentTurn.turnDef.kind,
5326
5385
  description: currentTurn.turnDef.description,
5327
- commentary: isHumanTurnDefinition2(currentTurn.turnDef) ? currentTurn.turnDef.commentary ?? null : null,
5386
+ commentary: isHumanTurnDefinition(currentTurn.turnDef) ? currentTurn.turnDef.commentary ?? null : null,
5328
5387
  externalTriggers: listExternalTriggers(currentTurn.turnId, currentTurn.turnDef, {
5329
5388
  process: process2,
5330
5389
  projects,
5331
5390
  params: params2,
5332
5391
  state
5333
- })
5392
+ }),
5393
+ ...wait?.status === "waiting" && process2.lifecycleStatus === "waiting" ? {
5394
+ readiness: {
5395
+ message: wait.message,
5396
+ nextCheckAt: wait.nextCheckAt > 0 ? new Date(wait.nextCheckAt).toISOString() : null
5397
+ }
5398
+ } : {}
5334
5399
  };
5335
5400
  }
5336
5401
  function resolveActionTarget(definition, processDef, process2) {
@@ -5363,7 +5428,7 @@ function resolveActionPreviewForProcess(processDef, process2, action, actionId)
5363
5428
  }
5364
5429
  function resolveTurnScopedActionForProcess(processDef, process2, actionId, source) {
5365
5430
  const currentTurn = resolveCurrentTurnForProcess(processDef, process2);
5366
- if (!currentTurn || !isHumanTurnDefinition2(currentTurn.turnDef)) return null;
5431
+ if (!currentTurn || !isHumanTurnDefinition(currentTurn.turnDef)) return null;
5367
5432
  const view = resolveHumanTurnView({ turnId: currentTurn.turnId, turn: currentTurn.turnDef });
5368
5433
  const action = view.actions.find((candidate) => candidate.actionId === actionId);
5369
5434
  if (!action) return null;
@@ -5414,7 +5479,7 @@ function buildProcessActionRegistry(catalog) {
5414
5479
  const def = serverDefs.get(processId);
5415
5480
  const processDef = processDefs.get(processId);
5416
5481
  const currentTurn = resolveCurrentTurnForProcess(processDef, ctx.process);
5417
- if (!def || !currentTurn || !isHumanTurnDefinition2(currentTurn.turnDef)) {
5482
+ if (!def || !currentTurn || !isHumanTurnDefinition(currentTurn.turnDef)) {
5418
5483
  return [];
5419
5484
  }
5420
5485
  const view = resolveHumanTurnView({
@@ -5532,6 +5597,7 @@ var ticketCapabilitySchema = v2.object({
5532
5597
  startTurnId: nonEmptyString,
5533
5598
  titlePath: v2.optional(v2.string()),
5534
5599
  descriptionPath: v2.optional(v2.string()),
5600
+ descriptionFormat: v2.optional(v2.picklist(["plain", "markdown"])),
5535
5601
  destinations: v2.optional(v2.unknown())
5536
5602
  });
5537
5603
  var destinationSummarySchema = v2.pipe(
@@ -5612,14 +5678,6 @@ function validateTicketCreationReceipt(value) {
5612
5678
  ...Object.hasOwn(receipt, "result") ? { result: receipt.result } : {}
5613
5679
  };
5614
5680
  }
5615
- function resolveJsonPointer(value, pointer) {
5616
- if (pointer === "") return value;
5617
- return pointer.slice(1).split("/").reduce((current, token) => {
5618
- if (!current || typeof current !== "object") return void 0;
5619
- const key = token.replaceAll("~1", "/").replaceAll("~0", "~");
5620
- return current[key];
5621
- }, value);
5622
- }
5623
5681
  var parseToolArgs = (value) => objectArg(value, "Integration tool arguments must be an object");
5624
5682
  function persistedTicketActor(value) {
5625
5683
  return parseSchema(persistedActorSchema, value, "Ticket creation actor is invalid");
@@ -5734,6 +5792,7 @@ var IntegrationToolRegistry = class {
5734
5792
  if (!definition) throw new Error(`Unknown integration tool '${name}'`);
5735
5793
  return {
5736
5794
  name: definition.name,
5795
+ ...definition.modelVisible === false ? { modelVisible: false } : {},
5737
5796
  description: definition.description,
5738
5797
  parameters: definition.capability?.kind === "ticket_creation" && definition.capability.destinations ? withTicketDestinationParameter(definition.parameters, destinations) : definition.parameters
5739
5798
  };
@@ -5752,6 +5811,9 @@ var IntegrationToolRegistry = class {
5752
5811
  return definition.execute(
5753
5812
  {
5754
5813
  ...ctx,
5814
+ reportProgress: (report) => {
5815
+ if (!controller.signal.aborted) ctx.reportProgress?.(report);
5816
+ },
5755
5817
  signal: controller.signal,
5756
5818
  externalWrites: bindExternalWrites(this.writes, ctx.process.id)
5757
5819
  },
@@ -5761,6 +5823,24 @@ var IntegrationToolRegistry = class {
5761
5823
  this.executions.set(ctx.idempotencyKey, { controller, promise });
5762
5824
  return promise;
5763
5825
  }
5826
+ /** Only trusted server extensions use this path; approval-gated ticket tools require worker IPC. */
5827
+ executeServer(name, args, ctx, signal) {
5828
+ const definition = this.tools.get(name);
5829
+ if (!definition || definition.capability)
5830
+ throw new Error(`Tool '${name}' is unavailable to server maintenance`);
5831
+ signal.throwIfAborted();
5832
+ return definition.execute(
5833
+ {
5834
+ ...ctx,
5835
+ signal,
5836
+ reportProgress: (report) => {
5837
+ if (!signal.aborted) ctx.reportProgress?.(report);
5838
+ },
5839
+ externalWrites: bindExternalWrites(this.writes, ctx.process.id)
5840
+ },
5841
+ definition.parse?.(args) ?? parseToolArgs(args)
5842
+ );
5843
+ }
5764
5844
  cancel(idempotencyKey) {
5765
5845
  const execution = this.executions.get(idempotencyKey);
5766
5846
  if (!execution) return false;
@@ -5804,13 +5884,18 @@ function createIntegrationToolRequestService(input) {
5804
5884
  if (process2.selectedTurnId !== turn.turnId) {
5805
5885
  return fail("Integration tool call targets a stale turn");
5806
5886
  }
5807
- const assertActive = () => {
5808
- if (signal.aborted) throw new Error("Integration tool execution cancelled");
5887
+ const isActive = () => {
5888
+ if (signal.aborted) return false;
5809
5889
  const current = input.repos.processes.getById(instanceId);
5810
5890
  const currentTurn = input.repos.turnRecords.getById(payload.turnRecordId);
5811
5891
  const start = current?.currentExecution?.kind === "worker_start" ? input.repos.turnStarts.getById(current.currentExecution.id) : null;
5812
- if (!current || currentTurn?.status !== "running" || current.selectedTurnId !== turn.turnId || start?.state.kind !== "accepted" || start.state.turnRecordId !== payload.turnRecordId)
5813
- throw new Error("Integration tool call targets a stale turn record");
5892
+ return Boolean(
5893
+ current && currentTurn?.status === "running" && currentTurn.instanceId === instanceId && current.selectedTurnId === turn.turnId && start?.state.kind === "accepted" && start.state.turnRecordId === payload.turnRecordId
5894
+ );
5895
+ };
5896
+ const assertActive = () => {
5897
+ if (signal.aborted) throw new Error("Integration tool execution cancelled");
5898
+ if (!isActive()) throw new Error("Integration tool call targets a stale turn record");
5814
5899
  };
5815
5900
  const authorizedTools = resolveTurnIntegrationToolNames(
5816
5901
  input.processActionRegistry,
@@ -5823,7 +5908,10 @@ function createIntegrationToolRequestService(input) {
5823
5908
  const projects = input.repos.projects.listByInstance(instanceId);
5824
5909
  const projectKey = typeof payload.args.projectKey === "string" ? payload.args.projectKey : null;
5825
5910
  const project = projectKey ? projects.find((candidate) => candidate.key === projectKey) ?? null : null;
5826
- if (projectKey && !project) return fail(`Unknown process project '${projectKey}'`);
5911
+ if (projectKey && !project)
5912
+ return fail(
5913
+ `Unknown process project '${projectKey}'. Available project keys: ${projects.map((candidate) => candidate.key).join(", ") || "(none)"}`
5914
+ );
5827
5915
  try {
5828
5916
  let ticketDestination;
5829
5917
  let executionArgs = payload.args;
@@ -5882,6 +5970,10 @@ function createIntegrationToolRequestService(input) {
5882
5970
  projects,
5883
5971
  turn,
5884
5972
  project,
5973
+ reportProgress: (report) => {
5974
+ if (isActive())
5975
+ input.reportProgress?.({ instanceId, turnRecordId: payload.turnRecordId, report });
5976
+ },
5885
5977
  ...ticketDestination ? { ticketDestination } : {},
5886
5978
  idempotencyKey: integrationToolIdempotencyKey({
5887
5979
  instanceId,
@@ -5932,6 +6024,18 @@ var StartProcess = defineOperation({
5932
6024
  kind: "start_process",
5933
6025
  label: "Start process",
5934
6026
  decide(ctx, input) {
6027
+ const restart = input.restart;
6028
+ if (restart && (ctx.process.lifecycleStatus !== "waiting" || ctx.process.currentExecution !== null || ctx.process.selectedTurnId !== restart.expected.turnId || ctx.process.paramsJson !== restart.expected.paramsJson || ctx.process.stateJson !== restart.expected.stateJson)) {
6029
+ return reject("restart_superseded", "The captured waiting process has changed");
6030
+ }
6031
+ if (restart && ctx.deps.isNewTurnBlocked?.(input.instanceId)) {
6032
+ return reject("session_transfer_in_progress", "A local session transfer is in progress");
6033
+ }
6034
+ const project = restart?.project ? ctx.deps.projects.getByInstanceAndKey(input.instanceId, restart.project.key) : null;
6035
+ if (restart?.project && (!project || project.baseBranch !== restart.project.expectedBaseBranch)) {
6036
+ return reject("restart_superseded", "The captured process repository has changed");
6037
+ }
6038
+ if (restart) JSON.parse(restart.stateJson);
5935
6039
  if (input.onlyIfUnstarted && (ctx.process.lifecycleStatus !== "discovered" || ctx.process.selectedTurnId !== null || ctx.process.currentExecution !== null)) {
5936
6040
  return noWrites();
5937
6041
  }
@@ -5941,6 +6045,12 @@ var StartProcess = defineOperation({
5941
6045
  trigger: "start"
5942
6046
  });
5943
6047
  if ("ok" in writes) return writes;
6048
+ if (restart) {
6049
+ applyProcessPatchField(writes, ctx.process, "stateJson", restart.stateJson);
6050
+ if (project && restart.project) {
6051
+ writes.projectWrite = { id: project.id, input: { baseBranch: restart.project.baseBranch } };
6052
+ }
6053
+ }
5944
6054
  stampActorOnEvents(writes, input.actor, "turn_selected");
5945
6055
  return accept({ writes });
5946
6056
  }
@@ -6338,9 +6448,17 @@ function createLaunchCoordinator(deps) {
6338
6448
  return bindLaunchPreparationChecks(attempt.preparationChecks, attempt.launchConfig);
6339
6449
  },
6340
6450
  async prepare(attempt) {
6451
+ const eventProfile = attempt.launchConfig.defaultModelProfileId;
6341
6452
  const prepared = await deps.launchPlans.prepare(
6342
6453
  withWatcherHandoffDedupKey(attempt.launchPlan, admissionKey),
6343
- { modelConfig: watcher.launchModelConfig, invalidModelConfig: "omit" }
6454
+ {
6455
+ modelConfig: {
6456
+ ...watcher.launchModelConfig,
6457
+ defaultModelProfileId: eventProfile ?? watcher.launchModelConfig.defaultModelProfileId
6458
+ },
6459
+ // Event selections express ticket/user intent. Never silently drop them.
6460
+ invalidModelConfig: eventProfile ? "reject" : "omit"
6461
+ }
6344
6462
  );
6345
6463
  return prepared.ok ? { ok: true, value: prepared.launchPlan } : {
6346
6464
  ok: false,
@@ -6479,15 +6597,24 @@ function buildLauncherModelConfigSchemaForLauncher(input) {
6479
6597
  })
6480
6598
  );
6481
6599
  }
6482
- function projectLauncherPreview(input, processId, modelConfig) {
6483
- return presentLauncherModelConfigPreview(
6600
+ function projectLauncherPreview(input, processId, modelConfig, plan) {
6601
+ const preview = presentLauncherModelConfigPreview(
6484
6602
  input.processModelPolicy.project({
6485
6603
  kind: "launcher_preview",
6604
+ plan,
6486
6605
  processId,
6487
6606
  modelConfig,
6488
6607
  availability: input.modelStatusCache.snapshot()
6489
6608
  })
6490
6609
  );
6610
+ const context = plan ? input.scopedSettingsService?.forLaunch(plan) : void 0;
6611
+ return {
6612
+ ...preview,
6613
+ ...context ? {
6614
+ settingsSubjectId: context.context.repository ?? "instance",
6615
+ settingsExplanations: context.explanations
6616
+ } : {}
6617
+ };
6491
6618
  }
6492
6619
  async function buildLauncherModelConfigPreviewForLauncher(input) {
6493
6620
  const launcher = findUiLauncherById(input.launcherService, input.launcherId);
@@ -6495,7 +6622,10 @@ async function buildLauncherModelConfigPreviewForLauncher(input) {
6495
6622
  let modelConfig = input.modelConfig;
6496
6623
  let resolved = null;
6497
6624
  try {
6498
- resolved = await input.launcherService.resolveUiLauncher(input.launcherId, input.launcherInput);
6625
+ resolved = await input.launcherService.resolveUiLauncherPreview(
6626
+ input.launcherId,
6627
+ input.launcherInput
6628
+ );
6499
6629
  } catch (error) {
6500
6630
  if (!input.ignoreResolveErrors) throw error;
6501
6631
  }
@@ -6516,7 +6646,12 @@ async function buildLauncherModelConfigPreviewForLauncher(input) {
6516
6646
  return {
6517
6647
  ok: true,
6518
6648
  launcher,
6519
- preview: projectLauncherPreview(input, launcher.processId, modelConfig)
6649
+ preview: projectLauncherPreview(
6650
+ input,
6651
+ launcher.processId,
6652
+ modelConfig,
6653
+ resolved?.ok ? resolved.launcher.launchPlan : void 0
6654
+ )
6520
6655
  };
6521
6656
  }
6522
6657
  function createLauncherModelConfigService(input) {
@@ -6681,12 +6816,12 @@ function encodeCredential(value) {
6681
6816
  }
6682
6817
  return encoded;
6683
6818
  }
6684
- function decodeCredential(provider, record3) {
6819
+ function decodeCredential(provider, record4) {
6685
6820
  const definition = provider.definition.credential;
6686
6821
  if (!definition) throw new Error(`Provider '${provider.id}' does not declare credentials`);
6687
6822
  let value;
6688
6823
  try {
6689
- value = JSON.parse(record3.payload);
6824
+ value = JSON.parse(record4.payload);
6690
6825
  } catch (error) {
6691
6826
  throw new Error(`Provider credential payload for '${provider.id}' is not valid JSON`, {
6692
6827
  cause: error
@@ -6722,10 +6857,10 @@ function materializeSecrets(provider, credential, options) {
6722
6857
  function createModelProviderCredentialService(input) {
6723
6858
  const status = (provider) => {
6724
6859
  if (!provider.definition.credential) return { available: true, revision: null };
6725
- const record3 = input.repo.get(provider.id);
6726
- if (!record3) return { available: false, revision: null };
6727
- decodeCredential(provider, record3);
6728
- return { available: true, revision: record3.revision };
6860
+ const record4 = input.repo.get(provider.id);
6861
+ if (!record4) return { available: false, revision: null };
6862
+ decodeCredential(provider, record4);
6863
+ return { available: true, revision: record4.revision };
6729
6864
  };
6730
6865
  return {
6731
6866
  initialize() {
@@ -6745,12 +6880,12 @@ function createModelProviderCredentialService(input) {
6745
6880
  resolve(providerId, options = {}) {
6746
6881
  const provider = input.registry.require(providerId);
6747
6882
  const definition = provider.definition.credential;
6748
- const record3 = definition ? input.repo.get(providerId) : null;
6749
- if (definition && !record3) return null;
6750
- const credential = record3 ? decodeCredential(provider, record3) : null;
6883
+ const record4 = definition ? input.repo.get(providerId) : null;
6884
+ if (definition && !record4) return null;
6885
+ const credential = record4 ? decodeCredential(provider, record4) : null;
6751
6886
  return {
6752
6887
  providerId,
6753
- revision: record3 ? record3.revision : null,
6888
+ revision: record4 ? record4.revision : null,
6754
6889
  values: materializeSecrets(provider, credential, options)
6755
6890
  };
6756
6891
  },
@@ -6839,23 +6974,23 @@ function createModelStatusCache(input) {
6839
6974
  );
6840
6975
  }
6841
6976
  const profileIds = /* @__PURE__ */ new Set();
6842
- for (const profile of input.modelProfiles) {
6843
- if (profileIds.has(profile.id)) throw new Error(`Duplicate model profile id '${profile.id}'`);
6844
- profileIds.add(profile.id);
6845
- input.registry.require(profile.provider);
6977
+ for (const profile2 of input.modelProfiles) {
6978
+ if (profileIds.has(profile2.id)) throw new Error(`Duplicate model profile id '${profile2.id}'`);
6979
+ profileIds.add(profile2.id);
6980
+ input.registry.require(profile2.provider);
6846
6981
  }
6847
6982
  const now2 = input.now ?? (() => /* @__PURE__ */ new Date());
6848
6983
  const orderedProfiles = [...input.modelProfiles];
6849
- const profilesByProvider = Map.groupBy(orderedProfiles, (profile) => profile.provider);
6984
+ const profilesByProvider = Map.groupBy(orderedProfiles, (profile2) => profile2.provider);
6850
6985
  let revision = 0;
6851
6986
  let inFlight = null;
6852
6987
  let statuses = new Map(
6853
- orderedProfiles.map((profile) => [
6854
- profile.id,
6988
+ orderedProfiles.map((profile2) => [
6989
+ profile2.id,
6855
6990
  {
6856
- profileId: profile.id,
6857
- providerId: profile.provider,
6858
- modelId: profile.model_id,
6991
+ profileId: profile2.id,
6992
+ providerId: profile2.provider,
6993
+ modelId: profile2.model_id,
6859
6994
  availability: "stale",
6860
6995
  safeReason: "Model status has not been refreshed",
6861
6996
  checkedAt: null,
@@ -6883,7 +7018,7 @@ function createModelStatusCache(input) {
6883
7018
  revision,
6884
7019
  capturedAt: at.toISOString(),
6885
7020
  profiles: orderedProfiles.map(
6886
- (profile) => statuses.get(profile.id)
7021
+ (profile2) => statuses.get(profile2.id)
6887
7022
  ),
6888
7023
  availabilityTransitions
6889
7024
  };
@@ -6905,9 +7040,9 @@ function createModelStatusCache(input) {
6905
7040
  const statuses2 = await provider.definition.models({
6906
7041
  config: provider.config,
6907
7042
  credentialStatus,
6908
- configuredModels: profiles.map((profile) => ({
6909
- profileId: profile.id,
6910
- modelId: profile.model_id
7043
+ configuredModels: profiles.map((profile2) => ({
7044
+ profileId: profile2.id,
7045
+ modelId: profile2.model_id
6911
7046
  }))
6912
7047
  });
6913
7048
  return validateProviderStatuses(provider, statuses2);
@@ -6928,14 +7063,14 @@ function createModelStatusCache(input) {
6928
7063
  };
6929
7064
  }
6930
7065
  return new Map(
6931
- profiles.map((profile) => {
6932
- const status = providerStatuses?.get(profile.model_id) ?? fallback;
7066
+ profiles.map((profile2) => {
7067
+ const status = providerStatuses?.get(profile2.model_id) ?? fallback;
6933
7068
  return [
6934
- profile.id,
7069
+ profile2.id,
6935
7070
  {
6936
- profileId: profile.id,
6937
- providerId: profile.provider,
6938
- modelId: profile.model_id,
7071
+ profileId: profile2.id,
7072
+ providerId: profile2.provider,
7073
+ modelId: profile2.model_id,
6939
7074
  ...status
6940
7075
  }
6941
7076
  ];
@@ -6961,13 +7096,13 @@ function createModelStatusCache(input) {
6961
7096
  }
6962
7097
  const transitions = [];
6963
7098
  let policyChanged = false;
6964
- for (const profile of orderedProfiles) {
6965
- const previous = statuses.get(profile.id);
6966
- const current = next.get(profile.id);
7099
+ for (const profile2 of orderedProfiles) {
7100
+ const previous = statuses.get(profile2.id);
7101
+ const current = next.get(profile2.id);
6967
7102
  if (!previous || !current) continue;
6968
7103
  if (previous.availability !== current.availability) {
6969
7104
  transitions.push({
6970
- profileId: profile.id,
7105
+ profileId: profile2.id,
6971
7106
  from: previous.availability,
6972
7107
  to: current.availability
6973
7108
  });
@@ -7024,24 +7159,24 @@ function validatePiReferences(owned, contribution) {
7024
7159
  }
7025
7160
  function validateConfiguredProfiles(providers, profiles, titleModelProfileId) {
7026
7161
  const profilesById = /* @__PURE__ */ new Map();
7027
- for (const profile of profiles) {
7028
- if (profilesById.has(profile.id)) {
7029
- throw new Error(`Duplicate model profile id '${profile.id}'`);
7162
+ for (const profile2 of profiles) {
7163
+ if (profilesById.has(profile2.id)) {
7164
+ throw new Error(`Duplicate model profile id '${profile2.id}'`);
7030
7165
  }
7031
- profilesById.set(profile.id, profile);
7032
- const provider = providers.get(profile.provider);
7166
+ profilesById.set(profile2.id, profile2);
7167
+ const provider = providers.get(profile2.provider);
7033
7168
  if (!provider) {
7034
7169
  throw new Error(
7035
- `Model profile '${profile.id}' names unknown provider '${profile.provider}'; load its owning extension before configuring the profile`
7170
+ `Model profile '${profile2.id}' names unknown provider '${profile2.provider}'; load its owning extension before configuring the profile`
7036
7171
  );
7037
7172
  }
7038
7173
  const optionIssues = validateConfiguredProviderOptions({
7039
7174
  provider,
7040
- values: profile.provider_options ?? {}
7175
+ values: profile2.provider_options ?? {}
7041
7176
  });
7042
7177
  if (optionIssues.length > 0) {
7043
7178
  throw new Error(
7044
- `Invalid provider_options for model profile '${profile.id}': ${optionIssues.map((issue) => issue.message).join("; ")}`
7179
+ `Invalid provider_options for model profile '${profile2.id}': ${optionIssues.map((issue) => issue.message).join("; ")}`
7045
7180
  );
7046
7181
  }
7047
7182
  }
@@ -7150,7 +7285,7 @@ async function createModelProviderServerAdapterRegistry(input) {
7150
7285
  }
7151
7286
  adapters.set(provider.id, adapter);
7152
7287
  }
7153
- const profilesById = new Map(input.modelProfiles.map((profile) => [profile.id, profile]));
7288
+ const profilesById = new Map(input.modelProfiles.map((profile2) => [profile2.id, profile2]));
7154
7289
  return {
7155
7290
  get(providerId) {
7156
7291
  return adapters.get(providerId) ?? null;
@@ -7161,18 +7296,18 @@ async function createModelProviderServerAdapterRegistry(input) {
7161
7296
  return adapter;
7162
7297
  },
7163
7298
  async generateText(request) {
7164
- const profile = profilesById.get(request.profileId);
7165
- if (!profile) throw new Error(`Unknown model profile '${request.profileId}'`);
7166
- const provider = input.registry.require(profile.provider);
7299
+ const profile2 = profilesById.get(request.profileId);
7300
+ if (!profile2) throw new Error(`Unknown model profile '${request.profileId}'`);
7301
+ const provider = input.registry.require(profile2.provider);
7167
7302
  const adapter = adapters.get(provider.id);
7168
7303
  if (!adapter) throw new Error(`Model provider '${provider.id}' has no server adapter`);
7169
7304
  const resolvedOptions = resolveRegisteredProviderOptions({
7170
7305
  provider,
7171
- profileDefaults: profile.provider_options ?? {}
7306
+ profileDefaults: profile2.provider_options ?? {}
7172
7307
  });
7173
7308
  if (!resolvedOptions.ok) {
7174
7309
  throw new Error(
7175
- `Invalid provider options for model profile '${profile.id}': ${resolvedOptions.issues.map((issue) => issue.message).join("; ")}`
7310
+ `Invalid provider options for model profile '${profile2.id}': ${resolvedOptions.issues.map((issue) => issue.message).join("; ")}`
7176
7311
  );
7177
7312
  }
7178
7313
  const credential = input.credentials.resolve(provider.id, resolvedOptions.value);
@@ -7181,8 +7316,8 @@ async function createModelProviderServerAdapterRegistry(input) {
7181
7316
  }
7182
7317
  return await adapter.generateText({
7183
7318
  providerId: provider.id,
7184
- modelId: profile.model_id,
7185
- thinkingLevel: profile.thinking_level ?? "off",
7319
+ modelId: profile2.model_id,
7320
+ thinkingLevel: profile2.thinking_level ?? "off",
7186
7321
  prompt: request.prompt,
7187
7322
  systemPrompt: request.systemPrompt,
7188
7323
  maxTokens: request.maxTokens,
@@ -7278,6 +7413,22 @@ function maybeBroadcastErrorAttentionToast(deps, result, input = {}) {
7278
7413
  }
7279
7414
 
7280
7415
  // src/process-engine/writes/build-process-abort-writes.ts
7416
+ function supersedeExecution(writes, record4, start, recordedAt) {
7417
+ writes.mappedRunWrites.push({ kind: "abort_active" });
7418
+ if (start?.state.kind === "starting")
7419
+ writes.turnStartWrites.push({
7420
+ kind: "cas_state",
7421
+ id: start.id,
7422
+ expectedKind: "starting",
7423
+ state: { kind: "superseded", start: start.state.start }
7424
+ });
7425
+ if (record4?.status === "running")
7426
+ writes.turnRecordWrites.push({
7427
+ kind: "update",
7428
+ id: record4.id,
7429
+ input: { status: "superseded", endedAt: recordedAt ?? (/* @__PURE__ */ new Date()).toISOString() }
7430
+ });
7431
+ }
7281
7432
  function buildAbortProcessWrites(input) {
7282
7433
  const writes = buildTurnSelectionWrites(input.processGraphs, input.process, {
7283
7434
  fromTurnId: input.process.selectedTurnId,
@@ -7288,25 +7439,7 @@ function buildAbortProcessWrites(input) {
7288
7439
  if (isWriteBuildFailure(writes)) {
7289
7440
  return writes;
7290
7441
  }
7291
- writes.mappedRunWrites.push({ kind: "abort_active" });
7292
- if (input.currentWorkerStart?.state.kind === "starting") {
7293
- writes.turnStartWrites.push({
7294
- kind: "cas_state",
7295
- id: input.currentWorkerStart.id,
7296
- expectedKind: "starting",
7297
- state: { kind: "superseded", start: input.currentWorkerStart.state.start }
7298
- });
7299
- }
7300
- if (input.activeTurnRecord?.status === "running") {
7301
- writes.turnRecordWrites.push({
7302
- kind: "update",
7303
- id: input.activeTurnRecord.id,
7304
- input: {
7305
- status: "superseded",
7306
- endedAt: input.recordedAt ?? (/* @__PURE__ */ new Date()).toISOString()
7307
- }
7308
- });
7309
- }
7442
+ supersedeExecution(writes, input.activeTurnRecord, input.currentWorkerStart, input.recordedAt);
7310
7443
  if (input.process.selectedTurnId === null) {
7311
7444
  appendProcessEvent(writes, input.process, {
7312
7445
  eventType: "process_aborted",
@@ -7790,10 +7923,7 @@ var ContinueFailedTurn = defineOperation({
7790
7923
  stampActorOnEvents(writes, input.options?.actor, "continue_scheduled");
7791
7924
  return accept({
7792
7925
  writes,
7793
- metadata: input.options?.nextTurnModelProfileId !== void 0 || input.options?.providerOptions !== void 0 ? {
7794
- ...input.options.nextTurnModelProfileId !== void 0 ? { nextTurnModelProfileId: input.options.nextTurnModelProfileId } : {},
7795
- ...input.options.providerOptions !== void 0 ? { providerOptions: input.options.providerOptions } : {}
7796
- } : void 0
7926
+ metadata: modelOverrideMetadata(input.options)
7797
7927
  });
7798
7928
  }
7799
7929
  });
@@ -7929,7 +8059,7 @@ var DEFAULT_ACTION_ORIGIN_BY_SOURCE = {
7929
8059
  scheduled: "scheduled"
7930
8060
  };
7931
8061
  function latestLlmSourceTurnRecordId(records) {
7932
- return [...records].filter((record3) => record3.turnType === "llm" && record3.status === "succeeded").sort(
8062
+ return [...records].filter((record4) => record4.turnType === "llm" && record4.status === "succeeded").sort(
7933
8063
  (left, right) => left.startedAt.localeCompare(right.startedAt) || left.id.localeCompare(right.id)
7934
8064
  ).at(-1)?.id ?? null;
7935
8065
  }
@@ -8269,7 +8399,7 @@ var QueueInputs = defineOperation({
8269
8399
  return accept({
8270
8400
  writes: { queuedInputs: queuedWithActor },
8271
8401
  data: [],
8272
- deriveData: (record3) => record3.persistedInputs
8402
+ deriveData: (record4) => record4.persistedInputs
8273
8403
  });
8274
8404
  }
8275
8405
  });
@@ -8344,10 +8474,7 @@ var RetryFailedTurn = defineOperation({
8344
8474
  stampActorOnEvents(writes, input.actor, "retry_scheduled");
8345
8475
  return accept({
8346
8476
  writes,
8347
- metadata: input.nextTurnModelProfileId !== void 0 || input.providerOptions !== void 0 ? {
8348
- ...input.nextTurnModelProfileId !== void 0 ? { nextTurnModelProfileId: input.nextTurnModelProfileId } : {},
8349
- ...input.providerOptions !== void 0 ? { providerOptions: input.providerOptions } : {}
8350
- } : void 0
8477
+ metadata: modelOverrideMetadata(input)
8351
8478
  });
8352
8479
  }
8353
8480
  });
@@ -8366,7 +8493,13 @@ var RetryStartup = defineOperation({
8366
8493
  return reject("retry_target_missing", "Startup retry requires a failed current start");
8367
8494
  }
8368
8495
  const id = generateId("tsr");
8369
- const state = failed.state.kind === "preparation_failed" ? failed.state : failed.state.start.kind === "automatic" ? { kind: "starting", start: failed.state.start } : {
8496
+ const state = failed.state.kind === "preparation_failed" ? {
8497
+ ...failed.state,
8498
+ // A new operator retry must validate current inputs; the previous
8499
+ // failure remains on its original start record.
8500
+ code: "model_required",
8501
+ safeSummary: "LLM start requires retry preparation"
8502
+ } : failed.state.start.kind === "automatic" ? { kind: "starting", start: failed.state.start } : {
8370
8503
  kind: "preparation_failed",
8371
8504
  requestedModelProfileId: failed.state.start.model.profileId,
8372
8505
  providerOptions: { ...failed.state.start.providerOptions },
@@ -8409,10 +8542,7 @@ var RetryStartup = defineOperation({
8409
8542
  return accept({
8410
8543
  writes,
8411
8544
  data: { startRecordId: id },
8412
- metadata: input.nextTurnModelProfileId !== void 0 || input.providerOptions !== void 0 ? {
8413
- ...input.nextTurnModelProfileId !== void 0 ? { nextTurnModelProfileId: input.nextTurnModelProfileId } : {},
8414
- ...input.providerOptions !== void 0 ? { providerOptions: input.providerOptions } : {}
8415
- } : void 0
8545
+ metadata: modelOverrideMetadata(input)
8416
8546
  });
8417
8547
  }
8418
8548
  });
@@ -8592,6 +8722,7 @@ async function captureLeafOutcomeSnapshot(options) {
8592
8722
  turnRecordId: options.leaf.turnRecordId
8593
8723
  },
8594
8724
  turnRecord: options.turnRecord,
8725
+ mappedResult: options.mappedResult,
8595
8726
  readTreeEntry,
8596
8727
  readLeafEntry,
8597
8728
  readTurnRecord(turnRecordId) {
@@ -8646,7 +8777,11 @@ async function captureLeafOutcomeSnapshot(options) {
8646
8777
  }
8647
8778
 
8648
8779
  // src/process-engine/writes/build-turn-outcome-writes.ts
8649
- import { SafeOutcomePlanningError as SafeOutcomePlanningError2 } from "@leitwerk-dev/process-sdk";
8780
+ import {
8781
+ applyOutcomeContract,
8782
+ resolveOutcomeContract,
8783
+ SafeOutcomePlanningError as SafeOutcomePlanningError2
8784
+ } from "@leitwerk-dev/process-sdk";
8650
8785
 
8651
8786
  // src/domain-logic/outcome-tools.ts
8652
8787
  import {
@@ -8656,100 +8791,12 @@ import {
8656
8791
  } from "@leitwerk-dev/domain";
8657
8792
  import {
8658
8793
  isAutomaticTurnDefinition as isAutomaticTurnDefinition2,
8659
- isLlmTurnDefinition as isLlmTurnDefinition3
8794
+ isLlmTurnDefinition as isLlmTurnDefinition3,
8795
+ validateOutcomeParameters
8660
8796
  } from "@leitwerk-dev/process-sdk";
8661
- import * as v3 from "valibot";
8662
8797
  function validationFailure2(code, message) {
8663
8798
  return { ok: false, code, message };
8664
8799
  }
8665
- function toSnakeCase(value) {
8666
- return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
8667
- }
8668
- function invalidParameterCode(key, spec) {
8669
- return spec.invalidErrorCode ?? `invalid_${toSnakeCase(key)}`;
8670
- }
8671
- function requiredParameterError(turnId, outcome, key, spec) {
8672
- return validationFailure2(
8673
- spec.requiredErrorCode ?? `${toSnakeCase(key)}_required`,
8674
- `${turnId}.${outcome} requires a non-empty ${key}`
8675
- );
8676
- }
8677
- function minItemsParameterError(turnId, outcome, key, spec) {
8678
- return validationFailure2(
8679
- spec.minItemsErrorCode ?? spec.requiredErrorCode ?? `${toSnakeCase(key)}_required`,
8680
- `${turnId}.${outcome} requires at least ${spec.minItems ?? 0} item(s) for ${key}`
8681
- );
8682
- }
8683
- function invalidParameterError(turnId, outcome, key, spec, expected) {
8684
- return validationFailure2(
8685
- invalidParameterCode(key, spec),
8686
- `${turnId}.${outcome} expects ${key} to be ${expected}`
8687
- );
8688
- }
8689
- function minimumParameterError(turnId, outcome, key, spec) {
8690
- return validationFailure2(
8691
- spec.minimumErrorCode ?? invalidParameterCode(key, spec),
8692
- `${turnId}.${outcome} expects ${key} to be >= ${spec.minimum ?? 0}`
8693
- );
8694
- }
8695
- var scalarParameters = {
8696
- string: { schema: v3.string(), label: "a string", plural: "strings" },
8697
- number: {
8698
- schema: v3.pipe(v3.number(), v3.finite()),
8699
- label: "a finite number",
8700
- plural: "finite numbers"
8701
- },
8702
- boolean: { schema: v3.boolean(), label: "a boolean", plural: "booleans" },
8703
- object: {
8704
- schema: v3.custom(isJsonObject, "Expected an object"),
8705
- label: "an object",
8706
- plural: "objects"
8707
- }
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
- }
8735
- function compileOutcomeParameterSchema(spec) {
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
- );
8742
- }
8743
- function effectiveArrayItemCount(spec, value) {
8744
- return (spec.items?.type ?? "string") === "string" ? normalizeStringArray(value).length : value.length;
8745
- }
8746
- function expectedParameterLabel(spec) {
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}`;
8752
- }
8753
8800
  function jsonValuesEqual(left, right) {
8754
8801
  if (left === right) {
8755
8802
  return true;
@@ -8838,11 +8885,7 @@ function validateChangedProjects(changedProjects, knownProjectKeys) {
8838
8885
  return null;
8839
8886
  }
8840
8887
  function validateTurnEndResultParams(turnId, outcome, params2, expectedParams) {
8841
- const parsed = v3.safeParse(
8842
- v3.custom((value) => jsonValuesEqual(value, expectedParams)),
8843
- params2
8844
- );
8845
- if (parsed.success) {
8888
+ if (jsonValuesEqual(params2, expectedParams)) {
8846
8889
  return null;
8847
8890
  }
8848
8891
  return validationFailure2(
@@ -8851,43 +8894,8 @@ function validateTurnEndResultParams(turnId, outcome, params2, expectedParams) {
8851
8894
  );
8852
8895
  }
8853
8896
  function validateDeclaredOutcomeParameters(turnId, outcome, params2, parameterSpecs, knownProjectKeys) {
8854
- const unknownKeys = Object.keys(params2).filter((key) => !Object.hasOwn(parameterSpecs, key));
8855
- if (unknownKeys.length > 0) {
8856
- return validationFailure2(
8857
- "unknown_parameter",
8858
- `${turnId}.${outcome} received unknown parameter(s): ${unknownKeys.join(", ")}`
8859
- );
8860
- }
8861
- for (const [key, spec] of Object.entries(parameterSpecs)) {
8862
- const value = params2[key];
8863
- if (value === void 0) {
8864
- if (spec.required) {
8865
- return requiredParameterError(turnId, outcome, key, spec);
8866
- }
8867
- continue;
8868
- }
8869
- if (!v3.safeParse(compileOutcomeParameterSchema(spec), value).success) {
8870
- return invalidParameterError(turnId, outcome, key, spec, expectedParameterLabel(spec));
8871
- }
8872
- if (spec.type === "string" && trimString(value) === "" && spec.required) {
8873
- return requiredParameterError(turnId, outcome, key, spec);
8874
- }
8875
- if (spec.type === "number" && spec.minimum !== void 0 && value < spec.minimum) {
8876
- return minimumParameterError(turnId, outcome, key, spec);
8877
- }
8878
- if (spec.enum && spec.enum.length > 0 && typeof value === "string" && !spec.enum.includes(value)) {
8879
- return invalidParameterError(turnId, outcome, key, spec, `one of: ${spec.enum.join(", ")}`);
8880
- }
8881
- if (spec.type === "array") {
8882
- const effectiveItemCount = effectiveArrayItemCount(spec, value);
8883
- if (spec.required && effectiveItemCount === 0) {
8884
- return requiredParameterError(turnId, outcome, key, spec);
8885
- }
8886
- if (spec.minItems !== void 0 && effectiveItemCount < spec.minItems) {
8887
- return minItemsParameterError(turnId, outcome, key, spec);
8888
- }
8889
- }
8890
- }
8897
+ const [issue] = validateOutcomeParameters(parameterSpecs, params2);
8898
+ if (issue) return validationFailure2(issue.code, `${turnId}.${outcome}: ${issue.message}`);
8891
8899
  const projectError = validateChangedProjects(params2.changedProjects, knownProjectKeys);
8892
8900
  if (projectError) {
8893
8901
  return projectError;
@@ -8990,6 +8998,7 @@ async function planMappedTurnEntries(input) {
8990
8998
  const active = input.mappedRuns?.getActiveByInstance(input.process.id) ?? null;
8991
8999
  let activeAborted = false;
8992
9000
  for (let entry = 0; entry <= MAX_EMPTY_MAPPED_ENTRIES; entry += 1) {
9001
+ deferTurnWaitStarts(input.processGraphs, input.process, writes);
8993
9002
  const candidate = { ...input.process, ...writes.processPatch };
8994
9003
  const startIndex = writes.turnStartWrites.findIndex(
8995
9004
  (write) => write.kind === "create" && write.input.turnType === "llm" && write.input.startKind === "selected_turn" && !write.input.iteration && write.input.turnId === candidate.selectedTurnId
@@ -9028,12 +9037,7 @@ async function planMappedTurnEntries(input) {
9028
9037
  instanceId: input.process.id,
9029
9038
  turnId,
9030
9039
  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
- }))
9040
+ items: frozen.items
9037
9041
  }
9038
9042
  });
9039
9043
  appendProcessEvent(writes, candidate, {
@@ -9048,7 +9052,7 @@ async function planMappedTurnEntries(input) {
9048
9052
  }
9049
9053
  const first = frozen.items[0];
9050
9054
  if (first) {
9051
- start.input.iteration = { runId, itemKey: first.key, itemIndex: 0 };
9055
+ start.input.iteration = { runId, itemKey: first.itemKey, itemIndex: 0 };
9052
9056
  return { ok: true };
9053
9057
  }
9054
9058
  writes.turnStartWrites.splice(startIndex, 1);
@@ -9210,10 +9214,39 @@ async function buildProcessTurnOutcomeEffectWrites(processGraphs, process2, proj
9210
9214
  }
9211
9215
  async function buildTurnOutcomeWrites(input) {
9212
9216
  const knownProjectKeys = new Set(input.projects.map((project) => project.key));
9213
- const turnDefinition = input.processActionRegistry.getTurnDefinition(
9217
+ let turnDefinition = input.processActionRegistry.getTurnDefinition(
9214
9218
  input.process.processId,
9215
9219
  input.payload.turnId
9216
9220
  );
9221
+ if (turnDefinition?.kind === "llm") {
9222
+ try {
9223
+ let snapshot = input.outcomeContract;
9224
+ if (!snapshot) {
9225
+ const ref = input.iteration;
9226
+ const item = ref ? input.mappedRuns?.getItem(ref.runId, ref.itemIndex) : void 0;
9227
+ const run = ref ? input.mappedRuns?.getById(ref.runId) : void 0;
9228
+ snapshot = {
9229
+ ...resolveOutcomeContract(
9230
+ turnDefinition,
9231
+ input.processActionRegistry.resolveContextData(input.process.processId, input.process),
9232
+ ref && item && run ? {
9233
+ ...ref,
9234
+ item: JSON.parse(item.itemJson),
9235
+ itemLabel: item.label,
9236
+ itemCount: run.itemCount
9237
+ } : void 0
9238
+ )
9239
+ };
9240
+ }
9241
+ turnDefinition = applyOutcomeContract(turnDefinition, snapshot);
9242
+ } catch (error) {
9243
+ return {
9244
+ ok: false,
9245
+ code: "invalid_outcome_contract",
9246
+ message: error instanceof Error ? error.message : "Invalid outcome contract"
9247
+ };
9248
+ }
9249
+ }
9217
9250
  const availabilityError = checkTurnOutcomeAvailability(
9218
9251
  input.processGraphs,
9219
9252
  turnDefinition,
@@ -9391,6 +9424,14 @@ function validatePublishedProductOutcome(input) {
9391
9424
  return null;
9392
9425
  }
9393
9426
  function resolveOutcomePublication(input) {
9427
+ if (input.outcomeContract) {
9428
+ const outcome2 = input.outcomeContract.outcomes[input.outcome];
9429
+ return {
9430
+ productName: outcome2?.publishedProduct ?? input.outcomeContract.publishedProduct,
9431
+ markdownParameterName: outcome2?.turnResultMarkdownParameter ?? null,
9432
+ resultSummaryParameter: outcome2?.resultSummaryParameter
9433
+ };
9434
+ }
9394
9435
  const definition = input.processGraphs.get(input.processId)?.turns.get(input.turnId)?.definition;
9395
9436
  if (!definition || !isLlmTurnDefinition4(definition) && !isAutomaticTurnDefinition3(definition)) {
9396
9437
  return { productName: input.turnPublishedProduct, markdownParameterName: null };
@@ -9428,6 +9469,8 @@ var TurnOutcome = defineOperation({
9428
9469
  input.onRecorded?.();
9429
9470
  },
9430
9471
  async decide(ctx, input) {
9472
+ const currentStart = ctx.process.currentExecution?.kind === "worker_start" ? ctx.deps.turnStarts.getById(ctx.process.currentExecution.id) : null;
9473
+ const outcomeContract = currentStart?.state.kind === "accepted" && currentStart.state.start?.kind === "llm" ? currentStart.state.start.outcomeContract : void 0;
9431
9474
  const initialPayload = input.payload;
9432
9475
  const turnGraph = getProcessTurnGraph(
9433
9476
  ctx.deps.processGraphs,
@@ -9440,11 +9483,11 @@ var TurnOutcome = defineOperation({
9440
9483
  processId: ctx.process.processId,
9441
9484
  turnId: initialPayload.turnId,
9442
9485
  outcome: initialPayload.outcome,
9443
- turnPublishedProduct: turnGraph?.publishedProduct ?? null
9486
+ turnPublishedProduct: turnGraph?.publishedProduct ?? null,
9487
+ outcomeContract
9444
9488
  });
9445
9489
  const payload = resolveEffectiveOutcomePayload({ payload: initialPayload, publication });
9446
9490
  const publishedProduct = publication.productName;
9447
- const currentStart = ctx.process.currentExecution?.kind === "worker_start" ? ctx.deps.turnStarts.getById(ctx.process.currentExecution.id) : null;
9448
9491
  const expected = currentStart?.state.kind === "accepted" ? currentStart.state.turnRecordId : null;
9449
9492
  const correlationError = validateTurnOutcomeCorrelation(ctx.process, payload, expected);
9450
9493
  if (correlationError) {
@@ -9459,7 +9502,7 @@ var TurnOutcome = defineOperation({
9459
9502
  }
9460
9503
  const requiredMarkdownError = validateRequiredTurnResultMarkdown({
9461
9504
  payload,
9462
- required: turnGraph?.turnResultMarkdownRequired === true
9505
+ required: outcomeContract ? outcomeContract.turnResultMarkdown?.mode !== "none" && outcomeContract.turnResultMarkdown?.required === true : turnGraph?.turnResultMarkdownRequired === true
9463
9506
  });
9464
9507
  if (requiredMarkdownError) {
9465
9508
  return reject(requiredMarkdownError.code, requiredMarkdownError.message);
@@ -9531,66 +9574,43 @@ var TurnOutcome = defineOperation({
9531
9574
  });
9532
9575
  }
9533
9576
  const existing = ctx.deps.turnRecords.getById(payload.turnRecordId);
9534
- const completedTurnRecord = existing ? {
9535
- ...existing,
9536
- turnType: payload.turnType ?? existing.turnType,
9537
- status: "succeeded",
9538
- resultPiEntryId: payload.resultPiEntryId ?? null,
9539
- modelProfileId: existing.modelProfileId,
9540
- turnResultMarkdown: payload.turnResultMarkdown ?? null,
9541
- endedAt: recordedAt,
9542
- errorSummary: null,
9543
- errorClass: null
9544
- } : {
9545
- id: payload.turnRecordId,
9546
- instanceId: input.instanceId,
9547
- turnId: payload.turnId,
9577
+ const completion = {
9548
9578
  turnType: payload.turnType,
9549
9579
  status: "succeeded",
9550
- attemptNumber: 1,
9551
- parentTurnRecordId: null,
9552
- pathType: payload.pathType ?? "primary",
9553
- forkPiEntryId: payload.forkPiEntryId ?? null,
9554
9580
  resultPiEntryId: payload.resultPiEntryId ?? null,
9555
- modelProfileId: null,
9556
9581
  turnResultMarkdown: payload.turnResultMarkdown ?? null,
9557
- errorSummary: null,
9558
- errorClass: null,
9559
- startedAt: recordedAt,
9560
9582
  endedAt: recordedAt
9561
9583
  };
9584
+ const completedTurnRecord = {
9585
+ ...existing ?? {
9586
+ id: payload.turnRecordId,
9587
+ instanceId: input.instanceId,
9588
+ turnId: payload.turnId,
9589
+ attemptNumber: 1,
9590
+ parentTurnRecordId: null,
9591
+ pathType: payload.pathType ?? "primary",
9592
+ forkPiEntryId: payload.forkPiEntryId ?? null,
9593
+ modelProfileId: null,
9594
+ startedAt: recordedAt
9595
+ },
9596
+ ...completion,
9597
+ turnType: existing ? payload.turnType ?? existing.turnType : payload.turnType,
9598
+ errorSummary: null,
9599
+ errorClass: null
9600
+ };
9562
9601
  if (existing) {
9563
9602
  baseWrites.turnRecordWrites.push({
9564
9603
  kind: "update",
9565
9604
  id: payload.turnRecordId,
9566
- input: {
9567
- turnType: payload.turnType,
9568
- status: "succeeded",
9569
- resultPiEntryId: payload.resultPiEntryId ?? null,
9570
- turnResultMarkdown: payload.turnResultMarkdown ?? null,
9571
- endedAt: recordedAt
9572
- }
9605
+ input: completion
9573
9606
  });
9574
9607
  } else {
9608
+ const { modelProfileId, ...recordInput } = completedTurnRecord;
9575
9609
  baseWrites.turnRecordWrites.push({
9576
9610
  kind: "create",
9577
9611
  input: {
9578
- id: completedTurnRecord.id,
9579
- instanceId: completedTurnRecord.instanceId,
9580
- turnId: completedTurnRecord.turnId,
9581
- turnType: completedTurnRecord.turnType,
9582
- status: completedTurnRecord.status,
9583
- attemptNumber: completedTurnRecord.attemptNumber,
9584
- parentTurnRecordId: completedTurnRecord.parentTurnRecordId,
9585
- pathType: completedTurnRecord.pathType,
9586
- forkPiEntryId: completedTurnRecord.forkPiEntryId,
9587
- resultPiEntryId: completedTurnRecord.resultPiEntryId,
9588
- ...completedTurnRecord.modelProfileId !== null ? { modelProfileId: completedTurnRecord.modelProfileId } : {},
9589
- turnResultMarkdown: completedTurnRecord.turnResultMarkdown,
9590
- errorSummary: completedTurnRecord.errorSummary,
9591
- errorClass: completedTurnRecord.errorClass,
9592
- startedAt: completedTurnRecord.startedAt,
9593
- endedAt: completedTurnRecord.endedAt
9612
+ ...recordInput,
9613
+ ...modelProfileId !== null ? { modelProfileId } : {}
9594
9614
  }
9595
9615
  });
9596
9616
  }
@@ -9608,7 +9628,8 @@ var TurnOutcome = defineOperation({
9608
9628
  processGraphs: ctx.deps.processGraphs,
9609
9629
  processActionRegistry,
9610
9630
  mappedRuns: ctx.deps.mappedRuns,
9611
- iteration: currentStart?.iteration ?? null
9631
+ iteration: currentStart?.iteration ?? null,
9632
+ outcomeContract: outcomeContract ? { ...outcomeContract } : void 0
9612
9633
  });
9613
9634
  if (isWriteBuildFailure(outcomeWrites)) {
9614
9635
  return reject(outcomeWrites.code, outcomeWrites.message);
@@ -9681,7 +9702,11 @@ var TurnOutcome = defineOperation({
9681
9702
  ...mergedWrites.processPatch,
9682
9703
  stateJson: mergedWrites.processPatch.stateJson ?? ctx.process.stateJson
9683
9704
  };
9705
+ const mappedWrite = mergedWrites.mappedRunWrites.find(
9706
+ (write) => write.kind === "complete_item" && write.input.turnRecordId === completedTurnRecord.id
9707
+ );
9684
9708
  const snapshotInput = await captureLeafOutcomeSnapshot({
9709
+ ...mappedWrite?.kind === "complete_item" ? { mappedResult: JSON.parse(mappedWrite.input.resultJson) } : {},
9685
9710
  process: capturedProcess,
9686
9711
  projects,
9687
9712
  processActionRegistry,
@@ -9867,41 +9892,281 @@ var WorkerFailure = defineOperation({
9867
9892
  }
9868
9893
  });
9869
9894
 
9870
- // src/process-engine/reactions.ts
9871
- async function dispatchReactions(deps, recorded, messages = {}, options = {}) {
9872
- const result = await runPostCommitEffectList(
9873
- deps,
9874
- recorded.reactions,
9875
- messages,
9876
- {
9877
- logger: deps.logger,
9878
- operationKind: recorded.operationKind,
9879
- stage: "post_commit"
9880
- },
9881
- options
9882
- );
9883
- if (result.ok) return result;
9884
- if (result.code === "input_dispatch_failed" || result.code === "worker_reconcile_failed") {
9885
- return { ok: false, code: result.code, message: result.message };
9895
+ // src/process-engine/ops/process-observation.ts
9896
+ var ApplyProcessObservation = defineOperation({
9897
+ kind: "process_observation",
9898
+ label: "Record integration observation",
9899
+ decide({ process: process2, deps }, input) {
9900
+ const expected = input.expected;
9901
+ if (expected.id !== process2.id || expected.processId !== process2.processId || expected.planRevision !== process2.planRevision || expected.paramsJson !== process2.paramsJson || expected.stateJson !== process2.stateJson || expected.selectedTurnId !== process2.selectedTurnId || expected.lifecycleStatus !== process2.lifecycleStatus || JSON.stringify(expected.currentExecution) !== JSON.stringify(process2.currentExecution) || Object.keys(input.metadata ?? {}).some(
9902
+ (key) => JSON.stringify(expected.metadata?.[key]) !== JSON.stringify(process2.metadata?.[key])
9903
+ ) || input.projectsJson !== void 0 && input.projectsJson !== JSON.stringify(deps.projects.listByInstance(process2.id)))
9904
+ return reject("observation_superseded", "The process changed during the integration read");
9905
+ const definition = deps.processGraphs.get(process2.processId);
9906
+ if (!definition) return reject("process_not_found", "Process definition is unavailable");
9907
+ const writes = createWrites({ preserveUpdatedAt: input.preserveUpdatedAt });
9908
+ if (input.state !== void 0) {
9909
+ const state = definition.stateCodec.parse(input.state);
9910
+ applyProcessPatchField(
9911
+ writes,
9912
+ process2,
9913
+ "stateJson",
9914
+ JSON.stringify(definition.stateCodec.serialize(state))
9915
+ );
9916
+ }
9917
+ if (input.metadata)
9918
+ applyMetadataPatch(writes, process2, { ...process2.metadata, ...input.metadata });
9919
+ if (input.lifecycleStatus || input.interrupt) {
9920
+ if (["completed", "aborted"].includes(process2.lifecycleStatus))
9921
+ return reject("invalid_transition", "Terminal processes cannot resume maintenance");
9922
+ if (input.interrupt && !definition.turns.has(input.interrupt.turnId))
9923
+ return reject("invalid_transition", "Maintenance recovery turn is unavailable");
9924
+ const recordId = resolveCurrentExecutionTurnRecordId(process2, deps.turnStarts);
9925
+ const record4 = recordId ? deps.turnRecords.getById(recordId) : null;
9926
+ const start = process2.currentExecution?.kind === "worker_start" ? deps.turnStarts.getById(process2.currentExecution.id) : null;
9927
+ supersedeExecution(writes, record4, start);
9928
+ for (const execution of deps.futureExecutions.listByInstance(process2.id)) {
9929
+ const plan = planCancelScheduledAction(execution, process2.id);
9930
+ if (plan) writes.futureExecutionPlans.push(plan);
9931
+ }
9932
+ writeTurnWait(
9933
+ writes,
9934
+ { ...process2, metadata: writes.processPatch.metadata ?? process2.metadata },
9935
+ null
9936
+ );
9937
+ applyProcessPatchField(writes, process2, "currentExecution", null);
9938
+ applyProcessPatchField(
9939
+ writes,
9940
+ process2,
9941
+ "selectedTurnId",
9942
+ input.lifecycleStatus ? null : input.interrupt?.turnId ?? process2.selectedTurnId
9943
+ );
9944
+ applyProcessPatchField(
9945
+ writes,
9946
+ process2,
9947
+ "lifecycleStatus",
9948
+ input.lifecycleStatus ?? "waiting"
9949
+ );
9950
+ if (input.interrupt && !input.lifecycleStatus) {
9951
+ const turn = definition.turns.get(input.interrupt.turnId)?.definition;
9952
+ if (!turn || turn.kind !== "llm" && turn.kind !== "automatic" || !turn.waitFor)
9953
+ return reject(
9954
+ "invalid_transition",
9955
+ "Maintenance recovery requires an existing gated worker turn"
9956
+ );
9957
+ reserveSelectedTurnStart(
9958
+ writes,
9959
+ { ...process2, ...writes.processPatch },
9960
+ input.interrupt.turnId,
9961
+ turn.kind
9962
+ );
9963
+ }
9964
+ writes.workerIntent = {
9965
+ kind: "stop_with_reason",
9966
+ reason: input.interrupt?.reason ?? "MR maintenance finished"
9967
+ };
9968
+ appendProcessEvent(writes, process2, {
9969
+ eventType: input.lifecycleStatus ? `process_${input.lifecycleStatus}` : "maintenance_interrupted",
9970
+ level: "info",
9971
+ message: input.interrupt?.reason ?? "MR maintenance finished"
9972
+ });
9973
+ }
9974
+ return accept({ writes });
9886
9975
  }
9887
- return { ok: false, code: "post_commit_failed", message: result.message };
9888
- }
9976
+ });
9889
9977
 
9890
- // src/process-engine/writes/commit-writes.ts
9891
- import {
9892
- parseProcessStateJsonLenient as parseProcessStateJsonLenient2,
9893
- areSemanticEntryRefsEqual as sameEntryRef2
9894
- } from "@leitwerk-dev/domain";
9895
- import { parseStructuralProcessState as parseStructuralProcessState2 } from "@leitwerk-dev/process-sdk";
9896
- import { WS_PRIMARY_PATH_TYPES } from "@leitwerk-dev/protocol";
9897
- function hasPrimaryPathRefChange(processBefore, processAfter) {
9898
- if (!processAfter) {
9899
- return false;
9978
+ // src/process-engine/ops/turn-wait.ts
9979
+ var ArmTurnWait = defineOperation({
9980
+ kind: "arm_turn_wait",
9981
+ label: "Wait for turn readiness",
9982
+ admission: "new_turn",
9983
+ decide({ process: process2, deps }) {
9984
+ if (pendingTurnWait(process2) || process2.currentExecution || !process2.selectedTurnId || process2.lifecycleStatus !== "active" || !turnWaitPredicate(deps.processGraphs, process2))
9985
+ return noWrites();
9986
+ const writes = buildTurnSelectionWrites(deps.processGraphs, process2, {
9987
+ toTurnId: process2.selectedTurnId
9988
+ });
9989
+ return isWriteBuildFailure(writes) ? writes : accept({ writes });
9900
9990
  }
9901
- const previousState = parseStructuralProcessState2(
9902
- parseProcessStateJsonLenient2(processBefore?.stateJson)
9903
- );
9904
- const updatedState = parseStructuralProcessState2(
9991
+ });
9992
+ var ResolveTurnWait = defineOperation({
9993
+ kind: "resolve_turn_wait",
9994
+ label: "Resolve turn readiness",
9995
+ admission: "new_turn",
9996
+ decide({ process: process2, deps }, input) {
9997
+ const wait = pendingTurnWait(process2);
9998
+ if (!wait || wait.id !== input.waitId || wait.revision !== input.revision || process2.selectedTurnId !== wait.turnId || process2.lifecycleStatus !== "waiting" || process2.paramsJson !== input.paramsJson || process2.stateJson !== input.stateJson || JSON.stringify(deps.projects.listByInstance(process2.id)) !== input.projectsJson) {
9999
+ return reject("turn_wait_superseded", "The waiting condition has changed");
10000
+ }
10001
+ const writes = createWrites();
10002
+ if (input.nextStateJson !== void 0 && !["retry", "error"].includes(input.result))
10003
+ applyProcessPatchField(writes, process2, "stateJson", input.nextStateJson);
10004
+ if (input.result === "bind") {
10005
+ const binding2 = input.initialBinding;
10006
+ if (!binding2?.projects.length || !wait.initialSelection || process2.currentExecution || deps.projects.listByInstance(process2.id).length || deps.turnStarts.listByInstance(process2.id).length || deps.turnRecords.listByInstance(process2.id).length)
10007
+ return reject(
10008
+ "startup_binding_unavailable",
10009
+ "Initial bindings require a process without projects or execution history"
10010
+ );
10011
+ if (Object.keys(binding2.metadata ?? {}).some(
10012
+ (key) => key === "turnWait" || Object.hasOwn(process2.metadata ?? {}, key)
10013
+ ))
10014
+ return reject(
10015
+ "startup_binding_superseded",
10016
+ "Initial repository binding cannot replace retained metadata"
10017
+ );
10018
+ const definition = deps.processGraphs.get(process2.processId);
10019
+ if (!definition) return reject("process_not_found", "Process definition is unavailable");
10020
+ applyProcessPatchField(
10021
+ writes,
10022
+ process2,
10023
+ "paramsJson",
10024
+ JSON.stringify(
10025
+ definition.paramsCodec.serialize(definition.paramsCodec.parse(binding2.params))
10026
+ )
10027
+ );
10028
+ applyProcessPatchField(writes, process2, "metadata", {
10029
+ ...process2.metadata,
10030
+ ...binding2.metadata,
10031
+ ...binding2.settingsContext ? { settingsContext: binding2.settingsContext } : {}
10032
+ });
10033
+ writes.initialProjects = binding2.projects.map((project) => ({
10034
+ ...project,
10035
+ instanceId: process2.id
10036
+ }));
10037
+ writeTurnWait(writes, process2, {
10038
+ ...wait,
10039
+ revision: wait.revision + 1,
10040
+ message: null,
10041
+ failures: 0,
10042
+ nextCheckAt: 0
10043
+ });
10044
+ appendProcessEvent(writes, process2, {
10045
+ eventType: "initial_repositories_bound",
10046
+ level: "info",
10047
+ message: "Startup repository bindings resolved",
10048
+ data: { projectKeys: binding2.projects.map((p) => p.key) }
10049
+ });
10050
+ return accept({ writes });
10051
+ }
10052
+ if (input.result === "ready") {
10053
+ writeTurnWait(writes, process2, null);
10054
+ writes.waitForAdmission = wait.id;
10055
+ writes.turnStartWrites.push({ kind: "create", input: wait.start });
10056
+ applyProcessPatchField(writes, process2, "currentExecution", {
10057
+ kind: "worker_start",
10058
+ id: wait.start.id
10059
+ });
10060
+ applyProcessPatchField(writes, process2, "lifecycleStatus", "active");
10061
+ writes.workerIntent = { kind: "reconcile" };
10062
+ return accept({ writes, metadata: wait.metadata });
10063
+ }
10064
+ if (input.result === "complete" || input.result === "abort") {
10065
+ writeTurnWait(writes, process2, null);
10066
+ applyProcessPatchField(writes, process2, "selectedTurnId", null);
10067
+ applyProcessPatchField(writes, process2, "currentExecution", null);
10068
+ applyProcessPatchField(
10069
+ writes,
10070
+ process2,
10071
+ "lifecycleStatus",
10072
+ input.result === "abort" ? "aborted" : "completed"
10073
+ );
10074
+ writes.workerIntent = { kind: "reconcile" };
10075
+ appendProcessEvent(writes, process2, {
10076
+ eventType: input.result === "abort" ? "process_aborted" : "process_completed",
10077
+ level: "info",
10078
+ message: input.message ?? "Waiting condition completed the process"
10079
+ });
10080
+ return accept({ writes });
10081
+ }
10082
+ const failures = input.result === "retry" ? wait.failures + 1 : 0;
10083
+ const message = input.message ?? null;
10084
+ writeTurnWait(writes, process2, {
10085
+ ...wait,
10086
+ revision: wait.revision + 1,
10087
+ status: input.result === "error" ? "error" : "waiting",
10088
+ failures,
10089
+ message,
10090
+ nextCheckAt: input.now + (failures ? Math.min(3e5, input.pollIntervalMs * 2 ** Math.min(failures, 8)) : input.pollIntervalMs)
10091
+ });
10092
+ if (input.result === "error")
10093
+ applyProcessPatchField(writes, process2, "lifecycleStatus", "error");
10094
+ if (message !== wait.message)
10095
+ appendProcessEvent(writes, process2, {
10096
+ eventType: message ? "turn_wait_failed" : "turn_wait_recovered",
10097
+ level: message ? "warn" : "info",
10098
+ message: message ?? "Waiting condition recovered",
10099
+ data: { turnId: wait.turnId, retryable: input.result === "retry", safeSummary: message }
10100
+ });
10101
+ writes.preserveUpdatedAt = input.result !== "error" && message === wait.message && writes.changedFields.every((field) => field === "metadata");
10102
+ return accept({ writes });
10103
+ }
10104
+ });
10105
+ var RetryTurnWait = defineOperation({
10106
+ kind: "retry_turn_wait",
10107
+ label: "Retry waiting condition",
10108
+ admission: "new_turn",
10109
+ decide({ process: process2 }, input) {
10110
+ const wait = pendingTurnWait(process2);
10111
+ if (!wait || wait.status !== "error" || process2.lifecycleStatus !== "error")
10112
+ return reject("retry_target_missing", "No failed waiting condition is current");
10113
+ const writes = createWrites();
10114
+ writeTurnWait(writes, process2, {
10115
+ ...wait,
10116
+ status: "waiting",
10117
+ revision: wait.revision + 1,
10118
+ nextCheckAt: 0,
10119
+ failures: 0,
10120
+ message: null,
10121
+ metadata: { ...wait.metadata, ...modelOverrideMetadata(input) }
10122
+ });
10123
+ applyProcessPatchField(writes, process2, "lifecycleStatus", "waiting");
10124
+ appendProcessEvent(writes, process2, {
10125
+ eventType: "turn_wait_retry",
10126
+ level: "info",
10127
+ message: "Waiting condition retry requested",
10128
+ data: { turnId: wait.turnId }
10129
+ });
10130
+ stampActorOnEvents(writes, input.actor, "turn_wait_retry");
10131
+ return accept({ writes });
10132
+ }
10133
+ });
10134
+
10135
+ // src/process-engine/reactions.ts
10136
+ async function dispatchReactions(deps, recorded, messages = {}, options = {}) {
10137
+ const result = await runPostCommitEffectList(
10138
+ deps,
10139
+ recorded.reactions,
10140
+ messages,
10141
+ {
10142
+ logger: deps.logger,
10143
+ operationKind: recorded.operationKind,
10144
+ stage: "post_commit"
10145
+ },
10146
+ options
10147
+ );
10148
+ if (result.ok) return result;
10149
+ if (result.code === "input_dispatch_failed" || result.code === "worker_reconcile_failed") {
10150
+ return { ok: false, code: result.code, message: result.message };
10151
+ }
10152
+ return { ok: false, code: "post_commit_failed", message: result.message };
10153
+ }
10154
+
10155
+ // src/process-engine/writes/commit-writes.ts
10156
+ import {
10157
+ parseProcessStateJsonLenient as parseProcessStateJsonLenient2,
10158
+ areSemanticEntryRefsEqual as sameEntryRef2
10159
+ } from "@leitwerk-dev/domain";
10160
+ import { parseStructuralProcessState as parseStructuralProcessState2 } from "@leitwerk-dev/process-sdk";
10161
+ import { WS_PRIMARY_PATH_TYPES } from "@leitwerk-dev/protocol";
10162
+ function hasPrimaryPathRefChange(processBefore, processAfter) {
10163
+ if (!processAfter) {
10164
+ return false;
10165
+ }
10166
+ const previousState = parseStructuralProcessState2(
10167
+ parseProcessStateJsonLenient2(processBefore?.stateJson)
10168
+ );
10169
+ const updatedState = parseStructuralProcessState2(
9905
10170
  parseProcessStateJsonLenient2(processAfter.stateJson)
9906
10171
  );
9907
10172
  return !sameEntryRef2(
@@ -10020,7 +10285,9 @@ function commitWrites(deps, instanceId, writes) {
10020
10285
  for (const write of writes.leafOutcomeSnapshotWrites) {
10021
10286
  committedLeafOutcomeSnapshots.push(repos.leafOutcomeSnapshots.create(write.input));
10022
10287
  }
10023
- const processAfter = writes.changedFields.length > 0 ? repos.processes.update(instanceId, writes.processPatch) : repos.processes.getById(instanceId);
10288
+ const processAfter = writes.changedFields.length > 0 ? repos.processes.update(instanceId, writes.processPatch, {
10289
+ preserveUpdatedAt: writes.preserveUpdatedAt
10290
+ }) : repos.processes.getById(instanceId);
10024
10291
  const committedProject = writes.projectWrite ? repos.projects.update(writes.projectWrite.id, writes.projectWrite.input) : null;
10025
10292
  if (writes.projectWrite && !committedProject) {
10026
10293
  throw new Error(`Process project '${writes.projectWrite.id}' disappeared during commit`);
@@ -10030,6 +10297,11 @@ function commitWrites(deps, instanceId, writes) {
10030
10297
  `Process project '${committedProject.id}' does not belong to '${instanceId}'`
10031
10298
  );
10032
10299
  }
10300
+ const initialProjects = (writes.initialProjects ?? []).map((project) => {
10301
+ if (project.instanceId !== instanceId)
10302
+ throw new Error("Initial repository belongs to another process");
10303
+ return repos.projects.create(project);
10304
+ });
10033
10305
  for (const write of writes.pendingExternalSourceFireWrites) {
10034
10306
  if (write.kind === "create") {
10035
10307
  repos.pendingExternalSourceFires.create(write.input);
@@ -10066,6 +10338,7 @@ function commitWrites(deps, instanceId, writes) {
10066
10338
  processBefore,
10067
10339
  processAfter,
10068
10340
  committedProject,
10341
+ initialProjects,
10069
10342
  committedTurnRecords,
10070
10343
  turnEventSequences,
10071
10344
  committedLeafOutcomeSnapshots,
@@ -10083,6 +10356,8 @@ function deriveReactions(commit, writes, options = {}) {
10083
10356
  effects.push({ kind: "broadcast", frame });
10084
10357
  }
10085
10358
  if (commit.committedProject) effects.push(buildProjectUpdatedEffect(commit.committedProject));
10359
+ for (const project of commit.initialProjects ?? [])
10360
+ effects.push(buildProjectUpdatedEffect(project));
10086
10361
  if (writes.changedFields.length > 0) {
10087
10362
  const includeClosedAt = commit.processAfter !== null && (commit.processBefore?.closedAt ?? null) !== (commit.processAfter.closedAt ?? null);
10088
10363
  const processPatch = {
@@ -10090,7 +10365,7 @@ function deriveReactions(commit, writes, options = {}) {
10090
10365
  ...commit.processAfter?.updatedAt ? { updatedAt: commit.processAfter.updatedAt } : {},
10091
10366
  ...includeClosedAt ? { closedAt: commit.processAfter?.closedAt ?? null } : {}
10092
10367
  };
10093
- let changedFields = commit.processAfter?.updatedAt && !writes.changedFields.includes("updatedAt") ? [...writes.changedFields, "updatedAt"] : writes.changedFields;
10368
+ let changedFields = commit.processAfter?.updatedAt !== commit.processBefore?.updatedAt && !writes.changedFields.includes("updatedAt") ? [...writes.changedFields, "updatedAt"] : writes.changedFields;
10094
10369
  if (includeClosedAt && !changedFields.includes("closedAt")) {
10095
10370
  changedFields = [...changedFields, "closedAt"];
10096
10371
  }
@@ -10242,6 +10517,7 @@ function buildRecordedDecision(input) {
10242
10517
  };
10243
10518
  }
10244
10519
  async function record2(deps, operation, input, initialProcess, decision) {
10520
+ deferTurnWaitStarts(deps.processGraphs, initialProcess, decision.writes, decision.metadata);
10245
10521
  const mappedPlan = await planMappedTurnEntries({
10246
10522
  processGraphs: deps.processGraphs,
10247
10523
  registry: deps.getProcessActionRegistry?.(),
@@ -10253,6 +10529,7 @@ async function record2(deps, operation, input, initialProcess, decision) {
10253
10529
  if (!mappedPlan.ok) {
10254
10530
  return { ok: false, stage: "pre_commit", code: mappedPlan.code, message: mappedPlan.message };
10255
10531
  }
10532
+ deferTurnWaitStarts(deps.processGraphs, initialProcess, decision.writes, decision.metadata);
10256
10533
  const baselineWrites = structuredClone(decision.writes);
10257
10534
  const runModelPreparation = async (availability) => {
10258
10535
  const candidateProcess = {
@@ -10262,8 +10539,8 @@ async function record2(deps, operation, input, initialProcess, decision) {
10262
10539
  const createdStart = decision.writes.turnStartWrites.find(
10263
10540
  (write) => write.kind === "create" && write.input.turnType === "llm"
10264
10541
  );
10265
- const shouldResolveSelection = !!candidateProcess.selectedTurnId && (!!createdStart || candidateProcess.selectedTurnId !== initialProcess.selectedTurnId || candidateProcess.lifecycleStatus === "active" && initialProcess.lifecycleStatus !== "active" || Object.hasOwn(decision.metadata ?? {}, "nextTurnModelProfileId"));
10266
- if (!candidateProcess.selectedTurnId) {
10542
+ const shouldResolveSelection = !pendingTurnWait(candidateProcess) && !!candidateProcess.selectedTurnId && (!!createdStart || candidateProcess.selectedTurnId !== initialProcess.selectedTurnId || candidateProcess.lifecycleStatus === "active" && initialProcess.lifecycleStatus !== "active" || Object.hasOwn(decision.metadata ?? {}, "nextTurnModelProfileId"));
10543
+ if (candidateProcess.selectedTurnId && deps.processGraphs.get(candidateProcess.processId)?.turns.get(candidateProcess.selectedTurnId)?.definition.kind !== "llm" || !candidateProcess.selectedTurnId && !(candidateProcess.lifecycleStatus === "discovered" && candidateProcess.selectedTurnModelSource === "launch_override")) {
10267
10544
  applyProcessPatchField(decision.writes, initialProcess, "selectedTurnModelProfileId", null);
10268
10545
  applyProcessPatchField(decision.writes, initialProcess, "selectedTurnModelKind", null);
10269
10546
  applyProcessPatchField(decision.writes, initialProcess, "selectedTurnModelSource", null);
@@ -10274,7 +10551,7 @@ async function record2(deps, operation, input, initialProcess, decision) {
10274
10551
  turnId: candidateProcess.selectedTurnId,
10275
10552
  availability,
10276
10553
  startKind: createdStart?.input.startKind,
10277
- initialSelection: createdStart?.input.startKind === "selected_turn" && initialProcess.selectedTurnId === null && initialProcess.lifecycleStatus === "discovered" && initialProcess.planRevision === 0,
10554
+ initialSelection: decision.writes.waitForAdmission === pendingTurnWait(initialProcess)?.id && pendingTurnWait(initialProcess)?.initialSelection === true || createdStart?.input.startKind === "selected_turn" && initialProcess.selectedTurnId === null && initialProcess.lifecycleStatus === "discovered" && initialProcess.planRevision === 0,
10278
10555
  ...Object.hasOwn(decision.metadata ?? {}, "nextTurnModelProfileId") ? { modelOverride: decision.metadata?.nextTurnModelProfileId ?? null } : {}
10279
10556
  });
10280
10557
  if (!resolution.ok && resolution.code !== "model_unavailable" && resolution.code !== "model_stale" && resolution.code !== "model_required") {
@@ -10658,6 +10935,9 @@ function createProcessEngine(deps) {
10658
10935
  const maybeBroadcastErrorAttentionToast2 = (result, input = {}) => maybeBroadcastErrorAttentionToast(deps, result, input);
10659
10936
  engine = {
10660
10937
  run,
10938
+ applyProcessObservation(instanceId, input) {
10939
+ return run(ApplyProcessObservation, { instanceId, ...input });
10940
+ },
10661
10941
  getDeferredProcessActivationSnapshots({ instanceId, processId, projectKey }) {
10662
10942
  const processes = instanceId ? [deps.processes.getById(instanceId)].filter((process2) => process2 !== null) : deps.processes.listAll().filter((process2) => process2.processId === processId);
10663
10943
  if (instanceId && processes.length === 0) return { outcome: "process_not_found" };
@@ -10690,7 +10970,7 @@ function createProcessEngine(deps) {
10690
10970
  return run(ParkDeferredProcessActivationFailure, { instanceId, failure: failure2 });
10691
10971
  },
10692
10972
  startProcess(instanceId, startTurnId, opts) {
10693
- return run(StartProcess, { instanceId, startTurnId, actor: opts?.actor });
10973
+ return run(StartProcess, { instanceId, startTurnId, ...opts });
10694
10974
  },
10695
10975
  abortProcess(instanceId, opts) {
10696
10976
  return run(AbortProcess, { instanceId, ...opts });
@@ -10703,7 +10983,10 @@ function createProcessEngine(deps) {
10703
10983
  });
10704
10984
  },
10705
10985
  async retryProcess(instanceId, opts) {
10706
- const current = deps.processes.getById(instanceId)?.currentExecution;
10986
+ const process2 = deps.processes.getById(instanceId);
10987
+ if (process2 && pendingTurnWait(process2)?.status === "error")
10988
+ return run(RetryTurnWait, { instanceId, ...opts });
10989
+ const current = process2?.currentExecution;
10707
10990
  const start = current?.kind === "worker_start" ? deps.turnStarts.getById(current.id) : null;
10708
10991
  if (start?.state.kind === "preparation_failed" || start?.state.kind === "bootstrap_failed") {
10709
10992
  const result = await run(RetryStartup, {
@@ -11088,6 +11371,7 @@ function normalizeProjectInputs(launchConfig, commitMessages) {
11088
11371
  externalUrl: project.externalUrl ?? null,
11089
11372
  metadata: {
11090
11373
  ...project.metadata ?? {},
11374
+ ...project.settingsRepository ? { settingsRepository: project.settingsRepository } : {},
11091
11375
  [COMMIT_MESSAGE_PROJECT_METADATA_KEY]: resolveCommitMessageMetadata(
11092
11376
  project.repoLocator,
11093
11377
  commitMessages
@@ -11108,9 +11392,16 @@ function buildProcessLaunchPlan(input) {
11108
11392
  const initialState = processDef.initialState(params2);
11109
11393
  const state = processDef.stateCodec.parse(initialState);
11110
11394
  const stateJson = serializeJson(processDef.stateCodec.serialize(state));
11395
+ if (input.launchConfig.primaryRepositoryKey && !input.launchConfig.projects?.some(
11396
+ (project) => project.key === input.launchConfig.primaryRepositoryKey
11397
+ )) {
11398
+ throw new Error("Primary repository must be a project in this launch");
11399
+ }
11111
11400
  const launchMetadata = {
11112
11401
  ...input.launchConfig.metadata ?? {},
11113
- ...input.metadataAdditions ?? {}
11402
+ ...input.metadataAdditions ?? {},
11403
+ ...input.launchConfig.primaryRepositoryKey ? { primaryRepositoryKey: input.launchConfig.primaryRepositoryKey } : {},
11404
+ ...input.launchConfig.settingsContext ? { settingsContext: input.launchConfig.settingsContext } : {}
11114
11405
  };
11115
11406
  return {
11116
11407
  launcherId: input.launcherId,
@@ -11182,6 +11473,22 @@ function buildProcessLauncherRegistry(catalog, options = {}) {
11182
11473
  ...ctx,
11183
11474
  modelProfiles: ctx.modelProfiles ?? options.getModelProfilesForProcess?.(processId) ?? options.modelProfiles ?? []
11184
11475
  });
11476
+ async function resolveUiLauncher(launcherId, input, ctx, preview) {
11477
+ const { launcher, ui } = requireUiLauncher(launcherId);
11478
+ const resolve = preview ? ui.resolvePreviewConfig ?? ui.resolveLaunchConfig : ui.resolveLaunchConfig;
11479
+ const resolved = await resolve.call(ui, input, createLauncherContext(launcher.processId, ctx));
11480
+ if (!resolved.ok) return resolved;
11481
+ const result = buildResolvedProcessLauncher(
11482
+ launcher,
11483
+ resolved.launchConfig,
11484
+ options.commitMessages
11485
+ );
11486
+ if (preview) result.launchPlan.preview = true;
11487
+ return {
11488
+ ok: true,
11489
+ launcher: result
11490
+ };
11491
+ }
11185
11492
  const uiLaunchers = [...launchers.values()].filter((launcher) => launcher.definition.ui).map(
11186
11493
  (launcher) => ({
11187
11494
  id: launcher.definition.id,
@@ -11225,22 +11532,10 @@ function buildProcessLauncherRegistry(catalog, options = {}) {
11225
11532
  );
11226
11533
  },
11227
11534
  async resolveUiLauncher(launcherId, input, ctx = {}) {
11228
- const { launcher, ui } = requireUiLauncher(launcherId);
11229
- const resolved = await ui.resolveLaunchConfig(
11230
- input,
11231
- createLauncherContext(launcher.processId, ctx)
11232
- );
11233
- if (!resolved.ok) {
11234
- return resolved;
11235
- }
11236
- return {
11237
- ok: true,
11238
- launcher: buildResolvedProcessLauncher(
11239
- launcher,
11240
- resolved.launchConfig,
11241
- options.commitMessages
11242
- )
11243
- };
11535
+ return resolveUiLauncher(launcherId, input, ctx, false);
11536
+ },
11537
+ async resolveUiLauncherPreview(launcherId, input, ctx = {}) {
11538
+ return resolveUiLauncher(launcherId, input, ctx, true);
11244
11539
  }
11245
11540
  };
11246
11541
  }
@@ -11361,27 +11656,27 @@ function findContextTurnRecord(input) {
11361
11656
  (ref) => ref?.entryId === input.entryId && ref.turnRecordId
11362
11657
  );
11363
11658
  if (semanticRef?.turnRecordId) {
11364
- const record3 = input.turnRecords.getById(semanticRef.turnRecordId);
11365
- if (record3?.instanceId === input.process.id && record3.resultPiEntryId === input.entryId) {
11366
- return record3;
11659
+ const record4 = input.turnRecords.getById(semanticRef.turnRecordId);
11660
+ if (record4?.instanceId === input.process.id && record4.resultPiEntryId === input.entryId) {
11661
+ return record4;
11367
11662
  }
11368
11663
  }
11369
- return [...input.turnRecords.listByInstance(input.process.id)].reverse().find((record3) => record3.resultPiEntryId === input.entryId) ?? null;
11664
+ return [...input.turnRecords.listByInstance(input.process.id)].reverse().find((record4) => record4.resultPiEntryId === input.entryId) ?? null;
11370
11665
  }
11371
11666
  function buildWarmPromptCache(input) {
11372
11667
  if (!input.continuationEntryId || !input.turnRecords || !input.turnStarts) return void 0;
11373
- const record3 = findContextTurnRecord({
11668
+ const record4 = findContextTurnRecord({
11374
11669
  process: input.process,
11375
11670
  entryId: input.continuationEntryId,
11376
11671
  semanticEntryRefs: input.semanticEntryRefs,
11377
11672
  turnRecords: input.turnRecords
11378
11673
  });
11379
- const profileId = record3?.modelProfileId?.trim() ?? "";
11380
- const endedAt = record3?.endedAt ?? null;
11674
+ const profileId = record4?.modelProfileId?.trim() ?? "";
11675
+ const endedAt = record4?.endedAt ?? null;
11381
11676
  const endedAtMs = endedAt === null ? Number.NaN : Date.parse(endedAt);
11382
- const start = record3?.turnStartRecordId ? input.turnStarts.getById(record3.turnStartRecordId) : null;
11677
+ const start = record4?.turnStartRecordId ? input.turnStarts.getById(record4.turnStartRecordId) : null;
11383
11678
  const executedModel = start?.state.kind === "accepted" ? start.state.start : null;
11384
- if (!record3 || profileId === "" || !endedAt || !Number.isFinite(endedAtMs) || executedModel?.kind !== "llm") {
11679
+ if (!record4 || profileId === "" || !endedAt || !Number.isFinite(endedAtMs) || executedModel?.kind !== "llm") {
11385
11680
  return void 0;
11386
11681
  }
11387
11682
  const expiresAtMs = endedAtMs + PROMPT_CACHE_WARM_MS;
@@ -11685,12 +11980,14 @@ import { parseDurationMs as parseDurationMs2 } from "@leitwerk-dev/watcher-utils
11685
11980
  import { preflightHostDocker } from "@leitwerk-dev/worker-runners/local";
11686
11981
  function resolveKubernetesDockerConfig(config) {
11687
11982
  const docker = config.kubernetes?.docker;
11688
- if (!docker?.runtime_class_name?.trim() || (docker.gvisor ? docker.host_users !== void 0 : typeof docker.host_users !== "boolean") || !docker.process_storage_class_name?.trim()) {
11983
+ const { isolation, errors } = resolveKubernetesDockerIsolation(docker);
11984
+ if (!docker?.runtime_class_name?.trim() || errors.length > 0 || isolation === void 0 && typeof docker.host_users !== "boolean" || !docker.process_storage_class_name?.trim()) {
11689
11985
  return void 0;
11690
11986
  }
11691
11987
  return {
11692
11988
  runtimeClassName: docker.runtime_class_name,
11693
- ...docker.gvisor ? { gvisor: true } : { hostUsers: docker.host_users },
11989
+ ...docker.node_selector ? { nodeSelector: { ...docker.node_selector } } : {},
11990
+ ...isolation ? { isolation } : { hostUsers: docker.host_users },
11694
11991
  processStorageClassName: docker.process_storage_class_name,
11695
11992
  ...docker.network ? { network: docker.network } : {}
11696
11993
  };
@@ -11702,7 +11999,7 @@ async function assertProcessRuntimeAvailable(deps, processId) {
11702
11999
  case "kubernetes":
11703
12000
  if (!resolveKubernetesDockerConfig(deps.config)) {
11704
12001
  throw new Error(
11705
- "This process requires Docker; configure kubernetes.docker.runtime_class_name, host_users, and process_storage_class_name"
12002
+ "This process requires Docker; configure kubernetes.docker.runtime_class_name, process_storage_class_name, and either isolation or host_users"
11706
12003
  );
11707
12004
  }
11708
12005
  return;
@@ -12271,7 +12568,7 @@ var DefaultProcessTitleGenerator = class {
12271
12568
  }
12272
12569
  async generateTitle(job) {
12273
12570
  const configuredProfile = this.config.pi.model_profiles.find(
12274
- (profile) => profile.id === job.modelProfileId
12571
+ (profile2) => profile2.id === job.modelProfileId
12275
12572
  );
12276
12573
  if (!configuredProfile) {
12277
12574
  return {
@@ -12722,6 +13019,527 @@ var ResultImageStore = class {
12722
13019
  }
12723
13020
  };
12724
13021
 
13022
+ // src/scoped-settings-service.ts
13023
+ import { normalize } from "node:path";
13024
+ import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
13025
+ import { SYSTEM_ACTOR as SYSTEM_ACTOR5 } from "@leitwerk-dev/domain";
13026
+ import { repositorySettingsIdentity } from "@leitwerk-dev/process-sdk";
13027
+ import { settingSelectionValues } from "@leitwerk-dev/protocol/http-contracts";
13028
+ var SettingsError = class extends Error {
13029
+ constructor(message, statusCode = 422) {
13030
+ super(message);
13031
+ this.statusCode = statusCode;
13032
+ }
13033
+ statusCode;
13034
+ };
13035
+ function normalizeSettingsLocator(locator) {
13036
+ const value = locator.trim();
13037
+ if (/^(\/|\.\/|\.\.\/|~\/)/.test(value)) return normalize(value);
13038
+ try {
13039
+ const url = new URL(value);
13040
+ if (url.password || (url.protocol === "https:" || url.protocol === "http:") && url.username)
13041
+ throw new SettingsError("Repository settings locators must not contain credentials");
13042
+ return url.toString();
13043
+ } catch (error) {
13044
+ if (error instanceof SettingsError) throw error;
13045
+ return value;
13046
+ }
13047
+ }
13048
+ function createScopedSettingsService(input) {
13049
+ const { repos, catalog } = input;
13050
+ const definitions = /* @__PURE__ */ new Map();
13051
+ const purposes = /* @__PURE__ */ new Map();
13052
+ const scopes = /* @__PURE__ */ new Map([
13053
+ ["instance", { id: "instance", label: "Instance" }],
13054
+ [
13055
+ "repository",
13056
+ {
13057
+ id: "repository",
13058
+ label: "Repository",
13059
+ overview: { itemLabel: "Repository", itemLabelPlural: "Repositories" }
13060
+ }
13061
+ ]
13062
+ ]);
13063
+ const discoveries = /* @__PURE__ */ new Map();
13064
+ for (const loaded of catalog.modules) {
13065
+ const owner = loaded.module.manifest.id;
13066
+ const declarations = loaded.module.scopedSettings;
13067
+ for (const scope of declarations?.scopes ?? []) {
13068
+ if (scopes.has(scope.id) || !scope.id.startsWith(`${owner}.`))
13069
+ throw new Error(`Invalid or duplicate settings scope '${scope.id}'`);
13070
+ scopes.set(scope.id, scope);
13071
+ }
13072
+ for (const definition of declarations?.settings ?? []) {
13073
+ if (definitions.has(definition.key) || !definition.key.startsWith(`${owner}.`))
13074
+ throw new Error(`Invalid or duplicate setting '${definition.key}'`);
13075
+ if (!Number.isSafeInteger(definition.schemaVersion) || definition.schemaVersion < 1 || definition.merge !== "replace" || !definition.scopes.length || new Set(definition.scopes).size !== definition.scopes.length)
13076
+ throw new Error(`Invalid setting declaration '${definition.key}'`);
13077
+ definition.schema.parse(definition.defaultValue);
13078
+ definitions.set(definition.key, { owner, definition });
13079
+ }
13080
+ for (const purpose of declarations?.purposes ?? []) {
13081
+ if (purposes.has(purpose.id) || !purpose.id.startsWith(`${owner}.`))
13082
+ throw new Error(`Invalid or duplicate execution purpose '${purpose.id}'`);
13083
+ purposes.set(purpose.id, purpose);
13084
+ }
13085
+ }
13086
+ for (const { definition } of definitions.values()) {
13087
+ for (const scope of definition.scopes)
13088
+ if (!scopes.has(scope)) throw new Error(`Unknown scope '${scope}' for '${definition.key}'`);
13089
+ }
13090
+ for (const purpose of purposes.values()) {
13091
+ for (const key of [
13092
+ ...purpose.settingKeys ?? [],
13093
+ ...purpose.modelSettingKey ? [purpose.modelSettingKey] : []
13094
+ ]) {
13095
+ if (!definitions.has(key)) throw new Error(`Unknown setting '${key}' for '${purpose.id}'`);
13096
+ }
13097
+ }
13098
+ for (const process2 of catalog.processes.values())
13099
+ for (const binding2 of process2.turns.values()) {
13100
+ const def = binding2.definition;
13101
+ if (def.kind === "llm" && def.executionPurpose && !purposes.has(def.executionPurpose))
13102
+ throw new Error(`Unknown execution purpose '${def.executionPurpose}'`);
13103
+ }
13104
+ const instance = repos.scopedSettings.findIdentity("instance", "installation") ?? repos.scopedSettings.putSubject({
13105
+ id: "instance",
13106
+ scopeType: "instance",
13107
+ identity: "installation",
13108
+ label: "Instance",
13109
+ context: {}
13110
+ });
13111
+ const choiceValues = settingSelectionValues;
13112
+ function requireSubject(id) {
13113
+ const subject = repos.scopedSettings.getSubject(id);
13114
+ if (!subject) throw new SettingsError("Settings scope was not found", 404);
13115
+ return subject;
13116
+ }
13117
+ function requireDefinition(key) {
13118
+ const definition = definitions.get(key)?.definition;
13119
+ if (!definition)
13120
+ throw new SettingsError(
13121
+ `Setting '${key}' is inactive. Install its owning extension to edit it.`,
13122
+ 409
13123
+ );
13124
+ return definition;
13125
+ }
13126
+ function contextForSubject(subject) {
13127
+ return { instance: instance.id, ...subject.context, [subject.scopeType]: subject.id };
13128
+ }
13129
+ function parse(definition, value) {
13130
+ try {
13131
+ const parsed = definition.schema.parse(value);
13132
+ if (JSON.stringify(parsed) === void 0) throw new Error("Value must be JSON-compatible");
13133
+ if (definition.form.control === "model" && parsed !== null && (typeof parsed !== "string" || !input.config.pi.model_profiles.some((profile2) => profile2.id === parsed)))
13134
+ throw new Error(`Unknown model profile '${String(parsed)}'`);
13135
+ return parsed;
13136
+ } catch (error) {
13137
+ throw new SettingsError(
13138
+ `${definition.form.label}: ${error instanceof Error ? error.message : "Invalid value"}. Correct '${definition.key}' in Settings.`
13139
+ );
13140
+ }
13141
+ }
13142
+ function resolveDefinition(definition, context, draft, omitSubject) {
13143
+ let value = definition.schema.parse(definition.defaultValue);
13144
+ let sources = [
13145
+ {
13146
+ subjectId: null,
13147
+ scopeType: "default",
13148
+ label: "Code default",
13149
+ revision: 0,
13150
+ schemaVersion: definition.schemaVersion,
13151
+ mode: "replace"
13152
+ }
13153
+ ];
13154
+ for (const scopeType of definition.scopes) {
13155
+ const contextId = scopeType === "instance" ? instance.id : context[scopeType];
13156
+ if (!contextId) continue;
13157
+ const subject = requireSubject(contextId);
13158
+ const subjectId = subject.id;
13159
+ if (subjectId === omitSubject) continue;
13160
+ if (subject.scopeType !== scopeType)
13161
+ throw new SettingsError(`Scope '${subjectId}' does not belong to '${scopeType}'`);
13162
+ const row = draft?.subjectId === subjectId && draft.key === definition.key ? draft : repos.scopedSettings.getOverride(subjectId, definition.key);
13163
+ if (!row || row.reset) continue;
13164
+ if (row.schemaVersion !== definition.schemaVersion)
13165
+ throw new SettingsError(
13166
+ `${definition.form.label} on ${subject.label} uses an incompatible schema. Correct '${definition.key}' in Settings.`
13167
+ );
13168
+ if (row.mode !== "replace")
13169
+ throw new SettingsError(
13170
+ `Append overrides are no longer supported. Reset '${definition.key}' in Settings.`
13171
+ );
13172
+ value = parse(definition, row.value);
13173
+ const source = {
13174
+ subjectId,
13175
+ scopeType,
13176
+ label: subject.label,
13177
+ revision: row.revision,
13178
+ schemaVersion: row.schemaVersion,
13179
+ mode: row.mode
13180
+ };
13181
+ sources = [source];
13182
+ }
13183
+ return { key: definition.key, value, sources };
13184
+ }
13185
+ function discover(subjectInput) {
13186
+ if (!scopes.has(subjectInput.scopeType))
13187
+ throw new SettingsError(`Unknown settings scope '${subjectInput.scopeType}'`);
13188
+ if (!subjectInput.identity.trim() || !subjectInput.label.trim())
13189
+ throw new SettingsError("Scope identity and label are required");
13190
+ const aliases = subjectInput.scopeType === "repository" ? (subjectInput.aliases ?? []).map(normalizeSettingsLocator) : [];
13191
+ return repos.transaction((tx) => {
13192
+ const repo = tx.scopedSettings;
13193
+ let previous = repo.findIdentity(subjectInput.scopeType, subjectInput.identity);
13194
+ const candidates = /* @__PURE__ */ new Map();
13195
+ if (previous) candidates.set(previous.id, previous);
13196
+ for (const alias of aliases) {
13197
+ const known = repo.findAlias(alias);
13198
+ if (!known) continue;
13199
+ if (known.identity !== subjectInput.identity && !known.identity.startsWith("locator:"))
13200
+ throw new SettingsError(
13201
+ `Repository alias '${alias}' belongs to another provider identity`,
13202
+ 409
13203
+ );
13204
+ candidates.set(known.id, known);
13205
+ }
13206
+ previous ??= [...candidates.values()].sort((a, b) => a.id.localeCompare(b.id))[0];
13207
+ if (candidates.size > 1) {
13208
+ if (subjectInput.identity.startsWith("locator:"))
13209
+ throw new SettingsError("Repository aliases require a verified provider identity", 409);
13210
+ const overrides = /* @__PURE__ */ new Map();
13211
+ for (const candidate of candidates.values()) {
13212
+ for (const row of repo.listOverrides(candidate.id)) {
13213
+ if (row.reset) continue;
13214
+ const saved = overrides.get(row.key);
13215
+ if (saved && (saved.mode !== row.mode || saved.schemaVersion !== row.schemaVersion || !isDeepStrictEqual2(saved.value, row.value)))
13216
+ throw new SettingsError(
13217
+ `Repository aliases have conflicting overrides for '${row.key}'. Compare /settings?scope=${saved.subjectId} and /settings?scope=${row.subjectId}; make the values and modes agree or use inherited value on one scope, then refresh repositories.`,
13218
+ 409
13219
+ );
13220
+ overrides.set(row.key, row);
13221
+ }
13222
+ }
13223
+ for (const candidate of candidates.values())
13224
+ if (previous && candidate.id !== previous.id)
13225
+ repo.mergeLocatorSubject(candidate.id, previous.id);
13226
+ }
13227
+ const context = subjectInput.context ?? previous?.context ?? {};
13228
+ for (const [type, id] of Object.entries(context))
13229
+ if (requireSubject(id).scopeType !== type || type === subjectInput.scopeType)
13230
+ throw new SettingsError("Invalid scope ancestry");
13231
+ const changed = !previous || previous.identity !== subjectInput.identity || previous.label !== subjectInput.label || JSON.stringify(previous.context) !== JSON.stringify(context);
13232
+ const subject = changed || !previous ? repo.putSubject({ ...subjectInput, id: previous?.id, context }) : previous;
13233
+ for (const alias of aliases) repo.putAlias(alias, subject.id);
13234
+ return subject;
13235
+ });
13236
+ }
13237
+ function repository(project) {
13238
+ const locator = normalizeSettingsLocator(project.repoLocator);
13239
+ const binding2 = project.metadata?.settingsRepository;
13240
+ if (binding2 && typeof binding2 === "object" && "origin" in binding2 && "repositoryId" in binding2 && typeof binding2.origin === "string" && (typeof binding2.repositoryId === "string" || typeof binding2.repositoryId === "number")) {
13241
+ const aliases = "aliases" in binding2 && Array.isArray(binding2.aliases) ? binding2.aliases.filter((alias) => typeof alias === "string") : [];
13242
+ const identity = repositorySettingsIdentity(binding2.origin, binding2.repositoryId);
13243
+ const known2 = repos.scopedSettings.findIdentity("repository", identity);
13244
+ return discover({
13245
+ scopeType: "repository",
13246
+ identity,
13247
+ label: known2?.label ?? locator,
13248
+ aliases: [locator, ...aliases]
13249
+ });
13250
+ }
13251
+ const known = repos.scopedSettings.findAlias(locator);
13252
+ if (known) return known;
13253
+ return discover({
13254
+ scopeType: "repository",
13255
+ identity: `locator:${locator}`,
13256
+ label: locator,
13257
+ aliases: [locator]
13258
+ });
13259
+ }
13260
+ function contextFor(process2, projects, preview2 = false) {
13261
+ const supplied = process2.metadata?.settingsContext;
13262
+ const context = { instance: instance.id };
13263
+ if (supplied && typeof supplied === "object")
13264
+ for (const [type, id] of Object.entries(supplied)) {
13265
+ if (typeof id !== "string" || requireSubject(id).scopeType !== type)
13266
+ throw new SettingsError("Invalid retained settings context");
13267
+ context[type] = id;
13268
+ }
13269
+ const subjects = projects.map((project) => ({ project, subject: repository(project) }));
13270
+ const primaryKey = process2.metadata?.primaryRepositoryKey;
13271
+ const primary = typeof primaryKey === "string" ? subjects.find((entry) => entry.project.key === primaryKey) : subjects.length === 1 ? subjects[0] : void 0;
13272
+ if (typeof primaryKey === "string" && !primary)
13273
+ throw new SettingsError(`Primary repository '${primaryKey}' is no longer bound`);
13274
+ if (!preview2 || projects.length > 0) delete context.repository;
13275
+ if (primary) context.repository = primary.subject.id;
13276
+ return {
13277
+ context,
13278
+ subjects,
13279
+ explanations: subjects.length > 1 && !primary ? ["No primary repository is bound. Process-wide model defaults use Instance settings."] : []
13280
+ };
13281
+ }
13282
+ function purposeFor(processId, turnId) {
13283
+ const turn = catalog.processes.get(processId)?.turns.get(turnId)?.definition;
13284
+ return turn?.kind === "llm" && turn.executionPurpose ? purposes.get(turn.executionPurpose) : void 0;
13285
+ }
13286
+ function forProcess(process2) {
13287
+ return contextFor(process2, repos.projects.listByInstance(process2.id));
13288
+ }
13289
+ function capture(process2, turnId, includeModelDefault = true) {
13290
+ const purpose = purposeFor(process2.processId, turnId);
13291
+ if (!purpose) return void 0;
13292
+ const { context, explanations } = forProcess(process2);
13293
+ const keys = /* @__PURE__ */ new Set([
13294
+ ...purpose.settingKeys ?? [],
13295
+ ...includeModelDefault && purpose.modelSettingKey ? [purpose.modelSettingKey] : []
13296
+ ]);
13297
+ const values = [...keys].map((key) => resolveDefinition(requireDefinition(key), context));
13298
+ return { version: 1, purpose: purpose.id, context, values, explanations };
13299
+ }
13300
+ function modelDefault(processId, turnId, process2, plan) {
13301
+ const purpose = purposeFor(processId, turnId);
13302
+ if (!purpose?.modelSettingKey) return null;
13303
+ const context = process2 ? forProcess(process2).context : plan ? contextFor(plan.processInput, plan.projectInputs, plan.preview).context : { instance: instance.id };
13304
+ const value = resolveDefinition(requireDefinition(purpose.modelSettingKey), context).value;
13305
+ if (value !== null && typeof value !== "string")
13306
+ throw new SettingsError(`Purpose '${purpose.id}' must select a model profile or null`);
13307
+ return value;
13308
+ }
13309
+ function definitionView(owner, definition) {
13310
+ const { key, schemaVersion, scopes: scopes2, merge, form } = definition;
13311
+ return { key, owner, schemaVersion, scopes: scopes2, merge, form };
13312
+ }
13313
+ async function preview(subjectId, draft) {
13314
+ const subject = requireSubject(subjectId);
13315
+ const context = contextForSubject(subject);
13316
+ const fields = [];
13317
+ for (const { owner, definition } of definitions.values()) {
13318
+ if (!definition.scopes.includes(subject.scopeType)) continue;
13319
+ let effective = null;
13320
+ let inherited = null;
13321
+ let error = null;
13322
+ let choices2 = [];
13323
+ try {
13324
+ inherited = resolveDefinition(definition, context, void 0, subject.id);
13325
+ effective = resolveDefinition(definition, context, draft);
13326
+ if (definition.form.control === "model") choices2 = input.modelChoices?.() ?? [];
13327
+ else if (definition.choiceLabel) {
13328
+ const label = definition.choiceLabel;
13329
+ choices2 = choiceValues(effective.value).map((value) => ({ value, label: label(value) }));
13330
+ }
13331
+ if (definition.form.control === "model" && effective.value !== null) {
13332
+ const selected = choices2.find((choice) => choice.value === effective?.value);
13333
+ if (selected?.disabledReason)
13334
+ error = `${selected.label}: ${selected.disabledReason}. Restore availability or choose another model before execution.`;
13335
+ }
13336
+ } catch (caught) {
13337
+ error = caught instanceof Error ? caught.message : "Could not resolve setting";
13338
+ }
13339
+ fields.push({
13340
+ ...definitionView(owner, definition),
13341
+ choices: choices2,
13342
+ ...definition.choices && definition.form.control !== "model" ? { choicesDeferred: true } : {},
13343
+ inherited,
13344
+ effective,
13345
+ override: repos.scopedSettings.getOverride(subject.id, definition.key),
13346
+ error
13347
+ });
13348
+ }
13349
+ return {
13350
+ subject,
13351
+ fields,
13352
+ inactive: repos.scopedSettings.listOverrides(subjectId).filter((row) => !row.reset && !definitions.has(row.key))
13353
+ };
13354
+ }
13355
+ async function choices(subjectId, key, search = "") {
13356
+ const subject = requireSubject(subjectId);
13357
+ const definition = requireDefinition(key);
13358
+ if (!definition.scopes.includes(subject.scopeType))
13359
+ throw new SettingsError(`'${key}' does not apply to ${subject.scopeType}`);
13360
+ if (definition.form.control === "model") return input.modelChoices?.() ?? [];
13361
+ if (search.trim().length < (definition.form.search?.minimumLength ?? 0)) return [];
13362
+ const context = contextForSubject(subject);
13363
+ const values = choiceValues(resolveDefinition(definition, context).value);
13364
+ return await definition.choices?.(context, { search, values }) ?? [];
13365
+ }
13366
+ function validateWrite({
13367
+ subjectId,
13368
+ key,
13369
+ value,
13370
+ mode,
13371
+ reset
13372
+ }) {
13373
+ const subject = requireSubject(subjectId);
13374
+ const definition = requireDefinition(key);
13375
+ if (!definition.scopes.includes(subject.scopeType))
13376
+ throw new SettingsError(`'${key}' does not apply to ${subject.scopeType}`);
13377
+ mode ??= "replace";
13378
+ if (mode !== "replace")
13379
+ throw new SettingsError("Settings overrides must replace inherited values");
13380
+ return {
13381
+ subjectId: subject.id,
13382
+ value: reset ? null : parse(definition, value),
13383
+ mode,
13384
+ schemaVersion: definition.schemaVersion
13385
+ };
13386
+ }
13387
+ function write(change) {
13388
+ if (!Number.isSafeInteger(change.expectedRevision) || change.expectedRevision < 0)
13389
+ throw new SettingsError("expectedRevision must be a non-negative integer", 400);
13390
+ const updated = repos.scopedSettings.write({ ...change, ...validateWrite(change) });
13391
+ if (!updated)
13392
+ throw new SettingsError(
13393
+ "This setting changed since you opened it. Your draft is preserved. Reload the current revision before saving again.",
13394
+ 409
13395
+ );
13396
+ return updated;
13397
+ }
13398
+ function listScopes() {
13399
+ discoverLocal();
13400
+ const scopesWithFields = new Set(
13401
+ [...definitions.values()].flatMap(({ definition }) => definition.scopes)
13402
+ );
13403
+ const subjectsWithInactiveOverrides = new Set(
13404
+ repos.scopedSettings.listOverrides().filter((row) => !row.reset && !definitions.has(row.key)).map((row) => row.subjectId)
13405
+ );
13406
+ const subjects = repos.scopedSettings.listSubjects();
13407
+ const byId = new Map(subjects.map((subject) => [subject.id, subject]));
13408
+ return {
13409
+ scopes: [...scopes.values()],
13410
+ subjects: subjects.filter((subject) => {
13411
+ const providers = discoveries.get(subject.scopeType);
13412
+ if (!providers) return true;
13413
+ const context = Object.fromEntries(
13414
+ Object.entries(subject.context).flatMap(([scope, id]) => {
13415
+ const parent = byId.get(id);
13416
+ return parent ? [[scope, parent]] : [];
13417
+ })
13418
+ );
13419
+ return providers.some(
13420
+ ({ includesSubject: includes }) => !includes || includes(subject, context)
13421
+ );
13422
+ }).map((subject) => ({
13423
+ ...subject,
13424
+ active: scopes.has(subject.scopeType),
13425
+ hasSettings: scopesWithFields.has(subject.scopeType) || subjectsWithInactiveOverrides.has(subject.id)
13426
+ }))
13427
+ };
13428
+ }
13429
+ function discoverLocal() {
13430
+ for (const [key, component] of Object.entries(input.config.components))
13431
+ repository({ key, repoLocator: component.repo });
13432
+ for (const project of repos.projects.listAll()) {
13433
+ try {
13434
+ repository(project);
13435
+ } catch (error) {
13436
+ if (!(error instanceof SettingsError) || error.statusCode !== 409) throw error;
13437
+ }
13438
+ }
13439
+ }
13440
+ discoverLocal();
13441
+ return {
13442
+ async overview(scopeType) {
13443
+ const subjects = listScopes().subjects.filter(
13444
+ (subject) => subject.scopeType === scopeType && subject.hasSettings
13445
+ );
13446
+ return {
13447
+ items: await Promise.all(
13448
+ subjects.map(async (subject) => {
13449
+ const result = await preview(subject.id);
13450
+ const mappingFields = result.fields.filter(
13451
+ (field) => field.form.overview === "repository-mapping"
13452
+ );
13453
+ return {
13454
+ subjectId: subject.id,
13455
+ customized: [
13456
+ ...result.fields.filter((field) => field.override && !field.override.reset).map((field) => field.form.label),
13457
+ ...result.inactive.map((field) => field.key)
13458
+ ],
13459
+ ...mappingFields.length ? {
13460
+ mapping: mappingFields.flatMap(
13461
+ (field) => settingSelectionValues(field.effective?.value).map(
13462
+ (value) => field.choices.find((choice) => choice.value === value) ?? {
13463
+ value,
13464
+ label: "Unavailable repository"
13465
+ }
13466
+ )
13467
+ )
13468
+ } : {},
13469
+ errors: result.fields.flatMap((field) => field.error ? [field.error] : [])
13470
+ };
13471
+ })
13472
+ )
13473
+ };
13474
+ },
13475
+ resolve: (definition, context) => resolveDefinition(requireDefinition(definition.key), context),
13476
+ findSubject: (scopeType, identity) => repos.scopedSettings.findIdentity(scopeType, identity),
13477
+ getSubject: (id) => repos.scopedSettings.getSubject(id),
13478
+ seedOverride(subjectId, definition, value) {
13479
+ const subject = requireSubject(subjectId);
13480
+ if (repos.scopedSettings.getOverride(subject.id, definition.key)) return false;
13481
+ write({
13482
+ subjectId: subject.id,
13483
+ key: definition.key,
13484
+ value,
13485
+ mode: "replace",
13486
+ reset: false,
13487
+ expectedRevision: 0,
13488
+ actor: SYSTEM_ACTOR5
13489
+ });
13490
+ return true;
13491
+ },
13492
+ discover,
13493
+ registerDiscovery(scopeType, discoverer, options) {
13494
+ if (!scopes.has(scopeType)) throw new SettingsError(`Unknown scope '${scopeType}'`);
13495
+ discoveries.set(scopeType, [
13496
+ ...discoveries.get(scopeType) ?? [],
13497
+ { discover: discoverer, includesSubject: options?.includesSubject }
13498
+ ]);
13499
+ },
13500
+ capture,
13501
+ modelDefault,
13502
+ preview,
13503
+ choices,
13504
+ write,
13505
+ listScopes,
13506
+ forProcess,
13507
+ forLaunch: (plan) => contextFor(plan.processInput, plan.projectInputs, plan.preview),
13508
+ previewProcess(process2) {
13509
+ return [...catalog.processes.get(process2.processId)?.turns.keys() ?? []].filter((turnId) => purposeFor(process2.processId, turnId)).map((turnId) => {
13510
+ try {
13511
+ return { turnId, settings: capture(process2, turnId) ?? null, error: null };
13512
+ } catch (caught) {
13513
+ return {
13514
+ turnId,
13515
+ settings: null,
13516
+ error: caught instanceof Error ? caught.message : "Invalid scoped settings"
13517
+ };
13518
+ }
13519
+ });
13520
+ },
13521
+ definitions: () => [...definitions.values()].map(({ owner, definition }) => definitionView(owner, definition)),
13522
+ async refresh() {
13523
+ discoverLocal();
13524
+ for (const [scope, providers] of discoveries)
13525
+ for (const { discover: provider } of providers)
13526
+ for (const subject of await provider()) {
13527
+ if (subject.scopeType !== scope)
13528
+ throw new SettingsError("Discovery returned a different scope type");
13529
+ discover(subject);
13530
+ }
13531
+ return listScopes();
13532
+ },
13533
+ async previewDraft(change) {
13534
+ return preview(change.subjectId, {
13535
+ ...change,
13536
+ ...validateWrite(change),
13537
+ revision: 0
13538
+ });
13539
+ }
13540
+ };
13541
+ }
13542
+
12725
13543
  // src/server-bootstrap/app-lifecycle.ts
12726
13544
  async function collectCleanupErrors(operations) {
12727
13545
  const errors = [];
@@ -12856,16 +13674,42 @@ function createAppLifecycle(input) {
12856
13674
 
12857
13675
  // src/server-bootstrap/build-host-capabilities.ts
12858
13676
  import path3 from "node:path";
12859
- import { SYSTEM_ACTOR as SYSTEM_ACTOR5 } from "@leitwerk-dev/domain";
13677
+ import { SYSTEM_ACTOR as SYSTEM_ACTOR6 } from "@leitwerk-dev/domain";
12860
13678
  import {
12861
13679
  coreHostCapabilities,
12862
13680
  createCapabilityAccessor
12863
13681
  } from "@leitwerk-dev/process-sdk";
13682
+ import { createWikiIntegration, topicWikiCapability } from "@leitwerk-dev/wiki/integration";
12864
13683
  function buildHostCapabilities(input) {
12865
13684
  const hostCapabilities = createCapabilityAccessor([
13685
+ { token: topicWikiCapability, value: createWikiIntegration(input.baseDeps.topicWiki) },
12866
13686
  {
12867
13687
  token: coreHostCapabilities.serverSetup,
12868
13688
  value: {
13689
+ async callIntegrationTool(expected, projectKey, name, args, signal) {
13690
+ const process2 = input.baseDeps.processes.getById(expected.id);
13691
+ if (!process2 || process2.lifecycleStatus !== expected.lifecycleStatus || process2.selectedTurnId !== expected.selectedTurnId || process2.paramsJson !== expected.paramsJson || process2.stateJson !== expected.stateJson || process2.planRevision !== expected.planRevision)
13692
+ throw new Error("Process changed before maintenance delivery");
13693
+ const projects = input.baseDeps.projects.listByInstance(process2.id);
13694
+ const project = projects.find((candidate) => candidate.key === projectKey);
13695
+ const turn = input.baseDeps.turnRecords.listByInstance(process2.id).at(-1);
13696
+ if (!project || !turn)
13697
+ throw new Error(
13698
+ "Maintenance delivery requires a bound project and publication history"
13699
+ );
13700
+ return input.integrationTools.executeServer(
13701
+ name,
13702
+ { ...args, projectKey },
13703
+ {
13704
+ process: process2,
13705
+ projects,
13706
+ project,
13707
+ turn,
13708
+ idempotencyKey: `maintenance:${process2.id}:${projectKey}:${name}`
13709
+ },
13710
+ signal
13711
+ );
13712
+ },
12869
13713
  get serverBaseUrl() {
12870
13714
  return input.config.server.base_url;
12871
13715
  },
@@ -12874,6 +13718,7 @@ function buildHostCapabilities(input) {
12874
13718
  },
12875
13719
  components: input.config.components,
12876
13720
  externalWrites: input.baseDeps.externalWrites,
13721
+ publications: input.baseDeps.publications,
12877
13722
  processes: input.baseDeps.processes,
12878
13723
  projects: input.projectMutations,
12879
13724
  events: input.baseDeps.events,
@@ -12899,13 +13744,13 @@ function buildHostCapabilities(input) {
12899
13744
  startProgrammatic(request, opts) {
12900
13745
  return input.launchCoordinator.startProgrammatic(request, {
12901
13746
  idempotencyKey: opts.idempotencyKey,
12902
- actor: opts.actor ?? SYSTEM_ACTOR5
13747
+ actor: opts.actor ?? SYSTEM_ACTOR6
12903
13748
  });
12904
13749
  },
12905
13750
  startWatcher(watcher, event, opts) {
12906
13751
  return input.launchCoordinator.startWatcher(watcher, event, {
12907
13752
  idempotencyKey: opts.idempotencyKey,
12908
- actor: opts.actor ?? SYSTEM_ACTOR5
13753
+ actor: opts.actor ?? SYSTEM_ACTOR6
12909
13754
  });
12910
13755
  }
12911
13756
  },
@@ -12947,6 +13792,9 @@ async function loadServerExtensionCatalog(input) {
12947
13792
  return { extensionLoadingStartDir, resolvedExtensionEntries, extensionCatalog };
12948
13793
  }
12949
13794
 
13795
+ // src/server-bootstrap/register-http.ts
13796
+ import { registerTopicWikiRoutes } from "@leitwerk-dev/wiki/server";
13797
+
12950
13798
  // src/auth/api-token-audit.ts
12951
13799
  function registerApiTokenAudit(app) {
12952
13800
  app.addHook("onResponse", async (request, reply) => {
@@ -13434,6 +14282,7 @@ function registerInternalWorkerSessionSnapshotRoutes(input) {
13434
14282
  }
13435
14283
 
13436
14284
  // src/routes/future-executions.ts
14285
+ import { parseActionRequestBody } from "@leitwerk-dev/protocol";
13437
14286
  function registerFutureExecutionRoutes(app, deps, futureExecutionLifecycle) {
13438
14287
  app.post(
13439
14288
  "/api/future-executions/cron-preview",
@@ -13499,13 +14348,13 @@ function registerFutureExecutionRoutes(app, deps, futureExecutionLifecycle) {
13499
14348
  app.put(
13500
14349
  "/api/future-executions/:futureExecutionId/action",
13501
14350
  async (req, reply) => {
13502
- const normalized = normalizeActionRequest(req.body);
13503
- if (!normalized.ok) {
13504
- return sendActionRequestNormalizationError(reply, normalized.error);
14351
+ const parsed = parseActionRequestBody(req.body);
14352
+ if (!parsed.ok) {
14353
+ return sendActionRequestNormalizationError(reply, parsed.error);
13505
14354
  }
13506
14355
  const result = await futureExecutionLifecycle.reviseScheduledAction(
13507
14356
  req.params.futureExecutionId,
13508
- normalized.request,
14357
+ parsed.value,
13509
14358
  { actor: actorForRequest(req) }
13510
14359
  );
13511
14360
  return sendScheduledActionMutationResponse(reply, deps, result);
@@ -13535,7 +14384,7 @@ function registerLauncherRoutes(app, deps, futureExecutionLifecycle) {
13535
14384
  let modelConfig = launcher ? { defaultModelProfileId: null, turnConfigs: {} } : {};
13536
14385
  const warnings = [];
13537
14386
  if (launcher) {
13538
- const resolved = await deps.launcherService.resolveUiLauncher(
14387
+ const resolved = await deps.launcherService.resolveUiLauncherPreview(
13539
14388
  req.params.launcherId,
13540
14389
  defaults
13541
14390
  );
@@ -13582,6 +14431,47 @@ function registerLauncherRoutes(app, deps, futureExecutionLifecycle) {
13582
14431
  return body;
13583
14432
  }
13584
14433
  );
14434
+ app.post(
14435
+ "/api/launchers/:launcherId/validate",
14436
+ {
14437
+ schema: {
14438
+ querystring: {
14439
+ type: "object",
14440
+ properties: { futureExecutionId: { type: "string", minLength: 1, pattern: "\\S" } }
14441
+ }
14442
+ }
14443
+ },
14444
+ async (req, reply) => {
14445
+ const normalized = normalizeLauncherRequest(req.body);
14446
+ if (!normalized.ok) {
14447
+ return sendLauncherRequestNormalizationError(reply, normalized.error);
14448
+ }
14449
+ try {
14450
+ const resolved = await deps.launcherService.resolveUiLauncherPreview(
14451
+ req.params.launcherId,
14452
+ normalized.request.launcherInput
14453
+ );
14454
+ if (!resolved.ok)
14455
+ return { errors: resolved.errors };
14456
+ const result = await futureExecutionLifecycle.prepareLaunch(
14457
+ req.params.launcherId,
14458
+ normalized.request,
14459
+ {
14460
+ resolvedLauncher: resolved.launcher,
14461
+ futureExecutionId: req.query.futureExecutionId
14462
+ }
14463
+ );
14464
+ if (result.ok) return { errors: [] };
14465
+ if (result.outcome.kind === "invalid") {
14466
+ return { errors: result.outcome.issues };
14467
+ }
14468
+ return sendLauncherMutationResponse(reply, deps, result.outcome);
14469
+ } catch (error) {
14470
+ if (sendLauncherLookupFailure(reply, error)) return;
14471
+ throw error;
14472
+ }
14473
+ }
14474
+ );
13585
14475
  app.post(
13586
14476
  "/api/launchers/:launcherId/model-config-preview",
13587
14477
  async (req, reply) => {
@@ -13593,6 +14483,7 @@ function registerLauncherRoutes(app, deps, futureExecutionLifecycle) {
13593
14483
  try {
13594
14484
  previewResult = await buildLauncherModelConfigPreviewForLauncher({
13595
14485
  launcherService: deps.launcherService,
14486
+ scopedSettingsService: deps.scopedSettingsService,
13596
14487
  launchPlans: deps.launchPlans,
13597
14488
  launcherId: req.params.launcherId,
13598
14489
  launcherInput: normalized.request.launcherInput,
@@ -13716,6 +14607,9 @@ function registerLauncherRoutes(app, deps, futureExecutionLifecycle) {
13716
14607
  );
13717
14608
  }
13718
14609
 
14610
+ // src/routes/process-actions.ts
14611
+ import { parseActionRequestBody as parseActionRequestBody2 } from "@leitwerk-dev/protocol";
14612
+
13719
14613
  // src/routes/process-engine-http.ts
13720
14614
  function mapEngineFailure(result, variant) {
13721
14615
  if (isInternalEngineFailureCode(result.code)) {
@@ -13807,7 +14701,7 @@ function registerProcessActionRoutes(app, deps, futureExecutionLifecycle) {
13807
14701
  return reply.code(503).send({ error: "Model provider catalog is unavailable" });
13808
14702
  }
13809
14703
  const config = routeConfig(deps);
13810
- const profile = config.pi.model_profiles.find(
14704
+ const profile2 = config.pi.model_profiles.find(
13811
14705
  (candidate) => candidate.id === req.params.modelProfileId
13812
14706
  );
13813
14707
  const profiles = deps.processModelPolicy.project({
@@ -13816,10 +14710,10 @@ function registerProcessActionRoutes(app, deps, futureExecutionLifecycle) {
13816
14710
  availability: deps.modelStatusCache.snapshot()
13817
14711
  });
13818
14712
  const allowed = profiles.some((candidate) => candidate.id === req.params.modelProfileId);
13819
- if (!profile || !allowed) {
14713
+ if (!profile2 || !allowed) {
13820
14714
  return reply.code(404).send({ error: "Model profile not found" });
13821
14715
  }
13822
- const provider = deps.modelProviderRegistry.require(profile.provider);
14716
+ const provider = deps.modelProviderRegistry.require(profile2.provider);
13823
14717
  const choicesResult = await loadProviderOptionChoices({
13824
14718
  provider,
13825
14719
  credentialStatus: deps.modelProviderCredentialStatus
@@ -13827,7 +14721,7 @@ function registerProcessActionRoutes(app, deps, futureExecutionLifecycle) {
13827
14721
  const fields = Object.entries(provider.definition.options?.fields ?? {}).map(
13828
14722
  ([fieldId, field]) => {
13829
14723
  const declaredDefault = typeof field.defaultValue === "function" ? field.defaultValue({ config: provider.config }) : field.defaultValue;
13830
- const profileDefault = profile.provider_options?.[fieldId];
14724
+ const profileDefault = profile2.provider_options?.[fieldId];
13831
14725
  return {
13832
14726
  id: fieldId,
13833
14727
  label: field.label,
@@ -13840,8 +14734,8 @@ function registerProcessActionRoutes(app, deps, futureExecutionLifecycle) {
13840
14734
  }
13841
14735
  );
13842
14736
  return {
13843
- modelProfileId: profile.id,
13844
- providerId: profile.provider,
14737
+ modelProfileId: profile2.id,
14738
+ providerId: profile2.provider,
13845
14739
  fields,
13846
14740
  choicesStatus: choicesResult.ok ? "available" : "unavailable",
13847
14741
  choicesUnavailableReason: choicesResult.ok ? null : choicesResult.safeReason
@@ -13972,28 +14866,28 @@ function registerProcessActionRoutes(app, deps, futureExecutionLifecycle) {
13972
14866
  if (!process2) {
13973
14867
  return null;
13974
14868
  }
13975
- const normalized = normalizeActionRequest(req.body);
13976
- if (!normalized.ok) {
13977
- sendActionRequestNormalizationError(reply, normalized.error);
14869
+ const parsed = parseActionRequestBody2(req.body);
14870
+ if (!parsed.ok) {
14871
+ sendActionRequestNormalizationError(reply, parsed.error);
13978
14872
  return null;
13979
14873
  }
13980
14874
  return {
13981
14875
  process: process2,
13982
- request: normalized.request,
14876
+ request: parsed.value,
13983
14877
  processActionRegistry: deps.processActionRegistry
13984
14878
  };
13985
14879
  }
13986
14880
  app.post(
13987
14881
  "/api/processes/:instanceId/actions/:actionId/model-preview",
13988
14882
  async (req, reply) => {
13989
- const normalized = normalizeActionRequest(req.body);
13990
- if (!normalized.ok) {
13991
- return sendActionRequestNormalizationError(reply, normalized.error);
14883
+ const parsed = parseActionRequestBody2(req.body);
14884
+ if (!parsed.ok) {
14885
+ return sendActionRequestNormalizationError(reply, parsed.error);
13992
14886
  }
13993
14887
  const result = await deps.processModelSelection.preview(
13994
14888
  req.params.instanceId,
13995
14889
  req.params.actionId,
13996
- normalized.request.input
14890
+ parsed.value.input
13997
14891
  );
13998
14892
  if (result.kind === "operational_failure") {
13999
14893
  if (result.code === "process_not_found") {
@@ -14035,6 +14929,336 @@ function registerProcessActionRoutes(app, deps, futureExecutionLifecycle) {
14035
14929
  );
14036
14930
  }
14037
14931
 
14932
+ // src/process-inspection-trace.ts
14933
+ import { createHash as createHash3 } from "node:crypto";
14934
+ import {
14935
+ asUnknownRecord as asUnknownRecord2
14936
+ } from "@leitwerk-dev/domain";
14937
+ function blocks(messageId, content) {
14938
+ const raw = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content : [];
14939
+ const occurrences = /* @__PURE__ */ new Map();
14940
+ return raw.flatMap((value) => {
14941
+ const block = asUnknownRecord2(value);
14942
+ if (!block) return [];
14943
+ let safe;
14944
+ if (block.type === "text" && typeof block.text === "string")
14945
+ safe = { type: "text", text: block.text };
14946
+ else if (block.type === "thinking" && typeof block.thinking === "string")
14947
+ safe = {
14948
+ type: "thinking",
14949
+ thinking: block.thinking,
14950
+ ...block.redacted === true ? { redacted: true } : {}
14951
+ };
14952
+ else if (block.type === "toolCall" && typeof block.id === "string" && typeof block.name === "string")
14953
+ safe = {
14954
+ type: "toolCall",
14955
+ id: block.id,
14956
+ name: block.name,
14957
+ arguments: asUnknownRecord2(block.arguments) ?? {}
14958
+ };
14959
+ else if (block.type === "image" && typeof block.data === "string" && typeof block.mimeType === "string")
14960
+ safe = { type: "image", data: block.data, mimeType: block.mimeType };
14961
+ else
14962
+ safe = {
14963
+ type: "text",
14964
+ text: `[Unsupported recorded ${String(block.type ?? "content")} block]`
14965
+ };
14966
+ const fingerprint = createHash3("sha256").update(JSON.stringify(safe)).digest("hex");
14967
+ const occurrence = occurrences.get(fingerprint) ?? 0;
14968
+ occurrences.set(fingerprint, occurrence + 1);
14969
+ const id = createHash3("sha256").update(`${messageId}\0${fingerprint}\0${occurrence}`).digest("hex").slice(0, 24);
14970
+ return [{ id: `block:${id}`, content: safe }];
14971
+ });
14972
+ }
14973
+ function buildInspectionTraceMessages(input) {
14974
+ const messages = [];
14975
+ const included = /* @__PURE__ */ new Set();
14976
+ const unassigned = input.scope === "unassigned_branch";
14977
+ const entries = unassigned ? input.record.resultPiEntryId ? input.tree.getBranch(input.record.resultPiEntryId) : [] : input.tree.entries;
14978
+ for (const entry of entries) {
14979
+ if (unassigned) {
14980
+ if (input.owner(entry.id) !== null || !["message", "custom_message"].includes(entry.type))
14981
+ continue;
14982
+ } else if (input.owner(entry.id) !== input.record.id) continue;
14983
+ const message = entry.type === "message" ? entry.message : entry.type === "custom_message" ? { role: "user", content: entry.content } : {
14984
+ role: entry.type,
14985
+ content: entry.type === "compaction" ? entry.summary : entry.type === "model_change" ? `Model changed to ${entry.provider}/${entry.modelId}` : `Recorded ${entry.type.replaceAll("_", " ")} session entry`
14986
+ };
14987
+ const record4 = message;
14988
+ const id = `entry:${entry.id}`;
14989
+ const link = input.captures.find(
14990
+ (item) => item.fact.kind === "entry_link" && item.fact.entryId === entry.id
14991
+ );
14992
+ const piTurnId = link?.fact.kind === "entry_link" ? link.fact.piTurnId : null;
14993
+ const aliases = link && piTurnId ? input.events.filter((event) => {
14994
+ if (event.data.workerLeaseId !== link.workerLeaseId || event.data.turnId !== piTurnId)
14995
+ return false;
14996
+ if (message.role === "assistant")
14997
+ return event.eventType === "pi.stream.delta" || ["pi.tool.call", "pi.tool.started"].includes(event.eventType) && Array.isArray(record4.content) && record4.content.some(
14998
+ (block) => block.type === "toolCall" && block.id === event.data.toolCallId
14999
+ );
15000
+ return message.role === "toolResult" && ["pi.tool.result", "pi.tool.completed"].includes(event.eventType) && event.data.toolCallId === record4.toolCallId;
15001
+ }).map((event) => `event:${event.eventSequence}`) : [];
15002
+ messages.push({
15003
+ id,
15004
+ entryId: entry.id,
15005
+ aliases,
15006
+ role: message.role,
15007
+ timestamp: entry.timestamp,
15008
+ blocks: blocks(id, record4.content),
15009
+ toolCallId: typeof record4.toolCallId === "string" ? record4.toolCallId : null,
15010
+ toolName: typeof record4.toolName === "string" ? record4.toolName : null,
15011
+ isError: record4.isError === true
15012
+ });
15013
+ included.add(entry.id);
15014
+ }
15015
+ if (unassigned) return messages;
15016
+ for (const capture of input.captures) {
15017
+ if (capture.fact.kind !== "model_input") continue;
15018
+ for (const message of capture.fact.messages) {
15019
+ if (message.role !== "user" || !message.entryId || included.has(message.entryId) || input.owner(message.entryId) !== input.record.id)
15020
+ continue;
15021
+ if (message.content.state !== "recorded" && message.content.state !== "redacted") continue;
15022
+ const id = `entry:${message.entryId}`;
15023
+ messages.push({
15024
+ id,
15025
+ entryId: message.entryId,
15026
+ aliases: [],
15027
+ role: message.role,
15028
+ timestamp: capture.timestamp,
15029
+ blocks: blocks(id, message.content.value),
15030
+ toolCallId: null,
15031
+ toolName: null,
15032
+ isError: false
15033
+ });
15034
+ included.add(message.entryId);
15035
+ }
15036
+ }
15037
+ return messages.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
15038
+ }
15039
+
15040
+ // src/process-inspection-reader.ts
15041
+ var ProcessInspectionReader = class {
15042
+ constructor(deps) {
15043
+ this.deps = deps;
15044
+ this.history = new ProcessUiSnapshotAssembler(deps);
15045
+ }
15046
+ deps;
15047
+ history;
15048
+ selected(instanceId, turnRecordId) {
15049
+ if (!this.deps.processes.getById(instanceId)) return null;
15050
+ const record4 = this.deps.turnRecords.getById(turnRecordId);
15051
+ return record4?.instanceId === instanceId ? record4 : null;
15052
+ }
15053
+ lineageSnapshot(instanceId) {
15054
+ return {
15055
+ records: this.deps.turnRecords.listByInstance(instanceId),
15056
+ leases: this.deps.leases.listByInstance(instanceId),
15057
+ observations: this.deps.executionInspections.listContextFacts(instanceId)
15058
+ };
15059
+ }
15060
+ /** No session or immutable-content reads are needed to open the shell. */
15061
+ summary(instanceId, turnRecordId) {
15062
+ const record4 = this.selected(instanceId, turnRecordId);
15063
+ if (!record4) return null;
15064
+ const records = this.deps.turnRecords.listByInstance(instanceId).sort((a, b) => a.startedAt.localeCompare(b.startedAt) || a.id.localeCompare(b.id));
15065
+ const index = records.findIndex((candidate) => candidate.id === turnRecordId);
15066
+ const start = record4.turnStartRecordId ? this.deps.turnStarts.getById(record4.turnStartRecordId) : null;
15067
+ const inputs = this.deps.executionInspections.modelInputs(instanceId, turnRecordId);
15068
+ const accepted = start && "start" in start.state && start.state.start?.kind === "llm" ? start.state.start.model : null;
15069
+ let model = record4.turnType === "llm" ? { state: "not_recorded", reason: "The historical model was not recorded" } : {
15070
+ state: "not_applicable",
15071
+ reason: `This ${record4.turnType} execution does not invoke a model`
15072
+ };
15073
+ const effective = inputs.at(-1)?.model;
15074
+ if (effective) model = { state: "recorded", value: effective };
15075
+ else if (accepted)
15076
+ model = {
15077
+ state: "recorded",
15078
+ value: {
15079
+ provider: accepted.providerId,
15080
+ id: accepted.modelId,
15081
+ thinkingLevel: accepted.thinkingLevel
15082
+ }
15083
+ };
15084
+ const { turnResultMarkdown: _output, ...execution } = record4;
15085
+ return {
15086
+ instanceId,
15087
+ execution,
15088
+ origin: createInspectionLineage(this.lineageSnapshot(instanceId)).origin(record4),
15089
+ startKind: start ? { state: "recorded", value: start.startKind } : { state: "not_recorded", reason: "Execution start kind was not recorded" },
15090
+ model,
15091
+ modelInputCount: inputs.length,
15092
+ usage: this.deps.turnSummaries.get(turnRecordId)?.usage ?? null,
15093
+ previousTurnRecordId: records[index - 1]?.id ?? null,
15094
+ nextTurnRecordId: records[index + 1]?.id ?? null
15095
+ };
15096
+ }
15097
+ missingModelEvidence(record4) {
15098
+ return record4.turnType === "llm" ? {
15099
+ state: "not_recorded",
15100
+ reason: "No model input was recorded for this execution. Historical instructions cannot be reconstructed from current settings."
15101
+ } : {
15102
+ state: "not_applicable",
15103
+ reason: `This ${record4.turnType} execution does not invoke a model`
15104
+ };
15105
+ }
15106
+ configuration(instanceId, turnRecordId) {
15107
+ const record4 = this.selected(instanceId, turnRecordId);
15108
+ if (!record4) return null;
15109
+ const revisions = this.deps.executionInspections.list(instanceId, turnRecordId).flatMap((capture) => {
15110
+ if (capture.fact.kind !== "model_input") return [];
15111
+ const { messages: _messages, kind: _kind, ...configuration } = capture.fact;
15112
+ return [{ id: capture.id, timestamp: capture.timestamp, ...configuration }];
15113
+ });
15114
+ return {
15115
+ instanceId,
15116
+ turnRecordId,
15117
+ revisions: revisions.length ? { state: "recorded", value: revisions } : this.missingModelEvidence(record4),
15118
+ currentWorkflowTurnId: record4.turnId
15119
+ };
15120
+ }
15121
+ async context(instanceId, turnRecordId) {
15122
+ const record4 = this.selected(instanceId, turnRecordId);
15123
+ if (!record4) return null;
15124
+ const lineageSnapshot = this.lineageSnapshot(instanceId);
15125
+ const captures = this.deps.executionInspections.list(instanceId, turnRecordId);
15126
+ const session = await this.deps.sessionReader.readSessionTree(instanceId);
15127
+ const lineage = createInspectionLineage({ ...lineageSnapshot, tree: session.piTree });
15128
+ const supplies = captures.filter((capture) => capture.fact.kind === "supplied_context");
15129
+ const products = supplies.flatMap(
15130
+ (capture) => capture.fact.kind === "supplied_context" ? capture.fact.products.map((product) => ({
15131
+ ...product,
15132
+ supplyId: capture.id,
15133
+ consumed: captures.some(
15134
+ (candidate) => candidate.fact.kind === "product_consumed" && `${turnRecordId}:${candidate.fact.supplyId}` === capture.id && candidate.fact.name === product.name
15135
+ )
15136
+ })) : []
15137
+ );
15138
+ const modelInputs = captures.flatMap(
15139
+ (capture) => capture.fact.kind === "model_input" ? [
15140
+ {
15141
+ id: capture.id,
15142
+ timestamp: capture.timestamp,
15143
+ boundaryEntryId: capture.fact.boundaryEntryId,
15144
+ model: capture.fact.model,
15145
+ messages: capture.fact.messages.map((message) => {
15146
+ const sourceTurnRecordId = message.entryId ? lineage.owner(message.entryId) : null;
15147
+ return {
15148
+ entryId: message.entryId,
15149
+ sourceTurnRecordId,
15150
+ role: message.role,
15151
+ content: sourceTurnRecordId && sourceTurnRecordId !== turnRecordId ? null : message.content
15152
+ };
15153
+ })
15154
+ }
15155
+ ] : []
15156
+ );
15157
+ const boundaries = new Set(
15158
+ modelInputs.map((revision) => revision.boundaryEntryId).filter((id) => id !== null)
15159
+ );
15160
+ if (record4.resultPiEntryId) boundaries.add(record4.resultPiEntryId);
15161
+ const contextEntries = new Map(
15162
+ [...boundaries].flatMap(
15163
+ (boundary) => session.piTree.getBranch(boundary).map((entry) => [entry.id, entry])
15164
+ )
15165
+ );
15166
+ const compactions = [...contextEntries.values()].flatMap(
15167
+ (entry) => entry.type === "compaction" ? [{ entryId: entry.id, firstKeptEntryId: entry.firstKeptEntryId, summary: entry.summary }] : []
15168
+ );
15169
+ const inputMessages = buildInspectionTraceMessages({
15170
+ tree: session.piTree,
15171
+ record: record4,
15172
+ captures,
15173
+ events: [],
15174
+ owner: lineage.owner
15175
+ }).filter((message) => message.role === "user" || message.role === "system");
15176
+ return {
15177
+ instanceId,
15178
+ turnRecordId,
15179
+ origin: lineage.origin(record4),
15180
+ ancestry: lineage.ancestry(record4),
15181
+ products: supplies.length ? { state: "recorded", value: products } : { state: "not_recorded", reason: "Supplied product versions were not recorded" },
15182
+ modelInputs: modelInputs.length ? { state: "recorded", value: modelInputs } : this.missingModelEvidence(record4),
15183
+ compactions,
15184
+ inputMessages
15185
+ };
15186
+ }
15187
+ async trace(instanceId, turnRecordId, target = {}) {
15188
+ const lineageSnapshot = this.lineageSnapshot(instanceId);
15189
+ const captures = this.deps.executionInspections.list(instanceId, turnRecordId);
15190
+ const annotations = this.deps.turnAnnotations.listByInstance(instanceId).filter(
15191
+ (annotation) => annotation.references.some(
15192
+ (reference) => reference.kind === "turn_record" && reference.turnRecordId === turnRecordId
15193
+ )
15194
+ );
15195
+ const evidence = await this.history.readReasoningEvidence({
15196
+ instanceId,
15197
+ turnRecordId,
15198
+ includeSession: true
15199
+ });
15200
+ if (!evidence?.session) return null;
15201
+ const { detail: history, turnRecord: record4, events, session } = evidence;
15202
+ const lineage = createInspectionLineage({ ...lineageSnapshot, tree: session.piTree });
15203
+ const messages = buildInspectionTraceMessages({
15204
+ tree: session.piTree,
15205
+ record: record4,
15206
+ captures,
15207
+ events,
15208
+ owner: lineage.owner
15209
+ });
15210
+ let targetState = null;
15211
+ let inheritedBoundary = null;
15212
+ const unavailable = {
15213
+ state: "unavailable",
15214
+ reason: "The requested item is unavailable or does not belong to this execution"
15215
+ };
15216
+ let itemId = target.entryId ? `entry:${target.entryId}` : target.itemId;
15217
+ if (itemId === "input")
15218
+ itemId = messages.find((message) => message.role === "user" || message.role === "system")?.id ?? itemId;
15219
+ if (itemId === "reasoning")
15220
+ itemId = messages.flatMap((message) => message.blocks).find((block) => block.content.type === "thinking")?.id ?? events.filter(
15221
+ (event) => event.eventType === "pi.stream.delta" && event.data.streamType === "thinking"
15222
+ ).map((event) => `event:${event.eventSequence}`)[0] ?? itemId;
15223
+ if (itemId) {
15224
+ const message = messages.find(
15225
+ (message2) => message2.id === itemId || message2.aliases.includes(itemId) || message2.blocks.some((block) => block.id === itemId)
15226
+ );
15227
+ const event = events.find((event2) => `event:${event2.eventSequence}` === itemId);
15228
+ targetState = message || event ? { state: "available", itemId: message?.aliases.includes(itemId) ? message.id : itemId } : unavailable;
15229
+ }
15230
+ if (target.boundaryFor) {
15231
+ const child = lineageSnapshot.records.find((record5) => record5.id === target.boundaryFor);
15232
+ const context = child ? lineage.origin(child).conversation : null;
15233
+ const boundary = context?.state === "recorded" ? context.value : null;
15234
+ if (boundary?.turnRecordId === turnRecordId && (!target.entryId || boundary.entryId === target.entryId)) {
15235
+ inheritedBoundary = boundary;
15236
+ targetState = messages.some((message) => message.entryId === boundary.entryId) ? { state: "available", itemId: `entry:${boundary.entryId}` } : {
15237
+ state: "unavailable",
15238
+ reason: "The inheritance boundary is recorded, but its source entry is unavailable"
15239
+ };
15240
+ } else targetState = unavailable;
15241
+ }
15242
+ return {
15243
+ ...history,
15244
+ messages,
15245
+ unassignedMessages: buildInspectionTraceMessages({
15246
+ tree: session.piTree,
15247
+ record: record4,
15248
+ scope: "unassigned_branch",
15249
+ captures: [],
15250
+ events: [],
15251
+ owner: lineage.owner
15252
+ }),
15253
+ events,
15254
+ annotations,
15255
+ output: record4.turnResultMarkdown,
15256
+ target: targetState,
15257
+ inheritedBoundary
15258
+ };
15259
+ }
15260
+ };
15261
+
14038
15262
  // src/process-overview-presenter.ts
14039
15263
  import {
14040
15264
  buildProcessRowSlot
@@ -14398,6 +15622,15 @@ function registerProcessDetailRoutes(app, deps) {
14398
15622
  const diagnosticsAssembler = new ProcessDiagnosticsAssembler(deps);
14399
15623
  const primaryPathAssembler = new ProcessPrimaryPathAssembler(deps);
14400
15624
  const uiSnapshotAssembler = new ProcessUiSnapshotAssembler(deps);
15625
+ const inspection = new ProcessInspectionReader(deps);
15626
+ app.get("/api/processes/:instanceId/turn-records/:turnRecordId/inspection", async (req, reply) => {
15627
+ const { instanceId, turnRecordId } = req.params;
15628
+ const section = req.query.section ?? "summary";
15629
+ if (!["summary", "trace", "context", "configuration"].includes(section))
15630
+ return reply.code(400).send({ error: "Unknown inspection section" });
15631
+ const body = section === "trace" ? await inspection.trace(instanceId, turnRecordId, req.query) : section === "context" ? await inspection.context(instanceId, turnRecordId) : section === "configuration" ? inspection.configuration(instanceId, turnRecordId) : inspection.summary(instanceId, turnRecordId);
15632
+ return body ?? reply.code(404).send({ error: "Execution not found in this process" });
15633
+ });
14401
15634
  app.get("/api/processes", async () => {
14402
15635
  const instances = deps.processes.listAll();
14403
15636
  const processes = instances.map((process2) => ({
@@ -14466,7 +15699,10 @@ function registerProcessDetailRoutes(app, deps) {
14466
15699
  "/api/processes/:instanceId/ui-snapshot",
14467
15700
  async (req, reply) => {
14468
15701
  const startedAt = performance.now();
14469
- const snapshot = await uiSnapshotAssembler.assemble(req.params.instanceId);
15702
+ const snapshot = await uiSnapshotAssembler.assemble(
15703
+ req.params.instanceId,
15704
+ req.query.beforeTurnRecordId
15705
+ );
14470
15706
  reply.header(
14471
15707
  "Server-Timing",
14472
15708
  `ui-snapshot;dur=${(performance.now() - startedAt).toFixed(1)}`
@@ -14514,6 +15750,187 @@ function registerProcessDetailRoutes(app, deps) {
14514
15750
  );
14515
15751
  }
14516
15752
 
15753
+ // src/process-model-config.ts
15754
+ import { parseStrictInstanceTurnConfigsJson } from "@leitwerk-dev/domain";
15755
+ function record3(value) {
15756
+ return value !== null && typeof value === "object" && !Array.isArray(value);
15757
+ }
15758
+ function profile(value) {
15759
+ return value === null || typeof value === "string" && value.trim().length > 0;
15760
+ }
15761
+ function parseProcessModelConfigPatch(value) {
15762
+ if (!record3(value) || Object.keys(value).some((key) => key !== "defaultModelProfileId" && key !== "turnConfigs"))
15763
+ throw new Error("Expected defaultModelProfileId and/or turnConfigs");
15764
+ const patch = {};
15765
+ if (Object.hasOwn(value, "defaultModelProfileId")) {
15766
+ if (!profile(value.defaultModelProfileId))
15767
+ throw new Error("defaultModelProfileId must be a profile ID or null");
15768
+ patch.defaultModelProfileId = value.defaultModelProfileId?.trim() ?? null;
15769
+ }
15770
+ if (Object.hasOwn(value, "turnConfigs")) {
15771
+ if (!record3(value.turnConfigs)) throw new Error("turnConfigs must be an object");
15772
+ patch.turnConfigs = Object.fromEntries(
15773
+ Object.entries(value.turnConfigs).map(([id, config]) => {
15774
+ if (!record3(config) || Object.keys(config).length !== 1 || !profile(config.modelProfileId))
15775
+ throw new Error(`Step '${id}' requires modelProfileId as a profile ID or null`);
15776
+ return [id, { modelProfileId: config.modelProfileId?.trim() ?? null }];
15777
+ })
15778
+ );
15779
+ }
15780
+ return patch;
15781
+ }
15782
+ function prepareProcessModelConfig(input) {
15783
+ const { process: process2, policy, availability } = input;
15784
+ const patch = parseProcessModelConfigPatch(input.patch);
15785
+ if (process2.lifecycleStatus === "completed" || process2.lifecycleStatus === "aborted")
15786
+ throw new Error("Completed and aborted processes have read-only model settings");
15787
+ const parsed = parseStrictInstanceTurnConfigsJson(process2.processId, process2.turnConfigsJson);
15788
+ if (!parsed.ok)
15789
+ throw new Error("Saved model configuration is malformed and must be repaired before editing");
15790
+ const current = policy.project({ kind: "process_configuration", process: process2, availability });
15791
+ const turns = new Map(current.turns.map((turn) => [turn.turnId, turn]));
15792
+ const turnConfigs = { ...parsed.value };
15793
+ for (const [id, config] of Object.entries(patch.turnConfigs ?? {})) {
15794
+ const turn = turns.get(id);
15795
+ if (!turn) throw new Error(`Step '${id}' is unknown or does not use a model`);
15796
+ if (turn.fixedModelProfileId) throw new Error(`Step '${id}' uses a fixed system model`);
15797
+ if (config.modelProfileId === null) delete turnConfigs[id];
15798
+ else turnConfigs[id] = { ...turnConfigs[id], modelProfileId: config.modelProfileId };
15799
+ }
15800
+ const selections = [
15801
+ patch.defaultModelProfileId,
15802
+ ...Object.values(patch.turnConfigs ?? {}).map((config) => config.modelProfileId)
15803
+ ];
15804
+ for (const id of selections) {
15805
+ if (!id) continue;
15806
+ const validation = policy.evaluate({
15807
+ kind: "runtime_selection",
15808
+ processId: process2.processId,
15809
+ availability,
15810
+ selection: {
15811
+ modelProfileId: id,
15812
+ provenance: { kind: "explicit", source: "instance_default" }
15813
+ }
15814
+ });
15815
+ if (!validation.ok) throw new Error(presentProcessModelPolicyFailure(validation));
15816
+ }
15817
+ const settings = {
15818
+ defaultModelProfileId: Object.hasOwn(patch, "defaultModelProfileId") ? patch.defaultModelProfileId ?? null : process2.defaultModelProfileId,
15819
+ turnConfigsJson: Object.hasOwn(patch, "turnConfigs") ? JSON.stringify(turnConfigs) : process2.turnConfigsJson
15820
+ };
15821
+ const candidate = { ...process2, ...settings };
15822
+ return {
15823
+ settings,
15824
+ modelConfiguration: presentProcessModelConfiguration(
15825
+ policy.project({ kind: "process_configuration", process: candidate, availability })
15826
+ )
15827
+ };
15828
+ }
15829
+
15830
+ // src/process-engine/ops/update-model-config.ts
15831
+ var UpdateModelConfig = defineOperation({
15832
+ kind: "update_model_config",
15833
+ decide(ctx, input) {
15834
+ let prepared;
15835
+ try {
15836
+ prepared = prepareProcessModelConfig({
15837
+ process: ctx.process,
15838
+ patch: input.patch,
15839
+ policy: ctx.deps.processModelPolicy,
15840
+ availability: ctx.deps.getModelAvailabilitySnapshot()
15841
+ });
15842
+ } catch (error) {
15843
+ return reject(
15844
+ "invalid_model_config",
15845
+ error instanceof Error ? error.message : "Invalid model configuration"
15846
+ );
15847
+ }
15848
+ const writes = createWrites();
15849
+ applyProcessPatchField(
15850
+ writes,
15851
+ ctx.process,
15852
+ "defaultModelProfileId",
15853
+ prepared.settings.defaultModelProfileId
15854
+ );
15855
+ applyProcessPatchField(
15856
+ writes,
15857
+ ctx.process,
15858
+ "turnConfigsJson",
15859
+ prepared.settings.turnConfigsJson
15860
+ );
15861
+ appendProcessEvent(writes, ctx.process, {
15862
+ eventType: "model_configuration_changed",
15863
+ level: "info",
15864
+ message: "Model defaults updated for future executions",
15865
+ data: {
15866
+ actor: input.actor,
15867
+ patch: input.patch,
15868
+ previous: {
15869
+ defaultModelProfileId: ctx.process.defaultModelProfileId,
15870
+ turnConfigsJson: ctx.process.turnConfigsJson
15871
+ },
15872
+ settings: prepared.settings
15873
+ }
15874
+ });
15875
+ return accept({ writes, data: { modelConfiguration: prepared.modelConfiguration } });
15876
+ }
15877
+ });
15878
+
15879
+ // src/routes/process-model-config.ts
15880
+ function registerProcessModelConfigRoutes(app, deps) {
15881
+ for (const preview of [true, false]) {
15882
+ app.route({
15883
+ method: preview ? "POST" : "PATCH",
15884
+ url: `/api/processes/:instanceId/model-config${preview ? "/preview" : ""}`,
15885
+ async handler(req, reply) {
15886
+ const process2 = getProcessOrReply(deps, req.params.instanceId, reply);
15887
+ if (!process2) return;
15888
+ const policy = deps.processModelPolicy;
15889
+ const cache = deps.modelStatusCache;
15890
+ if (!policy || !cache || !deps.processActionRegistry)
15891
+ return reply.code(503).send({ error: "Model policy is unavailable" });
15892
+ let patch;
15893
+ try {
15894
+ patch = parseProcessModelConfigPatch(req.body);
15895
+ if (preview) {
15896
+ const prepared = prepareProcessModelConfig({
15897
+ process: process2,
15898
+ patch,
15899
+ policy,
15900
+ availability: cache.snapshot()
15901
+ });
15902
+ return { modelConfiguration: prepared.modelConfiguration };
15903
+ }
15904
+ } catch (error) {
15905
+ return reply.code(400).send({
15906
+ error: error instanceof Error ? error.message : "Invalid model configuration"
15907
+ });
15908
+ }
15909
+ const result = await deps.processEngine.run(UpdateModelConfig, {
15910
+ instanceId: process2.id,
15911
+ patch,
15912
+ actor: actorForRequest(req)
15913
+ });
15914
+ if (!result.ok)
15915
+ return reply.code(
15916
+ result.code === "process_not_found" ? 404 : result.stage === "post_commit" ? 500 : 400
15917
+ ).send({ error: result.message });
15918
+ await reconcileFutureExecutionModelBlocks({
15919
+ ...deps,
15920
+ processGraphs: deps.processGraphs,
15921
+ processActionRegistry: deps.processActionRegistry,
15922
+ policy,
15923
+ availability: cache.snapshot(),
15924
+ getModelAvailabilitySnapshot: () => cache.snapshot(),
15925
+ instanceId: process2.id,
15926
+ asOf: (/* @__PURE__ */ new Date()).toISOString()
15927
+ });
15928
+ return result.data;
15929
+ }
15930
+ });
15931
+ }
15932
+ }
15933
+
14517
15934
  // src/routes/process-questions.ts
14518
15935
  function registerProcessQuestionRoutes(app, deps) {
14519
15936
  app.post("/api/processes/:instanceId/question-requests/:requestId/answers", async (req, reply) => {
@@ -14660,6 +16077,7 @@ function registerSessionTransferRoutes(app, service, publicBaseUrl) {
14660
16077
  // src/routes/processes.ts
14661
16078
  function registerProcessRoutes(app, deps) {
14662
16079
  registerProcessDetailRoutes(app, deps);
16080
+ registerProcessModelConfigRoutes(app, deps);
14663
16081
  registerLauncherRoutes(app, deps, deps.futureExecutionLifecycle);
14664
16082
  registerFutureExecutionRoutes(app, deps, deps.futureExecutionLifecycle);
14665
16083
  registerProcessActionRoutes(app, deps, deps.futureExecutionLifecycle);
@@ -14810,6 +16228,129 @@ function registerResultImageRoutes(input) {
14810
16228
  );
14811
16229
  }
14812
16230
 
16231
+ // src/routes/settings.ts
16232
+ function parseChange(value) {
16233
+ if (!value || typeof value !== "object" || Array.isArray(value))
16234
+ throw new SettingsError("Expected a settings change", 400);
16235
+ const raw = value;
16236
+ if (typeof raw.subjectId !== "string" || typeof raw.key !== "string" || !Number.isSafeInteger(raw.expectedRevision) || Number(raw.expectedRevision) < 0 || raw.mode !== void 0 && raw.mode !== "replace" || raw.reset !== void 0 && typeof raw.reset !== "boolean" || !raw.reset && !Object.hasOwn(raw, "value"))
16237
+ throw new SettingsError(
16238
+ "Provide subjectId, key, value, and expectedRevision; mode must be replace",
16239
+ 400
16240
+ );
16241
+ return raw;
16242
+ }
16243
+ function registerSettingsRoutes(app, settings, repos) {
16244
+ function normalizedChange(request) {
16245
+ const change = parseChange(request.body);
16246
+ return {
16247
+ ...change,
16248
+ value: change.value,
16249
+ reset: change.reset ?? false,
16250
+ actor: actorForRequest(request)
16251
+ };
16252
+ }
16253
+ app.get("/api/settings/definitions", async () => ({ definitions: settings.definitions() }));
16254
+ app.get("/api/settings/scopes", async () => settings.listScopes());
16255
+ app.get("/api/settings/overview", async (request) => {
16256
+ if (!request.query.scopeType) throw new SettingsError("Provide scopeType", 400);
16257
+ return settings.overview(request.query.scopeType);
16258
+ });
16259
+ app.post("/api/settings/scopes/refresh", async () => {
16260
+ const scopes = await settings.refresh();
16261
+ await repos.onSettingsChanged?.();
16262
+ repos.broadcaster.sendDurable("settings.updated", { subjectId: "instance" });
16263
+ return scopes;
16264
+ });
16265
+ app.get(
16266
+ "/api/settings/preview",
16267
+ async (request) => settings.preview(request.query.subjectId ?? "instance")
16268
+ );
16269
+ app.get(
16270
+ "/api/settings/choices",
16271
+ async (request) => {
16272
+ if (!request.query.subjectId || !request.query.key)
16273
+ throw new SettingsError("Provide subjectId and key", 400);
16274
+ return {
16275
+ choices: await settings.choices(
16276
+ request.query.subjectId,
16277
+ request.query.key,
16278
+ request.query.search
16279
+ )
16280
+ };
16281
+ }
16282
+ );
16283
+ app.post("/api/settings/preview", async (request) => {
16284
+ return settings.previewDraft(normalizedChange(request));
16285
+ });
16286
+ app.put("/api/settings/overrides", async (request) => {
16287
+ const change = normalizedChange(request);
16288
+ settings.write(change);
16289
+ await repos.onSettingsChanged?.();
16290
+ repos.broadcaster.sendDurable("settings.updated", { subjectId: change.subjectId });
16291
+ return settings.preview(change.subjectId);
16292
+ });
16293
+ app.put("/api/settings/processes/:instanceId/primary-repository", async (request) => {
16294
+ const result = await repos.processOperations.runExclusive(request.params.instanceId, () => {
16295
+ const process2 = repos.processes.getById(request.params.instanceId);
16296
+ if (!process2) throw new SettingsError("Process not found", 404);
16297
+ const body = request.body;
16298
+ if (!body || body.primaryRepositoryKey !== null && typeof body.primaryRepositoryKey !== "string" || body.expectedPrimaryRepositoryKey !== null && typeof body.expectedPrimaryRepositoryKey !== "string")
16299
+ throw new SettingsError(
16300
+ "Provide primaryRepositoryKey and expectedPrimaryRepositoryKey",
16301
+ 400
16302
+ );
16303
+ if ((process2.metadata?.primaryRepositoryKey ?? null) !== body.expectedPrimaryRepositoryKey)
16304
+ throw new SettingsError("Primary repository changed. Reload before saving again.", 409);
16305
+ if (body.primaryRepositoryKey !== null && !repos.projects.listByInstance(process2.id).some((project) => project.key === body.primaryRepositoryKey))
16306
+ throw new SettingsError("Primary repository must belong to this process");
16307
+ repos.processes.update(process2.id, {
16308
+ metadata: { ...process2.metadata, primaryRepositoryKey: body.primaryRepositoryKey }
16309
+ });
16310
+ repos.events.create({
16311
+ instanceId: process2.id,
16312
+ eventType: "settings.primary_repository_changed",
16313
+ data: { primaryRepositoryKey: body.primaryRepositoryKey, actor: actorForRequest(request) }
16314
+ });
16315
+ return { primaryRepositoryKey: body.primaryRepositoryKey };
16316
+ });
16317
+ await repos.onSettingsChanged?.();
16318
+ repos.broadcaster.sendDurable("settings.updated", { subjectId: "instance" });
16319
+ return result;
16320
+ });
16321
+ app.get(
16322
+ "/api/settings/processes/:instanceId",
16323
+ async (request) => {
16324
+ const process2 = repos.processes.getById(request.params.instanceId);
16325
+ if (!process2) throw new SettingsError("Process not found", 404);
16326
+ const context = settings.forProcess(process2);
16327
+ const future = settings.previewProcess(process2);
16328
+ return {
16329
+ primaryRepositoryKey: process2.metadata?.primaryRepositoryKey ?? null,
16330
+ future,
16331
+ context: context.context,
16332
+ explanations: context.explanations,
16333
+ repositories: context.subjects.map(({ project, subject }) => ({
16334
+ key: project.key,
16335
+ subjectId: subject.id,
16336
+ label: subject.label
16337
+ })),
16338
+ captured: repos.turnStarts.listByInstance(process2.id).flatMap(
16339
+ (record4) => record4.state.kind !== "preparation_failed" && record4.state.start?.kind === "llm" && record4.state.start.scopedSettings ? [
16340
+ {
16341
+ startRecordId: record4.id,
16342
+ turnId: record4.turnId,
16343
+ createdAt: record4.createdAt,
16344
+ state: record4.state.kind,
16345
+ settings: record4.state.start.scopedSettings
16346
+ }
16347
+ ] : []
16348
+ )
16349
+ };
16350
+ }
16351
+ );
16352
+ }
16353
+
14813
16354
  // src/routes/skills.ts
14814
16355
  function registerSkillRoutes(app, deps) {
14815
16356
  app.get("/api/skills", async () => deps.skillCatalog.list());
@@ -14921,7 +16462,10 @@ function registerTicketCreationRoutes(app, deps, registry) {
14921
16462
  async () => ({
14922
16463
  tools: registry.ticketCatalog().map((tool) => ({
14923
16464
  name: tool.name,
14924
- displayName: tool.capability.displayName
16465
+ displayName: tool.capability.displayName,
16466
+ descriptionFormat: tool.capability.descriptionFormat,
16467
+ titlePath: tool.capability.titlePath,
16468
+ descriptionPath: tool.capability.descriptionPath
14925
16469
  }))
14926
16470
  })
14927
16471
  );
@@ -14935,6 +16479,17 @@ function registerTicketCreationRoutes(app, deps, registry) {
14935
16479
  statusCode: 400
14936
16480
  });
14937
16481
  }
16482
+ const existing = deps.launchRuns.getByIdempotencyKey(idempotencyKey.trim());
16483
+ if (existing?.instanceId) {
16484
+ const relation2 = deps.processRelations.getByChild(existing.instanceId);
16485
+ if (existing.launcherId !== `ticket:${req.body.toolName}` || relation2?.parentInstanceId !== req.params.instanceId || relation2.purpose !== "ticket_creation") {
16486
+ return reply.code(409).send({ error: "This launch key already belongs to another request" });
16487
+ }
16488
+ return {
16489
+ childInstanceId: existing.instanceId,
16490
+ relation: relation2
16491
+ };
16492
+ }
14938
16493
  const tool = registry.resolveTicketTool(req.body.toolName);
14939
16494
  const { processId, startTurnId } = tool.capability;
14940
16495
  if (!hasProcessGraph(deps.processGraphs, processId)) {
@@ -14944,6 +16499,14 @@ function registerTicketCreationRoutes(app, deps, registry) {
14944
16499
  }
14945
16500
  const actor = actorForRequest(req);
14946
16501
  const destinationList = tool.capability.destinations ? await registry.listTicketDestinations(req.body.toolName, actor) : void 0;
16502
+ if (destinationList && destinationList.destinations.length === 0) {
16503
+ throw Object.assign(
16504
+ new Error(
16505
+ `No destinations are available in ${tool.capability.displayName}. Check project access and issue permissions, then try again.${destinationList.warnings?.length ? ` ${destinationList.warnings.join(" ")}` : ""}`
16506
+ ),
16507
+ { statusCode: 503 }
16508
+ );
16509
+ }
14947
16510
  const { parent, context } = assembleContext(deps, req.params.instanceId, req.body);
14948
16511
  const launchPlan = {
14949
16512
  launcherId: `ticket:${req.body.toolName}`,
@@ -14990,9 +16553,6 @@ function registerTicketCreationRoutes(app, deps, registry) {
14990
16553
  }
14991
16554
  const relation = deps.processRelations.getByChild(launched.process.id);
14992
16555
  if (!relation) throw new Error("Ticket launch did not create its process relation");
14993
- if (launched.error) {
14994
- return reply.code(500).send({ error: launched.error, childInstanceId: launched.process.id });
14995
- }
14996
16556
  return {
14997
16557
  childInstanceId: launched.process.id,
14998
16558
  relation
@@ -15280,6 +16840,10 @@ function registerHttp(input) {
15280
16840
  store: input.resultImages
15281
16841
  });
15282
16842
  registerProcessRoutes(input.app, input.deps);
16843
+ if (input.deps.topicWiki)
16844
+ registerTopicWikiRoutes(input.app, input.deps.topicWiki, actorForRequest);
16845
+ if (input.deps.scopedSettingsService)
16846
+ registerSettingsRoutes(input.app, input.deps.scopedSettingsService, input.deps);
15283
16847
  registerWatcherRoutes(input.app, { processWatchers: input.processWatcherService });
15284
16848
  registerTicketCreationRoutes(input.app, input.deps, input.integrationTools);
15285
16849
  if (input.deps.skillCatalog) {
@@ -15293,8 +16857,8 @@ function registerHttp(input) {
15293
16857
 
15294
16858
  // src/server-topology.ts
15295
16859
  import { readFileSync } from "node:fs";
15296
- var defaultFileReader = (path9) => readFileSync(path9, "utf8");
15297
- function resolveServerTlsOptions(config, readFile5 = defaultFileReader) {
16860
+ var defaultFileReader = (path11) => readFileSync(path11, "utf8");
16861
+ function resolveServerTlsOptions(config, readFile6 = defaultFileReader) {
15298
16862
  const tls = config.internal_tls;
15299
16863
  if (!tls || tls.enabled !== true) {
15300
16864
  return null;
@@ -15302,9 +16866,9 @@ function resolveServerTlsOptions(config, readFile5 = defaultFileReader) {
15302
16866
  if (!tls.cert_file || !tls.key_file) {
15303
16867
  throw new Error("internal_tls requires cert_file and key_file when enabled");
15304
16868
  }
15305
- const cert = readFile5(tls.cert_file);
15306
- const key = readFile5(tls.key_file);
15307
- const ca = tls.client_ca_file ? readFile5(tls.client_ca_file) : void 0;
16869
+ const cert = readFile6(tls.cert_file);
16870
+ const key = readFile6(tls.key_file);
16871
+ const ca = tls.client_ca_file ? readFile6(tls.client_ca_file) : void 0;
15308
16872
  const mtls = ca !== void 0;
15309
16873
  return {
15310
16874
  cert,
@@ -15321,7 +16885,7 @@ import { PassThrough } from "node:stream";
15321
16885
  import {
15322
16886
  sessionTransferPreflightReportSchema
15323
16887
  } from "@leitwerk-dev/session-transfer";
15324
- import * as v4 from "valibot";
16888
+ import * as v3 from "valibot";
15325
16889
  function withAbort(promise, signal) {
15326
16890
  if (!signal) return promise;
15327
16891
  return Promise.race([
@@ -15434,7 +16998,7 @@ function createSessionTransferHelperRelays(deps) {
15434
16998
  if (!attempt || attempt.phase !== "scanning" && attempt.phase !== "starting_exporter") {
15435
16999
  return false;
15436
17000
  }
15437
- const parsed = v4.safeParse(sessionTransferPreflightReportSchema, input.report);
17001
+ const parsed = v3.safeParse(sessionTransferPreflightReportSchema, input.report);
15438
17002
  if (!parsed.success) return false;
15439
17003
  const report = parsed.output;
15440
17004
  if (report.preflight.entriesTotal > deps.limits.maxEntries || report.preflight.logicalBytesTotal > deps.limits.maxLogicalBytes || !sameManifestAuthority(helper.expectedManifest, report.manifest)) {
@@ -15464,25 +17028,82 @@ function createSessionTransferHelperRelays(deps) {
15464
17028
  };
15465
17029
  }
15466
17030
 
17031
+ // src/skills/bundled-skills.ts
17032
+ import path5 from "node:path";
17033
+ import { createCanonicalPiResourceBundle } from "@leitwerk-dev/worker-protocol";
17034
+ async function importBundledSkills(contributions) {
17035
+ const skills = /* @__PURE__ */ new Map();
17036
+ const collector = new ResourceCollector();
17037
+ for (const contribution of contributions) {
17038
+ for (const directory of contribution.resources.skillDirectories) {
17039
+ await collector.addDirectory(directory, "skills", {
17040
+ kind: "skill",
17041
+ ownerExtensionId: contribution.ownerExtensionId,
17042
+ packageName: contribution.packageName
17043
+ });
17044
+ }
17045
+ }
17046
+ const files = collector.toResourceFiles();
17047
+ for (const file of files) {
17048
+ if (!file.path.endsWith("/SKILL.md")) continue;
17049
+ const skillRoot = path5.posix.dirname(file.path);
17050
+ const skillId = path5.posix.basename(skillRoot);
17051
+ if (!SAFE_SKILL_ID_PATTERN.test(skillId)) {
17052
+ throw new Error(`Bundled skill has an invalid id '${skillId}' at '${file.path}'`);
17053
+ }
17054
+ if (skills.has(skillId)) throw new Error(`Duplicate bundled skill id '${skillId}'`);
17055
+ const skillMarkdown = Buffer.from(file.content).toString("utf8");
17056
+ const metadata = skillMetadata(skillMarkdown);
17057
+ const sourceExtensionId = collector.provenance.find(
17058
+ (source) => source.snapshotPath === file.path
17059
+ )?.ownerExtensionId;
17060
+ const bundle = createCanonicalPiResourceBundle(
17061
+ files.filter((candidate) => candidate.path.startsWith(`${skillRoot}/`))
17062
+ );
17063
+ skills.set(skillId, {
17064
+ id: skillId,
17065
+ label: metadata.name ?? skillId,
17066
+ description: metadata.description,
17067
+ registrationKind: "bundled",
17068
+ ...sourceExtensionId ? { sourceExtensionId } : {},
17069
+ activeRevisionId: bundle.digest,
17070
+ activeSourceRevision: null,
17071
+ sourceRepositoryId: null,
17072
+ updateAvailable: false,
17073
+ modelInvocable: isSkillModelInvocable(skillMarkdown),
17074
+ usage: {
17075
+ attachedAllTime: 0,
17076
+ attachedLast30Days: 0,
17077
+ invokedAllTime: 0,
17078
+ invokedLast30Days: 0
17079
+ },
17080
+ skillMarkdown,
17081
+ processes: [],
17082
+ revisions: []
17083
+ });
17084
+ }
17085
+ return [...skills.values()];
17086
+ }
17087
+
15467
17088
  // src/skills/source-importer.ts
15468
17089
  import { execFile } from "node:child_process";
15469
17090
  import { mkdtemp as mkdtemp2, readdir as readdir2, readFile as readFile4, rm as rm3 } from "node:fs/promises";
15470
17091
  import { tmpdir as tmpdir2 } from "node:os";
15471
- import path5 from "node:path";
17092
+ import path6 from "node:path";
15472
17093
  import { promisify } from "node:util";
15473
17094
  import {
15474
- createCanonicalPiResourceBundle
17095
+ createCanonicalPiResourceBundle as createCanonicalPiResourceBundle2
15475
17096
  } from "@leitwerk-dev/worker-protocol";
15476
17097
  var execFileAsync = promisify(execFile);
15477
17098
  var GIT_ENV = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "/bin/false" };
15478
17099
  var FORBIDDEN_SKILL_NAMES = /* @__PURE__ */ new Set([".git"]);
15479
17100
  function isWithin(root, candidate) {
15480
- const relative = path5.relative(root, candidate);
15481
- return relative === "" || relative !== ".." && !relative.startsWith(`..${path5.sep}`);
17101
+ const relative = path6.relative(root, candidate);
17102
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path6.sep}`);
15482
17103
  }
15483
17104
  async function importSkillDirectory(root, skill, sourceRevision) {
15484
17105
  const collector = new ResourceCollector();
15485
- await collector.addDirectory(path5.resolve(root), `skills/${skill.id}`, SKILL_RESOURCE_OWNER, {
17106
+ await collector.addDirectory(path6.resolve(root), `skills/${skill.id}`, SKILL_RESOURCE_OWNER, {
15486
17107
  forbiddenNames: FORBIDDEN_SKILL_NAMES
15487
17108
  });
15488
17109
  const files = collector.toResourceFiles();
@@ -15493,7 +17114,7 @@ async function importSkillDirectory(root, skill, sourceRevision) {
15493
17114
  skillId: skill.id,
15494
17115
  label: skill.label ?? skill.id,
15495
17116
  description: skill.description ?? null,
15496
- bundle: createCanonicalPiResourceBundle(files),
17117
+ bundle: createCanonicalPiResourceBundle2(files),
15497
17118
  sourceRevision
15498
17119
  };
15499
17120
  }
@@ -15525,14 +17146,14 @@ async function discoverSkillRoots(catalogRoot) {
15525
17146
  const entries = (await readdir2(directory, { withFileTypes: true })).sort(
15526
17147
  (left, right) => left.name.localeCompare(right.name)
15527
17148
  );
15528
- const skillId = path5.basename(directory);
17149
+ const skillId = path6.basename(directory);
15529
17150
  if (SAFE_SKILL_ID_PATTERN.test(skillId) && entries.some((entry) => entry.name === "SKILL.md" && entry.isFile())) {
15530
17151
  result.push(directory);
15531
17152
  return;
15532
17153
  }
15533
17154
  for (const entry of entries) {
15534
17155
  if (entry.isDirectory() && entry.name !== ".git") {
15535
- await visit(path5.join(directory, entry.name));
17156
+ await visit(path6.join(directory, entry.name));
15536
17157
  }
15537
17158
  }
15538
17159
  };
@@ -15540,20 +17161,20 @@ async function discoverSkillRoots(catalogRoot) {
15540
17161
  return result;
15541
17162
  }
15542
17163
  function repositorySourcePath(checkoutRoot, skillRoot) {
15543
- return path5.relative(checkoutRoot, skillRoot).split(path5.sep).join(path5.posix.sep);
17164
+ return path6.relative(checkoutRoot, skillRoot).split(path6.sep).join(path6.posix.sep);
15544
17165
  }
15545
17166
  async function importSkillRepository(repository) {
15546
- const tempRoot = await mkdtemp2(path5.join(tmpdir2(), "leitwerk-skill-repository-"));
17167
+ const tempRoot = await mkdtemp2(path6.join(tmpdir2(), "leitwerk-skill-repository-"));
15547
17168
  try {
15548
- const checkout = await checkoutGitSource(repository, path5.join(tempRoot, "checkout"));
15549
- const catalogRoot = path5.resolve(checkout.root, repository.path ?? "skills");
17169
+ const checkout = await checkoutGitSource(repository, path6.join(tempRoot, "checkout"));
17170
+ const catalogRoot = path6.resolve(checkout.root, repository.path ?? "skills");
15550
17171
  if (!isWithin(checkout.root, catalogRoot)) {
15551
17172
  throw new Error(`Skill repository '${repository.id}' path escapes its checkout`);
15552
17173
  }
15553
17174
  const skillRoots = await discoverSkillRoots(catalogRoot);
15554
17175
  const rootsById = /* @__PURE__ */ new Map();
15555
17176
  for (const skillRoot of skillRoots) {
15556
- const skillId = path5.basename(skillRoot);
17177
+ const skillId = path6.basename(skillRoot);
15557
17178
  const previous = rootsById.get(skillId);
15558
17179
  if (previous) {
15559
17180
  throw new Error(
@@ -15564,8 +17185,8 @@ async function importSkillRepository(repository) {
15564
17185
  }
15565
17186
  const skills = [];
15566
17187
  for (const skillRoot of skillRoots) {
15567
- const skillId = path5.basename(skillRoot);
15568
- const markdown = await readFile4(path5.join(skillRoot, "SKILL.md"), "utf8");
17188
+ const skillId = path6.basename(skillRoot);
17189
+ const markdown = await readFile4(path6.join(skillRoot, "SKILL.md"), "utf8");
15569
17190
  const imported = await importSkillDirectory(
15570
17191
  skillRoot,
15571
17192
  {
@@ -15589,6 +17210,12 @@ async function importSkillRepository(repository) {
15589
17210
  // src/skills/catalog-service.ts
15590
17211
  function createSkillCatalogService(input) {
15591
17212
  const importRepository = input.importRepository ?? importSkillRepository;
17213
+ const bundledSkills = new Map((input.bundledSkills ?? []).map((skill) => [skill.id, skill]));
17214
+ for (const skill of input.repos.skills.listAvailable()) {
17215
+ if (bundledSkills.has(skill.id)) {
17216
+ throw new Error(`Bundled skill '${skill.id}' conflicts with an installed skill`);
17217
+ }
17218
+ }
15592
17219
  const statuses = /* @__PURE__ */ new Map();
15593
17220
  let refreshPromise = null;
15594
17221
  input.repos.transaction(
@@ -15608,10 +17235,23 @@ function createSkillCatalogService(input) {
15608
17235
  error: status?.error ?? null
15609
17236
  };
15610
17237
  });
15611
- const list = () => ({
15612
- repositories: summaries(),
15613
- ...input.repos.skills.catalog()
15614
- });
17238
+ const list = () => {
17239
+ const catalog = input.repos.skills.catalog();
17240
+ return {
17241
+ repositories: summaries(),
17242
+ availableSkills: catalog.availableSkills.map(
17243
+ (skill) => bundledSkills.has(skill.id) ? { ...skill, conflict: !skill.stale, registered: false, updateAvailable: false } : skill
17244
+ ),
17245
+ installedSkills: [
17246
+ ...catalog.installedSkills,
17247
+ ...[...bundledSkills.values()].map(
17248
+ ({ skillMarkdown, processes, revisions, ...skill }) => skill
17249
+ )
17250
+ ].sort(
17251
+ (left, right) => left.label.localeCompare(right.label) || left.id.localeCompare(right.id)
17252
+ )
17253
+ };
17254
+ };
15615
17255
  const refresh = () => {
15616
17256
  if (refreshPromise) return refreshPromise;
15617
17257
  refreshPromise = (async () => {
@@ -15642,30 +17282,112 @@ function createSkillCatalogService(input) {
15642
17282
  list,
15643
17283
  refresh,
15644
17284
  detail(repositoryId, skillId) {
15645
- return input.repos.skills.getCatalogDetail(repositoryId, skillId);
17285
+ const detail = input.repos.skills.getCatalogDetail(repositoryId, skillId);
17286
+ return detail && bundledSkills.has(skillId) ? { ...detail, conflict: !detail.stale, registered: false, updateAvailable: false } : detail;
15646
17287
  },
15647
17288
  installedDetail(skillId) {
15648
- return input.repos.skills.getInstalledDetail(skillId);
17289
+ return bundledSkills.get(skillId) ?? input.repos.skills.getInstalledDetail(skillId);
15649
17290
  },
15650
17291
  register(repositoryId, skillId) {
17292
+ if (bundledSkills.has(skillId)) {
17293
+ throw new Error(`Skill '${skillId}' has a conflicting bundled extension skill`);
17294
+ }
15651
17295
  return input.repos.transaction(
15652
17296
  (repos) => repos.skills.registerCatalogEntry(repositoryId, skillId)
15653
17297
  );
15654
17298
  },
15655
17299
  remove(skillId) {
17300
+ if (bundledSkills.has(skillId)) return false;
15656
17301
  return input.repos.transaction((repos) => repos.skills.remove(skillId));
15657
17302
  }
15658
17303
  };
15659
17304
  }
15660
17305
 
17306
+ // src/skills/extension-importer.ts
17307
+ import { lstat, readFile as readFile5, realpath } from "node:fs/promises";
17308
+ import path7 from "node:path";
17309
+ import { parseSkillPackManifest } from "@leitwerk-dev/protocol";
17310
+ import { createCanonicalPiResourceBundle as createCanonicalPiResourceBundle3 } from "@leitwerk-dev/worker-protocol";
17311
+ import { parse as parseYaml } from "yaml";
17312
+ async function packagePath(packageRoot, target) {
17313
+ const relative = path7.relative(packageRoot, target);
17314
+ if (!relative || relative === ".." || relative.startsWith(`..${path7.sep}`) || path7.isAbsolute(relative)) {
17315
+ throw new Error(`Skill-pack path escapes package: ${target}`);
17316
+ }
17317
+ let current = packageRoot;
17318
+ for (const part of relative.split(path7.sep)) {
17319
+ current = path7.join(current, part);
17320
+ if ((await lstat(current)).isSymbolicLink())
17321
+ throw new Error(`Skill-pack symlink is forbidden: ${current}`);
17322
+ }
17323
+ return current;
17324
+ }
17325
+ async function importExtensionSkills(modules) {
17326
+ const imported = [];
17327
+ for (const loaded of modules) {
17328
+ if (!loaded.skillPackPath) continue;
17329
+ const packageRoot = await realpath(loaded.packageDir);
17330
+ const manifestPath = await packagePath(
17331
+ packageRoot,
17332
+ path7.resolve(packageRoot, path7.relative(loaded.packageDir, loaded.skillPackPath))
17333
+ );
17334
+ const manifest = parseSkillPackManifest(JSON.parse(await readFile5(manifestPath, "utf8")));
17335
+ for (const skill of manifest.skills) {
17336
+ const directory = await packagePath(
17337
+ packageRoot,
17338
+ path7.resolve(path7.dirname(manifestPath), skill.directory)
17339
+ );
17340
+ const provenance = {
17341
+ extensionId: loaded.module.manifest.id,
17342
+ packageName: loaded.packageName,
17343
+ packageVersion: loaded.packageVersion ?? loaded.module.manifest.version,
17344
+ upstream: manifest.upstream,
17345
+ sourcePath: skill.sourcePath,
17346
+ patchDigest: manifest.patchDigest,
17347
+ dependencies: skill.dependencies
17348
+ };
17349
+ const collector = new ResourceCollector();
17350
+ await collector.addDirectory(
17351
+ directory,
17352
+ `skills/${skill.id}`,
17353
+ {
17354
+ kind: "skill",
17355
+ ownerExtensionId: provenance.extensionId,
17356
+ packageName: provenance.packageName
17357
+ },
17358
+ { forbiddenNames: /* @__PURE__ */ new Set([".git", ".leitwerk-skill.json"]) }
17359
+ );
17360
+ const markdown = collector.files.get(`skills/${skill.id}/SKILL.md`);
17361
+ const header = markdown && /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(Buffer.from(markdown).toString("utf8"));
17362
+ const metadata = header ? parseYaml(header[1]) : null;
17363
+ if (metadata?.name !== skill.id || metadata.description !== skill.description) {
17364
+ throw new Error(`Skill '${skill.id}' frontmatter does not match its pack manifest`);
17365
+ }
17366
+ collector.addBytes(
17367
+ `skills/${skill.id}/.leitwerk-skill.json`,
17368
+ Buffer.from(JSON.stringify(provenance))
17369
+ );
17370
+ imported.push({
17371
+ skillId: skill.id,
17372
+ label: skill.label,
17373
+ description: skill.description,
17374
+ sourceRevision: manifest.upstream.commit,
17375
+ provenance,
17376
+ bundle: createCanonicalPiResourceBundle3(collector.toResourceFiles())
17377
+ });
17378
+ }
17379
+ }
17380
+ return imported;
17381
+ }
17382
+
15661
17383
  // src/supervisor/diagnostic-trace-writer.ts
15662
17384
  import { appendFileSync, mkdirSync } from "node:fs";
15663
- import path6 from "node:path";
17385
+ import path8 from "node:path";
15664
17386
  function createDiagnosticTraceWriter(directory) {
15665
17387
  mkdirSync(directory, { recursive: true, mode: 448 });
15666
17388
  return {
15667
17389
  append(instanceId, text) {
15668
- appendFileSync(path6.join(directory, `${instanceId}.log`), text, {
17390
+ appendFileSync(path8.join(directory, `${instanceId}.log`), text, {
15669
17391
  encoding: "utf8",
15670
17392
  mode: 384
15671
17393
  });
@@ -15694,12 +17416,10 @@ function recordWorkerLifecycleEvent(deps, { level, message, ...event }) {
15694
17416
 
15695
17417
  // src/supervisor/worker-event-ingestor.ts
15696
17418
  import {
15697
- applyPiEventToLiveTurnProjection,
15698
17419
  asWsEventPayloadRecord,
15699
- buildLiveTurnProjectionFromEvents,
15700
17420
  createDurableWsFrame as createDurableWsFrame6,
15701
17421
  createEphemeralWsFrame as createEphemeralWsFrame2,
15702
- createMutableLiveTurnProjection,
17422
+ createLiveTurnProjection,
15703
17423
  isStreamableEvent,
15704
17424
  mapWorkerEventToWsType,
15705
17425
  readWsEventNonEmptyString,
@@ -15749,6 +17469,35 @@ function recordTurnPreparation(deps, input) {
15749
17469
  return true;
15750
17470
  }
15751
17471
 
17472
+ // src/supervisor/execution-inspection-ingestor.ts
17473
+ function ingestExecutionInspection(deps, input) {
17474
+ const record4 = deps.turnRecords.getById(input.turnRecordId);
17475
+ const lease = deps.leases.getByInstance(input.instanceId);
17476
+ if (!record4 || record4.instanceId !== input.instanceId || record4.status !== "running" || !record4.turnStartRecordId || !lease || lease.workerId !== input.workerId || lease.turnStartRecordId !== record4.turnStartRecordId || lease.exitedAt !== null)
17477
+ return false;
17478
+ const capture = input.capture;
17479
+ if (!capture || capture.version !== 1 || typeof capture.id !== "string" || !capture.id || typeof capture.timestamp !== "string" || !capture.fact || !["model_input", "supplied_context", "product_consumed", "entry_link"].includes(
17480
+ capture.fact.kind
17481
+ ))
17482
+ return false;
17483
+ if (capture.fact.kind === "supplied_context") {
17484
+ for (const product of capture.fact.products) {
17485
+ const producer = deps.turnRecords.getById(product.producerTurnRecordId);
17486
+ if (!producer || producer.instanceId !== input.instanceId || producer.resultPiEntryId !== product.entryId)
17487
+ return false;
17488
+ }
17489
+ }
17490
+ deps.executionInspections.append({
17491
+ ...capture,
17492
+ id: `${input.turnRecordId}:${capture.id}`,
17493
+ instanceId: input.instanceId,
17494
+ turnRecordId: record4.id,
17495
+ startRecordId: record4.turnStartRecordId,
17496
+ workerLeaseId: lease.id
17497
+ });
17498
+ return true;
17499
+ }
17500
+
15752
17501
  // src/supervisor/startup-observer.ts
15753
17502
  function createStartupObserver(deps, instanceId, workerId, deadlineMs) {
15754
17503
  const lease = deps.leases.getByInstance(instanceId);
@@ -15818,13 +17567,13 @@ function eventObservationLatencyMs(eventTimestamp2, observedAt) {
15818
17567
  }
15819
17568
  function hydrateLiveTurnProjection(deps, instanceId, turnRecordId) {
15820
17569
  if (!turnRecordId) {
15821
- return createMutableLiveTurnProjection();
17570
+ return createLiveTurnProjection();
15822
17571
  }
15823
17572
  const turnRecord = deps.turnRecords.getById(turnRecordId);
15824
17573
  if (!turnRecord) {
15825
- return createMutableLiveTurnProjection();
17574
+ return createLiveTurnProjection();
15826
17575
  }
15827
- return buildLiveTurnProjectionFromEvents(deps.events.listByTurnRecord(instanceId, turnRecordId));
17576
+ return createLiveTurnProjection(deps.events.listByTurnRecord(instanceId, turnRecordId));
15828
17577
  }
15829
17578
  function createWorkerEventIngestor(deps) {
15830
17579
  const liveTurnRecordIds = /* @__PURE__ */ new Map();
@@ -15841,7 +17590,7 @@ function createWorkerEventIngestor(deps) {
15841
17590
  function setLiveTurnProjection(instanceId, turnRecordId) {
15842
17591
  liveTurnProjections.set(instanceId, {
15843
17592
  turnRecordId,
15844
- projection: createMutableLiveTurnProjection()
17593
+ projection: createLiveTurnProjection()
15845
17594
  });
15846
17595
  }
15847
17596
  return {
@@ -15862,7 +17611,7 @@ function createWorkerEventIngestor(deps) {
15862
17611
  if (!process2) {
15863
17612
  return;
15864
17613
  }
15865
- const currentTurnRecordId = liveTurnRecordIds.get(instanceId) ?? deps.turnRecords.listByInstance(instanceId).find((record3) => record3.status === "running" && record3.turnId === process2.selectedTurnId)?.id ?? null;
17614
+ const currentTurnRecordId = liveTurnRecordIds.get(instanceId) ?? deps.turnRecords.listByInstance(instanceId).find((record4) => record4.status === "running" && record4.turnId === process2.selectedTurnId)?.id ?? null;
15866
17615
  const data = asWsEventPayloadRecord(payload.data);
15867
17616
  const suppliedTurnRecordId = readWsEventNonEmptyString(data.turnRecordId);
15868
17617
  const milestone = payload.eventType === "worker.trace" && data.code === "turn.prompt_started" ? "prompt_started" : payload.eventType === "pi.stream.delta" && data.streamType === "text" && (readWsEventStreamText(data)?.length ?? 0) > 0 ? "first_text" : null;
@@ -15880,6 +17629,18 @@ function createWorkerEventIngestor(deps) {
15880
17629
  );
15881
17630
  }
15882
17631
  if (suppliedTurnRecordId && suppliedTurnRecordId !== currentTurnRecordId) return;
17632
+ if (payload.eventType === "execution.inspection") {
17633
+ if (suppliedTurnRecordId && deps.executionInspections && deps.leases)
17634
+ ingestExecutionInspection(
17635
+ {
17636
+ executionInspections: deps.executionInspections,
17637
+ turnRecords: deps.turnRecords,
17638
+ leases: deps.leases
17639
+ },
17640
+ { instanceId, workerId, turnRecordId: suppliedTurnRecordId, capture: data.capture }
17641
+ );
17642
+ return;
17643
+ }
15883
17644
  if (payload.eventType === "turn.progress") {
15884
17645
  const reportedTurnRecordId = readWsEventNonEmptyString(data.turnRecordId);
15885
17646
  if (!reportedTurnRecordId || reportedTurnRecordId !== currentTurnRecordId) return;
@@ -15901,13 +17662,17 @@ function createWorkerEventIngestor(deps) {
15901
17662
  return;
15902
17663
  }
15903
17664
  const projection = getLiveTurnProjection(instanceId, currentTurnRecordId);
15904
- const appliedProjectionEvent = applyPiEventToLiveTurnProjection(projection, {
17665
+ const appliedProjectionEvent = projection.apply({
15905
17666
  eventType: payload.eventType,
15906
17667
  data,
15907
17668
  fallbackTimestamp: (/* @__PURE__ */ new Date()).toISOString()
15908
17669
  });
15909
17670
  const projectionData = appliedProjectionEvent.canonicalData;
15910
- const enrichedData = currentTurnRecordId && !readWsEventNonEmptyString(projectionData.turnRecordId) ? { ...projectionData, turnRecordId: currentTurnRecordId } : projectionData;
17671
+ const enrichedData = currentTurnRecordId && !readWsEventNonEmptyString(projectionData.turnRecordId) ? {
17672
+ ...projectionData,
17673
+ turnRecordId: currentTurnRecordId,
17674
+ workerLeaseId: deps.leases?.getByInstance(instanceId)?.id ?? null
17675
+ } : projectionData;
15911
17676
  const currentSelectedTurnId = payload.selectedTurnId ?? process2.selectedTurnId ?? null;
15912
17677
  const normalizedTimestamp = eventTimestamp(enrichedData);
15913
17678
  const serverObservedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -15967,7 +17732,7 @@ function createWorkerEventIngestor(deps) {
15967
17732
  );
15968
17733
  }
15969
17734
  } else if (payload.eventType === "pi.usage") {
15970
- const usage = projection.usage;
17735
+ const usage = appliedProjectionEvent.usage;
15971
17736
  if (usage) {
15972
17737
  deps.broadcaster.broadcast(
15973
17738
  createEphemeralWsFrame2({
@@ -16091,8 +17856,8 @@ import {
16091
17856
  isWorkerErrorClass
16092
17857
  } from "@leitwerk-dev/domain";
16093
17858
  function terminalWasAlreadyRecorded(deps, turnRecordId, terminalType) {
16094
- const record3 = deps.turnRecords.getById(turnRecordId);
16095
- return terminalType === "outcome" ? record3?.status === "succeeded" : record3?.status === "failed";
17859
+ const record4 = deps.turnRecords.getById(turnRecordId);
17860
+ return terminalType === "outcome" ? record4?.status === "succeeded" : record4?.status === "failed";
16096
17861
  }
16097
17862
  function failureDetails(result) {
16098
17863
  if (result instanceof Error) {
@@ -17110,7 +18875,7 @@ function createWorkerShutdownController(input) {
17110
18875
 
17111
18876
  // src/supervisor/worker-start-payload-builder.ts
17112
18877
  import { randomUUID as randomUUID5 } from "node:crypto";
17113
- import path7 from "node:path";
18878
+ import path9 from "node:path";
17114
18879
  import { parseProductRefsFromStateJsonLenient } from "@leitwerk-dev/domain";
17115
18880
  import { parseDurationMs as parseDurationMs6 } from "@leitwerk-dev/watcher-utils";
17116
18881
  import {
@@ -17176,7 +18941,7 @@ function isTransitionScopedProductFresh(process2, productName, deps) {
17176
18941
  if (!productRef?.turnRecordId) {
17177
18942
  return true;
17178
18943
  }
17179
- const latestTurnRecord = deps.turnRecords.listByInstance(process2.id).findLast((record3) => record3.status === "succeeded") ?? null;
18944
+ const latestTurnRecord = deps.turnRecords.listByInstance(process2.id).findLast((record4) => record4.status === "succeeded") ?? null;
17180
18945
  if (!latestTurnRecord || productRef.turnRecordId === latestTurnRecord.id) {
17181
18946
  return true;
17182
18947
  }
@@ -17276,6 +19041,20 @@ function createWorkerStartPayloadBuilder(deps) {
17276
19041
  function buildWorkerRuntimeContextSnapshot(process2, start) {
17277
19042
  const turnResultMarkdownBySemanticRef = buildTurnResultMarkdownBySemanticRef(process2, deps);
17278
19043
  const turnResultMarkdownByProduct = buildTurnResultMarkdownByProduct(process2, deps);
19044
+ const productRefs = parseProductRefsFromStateJsonLenient(process2.stateJson);
19045
+ const inspectionProducts = Object.entries(turnResultMarkdownByProduct ?? {}).flatMap(
19046
+ ([name, content]) => {
19047
+ const ref = productRefs[name];
19048
+ return ref?.turnRecordId ? [
19049
+ {
19050
+ name,
19051
+ producerTurnRecordId: ref.turnRecordId,
19052
+ entryId: ref.entryId,
19053
+ content: { state: "recorded", value: content }
19054
+ }
19055
+ ] : [];
19056
+ }
19057
+ );
17279
19058
  const prepared = start.state.kind === "starting" || start.state.kind === "accepted" || start.state.kind === "bootstrap_failed" ? start.state.start : null;
17280
19059
  const preparedLlm = prepared?.kind === "llm" ? prepared : null;
17281
19060
  return {
@@ -17287,7 +19066,8 @@ function createWorkerStartPayloadBuilder(deps) {
17287
19066
  },
17288
19067
  projectSnapshots: buildProjectSnapshots(process2.id),
17289
19068
  ...turnResultMarkdownBySemanticRef ? { turnResultMarkdownBySemanticRef } : {},
17290
- ...turnResultMarkdownByProduct ? { turnResultMarkdownByProduct } : {}
19069
+ ...turnResultMarkdownByProduct ? { turnResultMarkdownByProduct } : {},
19070
+ inspectionProducts
17291
19071
  };
17292
19072
  }
17293
19073
  function buildPendingInputsSnapshot(instanceId) {
@@ -17357,7 +19137,7 @@ function createWorkerStartPayloadBuilder(deps) {
17357
19137
  30 * 60 * 1e3,
17358
19138
  { allowHours: true }
17359
19139
  ),
17360
- processStorageRoot: deps.config.workers.runner === "local" ? treePaths.workspaceRoot : path7.dirname(treePaths.workspaceRoot)
19140
+ processStorageRoot: deps.config.workers.runner === "local" ? treePaths.workspaceRoot : path9.dirname(treePaths.workspaceRoot)
17361
19141
  },
17362
19142
  ...treePaths.resume ? { resumeLeafEntryId } : {},
17363
19143
  ...llmPreparation ? { llmPreparation } : {},
@@ -18138,14 +19918,15 @@ function createWorkerSupervisor(deps) {
18138
19918
  buildRuntimeProfileSelectionInput({
18139
19919
  config: deps.config,
18140
19920
  processId: process2.processId,
18141
- componentKeys: deps.projects.listByInstance(process2.id).map((project) => project.key)
19921
+ componentKeys: deps.projects.listByInstance(process2.id).map((project) => project.key),
19922
+ docker: deps.processGraphs.get(process2.processId)?.runtime?.docker === true
18142
19923
  })
18143
19924
  );
18144
19925
  if (!selection.ok) {
18145
19926
  throw new Error(selection.error);
18146
19927
  }
18147
- const profile = deps.config.worker_runtime_profiles?.[selection.runtimeProfile];
18148
- return { selection, profile };
19928
+ const profile2 = deps.config.worker_runtime_profiles?.[selection.runtimeProfile];
19929
+ return { selection, profile: profile2 };
18149
19930
  }
18150
19931
  function runnerServerUrl() {
18151
19932
  if (deps.config.workers.runner === "kubernetes") {
@@ -18159,9 +19940,9 @@ function createWorkerSupervisor(deps) {
18159
19940
  async function startRunnerWorker(options, connect) {
18160
19941
  const process2 = deps.processes.getById(options.instanceId);
18161
19942
  if (!process2) throw new Error(`Cannot start worker for missing process ${options.instanceId}`);
18162
- const { selection, profile } = resolveRunnerStartSelection(process2);
19943
+ const { selection, profile: profile2 } = resolveRunnerStartSelection(process2);
18163
19944
  const docker = deps.processGraphs.get(process2.processId)?.runtime?.docker === true;
18164
- const resourceLimits = profile?.resources?.limits ?? (profile?.resources ? { cpu: profile.resources.cpu, memory: profile.resources.memory } : void 0);
19945
+ const resourceLimits = profile2?.resources?.limits ?? (profile2?.resources ? { cpu: profile2.resources.cpu, memory: profile2.resources.memory } : void 0);
18165
19946
  const observer = createStartupObserver(
18166
19947
  deps,
18167
19948
  options.instanceId,
@@ -18216,7 +19997,7 @@ function createWorkerSupervisor(deps) {
18216
19997
  ...volume ? { runnerKind: "isolated", volume } : { runnerKind: "local" },
18217
19998
  docker,
18218
19999
  resources: resourceLimits,
18219
- resourceRequests: profile?.resources?.requests
20000
+ resourceRequests: profile2?.resources?.requests
18220
20001
  },
18221
20002
  observer
18222
20003
  );
@@ -18493,6 +20274,15 @@ function resolvedDecision(request) {
18493
20274
  }
18494
20275
  function createToolApprovalGate(input) {
18495
20276
  const waiters = /* @__PURE__ */ new Map();
20277
+ const notify = (instanceId) => input.broadcaster.sendDurable(
20278
+ "process.event",
20279
+ {
20280
+ eventType: "tool_approval_updated",
20281
+ level: "info",
20282
+ message: "Issue approval updated"
20283
+ },
20284
+ instanceId
20285
+ );
18496
20286
  function reconcile(instanceId) {
18497
20287
  for (const request of input.repos.toolApprovalRequests.listByInstance(instanceId)) {
18498
20288
  const decision = resolvedDecision(request);
@@ -18510,6 +20300,7 @@ function createToolApprovalGate(input) {
18510
20300
  const result = input.repos.toolApprovalRequests.createIdempotent(requestInput);
18511
20301
  const decision = resolvedDecision(result.request);
18512
20302
  if (decision) return decision;
20303
+ if (result.kind === "created") notify(requestInput.instanceId);
18513
20304
  return await new Promise((resolve) => {
18514
20305
  const pending = waiters.get(result.request.id) ?? /* @__PURE__ */ new Set();
18515
20306
  pending.add(resolve);
@@ -18539,26 +20330,209 @@ function createToolApprovalGate(input) {
18539
20330
  });
18540
20331
  })
18541
20332
  );
20333
+ if (resolved) notify(instanceId);
18542
20334
  reconcile(instanceId);
18543
20335
  return resolved;
18544
20336
  },
18545
20337
  /** @internal */
18546
20338
  cancelTurn(instanceId, turnRecordId) {
18547
20339
  const changed = input.repos.toolApprovalRequests.cancelOpenByTurn(instanceId, turnRecordId);
20340
+ if (changed) notify(instanceId);
18548
20341
  reconcile(instanceId);
18549
20342
  return changed;
18550
20343
  }
18551
20344
  };
18552
20345
  }
18553
20346
 
20347
+ // src/turn-wait-service.ts
20348
+ import { assertRepoLocator } from "@leitwerk-dev/domain";
20349
+ import {
20350
+ RetryableWaitError
20351
+ } from "@leitwerk-dev/process-sdk";
20352
+ function createTurnWaitService(deps) {
20353
+ const running = /* @__PURE__ */ new Map();
20354
+ const controllers = /* @__PURE__ */ new Set();
20355
+ const now2 = deps.now ?? Date.now;
20356
+ const interval = deps.pollIntervalMs ?? 3e4;
20357
+ let stopped = false;
20358
+ let activeChecks = 0;
20359
+ const queued = [];
20360
+ function schedule(work) {
20361
+ return new Promise((resolve, reject2) => {
20362
+ const start = () => {
20363
+ if (stopped) {
20364
+ resolve();
20365
+ return;
20366
+ }
20367
+ activeChecks++;
20368
+ void work().then(resolve, reject2).finally(() => {
20369
+ activeChecks--;
20370
+ queued.shift()?.();
20371
+ });
20372
+ };
20373
+ if (activeChecks < 4) start();
20374
+ else queued.push(start);
20375
+ });
20376
+ }
20377
+ if (!Number.isFinite(interval) || interval <= 0) throw new Error("Invalid wait polling interval");
20378
+ async function evaluate(instanceId) {
20379
+ let process2 = deps.processes.getById(instanceId);
20380
+ if (!process2 || !turnWaitPredicate(deps.processGraphs, process2)) return;
20381
+ if (!pendingTurnWait(process2)) {
20382
+ if (process2.currentExecution || process2.lifecycleStatus !== "active") return;
20383
+ await deps.commands.run(ArmTurnWait, { instanceId });
20384
+ process2 = deps.processes.getById(instanceId);
20385
+ }
20386
+ if (!process2 || stopped) return;
20387
+ const wait = pendingTurnWait(process2);
20388
+ if (!wait || wait.status !== "waiting" || process2.lifecycleStatus !== "waiting" || wait.nextCheckAt > now2())
20389
+ return;
20390
+ const predicate = turnWaitPredicate(deps.processGraphs, process2);
20391
+ if (!predicate) return;
20392
+ const projects = deps.projects.listByInstance(instanceId);
20393
+ const controller = new AbortController();
20394
+ controllers.add(controller);
20395
+ let state;
20396
+ let nextStateJson;
20397
+ let result;
20398
+ let initialBinding;
20399
+ let message;
20400
+ let timeout;
20401
+ let onAbort;
20402
+ try {
20403
+ const data = deps.registry.resolveContextData(process2.processId, process2);
20404
+ const context = {
20405
+ process: structuredClone(process2),
20406
+ projects: structuredClone(projects),
20407
+ params: data.params,
20408
+ state: data.state,
20409
+ signal: controller.signal,
20410
+ require: deps.require,
20411
+ setState(value2) {
20412
+ if (!controller.signal.aborted) state = value2;
20413
+ },
20414
+ complete: () => ({ kind: "complete" }),
20415
+ waiting: (message2) => ({ kind: "waiting", message: message2 }),
20416
+ abort: (message2) => ({ kind: "abort", message: message2 }),
20417
+ bindInitialProjects: (binding2) => ({ kind: "bind", binding: binding2 })
20418
+ };
20419
+ const timedOut = new Promise((_, reject2) => {
20420
+ onAbort = () => reject2(new RetryableWaitError("Waiting condition interrupted"));
20421
+ controller.signal.addEventListener("abort", onAbort, { once: true });
20422
+ timeout = setTimeout(() => {
20423
+ reject2(new RetryableWaitError("Waiting condition timed out"));
20424
+ controller.abort();
20425
+ }, deps.timeoutMs ?? 3e4);
20426
+ });
20427
+ const value = await Promise.race([
20428
+ Promise.resolve().then(() => predicate(context)),
20429
+ timedOut
20430
+ ]);
20431
+ if (typeof value === "boolean") result = value ? "ready" : "waiting";
20432
+ else if (value && value.kind === "complete") result = "complete";
20433
+ else if (value && (value.kind === "waiting" || value.kind === "abort")) {
20434
+ if (typeof value.message !== "string" || !value.message.trim())
20435
+ throw new Error("Readiness guidance must be nonempty text");
20436
+ result = value.kind;
20437
+ message = value.message.slice(0, 2e3);
20438
+ } else if (value?.kind === "bind") {
20439
+ if (!wait.initialSelection || projects.length || !value.binding.projects.length)
20440
+ throw new Error(
20441
+ "Initial repository binding requires an unstarted process without projects"
20442
+ );
20443
+ const codec = deps.processGraphs.get(process2.processId)?.paramsCodec;
20444
+ if (!codec) throw new Error("Process params codec is unavailable");
20445
+ const keys = /* @__PURE__ */ new Set();
20446
+ for (const project of value.binding.projects) {
20447
+ if (!/^[a-zA-Z0-9_-]+$/.test(project.key) || keys.has(project.key) || !project.baseBranch?.trim())
20448
+ throw new Error("Invalid initial repository binding");
20449
+ assertRepoLocator(project.repoLocator);
20450
+ keys.add(project.key);
20451
+ }
20452
+ if (Object.keys(value.binding.metadata ?? {}).some(
20453
+ (key) => key === "turnWait" || Object.hasOwn(process2.metadata ?? {}, key)
20454
+ ))
20455
+ throw new Error("Initial repository binding cannot replace retained metadata");
20456
+ initialBinding = structuredClone({
20457
+ params: codec.serialize(codec.parse(value.binding.params)),
20458
+ projects: normalizeProjectInputs(value.binding, deps.commitMessages),
20459
+ metadata: value.binding.metadata,
20460
+ settingsContext: value.binding.settingsContext
20461
+ });
20462
+ result = "bind";
20463
+ } else throw new Error("Invalid turn readiness decision");
20464
+ if (state !== void 0) {
20465
+ const codec = deps.processGraphs.get(process2.processId)?.stateCodec;
20466
+ if (!codec) throw new Error("Process state codec is unavailable");
20467
+ nextStateJson = JSON.stringify(codec.serialize(codec.parse(state)));
20468
+ }
20469
+ } catch (error) {
20470
+ result = error instanceof RetryableWaitError ? "retry" : "error";
20471
+ message = error instanceof Error ? error.message.slice(0, 500) : "Waiting condition failed";
20472
+ } finally {
20473
+ if (timeout) clearTimeout(timeout);
20474
+ if (onAbort) controller.signal.removeEventListener("abort", onAbort);
20475
+ controllers.delete(controller);
20476
+ }
20477
+ if (stopped) return;
20478
+ await deps.commands.run(ResolveTurnWait, {
20479
+ instanceId,
20480
+ waitId: wait.id,
20481
+ revision: wait.revision,
20482
+ paramsJson: process2.paramsJson,
20483
+ stateJson: process2.stateJson,
20484
+ projectsJson: JSON.stringify(projects),
20485
+ nextStateJson,
20486
+ initialBinding,
20487
+ result,
20488
+ message,
20489
+ now: now2(),
20490
+ pollIntervalMs: interval
20491
+ });
20492
+ }
20493
+ function check(instanceId) {
20494
+ if (stopped) return Promise.resolve();
20495
+ const current = running.get(instanceId);
20496
+ if (current) return current;
20497
+ const promise = Promise.resolve().then(() => schedule(() => evaluate(instanceId))).finally(() => running.delete(instanceId));
20498
+ running.set(instanceId, promise);
20499
+ return promise;
20500
+ }
20501
+ return {
20502
+ check,
20503
+ async poll() {
20504
+ const errors = [];
20505
+ const candidates = deps.processes.listAll().filter(
20506
+ (process2) => ["waiting", "active"].includes(process2.lifecycleStatus) && turnWaitPredicate(deps.processGraphs, process2)
20507
+ );
20508
+ await Promise.all(
20509
+ candidates.map(async (process2) => {
20510
+ try {
20511
+ await check(process2.id);
20512
+ } catch {
20513
+ errors.push(`${process2.id}:waiting_check_failed`);
20514
+ }
20515
+ })
20516
+ );
20517
+ return { errors };
20518
+ },
20519
+ async stop() {
20520
+ stopped = true;
20521
+ for (const start of queued.splice(0)) start();
20522
+ for (const controller of controllers) controller.abort();
20523
+ await Promise.allSettled(running.values());
20524
+ }
20525
+ };
20526
+ }
20527
+
18554
20528
  // src/app.ts
18555
20529
  function createConfiguredDatabase(config) {
18556
20530
  return config.storage.sqlite_path === ":memory:" ? createInMemoryDatabase() : createDatabase({ sqlitePath: config.storage.sqlite_path });
18557
20531
  }
18558
20532
  function configuredExporterProfile(config) {
18559
20533
  const profileId = defaultWorkerRuntimeProfile(config);
18560
- const profile = profileId ? config.worker_runtime_profiles?.[profileId] : void 0;
18561
- return { image: profile?.image, imagePullPolicy: profile?.image_pull_policy };
20534
+ const profile2 = profileId ? config.worker_runtime_profiles?.[profileId] : void 0;
20535
+ return { image: profile2?.image, imagePullPolicy: profile2?.image_pull_policy };
18562
20536
  }
18563
20537
  async function createConfiguredWorkerRunnerRuntime(input) {
18564
20538
  if (input.provided) {
@@ -18595,6 +20569,12 @@ async function createConfiguredWorkerRunnerRuntime(input) {
18595
20569
  const created2 = createKubernetesWorkerRunner({
18596
20570
  client: kubernetesClient,
18597
20571
  preProvision: processVolume?.pre_provision ? { ...processVolume.pre_provision, onError: input.onVolumePoolError } : void 0,
20572
+ imagePreload: input.config.kubernetes?.image_preload?.enabled ? {
20573
+ images: Object.values(input.config.worker_runtime_profiles ?? {}).map(
20574
+ (profile2) => profile2.image
20575
+ ),
20576
+ onEvent: input.onImagePreparationEvent
20577
+ } : void 0,
18598
20578
  processNamespacePrefix: input.config.kubernetes?.process_namespace_prefix ?? "leitwerk-process-",
18599
20579
  volume: {
18600
20580
  size: processVolume?.size ?? "20Gi",
@@ -18717,13 +20697,16 @@ ${configErrors.join("\n")}`);
18717
20697
  const repos = createAllRepos(db, {
18718
20698
  ...credentialCipher ? { credentialCipher } : {}
18719
20699
  });
20700
+ const extensionSkills = await importExtensionSkills(extensionCatalog.modules);
18720
20701
  repos.transaction((transactionRepos) => {
20702
+ transactionRepos.skills.reconcileExtensions(extensionSkills);
18721
20703
  transactionRepos.skills.reconcile([]);
18722
20704
  transactionRepos.skills.backfillDependencies();
18723
20705
  });
18724
20706
  const skillCatalog = createSkillCatalogService({
18725
20707
  repositories: config.skill_repositories ?? [],
18726
- repos
20708
+ repos,
20709
+ bundledSkills: await importBundledSkills(extensionCatalog.piContributions)
18727
20710
  });
18728
20711
  await skillCatalog.refresh();
18729
20712
  markStartup("skill_catalog");
@@ -18757,12 +20740,30 @@ ${configErrors.join("\n")}`);
18757
20740
  });
18758
20741
  markStartup("model_providers");
18759
20742
  const broadcaster = createBroadcaster();
20743
+ repos.topicWiki = createTopicWikiRepo(
20744
+ db,
20745
+ (topicId) => broadcaster.sendDurable("wiki.updated", { topicId })
20746
+ );
18760
20747
  const processOperations = createProcessOperationCoordinator();
18761
20748
  const processGraphs = extensionCatalog.processes;
18762
20749
  const processActionRegistry = buildProcessActionRegistry(extensionCatalog);
18763
20750
  const integrationTools = new IntegrationToolRegistry(repos.externalWrites);
18764
20751
  const processUiRegistry = buildProcessUiRegistry(extensionCatalog);
20752
+ const scopedSettings = createScopedSettingsService({
20753
+ repos,
20754
+ catalog: extensionCatalog,
20755
+ config,
20756
+ modelChoices: () => config.pi.model_profiles.map((profile2) => {
20757
+ const status = modelStatusCache.snapshot().profiles.find((entry) => entry.profileId === profile2.id);
20758
+ return {
20759
+ value: profile2.id,
20760
+ label: `${profile2.id} \u2014 ${profile2.provider}/${profile2.model_id}`,
20761
+ ...status?.availability === "available" ? {} : { disabledReason: status?.safeReason ?? "Model unavailable" }
20762
+ };
20763
+ })
20764
+ });
18765
20765
  const processModelPolicy = createServerProcessModelPolicy({
20766
+ scopedSettings,
18766
20767
  config,
18767
20768
  processGraphs,
18768
20769
  processActionRegistry
@@ -18773,23 +20774,23 @@ ${configErrors.join("\n")}`);
18773
20774
  );
18774
20775
  markStartup("extension_ui_catalog");
18775
20776
  const launcherModelProfiles = config.pi.model_profiles.map(
18776
- (profile) => ({
18777
- id: profile.id,
18778
- provider: profile.provider,
18779
- modelId: profile.model_id,
18780
- thinkingLevel: profile.thinking_level ?? "off"
20777
+ (profile2) => ({
20778
+ id: profile2.id,
20779
+ provider: profile2.provider,
20780
+ modelId: profile2.model_id,
20781
+ thinkingLevel: profile2.thinking_level ?? "off"
18781
20782
  })
18782
20783
  );
18783
20784
  const launcherModelProfilesById = new Map(
18784
- launcherModelProfiles.map((profile) => [profile.id, profile])
20785
+ launcherModelProfiles.map((profile2) => [profile2.id, profile2])
18785
20786
  );
18786
20787
  const getModelProfilesForProcess = (processId) => {
18787
20788
  return processModelPolicy.project({
18788
20789
  kind: "profile_options",
18789
20790
  processId,
18790
20791
  availability: modelStatusCache.snapshot()
18791
- }).map((profile) => launcherModelProfilesById.get(profile.id)).filter(
18792
- (profile) => profile !== void 0
20792
+ }).map((profile2) => launcherModelProfilesById.get(profile2.id)).filter(
20793
+ (profile2) => profile2 !== void 0
18793
20794
  );
18794
20795
  };
18795
20796
  const launcherService = buildProcessLauncherRegistry(extensionCatalog, {
@@ -18812,7 +20813,7 @@ ${configErrors.join("\n")}`);
18812
20813
  for (const process2 of repos.processes.listAll()) await sessionSnapshots.backfill(process2.id);
18813
20814
  const sessionReader = new ProcessSessionReader(sessionSnapshots);
18814
20815
  const resultImages = new ResultImageStore({
18815
- rootDir: path8.join(config.storage.tree_files_dir, "result-images")
20816
+ rootDir: path10.join(config.storage.tree_files_dir, "result-images")
18816
20817
  });
18817
20818
  const authService = createAuthService({ config, repos });
18818
20819
  await registerWebsocket(app, broadcaster, workerWebSocketIpc, authService);
@@ -18864,6 +20865,7 @@ ${configErrors.join("\n")}`);
18864
20865
  }
18865
20866
  };
18866
20867
  const launcherModelConfigs = createLauncherModelConfigService({
20868
+ scopedSettingsService: scopedSettings,
18867
20869
  launcherService,
18868
20870
  launchPlans,
18869
20871
  processModelPolicy,
@@ -19008,6 +21010,7 @@ ${configErrors.join("\n")}`);
19008
21010
  processModelPolicy,
19009
21011
  getModelAvailabilitySnapshot: () => modelStatusCache.snapshot(),
19010
21012
  afterRecord(process2) {
21013
+ invalidateExternalSourceArmings?.(process2.id);
19011
21014
  piResourceBundlePins.reconcile(process2);
19012
21015
  toolApprovalGate.reconcile(process2.id);
19013
21016
  },
@@ -19017,11 +21020,15 @@ ${configErrors.join("\n")}`);
19017
21020
  {
19018
21021
  config,
19019
21022
  registry: modelProviderRegistry,
21023
+ processActionRegistry,
21024
+ mappedRuns: baseDeps.mappedRuns,
19020
21025
  modelStatusCache,
19021
21026
  piContributions: extensionCatalog.piContributions,
19022
21027
  bundleCache: piResourceBundles,
19023
21028
  projects: baseDeps.projects,
19024
- processSkills: baseDeps.processSkills
21029
+ processSkills: baseDeps.processSkills,
21030
+ scopedSettings,
21031
+ processModelPolicy
19025
21032
  },
19026
21033
  process2,
19027
21034
  writes,
@@ -19044,19 +21051,24 @@ ${configErrors.join("\n")}`);
19044
21051
  });
19045
21052
  const toolApprovalGate = createToolApprovalGate({
19046
21053
  repos: baseDeps,
19047
- processOperations
21054
+ processOperations,
21055
+ broadcaster
19048
21056
  });
19049
21057
  const integrationToolRequests = createIntegrationToolRequestService({
19050
21058
  registry: integrationTools,
19051
21059
  repos: baseDeps,
19052
21060
  processActionRegistry,
19053
- toolApprovalGate
21061
+ toolApprovalGate,
21062
+ reportProgress: (report) => {
21063
+ recordTurnProgress(baseDeps, report);
21064
+ }
19054
21065
  });
19055
21066
  const diagnosticTraceWriter = createDiagnosticTraceWriter(
19056
- path8.join(config.storage.tree_files_dir, "diagnostic-traces")
21067
+ path10.join(config.storage.tree_files_dir, "diagnostic-traces")
19057
21068
  );
19058
21069
  const ipcHandler = createIpcHandler(
19059
21070
  {
21071
+ executionInspections: baseDeps.executionInspections,
19060
21072
  startupObservations: baseDeps.startupObservations,
19061
21073
  processes: baseDeps.processes,
19062
21074
  getLaunchCoordinator: () => launchCoordinator,
@@ -19153,15 +21165,20 @@ ${configErrors.join("\n")}`);
19153
21165
  provided: opts.workerRunnerRuntime,
19154
21166
  helperRelays: sessionTransferHelperRelays,
19155
21167
  onVolumePoolError: () => app.log.warn("Volume pre-provisioning failed; retrying in the background"),
21168
+ onImagePreparationEvent: (event) => {
21169
+ if (event.outcome === "succeeded") app.log.info(event, "Worker image prepared");
21170
+ else app.log.warn(event, "Worker image preparation failed; retrying in the background");
21171
+ },
19156
21172
  localWorkerSpawnImpl: opts.localWorkerSpawnImpl,
19157
21173
  localWorkerDockerPreflightImpl: opts.localWorkerDockerPreflightImpl
19158
21174
  });
19159
- if (runnerRuntime.volumePool) {
19160
- startHooks.push(() => runnerRuntime.volumePool?.start());
19161
- stopHooks.push(() => runnerRuntime.volumePool?.stop());
21175
+ if (runnerRuntime.preparation) {
21176
+ startHooks.push(() => runnerRuntime.preparation?.start());
21177
+ stopHooks.push(() => runnerRuntime.preparation?.stop());
19162
21178
  }
19163
21179
  markStartup("worker_runner");
19164
21180
  supervisor = createWorkerSupervisor({
21181
+ executionInspections: baseDeps.executionInspections,
19165
21182
  startupObservations: baseDeps.startupObservations,
19166
21183
  config: supervisorConfig,
19167
21184
  processGraphs,
@@ -19291,6 +21308,7 @@ ${configErrors.join("\n")}`);
19291
21308
  );
19292
21309
  const processLaunchDeps = {
19293
21310
  ...baseDeps,
21311
+ skillDefaults: config,
19294
21312
  broadcaster,
19295
21313
  commands: processEngine,
19296
21314
  processTitles,
@@ -19302,6 +21320,7 @@ ${configErrors.join("\n")}`);
19302
21320
  };
19303
21321
  const createProcess = createProcessFromLaunchPlan.bind(null, processLaunchDeps);
19304
21322
  futureExecutionLifecycle = createFutureExecutionLifecycle({
21323
+ skillDefaults: config,
19305
21324
  futureExecutions: baseDeps.futureExecutions,
19306
21325
  processes: baseDeps.processes,
19307
21326
  projects: baseDeps.projects,
@@ -19429,6 +21448,7 @@ ${configErrors.join("\n")}`);
19429
21448
  modelStatusCache
19430
21449
  });
19431
21450
  const hostCapabilities = buildHostCapabilities({
21451
+ integrationTools,
19432
21452
  config,
19433
21453
  baseDeps,
19434
21454
  projectMutations,
@@ -19452,6 +21472,32 @@ ${configErrors.join("\n")}`);
19452
21472
  launchCoordinator,
19453
21473
  preProvidedCapabilities: opts.preProvidedCapabilities
19454
21474
  });
21475
+ hostCapabilities.provide(scopedSettingsCapability, scopedSettings);
21476
+ const turnWaitService = createTurnWaitService({
21477
+ commitMessages: config.commit_messages,
21478
+ processes: baseDeps.processes,
21479
+ projects: baseDeps.projects,
21480
+ processGraphs,
21481
+ registry: processActionRegistry,
21482
+ commands: processEngine,
21483
+ require: hostCapabilities.require.bind(hostCapabilities),
21484
+ ...opts.turnWait
21485
+ });
21486
+ polling.create({
21487
+ id: "turn-readiness",
21488
+ pollOnce: turnWaitService.poll,
21489
+ isEnabled: () => true,
21490
+ pollInterval: () => "1s",
21491
+ defaultIntervalMs: 1e3
21492
+ });
21493
+ afterSuccessHooks.add((instanceId) => {
21494
+ void turnWaitService.check(instanceId).catch((error) => {
21495
+ app.log.error({ err: error, instanceId }, "Turn readiness check failed");
21496
+ });
21497
+ });
21498
+ const wiki = hostCapabilities.require(topicWikiCapability2);
21499
+ if (Array.isArray(wiki)) throw new Error("Wiki integration must be singular");
21500
+ registerWikiTools({ tool: (definition) => integrationTools.register(definition) }, wiki);
19455
21501
  await setupServerExtensions(
19456
21502
  extensionCatalog,
19457
21503
  {
@@ -19472,7 +21518,10 @@ ${configErrors.join("\n")}`);
19472
21518
  );
19473
21519
  integrationTools.validateTicketProcesses(extensionCatalog.processes);
19474
21520
  startHooks.push(() => polling.start());
19475
- stopHooks.push(() => polling.stop());
21521
+ stopHooks.push(async () => {
21522
+ await turnWaitService.stop();
21523
+ await polling.stop();
21524
+ });
19476
21525
  for (const process2 of extensionCatalog.processes.values()) {
19477
21526
  for (const [turnId, binding2] of process2.turns) {
19478
21527
  const definition = binding2.definition;
@@ -19488,6 +21537,12 @@ ${configErrors.join("\n")}`);
19488
21537
  }
19489
21538
  markStartup("server_extensions");
19490
21539
  const deps = {
21540
+ onSettingsChanged: async () => {
21541
+ await futureExecutionLifecycle.reconcileModelAvailability({
21542
+ availability: modelStatusCache.snapshot()
21543
+ });
21544
+ },
21545
+ scopedSettingsService: scopedSettings,
19491
21546
  externalSourceService,
19492
21547
  ...baseDeps,
19493
21548
  launchCoordinator,
@@ -19577,4 +21632,4 @@ ${configErrors.join("\n")}`);
19577
21632
  export {
19578
21633
  createAppContext
19579
21634
  };
19580
- //# sourceMappingURL=chunk-QCHS3X33.js.map
21635
+ //# sourceMappingURL=chunk-FPMDWQF7.js.map