@leitwerk-dev/server 0.4.0 → 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 (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
@@ -1,4 +1,5 @@
1
1
  import type { ProcessInstance } from "@leitwerk-dev/domain";
2
+ import { generateId } from "../db/repo-helpers.js";
2
3
  import type { PostCommitEffect } from "../effects/post-commit-effect.js";
3
4
  import type { ModelStatusCacheSnapshot } from "../model-providers/model-status-cache.js";
4
5
  import {
@@ -300,6 +301,18 @@ export async function record<TOp extends OperationSpec<string, OperationInputBas
300
301
  };
301
302
  }
302
303
 
304
+ for (const write of decision.writes.turnStartWrites) {
305
+ if (write.kind !== "create") continue;
306
+ write.input.id ??= generateId("tsr");
307
+ const original = baselineWrites.turnStartWrites.find(
308
+ (entry) => entry.kind === "create" && entry.input.id === write.input.id,
309
+ );
310
+ write.input.state.automaticRetry =
311
+ original?.kind === "create" && original.input.state.automaticRetry
312
+ ? original.input.state.automaticRetry
313
+ : { episodeStartRecordId: write.input.id, starts: 1, nextRetryAt: null };
314
+ }
315
+
303
316
  let commit: RecordCommit;
304
317
  try {
305
318
  commit = commitWrites(getRecordDeps(deps), input.instanceId, decision.writes);
@@ -1,5 +1,6 @@
1
1
  import type {
2
2
  Actor,
3
+ AutomaticStartupRecoverySummary,
3
4
  ProcessInput,
4
5
  ProcessInstance,
5
6
  ProcessLifecycleStatus,
@@ -326,6 +327,8 @@ export interface ProcessEngine {
326
327
  instanceId: string,
327
328
  startRecordId: string,
328
329
  opts?: {
330
+ /** @internal */
331
+ actor?: Actor;
329
332
  /** @internal */
330
333
  nextTurnModelProfileId?: string | null;
331
334
  /** @internal */
@@ -337,6 +340,15 @@ export interface ProcessEngine {
337
340
  startRecordId: string;
338
341
  }>
339
342
  >;
343
+ /** Automatic recovery never retries accepted turns or resets the startup budget. @internal */
344
+ retryStartupAutomatically(
345
+ instanceId: string,
346
+ startRecordId: string,
347
+ opts?: {
348
+ /** @internal */
349
+ availabilityCause?: "availability_transition" | "startup_reconciliation";
350
+ },
351
+ ): Promise<EngineResult<AutomaticStartupRecoverySummary>>;
340
352
  /** @internal */
341
353
  continueFailedTurn(
342
354
  instanceId: string,
@@ -201,9 +201,8 @@ export function commitWrites(
201
201
  }
202
202
  for (const write of writes.turnStartWrites) {
203
203
  if (write.kind === "create") repos.turnStarts.create(write.input);
204
- else if (!repos.turnStarts.compareAndSetState(write)) {
204
+ else if (!repos.turnStarts.compareAndSetState(write))
205
205
  throw new Error(`Turn start '${write.id}' changed before acceptance`);
206
- }
207
206
  }
208
207
  const committedLeafOutcomeSnapshots: ProcessLeafOutcomeSnapshot[] = [];
209
208
  const committedAnnotationChanges: Array<{
@@ -11,7 +11,7 @@ import type { ServerProcessModelPolicy } from "./process-model-policy/index.js";
11
11
  export async function recoverModelAvailabilityFailures(input: {
12
12
  processes: Pick<RepositoryBundle["processes"], "listAll">;
13
13
  turnStarts: Pick<RepositoryBundle["turnStarts"], "getById">;
14
- commands: Pick<ProcessEngine, "retryStartup">;
14
+ commands: Pick<ProcessEngine, "retryStartupAutomatically">;
15
15
  policy: ServerProcessModelPolicy;
16
16
  availability: ModelStatusCacheSnapshot;
17
17
  cause: "availability_transition" | "startup_reconciliation";
@@ -42,9 +42,11 @@ export async function recoverModelAvailabilityFailures(input: {
42
42
  availability: input.availability,
43
43
  });
44
44
  if (!evaluation.ok || !evaluation.selection) continue;
45
- const result = await input.commands.retryStartup(process.id, start.id);
46
- if (result.ok) recovered += 1;
47
- else if (result.code !== "stale_turn_start" && result.code !== "stale_startup_target") {
45
+ const result = await input.commands.retryStartupAutomatically(process.id, start.id, {
46
+ availabilityCause: input.cause,
47
+ });
48
+ if (result.ok && result.data.status === "retried") recovered += 1;
49
+ else if (!result.ok && result.code !== "stale_turn_start") {
48
50
  input.logger?.warn(
49
51
  { instanceId: process.id, startRecordId: start.id, code: result.code },
50
52
  "Model availability recovery was rejected",
@@ -0,0 +1,106 @@
1
+ import type { DashboardResponseBody } from "@leitwerk-dev/protocol/http-contracts";
2
+ import type { FastifyInstance } from "fastify";
3
+ import {
4
+ buildDashboardModelIssues,
5
+ type DashboardModelIssueDeps,
6
+ } from "../dashboard-model-issues.js";
7
+ import type { RouteDeps } from "./processes.js";
8
+
9
+ /** @internal */
10
+ export type DashboardRouteDeps = DashboardModelIssueDeps &
11
+ Pick<RouteDeps, "turnSummaries" | "skillCatalog">;
12
+
13
+ /** Aggregate each accepted LLM turn once, including active, failed and retry branches. @internal */
14
+ export function aggregateDashboardCosts(
15
+ rows: readonly {
16
+ /** @internal */ providerId: string | null;
17
+ /** @internal */ modelId: string | null;
18
+ /** @internal */ costUsd: number | null;
19
+ }[],
20
+ ): DashboardResponseBody["costs"] {
21
+ const groups = new Map<string, DashboardResponseBody["costs"]["byModel"][number]>();
22
+ let totalUsd = 0;
23
+ let pricedTurnCount = 0;
24
+ for (const row of rows) {
25
+ if (typeof row.costUsd !== "number" || !Number.isFinite(row.costUsd)) continue;
26
+ const providerId = row.providerId && row.modelId ? row.providerId : null;
27
+ const modelId = providerId ? row.modelId : null;
28
+ const key = JSON.stringify([providerId, modelId]);
29
+ const group = groups.get(key) ?? { providerId, modelId, costUsd: 0, turnCount: 0 };
30
+ group.turnCount += 1;
31
+ group.costUsd += row.costUsd;
32
+ totalUsd += row.costUsd;
33
+ pricedTurnCount += 1;
34
+ groups.set(key, group);
35
+ }
36
+ const missingCostTurnCount = rows.length - pricedTurnCount;
37
+ return {
38
+ totalUsd: rows.length > 0 && pricedTurnCount === 0 ? null : totalUsd,
39
+ totalLlmTurnCount: rows.length,
40
+ pricedTurnCount,
41
+ missingCostTurnCount,
42
+ isPartial: missingCostTurnCount > 0,
43
+ byModel: [...groups.values()].sort(
44
+ (a, b) =>
45
+ b.costUsd - a.costUsd ||
46
+ (a.providerId ?? "").localeCompare(b.providerId ?? "") ||
47
+ (a.modelId ?? "").localeCompare(b.modelId ?? ""),
48
+ ),
49
+ };
50
+ }
51
+
52
+ /** @internal */
53
+ export function buildDashboard(deps: DashboardRouteDeps): DashboardResponseBody {
54
+ const items = [...deps.processGraphs.values()]
55
+ .map((process) => ({ id: process.id, name: process.displayName }))
56
+ .sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
57
+ const watchers = (deps.processWatchers?.listAll() ?? [])
58
+ .map((watcher) => ({
59
+ id: `${watcher.processId}.${watcher.watcherId}`,
60
+ name: watcher.watcherLabel,
61
+ enabled: watcher.enabled,
62
+ }))
63
+ .sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
64
+ const skills = deps.skillCatalog?.list().installedSkills ?? [];
65
+ const bundled = skills.filter((skill) => skill.registrationKind === "bundled").length;
66
+ const lifecycle: Record<string, number> = Object.fromEntries(
67
+ deps.processes.countOverviewByLifecycle({}).map((row) => [row.lifecycleStatus, row.value]),
68
+ );
69
+ const processTotal = Object.values(lifecycle).reduce((sum, count) => sum + count, 0);
70
+ lifecycle.running = (lifecycle.active ?? 0) + (lifecycle.discovered ?? 0);
71
+ const statuses = ["running", "waiting", "error", "completed", "aborted"] as const;
72
+ return {
73
+ generatedAt: new Date().toISOString(),
74
+ definitions: { total: items.length, items },
75
+ watchers: {
76
+ total: watchers.length,
77
+ enabled: watchers.filter((watcher) => watcher.enabled).length,
78
+ items: watchers,
79
+ },
80
+ skills: { total: skills.length, installed: skills.length - bundled, bundled },
81
+ processes: {
82
+ total: processTotal,
83
+ byStatus: statuses.map((status) => ({ status, count: lifecycle[status] ?? 0 })),
84
+ byDefinition: deps.processes
85
+ .listOverviewProcessTypes({ status: "all" })
86
+ .map((row) => ({
87
+ processId: row.processId,
88
+ name: deps.processGraphs.get(row.processId)?.displayName ?? row.processId,
89
+ count: row.value,
90
+ }))
91
+ .sort(
92
+ (a, b) =>
93
+ b.count - a.count ||
94
+ a.name.localeCompare(b.name) ||
95
+ a.processId.localeCompare(b.processId),
96
+ ),
97
+ },
98
+ costs: aggregateDashboardCosts(deps.turnSummaries.listDashboardCosts()),
99
+ configuration: { issues: buildDashboardModelIssues(deps) },
100
+ };
101
+ }
102
+
103
+ /** @internal */
104
+ export function registerDashboardRoutes(app: FastifyInstance, deps: DashboardRouteDeps): void {
105
+ app.get("/api/dashboard", async () => buildDashboard(deps));
106
+ }
@@ -174,7 +174,7 @@ export function registerProcessActionRoutes(
174
174
  const result = await deps.processEngine.retryStartup(
175
175
  req.params.instanceId,
176
176
  req.params.startRecordId,
177
- Object.keys(options).length > 0 ? options : undefined,
177
+ { ...options, actor: resolveActor(req) },
178
178
  );
179
179
  deps.launchCoordinator.refresh(req.params.instanceId);
180
180
  if (!result.ok) {
@@ -91,8 +91,23 @@ interface ProcessSettingsPreview {
91
91
  /** @internal */
92
92
  error: string | null;
93
93
  }
94
+ /** Read-only model references without repository discovery or choice providers. @internal */
95
+ export interface ScopedModelReference {
96
+ /** @internal */
97
+ key: string;
98
+ /** @internal */
99
+ label: string;
100
+ /** Null for extension-defined defaults. @internal */
101
+ subjectId: string | null;
102
+ /** @internal */
103
+ modelProfileId: string | null;
104
+ /** Invalid schema, version, or override mode; never includes raw values. @internal */
105
+ invalid: boolean;
106
+ }
94
107
  /** @internal */
95
108
  export interface ScopedSettingsService extends ScopedSettingsResolver {
109
+ /** @internal */
110
+ modelReferences(): ScopedModelReference[];
96
111
  /** @internal */
97
112
  capture(
98
113
  process: SubjectProcess,
@@ -625,6 +640,52 @@ export function createScopedSettingsService(input: {
625
640
  }
626
641
  discoverLocal();
627
642
  return {
643
+ modelReferences() {
644
+ const references: ScopedModelReference[] = [];
645
+ const append = (
646
+ definition: SettingDefinition,
647
+ value: unknown,
648
+ subjectId: string | null,
649
+ label: string,
650
+ invalid = false,
651
+ ) => {
652
+ let modelProfileId: string | null = null;
653
+ try {
654
+ const parsed = definition.schema.parse(value);
655
+ if (parsed !== null && (typeof parsed !== "string" || !parsed.trim())) invalid = true;
656
+ else modelProfileId = typeof parsed === "string" ? parsed.trim() : null;
657
+ } catch {
658
+ invalid = true;
659
+ }
660
+ if (invalid || modelProfileId !== null)
661
+ references.push({ key: definition.key, label, subjectId, modelProfileId, invalid });
662
+ };
663
+ for (const { definition } of definitions.values()) {
664
+ if (definition.form.control === "model")
665
+ append(
666
+ definition,
667
+ definition.defaultValue,
668
+ null,
669
+ `${definition.form.label} (code default)`,
670
+ );
671
+ }
672
+ const subjects = new Map(
673
+ repos.scopedSettings.listSubjects().map((subject) => [subject.id, subject]),
674
+ );
675
+ for (const override of repos.scopedSettings.listOverrides()) {
676
+ const definition = definitions.get(override.key)?.definition;
677
+ const subject = subjects.get(override.subjectId);
678
+ if (override.reset || !subject || definition?.form.control !== "model") continue;
679
+ append(
680
+ definition,
681
+ override.value,
682
+ subject.id,
683
+ `${subject.label}: ${definition.form.label}`,
684
+ override.schemaVersion !== definition.schemaVersion || override.mode !== "replace",
685
+ );
686
+ }
687
+ return references;
688
+ },
628
689
  async overview(scopeType) {
629
690
  const subjects = listScopes().subjects.filter(
630
691
  (subject) => subject.scopeType === scopeType && subject.hasSettings,
@@ -8,6 +8,7 @@ import type { ExtensionUiCatalog } from "../extension-ui/catalog.js";
8
8
  import type { IntegrationToolRegistry } from "../integration-tool-registry.js";
9
9
  import type { ProcessSessionSnapshotStore } from "../process-session-store.js";
10
10
  import type { ResultImageStore } from "../result-image-store.js";
11
+ import { registerDashboardRoutes } from "../routes/dashboard.js";
11
12
  import { registerInternalSessionTransferExportRoutes } from "../routes/internal-session-transfer-exports.js";
12
13
  import { registerInternalWorkerSessionSnapshotRoutes } from "../routes/internal-worker-session-snapshot.js";
13
14
  import { type RouteDeps, registerProcessRoutes } from "../routes/processes.js";
@@ -76,6 +77,10 @@ export function registerHttp(input: {
76
77
  store: input.resultImages,
77
78
  });
78
79
  registerProcessRoutes(input.app, input.deps);
80
+ registerDashboardRoutes(input.app, {
81
+ ...input.deps,
82
+ processWatchers: input.processWatcherService,
83
+ });
79
84
  if (input.deps.topicWiki)
80
85
  registerTopicWikiRoutes(input.app, input.deps.topicWiki, actorForRequest);
81
86
  if (input.deps.scopedSettingsService)
@@ -3,8 +3,8 @@ import path from "node:path";
3
3
  import type { LoadedExtensionModule } from "@leitwerk-dev/extension-runtime";
4
4
  import { parseSkillPackManifest, type SkillRevisionProvenance } from "@leitwerk-dev/protocol";
5
5
  import { createCanonicalPiResourceBundle } from "@leitwerk-dev/worker-protocol";
6
- import { parse as parseYaml } from "yaml";
7
6
  import { ResourceCollector } from "../pi-resources/resource-collector.js";
7
+ import { skillFrontmatter } from "./skill-frontmatter.js";
8
8
  import type { ImportedSkill } from "./source-importer.js";
9
9
 
10
10
  /** @internal */
@@ -71,11 +71,8 @@ export async function importExtensionSkills(
71
71
  { forbiddenNames: new Set([".git", ".leitwerk-skill.json"]) },
72
72
  );
73
73
  const markdown = collector.files.get(`skills/${skill.id}/SKILL.md`);
74
- const header =
75
- markdown &&
76
- /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(Buffer.from(markdown).toString("utf8"));
77
- const metadata = header ? parseYaml(header[1]) : null;
78
- if (metadata?.name !== skill.id || metadata.description !== skill.description) {
74
+ const metadata = markdown ? skillFrontmatter(Buffer.from(markdown).toString("utf8")) : null;
75
+ if (metadata?.name !== skill.id || metadata?.description !== skill.description) {
79
76
  throw new Error(`Skill '${skill.id}' frontmatter does not match its pack manifest`);
80
77
  }
81
78
  // Include dependency/provenance changes in revision identity even when prose is unchanged.
@@ -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,7 +13,7 @@ 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
17
  }
18
18
 
19
19
  /** @internal */
@@ -21,7 +21,7 @@ export function skillMetadata(markdown: string): {
21
21
  name: string | null;
22
22
  description: string | null;
23
23
  } {
24
- const metadata = frontmatter(markdown);
24
+ const metadata = skillFrontmatter(markdown);
25
25
  const text = (key: string): string | null => {
26
26
  const value = metadata?.[key];
27
27
  return typeof value === "string" ? value.trim() || null : null;
@@ -10,6 +10,7 @@ import {
10
10
  } from "@leitwerk-dev/worker-protocol";
11
11
  import type { SkillRepositoryConfig } from "../config/config-types.js";
12
12
  import { ResourceCollector, SKILL_RESOURCE_OWNER } from "../pi-resources/resource-collector.js";
13
+ import { skillMetadata } from "./skill-frontmatter.js";
13
14
  import { SAFE_SKILL_ID_PATTERN } from "./skill-id.js";
14
15
 
15
16
  const execFileAsync = promisify(execFile);
@@ -81,16 +82,6 @@ async function checkoutGitSource(
81
82
  return { root, commit: stdout.trim() };
82
83
  }
83
84
 
84
- function metadataValue(markdown: string, key: string): string | null {
85
- if (!markdown.startsWith("---")) return null;
86
- const end = markdown.indexOf("\n---", 3);
87
- if (end < 0) return null;
88
- const match = markdown
89
- .slice(3, end)
90
- .match(new RegExp(`^${key}:\\s*["']?([^\\n"']+)["']?\\s*$`, "m"));
91
- return match?.[1]?.trim() || null;
92
- }
93
-
94
85
  function fallbackLabel(id: string): string {
95
86
  return id
96
87
  .split(/[-_.]+/)
@@ -152,13 +143,13 @@ export async function importSkillRepository(
152
143
  const skills: ImportedRepositorySkill[] = [];
153
144
  for (const skillRoot of skillRoots) {
154
145
  const skillId = path.basename(skillRoot);
155
- const markdown = await readFile(path.join(skillRoot, "SKILL.md"), "utf8");
146
+ const metadata = skillMetadata(await readFile(path.join(skillRoot, "SKILL.md"), "utf8"));
156
147
  const imported = await importSkillDirectory(
157
148
  skillRoot,
158
149
  {
159
150
  id: skillId,
160
- label: metadataValue(markdown, "name") ?? fallbackLabel(skillId),
161
- description: metadataValue(markdown, "description") ?? undefined,
151
+ label: metadata.name ?? fallbackLabel(skillId),
152
+ description: metadata.description ?? undefined,
162
153
  },
163
154
  checkout.commit,
164
155
  );
@@ -14,6 +14,7 @@ import type {
14
14
  } from "@leitwerk-dev/protocol";
15
15
  import { completeLaunchWhenReady, failLaunchRun } from "./launch-pipeline.js";
16
16
  import { pendingTurnWait } from "./process-engine/turn-wait-state.js";
17
+ import { automaticStartupRecovery, startupRetryState } from "./startup-retry-policy.js";
17
18
 
18
19
  export interface StartupEvidenceInput {
19
20
  process: ProcessInstance;
@@ -51,16 +52,12 @@ function validObservedAt(value: string | null | undefined, notBefore: string): s
51
52
 
52
53
  export function buildStartupRecovery(
53
54
  process: ProcessInstance,
54
- turnStartsById:
55
- | ReadonlyMap<string, TurnStartRecord>
56
- | { getById(id: string): TurnStartRecord | null },
55
+ turnStartsById: ReadonlyMap<string, TurnStartRecord>,
56
+ events: readonly ProcessEvent[] = [],
57
57
  ): StartupRecoverySummary | null {
58
58
  if (process.lifecycleStatus !== "error" || process.currentExecution?.kind !== "worker_start")
59
59
  return null;
60
- const start =
61
- "getById" in turnStartsById
62
- ? turnStartsById.getById(process.currentExecution.id)
63
- : turnStartsById.get(process.currentExecution.id);
60
+ const start = turnStartsById.get(process.currentExecution.id);
64
61
  if (
65
62
  !start ||
66
63
  (start.state.kind !== "preparation_failed" && start.state.kind !== "bootstrap_failed")
@@ -68,6 +65,10 @@ export function buildStartupRecovery(
68
65
  return null;
69
66
  const resolvedStart = "start" in start.state ? start.state.start : null;
70
67
  return {
68
+ automaticRetry: automaticStartupRecovery(
69
+ start,
70
+ startupRetryState(start, [...turnStartsById.values()], events),
71
+ ),
71
72
  startRecordId: start.id,
72
73
  kind: start.state.kind,
73
74
  action: start.state.kind === "bootstrap_failed" ? "retry_startup" : "choose_model",
@@ -266,7 +267,7 @@ export function buildStartupEvidence(input: StartupEvidenceInput): StartupEviden
266
267
  : {}),
267
268
  currentAttempt,
268
269
  authoritativeAttemptId: authoritative?.startRecordId ?? null,
269
- recovery: buildStartupRecovery(input.process, turnStartsById),
270
+ recovery: buildStartupRecovery(input.process, turnStartsById, input.events),
270
271
  };
271
272
  }
272
273
 
@@ -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
+ }
@@ -641,7 +641,29 @@ export function createWorkerSupervisor(deps: SupervisorDeps): WorkerSupervisor {
641
641
  pendingCleanup.delete(instanceId);
642
642
  const leaseBeforeExit = safeGetLeaseByInstance(instanceId);
643
643
  const startupTimedOut = startupTimedOutWorkers.delete(timedOutWorkerKey(instanceId, workerId));
644
- if (isLiveWorkerLease(leaseBeforeExit, workerId)) {
644
+ // Graceful runtime termination may report cleanup before the exit arrives.
645
+ // Cleanup alone does not complete an accepted turn's durable outcome.
646
+ const processBeforeExit = safeGetProcessById(instanceId);
647
+ const startBeforeExit =
648
+ processBeforeExit?.currentExecution?.kind === "worker_start"
649
+ ? deps.turnStarts.getById(processBeforeExit.currentExecution.id)
650
+ : null;
651
+ const acceptedTurnBeforeExit =
652
+ startBeforeExit?.state.kind === "accepted"
653
+ ? deps.turnRecords.getById(startBeforeExit.state.turnRecordId)
654
+ : null;
655
+ const unfinishedOwningTurn =
656
+ leaseBeforeExit?.workerId === workerId &&
657
+ ["draining", "cleanup"].includes(leaseBeforeExit.state) &&
658
+ processBeforeExit?.lifecycleStatus === "active" &&
659
+ startBeforeExit?.state.kind === "accepted" &&
660
+ startBeforeExit.state.acceptedWorkerLeaseId === leaseBeforeExit.id &&
661
+ startBeforeExit.instanceId === instanceId &&
662
+ acceptedTurnBeforeExit?.instanceId === instanceId &&
663
+ acceptedTurnBeforeExit.turnStartRecordId === startBeforeExit.id &&
664
+ acceptedTurnBeforeExit.acceptedWorkerLeaseId === leaseBeforeExit.id &&
665
+ acceptedTurnBeforeExit.status === "running";
666
+ if (isLiveWorkerLease(leaseBeforeExit, workerId) || unfinishedOwningTurn) {
645
667
  const diagnostics = formatWorkerExitDiagnostics(info);
646
668
  emitServerObservedWorkerFailure(instanceId, workerId, {
647
669
  errorCode: startupTimedOut
@@ -1,8 +0,0 @@
1
- import {
2
- createAppContext
3
- } from "./chunk-FPMDWQF7.js";
4
- import "./chunk-MBHRCQFE.js";
5
- export {
6
- createAppContext
7
- };
8
- //# sourceMappingURL=app-JM4CBTND.js.map