@leitwerk-dev/server 0.5.3 → 0.5.5

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 (84) hide show
  1. package/dist/{app-DZUsf76a.d.ts → app-DWWNqFtH.d.ts} +83 -77
  2. package/dist/app-VLQCV5WS.js +8 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/{chunk-6EEU4QOU.js → chunk-65CBLH7U.js} +350 -144
  5. package/dist/chunk-65CBLH7U.js.map +1 -0
  6. package/dist/chunk-C2K2AM5X.js +82 -0
  7. package/dist/chunk-C2K2AM5X.js.map +1 -0
  8. package/dist/{chunk-AJ2DQWI3.js → chunk-I3CCVPXY.js} +133 -83
  9. package/dist/chunk-I3CCVPXY.js.map +1 -0
  10. package/dist/config/config-loader.d.ts.map +1 -1
  11. package/dist/dashboard-model-issues.d.ts.map +1 -1
  12. package/dist/deployment-preflight.d.ts +2 -1
  13. package/dist/deployment-preflight.d.ts.map +1 -1
  14. package/dist/extension-boot-check.d.ts +5 -0
  15. package/dist/extension-boot-check.d.ts.map +1 -0
  16. package/dist/future-execution/execution.d.ts.map +1 -1
  17. package/dist/future-execution/launch-lifecycle.d.ts.map +1 -1
  18. package/dist/future-execution/lifecycle.d.ts.map +1 -1
  19. package/dist/future-execution/reconciliation.d.ts.map +1 -1
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +41 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/main.js +6 -71
  25. package/dist/main.js.map +1 -1
  26. package/dist/process-engine/ops/execute-action.d.ts.map +1 -1
  27. package/dist/process-engine/ops/retry-startup.d.ts.map +1 -1
  28. package/dist/process-engine/turn-start-preflight.d.ts.map +1 -1
  29. package/dist/process-model-config.d.ts.map +1 -1
  30. package/dist/process-model-policy/construct.d.ts +1 -0
  31. package/dist/process-model-policy/construct.d.ts.map +1 -1
  32. package/dist/process-model-policy/evaluate.d.ts +3 -3
  33. package/dist/process-model-policy/evaluate.d.ts.map +1 -1
  34. package/dist/process-model-policy/index.d.ts +1 -0
  35. package/dist/process-model-policy/index.d.ts.map +1 -1
  36. package/dist/process-model-policy/launch.d.ts.map +1 -1
  37. package/dist/process-model-policy/project.d.ts.map +1 -1
  38. package/dist/process-model-policy/requirements.d.ts +16 -0
  39. package/dist/process-model-policy/requirements.d.ts.map +1 -0
  40. package/dist/process-model-policy/types.d.ts +87 -75
  41. package/dist/process-model-policy/types.d.ts.map +1 -1
  42. package/dist/process-model-policy-presenter.d.ts.map +1 -1
  43. package/dist/process-model-selection.d.ts.map +1 -1
  44. package/dist/process-title-generator.d.ts +2 -0
  45. package/dist/process-title-generator.d.ts.map +1 -1
  46. package/dist/routes/process-actions.d.ts.map +1 -1
  47. package/dist/supervisor/worker-start-payload-builder.d.ts.map +1 -1
  48. package/dist/test-helpers/process-model-fixtures.d.ts +6 -0
  49. package/dist/test-helpers/process-model-fixtures.d.ts.map +1 -1
  50. package/dist/testing.js +1 -1
  51. package/package.json +12 -12
  52. package/src/app.ts +21 -0
  53. package/src/config/config-loader.ts +5 -0
  54. package/src/dashboard-model-issues.ts +66 -5
  55. package/src/deployment-preflight.ts +15 -7
  56. package/src/extension-boot-check.ts +36 -0
  57. package/src/future-execution/execution.ts +3 -8
  58. package/src/future-execution/launch-lifecycle.ts +15 -10
  59. package/src/future-execution/lifecycle.ts +1 -0
  60. package/src/future-execution/reconciliation.ts +2 -34
  61. package/src/index.ts +1 -0
  62. package/src/launch-coordinator.ts +2 -2
  63. package/src/process-engine/ops/execute-action.ts +1 -0
  64. package/src/process-engine/ops/retry-startup.ts +10 -12
  65. package/src/process-engine/turn-start-preflight.ts +38 -15
  66. package/src/process-model-config.ts +7 -3
  67. package/src/process-model-policy/construct.ts +61 -3
  68. package/src/process-model-policy/evaluate.ts +73 -64
  69. package/src/process-model-policy/index.ts +16 -14
  70. package/src/process-model-policy/launch.ts +27 -29
  71. package/src/process-model-policy/project.ts +72 -43
  72. package/src/process-model-policy/requirements.ts +73 -0
  73. package/src/process-model-policy/types.ts +108 -78
  74. package/src/process-model-policy-presenter.ts +18 -2
  75. package/src/process-model-selection.ts +2 -0
  76. package/src/process-title-generator.ts +12 -16
  77. package/src/routes/launchers.ts +1 -1
  78. package/src/routes/process-actions.ts +1 -0
  79. package/src/supervisor/worker-start-payload-builder.ts +6 -1
  80. package/src/test-helpers/process-model-fixtures.ts +25 -4
  81. package/dist/app-2TCRADVA.js +0 -8
  82. package/dist/chunk-6EEU4QOU.js.map +0 -1
  83. package/dist/chunk-AJ2DQWI3.js.map +0 -1
  84. /package/dist/{app-2TCRADVA.js.map → app-VLQCV5WS.js.map} +0 -0
