@leitwerk-dev/server 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/dist/{app-BuJCdkvy.d.ts → app-CtlotzYm.d.ts} +312 -121
  2. package/dist/app-KR3N2JAE.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-OUA5EZS2.js} +3127 -689
  8. package/dist/chunk-OUA5EZS2.js.map +1 -0
  9. package/dist/{chunk-HK6BLLHA.js → chunk-YLWY4UTT.js} +2424 -1580
  10. package/dist/chunk-YLWY4UTT.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 +16 -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/dashboard-model-issues.d.ts +10 -0
  18. package/dist/dashboard-model-issues.d.ts.map +1 -0
  19. package/dist/db/database.d.ts.map +1 -1
  20. package/dist/db/execution-inspection-repo.d.ts +15 -0
  21. package/dist/db/execution-inspection-repo.d.ts.map +1 -0
  22. package/dist/db/history-window.d.ts +11 -0
  23. package/dist/db/history-window.d.ts.map +1 -0
  24. package/dist/db/process-event-repo.d.ts +2 -0
  25. package/dist/db/process-event-repo.d.ts.map +1 -1
  26. package/dist/db/process-instance-repo.d.ts +21 -1
  27. package/dist/db/process-instance-repo.d.ts.map +1 -1
  28. package/dist/db/process-leaf-outcome-snapshot-repo.d.ts +2 -1
  29. package/dist/db/process-leaf-outcome-snapshot-repo.d.ts.map +1 -1
  30. package/dist/db/process-project-repo.d.ts +2 -0
  31. package/dist/db/process-project-repo.d.ts.map +1 -1
  32. package/dist/db/process-skill-repo.d.ts.map +1 -1
  33. package/dist/db/process-turn-annotation-repo.d.ts +4 -1
  34. package/dist/db/process-turn-annotation-repo.d.ts.map +1 -1
  35. package/dist/db/process-turn-record-repo.d.ts +4 -0
  36. package/dist/db/process-turn-record-repo.d.ts.map +1 -1
  37. package/dist/db/publication-repo.d.ts +5 -0
  38. package/dist/db/publication-repo.d.ts.map +1 -0
  39. package/dist/db/repositories.d.ts +12 -0
  40. package/dist/db/repositories.d.ts.map +1 -1
  41. package/dist/db/schema.d.ts +693 -2
  42. package/dist/db/schema.d.ts.map +1 -1
  43. package/dist/db/scoped-settings-repo.d.ts +37 -0
  44. package/dist/db/scoped-settings-repo.d.ts.map +1 -0
  45. package/dist/db/skill-repo.d.ts +3 -0
  46. package/dist/db/skill-repo.d.ts.map +1 -1
  47. package/dist/db/turn-start-record-repo.d.ts +2 -1
  48. package/dist/db/turn-start-record-repo.d.ts.map +1 -1
  49. package/dist/db/turn-summary-repo.d.ts +10 -1
  50. package/dist/db/turn-summary-repo.d.ts.map +1 -1
  51. package/dist/db/worker-lease-repo.d.ts +2 -1
  52. package/dist/db/worker-lease-repo.d.ts.map +1 -1
  53. package/dist/domain-logic/outcome-tools.d.ts.map +1 -1
  54. package/dist/domain-logic/worker-lease-lifecycle.d.ts.map +1 -1
  55. package/dist/external-source-service.d.ts.map +1 -1
  56. package/dist/future-execution/execution.d.ts +4 -1
  57. package/dist/future-execution/execution.d.ts.map +1 -1
  58. package/dist/future-execution/launch-lifecycle.d.ts +9 -25
  59. package/dist/future-execution/launch-lifecycle.d.ts.map +1 -1
  60. package/dist/future-execution/lifecycle.d.ts +3 -28
  61. package/dist/future-execution/lifecycle.d.ts.map +1 -1
  62. package/dist/future-execution/model-projection.d.ts.map +1 -1
  63. package/dist/future-execution/reconciliation.d.ts +1 -0
  64. package/dist/future-execution/reconciliation.d.ts.map +1 -1
  65. package/dist/future-execution-presenter.d.ts.map +1 -1
  66. package/dist/index.js +2 -2
  67. package/dist/integration-tool-registry.d.ts +11 -2
  68. package/dist/integration-tool-registry.d.ts.map +1 -1
  69. package/dist/launch-coordinator.d.ts.map +1 -1
  70. package/dist/launcher-model-config-service.d.ts +7 -1
  71. package/dist/launcher-model-config-service.d.ts.map +1 -1
  72. package/dist/leaf-outcome-snapshot-capture.d.ts +1 -0
  73. package/dist/leaf-outcome-snapshot-capture.d.ts.map +1 -1
  74. package/dist/main.js +3 -3
  75. package/dist/primary-path-snapshot.d.ts.map +1 -1
  76. package/dist/process-action-presenter.d.ts +1 -6
  77. package/dist/process-action-presenter.d.ts.map +1 -1
  78. package/dist/process-action-registry.d.ts.map +1 -1
  79. package/dist/process-engine/decision.d.ts +2 -0
  80. package/dist/process-engine/decision.d.ts.map +1 -1
  81. package/dist/process-engine/engine.d.ts.map +1 -1
  82. package/dist/process-engine/mapped-turns.d.ts.map +1 -1
  83. package/dist/process-engine/ops/automatic-retry-startup.d.ts +8 -0
  84. package/dist/process-engine/ops/automatic-retry-startup.d.ts.map +1 -0
  85. package/dist/process-engine/ops/continue-failed-turn.d.ts.map +1 -1
  86. package/dist/process-engine/ops/process-observation.d.ts +6 -0
  87. package/dist/process-engine/ops/process-observation.d.ts.map +1 -0
  88. package/dist/process-engine/ops/retry-failed-turn.d.ts.map +1 -1
  89. package/dist/process-engine/ops/retry-startup.d.ts +2 -0
  90. package/dist/process-engine/ops/retry-startup.d.ts.map +1 -1
  91. package/dist/process-engine/ops/start-process.d.ts +2 -0
  92. package/dist/process-engine/ops/start-process.d.ts.map +1 -1
  93. package/dist/process-engine/ops/turn-outcome.d.ts.map +1 -1
  94. package/dist/process-engine/ops/turn-wait.d.ts +30 -0
  95. package/dist/process-engine/ops/turn-wait.d.ts.map +1 -0
  96. package/dist/process-engine/ops/update-model-config.d.ts +9 -0
  97. package/dist/process-engine/ops/update-model-config.d.ts.map +1 -0
  98. package/dist/process-engine/recorder.d.ts.map +1 -1
  99. package/dist/process-engine/turn-start-preflight.d.ts +6 -0
  100. package/dist/process-engine/turn-start-preflight.d.ts.map +1 -1
  101. package/dist/process-engine/turn-wait-state.d.ts +24 -0
  102. package/dist/process-engine/turn-wait-state.d.ts.map +1 -0
  103. package/dist/process-engine/turn-worker-requirement.d.ts +2 -0
  104. package/dist/process-engine/turn-worker-requirement.d.ts.map +1 -1
  105. package/dist/process-engine/types.d.ts +13 -2
  106. package/dist/process-engine/types.d.ts.map +1 -1
  107. package/dist/process-engine/writes/build-process-abort-writes.d.ts +3 -1
  108. package/dist/process-engine/writes/build-process-abort-writes.d.ts.map +1 -1
  109. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts +2 -0
  110. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts.map +1 -1
  111. package/dist/process-engine/writes/commit-writes.d.ts +2 -0
  112. package/dist/process-engine/writes/commit-writes.d.ts.map +1 -1
  113. package/dist/process-engine/writes/writes.d.ts +28 -60
  114. package/dist/process-engine/writes/writes.d.ts.map +1 -1
  115. package/dist/process-graph.d.ts +1 -1
  116. package/dist/process-graph.d.ts.map +1 -1
  117. package/dist/process-inspection-reader.d.ts +21 -0
  118. package/dist/process-inspection-reader.d.ts.map +1 -0
  119. package/dist/process-inspection-trace.d.ts +13 -0
  120. package/dist/process-inspection-trace.d.ts.map +1 -0
  121. package/dist/process-inspection.d.ts +22 -0
  122. package/dist/process-inspection.d.ts.map +1 -0
  123. package/dist/process-instance-tree-presenter.d.ts +4 -3
  124. package/dist/process-instance-tree-presenter.d.ts.map +1 -1
  125. package/dist/process-launch-executor.d.ts +2 -0
  126. package/dist/process-launch-executor.d.ts.map +1 -1
  127. package/dist/process-launch-plan.d.ts +1 -0
  128. package/dist/process-launch-plan.d.ts.map +1 -1
  129. package/dist/process-launcher-registry.d.ts.map +1 -1
  130. package/dist/process-model-availability-recovery.d.ts +1 -1
  131. package/dist/process-model-availability-recovery.d.ts.map +1 -1
  132. package/dist/process-model-config.d.ts +19 -0
  133. package/dist/process-model-config.d.ts.map +1 -0
  134. package/dist/process-model-policy/construct.d.ts.map +1 -1
  135. package/dist/process-model-policy/evaluate.d.ts.map +1 -1
  136. package/dist/process-model-policy/index.d.ts +4 -1
  137. package/dist/process-model-policy/index.d.ts.map +1 -1
  138. package/dist/process-model-policy/project.d.ts.map +1 -1
  139. package/dist/process-model-policy/types.d.ts +18 -0
  140. package/dist/process-model-policy/types.d.ts.map +1 -1
  141. package/dist/process-model-policy-presenter.d.ts.map +1 -1
  142. package/dist/process-runtime-availability.d.ts +2 -1
  143. package/dist/process-runtime-availability.d.ts.map +1 -1
  144. package/dist/process-turn-trace.d.ts.map +1 -1
  145. package/dist/process-ui-snapshot-presenter.d.ts +14 -3
  146. package/dist/process-ui-snapshot-presenter.d.ts.map +1 -1
  147. package/dist/routes/dashboard.d.ts +17 -0
  148. package/dist/routes/dashboard.d.ts.map +1 -0
  149. package/dist/routes/future-executions.d.ts.map +1 -1
  150. package/dist/routes/launchers.d.ts.map +1 -1
  151. package/dist/routes/process-actions.d.ts.map +1 -1
  152. package/dist/routes/process-detail.d.ts.map +1 -1
  153. package/dist/routes/process-model-config.d.ts +4 -0
  154. package/dist/routes/process-model-config.d.ts.map +1 -0
  155. package/dist/routes/process-route-helpers.d.ts +8 -9
  156. package/dist/routes/process-route-helpers.d.ts.map +1 -1
  157. package/dist/routes/processes.d.ts.map +1 -1
  158. package/dist/routes/settings.d.ts +11 -0
  159. package/dist/routes/settings.d.ts.map +1 -0
  160. package/dist/routes/ticket-creation.d.ts.map +1 -1
  161. package/dist/scoped-settings-service.d.ts +98 -0
  162. package/dist/scoped-settings-service.d.ts.map +1 -0
  163. package/dist/server-bootstrap/build-host-capabilities.d.ts +2 -0
  164. package/dist/server-bootstrap/build-host-capabilities.d.ts.map +1 -1
  165. package/dist/server-bootstrap/register-http.d.ts.map +1 -1
  166. package/dist/session-summary-projection.d.ts.map +1 -1
  167. package/dist/skills/bundled-skills.d.ts +5 -0
  168. package/dist/skills/bundled-skills.d.ts.map +1 -0
  169. package/dist/skills/catalog-service.d.ts +1 -0
  170. package/dist/skills/catalog-service.d.ts.map +1 -1
  171. package/dist/skills/extension-importer.d.ts +11 -0
  172. package/dist/skills/extension-importer.d.ts.map +1 -0
  173. package/dist/skills/launch-skills.d.ts +11 -0
  174. package/dist/skills/launch-skills.d.ts.map +1 -0
  175. package/dist/skills/skill-frontmatter.d.ts +7 -0
  176. package/dist/skills/skill-frontmatter.d.ts.map +1 -1
  177. package/dist/skills/source-importer.d.ts +3 -0
  178. package/dist/skills/source-importer.d.ts.map +1 -1
  179. package/dist/startup-evidence.d.ts +4 -3
  180. package/dist/startup-evidence.d.ts.map +1 -1
  181. package/dist/startup-retry-policy.d.ts +8 -0
  182. package/dist/startup-retry-policy.d.ts.map +1 -0
  183. package/dist/supervisor/execution-inspection-ingestor.d.ts +9 -0
  184. package/dist/supervisor/execution-inspection-ingestor.d.ts.map +1 -0
  185. package/dist/supervisor/ipc-handler.d.ts +2 -0
  186. package/dist/supervisor/ipc-handler.d.ts.map +1 -1
  187. package/dist/supervisor/worker-event-ingestor.d.ts +1 -0
  188. package/dist/supervisor/worker-event-ingestor.d.ts.map +1 -1
  189. package/dist/supervisor/worker-start-payload-builder.d.ts.map +1 -1
  190. package/dist/supervisor/worker-supervisor.d.ts +2 -0
  191. package/dist/supervisor/worker-supervisor.d.ts.map +1 -1
  192. package/dist/test-helpers/prepared-fixture-start.d.ts.map +1 -1
  193. package/dist/test-helpers/process-model-fixtures.d.ts +1 -0
  194. package/dist/test-helpers/process-model-fixtures.d.ts.map +1 -1
  195. package/dist/test-helpers/scoped-settings-fixtures.d.ts +16 -0
  196. package/dist/test-helpers/scoped-settings-fixtures.d.ts.map +1 -0
  197. package/dist/test-helpers/skill-fixtures.d.ts +4 -0
  198. package/dist/test-helpers/skill-fixtures.d.ts.map +1 -0
  199. package/dist/testing.js +2 -1
  200. package/dist/testing.js.map +1 -1
  201. package/dist/tool-approval-gate.d.ts +3 -0
  202. package/dist/tool-approval-gate.d.ts.map +1 -1
  203. package/dist/turn-progress.d.ts.map +1 -1
  204. package/dist/turn-wait-service.d.ts +28 -0
  205. package/dist/turn-wait-service.d.ts.map +1 -0
  206. package/dist/worker-runtime-profile-selection.d.ts +2 -0
  207. package/dist/worker-runtime-profile-selection.d.ts.map +1 -1
  208. package/package.json +20 -19
  209. package/src/app.ts +177 -25
  210. package/src/auth/fastify-auth.ts +13 -0
  211. package/src/config/config-loader.ts +42 -2
  212. package/src/config/config-types.ts +16 -1
  213. package/src/config/kubernetes-docker-isolation.ts +21 -0
  214. package/src/dashboard-model-issues.ts +199 -0
  215. package/src/db/database.ts +131 -40
  216. package/src/db/execution-inspection-repo.ts +163 -0
  217. package/src/db/history-window.ts +18 -0
  218. package/src/db/process-event-repo.ts +88 -10
  219. package/src/db/process-instance-repo.ts +33 -2
  220. package/src/db/process-leaf-outcome-snapshot-repo.ts +8 -2
  221. package/src/db/process-project-repo.ts +4 -0
  222. package/src/db/process-skill-repo.ts +9 -2
  223. package/src/db/process-turn-annotation-repo.ts +27 -9
  224. package/src/db/process-turn-record-repo.ts +45 -12
  225. package/src/db/publication-repo.ts +63 -0
  226. package/src/db/repositories.ts +17 -0
  227. package/src/db/schema.ts +103 -1
  228. package/src/db/scoped-settings-repo.ts +234 -0
  229. package/src/db/skill-repo.ts +89 -27
  230. package/src/db/turn-start-record-repo.ts +13 -3
  231. package/src/db/turn-summary-repo.ts +36 -4
  232. package/src/db/worker-lease-repo.ts +8 -2
  233. package/src/domain-logic/outcome-tools.ts +18 -216
  234. package/src/domain-logic/worker-lease-lifecycle.ts +2 -1
  235. package/src/external-source-service.ts +33 -7
  236. package/src/future-execution/execution.ts +9 -2
  237. package/src/future-execution/launch-lifecycle.ts +87 -78
  238. package/src/future-execution/lifecycle.ts +5 -34
  239. package/src/future-execution/model-projection.ts +2 -0
  240. package/src/future-execution/reconciliation.ts +7 -0
  241. package/src/future-execution-presenter.ts +7 -8
  242. package/src/integration-tool-registry.ts +59 -26
  243. package/src/launch-coordinator.ts +10 -1
  244. package/src/launcher-model-config-service.ts +24 -3
  245. package/src/leaf-outcome-snapshot-capture.ts +2 -0
  246. package/src/primary-path-snapshot.ts +3 -4
  247. package/src/process-action-presenter.ts +22 -57
  248. package/src/process-action-registry.ts +31 -39
  249. package/src/process-engine/decision.ts +10 -0
  250. package/src/process-engine/engine.ts +25 -2
  251. package/src/process-engine/mapped-turns.ts +5 -7
  252. package/src/process-engine/ops/automatic-retry-startup.ts +93 -0
  253. package/src/process-engine/ops/continue-failed-turn.ts +2 -13
  254. package/src/process-engine/ops/process-observation.ts +119 -0
  255. package/src/process-engine/ops/retry-failed-turn.ts +2 -12
  256. package/src/process-engine/ops/retry-startup.ts +20 -16
  257. package/src/process-engine/ops/start-process.ts +34 -2
  258. package/src/process-engine/ops/turn-outcome.ts +61 -60
  259. package/src/process-engine/ops/turn-wait.ts +225 -0
  260. package/src/process-engine/ops/update-model-config.ts +66 -0
  261. package/src/process-engine/recorder.ts +34 -5
  262. package/src/process-engine/turn-start-preflight.ts +168 -105
  263. package/src/process-engine/turn-wait-state.ts +126 -0
  264. package/src/process-engine/turn-worker-requirement.ts +4 -0
  265. package/src/process-engine/types.ts +21 -0
  266. package/src/process-engine/writes/build-process-abort-writes.ts +30 -20
  267. package/src/process-engine/writes/build-turn-outcome-writes.ts +39 -2
  268. package/src/process-engine/writes/commit-writes.ts +16 -4
  269. package/src/process-engine/writes/writes.ts +59 -74
  270. package/src/process-graph.ts +0 -1
  271. package/src/process-inspection-reader.ts +305 -0
  272. package/src/process-inspection-trace.ts +176 -0
  273. package/src/process-inspection.ts +169 -0
  274. package/src/process-instance-tree-presenter.ts +56 -216
  275. package/src/process-launch-executor.ts +5 -2
  276. package/src/process-launch-plan.ts +17 -2
  277. package/src/process-launcher-registry.ts +28 -16
  278. package/src/process-model-availability-recovery.ts +6 -4
  279. package/src/process-model-config.ts +100 -0
  280. package/src/process-model-policy/construct.ts +1 -0
  281. package/src/process-model-policy/evaluate.ts +34 -32
  282. package/src/process-model-policy/index.ts +45 -3
  283. package/src/process-model-policy/project.ts +62 -76
  284. package/src/process-model-policy/types.ts +26 -0
  285. package/src/process-model-policy-presenter.ts +7 -3
  286. package/src/process-runtime-availability.ts +9 -4
  287. package/src/process-turn-trace.ts +12 -24
  288. package/src/process-ui-snapshot-presenter.ts +210 -295
  289. package/src/routes/dashboard.ts +106 -0
  290. package/src/routes/future-executions.ts +5 -5
  291. package/src/routes/launchers.ts +51 -1
  292. package/src/routes/process-actions.ts +10 -10
  293. package/src/routes/process-detail.ts +25 -2
  294. package/src/routes/process-model-config.ts +70 -0
  295. package/src/routes/process-route-helpers.ts +153 -162
  296. package/src/routes/processes.ts +2 -0
  297. package/src/routes/settings.ts +173 -0
  298. package/src/routes/ticket-creation.ts +28 -5
  299. package/src/scoped-settings-service.ts +797 -0
  300. package/src/server-bootstrap/build-host-capabilities.ts +42 -0
  301. package/src/server-bootstrap/register-http.ts +12 -1
  302. package/src/session-summary-projection.ts +1 -2
  303. package/src/skills/bundled-skills.ts +64 -0
  304. package/src/skills/catalog-service.ts +35 -6
  305. package/src/skills/extension-importer.ts +94 -0
  306. package/src/skills/launch-skills.ts +19 -0
  307. package/src/skills/skill-frontmatter.ts +19 -6
  308. package/src/skills/source-importer.ts +7 -13
  309. package/src/startup-evidence.ts +29 -8
  310. package/src/startup-retry-policy.ts +106 -0
  311. package/src/supervisor/execution-inspection-ingestor.ts +55 -0
  312. package/src/supervisor/ipc-handler.ts +2 -0
  313. package/src/supervisor/worker-event-ingestor.ts +30 -14
  314. package/src/supervisor/worker-start-payload-builder.ts +17 -0
  315. package/src/supervisor/worker-supervisor.ts +26 -1
  316. package/src/test-helpers/prepared-fixture-start.ts +1 -0
  317. package/src/test-helpers/process-model-fixtures.ts +2 -0
  318. package/src/test-helpers/scoped-settings-fixtures.ts +126 -0
  319. package/src/test-helpers/skill-fixtures.ts +28 -0
  320. package/src/tool-approval-gate.ts +16 -0
  321. package/src/turn-progress.ts +3 -2
  322. package/src/turn-wait-service.ts +228 -0
  323. package/src/worker-runtime-profile-selection.ts +8 -1
  324. package/dist/app-MSJXFK33.js +0 -8
  325. package/dist/chunk-HK6BLLHA.js.map +0 -1
  326. package/dist/chunk-QCHS3X33.js.map +0 -1
  327. /package/dist/{app-MSJXFK33.js.map → app-KR3N2JAE.js.map} +0 -0
