@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
@@ -500,6 +500,7 @@ var configSchema = v.looseObject({
500
500
  worker_service_account: v.optional(v.string()),
501
501
  image_preload: v.optional(v.strictObject({ enabled: v.boolean() })),
502
502
  process_volume: v.looseObject({
503
+ reclaim_on_close: v.optional(v.boolean()),
503
504
  storage_class_name: v.optional(v.string()),
504
505
  pre_provision: v.optional(
505
506
  v.strictObject({ count: v.pipe(v.number(), v.integer(), v.minValue(0)) })
@@ -1143,6 +1144,7 @@ function getDefaultConfig() {
1143
1144
  default_worker_runtime_profile: "generic",
1144
1145
  worker_service_account: "leitwerk-worker",
1145
1146
  process_volume: {
1147
+ reclaim_on_close: false,
1146
1148
  size: "20Gi",
1147
1149
  access_modes: ["ReadWriteOnce"],
1148
1150
  mount_path: "/state"
@@ -2275,8 +2277,8 @@ function splitCreateTableDefinitions(body) {
2275
2277
  definitions.push(body.slice(start));
2276
2278
  return definitions;
2277
2279
  }
2278
- function normalizeCreateTableSql(sql11) {
2279
- const compact = sql11.toLowerCase().replace(/create\s+table\s+if\s+not\s+exists/g, "create table").replace(/\s+/g, "").trim();
2280
+ function normalizeCreateTableSql(sql12) {
2281
+ const compact = sql12.toLowerCase().replace(/create\s+table\s+if\s+not\s+exists/g, "create table").replace(/\s+/g, "").trim();
2280
2282
  const openingParenthesis = compact.indexOf("(");
2281
2283
  const closingParenthesis = compact.lastIndexOf(")");
2282
2284
  if (openingParenthesis < 0 || closingParenthesis <= openingParenthesis) return compact;
@@ -2284,8 +2286,8 @@ function normalizeCreateTableSql(sql11) {
2284
2286
  const definitions = splitCreateTableDefinitions(body).sort();
2285
2287
  return `${compact.slice(0, openingParenthesis + 1)}${definitions.join(",")}${compact.slice(closingParenthesis)}`;
2286
2288
  }
2287
- function normalizeSchemaSql(sql11) {
2288
- return normalizeCreateTableSql(sql11).replace(/create(unique)?indexifnotexists/g, "create$1index");
2289
+ function normalizeSchemaSql(sql12) {
2290
+ return normalizeCreateTableSql(sql12).replace(/create(unique)?indexifnotexists/g, "create$1index");
2289
2291
  }
2290
2292
  function assertCompatibleTableSchema(sqlite, table, sqlitePath) {
2291
2293
  const tableName = getTableName(table);
@@ -3486,9 +3488,20 @@ function createStartupObservationRepo(db) {
3486
3488
  }
3487
3489
 
3488
3490
  // src/db/turn-summary-repo.ts
3489
- import { and as and4, eq as eq6, inArray as inArray2 } from "drizzle-orm";
3491
+ import { and as and4, eq as eq6, inArray as inArray2, sql as sql3 } from "drizzle-orm";
3490
3492
  function createTurnSummaryRepo(db) {
3491
3493
  return {
3494
+ /** Dashboard projections never load assistant text, event payloads or session files. @internal */
3495
+ listDashboardCosts() {
3496
+ return db.select({
3497
+ /** @internal */
3498
+ providerId: sql3`case when json_extract(${turnStartRecords.stateJson}, '$.kind') = 'accepted' then json_extract(${turnStartRecords.stateJson}, '$.start.model.providerId') end`,
3499
+ /** @internal */
3500
+ modelId: sql3`case when json_extract(${turnStartRecords.stateJson}, '$.kind') = 'accepted' then json_extract(${turnStartRecords.stateJson}, '$.start.model.modelId') end`,
3501
+ /** @internal */
3502
+ costUsd: sql3`json_extract(${turnSummaries.summaryJson}, '$.usage.cost.total')`
3503
+ }).from(turnRecords).leftJoin(turnSummaries, eq6(turnSummaries.turnRecordId, turnRecords.id)).leftJoin(turnStartRecords, eq6(turnStartRecords.id, turnRecords.turnStartRecordId)).where(eq6(turnRecords.turnType, "llm")).all();
3504
+ },
3492
3505
  /** @internal */
3493
3506
  get(turnRecordId) {
3494
3507
  const row = db.select().from(turnSummaries).where(eq6(turnSummaries.turnRecordId, turnRecordId)).get();
@@ -3651,15 +3664,15 @@ function createExternalWriteLogRepo(db) {
3651
3664
  }
3652
3665
 
3653
3666
  // src/db/future-execution-repo.ts
3654
- import { and as and6, asc as asc2, count, desc as desc3, eq as eq9, inArray as inArray3, lte, or, sql as sql3 } from "drizzle-orm";
3667
+ import { and as and6, asc as asc2, count, desc as desc3, eq as eq9, inArray as inArray3, lte, or, sql as sql4 } from "drizzle-orm";
3655
3668
  function overviewPredicates(input) {
3656
3669
  const predicates = [eq9(futureExecutions.kind, "launch")];
3657
3670
  if (input.status === "needs_attention") {
3658
- predicates.push(sql3`${futureExecutions.blockedReasonJson} is not null`);
3671
+ predicates.push(sql4`${futureExecutions.blockedReasonJson} is not null`);
3659
3672
  } else if (input.status === "scheduled") {
3660
- predicates.push(sql3`${futureExecutions.blockedReasonJson} is null`);
3673
+ predicates.push(sql4`${futureExecutions.blockedReasonJson} is null`);
3661
3674
  } else if (input.status && input.status !== "all") {
3662
- predicates.push(sql3`0 = 1`);
3675
+ predicates.push(sql4`0 = 1`);
3663
3676
  }
3664
3677
  const processType = input.processType?.trim();
3665
3678
  if (processType) {
@@ -3667,12 +3680,12 @@ function overviewPredicates(input) {
3667
3680
  }
3668
3681
  for (const [index2, pattern] of sqliteLikePatterns(input.query).entries()) {
3669
3682
  const matchingLauncherIds = input.matchingLauncherIdsByTerm?.[index2] ?? [];
3670
- const launcherMatch = matchingLauncherIds.length > 0 ? inArray3(futureExecutions.launcherId, [...matchingLauncherIds]) : sql3`0 = 1`;
3683
+ const launcherMatch = matchingLauncherIds.length > 0 ? inArray3(futureExecutions.launcherId, [...matchingLauncherIds]) : sql4`0 = 1`;
3671
3684
  predicates.push(
3672
3685
  or(
3673
- sql3`lower(${futureExecutions.payloadJson}) LIKE ${pattern} ESCAPE '\\'`,
3674
- sql3`lower(${futureExecutions.processId}) LIKE ${pattern} ESCAPE '\\'`,
3675
- sql3`lower(coalesce(${futureExecutions.id}, '')) LIKE ${pattern} ESCAPE '\\'`,
3686
+ sql4`lower(${futureExecutions.payloadJson}) LIKE ${pattern} ESCAPE '\\'`,
3687
+ sql4`lower(${futureExecutions.processId}) LIKE ${pattern} ESCAPE '\\'`,
3688
+ sql4`lower(coalesce(${futureExecutions.id}, '')) LIKE ${pattern} ESCAPE '\\'`,
3676
3689
  launcherMatch
3677
3690
  )
3678
3691
  );
@@ -3780,13 +3793,13 @@ function createFutureExecutionRepo(db) {
3780
3793
  /** @internal */
3781
3794
  listOverviewWindow(input) {
3782
3795
  const fallbackCases = Object.entries(input.launcherFallbackTitles).map(
3783
- ([launcherId, title2]) => sql3`when ${launcherId} then ${title2}`
3796
+ ([launcherId, title2]) => sql4`when ${launcherId} then ${title2}`
3784
3797
  );
3785
- const unknownLauncherFallback = sql3`case
3798
+ const unknownLauncherFallback = sql4`case
3786
3799
  when json_valid(${futureExecutions.payloadJson}) then ${futureExecutions.processId}
3787
3800
  else coalesce(${futureExecutions.launcherId}, ${futureExecutions.processId}) end`;
3788
- const launcherFallback = fallbackCases.length > 0 ? sql3`case ${futureExecutions.launcherId} ${sql3.join(fallbackCases, sql3.raw(" "))} else ${unknownLauncherFallback} end` : unknownLauncherFallback;
3789
- const title = sql3`coalesce(
3801
+ const launcherFallback = fallbackCases.length > 0 ? sql4`case ${futureExecutions.launcherId} ${sql4.join(fallbackCases, sql4.raw(" "))} else ${unknownLauncherFallback} end` : unknownLauncherFallback;
3802
+ const title = sql4`coalesce(
3790
3803
  case when json_valid(${futureExecutions.payloadJson})
3791
3804
  then nullif(trim(json_extract(${futureExecutions.payloadJson}, '$.launchPlan.processInput.title')), '') end,
3792
3805
  case when json_valid(${futureExecutions.payloadJson})
@@ -3815,7 +3828,7 @@ function createFutureExecutionRepo(db) {
3815
3828
  return db.select().from(futureExecutions).where(
3816
3829
  and6(
3817
3830
  lte(futureExecutions.nextRunAt, asOf),
3818
- sql3`${futureExecutions.blockedReasonJson} is null`
3831
+ sql4`${futureExecutions.blockedReasonJson} is null`
3819
3832
  )
3820
3833
  ).orderBy(asc2(futureExecutions.nextRunAt), asc2(futureExecutions.createdAt)).all().map(rowToFutureExecution);
3821
3834
  },
@@ -3825,7 +3838,7 @@ function createFutureExecutionRepo(db) {
3825
3838
  and6(
3826
3839
  lte(futureExecutions.nextRunAt, asOf),
3827
3840
  eq9(futureExecutions.scheduleKind, "cron"),
3828
- sql3`${futureExecutions.blockedReasonJson} is not null`
3841
+ sql4`${futureExecutions.blockedReasonJson} is not null`
3829
3842
  )
3830
3843
  ).orderBy(asc2(futureExecutions.nextRunAt), asc2(futureExecutions.createdAt)).all().map(rowToFutureExecution);
3831
3844
  },
@@ -4208,7 +4221,7 @@ function createPendingExternalSourceFireRepo(db) {
4208
4221
 
4209
4222
  // src/db/process-event-repo.ts
4210
4223
  import { applyEventToCompactTurnSummary, emptyCompactTurnSummary } from "@leitwerk-dev/protocol";
4211
- import { and as and11, asc as asc6, desc as desc5, eq as eq14, getTableColumns, gte, inArray as inArray5, like, sql as sql4 } from "drizzle-orm";
4224
+ import { and as and11, asc as asc6, desc as desc5, eq as eq14, getTableColumns, gte, inArray as inArray5, like, sql as sql5 } from "drizzle-orm";
4212
4225
  function rowToProcessEvent(row) {
4213
4226
  return {
4214
4227
  id: row.id,
@@ -4263,7 +4276,7 @@ function createProcessEventRepo(db) {
4263
4276
  const data = processEvents.data;
4264
4277
  return db.select({
4265
4278
  ...getTableColumns(processEvents),
4266
- data: sql4`json_object(
4279
+ data: sql5`json_object(
4267
4280
  'turnRecordId', json_extract(${data}, '$.turnRecordId'),
4268
4281
  'turnId', json_extract(${data}, '$.turnId'),
4269
4282
  'outcome', json_extract(${data}, '$.outcome'),
@@ -4294,7 +4307,7 @@ function createProcessEventRepo(db) {
4294
4307
  const id = generateId("evt");
4295
4308
  const ts = now();
4296
4309
  const values = {
4297
- eventSequence: (db.select({ sequence: sql4`coalesce(max(${processEvents.eventSequence}), 0)` }).from(processEvents).get()?.sequence ?? 0) + 1,
4310
+ eventSequence: (db.select({ sequence: sql5`coalesce(max(${processEvents.eventSequence}), 0)` }).from(processEvents).get()?.sequence ?? 0) + 1,
4298
4311
  turnRecordId: typeof input.data?.turnRecordId === "string" ? input.data.turnRecordId : null,
4299
4312
  id,
4300
4313
  instanceId: input.instanceId,
@@ -4523,7 +4536,7 @@ function createProcessInputRepo(db) {
4523
4536
  import {
4524
4537
  isProcessSelectedTurnModelSource
4525
4538
  } from "@leitwerk-dev/domain";
4526
- import { and as and13, asc as asc8, count as count2, desc as desc6, eq as eq17, inArray as inArray6, notInArray as notInArray2, or as or2, sql as sql5 } from "drizzle-orm";
4539
+ import { and as and13, asc as asc8, count as count2, desc as desc6, eq as eq17, inArray as inArray6, notInArray as notInArray2, or as or2, sql as sql6 } from "drizzle-orm";
4527
4540
 
4528
4541
  // src/launch-title.ts
4529
4542
  var MAX_PROCESS_TITLE_LENGTH = 80;
@@ -4586,7 +4599,7 @@ function overviewPredicates2(input) {
4586
4599
  predicates.push(eq17(processInstances.lifecycleStatus, "aborted"));
4587
4600
  break;
4588
4601
  case "scheduled":
4589
- predicates.push(sql5`0 = 1`);
4602
+ predicates.push(sql6`0 = 1`);
4590
4603
  break;
4591
4604
  case "all":
4592
4605
  break;
@@ -4594,10 +4607,10 @@ function overviewPredicates2(input) {
4594
4607
  for (const pattern of sqliteLikePatterns(input.query)) {
4595
4608
  predicates.push(
4596
4609
  or2(
4597
- sql5`lower(coalesce(${processInstances.title}, '')) LIKE ${pattern} ESCAPE '\\'`,
4598
- sql5`lower(coalesce(${processInstances.externalId}, '')) LIKE ${pattern} ESCAPE '\\'`,
4599
- sql5`lower(${processInstances.id}) LIKE ${pattern} ESCAPE '\\'`,
4600
- sql5`lower(coalesce(${processInstances.paramsJson}, '')) LIKE ${pattern} ESCAPE '\\'`
4610
+ sql6`lower(coalesce(${processInstances.title}, '')) LIKE ${pattern} ESCAPE '\\'`,
4611
+ sql6`lower(coalesce(${processInstances.externalId}, '')) LIKE ${pattern} ESCAPE '\\'`,
4612
+ sql6`lower(${processInstances.id}) LIKE ${pattern} ESCAPE '\\'`,
4613
+ sql6`lower(coalesce(${processInstances.paramsJson}, '')) LIKE ${pattern} ESCAPE '\\'`
4601
4614
  )
4602
4615
  );
4603
4616
  }
@@ -4689,6 +4702,25 @@ function createProcessInstanceRepo(db) {
4689
4702
  listAll() {
4690
4703
  return db.select().from(processInstances).orderBy(desc6(processInstances.updatedAt)).all().map(rowToProcessInstance);
4691
4704
  },
4705
+ /** Model references for current work without loading prompts or process state. @internal */
4706
+ listModelConfigurations() {
4707
+ return db.select({
4708
+ /** @internal */
4709
+ id: processInstances.id,
4710
+ /** @internal */
4711
+ processId: processInstances.processId,
4712
+ /** @internal */
4713
+ title: processInstances.title,
4714
+ /** @internal */
4715
+ defaultModelProfileId: processInstances.defaultModelProfileId,
4716
+ /** @internal */
4717
+ turnConfigsJson: processInstances.turnConfigsJson,
4718
+ /** @internal */
4719
+ selectedTurnId: processInstances.selectedTurnId,
4720
+ /** @internal */
4721
+ selectedTurnModelProfileId: processInstances.selectedTurnModelProfileId
4722
+ }).from(processInstances).where(notInArray2(processInstances.lifecycleStatus, ["completed", "aborted"])).all();
4723
+ },
4692
4724
  /** @internal */
4693
4725
  listCurrent(limit) {
4694
4726
  return db.select().from(processInstances).where(notInArray2(processInstances.lifecycleStatus, ["completed", "aborted"])).orderBy(desc6(processInstances.updatedAt), asc8(processInstances.id)).limit(limit).all().map(rowToProcessInstance);
@@ -4721,13 +4753,13 @@ function createProcessInstanceRepo(db) {
4721
4753
  },
4722
4754
  /** @internal */
4723
4755
  listOverviewWindow(input) {
4724
- const title = sql5`coalesce(${processInstances.title}, ${processInstances.externalId}, ${processInstances.id})`;
4725
- const status = sql5`case
4756
+ const title = sql6`coalesce(${processInstances.title}, ${processInstances.externalId}, ${processInstances.id})`;
4757
+ const status = sql6`case
4726
4758
  when ${processInstances.lifecycleStatus} in ('waiting', 'error') then 0
4727
4759
  when ${processInstances.lifecycleStatus} in ('discovered', 'active') then 1
4728
4760
  when ${processInstances.lifecycleStatus} = 'completed' then 3
4729
4761
  else 4 end`;
4730
- const timeline = sql5`case
4762
+ const timeline = sql6`case
4731
4763
  when ${processInstances.lifecycleStatus} in ('completed', 'aborted')
4732
4764
  then coalesce(${processInstances.closedAt}, ${processInstances.updatedAt})
4733
4765
  else ${processInstances.updatedAt} end`;
@@ -4747,7 +4779,7 @@ function createProcessInstanceRepo(db) {
4747
4779
  const result = db.update(processInstances).set({ title: normalizedTitle, updatedAt: now() }).where(
4748
4780
  and13(
4749
4781
  eq17(processInstances.id, id),
4750
- sql5`trim(coalesce(${processInstances.title}, '')) = ''`
4782
+ sql6`trim(coalesce(${processInstances.title}, '')) = ''`
4751
4783
  )
4752
4784
  ).run();
4753
4785
  return result.changes > 0 ? this.getById(id) : null;
@@ -4778,7 +4810,7 @@ function createProcessInstanceRepo(db) {
4778
4810
  if (input.metadata !== void 0)
4779
4811
  setValues.metadata = input.metadata ? JSON.stringify(input.metadata) : null;
4780
4812
  if (isTerminalLifecycleStatus(input.lifecycleStatus)) {
4781
- setValues.closedAt = sql5`coalesce(${processInstances.closedAt}, ${ts})`;
4813
+ setValues.closedAt = sql6`coalesce(${processInstances.closedAt}, ${ts})`;
4782
4814
  }
4783
4815
  db.update(processInstances).set(setValues).where(eq17(processInstances.id, id)).run();
4784
4816
  return this.getById(id);
@@ -4792,7 +4824,7 @@ function createProcessInstanceRepo(db) {
4792
4824
  }
4793
4825
 
4794
4826
  // src/db/process-leaf-outcome-snapshot-repo.ts
4795
- import { and as and15, asc as asc9, desc as desc7, eq as eq18, sql as sql6 } from "drizzle-orm";
4827
+ import { and as and15, asc as asc9, desc as desc7, eq as eq18, sql as sql7 } from "drizzle-orm";
4796
4828
 
4797
4829
  // src/db/history-window.ts
4798
4830
  import { and as and14, gte as gte2, lte as lte2 } from "drizzle-orm";
@@ -4862,7 +4894,7 @@ function createProcessLeafOutcomeSnapshotRepo(db) {
4862
4894
  eq18(processLeafOutcomeSnapshots.instanceId, instanceId),
4863
4895
  eq18(processLeafOutcomeSnapshots.leafEntryId, leafEntryId)
4864
4896
  )
4865
- ).orderBy(desc7(processLeafOutcomeSnapshots.createdAt), desc7(sql6`rowid`)).limit(1).get();
4897
+ ).orderBy(desc7(processLeafOutcomeSnapshots.createdAt), desc7(sql7`rowid`)).limit(1).get();
4866
4898
  return row ? rowToProcessLeafOutcomeSnapshot(row) : null;
4867
4899
  }
4868
4900
  };
@@ -5326,7 +5358,7 @@ function createProcessSkillRepo(db) {
5326
5358
  }
5327
5359
 
5328
5360
  // src/db/process-title-job-repo.ts
5329
- import { and as and18, asc as asc13, eq as eq23, inArray as inArray8, lte as lte3, sql as sql7 } from "drizzle-orm";
5361
+ import { and as and18, asc as asc13, eq as eq23, inArray as inArray8, lte as lte3, sql as sql8 } from "drizzle-orm";
5330
5362
  function createProcessTitleJobRepo(db) {
5331
5363
  function transition(id, from, values) {
5332
5364
  return db.update(processTitleJobs).set({ ...values, updatedAt: now() }).where(and18(eq23(processTitleJobs.id, id), inArray8(processTitleJobs.status, from))).returning().get() ?? null;
@@ -5386,7 +5418,7 @@ function createProcessTitleJobRepo(db) {
5386
5418
  markRunning(id) {
5387
5419
  return transition(id, ["pending"], {
5388
5420
  status: "running",
5389
- attemptCount: sql7`${processTitleJobs.attemptCount} + 1`,
5421
+ attemptCount: sql8`${processTitleJobs.attemptCount} + 1`,
5390
5422
  lastError: null
5391
5423
  });
5392
5424
  },
@@ -5507,7 +5539,7 @@ function createProcessToolApprovalRequestRepo(db) {
5507
5539
 
5508
5540
  // src/db/process-turn-annotation-repo.ts
5509
5541
  import { parseTurnAnnotationReferences } from "@leitwerk-dev/domain";
5510
- import { and as and20, asc as asc15, eq as eq25, getTableColumns as getTableColumns2, sql as sql8 } from "drizzle-orm";
5542
+ import { and as and20, asc as asc15, eq as eq25, getTableColumns as getTableColumns2, sql as sql9 } from "drizzle-orm";
5511
5543
  function parseReferences(value) {
5512
5544
  try {
5513
5545
  return parseTurnAnnotationReferences(JSON.parse(value));
@@ -5530,7 +5562,7 @@ function rowToProcessTurnAnnotation(row) {
5530
5562
  function createProcessTurnAnnotationRepo(db) {
5531
5563
  const list = (instanceId, window, compact) => db.select({
5532
5564
  ...getTableColumns2(turnAnnotations),
5533
- payloadJson: compact ? sql8`json_remove(${turnAnnotations.payloadJson}, '$.event')` : turnAnnotations.payloadJson
5565
+ payloadJson: compact ? sql9`json_remove(${turnAnnotations.payloadJson}, '$.event')` : turnAnnotations.payloadJson
5534
5566
  }).from(turnAnnotations).where(
5535
5567
  and20(
5536
5568
  eq25(turnAnnotations.instanceId, instanceId),
@@ -5605,7 +5637,7 @@ function createProcessTurnAnnotationRepo(db) {
5605
5637
  }
5606
5638
 
5607
5639
  // src/db/process-turn-record-repo.ts
5608
- import { and as and21, asc as asc16, desc as desc8, eq as eq26, getTableColumns as getTableColumns3, isNull as isNull3, ne, sql as sql9 } from "drizzle-orm";
5640
+ import { and as and21, asc as asc16, desc as desc8, eq as eq26, getTableColumns as getTableColumns3, isNull as isNull3, ne, sql as sql10 } from "drizzle-orm";
5609
5641
  function rowToProcessTurnRecord(row) {
5610
5642
  return {
5611
5643
  id: row.id,
@@ -5684,7 +5716,7 @@ function createProcessTurnRecordRepo(db) {
5684
5716
  return db.select().from(turnRecords).where(
5685
5717
  and21(
5686
5718
  eq26(turnRecords.instanceId, instanceId),
5687
- before ? sql9`(${turnRecords.startedAt}, ${turnRecords.id}) < (${before.startedAt}, ${before.id})` : void 0
5719
+ before ? sql10`(${turnRecords.startedAt}, ${turnRecords.id}) < (${before.startedAt}, ${before.id})` : void 0
5688
5720
  )
5689
5721
  ).orderBy(desc8(turnRecords.startedAt), desc8(turnRecords.id)).limit(limit).all().map(rowToProcessTurnRecord).reverse();
5690
5722
  },
@@ -5989,7 +6021,7 @@ function createSessionTransferRepo(db) {
5989
6021
 
5990
6022
  // src/db/skill-repo.ts
5991
6023
  import { verifyCanonicalPiResourceBundle as verifyCanonicalPiResourceBundle2 } from "@leitwerk-dev/worker-protocol";
5992
- import { and as and24, asc as asc17, count as count4, desc as desc9, eq as eq29, isNotNull as isNotNull2, max as max2, notExists as notExists2, notInArray as notInArray3, sql as sql10 } from "drizzle-orm";
6024
+ import { and as and24, asc as asc17, count as count4, desc as desc9, eq as eq29, isNotNull as isNotNull2, max as max2, notExists as notExists2, notInArray as notInArray3, sql as sql11 } from "drizzle-orm";
5993
6025
 
5994
6026
  // src/skills/skill-dependencies.ts
5995
6027
  var EXPLICIT_SKILL_REFERENCE = /\/([A-Za-z0-9][A-Za-z0-9._-]{0,83})|`([A-Za-z0-9][A-Za-z0-9._-]{0,83})`/g;
@@ -6008,22 +6040,21 @@ function referencedSkillIds(markdown, availableSkillIds) {
6008
6040
 
6009
6041
  // src/skills/skill-frontmatter.ts
6010
6042
  import { parse as parseYaml2 } from "yaml";
6011
- function frontmatter(markdown) {
6012
- if (!markdown.startsWith("---")) return null;
6013
- const end = markdown.indexOf("\n---", 3);
6014
- if (end < 0) return null;
6043
+ function skillFrontmatter(markdown) {
6044
+ const header = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown);
6045
+ if (!header) return null;
6015
6046
  try {
6016
- const parsed = parseYaml2(markdown.slice(3, end));
6047
+ const parsed = parseYaml2(header[1]);
6017
6048
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
6018
6049
  } catch {
6019
6050
  return null;
6020
6051
  }
6021
6052
  }
6022
6053
  function isSkillModelInvocable(markdown) {
6023
- return frontmatter(markdown)?.["disable-model-invocation"] !== true;
6054
+ return skillFrontmatter(markdown)?.["disable-model-invocation"] !== true;
6024
6055
  }
6025
6056
  function skillMetadata(markdown) {
6026
- const metadata = frontmatter(markdown);
6057
+ const metadata = skillFrontmatter(markdown);
6027
6058
  const text3 = (key) => {
6028
6059
  const value = metadata?.[key];
6029
6060
  return typeof value === "string" ? value.trim() || null : null;
@@ -6067,7 +6098,7 @@ function usageBySkill(db) {
6067
6098
  for (const row of db.select({
6068
6099
  skillId: processSkills.skillId,
6069
6100
  allTime: count4(),
6070
- last30Days: sql10`sum(case when ${processInstances.createdAt} >= ${cutoff} then 1 else 0 end)`
6101
+ last30Days: sql11`sum(case when ${processInstances.createdAt} >= ${cutoff} then 1 else 0 end)`
6071
6102
  }).from(processSkills).innerJoin(processInstances, eq29(processSkills.instanceId, processInstances.id)).groupBy(processSkills.skillId).all()) {
6072
6103
  result.set(row.skillId, {
6073
6104
  ...usage(row.skillId),
@@ -6078,7 +6109,7 @@ function usageBySkill(db) {
6078
6109
  for (const row of db.select({
6079
6110
  skillId: skillInvocations.skillId,
6080
6111
  allTime: count4(),
6081
- last30Days: sql10`sum(case when ${skillInvocations.invokedAt} >= ${cutoff} then 1 else 0 end)`
6112
+ last30Days: sql11`sum(case when ${skillInvocations.invokedAt} >= ${cutoff} then 1 else 0 end)`
6082
6113
  }).from(skillInvocations).groupBy(skillInvocations.skillId).all()) {
6083
6114
  result.set(row.skillId, {
6084
6115
  ...usage(row.skillId),
@@ -6091,7 +6122,7 @@ function usageBySkill(db) {
6091
6122
  function processUsage(db, skillId) {
6092
6123
  return db.select({
6093
6124
  instanceId: processSkills.instanceId,
6094
- title: sql10`coalesce(${processInstances.title}, ${processInstances.externalId}, ${processInstances.id})`,
6125
+ title: sql11`coalesce(${processInstances.title}, ${processInstances.externalId}, ${processInstances.id})`,
6095
6126
  attachedAt: processInstances.createdAt,
6096
6127
  invocationCount: count4(skillInvocations.skillId),
6097
6128
  lastInvokedAt: max2(skillInvocations.invokedAt)
@@ -6583,7 +6614,11 @@ function createTurnStartRecordRepo(db) {
6583
6614
  compareAndSetState(input) {
6584
6615
  const current = this.getById(input.id);
6585
6616
  if (!current || current.state.kind !== input.expectedKind) return null;
6586
- const result = db.update(turnStartRecords).set({ stateJson: JSON.stringify(input.state), updatedAt: now() }).where(
6617
+ const state = {
6618
+ ...input.state,
6619
+ automaticRetry: input.state.automaticRetry ?? current.state.automaticRetry
6620
+ };
6621
+ const result = db.update(turnStartRecords).set({ stateJson: JSON.stringify(state), updatedAt: now() }).where(
6587
6622
  and26(
6588
6623
  eq31(turnStartRecords.id, input.id),
6589
6624
  eq31(turnStartRecords.stateJson, JSON.stringify(current.state))
@@ -11437,6 +11472,81 @@ function mergeProcessEventWindowsAscending(windows) {
11437
11472
  );
11438
11473
  }
11439
11474
 
11475
+ // src/startup-retry-policy.ts
11476
+ var MAX_STARTUP_STARTS = 3;
11477
+ function startupRetryState(start, starts, events = []) {
11478
+ if (start.state.automaticRetry) return start.state.automaticRetry;
11479
+ const byId = new Map(starts.map((entry) => [entry.id, entry]));
11480
+ const predecessors = new Map(
11481
+ events.filter((event) => event.eventType === "startup_retry_scheduled").map((event) => [String(event.data.startRecordId), event])
11482
+ );
11483
+ let current = start;
11484
+ let count5 = 1;
11485
+ const seen = /* @__PURE__ */ new Set([start.id]);
11486
+ while (current.startKind === "startup_retry") {
11487
+ const event = predecessors.get(current.id);
11488
+ const actor = event?.data.actor;
11489
+ if (event?.data.retrySource === "manual" || actor && actor.kind !== "system") break;
11490
+ const previous = byId.get(String(event?.data.previousStartRecordId));
11491
+ if (!previous || seen.has(previous.id) || previous.turnId !== start.turnId) {
11492
+ count5 = Math.max(count5, MAX_STARTUP_STARTS);
11493
+ break;
11494
+ }
11495
+ seen.add(previous.id);
11496
+ count5 += 1;
11497
+ current = previous;
11498
+ if (current.state.automaticRetry) {
11499
+ return {
11500
+ ...current.state.automaticRetry,
11501
+ starts: current.state.automaticRetry.starts + count5 - 1,
11502
+ nextRetryAt: null
11503
+ };
11504
+ }
11505
+ }
11506
+ return { episodeStartRecordId: current.id, starts: count5, nextRetryAt: null };
11507
+ }
11508
+ function automaticStartupRecovery(start, retry, now2 = Date.now(), modelRestored = false) {
11509
+ const summary = (status, reason, nextRetryAt2 = null) => ({
11510
+ starts: retry.starts,
11511
+ maxStarts: MAX_STARTUP_STARTS,
11512
+ status,
11513
+ reason,
11514
+ nextRetryAt: nextRetryAt2
11515
+ });
11516
+ if (start.state.kind !== "preparation_failed" && start.state.kind !== "bootstrap_failed")
11517
+ return summary("blocked", "This start is no longer eligible for automatic recovery.");
11518
+ const code = start.state.code;
11519
+ const modelFailure = code === "model_unavailable" || code === "model_stale";
11520
+ const transient = start.state.kind === "bootstrap_failed" && [
11521
+ "startup_timeout",
11522
+ "spawn_error",
11523
+ "worker_spawn_failed",
11524
+ "worker_adoption_failed",
11525
+ "process_exited"
11526
+ ].includes(code);
11527
+ if (!modelFailure && !transient)
11528
+ return summary("blocked", "Automatic retry stopped. Correct the failure and retry manually.");
11529
+ if (retry.starts >= MAX_STARTUP_STARTS)
11530
+ return summary(
11531
+ "exhausted",
11532
+ "Automatic startup retries exhausted. Retry manually after correcting the failure."
11533
+ );
11534
+ if (modelFailure)
11535
+ return summary(
11536
+ modelRestored ? "ready" : "waiting_for_model",
11537
+ modelRestored ? "Model availability restored." : "Waiting for model availability to be restored."
11538
+ );
11539
+ const failureAt = Date.parse(start.updatedAt);
11540
+ if (!Number.isFinite(failureAt))
11541
+ return summary("blocked", "Startup failure timing is unavailable. Retry manually.");
11542
+ const nextRetryAt = retry.nextRetryAt ?? new Date(failureAt + 3e4 * 2 ** (retry.starts - 1)).toISOString();
11543
+ return summary(
11544
+ Date.parse(nextRetryAt) > now2 ? "waiting" : "ready",
11545
+ "A transient worker startup failure is eligible for automatic recovery.",
11546
+ nextRetryAt
11547
+ );
11548
+ }
11549
+
11440
11550
  // src/startup-evidence.ts
11441
11551
  var STARTUP_STEP_LABELS = {
11442
11552
  start_worker: "Request worker",
@@ -11449,14 +11559,18 @@ function validObservedAt(value, notBefore) {
11449
11559
  const time = Date.parse(value);
11450
11560
  return Number.isFinite(time) && time >= Date.parse(notBefore) ? value : null;
11451
11561
  }
11452
- function buildStartupRecovery(process2, turnStartsById) {
11562
+ function buildStartupRecovery(process2, turnStartsById, events = []) {
11453
11563
  if (process2.lifecycleStatus !== "error" || process2.currentExecution?.kind !== "worker_start")
11454
11564
  return null;
11455
- const start = "getById" in turnStartsById ? turnStartsById.getById(process2.currentExecution.id) : turnStartsById.get(process2.currentExecution.id);
11565
+ const start = turnStartsById.get(process2.currentExecution.id);
11456
11566
  if (!start || start.state.kind !== "preparation_failed" && start.state.kind !== "bootstrap_failed")
11457
11567
  return null;
11458
11568
  const resolvedStart = "start" in start.state ? start.state.start : null;
11459
11569
  return {
11570
+ automaticRetry: automaticStartupRecovery(
11571
+ start,
11572
+ startupRetryState(start, [...turnStartsById.values()], events)
11573
+ ),
11460
11574
  startRecordId: start.id,
11461
11575
  kind: start.state.kind,
11462
11576
  action: start.state.kind === "bootstrap_failed" ? "retry_startup" : "choose_model",
@@ -11558,7 +11672,7 @@ function buildStartupEvidence(input) {
11558
11672
  ...pendingTurnWait(input.process)?.initialSelection ? { readiness: { message: pendingTurnWait(input.process)?.message ?? null } } : {},
11559
11673
  currentAttempt,
11560
11674
  authoritativeAttemptId: authoritative?.startRecordId ?? null,
11561
- recovery: buildStartupRecovery(input.process, turnStartsById)
11675
+ recovery: buildStartupRecovery(input.process, turnStartsById, input.events)
11562
11676
  };
11563
11677
  }
11564
11678
  function presentProcessStartupSummary(evidence) {
@@ -12942,6 +13056,7 @@ export {
12942
13056
  applySubmittedProcessTitleToLaunchPlan,
12943
13057
  SKILL_RESOURCE_OWNER,
12944
13058
  ResourceCollector,
13059
+ skillFrontmatter,
12945
13060
  isSkillModelInvocable,
12946
13061
  skillMetadata,
12947
13062
  createAllRepos,
@@ -12987,6 +13102,8 @@ export {
12987
13102
  failLaunchRun,
12988
13103
  completeCommittedLaunch,
12989
13104
  createLaunchPipeline,
13105
+ startupRetryState,
13106
+ automaticStartupRecovery,
12990
13107
  buildStartupEvidence,
12991
13108
  projectLaunchRunStartup,
12992
13109
  positiveBound,
@@ -13045,4 +13162,4 @@ export {
13045
13162
  createProjectedSessionSnapshotStore,
13046
13163
  createBroadcaster
13047
13164
  };
13048
- //# sourceMappingURL=chunk-MBHRCQFE.js.map
13165
+ //# sourceMappingURL=chunk-YLWY4UTT.js.map