@@ -25,12 +25,18 @@ export function buildDashboardModelIssues(
25
25
  ): DashboardConfigurationIssue[] {
26
26
  const issues = new Map<string, DashboardConfigurationIssue>();
27
27
  const availability = deps.modelStatusCache.snapshot();
28
- function add(code: string, key: string, message: string, source: IssueSource) {
28
+ function add(
29
+ code: string,
30
+ key: string,
31
+ message: string,
32
+ source: IssueSource,
33
+ severity?: "warning" | "error",
34
+ ) {
29
35
  const id = JSON.stringify([code, key]);
30
36
  const issue = issues.get(id) ?? {
31
37
  id,
32
38
  code,
33
- severity: code === "model_stale" ? ("warning" as const) : ("error" as const),
39
+ severity: severity ?? (code === "model_stale" ? ("warning" as const) : ("error" as const)),
34
40
  message,
35
41
  sources: [],
36
42
  };
@@ -38,11 +44,18 @@ export function buildDashboardModelIssues(
38
44
  issue.sources.push(source);
39
45
  issues.set(id, issue);
40
46
  }
41
- function check(profileId: string | null | undefined, source: IssueSource, processId = "") {
47
+ function check(
48
+ profileId: string | null | undefined,
49
+ source: IssueSource,
50
+ processId = "",
51
+ turnId?: string,
52
+ preference = false,
53
+ ) {
42
54
  const id = trimToNull(profileId);
43
55
  if (!id) return;
44
56
  const result = deps.processModelPolicy.evaluate({
45
57
  kind: "runtime_selection",
58
+ target: turnId ? { kind: "turn", turnId } : { kind: "process_default" },
46
59
  processId,
47
60
  selection: {
48
61
  modelProfileId: id,
@@ -50,7 +63,7 @@ export function buildDashboardModelIssues(
50
63
  },
51
64
  availability,
52
65
  });
53
- if (result.ok) return;
66
+ if (result.ok || (preference && result.code === "model_profile_not_allowed")) return;
54
67
  const key = result.code === "model_profile_not_allowed" ? JSON.stringify([id, processId]) : id;
55
68
  const message = presentProcessModelPolicyFailure(result);
56
69
  add(
@@ -75,6 +88,8 @@ export function buildDashboardModelIssues(
75
88
  input.defaultModelProfileId,
76
89
  { ...source, label: `${source.label}: default model` },
77
90
  input.processId,
91
+ undefined,
92
+ true,
78
93
  );
79
94
  check(
80
95
  input.selectedTurnModelProfileId,
@@ -99,8 +114,43 @@ export function buildDashboardModelIssues(
99
114
  config.modelProfileId,
100
115
  { ...source, label: `${source.label}: ${turnId}` },
101
116
  input.processId,
117
+ turnId,
102
118
  );
103
119
  }
120
+ for (const processId of deps.processGraphs.keys()) {
121
+ check(
122
+ deps.config?.pi.process_title_generation.model_profile,
123
+ { label: `${processId}: title generation`, href: null },
124
+ processId,
125
+ );
126
+ const preview = deps.processModelPolicy.project({
127
+ kind: "launcher_preview",
128
+ processId,
129
+ modelConfig: {},
130
+ availability,
131
+ });
132
+ for (const turn of preview.turns) {
133
+ if (
134
+ !turn.effective.error &&
135
+ (turn.effective.ranking?.kind === "cost_id" ||
136
+ (turn.effective.ranking?.tiedProfileIds.length ?? 0) > 1)
137
+ )
138
+ add(
139
+ "automatic_model_tiebreak",
140
+ `${processId}/${turn.turnId}`,
141
+ `Selected '${turn.effective.profile?.id}' by ${turn.effective.ranking?.kind === "cost_id" ? "cost group and profile ID" : `cost group and profile ID among equal-specificity defaults: ${turn.effective.ranking?.tiedProfileIds.join(", ")}`}`,
142
+ { label: `${processId}: ${turn.turnId}`, href: null },
143
+ "warning",
144
+ );
145
+ if (turn.effective.error)
146
+ add(
147
+ "model_policy_blocked",
148
+ turn.effective.profile?.id ?? `${processId}/${turn.turnId}`,
149
+ turn.effective.error,
150
+ { label: `${processId}: ${turn.turnId}`, href: null },
151
+ );
152
+ }
153
+ }
104
154
  const config = deps.config;
105
155
  if (config) {
106
156
  for (const profile of config.pi.model_profiles)
@@ -116,12 +166,16 @@ export function buildDashboardModelIssues(
116
166
  processConfig.default_model_profile,
117
167
  { label: `${prefix}.default_model_profile`, href: null },
118
168
  processId,
169
+ undefined,
170
+ true,
119
171
  );
120
172
  for (const [turnId, turnConfig] of Object.entries(processConfig.turn_configs ?? {}))
121
173
  check(
122
174
  turnConfig.model_profile,
123
175
  { label: `${prefix}.turn_configs.${turnId}.model_profile`, href: null },
124
176
  processId,
177
+ turnId,
178
+ true,
125
179
  );
126
180
  }
127
181
  }
@@ -143,12 +197,19 @@ export function buildDashboardModelIssues(
143
197
  }
144
198
  for (const watcher of deps.processWatchers?.listAll() ?? []) {
145
199
  const source = { label: watcher.configPath, href: "/watchers" };
146
- check(watcher.launchModelConfig.defaultModelProfileId, source, watcher.processId);
200
+ check(
201
+ watcher.launchModelConfig.defaultModelProfileId,
202
+ source,
203
+ watcher.processId,
204
+ undefined,
205
+ true,
206
+ );
147
207
  for (const [turnId, turnConfig] of Object.entries(watcher.launchModelConfig.turnConfigs ?? {}))
148
208
  check(
149
209
  turnConfig.modelProfileId,
150
210
  { ...source, label: `${source.label}: ${turnId}` },
151
211
  watcher.processId,
212
+ turnId,
152
213
  );
153
214
  }
154
215
  for (const process of deps.processes.listModelConfigurations()) {
@@ -69,21 +69,29 @@ export async function runDeploymentPreflight(input: {
69
69
  await backupProductionDatabase({ sourcePath, destinationPath: databaseCopyPath });
70
70
 
71
71
  const createContext = input.createContext ?? (await import("./app.js")).createAppContext;
72
- let ctx: AppContext | null = null;
73
- try {
74
- ctx = await createContext({
72
+ await checkPreflightApp(
73
+ await createContext({
75
74
  config: deploymentPreflightConfig(input.config, scratchRoot, databaseCopyPath),
76
75
  extensionLoadingStartDir: input.extensionLoadingStartDir,
77
- });
76
+ }),
77
+ );
78
+ }
79
+
80
+ export async function checkPreflightApp(ctx: AppContext, listen = true): Promise<void> {
81
+ try {
82
+ if (!listen) {
83
+ await ctx.app.ready();
84
+ return;
85
+ }
78
86
  await ctx.app.listen({ host: "127.0.0.1", port: 0 });
79
87
  const health = await ctx.app.inject({ method: "GET", url: "/api/health" });
80
88
  if (health.statusCode !== 200 || health.json().status !== "ok") {
81
- throw new Error(`Deployment preflight health check failed with HTTP ${health.statusCode}`);
89
+ throw new Error(`Preflight health check failed with HTTP ${health.statusCode}`);
82
90
  }
83
91
  if (ctx.isReady()) {
84
- throw new Error("Deployment preflight started background services unexpectedly");
92
+ throw new Error("Preflight started background services unexpectedly");
85
93
  }
86
94
  } finally {
87
- await ctx?.close();
95
+ await ctx.close();
88
96
  }
89
97
  }
@@ -0,0 +1,36 @@
1
+ import { statSync } from "node:fs";
2
+ import { mkdtempDisposable } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { type AppOptions, createAppContext } from "./app.js";
6
+ import type { LeitwerkConfig } from "./config/index.js";
7
+ import {
8
+ backupProductionDatabase,
9
+ checkPreflightApp,
10
+ deploymentPreflightConfig,
11
+ } from "./deployment-preflight.js";
12
+
13
+ /** Boot extensions with disposable storage and no background services. @internal */
14
+ export async function runExtensionBootCheck(
15
+ config: LeitwerkConfig,
16
+ options: Pick<
17
+ AppOptions,
18
+ "extensionLoadingStartDir" | "extensionCatalog" | "resolvedExtensionEntries"
19
+ >,
20
+ mode: "boot" | "source-reload" = "boot",
21
+ ): Promise<void> {
22
+ await using scratch = await mkdtempDisposable(path.join(tmpdir(), "leitwerk-extension-boot-"));
23
+ let sqlitePath = ":memory:";
24
+ const sourcePath = config.storage.sqlite_path;
25
+ if (mode === "source-reload" && sourcePath !== ":memory:") {
26
+ sqlitePath = path.join(scratch.path, "leitwerk.sqlite");
27
+ if (statSync(sourcePath, { throwIfNoEntry: false }))
28
+ await backupProductionDatabase({ sourcePath, destinationPath: sqlitePath });
29
+ }
30
+ const app = await createAppContext({
31
+ ...options,
32
+ config: deploymentPreflightConfig(config, scratch.path, sqlitePath),
33
+ logger: mode === "source-reload" ? undefined : false,
34
+ });
35
+ await checkPreflightApp(app, mode === "boot");
36
+ }
@@ -189,7 +189,7 @@ async function executeScheduledLaunch(
189
189
  async prepare(payload) {
190
190
  const prepared = await deps.launchPlans.prepare(payload.launchPlan, {
191
191
  modelConfig: payload.modelConfig,
192
- invalidModelConfig: "reject",
192
+ invalidModelConfig: "retain",
193
193
  });
194
194
  if (!prepared.ok) {
195
195
  return {
@@ -348,6 +348,7 @@ export function createFutureExecutionExecutor(deps: FutureExecutionExecutorDeps)
348
348
  const snapshot = deps.modelStatusCache.snapshot();
349
349
  const result = deps.processModelPolicy.evaluate({
350
350
  kind: "runtime_selection",
351
+ target: { kind: "process_default" },
351
352
  availability: snapshot,
352
353
  processId: execution.processId,
353
354
  selection: execution.modelSelection,
@@ -445,13 +446,7 @@ export function createFutureExecutionExecutor(deps: FutureExecutionExecutorDeps)
445
446
  if (!latest || latest.nextRunAt > asOf) {
446
447
  return;
447
448
  }
448
- if (
449
- (!latest.modelSelection ||
450
- (latest.kind === "action" && !isPinnedModelSelection(latest.modelSelection))) &&
451
- deps.processGraphs &&
452
- deps.processActionRegistry &&
453
- deps.turnRecords
454
- ) {
449
+ if (deps.processGraphs && deps.processActionRegistry && deps.turnRecords) {
455
450
  const projected = await projectFutureExecutionModelState(
456
451
  {
457
452
  processes: deps.processes,
@@ -372,7 +372,7 @@ export function createFutureLaunchLifecycle(
372
372
  modelConfig: normalizeLaunchModelConfigInput(input.modelConfig),
373
373
  invalidModelConfig: "reject",
374
374
  });
375
- if (!prepared.ok && schedule.value.mode === "now") {
375
+ if (!prepared.ok) {
376
376
  return {
377
377
  ok: false as const,
378
378
  outcome: {
@@ -382,20 +382,25 @@ export function createFutureLaunchLifecycle(
382
382
  };
383
383
  }
384
384
  const launchPlan = applySubmittedProcessTitleToLaunchPlan(prepared.launchPlan, input);
385
+ const preview = deps.processModelPolicy.project({
386
+ kind: "launcher_preview",
387
+ processId: launchPlan.processId,
388
+ plan: launchPlan,
389
+ modelConfig: prepared.modelConfig,
390
+ availability: deps.modelStatusCache.snapshot(),
391
+ });
392
+ const issues = preview.turns
393
+ .filter((turn) => turn.effective.error)
394
+ .map((turn) => ({
395
+ code: "model_not_ready",
396
+ message: `${turn.turnId}: ${turn.effective.error}`,
397
+ }));
398
+ if (issues.length) return { ok: false as const, outcome: { kind: "invalid" as const, issues } };
385
399
  const modelState = projectLaunchPlanModelState(launchPlan, {
386
400
  policy: deps.processModelPolicy,
387
401
  availability: deps.modelStatusCache.snapshot(),
388
402
  detectedAt: operationTime.toISOString(),
389
403
  });
390
- if (!prepared.ok && !modelState.blockedReason) {
391
- return {
392
- ok: false as const,
393
- outcome: {
394
- kind: "invalid" as const,
395
- issues: presentLaunchPlanPreparationIssues(prepared.errors),
396
- },
397
- };
398
- }
399
404
  return { ok: true as const, launchPlan, modelState, schedule: schedule.value };
400
405
  }
401
406
 
@@ -250,6 +250,7 @@ async function validateScheduledActionRequest(
250
250
  if (typeof nextTurnModelProfileId === "string") {
251
251
  const result = deps.processModelPolicy.evaluate({
252
252
  kind: "runtime_selection",
253
+ target: { kind: "turn", turnId: validation.candidateSelectedTurnId! },
253
254
  availability: deps.modelStatusCache.snapshot(),
254
255
  processId: process.processId,
255
256
  selection: {
@@ -6,7 +6,6 @@ import type { ProcessActionRegistry } from "../process-action-registry.js";
6
6
  import type { ProcessGraphRegistry } from "../process-graph.js";
7
7
  import {
8
8
  evaluateAtStableAvailabilityRevision,
9
- isPinnedModelSelection,
10
9
  type ServerProcessModelPolicy,
11
10
  } from "../process-model-policy/index.js";
12
11
  import type { ProcessOperationCoordinator } from "../process-operation-coordinator.js";
@@ -101,39 +100,8 @@ export async function reconcileFutureExecutionModelBlocks(input: {
101
100
  if (projected && !sameModelPolicyState(current, projected)) updateCurrent(projected);
102
101
  };
103
102
 
104
- if (!isPinnedModelSelection(current.modelSelection)) {
105
- await projectCurrent();
106
- return;
107
- }
108
- if (!current.modelSelection) {
109
- await projectCurrent();
110
- if (!current.modelSelection) return;
111
- }
112
-
113
- const validation = await evaluateStable((snapshot) =>
114
- input.policy.evaluate({
115
- kind: "runtime_selection",
116
- availability: snapshot,
117
- processId: current.processId,
118
- selection: current.modelSelection ?? null,
119
- }),
120
- );
121
- if (!validation.ok) {
122
- parkStaleEvaluation();
123
- return;
124
- }
125
- const result = validation.value;
126
- const inheritedInvalid =
127
- !result.ok &&
128
- current.modelSelection.provenance.kind === "inherited" &&
129
- (result.code === "unknown_model_profile" || result.code === "model_profile_not_allowed");
130
- if (inheritedInvalid) {
131
- await projectCurrent();
132
- return;
133
- }
134
- const blockedReason = toFutureExecutionBlockReason(result, input.asOf, current.blockedReason);
135
- if (sameModelPolicyState(current, { ...current, blockedReason })) return;
136
- updateCurrent({ blockedReason });
103
+ // Re-plan the destination and validate against that turn, including pinned payload choices.
104
+ await projectCurrent();
137
105
  });
138
106
  }
139
107
  const reaction = await runFutureExecutionPostCommitEffects(input, effects);
package/src/index.ts CHANGED
@@ -8,4 +8,5 @@ export {
8
8
  type LeitwerkConfig,
9
9
  loadConfig,
10
10
  } from "./config/index.js";
11
+ export { runExtensionBootCheck } from "./extension-boot-check.js";
11
12
  export type { WsFrame } from "./ws/broadcast.js";
@@ -638,8 +638,8 @@ export function createLaunchCoordinator(deps: LaunchCoordinatorDeps): LaunchCoor
638
638
  defaultModelProfileId:
639
639
  eventProfile ?? watcher.launchModelConfig.defaultModelProfileId,
640
640
  },
641
- // Event selections express ticket/user intent. Never silently drop them.
642
- invalidModelConfig: eventProfile ? "reject" : "omit",
641
+ // Keep watcher intent; the affected turn enforces policy before starting.
642
+ invalidModelConfig: "retain",
643
643
  },
644
644
  );
645
645
  return prepared.ok
@@ -212,6 +212,7 @@ export const ExecuteAction = defineOperation<
212
212
  if (input.opts.nextTurnModelProfileId !== null) {
213
213
  const evaluation = ctx.deps.processModelPolicy.evaluate({
214
214
  kind: "runtime_selection",
215
+ target: { kind: "turn", turnId: candidateSelectedTurnId! },
215
216
  availability: ctx.deps.getModelAvailabilitySnapshot(),
216
217
  processId: ctx.process.processId,
217
218
  selection: {
@@ -44,26 +44,24 @@ export const RetryStartup = defineOperation<
44
44
  return reject("retry_target_missing", "Startup retry requires a failed current start");
45
45
  }
46
46
  const id = generateId("tsr");
47
+ // Operator retries validate current inputs; the old failure stays on its record.
48
+ const preparation = {
49
+ code: "model_required" as const,
50
+ safeSummary: "LLM start requires retry preparation",
51
+ };
47
52
  const state: TurnStartRecordState =
48
53
  failed.state.kind === "preparation_failed"
49
- ? {
50
- ...failed.state,
51
- // A new operator retry must validate current inputs; the previous
52
- // failure remains on its original start record.
53
- code: "model_required" as const,
54
- safeSummary: "LLM start requires retry preparation",
55
- }
56
- : failed.state.start.kind === "automatic"
57
- ? { kind: "starting" as const, start: failed.state.start }
54
+ ? { ...failed.state, ...preparation }
55
+ : input.automaticRetry || failed.state.start.kind === "automatic"
56
+ ? { kind: "starting", start: failed.state.start }
58
57
  : {
59
- kind: "preparation_failed" as const,
58
+ kind: "preparation_failed",
60
59
  requestedModelProfileId: failed.state.start.model.profileId,
61
60
  providerOptions: { ...failed.state.start.providerOptions },
62
- code: "model_required" as const,
63
- safeSummary: "LLM start requires retry preparation",
64
61
  ...(failed.state.start.modelSelectionProvenance
65
62
  ? { modelSelectionProvenance: failed.state.start.modelSelectionProvenance }
66
63
  : {}),
64
+ ...preparation,
67
65
  };
68
66
  state.automaticRetry = input.automaticRetry;
69
67
  const writes = createWrites({
@@ -4,10 +4,7 @@ import type {
4
4
  ResolvedTurnStart,
5
5
  TurnStartRecordState,
6
6
  } from "@leitwerk-dev/domain";
7
- import {
8
- filterProviderOptionsForDefinition,
9
- resolveOutcomeContract,
10
- } from "@leitwerk-dev/process-sdk";
7
+ import { resolveOutcomeContract } from "@leitwerk-dev/process-sdk";
11
8
  import { IPC_PROTOCOL_VERSION, WORKER_API_VERSION } from "@leitwerk-dev/worker-protocol";
12
9
  import type { LeitwerkConfig } from "../config/config-types.js";
13
10
  import type { RepositoryBundle } from "../db/repositories.js";
@@ -207,14 +204,40 @@ export async function prepareCreatedTurnStarts(
207
204
 
208
205
  // Resolve the model and required settings without yielding. An edit while the
209
206
  // resource bundle is assembled belongs to the next start, not this snapshot.
210
- const evaluated = deps.processModelPolicy.evaluate({
211
- kind: "process_turn",
212
- process: nextProcess,
213
- turnId: write.input.turnId,
214
- initialSelection: true,
215
- startKind: write.input.startKind,
216
- availability,
217
- });
207
+ const priorState = write.input.state;
208
+ const captured = priorState.automaticRetry
209
+ ? priorState.kind === "preparation_failed"
210
+ ? priorState.requestedModelProfileId && priorState.modelSelectionProvenance
211
+ ? {
212
+ modelProfileId: priorState.requestedModelProfileId,
213
+ provenance: priorState.modelSelectionProvenance,
214
+ }
215
+ : null
216
+ : priorState.kind === "starting" &&
217
+ priorState.start.kind === "llm" &&
218
+ priorState.start.modelSelectionProvenance
219
+ ? {
220
+ modelProfileId: priorState.start.model.profileId,
221
+ provenance: priorState.start.modelSelectionProvenance,
222
+ }
223
+ : null
224
+ : null;
225
+ const evaluated = captured
226
+ ? deps.processModelPolicy.evaluate({
227
+ kind: "runtime_selection",
228
+ target: { kind: "turn", turnId: write.input.turnId },
229
+ processId: nextProcess.processId,
230
+ selection: captured,
231
+ availability,
232
+ })
233
+ : deps.processModelPolicy.evaluate({
234
+ kind: "process_turn",
235
+ process: nextProcess,
236
+ turnId: write.input.turnId,
237
+ initialSelection: true,
238
+ startKind: write.input.startKind,
239
+ availability,
240
+ });
218
241
  if (!evaluated.ok) {
219
242
  const code =
220
243
  evaluated.code === "model_unavailable" ||
@@ -243,6 +266,8 @@ export async function prepareCreatedTurnStarts(
243
266
  Object.assign(nextProcess, patch);
244
267
  Object.assign(writes.processPatch, patch);
245
268
  }
269
+ // Automatic bootstrap recovery reuses the complete prepared execution, not current settings.
270
+ if (captured && priorState.kind === "starting") continue;
246
271
  const provenance =
247
272
  nextProcess.selectedTurnModelKind && nextProcess.selectedTurnModelSource
248
273
  ? {
@@ -303,9 +328,7 @@ export async function prepareCreatedTurnStarts(
303
328
  const recoveryOptions = explicitProviderOptions
304
329
  ? { ...explicitProviderOptions }
305
330
  : retainedProviderId !== null && retainedProviderId !== provider.id
306
- ? {
307
- ...filterProviderOptionsForDefinition(provider.definition.options, retainedOptions),
308
- }
331
+ ? {}
309
332
  : retainedOptions;
310
333
  const optionResult = resolveRegisteredProviderOptions({
311
334
  provider,
@@ -66,13 +66,17 @@ export function prepareProcessModelConfig(input: {
66
66
  else turnConfigs[id] = { ...turnConfigs[id], modelProfileId: config.modelProfileId };
67
67
  }
68
68
  const selections = [
69
- patch.defaultModelProfileId,
70
- ...Object.values(patch.turnConfigs ?? {}).map((config) => config.modelProfileId),
69
+ { id: patch.defaultModelProfileId, target: { kind: "process_default" } as const },
70
+ ...Object.entries(patch.turnConfigs ?? {}).map(([turnId, config]) => ({
71
+ id: config.modelProfileId,
72
+ target: { kind: "turn", turnId } as const,
73
+ })),
71
74
  ];
72
- for (const id of selections) {
75
+ for (const { id, target } of selections) {
73
76
  if (!id) continue;
74
77
  const validation = policy.evaluate({
75
78
  kind: "runtime_selection",
79
+ target,
76
80
  processId: process.processId,
77
81
  availability,
78
82
  selection: {
@@ -1,9 +1,15 @@
1
1
  import { trimToNull } from "@leitwerk-dev/domain";
2
2
  import { isLlmTurnDefinition } from "@leitwerk-dev/process-sdk";
3
+ import { assertValidModelRequirements, compareModelProfileIds } from "@leitwerk-dev/protocol";
3
4
  import type { LeitwerkConfig } from "../config/config-types.js";
4
5
  import type { ProcessActionRegistry } from "../process-action-registry.js";
5
6
  import { getProcessGraph, type ProcessGraphRegistry } from "../process-graph.js";
6
- import type { PolicyProcess, PolicyProfile, PolicySnapshot } from "./types.js";
7
+ import type {
8
+ PolicyProcess,
9
+ PolicyProfile,
10
+ PolicyRequirementLayer,
11
+ PolicySnapshot,
12
+ } from "./types.js";
7
13
 
8
14
  export interface ProcessModelPolicyConfigurationIssue {
9
15
  readonly code: "unknown_llm_turn";
@@ -25,6 +31,10 @@ export function constructPolicySnapshot(input: {
25
31
  config: LeitwerkConfig;
26
32
  processGraphs: ProcessGraphRegistry;
27
33
  processActionRegistry: Pick<ProcessActionRegistry, "getTurnDefinition">;
34
+ capabilities?: (
35
+ providerId: string,
36
+ modelId: string,
37
+ ) => Readonly<Record<string, boolean | "unknown">>;
28
38
  }): PolicySnapshot {
29
39
  const configSnapshot = structuredClone(input.config);
30
40
  const profiles: PolicyProfile[] = configSnapshot.pi.model_profiles.map((profile) => ({
@@ -33,6 +43,9 @@ export function constructPolicySnapshot(input: {
33
43
  modelId: profile.model_id,
34
44
  thinkingLevel: profile.thinking_level ?? "off",
35
45
  providerOptions: profile.provider_options ?? {},
46
+ labels: [...new Set(profile.labels ?? [])].sort(compareModelProfileIds),
47
+ default: profile.default ?? false,
48
+ capabilities: structuredClone(input.capabilities?.(profile.provider, profile.model_id) ?? {}),
36
49
  }));
37
50
  const processIds = new Set([
38
51
  ...input.processGraphs.keys(),
@@ -44,12 +57,50 @@ export function constructPolicySnapshot(input: {
44
57
  ? getProcessGraph(input.processGraphs, processId)
45
58
  : null;
46
59
  const config = configSnapshot.process_configs?.[processId];
60
+ const requirements: PolicyRequirementLayer[] = [];
61
+ const turnRequirements: Record<string, PolicyRequirementLayer[]> = {};
62
+ const add = (
63
+ layers: PolicyRequirementLayer[],
64
+ origin: string,
65
+ value: import("@leitwerk-dev/protocol").ModelRequirements | undefined,
66
+ ) => {
67
+ if (value === undefined) return;
68
+ assertValidModelRequirements(value);
69
+ layers.push({ origin, requirements: structuredClone(value) });
70
+ };
71
+ add(
72
+ requirements,
73
+ `process:${processId}`,
74
+ input.processGraphs.get(processId)?.modelRequirements,
75
+ );
76
+ add(
77
+ requirements,
78
+ `process_configs.${processId}.model_requirements`,
79
+ config?.model_requirements,
80
+ );
47
81
  const llmTurnIds = new Set<string>();
48
82
  const purposeProfileIdsByTurn: Record<string, string> = {};
49
83
  const descriptions: Record<string, string> = {};
50
84
  const pathTypes: Record<string, string> = {};
51
85
  for (const [turnId, turn] of graph?.turns ?? []) {
52
- if (turn.turnType !== "llm") continue;
86
+ const declared = input.processGraphs.get(processId)?.turns.get(turnId)?.definition;
87
+ if (turn.turnType !== "llm") {
88
+ if (declared && "modelRequirements" in declared)
89
+ throw new Error(`Model requirements require an LLM turn: ${processId}/${turnId}`);
90
+ continue;
91
+ }
92
+ const layers: PolicyRequirementLayer[] = [];
93
+ add(
94
+ layers,
95
+ `turn:${processId}/${turnId}`,
96
+ declared?.kind === "llm" ? declared.modelRequirements : undefined,
97
+ );
98
+ add(
99
+ layers,
100
+ `process_configs.${processId}.turn_configs.${turnId}.model_requirements`,
101
+ config?.turn_configs?.[turnId]?.model_requirements,
102
+ );
103
+ turnRequirements[turnId] = layers;
53
104
  llmTurnIds.add(turnId);
54
105
  const definition = input.processActionRegistry.getTurnDefinition(processId, turnId);
55
106
  pathTypes[turnId] =
@@ -70,6 +121,8 @@ export function constructPolicySnapshot(input: {
70
121
  : null;
71
122
  processesById.set(processId, {
72
123
  id: processId,
124
+ requirements,
125
+ turnRequirements,
73
126
  allowedProfileIds: allowed,
74
127
  defaultProfileId: trimToNull(config?.default_model_profile),
75
128
  turnProfileIds: Object.fromEntries(
@@ -101,7 +154,12 @@ export function constructPolicySnapshot(input: {
101
154
  profilesById: new Map(profiles.map((profile) => [profile.id, profile])),
102
155
  processesById,
103
156
  workerStaticConfig: {
104
- pi: configSnapshot.pi,
157
+ pi: {
158
+ ...configSnapshot.pi,
159
+ model_profiles: configSnapshot.pi.model_profiles
160
+ .map(({ labels: _labels, default: _default, ...profile }) => profile)
161
+ .sort((a, b) => compareModelProfileIds(a.id, b.id)),
162
+ },
105
163
  workers: configSnapshot.workers,
106
164
  processPi: Object.fromEntries(
107
165
  Object.entries(configSnapshot.process_configs ?? {}).map(([id, value]) => [