@@ -14,8 +14,10 @@ import {
14
14
  type ProvidedCapability,
15
15
  type RegisteredProcessWatcherLike,
16
16
  } from "@leitwerk-dev/process-sdk";
17
+ import { createWikiIntegration, topicWikiCapability } from "@leitwerk-dev/wiki/integration";
17
18
  import type { LeitwerkConfig } from "../config/index.js";
18
19
  import type { RepositoryBundle } from "../db/repositories.js";
20
+ import type { IntegrationToolRegistry } from "../integration-tool-registry.js";
19
21
  import type { LaunchCoordinator } from "../launch-coordinator.js";
20
22
  import type { ProcessEngine } from "../process-engine/types.js";
21
23
  import type { ProjectMutationService } from "../project-mutation-service.js";
@@ -28,6 +30,7 @@ export function buildHostCapabilities(input: {
28
30
  baseDeps: RepositoryBundle & { broadcaster: Broadcaster };
29
31
  projectMutations: ProjectMutationService;
30
32
  commands: ProcessEngine;
33
+ integrationTools: IntegrationToolRegistry;
31
34
  getSupervisor: () => WorkerSupervisor | undefined;
32
35
  listVisibleActionsForProcess: (instanceId: string) => readonly ProcessActionSummaryLike[];
33
36
  launcherService: unknown;
@@ -45,9 +48,47 @@ export function buildHostCapabilities(input: {
45
48
  preProvidedCapabilities?: readonly ProvidedCapability[];
46
49
  }) {
47
50
  const hostCapabilities = createCapabilityAccessor([
51
+ { token: topicWikiCapability, value: createWikiIntegration(input.baseDeps.topicWiki) },
48
52
  {
49
53
  token: coreHostCapabilities.serverSetup,
50
54
  value: {
55
+ async callIntegrationTool(
56
+ expected: import("@leitwerk-dev/domain").ProcessInstance,
57
+ projectKey: string,
58
+ name: string,
59
+ args: Record<string, unknown>,
60
+ signal: AbortSignal,
61
+ ) {
62
+ const process = input.baseDeps.processes.getById(expected.id);
63
+ if (
64
+ !process ||
65
+ process.lifecycleStatus !== expected.lifecycleStatus ||
66
+ process.selectedTurnId !== expected.selectedTurnId ||
67
+ process.paramsJson !== expected.paramsJson ||
68
+ process.stateJson !== expected.stateJson ||
69
+ process.planRevision !== expected.planRevision
70
+ )
71
+ throw new Error("Process changed before maintenance delivery");
72
+ const projects = input.baseDeps.projects.listByInstance(process.id);
73
+ const project = projects.find((candidate) => candidate.key === projectKey);
74
+ const turn = input.baseDeps.turnRecords.listByInstance(process.id).at(-1);
75
+ if (!project || !turn)
76
+ throw new Error(
77
+ "Maintenance delivery requires a bound project and publication history",
78
+ );
79
+ return input.integrationTools.executeServer(
80
+ name,
81
+ { ...args, projectKey },
82
+ {
83
+ process,
84
+ projects,
85
+ project,
86
+ turn,
87
+ idempotencyKey: `maintenance:${process.id}:${projectKey}:${name}`,
88
+ },
89
+ signal,
90
+ );
91
+ },
51
92
  get serverBaseUrl() {
52
93
  return input.config.server.base_url;
53
94
  },
@@ -56,6 +97,7 @@ export function buildHostCapabilities(input: {
56
97
  },
57
98
  components: input.config.components,
58
99
  externalWrites: input.baseDeps.externalWrites,
100
+ publications: input.baseDeps.publications,
59
101
  processes: input.baseDeps.processes,
60
102
  projects: input.projectMutations,
61
103
  events: input.baseDeps.events,
@@ -1,16 +1,19 @@
1
+ import { registerTopicWikiRoutes } from "@leitwerk-dev/wiki/server";
1
2
  import type { FastifyInstance } from "fastify";
2
3
  import { registerApiTokenAudit } from "../auth/api-token-audit.js";
3
4
  import type { AuthService } from "../auth/auth-service.js";
4
- import { requireApiActor } from "../auth/fastify-auth.js";
5
+ import { actorForRequest, requireApiActor } from "../auth/fastify-auth.js";
5
6
  import { registerAuthRoutes } from "../auth/routes.js";
6
7
  import type { ExtensionUiCatalog } from "../extension-ui/catalog.js";
7
8
  import type { IntegrationToolRegistry } from "../integration-tool-registry.js";
8
9
  import type { ProcessSessionSnapshotStore } from "../process-session-store.js";
9
10
  import type { ResultImageStore } from "../result-image-store.js";
11
+ import { registerDashboardRoutes } from "../routes/dashboard.js";
10
12
  import { registerInternalSessionTransferExportRoutes } from "../routes/internal-session-transfer-exports.js";
11
13
  import { registerInternalWorkerSessionSnapshotRoutes } from "../routes/internal-worker-session-snapshot.js";
12
14
  import { type RouteDeps, registerProcessRoutes } from "../routes/processes.js";
13
15
  import { registerResultImageRoutes } from "../routes/result-images.js";
16
+ import { registerSettingsRoutes } from "../routes/settings.js";
14
17
  import { registerSkillRoutes } from "../routes/skills.js";
15
18
  import { registerTicketCreationRoutes } from "../routes/ticket-creation.js";
16
19
  import { registerUiRendererRoutes } from "../routes/ui-renderers.js";
@@ -74,6 +77,14 @@ export function registerHttp(input: {
74
77
  store: input.resultImages,
75
78
  });
76
79
  registerProcessRoutes(input.app, input.deps);
80
+ registerDashboardRoutes(input.app, {
81
+ ...input.deps,
82
+ processWatchers: input.processWatcherService,
83
+ });
84
+ if (input.deps.topicWiki)
85
+ registerTopicWikiRoutes(input.app, input.deps.topicWiki, actorForRequest);
86
+ if (input.deps.scopedSettingsService)
87
+ registerSettingsRoutes(input.app, input.deps.scopedSettingsService, input.deps);
77
88
  registerWatcherRoutes(input.app, { processWatchers: input.processWatcherService });
78
89
  registerTicketCreationRoutes(input.app, input.deps, input.integrationTools);
79
90
  if (input.deps.skillCatalog) {
@@ -90,8 +90,7 @@ export function createProjectedSessionSnapshotStore(
90
90
  },
91
91
  backfill(instanceId: string) {
92
92
  return serial(instanceId, async () => {
93
- for (const turn of repos.turnRecords.listByInstance(instanceId)) {
94
- if (repos.turnSummaries.get(turn.id)) continue;
93
+ for (const turn of repos.turnRecords.listMissingSummaries(instanceId)) {
95
94
  let summary = emptyCompactTurnSummary();
96
95
  for (const event of repos.events.listByTurnRecord(instanceId, turn.id)) {
97
96
  summary = applyEventToCompactTurnSummary(summary, {
@@ -0,0 +1,64 @@
1
+ import path from "node:path";
2
+ import type { CatalogPiContribution } from "@leitwerk-dev/extension-runtime";
3
+ import type { InstalledSkillCatalogDetail } from "@leitwerk-dev/protocol";
4
+ import { createCanonicalPiResourceBundle } from "@leitwerk-dev/worker-protocol";
5
+ import { ResourceCollector } from "../pi-resources/resource-collector.js";
6
+ import { isSkillModelInvocable, skillMetadata } from "./skill-frontmatter.js";
7
+ import { SAFE_SKILL_ID_PATTERN } from "./skill-id.js";
8
+
9
+ /** Read the same declared skill directories used by worker snapshots. @internal */
10
+ export async function importBundledSkills(
11
+ contributions: readonly CatalogPiContribution[],
12
+ ): Promise<InstalledSkillCatalogDetail[]> {
13
+ const skills = new Map<string, InstalledSkillCatalogDetail>();
14
+ const collector = new ResourceCollector();
15
+ for (const contribution of contributions) {
16
+ for (const directory of contribution.resources.skillDirectories) {
17
+ await collector.addDirectory(directory, "skills", {
18
+ kind: "skill",
19
+ ownerExtensionId: contribution.ownerExtensionId,
20
+ packageName: contribution.packageName,
21
+ });
22
+ }
23
+ }
24
+ const files = collector.toResourceFiles();
25
+ for (const file of files) {
26
+ if (!file.path.endsWith("/SKILL.md")) continue;
27
+ const skillRoot = path.posix.dirname(file.path);
28
+ const skillId = path.posix.basename(skillRoot);
29
+ if (!SAFE_SKILL_ID_PATTERN.test(skillId)) {
30
+ throw new Error(`Bundled skill has an invalid id '${skillId}' at '${file.path}'`);
31
+ }
32
+ if (skills.has(skillId)) throw new Error(`Duplicate bundled skill id '${skillId}'`);
33
+ const skillMarkdown = Buffer.from(file.content).toString("utf8");
34
+ const metadata = skillMetadata(skillMarkdown);
35
+ const sourceExtensionId = collector.provenance.find(
36
+ (source) => source.snapshotPath === file.path,
37
+ )?.ownerExtensionId;
38
+ const bundle = createCanonicalPiResourceBundle(
39
+ files.filter((candidate) => candidate.path.startsWith(`${skillRoot}/`)),
40
+ );
41
+ skills.set(skillId, {
42
+ id: skillId,
43
+ label: metadata.name ?? skillId,
44
+ description: metadata.description,
45
+ registrationKind: "bundled",
46
+ ...(sourceExtensionId ? { sourceExtensionId } : {}),
47
+ activeRevisionId: bundle.digest,
48
+ activeSourceRevision: null,
49
+ sourceRepositoryId: null,
50
+ updateAvailable: false,
51
+ modelInvocable: isSkillModelInvocable(skillMarkdown),
52
+ usage: {
53
+ attachedAllTime: 0,
54
+ attachedLast30Days: 0,
55
+ invokedAllTime: 0,
56
+ invokedLast30Days: 0,
57
+ },
58
+ skillMarkdown,
59
+ processes: [],
60
+ revisions: [],
61
+ });
62
+ }
63
+ return [...skills.values()];
64
+ }
@@ -27,9 +27,16 @@ export interface SkillCatalogService {
27
27
  export function createSkillCatalogService(input: {
28
28
  repositories: readonly SkillRepositoryConfig[];
29
29
  repos: RepositoryBundle;
30
+ bundledSkills?: readonly InstalledSkillCatalogDetail[];
30
31
  importRepository?: typeof importSkillRepository;
31
32
  }): SkillCatalogService {
32
33
  const importRepository = input.importRepository ?? importSkillRepository;
34
+ const bundledSkills = new Map((input.bundledSkills ?? []).map((skill) => [skill.id, skill]));
35
+ for (const skill of input.repos.skills.listAvailable()) {
36
+ if (bundledSkills.has(skill.id)) {
37
+ throw new Error(`Bundled skill '${skill.id}' conflicts with an installed skill`);
38
+ }
39
+ }
33
40
  const statuses = new Map<string, { lastRefreshedAt: string | null; error: string | null }>();
34
41
  let refreshPromise: Promise<SkillsCatalogResponseBody> | null = null;
35
42
  input.repos.transaction((repos) =>
@@ -52,10 +59,25 @@ export function createSkillCatalogService(input: {
52
59
  };
53
60
  });
54
61
 
55
- const list = (): SkillsCatalogResponseBody => ({
56
- repositories: summaries(),
57
- ...input.repos.skills.catalog(),
58
- });
62
+ const list = (): SkillsCatalogResponseBody => {
63
+ const catalog = input.repos.skills.catalog();
64
+ return {
65
+ repositories: summaries(),
66
+ availableSkills: catalog.availableSkills.map((skill) =>
67
+ bundledSkills.has(skill.id)
68
+ ? { ...skill, conflict: !skill.stale, registered: false, updateAvailable: false }
69
+ : skill,
70
+ ),
71
+ installedSkills: [
72
+ ...catalog.installedSkills,
73
+ ...[...bundledSkills.values()].map(
74
+ ({ skillMarkdown, processes, revisions, ...skill }) => skill,
75
+ ),
76
+ ].sort(
77
+ (left, right) => left.label.localeCompare(right.label) || left.id.localeCompare(right.id),
78
+ ),
79
+ };
80
+ };
59
81
 
60
82
  const refresh = (): Promise<SkillsCatalogResponseBody> => {
61
83
  if (refreshPromise) return refreshPromise;
@@ -88,17 +110,24 @@ export function createSkillCatalogService(input: {
88
110
  list,
89
111
  refresh,
90
112
  detail(repositoryId, skillId) {
91
- return input.repos.skills.getCatalogDetail(repositoryId, skillId);
113
+ const detail = input.repos.skills.getCatalogDetail(repositoryId, skillId);
114
+ return detail && bundledSkills.has(skillId)
115
+ ? { ...detail, conflict: !detail.stale, registered: false, updateAvailable: false }
116
+ : detail;
92
117
  },
93
118
  installedDetail(skillId) {
94
- return input.repos.skills.getInstalledDetail(skillId);
119
+ return bundledSkills.get(skillId) ?? input.repos.skills.getInstalledDetail(skillId);
95
120
  },
96
121
  register(repositoryId, skillId) {
122
+ if (bundledSkills.has(skillId)) {
123
+ throw new Error(`Skill '${skillId}' has a conflicting bundled extension skill`);
124
+ }
97
125
  return input.repos.transaction((repos) =>
98
126
  repos.skills.registerCatalogEntry(repositoryId, skillId),
99
127
  );
100
128
  },
101
129
  remove(skillId) {
130
+ if (bundledSkills.has(skillId)) return false;
102
131
  return input.repos.transaction((repos) => repos.skills.remove(skillId));
103
132
  },
104
133
  };
@@ -0,0 +1,94 @@
1
+ import { lstat, readFile, realpath } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import type { LoadedExtensionModule } from "@leitwerk-dev/extension-runtime";
4
+ import { parseSkillPackManifest, type SkillRevisionProvenance } from "@leitwerk-dev/protocol";
5
+ import { createCanonicalPiResourceBundle } from "@leitwerk-dev/worker-protocol";
6
+ import { ResourceCollector } from "../pi-resources/resource-collector.js";
7
+ import { skillFrontmatter } from "./skill-frontmatter.js";
8
+ import type { ImportedSkill } from "./source-importer.js";
9
+
10
+ /** @internal */
11
+ export interface ImportedExtensionSkill extends ImportedSkill {
12
+ /** @internal */
13
+ provenance: SkillRevisionProvenance;
14
+ }
15
+
16
+ async function packagePath(packageRoot: string, target: string): Promise<string> {
17
+ const relative = path.relative(packageRoot, target);
18
+ if (
19
+ !relative ||
20
+ relative === ".." ||
21
+ relative.startsWith(`..${path.sep}`) ||
22
+ path.isAbsolute(relative)
23
+ ) {
24
+ throw new Error(`Skill-pack path escapes package: ${target}`);
25
+ }
26
+ let current = packageRoot;
27
+ for (const part of relative.split(path.sep)) {
28
+ current = path.join(current, part);
29
+ if ((await lstat(current)).isSymbolicLink())
30
+ throw new Error(`Skill-pack symlink is forbidden: ${current}`);
31
+ }
32
+ return current;
33
+ }
34
+
35
+ /** Import only declared packages; no network or patch execution at runtime. @internal */
36
+ export async function importExtensionSkills(
37
+ modules: readonly LoadedExtensionModule[],
38
+ ): Promise<ImportedExtensionSkill[]> {
39
+ const imported: ImportedExtensionSkill[] = [];
40
+ for (const loaded of modules) {
41
+ if (!loaded.skillPackPath) continue;
42
+ const packageRoot = await realpath(loaded.packageDir);
43
+ const manifestPath = await packagePath(
44
+ packageRoot,
45
+ path.resolve(packageRoot, path.relative(loaded.packageDir, loaded.skillPackPath)),
46
+ );
47
+ const manifest = parseSkillPackManifest(JSON.parse(await readFile(manifestPath, "utf8")));
48
+ for (const skill of manifest.skills) {
49
+ const directory = await packagePath(
50
+ packageRoot,
51
+ path.resolve(path.dirname(manifestPath), skill.directory),
52
+ );
53
+ const provenance: SkillRevisionProvenance = {
54
+ extensionId: loaded.module.manifest.id,
55
+ packageName: loaded.packageName,
56
+ packageVersion: loaded.packageVersion ?? loaded.module.manifest.version,
57
+ upstream: manifest.upstream,
58
+ sourcePath: skill.sourcePath,
59
+ patchDigest: manifest.patchDigest,
60
+ dependencies: skill.dependencies,
61
+ };
62
+ const collector = new ResourceCollector();
63
+ await collector.addDirectory(
64
+ directory,
65
+ `skills/${skill.id}`,
66
+ {
67
+ kind: "skill",
68
+ ownerExtensionId: provenance.extensionId,
69
+ packageName: provenance.packageName,
70
+ },
71
+ { forbiddenNames: new Set([".git", ".leitwerk-skill.json"]) },
72
+ );
73
+ const markdown = collector.files.get(`skills/${skill.id}/SKILL.md`);
74
+ const metadata = markdown ? skillFrontmatter(Buffer.from(markdown).toString("utf8")) : null;
75
+ if (metadata?.name !== skill.id || metadata?.description !== skill.description) {
76
+ throw new Error(`Skill '${skill.id}' frontmatter does not match its pack manifest`);
77
+ }
78
+ // Include dependency/provenance changes in revision identity even when prose is unchanged.
79
+ collector.addBytes(
80
+ `skills/${skill.id}/.leitwerk-skill.json`,
81
+ Buffer.from(JSON.stringify(provenance)),
82
+ );
83
+ imported.push({
84
+ skillId: skill.id,
85
+ label: skill.label,
86
+ description: skill.description,
87
+ sourceRevision: manifest.upstream.commit,
88
+ provenance,
89
+ bundle: createCanonicalPiResourceBundle(collector.toResourceFiles()),
90
+ });
91
+ }
92
+ }
93
+ return imported;
94
+ }
@@ -0,0 +1,19 @@
1
+ import type { SkillSelection } from "@leitwerk-dev/protocol";
2
+ import type { LeitwerkConfig } from "../config/config-types.js";
3
+ import type { RepositoryBundle } from "../db/repositories.js";
4
+
5
+ /** Server-owned defaults, resolved only when selecting skills for a new launch. @internal */
6
+ export type LaunchSkillDefaults = Pick<LeitwerkConfig, "default_skills" | "process_configs">;
7
+
8
+ /** @internal */
9
+ export function resolveLaunchSkills(
10
+ deps: { skills: RepositoryBundle["skills"]; skillDefaults?: LaunchSkillDefaults },
11
+ processId: string,
12
+ selectedSkillIds: readonly string[] = [],
13
+ ): SkillSelection[] {
14
+ const defaults =
15
+ deps.skillDefaults?.process_configs?.[processId]?.default_skills ??
16
+ deps.skillDefaults?.default_skills ??
17
+ [];
18
+ return deps.skills.resolveActive([...new Set([...defaults, ...selectedSkillIds])]);
19
+ }
@@ -1,11 +1,11 @@
1
1
  import { parse as parseYaml } from "yaml";
2
2
 
3
- function frontmatter(markdown: string): Record<string, unknown> | null {
4
- if (!markdown.startsWith("---")) return null;
5
- const end = markdown.indexOf("\n---", 3);
6
- if (end < 0) return null;
3
+ /** @internal */
4
+ export function skillFrontmatter(markdown: string): Record<string, unknown> | null {
5
+ const header = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown);
6
+ if (!header) return null;
7
7
  try {
8
- const parsed = parseYaml(markdown.slice(3, end));
8
+ const parsed = parseYaml(header[1]);
9
9
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
10
10
  } catch {
11
11
  return null;
@@ -13,5 +13,18 @@ function frontmatter(markdown: string): Record<string, unknown> | null {
13
13
  }
14
14
 
15
15
  export function isSkillModelInvocable(markdown: string): boolean {
16
- return frontmatter(markdown)?.["disable-model-invocation"] !== true;
16
+ return skillFrontmatter(markdown)?.["disable-model-invocation"] !== true;
17
+ }
18
+
19
+ /** @internal */
20
+ export function skillMetadata(markdown: string): {
21
+ name: string | null;
22
+ description: string | null;
23
+ } {
24
+ const metadata = skillFrontmatter(markdown);
25
+ const text = (key: string): string | null => {
26
+ const value = metadata?.[key];
27
+ return typeof value === "string" ? value.trim() || null : null;
28
+ };
29
+ return { name: text("name"), description: text("description") };
17
30
  }
@@ -3,12 +3,14 @@ import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import path from "node:path";
5
5
  import { promisify } from "node:util";
6
+ import type { SkillRevisionProvenance } from "@leitwerk-dev/protocol";
6
7
  import {
7
8
  createCanonicalPiResourceBundle,
8
9
  type PiResourceBundle,
9
10
  } from "@leitwerk-dev/worker-protocol";
10
11
  import type { SkillRepositoryConfig } from "../config/config-types.js";
11
12
  import { ResourceCollector, SKILL_RESOURCE_OWNER } from "../pi-resources/resource-collector.js";
13
+ import { skillMetadata } from "./skill-frontmatter.js";
12
14
  import { SAFE_SKILL_ID_PATTERN } from "./skill-id.js";
13
15
 
14
16
  const execFileAsync = promisify(execFile);
@@ -17,6 +19,8 @@ const FORBIDDEN_SKILL_NAMES = new Set([".git"]);
17
19
 
18
20
  /** @internal */
19
21
  export interface ImportedSkill {
22
+ /** Explicit extension provenance and dependencies. @internal */
23
+ provenance?: SkillRevisionProvenance;
20
24
  /** @internal */
21
25
  skillId: string;
22
26
  /** @internal */
@@ -78,16 +82,6 @@ async function checkoutGitSource(
78
82
  return { root, commit: stdout.trim() };
79
83
  }
80
84
 
81
- function metadataValue(markdown: string, key: string): string | null {
82
- if (!markdown.startsWith("---")) return null;
83
- const end = markdown.indexOf("\n---", 3);
84
- if (end < 0) return null;
85
- const match = markdown
86
- .slice(3, end)
87
- .match(new RegExp(`^${key}:\\s*["']?([^\\n"']+)["']?\\s*$`, "m"));
88
- return match?.[1]?.trim() || null;
89
- }
90
-
91
85
  function fallbackLabel(id: string): string {
92
86
  return id
93
87
  .split(/[-_.]+/)
@@ -149,13 +143,13 @@ export async function importSkillRepository(
149
143
  const skills: ImportedRepositorySkill[] = [];
150
144
  for (const skillRoot of skillRoots) {
151
145
  const skillId = path.basename(skillRoot);
152
- const markdown = await readFile(path.join(skillRoot, "SKILL.md"), "utf8");
146
+ const metadata = skillMetadata(await readFile(path.join(skillRoot, "SKILL.md"), "utf8"));
153
147
  const imported = await importSkillDirectory(
154
148
  skillRoot,
155
149
  {
156
150
  id: skillId,
157
- label: metadataValue(markdown, "name") ?? fallbackLabel(skillId),
158
- description: metadataValue(markdown, "description") ?? undefined,
151
+ label: metadata.name ?? fallbackLabel(skillId),
152
+ description: metadata.description ?? undefined,
159
153
  },
160
154
  checkout.commit,
161
155
  );
@@ -13,6 +13,8 @@ import type {
13
13
  StartupRecoverySummary,
14
14
  } from "@leitwerk-dev/protocol";
15
15
  import { completeLaunchWhenReady, failLaunchRun } from "./launch-pipeline.js";
16
+ import { pendingTurnWait } from "./process-engine/turn-wait-state.js";
17
+ import { automaticStartupRecovery, startupRetryState } from "./startup-retry-policy.js";
16
18
 
17
19
  export interface StartupEvidenceInput {
18
20
  process: ProcessInstance;
@@ -23,6 +25,7 @@ export interface StartupEvidenceInput {
23
25
  }
24
26
 
25
27
  export interface StartupEvidence {
28
+ readiness?: { message: string | null };
26
29
  attempts: readonly StartupAttemptSummary[];
27
30
  currentAttempt: StartupAttemptSummary | null;
28
31
  authoritativeAttemptId: string | null;
@@ -49,16 +52,12 @@ function validObservedAt(value: string | null | undefined, notBefore: string): s
49
52
 
50
53
  export function buildStartupRecovery(
51
54
  process: ProcessInstance,
52
- turnStartsById:
53
- | ReadonlyMap<string, TurnStartRecord>
54
- | { getById(id: string): TurnStartRecord | null },
55
+ turnStartsById: ReadonlyMap<string, TurnStartRecord>,
56
+ events: readonly ProcessEvent[] = [],
55
57
  ): StartupRecoverySummary | null {
56
58
  if (process.lifecycleStatus !== "error" || process.currentExecution?.kind !== "worker_start")
57
59
  return null;
58
- const start =
59
- "getById" in turnStartsById
60
- ? turnStartsById.getById(process.currentExecution.id)
61
- : turnStartsById.get(process.currentExecution.id);
60
+ const start = turnStartsById.get(process.currentExecution.id);
62
61
  if (
63
62
  !start ||
64
63
  (start.state.kind !== "preparation_failed" && start.state.kind !== "bootstrap_failed")
@@ -66,6 +65,10 @@ export function buildStartupRecovery(
66
65
  return null;
67
66
  const resolvedStart = "start" in start.state ? start.state.start : null;
68
67
  return {
68
+ automaticRetry: automaticStartupRecovery(
69
+ start,
70
+ startupRetryState(start, [...turnStartsById.values()], events),
71
+ ),
69
72
  startRecordId: start.id,
70
73
  kind: start.state.kind,
71
74
  action: start.state.kind === "bootstrap_failed" ? "retry_startup" : "choose_model",
@@ -259,9 +262,12 @@ export function buildStartupEvidence(input: StartupEvidenceInput): StartupEviden
259
262
  null;
260
263
  return {
261
264
  attempts: recoveredAttempts,
265
+ ...(pendingTurnWait(input.process)?.initialSelection
266
+ ? { readiness: { message: pendingTurnWait(input.process)?.message ?? null } }
267
+ : {}),
262
268
  currentAttempt,
263
269
  authoritativeAttemptId: authoritative?.startRecordId ?? null,
264
- recovery: buildStartupRecovery(input.process, turnStartsById),
270
+ recovery: buildStartupRecovery(input.process, turnStartsById, input.events),
265
271
  };
266
272
  }
267
273
 
@@ -343,6 +349,21 @@ export function projectLaunchRunStartup(
343
349
  }),
344
350
  };
345
351
  const failedStep = attempt?.steps.find((step) => step.status === "failed");
352
+ if (!attempt && evidence.readiness) {
353
+ next = {
354
+ ...next,
355
+ steps: next.steps.map((step) =>
356
+ step.id === "start_worker"
357
+ ? {
358
+ ...step,
359
+ status: "pending",
360
+ label: "Waiting for startup prerequisites",
361
+ safeSummary: evidence.readiness?.message ?? "Checking startup prerequisites…",
362
+ }
363
+ : step,
364
+ ),
365
+ };
366
+ }
346
367
  if (failedStep) {
347
368
  next = failLaunchRun(
348
369
  next,
@@ -0,0 +1,106 @@
1
+ import type {
2
+ AutomaticStartupRecoverySummary,
3
+ ProcessEvent,
4
+ StartupRetryState,
5
+ TurnStartRecord,
6
+ } from "@leitwerk-dev/domain";
7
+
8
+ /** @internal */
9
+ export const MAX_STARTUP_STARTS = 3;
10
+
11
+ /** Read retained history only for starts written before retry metadata existed. @internal */
12
+ export function startupRetryState(
13
+ start: TurnStartRecord,
14
+ starts: readonly TurnStartRecord[],
15
+ events: readonly ProcessEvent[] = [],
16
+ ): StartupRetryState {
17
+ if (start.state.automaticRetry) return start.state.automaticRetry;
18
+ const byId = new Map(starts.map((entry) => [entry.id, entry]));
19
+ const predecessors = new Map(
20
+ events
21
+ .filter((event) => event.eventType === "startup_retry_scheduled")
22
+ .map((event) => [String(event.data.startRecordId), event]),
23
+ );
24
+ let current = start;
25
+ let count = 1;
26
+ const seen = new Set([start.id]);
27
+ while (current.startKind === "startup_retry") {
28
+ const event = predecessors.get(current.id);
29
+ const actor = event?.data.actor as { kind?: string } | undefined;
30
+ if (event?.data.retrySource === "manual" || (actor && actor.kind !== "system")) break;
31
+ const previous = byId.get(String(event?.data.previousStartRecordId));
32
+ if (!previous || seen.has(previous.id) || previous.turnId !== start.turnId) {
33
+ // Missing legacy history must not grant a new allowance after an upgrade.
34
+ count = Math.max(count, MAX_STARTUP_STARTS);
35
+ break;
36
+ }
37
+ seen.add(previous.id);
38
+ count += 1;
39
+ current = previous;
40
+ if (current.state.automaticRetry) {
41
+ return {
42
+ ...current.state.automaticRetry,
43
+ starts: current.state.automaticRetry.starts + count - 1,
44
+ nextRetryAt: null,
45
+ };
46
+ }
47
+ }
48
+ return { episodeStartRecordId: current.id, starts: count, nextRetryAt: null };
49
+ }
50
+
51
+ /** Configuration, unknown errors and OOMs require attention rather than blind retries. @internal */
52
+ export function automaticStartupRecovery(
53
+ start: TurnStartRecord,
54
+ retry: StartupRetryState,
55
+ now = Date.now(),
56
+ modelRestored = false,
57
+ ): AutomaticStartupRecoverySummary {
58
+ const summary = (
59
+ status: AutomaticStartupRecoverySummary["status"],
60
+ reason: string,
61
+ nextRetryAt: string | null = null,
62
+ ): AutomaticStartupRecoverySummary => ({
63
+ starts: retry.starts,
64
+ maxStarts: MAX_STARTUP_STARTS,
65
+ status,
66
+ reason,
67
+ nextRetryAt,
68
+ });
69
+ if (start.state.kind !== "preparation_failed" && start.state.kind !== "bootstrap_failed")
70
+ return summary("blocked", "This start is no longer eligible for automatic recovery.");
71
+ const code = start.state.code;
72
+ const modelFailure = code === "model_unavailable" || code === "model_stale";
73
+ const transient =
74
+ start.state.kind === "bootstrap_failed" &&
75
+ [
76
+ "startup_timeout",
77
+ "spawn_error",
78
+ "worker_spawn_failed",
79
+ "worker_adoption_failed",
80
+ "process_exited",
81
+ ].includes(code);
82
+ if (!modelFailure && !transient)
83
+ return summary("blocked", "Automatic retry stopped. Correct the failure and retry manually.");
84
+ if (retry.starts >= MAX_STARTUP_STARTS)
85
+ return summary(
86
+ "exhausted",
87
+ "Automatic startup retries exhausted. Retry manually after correcting the failure.",
88
+ );
89
+ if (modelFailure)
90
+ return summary(
91
+ modelRestored ? "ready" : "waiting_for_model",
92
+ modelRestored
93
+ ? "Model availability restored."
94
+ : "Waiting for model availability to be restored.",
95
+ );
96
+ const failureAt = Date.parse(start.updatedAt);
97
+ if (!Number.isFinite(failureAt))
98
+ return summary("blocked", "Startup failure timing is unavailable. Retry manually.");
99
+ const nextRetryAt =
100
+ retry.nextRetryAt ?? new Date(failureAt + 30_000 * 2 ** (retry.starts - 1)).toISOString();
101
+ return summary(
102
+ Date.parse(nextRetryAt) > now ? "waiting" : "ready",
103
+ "A transient worker startup failure is eligible for automatic recovery.",
104
+ nextRetryAt,
105
+ );
106
+ }