@leitwerk-dev/server 0.4.0 → 0.4.2

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 (78) hide show
  1. package/dist/{app-CsuxFZT5.d.ts → app-CtlotzYm.d.ts} +51 -1
  2. package/dist/app-KR3N2JAE.js +8 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/{chunk-FPMDWQF7.js → chunk-OUA5EZS2.js} +518 -135
  5. package/dist/chunk-OUA5EZS2.js.map +1 -0
  6. package/dist/{chunk-MBHRCQFE.js → chunk-YLWY4UTT.js} +174 -57
  7. package/dist/chunk-YLWY4UTT.js.map +1 -0
  8. package/dist/config/config-loader.d.ts.map +1 -1
  9. package/dist/config/config-types.d.ts +2 -0
  10. package/dist/config/config-types.d.ts.map +1 -1
  11. package/dist/dashboard-model-issues.d.ts +10 -0
  12. package/dist/dashboard-model-issues.d.ts.map +1 -0
  13. package/dist/db/process-instance-repo.d.ts +17 -0
  14. package/dist/db/process-instance-repo.d.ts.map +1 -1
  15. package/dist/db/turn-start-record-repo.d.ts.map +1 -1
  16. package/dist/db/turn-summary-repo.d.ts +9 -0
  17. package/dist/db/turn-summary-repo.d.ts.map +1 -1
  18. package/dist/domain-logic/outcome-tools.d.ts.map +1 -1
  19. package/dist/domain-logic/worker-lease-lifecycle.d.ts.map +1 -1
  20. package/dist/index.js +2 -2
  21. package/dist/main.js +3 -3
  22. package/dist/process-engine/engine.d.ts.map +1 -1
  23. package/dist/process-engine/ops/automatic-retry-startup.d.ts +8 -0
  24. package/dist/process-engine/ops/automatic-retry-startup.d.ts.map +1 -0
  25. package/dist/process-engine/ops/retry-startup.d.ts +2 -0
  26. package/dist/process-engine/ops/retry-startup.d.ts.map +1 -1
  27. package/dist/process-engine/recorder.d.ts.map +1 -1
  28. package/dist/process-engine/types.d.ts +8 -1
  29. package/dist/process-engine/types.d.ts.map +1 -1
  30. package/dist/process-engine/writes/commit-writes.d.ts.map +1 -1
  31. package/dist/process-model-availability-recovery.d.ts +1 -1
  32. package/dist/process-model-availability-recovery.d.ts.map +1 -1
  33. package/dist/routes/dashboard.d.ts +17 -0
  34. package/dist/routes/dashboard.d.ts.map +1 -0
  35. package/dist/scoped-settings-service.d.ts +15 -0
  36. package/dist/scoped-settings-service.d.ts.map +1 -1
  37. package/dist/server-bootstrap/register-http.d.ts.map +1 -1
  38. package/dist/skills/extension-importer.d.ts.map +1 -1
  39. package/dist/skills/skill-frontmatter.d.ts +2 -0
  40. package/dist/skills/skill-frontmatter.d.ts.map +1 -1
  41. package/dist/skills/source-importer.d.ts.map +1 -1
  42. package/dist/startup-evidence.d.ts +1 -3
  43. package/dist/startup-evidence.d.ts.map +1 -1
  44. package/dist/startup-retry-policy.d.ts +8 -0
  45. package/dist/startup-retry-policy.d.ts.map +1 -0
  46. package/dist/supervisor/worker-supervisor.d.ts.map +1 -1
  47. package/dist/testing.js +1 -1
  48. package/package.json +12 -12
  49. package/src/app.ts +62 -20
  50. package/src/config/config-loader.ts +2 -0
  51. package/src/config/config-types.ts +2 -0
  52. package/src/dashboard-model-issues.ts +199 -0
  53. package/src/db/process-instance-repo.ts +24 -0
  54. package/src/db/turn-start-record-repo.ts +5 -1
  55. package/src/db/turn-summary-repo.ts +25 -2
  56. package/src/domain-logic/outcome-tools.ts +14 -23
  57. package/src/domain-logic/worker-lease-lifecycle.ts +2 -1
  58. package/src/process-engine/engine.ts +14 -0
  59. package/src/process-engine/ops/automatic-retry-startup.ts +93 -0
  60. package/src/process-engine/ops/retry-startup.ts +11 -3
  61. package/src/process-engine/recorder.ts +13 -0
  62. package/src/process-engine/types.ts +12 -0
  63. package/src/process-engine/writes/commit-writes.ts +1 -2
  64. package/src/process-model-availability-recovery.ts +6 -4
  65. package/src/routes/dashboard.ts +106 -0
  66. package/src/routes/process-actions.ts +1 -1
  67. package/src/scoped-settings-service.ts +61 -0
  68. package/src/server-bootstrap/register-http.ts +5 -0
  69. package/src/skills/extension-importer.ts +3 -6
  70. package/src/skills/skill-frontmatter.ts +7 -7
  71. package/src/skills/source-importer.ts +4 -13
  72. package/src/startup-evidence.ts +9 -8
  73. package/src/startup-retry-policy.ts +106 -0
  74. package/src/supervisor/worker-supervisor.ts +23 -1
  75. package/dist/app-JM4CBTND.js +0 -8
  76. package/dist/chunk-FPMDWQF7.js.map +0 -1
  77. package/dist/chunk-MBHRCQFE.js.map +0 -1
  78. /package/dist/{app-JM4CBTND.js.map → app-KR3N2JAE.js.map} +0 -0
package/src/app.ts CHANGED
@@ -259,7 +259,7 @@ async function createConfiguredWorkerRunnerRuntime(input: {
259
259
  webSocketIpc: WorkerWebSocketIpcManager;
260
260
  provided?: AppOptions["workerRunnerRuntime"];
261
261
  helperRelays: ProcessStateExportHelperRelayProvider;
262
- onVolumePoolError: () => void;
262
+ onVolumePoolError: (error?: unknown) => void;
263
263
  onImagePreparationEvent: NonNullable<
264
264
  Parameters<
265
265
  typeof import("@leitwerk-dev/worker-runners/kubernetes").createKubernetesWorkerRunner
@@ -308,6 +308,7 @@ async function createConfiguredWorkerRunnerRuntime(input: {
308
308
  });
309
309
  const created = createKubernetesWorkerRunner({
310
310
  client: kubernetesClient,
311
+ reclaimOnClose: processVolume?.reclaim_on_close === true,
311
312
  preProvision: processVolume?.pre_provision
312
313
  ? { ...processVolume.pre_provision, onError: input.onVolumePoolError }
313
314
  : undefined,
@@ -965,8 +966,11 @@ export async function createAppContext(opts: AppOptions = {}): Promise<AppContex
965
966
  webSocketIpc: workerWebSocketIpc,
966
967
  provided: opts.workerRunnerRuntime,
967
968
  helperRelays: sessionTransferHelperRelays,
968
- onVolumePoolError: () =>
969
- app.log.warn("Volume pre-provisioning failed; retrying in the background"),
969
+ onVolumePoolError: (error) =>
970
+ app.log.warn(
971
+ { err: error },
972
+ "Volume pool degraded; inspect preparation Pods and CSI storage scheduling",
973
+ ),
970
974
  onImagePreparationEvent: (event) => {
971
975
  if (event.outcome === "succeeded") app.log.info(event, "Worker image prepared");
972
976
  else app.log.warn(event, "Worker image preparation failed; retrying in the background");
@@ -1022,30 +1026,67 @@ export async function createAppContext(opts: AppOptions = {}): Promise<AppContex
1022
1026
  let retentionWork: Promise<void> | undefined;
1023
1027
  let retainedVolumeCleanupTimer: NodeJS.Timeout | null = null;
1024
1028
  let retainedVolumeCleanupRunning = false;
1025
- const releasedRetainedVolumes = new Set<string>();
1029
+ const retentionPolicy = {
1030
+ completedProcessRetention: config.workers.cleanup.completed_process_retention,
1031
+ errorProcessRetention: config.workers.cleanup.error_process_retention,
1032
+ };
1033
+ const reclaimTerminalStorage =
1034
+ config.workers.runner === "kubernetes" &&
1035
+ config.kubernetes?.process_volume.reclaim_on_close === true;
1036
+ const volumeRetentionPolicy = reclaimTerminalStorage
1037
+ ? { ...retentionPolicy, completedProcessRetention: "0s", abortedProcessRetention: "0s" }
1038
+ : retentionPolicy;
1039
+ const pendingVolumeReleases = new Set<Promise<void>>();
1040
+ function releaseRetainedVolume(instanceId: string): Promise<void> {
1041
+ const work = processOperations.runExclusive(instanceId, async () => {
1042
+ // Re-read under the lifecycle lock so a resumed process keeps its workspace.
1043
+ const process = baseDeps.processes.getById(instanceId);
1044
+ const lease = baseDeps.leases.getByInstance(instanceId);
1045
+ if (!process || (lease && !lease.exitedAt)) return;
1046
+ await cleanupRetainedProcessVolumes({
1047
+ volume: runnerRuntime.volume,
1048
+ processes: [process],
1049
+ now: new Date(),
1050
+ policy: volumeRetentionPolicy,
1051
+ reclaimTerminalBackingStorage: reclaimTerminalStorage,
1052
+ });
1053
+ });
1054
+ pendingVolumeReleases.add(work);
1055
+ return work.finally(() => pendingVolumeReleases.delete(work));
1056
+ }
1057
+ afterSuccessHooks.add(async (instanceId) => {
1058
+ const process = baseDeps.processes.getById(instanceId);
1059
+ if (
1060
+ !reclaimTerminalStorage ||
1061
+ !process ||
1062
+ !["completed", "aborted"].includes(process.lifecycleStatus)
1063
+ )
1064
+ return;
1065
+ try {
1066
+ await releaseRetainedVolume(instanceId);
1067
+ } catch (err) {
1068
+ app.log.warn({ err, instanceId }, "process PVC release failed; retention sweep will retry");
1069
+ }
1070
+ });
1026
1071
  async function runRetainedVolumeCleanup(): Promise<void> {
1027
1072
  if (retainedVolumeCleanupRunning) return;
1028
1073
  retainedVolumeCleanupRunning = true;
1029
1074
  const processes = baseDeps.processes.listAll();
1030
1075
  const now = new Date();
1031
- const policy = {
1032
- completedProcessRetention: config.workers.cleanup.completed_process_retention,
1033
- errorProcessRetention: config.workers.cleanup.error_process_retention,
1034
- };
1035
1076
  const expiredImageProcesses = new Set(
1036
- planProcessVolumeRetentionCleanup({ processes, now, policy }),
1077
+ planProcessVolumeRetentionCleanup({ processes, now, policy: retentionPolicy }),
1037
1078
  );
1038
- try {
1039
- const released = await cleanupRetainedProcessVolumes({
1040
- volume: runnerRuntime.volume,
1041
- processes,
1042
- now,
1043
- policy,
1044
- alreadyReleased: releasedRetainedVolumes,
1045
- });
1046
- for (const instanceId of released) releasedRetainedVolumes.add(instanceId);
1047
- } catch (error) {
1048
- app.log.warn({ error }, "retained process volume cleanup failed");
1079
+ const expiredVolumes = planProcessVolumeRetentionCleanup({
1080
+ processes,
1081
+ now,
1082
+ policy: volumeRetentionPolicy,
1083
+ });
1084
+ for (const instanceId of expiredVolumes) {
1085
+ try {
1086
+ await releaseRetainedVolume(instanceId);
1087
+ } catch (err) {
1088
+ app.log.warn({ err, instanceId }, "retained process volume cleanup failed");
1089
+ }
1049
1090
  }
1050
1091
  try {
1051
1092
  await resultImages.cleanupProcesses({
@@ -1090,6 +1131,7 @@ export async function createAppContext(opts: AppOptions = {}): Promise<AppContex
1090
1131
  retainedVolumeCleanupTimer = null;
1091
1132
  }
1092
1133
  await retentionWork;
1134
+ await Promise.allSettled([...pendingVolumeReleases]);
1093
1135
  });
1094
1136
 
1095
1137
  if (processTitles?.start) {
@@ -397,6 +397,7 @@ const configSchema = v.looseObject({
397
397
  worker_service_account: v.optional(v.string()),
398
398
  image_preload: v.optional(v.strictObject({ enabled: v.boolean() })),
399
399
  process_volume: v.looseObject({
400
+ reclaim_on_close: v.optional(v.boolean()),
400
401
  storage_class_name: v.optional(v.string()),
401
402
  pre_provision: v.optional(
402
403
  v.strictObject({ count: v.pipe(v.number(), v.integer(), v.minValue(0)) }),
@@ -1116,6 +1117,7 @@ export function getDefaultConfig(): LeitwerkConfig {
1116
1117
  default_worker_runtime_profile: "generic",
1117
1118
  worker_service_account: "leitwerk-worker",
1118
1119
  process_volume: {
1120
+ reclaim_on_close: false,
1119
1121
  size: "20Gi",
1120
1122
  access_modes: ["ReadWriteOnce"],
1121
1123
  mount_path: "/state",
@@ -148,6 +148,8 @@ export interface DockerRunnerConfig {
148
148
 
149
149
  /** @internal */
150
150
  export interface KubernetesProcessVolumeConfig {
151
+ /** Discard terminal workspaces and their backing storage; disabled by default. @internal */
152
+ reclaim_on_close?: boolean;
151
153
  /** Optional ready-volume target; zero stops replenishment. @internal */
152
154
  pre_provision?: {
153
155
  /** @internal */
@@ -0,0 +1,199 @@
1
+ import { parseStrictInstanceTurnConfigsJson, trimToNull } from "@leitwerk-dev/domain";
2
+ import { parseFutureActionPayloadJson, parseFutureLaunchPayloadJson } from "@leitwerk-dev/protocol";
3
+ import type { DashboardConfigurationIssue } from "@leitwerk-dev/protocol/http-contracts";
4
+ import { presentProcessModelPolicyFailure } from "./process-model-policy-presenter.js";
5
+ import type { ProcessWatcherServiceLike } from "./process-watcher-registry.js";
6
+ import type { RouteDeps } from "./routes/process-route-helpers.js";
7
+
8
+ type IssueSource = DashboardConfigurationIssue["sources"][number];
9
+
10
+ /** @internal */
11
+ export type DashboardModelIssueDeps = Pick<
12
+ RouteDeps,
13
+ | "config"
14
+ | "processModelPolicy"
15
+ | "modelStatusCache"
16
+ | "processes"
17
+ | "futureExecutions"
18
+ | "scopedSettingsService"
19
+ | "processGraphs"
20
+ > & { /** @internal */ processWatchers?: ProcessWatcherServiceLike };
21
+
22
+ /** Reads cached availability and model references; never resolves launches or process contexts. @internal */
23
+ export function buildDashboardModelIssues(
24
+ deps: DashboardModelIssueDeps,
25
+ ): DashboardConfigurationIssue[] {
26
+ const issues = new Map<string, DashboardConfigurationIssue>();
27
+ const availability = deps.modelStatusCache.snapshot();
28
+ function add(code: string, key: string, message: string, source: IssueSource) {
29
+ const id = JSON.stringify([code, key]);
30
+ const issue = issues.get(id) ?? {
31
+ id,
32
+ code,
33
+ severity: code === "model_stale" ? ("warning" as const) : ("error" as const),
34
+ message,
35
+ sources: [],
36
+ };
37
+ if (!issue.sources.some((item) => item.label === source.label && item.href === source.href))
38
+ issue.sources.push(source);
39
+ issues.set(id, issue);
40
+ }
41
+ function check(profileId: string | null | undefined, source: IssueSource, processId = "") {
42
+ const id = trimToNull(profileId);
43
+ if (!id) return;
44
+ const result = deps.processModelPolicy.evaluate({
45
+ kind: "runtime_selection",
46
+ processId,
47
+ selection: {
48
+ modelProfileId: id,
49
+ provenance: { kind: "explicit", source: "instance_default" },
50
+ },
51
+ availability,
52
+ });
53
+ if (result.ok) return;
54
+ const key = result.code === "model_profile_not_allowed" ? JSON.stringify([id, processId]) : id;
55
+ const message = presentProcessModelPolicyFailure(result);
56
+ add(
57
+ result.code,
58
+ key,
59
+ result.code === "model_stale" || result.code === "model_unavailable"
60
+ ? `${id}: ${message}`
61
+ : message,
62
+ source,
63
+ );
64
+ }
65
+ function checkPersisted(
66
+ input: {
67
+ processId: string;
68
+ defaultModelProfileId?: string | null;
69
+ turnConfigsJson?: string | null;
70
+ selectedTurnModelProfileId?: string | null;
71
+ },
72
+ source: IssueSource,
73
+ ) {
74
+ check(
75
+ input.defaultModelProfileId,
76
+ { ...source, label: `${source.label}: default model` },
77
+ input.processId,
78
+ );
79
+ check(
80
+ input.selectedTurnModelProfileId,
81
+ { ...source, label: `${source.label}: selected step` },
82
+ input.processId,
83
+ );
84
+ const parsed = parseStrictInstanceTurnConfigsJson(
85
+ input.processId,
86
+ input.turnConfigsJson ?? null,
87
+ );
88
+ if (!parsed.ok) {
89
+ add(
90
+ "invalid_model_configuration",
91
+ source.href ?? source.label,
92
+ "Saved step model configuration is invalid.",
93
+ source,
94
+ );
95
+ return;
96
+ }
97
+ for (const [turnId, config] of Object.entries(parsed.value))
98
+ check(
99
+ config.modelProfileId,
100
+ { ...source, label: `${source.label}: ${turnId}` },
101
+ input.processId,
102
+ );
103
+ }
104
+ const config = deps.config;
105
+ if (config) {
106
+ for (const profile of config.pi.model_profiles)
107
+ check(profile.id, { label: `pi.model_profiles (${profile.id})`, href: null });
108
+ check(config.pi.default_model_profile, { label: "pi.default_model_profile", href: null });
109
+ check(config.pi.process_title_generation.model_profile, {
110
+ label: "pi.process_title_generation.model_profile",
111
+ href: null,
112
+ });
113
+ for (const [processId, processConfig] of Object.entries(config.process_configs ?? {})) {
114
+ const prefix = `process_configs.${processId}`;
115
+ check(
116
+ processConfig.default_model_profile,
117
+ { label: `${prefix}.default_model_profile`, href: null },
118
+ processId,
119
+ );
120
+ for (const [turnId, turnConfig] of Object.entries(processConfig.turn_configs ?? {}))
121
+ check(
122
+ turnConfig.model_profile,
123
+ { label: `${prefix}.turn_configs.${turnId}.model_profile`, href: null },
124
+ processId,
125
+ );
126
+ }
127
+ }
128
+ for (const reference of deps.scopedSettingsService?.modelReferences() ?? []) {
129
+ const source = {
130
+ label: `${reference.label} (${reference.key})`,
131
+ href: reference.subjectId
132
+ ? `/settings?scope=${encodeURIComponent(reference.subjectId)}`
133
+ : null,
134
+ };
135
+ if (reference.invalid)
136
+ add(
137
+ "invalid_model_configuration",
138
+ `${reference.subjectId}:${reference.key}`,
139
+ "Saved model setting is invalid. Correct it in Settings.",
140
+ source,
141
+ );
142
+ else check(reference.modelProfileId, source);
143
+ }
144
+ for (const watcher of deps.processWatchers?.listAll() ?? []) {
145
+ const source = { label: watcher.configPath, href: "/watchers" };
146
+ check(watcher.launchModelConfig.defaultModelProfileId, source, watcher.processId);
147
+ for (const [turnId, turnConfig] of Object.entries(watcher.launchModelConfig.turnConfigs ?? {}))
148
+ check(
149
+ turnConfig.modelProfileId,
150
+ { ...source, label: `${source.label}: ${turnId}` },
151
+ watcher.processId,
152
+ );
153
+ }
154
+ for (const process of deps.processes.listModelConfigurations()) {
155
+ checkPersisted(
156
+ {
157
+ ...process,
158
+ selectedTurnModelProfileId: process.selectedTurnId
159
+ ? process.selectedTurnModelProfileId
160
+ : null,
161
+ },
162
+ {
163
+ label: process.title ?? process.id,
164
+ href: `/processes/${encodeURIComponent(process.id)}?inspect=process&section=inputs`,
165
+ },
166
+ );
167
+ }
168
+ for (const execution of deps.futureExecutions.listAll()) {
169
+ const source = {
170
+ label: `Scheduled ${execution.kind}: ${execution.id}`,
171
+ href:
172
+ execution.kind === "launch"
173
+ ? `/future-launches/${encodeURIComponent(execution.id)}`
174
+ : `/processes/${encodeURIComponent(execution.instanceId ?? "")}`,
175
+ };
176
+ check(execution.modelSelection?.modelProfileId, source, execution.processId);
177
+ const parsed =
178
+ execution.kind === "launch"
179
+ ? parseFutureLaunchPayloadJson(execution.payloadJson)
180
+ : parseFutureActionPayloadJson(execution.payloadJson);
181
+ if (!parsed.ok)
182
+ add(
183
+ "invalid_model_configuration",
184
+ execution.id,
185
+ `Scheduled ${execution.kind} configuration is invalid.`,
186
+ source,
187
+ );
188
+ else if ("launchPlan" in parsed.value)
189
+ checkPersisted(parsed.value.launchPlan.processInput, source);
190
+ else check(parsed.value.nextTurnModelProfileId, source, execution.processId);
191
+ }
192
+ for (const issue of issues.values()) issue.sources.sort((a, b) => a.label.localeCompare(b.label));
193
+ return [...issues.values()].sort(
194
+ (a, b) =>
195
+ (a.severity === b.severity ? 0 : a.severity === "error" ? -1 : 1) ||
196
+ a.message.localeCompare(b.message) ||
197
+ a.id.localeCompare(b.id),
198
+ );
199
+ }
@@ -252,6 +252,30 @@ export function createProcessInstanceRepo(db: LeitwerkDb) {
252
252
  .map(rowToProcessInstance);
253
253
  },
254
254
 
255
+ /** Model references for current work without loading prompts or process state. @internal */
256
+ listModelConfigurations() {
257
+ return db
258
+ .select({
259
+ /** @internal */
260
+ id: s.processInstances.id,
261
+ /** @internal */
262
+ processId: s.processInstances.processId,
263
+ /** @internal */
264
+ title: s.processInstances.title,
265
+ /** @internal */
266
+ defaultModelProfileId: s.processInstances.defaultModelProfileId,
267
+ /** @internal */
268
+ turnConfigsJson: s.processInstances.turnConfigsJson,
269
+ /** @internal */
270
+ selectedTurnId: s.processInstances.selectedTurnId,
271
+ /** @internal */
272
+ selectedTurnModelProfileId: s.processInstances.selectedTurnModelProfileId,
273
+ })
274
+ .from(s.processInstances)
275
+ .where(notInArray(s.processInstances.lifecycleStatus, ["completed", "aborted"]))
276
+ .all();
277
+ },
278
+
255
279
  /** @internal */
256
280
  listCurrent(limit: number): ProcessInstance[] {
257
281
  return db
@@ -90,9 +90,13 @@ export function createTurnStartRecordRepo(db: LeitwerkDb) {
90
90
  }): TurnStartRecord | null {
91
91
  const current = this.getById(input.id);
92
92
  if (!current || current.state.kind !== input.expectedKind) return null;
93
+ const state = {
94
+ ...input.state,
95
+ automaticRetry: input.state.automaticRetry ?? current.state.automaticRetry,
96
+ };
93
97
  const result = db
94
98
  .update(s.turnStartRecords)
95
- .set({ stateJson: JSON.stringify(input.state), updatedAt: now() })
99
+ .set({ stateJson: JSON.stringify(state), updatedAt: now() })
96
100
  .where(
97
101
  and(
98
102
  eq(s.turnStartRecords.id, input.id),
@@ -3,9 +3,9 @@ import type {
3
3
  PrimaryPathUiSnapshot,
4
4
  TurnTracePreview,
5
5
  } from "@leitwerk-dev/protocol";
6
- import { and, eq, inArray } from "drizzle-orm";
6
+ import { and, eq, inArray, sql } from "drizzle-orm";
7
7
  import type { LeitwerkDb } from "./database.js";
8
- import { sessionSummaries, turnSummaries } from "./schema.js";
8
+ import { sessionSummaries, turnRecords, turnStartRecords, turnSummaries } from "./schema.js";
9
9
 
10
10
  /** @internal */
11
11
  export interface SessionSummary {
@@ -42,6 +42,29 @@ export interface SessionSummary {
42
42
  /** @internal */
43
43
  export function createTurnSummaryRepo(db: LeitwerkDb) {
44
44
  return {
45
+ /** Dashboard projections never load assistant text, event payloads or session files. @internal */
46
+ listDashboardCosts() {
47
+ return db
48
+ .select({
49
+ /** @internal */
50
+ providerId: sql<
51
+ string | null
52
+ >`case when json_extract(${turnStartRecords.stateJson}, '$.kind') = 'accepted' then json_extract(${turnStartRecords.stateJson}, '$.start.model.providerId') end`,
53
+ /** @internal */
54
+ modelId: sql<
55
+ string | null
56
+ >`case when json_extract(${turnStartRecords.stateJson}, '$.kind') = 'accepted' then json_extract(${turnStartRecords.stateJson}, '$.start.model.modelId') end`,
57
+ /** @internal */
58
+ costUsd: sql<
59
+ number | null
60
+ >`json_extract(${turnSummaries.summaryJson}, '$.usage.cost.total')`,
61
+ })
62
+ .from(turnRecords)
63
+ .leftJoin(turnSummaries, eq(turnSummaries.turnRecordId, turnRecords.id))
64
+ .leftJoin(turnStartRecords, eq(turnStartRecords.id, turnRecords.turnStartRecordId))
65
+ .where(eq(turnRecords.turnType, "llm"))
66
+ .all();
67
+ },
45
68
  /** @internal */
46
69
  get(turnRecordId: string): CompactTurnSummary | null {
47
70
  const row = db
@@ -36,29 +36,20 @@ function validationFailure(code: string, message: string): OutcomeValidationFail
36
36
  }
37
37
 
38
38
  function jsonValuesEqual(left: unknown, right: unknown): boolean {
39
- if (left === right) {
40
- return true;
41
- }
42
- if (Array.isArray(left) && Array.isArray(right)) {
43
- if (left.length !== right.length) {
44
- return false;
45
- }
46
- return left.every((entry, index) => jsonValuesEqual(entry, right[index]));
47
- }
48
- if (isJsonObject(left) && isJsonObject(right)) {
49
- const leftKeys = Object.keys(left).sort();
50
- const rightKeys = Object.keys(right).sort();
51
- if (leftKeys.length !== rightKeys.length) {
52
- return false;
53
- }
54
- for (let index = 0; index < leftKeys.length; index += 1) {
55
- if (leftKeys[index] !== rightKeys[index]) {
56
- return false;
57
- }
58
- }
59
- return leftKeys.every((key) => jsonValuesEqual(left[key], right[key]));
60
- }
61
- return false;
39
+ if (left === right) return true;
40
+ if (Array.isArray(left) && Array.isArray(right))
41
+ return (
42
+ left.length === right.length &&
43
+ left.every((value, index) => jsonValuesEqual(value, right[index]))
44
+ );
45
+ return (
46
+ isJsonObject(left) &&
47
+ isJsonObject(right) &&
48
+ Object.keys(left).length === Object.keys(right).length &&
49
+ Object.keys(left).every(
50
+ (key) => Object.hasOwn(right, key) && jsonValuesEqual(left[key], right[key]),
51
+ )
52
+ );
62
53
  }
63
54
 
64
55
  function resolveOutcomeValidationContract(
@@ -38,6 +38,7 @@ const WORKER_LEASE_TRANSITIONS: ReadonlyArray<WorkerLeaseTransitionRule> = [
38
38
  { from: "idle", to: "failed", observation: "failure_reported" },
39
39
  { from: "busy", to: "failed", observation: "failure_reported" },
40
40
  { from: "draining", to: "failed", observation: "failure_reported" },
41
+ { from: "cleanup", to: "failed", observation: "failure_reported" },
41
42
 
42
43
  { from: "draining", to: "cleanup", observation: "cleanup_completed" },
43
44
  { from: "failed", to: "cleanup", observation: "cleanup_completed" },
@@ -68,7 +69,7 @@ const WORKER_LEASE_NOOPS: Readonly<Record<WorkerLeaseObservation, ReadonlySet<Wo
68
69
  busy_reported: new Set(["busy", "draining", "failed", "cleanup", "exited"]),
69
70
  idle_reported: new Set(["idle", "draining", "failed", "cleanup", "exited"]),
70
71
  stop_requested: new Set(["absent", "draining", "failed", "cleanup", "exited"]),
71
- failure_reported: new Set(["failed", "cleanup", "exited"]),
72
+ failure_reported: new Set(["failed", "exited"]),
72
73
  cleanup_completed: new Set(["cleanup", "exited"]),
73
74
  process_exited: new Set(["absent", "exited"]),
74
75
  reclaimed: new Set(["absent"]),
@@ -3,6 +3,8 @@ import {
3
3
  maybeBroadcastErrorAttentionToast as maybeBroadcastErrorAttentionToastCore,
4
4
  } from "../process-attention-notifier.js";
5
5
  import { broadcastProcessAttentionToast } from "../process-operator-attention.js";
6
+ import { automaticStartupRecovery, startupRetryState } from "../startup-retry-policy.js";
7
+ import { AutomaticRetryStartup } from "./ops/automatic-retry-startup.js";
6
8
  import {
7
9
  AbortProcess,
8
10
  AbortTurn,
@@ -177,6 +179,18 @@ export function createProcessEngine(deps: ProcessEngineDeps): ProcessEngine {
177
179
  retryStartup(instanceId, startRecordId, opts) {
178
180
  return run(RetryStartup, { instanceId, startRecordId, ...(opts ?? {}) });
179
181
  },
182
+ async retryStartupAutomatically(instanceId, startRecordId, opts) {
183
+ const result = await run(AutomaticRetryStartup, { instanceId, startRecordId, ...opts });
184
+ if (!result.ok || result.data.status !== "retried") return result;
185
+ const current = deps.processes.getById(instanceId)?.currentExecution;
186
+ const start = current?.kind === "worker_start" ? deps.turnStarts.getById(current.id) : null;
187
+ if (
188
+ start &&
189
+ (start.state.kind === "preparation_failed" || start.state.kind === "bootstrap_failed")
190
+ )
191
+ return { ...result, data: automaticStartupRecovery(start, startupRetryState(start, [])) };
192
+ return result;
193
+ },
180
194
 
181
195
  continueFailedTurn(instanceId, turnRecordId, options) {
182
196
  return run(ContinueFailedTurn, { instanceId, turnRecordId, options });
@@ -0,0 +1,93 @@
1
+ import type { AutomaticStartupRecoverySummary } from "@leitwerk-dev/domain";
2
+ import { automaticStartupRecovery, startupRetryState } from "../../startup-retry-policy.js";
3
+ import { accept, reject } from "../decision.js";
4
+ import { defineOperation } from "../operation.js";
5
+ import { RetryStartup } from "./retry-startup.js";
6
+
7
+ /** @internal */
8
+ export const AutomaticRetryStartup = defineOperation<
9
+ "automatic_retry_startup",
10
+ {
11
+ instanceId: string;
12
+ startRecordId: string;
13
+ availabilityCause?: "availability_transition" | "startup_reconciliation";
14
+ },
15
+ AutomaticStartupRecoverySummary
16
+ >({
17
+ kind: "automatic_retry_startup",
18
+ label: "Automatic startup recovery",
19
+ admission: "new_turn",
20
+ async decide(ctx, input) {
21
+ if (
22
+ ctx.process.lifecycleStatus !== "error" ||
23
+ ctx.process.currentExecution?.kind !== "worker_start" ||
24
+ ctx.process.currentExecution.id !== input.startRecordId
25
+ )
26
+ return reject("stale_turn_start", "Startup recovery target is no longer current");
27
+ const start = ctx.deps.turnStarts.getById(input.startRecordId);
28
+ if (
29
+ !start ||
30
+ (start.state.kind !== "preparation_failed" && start.state.kind !== "bootstrap_failed")
31
+ )
32
+ return reject(
33
+ "retry_target_missing",
34
+ "Automatic recovery requires an unaccepted failed start",
35
+ );
36
+ const retry =
37
+ start.state.automaticRetry ??
38
+ startupRetryState(
39
+ start,
40
+ ctx.deps.turnStarts.listByInstance(ctx.process.id),
41
+ ctx.deps.events.listByInstanceEventTypes(ctx.process.id, ["startup_retry_scheduled"], -1),
42
+ );
43
+ let modelRestored = false;
44
+ if (input.availabilityCause && start.state.kind === "preparation_failed") {
45
+ const evaluation = ctx.deps.processModelPolicy.evaluate({
46
+ kind: "preparation_recovery",
47
+ cause: input.availabilityCause,
48
+ process: ctx.process,
49
+ currentStart: start,
50
+ availability: ctx.deps.getModelAvailabilitySnapshot(),
51
+ });
52
+ modelRestored = evaluation.ok && evaluation.selection !== null;
53
+ }
54
+ const summary = automaticStartupRecovery(start, retry, Date.now(), modelRestored);
55
+ if (summary.status !== "ready") {
56
+ if (start.state.automaticRetry && retry.nextRetryAt === summary.nextRetryAt)
57
+ return accept({ data: summary });
58
+ const metadata = { ...retry, nextRetryAt: summary.nextRetryAt };
59
+ return accept({
60
+ data: summary,
61
+ writes: {
62
+ turnStartWrites: [
63
+ {
64
+ kind: "cas_state",
65
+ id: start.id,
66
+ expectedKind: start.state.kind,
67
+ state: { ...start.state, automaticRetry: metadata },
68
+ },
69
+ ],
70
+ // Refresh the recovery projection only when retained metadata changes.
71
+ processPatch: { currentExecution: ctx.process.currentExecution },
72
+ changedFields: ["currentExecution"],
73
+ },
74
+ });
75
+ }
76
+ const decision = await RetryStartup.decide(ctx, {
77
+ ...input,
78
+ automaticRetry: { ...retry, starts: retry.starts + 1, nextRetryAt: null },
79
+ });
80
+ if (!decision.ok) return reject(decision.code, decision.message);
81
+ return accept({
82
+ writes: decision.writes,
83
+ metadata: decision.metadata,
84
+ data: {
85
+ ...summary,
86
+ starts: retry.starts + 1,
87
+ status: "retried",
88
+ nextRetryAt: null,
89
+ reason: "Worker startup retry requested.",
90
+ },
91
+ });
92
+ },
93
+ });
@@ -1,4 +1,4 @@
1
- import type { Actor } from "@leitwerk-dev/domain";
1
+ import type { Actor, TurnStartRecordState } from "@leitwerk-dev/domain";
2
2
  import { generateId } from "../../db/repo-helpers.js";
3
3
  import { accept, modelOverrideMetadata, reject } from "../decision.js";
4
4
  import { defineOperation } from "../operation.js";
@@ -15,6 +15,8 @@ export interface RetryStartupInput {
15
15
  nextTurnModelProfileId?: string | null;
16
16
  providerOptions?: Readonly<Record<string, string>>;
17
17
  actor?: Actor;
18
+ /** Only the server's automatic recovery operation supplies inherited counters. */
19
+ automaticRetry?: import("@leitwerk-dev/domain").StartupRetryState;
18
20
  }
19
21
 
20
22
  /** Replaces only the current failed worker start; it never creates a turn attempt. */
@@ -42,7 +44,7 @@ export const RetryStartup = defineOperation<
42
44
  return reject("retry_target_missing", "Startup retry requires a failed current start");
43
45
  }
44
46
  const id = generateId("tsr");
45
- const state =
47
+ const state: TurnStartRecordState =
46
48
  failed.state.kind === "preparation_failed"
47
49
  ? {
48
50
  ...failed.state,
@@ -63,6 +65,7 @@ export const RetryStartup = defineOperation<
63
65
  ? { modelSelectionProvenance: failed.state.start.modelSelectionProvenance }
64
66
  : {}),
65
67
  };
68
+ state.automaticRetry = input.automaticRetry;
66
69
  const writes = createWrites({
67
70
  workerIntent: state.kind === "starting" ? { kind: "restart_worker" } : undefined,
68
71
  });
@@ -92,7 +95,12 @@ export const RetryStartup = defineOperation<
92
95
  eventType: "startup_retry_scheduled",
93
96
  level: "info",
94
97
  message: "Startup retry scheduled",
95
- data: { previousStartRecordId: failed.id, startRecordId: id, state: state.kind },
98
+ data: {
99
+ previousStartRecordId: failed.id,
100
+ startRecordId: id,
101
+ state: state.kind,
102
+ retrySource: input.automaticRetry ? "automatic" : "manual",
103
+ },
96
104
  });
97
105
  stampActorOnEvents(writes, input.actor, "startup_retry_scheduled");
98
106
  return accept({