@leitwerk-dev/server 0.3.0 → 0.3.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 (120) hide show
  1. package/dist/{app-WfwKzrVk.d.ts → app-BuJCdkvy.d.ts} +82 -2
  2. package/dist/app-MSJXFK33.js +8 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/{chunk-KIOQNNG6.js → chunk-HK6BLLHA.js} +738 -506
  5. package/dist/chunk-HK6BLLHA.js.map +1 -0
  6. package/dist/{chunk-LK3RO6C7.js → chunk-QCHS3X33.js} +486 -136
  7. package/dist/chunk-QCHS3X33.js.map +1 -0
  8. package/dist/db/database.d.ts.map +1 -1
  9. package/dist/db/mapped-llm-run-repo.d.ts +56 -0
  10. package/dist/db/mapped-llm-run-repo.d.ts.map +1 -0
  11. package/dist/db/process-turn-record-repo.d.ts +3 -1
  12. package/dist/db/process-turn-record-repo.d.ts.map +1 -1
  13. package/dist/db/repo-helpers.d.ts +6 -0
  14. package/dist/db/repo-helpers.d.ts.map +1 -1
  15. package/dist/db/repositories.d.ts +4 -0
  16. package/dist/db/repositories.d.ts.map +1 -1
  17. package/dist/db/schema.d.ts +415 -0
  18. package/dist/db/schema.d.ts.map +1 -1
  19. package/dist/db/turn-start-record-repo.d.ts.map +1 -1
  20. package/dist/domain-logic/outcome-tools.d.ts.map +1 -1
  21. package/dist/future-execution-presenter.d.ts +4 -14
  22. package/dist/future-execution-presenter.d.ts.map +1 -1
  23. package/dist/index.js +2 -2
  24. package/dist/launch-coordinator-test-harness.d.ts.map +1 -1
  25. package/dist/main.js +3 -3
  26. package/dist/process-action-presenter.d.ts +16 -0
  27. package/dist/process-action-presenter.d.ts.map +1 -0
  28. package/dist/process-engine/mapped-turns.d.ts +45 -0
  29. package/dist/process-engine/mapped-turns.d.ts.map +1 -0
  30. package/dist/process-engine/operation.d.ts +1 -1
  31. package/dist/process-engine/operation.d.ts.map +1 -1
  32. package/dist/process-engine/ops/accept-worker-turn-start.d.ts +2 -0
  33. package/dist/process-engine/ops/accept-worker-turn-start.d.ts.map +1 -1
  34. package/dist/process-engine/ops/retry-startup.d.ts.map +1 -1
  35. package/dist/process-engine/ops/turn-outcome.d.ts.map +1 -1
  36. package/dist/process-engine/recorder.d.ts.map +1 -1
  37. package/dist/process-engine/types.d.ts +5 -0
  38. package/dist/process-engine/types.d.ts.map +1 -1
  39. package/dist/process-engine/writes/build-process-abort-writes.d.ts.map +1 -1
  40. package/dist/process-engine/writes/build-recovery-start-writes.d.ts.map +1 -1
  41. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts +8 -1
  42. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts.map +1 -1
  43. package/dist/process-engine/writes/build-turn-selection-writes.d.ts.map +1 -1
  44. package/dist/process-engine/writes/commit-writes.d.ts.map +1 -1
  45. package/dist/process-engine/writes/reserve-selected-turn-start.d.ts +5 -0
  46. package/dist/process-engine/writes/reserve-selected-turn-start.d.ts.map +1 -0
  47. package/dist/process-engine/writes/writes.d.ts +18 -0
  48. package/dist/process-engine/writes/writes.d.ts.map +1 -1
  49. package/dist/process-turn-navigation.d.ts +12 -2
  50. package/dist/process-turn-navigation.d.ts.map +1 -1
  51. package/dist/process-ui-snapshot-presenter.d.ts +2 -1
  52. package/dist/process-ui-snapshot-presenter.d.ts.map +1 -1
  53. package/dist/routes/process-actions.d.ts.map +1 -1
  54. package/dist/routes/process-diagnostics-assembler.d.ts +3 -1
  55. package/dist/routes/process-diagnostics-assembler.d.ts.map +1 -1
  56. package/dist/routes/process-primary-path-assembler.d.ts +4 -12
  57. package/dist/routes/process-primary-path-assembler.d.ts.map +1 -1
  58. package/dist/routes/process-route-helpers.d.ts +7 -32
  59. package/dist/routes/process-route-helpers.d.ts.map +1 -1
  60. package/dist/supervisor/ipc-handler.d.ts.map +1 -1
  61. package/dist/supervisor/worker-start-payload-builder.d.ts +2 -0
  62. package/dist/supervisor/worker-start-payload-builder.d.ts.map +1 -1
  63. package/dist/supervisor/worker-supervisor.d.ts +2 -0
  64. package/dist/supervisor/worker-supervisor.d.ts.map +1 -1
  65. package/dist/supervisor/worker-turn-ipc-recorder.d.ts +2 -2
  66. package/dist/supervisor/worker-turn-ipc-recorder.d.ts.map +1 -1
  67. package/dist/test-helpers/accepted-turn-start.d.ts +18 -4
  68. package/dist/test-helpers/accepted-turn-start.d.ts.map +1 -1
  69. package/dist/test-helpers/owned-test-deps.d.ts +18 -0
  70. package/dist/test-helpers/owned-test-deps.d.ts.map +1 -0
  71. package/dist/testing.d.ts +1 -1
  72. package/dist/testing.d.ts.map +1 -1
  73. package/dist/testing.js +13 -10
  74. package/dist/testing.js.map +1 -1
  75. package/package.json +11 -11
  76. package/src/app.ts +2 -0
  77. package/src/db/database.ts +28 -0
  78. package/src/db/mapped-llm-run-repo.ts +177 -0
  79. package/src/db/process-turn-record-repo.ts +8 -1
  80. package/src/db/repo-helpers.ts +11 -1
  81. package/src/db/repositories.ts +5 -0
  82. package/src/db/schema.ts +70 -1
  83. package/src/db/turn-start-record-repo.ts +5 -1
  84. package/src/domain-logic/outcome-tools.ts +50 -6
  85. package/src/future-execution-presenter.ts +10 -17
  86. package/src/launch-coordinator-test-harness.ts +8 -4
  87. package/src/process-action-presenter.ts +133 -0
  88. package/src/process-engine/engine.ts +2 -2
  89. package/src/process-engine/mapped-turns.ts +330 -0
  90. package/src/process-engine/operation.ts +1 -1
  91. package/src/process-engine/ops/accept-worker-turn-start.ts +6 -0
  92. package/src/process-engine/ops/retry-startup.ts +1 -0
  93. package/src/process-engine/ops/turn-outcome.ts +7 -5
  94. package/src/process-engine/recorder.ts +12 -0
  95. package/src/process-engine/runner.ts +8 -8
  96. package/src/process-engine/types.ts +6 -0
  97. package/src/process-engine/writes/build-process-abort-writes.ts +1 -0
  98. package/src/process-engine/writes/build-recovery-start-writes.ts +1 -0
  99. package/src/process-engine/writes/build-turn-outcome-writes.ts +80 -20
  100. package/src/process-engine/writes/build-turn-selection-writes.ts +2 -31
  101. package/src/process-engine/writes/commit-writes.ts +5 -0
  102. package/src/process-engine/writes/reserve-selected-turn-start.ts +44 -0
  103. package/src/process-engine/writes/writes.ts +27 -0
  104. package/src/process-turn-navigation.ts +86 -8
  105. package/src/process-ui-snapshot-presenter.ts +40 -4
  106. package/src/routes/process-actions.ts +1 -1
  107. package/src/routes/process-diagnostics-assembler.ts +32 -6
  108. package/src/routes/process-primary-path-assembler.ts +17 -33
  109. package/src/routes/process-route-helpers.ts +8 -165
  110. package/src/supervisor/ipc-handler.ts +27 -18
  111. package/src/supervisor/worker-start-payload-builder.ts +25 -0
  112. package/src/supervisor/worker-supervisor.ts +2 -0
  113. package/src/supervisor/worker-turn-ipc-recorder.ts +13 -1
  114. package/src/test-helpers/accepted-turn-start.ts +51 -27
  115. package/src/test-helpers/owned-test-deps.ts +45 -0
  116. package/src/testing.ts +4 -1
  117. package/dist/app-4QSV4FUQ.js +0 -8
  118. package/dist/chunk-KIOQNNG6.js.map +0 -1
  119. package/dist/chunk-LK3RO6C7.js.map +0 -1
  120. /package/dist/{app-4QSV4FUQ.js.map → app-MSJXFK33.js.map} +0 -0
@@ -1118,7 +1118,9 @@ import { DatabaseSync } from "node:sqlite";
1118
1118
  import { drizzle } from "drizzle-orm/node-sqlite";
1119
1119
 
1120
1120
  // src/db/schema.ts
1121
- import { SERIALIZED_SYSTEM_ACTOR } from "@leitwerk-dev/domain";
1121
+ import {
1122
+ SERIALIZED_SYSTEM_ACTOR
1123
+ } from "@leitwerk-dev/domain";
1122
1124
  import { sql } from "drizzle-orm";
1123
1125
  import {
1124
1126
  blob,
@@ -1510,7 +1512,10 @@ var turnRecords = sqliteTable(
1510
1512
  startedAt: text("started_at").notNull(),
1511
1513
  endedAt: text("ended_at"),
1512
1514
  modelSelectionKind: text("model_selection_kind"),
1513
- modelSelectionSource: text("model_selection_source")
1515
+ modelSelectionSource: text("model_selection_source"),
1516
+ mappedRunId: text("mapped_run_id"),
1517
+ mappedItemKey: text("mapped_item_key"),
1518
+ mappedItemIndex: integer2("mapped_item_index")
1514
1519
  },
1515
1520
  (t) => [
1516
1521
  uniqueIndex("uq_turn_records_instance_id").on(t.instanceId, t.id),
@@ -1538,7 +1543,10 @@ var turnStartRecords = sqliteTable(
1538
1543
  continuationJson: text("continuation_json"),
1539
1544
  stateJson: text("state_json").notNull(),
1540
1545
  createdAt: text("created_at").notNull(),
1541
- updatedAt: text("updated_at").notNull()
1546
+ updatedAt: text("updated_at").notNull(),
1547
+ mappedRunId: text("mapped_run_id"),
1548
+ mappedItemKey: text("mapped_item_key"),
1549
+ mappedItemIndex: integer2("mapped_item_index")
1542
1550
  },
1543
1551
  (t) => [
1544
1552
  uniqueIndex("uq_turn_start_records_proposed_turn_record").on(t.proposedTurnRecordId),
@@ -1815,6 +1823,55 @@ var externalWriteLog = sqliteTable(
1815
1823
  index("idx_ewl_write_type").on(t.writeType)
1816
1824
  ]
1817
1825
  );
1826
+ var mappedLlmRuns = sqliteTable(
1827
+ "mapped_llm_runs",
1828
+ {
1829
+ id: text("id").primaryKey(),
1830
+ instanceId: text("instance_id").notNull().references(() => processInstances.id, { onDelete: "cascade" }),
1831
+ turnId: text("turn_id").notNull(),
1832
+ status: text("status").$type().notNull(),
1833
+ itemCount: integer2("item_count").notNull(),
1834
+ nextIndex: integer2("next_index").notNull(),
1835
+ createdAt: text("created_at").notNull(),
1836
+ updatedAt: text("updated_at").notNull()
1837
+ },
1838
+ (t) => [
1839
+ index("idx_mapped_llm_runs_instance").on(t.instanceId),
1840
+ uniqueIndex("uq_mapped_llm_runs_active_instance").on(t.instanceId).where(sql`${t.status} = 'active'`),
1841
+ check2("mapped_llm_runs_status", sql`${t.status} in ('active', 'completed', 'aborted')`),
1842
+ check2(
1843
+ "mapped_llm_runs_progress",
1844
+ sql`${t.itemCount} >= 0 and ${t.nextIndex} >= 0 and ${t.nextIndex} <= ${t.itemCount}`
1845
+ )
1846
+ ]
1847
+ );
1848
+ var mappedLlmItems = sqliteTable(
1849
+ "mapped_llm_items",
1850
+ {
1851
+ runId: text("run_id").notNull().references(() => mappedLlmRuns.id, { onDelete: "cascade" }),
1852
+ instanceId: text("instance_id").notNull().references(() => processInstances.id, { onDelete: "cascade" }),
1853
+ itemIndex: integer2("item_index").notNull(),
1854
+ itemKey: text("item_key").notNull(),
1855
+ label: text("label").notNull(),
1856
+ itemJson: text("item_json").notNull(),
1857
+ status: text("status").$type().notNull().default("pending"),
1858
+ outcome: text("outcome"),
1859
+ resultJson: text("result_json"),
1860
+ turnRecordId: text("turn_record_id"),
1861
+ completedAt: text("completed_at")
1862
+ },
1863
+ (t) => [
1864
+ uniqueIndex("uq_mapped_llm_items_run_index").on(t.runId, t.itemIndex),
1865
+ uniqueIndex("uq_mapped_llm_items_run_key").on(t.runId, t.itemKey),
1866
+ index("idx_mapped_llm_items_instance").on(t.instanceId),
1867
+ check2("mapped_llm_items_status", sql`${t.status} in ('pending', 'completed')`),
1868
+ check2("mapped_llm_items_item_json", sql`json_valid(${t.itemJson})`),
1869
+ check2(
1870
+ "mapped_llm_items_result",
1871
+ sql`(${t.status} = 'pending' and ${t.resultJson} is null) or (${t.status} = 'completed' and ${t.resultJson} is not null and json_valid(${t.resultJson}))`
1872
+ )
1873
+ ]
1874
+ );
1818
1875
  var BASELINE_TABLE_CONSTRAINTS = {
1819
1876
  skills: [
1820
1877
  "CONSTRAINT fk_skills_active_revision FOREIGN KEY (active_revision_id) REFERENCES skill_revisions(id)"
@@ -2003,6 +2060,8 @@ var ALL_TABLES = [
2003
2060
  processLeafOutcomeSnapshots,
2004
2061
  turnRecords,
2005
2062
  turnStartRecords,
2063
+ mappedLlmRuns,
2064
+ mappedLlmItems,
2006
2065
  apiTokens,
2007
2066
  authSessions,
2008
2067
  authLoginFlows,
@@ -2524,6 +2583,27 @@ var KNOWN_MIGRATIONS = [
2524
2583
  sqlite.exec("DROP TABLE provider_credentials_before_20260724");
2525
2584
  }
2526
2585
  },
2586
+ {
2587
+ // Runs before 20260821 so its legacy turn_records validation sees these columns.
2588
+ id: "20260922_add_mapped_llm_runs",
2589
+ tableNames: ["mapped_llm_runs", "mapped_llm_items", "turn_records", "turn_start_records"],
2590
+ matches: (sqlite) => hasExistingSchema(sqlite) && (existingTableSql(sqlite, "mapped_llm_runs") === null || existingTableSql(sqlite, "mapped_llm_items") === null || !tableHasColumn(sqlite, "turn_records", "mapped_run_id") || !tableHasColumn(sqlite, "turn_start_records", "mapped_run_id")),
2591
+ apply(sqlite) {
2592
+ for (const table of ["turn_records", "turn_start_records"]) {
2593
+ if (!tableHasColumn(sqlite, table, "mapped_run_id")) {
2594
+ sqlite.exec(`ALTER TABLE ${table} ADD COLUMN mapped_run_id text;
2595
+ ALTER TABLE ${table} ADD COLUMN mapped_item_key text;
2596
+ ALTER TABLE ${table} ADD COLUMN mapped_item_index integer;`);
2597
+ }
2598
+ }
2599
+ if (existingTableSql(sqlite, "mapped_llm_runs") === null) {
2600
+ createTableWithIndexes(sqlite, mappedLlmRuns);
2601
+ }
2602
+ if (existingTableSql(sqlite, "mapped_llm_items") === null) {
2603
+ createTableWithIndexes(sqlite, mappedLlmItems);
2604
+ }
2605
+ }
2606
+ },
2527
2607
  {
2528
2608
  id: "20260821_remove_server_automatic_execution",
2529
2609
  tableNames: ["process_instances", "turn_records"],
@@ -2905,6 +2985,9 @@ import { and as and2, eq as eq4, gt, lt } from "drizzle-orm";
2905
2985
 
2906
2986
  // src/db/repo-helpers.ts
2907
2987
  import { asUnknownRecord } from "@leitwerk-dev/domain";
2988
+ function mappedItemRef(row) {
2989
+ return row.mappedRunId !== null && row.mappedItemKey !== null && row.mappedItemIndex !== null ? { runId: row.mappedRunId, itemKey: row.mappedItemKey, itemIndex: row.mappedItemIndex } : null;
2990
+ }
2908
2991
  function parsePersistedJson(value, label) {
2909
2992
  try {
2910
2993
  return JSON.parse(value);
@@ -3432,8 +3515,111 @@ function createLauncherRecentValueRepo(db) {
3432
3515
  };
3433
3516
  }
3434
3517
 
3435
- // src/db/pending-external-source-fire-repo.ts
3518
+ // src/db/mapped-llm-run-repo.ts
3436
3519
  import { and as and6, asc as asc3, eq as eq9 } from "drizzle-orm";
3520
+ function createMappedLlmRunRepo(db) {
3521
+ return {
3522
+ /** @internal */
3523
+ create(input) {
3524
+ const ts = now();
3525
+ const run = {
3526
+ id: input.id,
3527
+ instanceId: input.instanceId,
3528
+ turnId: input.turnId,
3529
+ status: input.status,
3530
+ itemCount: input.items.length,
3531
+ nextIndex: input.status === "completed" ? input.items.length : 0,
3532
+ createdAt: ts,
3533
+ updatedAt: ts
3534
+ };
3535
+ db.insert(mappedLlmRuns).values(run).run();
3536
+ for (const item of input.items) {
3537
+ db.insert(mappedLlmItems).values({
3538
+ runId: input.id,
3539
+ instanceId: input.instanceId,
3540
+ itemIndex: item.itemIndex,
3541
+ itemKey: item.itemKey,
3542
+ label: item.label,
3543
+ itemJson: item.itemJson,
3544
+ status: "pending"
3545
+ }).run();
3546
+ }
3547
+ return run;
3548
+ },
3549
+ /** @internal */
3550
+ getById(id) {
3551
+ return db.select().from(mappedLlmRuns).where(eq9(mappedLlmRuns.id, id)).get() ?? null;
3552
+ },
3553
+ /** @internal */
3554
+ getActiveByInstance(instanceId) {
3555
+ return db.select().from(mappedLlmRuns).where(
3556
+ and6(eq9(mappedLlmRuns.instanceId, instanceId), eq9(mappedLlmRuns.status, "active"))
3557
+ ).get() ?? null;
3558
+ },
3559
+ /** @internal */
3560
+ listByInstance(instanceId) {
3561
+ return db.select().from(mappedLlmRuns).where(eq9(mappedLlmRuns.instanceId, instanceId)).orderBy(asc3(mappedLlmRuns.createdAt)).all();
3562
+ },
3563
+ /** @internal */
3564
+ listItems(runId) {
3565
+ return db.select().from(mappedLlmItems).where(eq9(mappedLlmItems.runId, runId)).orderBy(asc3(mappedLlmItems.itemIndex)).all();
3566
+ },
3567
+ /** @internal */
3568
+ listItemsByInstance(instanceId) {
3569
+ return db.select().from(mappedLlmItems).where(eq9(mappedLlmItems.instanceId, instanceId)).all();
3570
+ },
3571
+ /** @internal */
3572
+ getItem(runId, itemIndex) {
3573
+ return db.select().from(mappedLlmItems).where(and6(eq9(mappedLlmItems.runId, runId), eq9(mappedLlmItems.itemIndex, itemIndex))).get() ?? null;
3574
+ },
3575
+ /**
3576
+ * Records one item result and advances the run. Fails unless the item is the
3577
+ * run's current pending item, so a replayed outcome cannot complete it twice.
3578
+ * @internal
3579
+ */
3580
+ completeItem(input) {
3581
+ const run = this.getById(input.runId);
3582
+ if (!run || run.status !== "active" || run.nextIndex !== input.itemIndex) {
3583
+ throw new Error(`Mapped item ${input.itemIndex} of run '${input.runId}' is not current`);
3584
+ }
3585
+ const ts = now();
3586
+ const updated = db.update(mappedLlmItems).set({
3587
+ status: "completed",
3588
+ outcome: input.outcome,
3589
+ resultJson: input.resultJson,
3590
+ turnRecordId: input.turnRecordId,
3591
+ completedAt: ts
3592
+ }).where(
3593
+ and6(
3594
+ eq9(mappedLlmItems.runId, input.runId),
3595
+ eq9(mappedLlmItems.itemIndex, input.itemIndex),
3596
+ eq9(mappedLlmItems.status, "pending")
3597
+ )
3598
+ ).run();
3599
+ if (updated.changes !== 1) {
3600
+ throw new Error(`Mapped item ${input.itemIndex} of run '${input.runId}' is not pending`);
3601
+ }
3602
+ const nextIndex = input.itemIndex + 1;
3603
+ db.update(mappedLlmRuns).set({
3604
+ nextIndex,
3605
+ status: nextIndex === run.itemCount ? "completed" : "active",
3606
+ updatedAt: ts
3607
+ }).where(eq9(mappedLlmRuns.id, input.runId)).run();
3608
+ return this.getById(input.runId);
3609
+ },
3610
+ /** @internal */
3611
+ abortActiveByInstance(instanceId) {
3612
+ return Number(
3613
+ db.update(mappedLlmRuns).set({ status: "aborted", updatedAt: now() }).where(
3614
+ and6(eq9(mappedLlmRuns.instanceId, instanceId), eq9(mappedLlmRuns.status, "active"))
3615
+ ).run().changes
3616
+ );
3617
+ }
3618
+ };
3619
+ }
3620
+
3621
+ // src/db/pending-external-source-fire-repo.ts
3622
+ import { and as and7, asc as asc4, eq as eq10 } from "drizzle-orm";
3437
3623
  function parseRecord(json) {
3438
3624
  const value = JSON.parse(json);
3439
3625
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
@@ -3478,15 +3664,15 @@ function createPendingExternalSourceFireRepo(db) {
3478
3664
  },
3479
3665
  /** @internal */
3480
3666
  listByInstance(instanceId) {
3481
- return db.select().from(pendingExternalSourceFires).where(eq9(pendingExternalSourceFires.instanceId, instanceId)).orderBy(asc3(pendingExternalSourceFires.createdAt)).all().map(rowToPendingExternalSourceFire);
3667
+ return db.select().from(pendingExternalSourceFires).where(eq10(pendingExternalSourceFires.instanceId, instanceId)).orderBy(asc4(pendingExternalSourceFires.createdAt)).all().map(rowToPendingExternalSourceFire);
3482
3668
  },
3483
3669
  /** @internal */
3484
3670
  getByMergeKey(instanceId, armingId, mergeKey) {
3485
3671
  const row = db.select().from(pendingExternalSourceFires).where(
3486
- and6(
3487
- eq9(pendingExternalSourceFires.instanceId, instanceId),
3488
- eq9(pendingExternalSourceFires.armingId, armingId),
3489
- eq9(pendingExternalSourceFires.mergeKey, mergeKey)
3672
+ and7(
3673
+ eq10(pendingExternalSourceFires.instanceId, instanceId),
3674
+ eq10(pendingExternalSourceFires.armingId, armingId),
3675
+ eq10(pendingExternalSourceFires.mergeKey, mergeKey)
3490
3676
  )
3491
3677
  ).get();
3492
3678
  return row ? rowToPendingExternalSourceFire(row) : null;
@@ -3499,13 +3685,13 @@ function createPendingExternalSourceFireRepo(db) {
3499
3685
  };
3500
3686
  if (input.input !== void 0) setValues.inputJson = JSON.stringify(input.input);
3501
3687
  if (input.event !== void 0) setValues.eventJson = JSON.stringify(input.event);
3502
- db.update(pendingExternalSourceFires).set(setValues).where(eq9(pendingExternalSourceFires.id, id)).run();
3503
- const row = db.select().from(pendingExternalSourceFires).where(eq9(pendingExternalSourceFires.id, id)).get();
3688
+ db.update(pendingExternalSourceFires).set(setValues).where(eq10(pendingExternalSourceFires.id, id)).run();
3689
+ const row = db.select().from(pendingExternalSourceFires).where(eq10(pendingExternalSourceFires.id, id)).get();
3504
3690
  return row ? rowToPendingExternalSourceFire(row) : null;
3505
3691
  },
3506
3692
  /** @internal */
3507
3693
  delete(id) {
3508
- const result = db.delete(pendingExternalSourceFires).where(eq9(pendingExternalSourceFires.id, id)).run();
3694
+ const result = db.delete(pendingExternalSourceFires).where(eq10(pendingExternalSourceFires.id, id)).run();
3509
3695
  return result.changes > 0;
3510
3696
  }
3511
3697
  };
@@ -3513,7 +3699,7 @@ function createPendingExternalSourceFireRepo(db) {
3513
3699
 
3514
3700
  // src/db/process-event-repo.ts
3515
3701
  import { applyEventToCompactTurnSummary, emptyCompactTurnSummary } from "@leitwerk-dev/protocol";
3516
- import { and as and7, asc as asc4, desc as desc5, eq as eq10, gte, inArray as inArray3, like, sql as sql3 } from "drizzle-orm";
3702
+ import { and as and8, asc as asc5, desc as desc5, eq as eq11, gte, inArray as inArray3, like, sql as sql3 } from "drizzle-orm";
3517
3703
  function rowToProcessEvent(row) {
3518
3704
  return {
3519
3705
  id: row.id,
@@ -3563,24 +3749,24 @@ function createProcessEventRepo(db) {
3563
3749
  },
3564
3750
  /** @internal */
3565
3751
  latestSequence(instanceId) {
3566
- return db.select({ sequence: processEvents.eventSequence }).from(processEvents).where(eq10(processEvents.instanceId, instanceId)).orderBy(desc5(processEvents.eventSequence)).limit(1).get()?.sequence ?? 0;
3752
+ return db.select({ sequence: processEvents.eventSequence }).from(processEvents).where(eq11(processEvents.instanceId, instanceId)).orderBy(desc5(processEvents.eventSequence)).limit(1).get()?.sequence ?? 0;
3567
3753
  },
3568
3754
  /** @internal */
3569
3755
  listByTurnRecord(instanceId, turnRecordId) {
3570
3756
  return db.select().from(processEvents).where(
3571
- and7(
3572
- eq10(processEvents.instanceId, instanceId),
3573
- eq10(processEvents.turnRecordId, turnRecordId)
3757
+ and8(
3758
+ eq11(processEvents.instanceId, instanceId),
3759
+ eq11(processEvents.turnRecordId, turnRecordId)
3574
3760
  )
3575
- ).orderBy(asc4(processEvents.eventSequence)).all().map(rowToProcessEvent);
3761
+ ).orderBy(asc5(processEvents.eventSequence)).all().map(rowToProcessEvent);
3576
3762
  },
3577
3763
  /** @internal */
3578
3764
  latestByTurnRecordEventType(instanceId, turnRecordId, eventType) {
3579
3765
  const row = db.select().from(processEvents).where(
3580
- and7(
3581
- eq10(processEvents.instanceId, instanceId),
3582
- eq10(processEvents.turnRecordId, turnRecordId),
3583
- eq10(processEvents.eventType, eventType)
3766
+ and8(
3767
+ eq11(processEvents.instanceId, instanceId),
3768
+ eq11(processEvents.turnRecordId, turnRecordId),
3769
+ eq11(processEvents.eventType, eventType)
3584
3770
  )
3585
3771
  ).orderBy(desc5(processEvents.eventSequence)).limit(1).get();
3586
3772
  return row ? rowToProcessEvent(row) : null;
@@ -3591,7 +3777,7 @@ function createProcessEventRepo(db) {
3591
3777
  },
3592
3778
  /** @internal */
3593
3779
  listByInstance(instanceId, limit = 100) {
3594
- return listNewest(eq10(processEvents.instanceId, instanceId), limit);
3780
+ return listNewest(eq11(processEvents.instanceId, instanceId), limit);
3595
3781
  },
3596
3782
  /** @internal */
3597
3783
  listByInstanceEventTypes(instanceId, eventTypes, limit = 100) {
@@ -3603,7 +3789,7 @@ function createProcessEventRepo(db) {
3603
3789
  }
3604
3790
  const events = filteredEventTypes.flatMap(
3605
3791
  (eventType) => listNewest(
3606
- and7(eq10(processEvents.instanceId, instanceId), eq10(processEvents.eventType, eventType)),
3792
+ and8(eq11(processEvents.instanceId, instanceId), eq11(processEvents.eventType, eventType)),
3607
3793
  limit
3608
3794
  )
3609
3795
  );
@@ -3614,8 +3800,8 @@ function createProcessEventRepo(db) {
3614
3800
  listByInstanceSince(instanceId, sinceCreatedAt, options = {}) {
3615
3801
  const prefix = typeof options.eventTypePrefix === "string" ? options.eventTypePrefix.trim() : "";
3616
3802
  return listNewest(
3617
- and7(
3618
- eq10(processEvents.instanceId, instanceId),
3803
+ and8(
3804
+ eq11(processEvents.instanceId, instanceId),
3619
3805
  gte(processEvents.createdAt, sinceCreatedAt),
3620
3806
  prefix ? like(processEvents.eventType, `${prefix}%`) : void 0
3621
3807
  ),
@@ -3629,12 +3815,12 @@ function createProcessEventRepo(db) {
3629
3815
  return [];
3630
3816
  }
3631
3817
  return db.select().from(processEvents).where(
3632
- and7(
3633
- eq10(processEvents.instanceId, instanceId),
3818
+ and8(
3819
+ eq11(processEvents.instanceId, instanceId),
3634
3820
  inArray3(processEvents.eventType, filteredEventTypes),
3635
- eq10(processEvents.turnRecordId, turnRecordId)
3821
+ eq11(processEvents.turnRecordId, turnRecordId)
3636
3822
  )
3637
- ).orderBy(asc4(processEvents.eventSequence)).all().map(rowToProcessEvent);
3823
+ ).orderBy(asc5(processEvents.eventSequence)).all().map(rowToProcessEvent);
3638
3824
  },
3639
3825
  /** @internal */
3640
3826
  listByInstanceSinceEventTypes(instanceId, sinceCreatedAt, eventTypes, limit = 100) {
@@ -3643,8 +3829,8 @@ function createProcessEventRepo(db) {
3643
3829
  return [];
3644
3830
  }
3645
3831
  return listNewest(
3646
- and7(
3647
- eq10(processEvents.instanceId, instanceId),
3832
+ and8(
3833
+ eq11(processEvents.instanceId, instanceId),
3648
3834
  gte(processEvents.createdAt, sinceCreatedAt),
3649
3835
  inArray3(processEvents.eventType, filteredEventTypes)
3650
3836
  ),
@@ -3655,7 +3841,7 @@ function createProcessEventRepo(db) {
3655
3841
  }
3656
3842
 
3657
3843
  // src/db/process-handoff-dedup-key-repo.ts
3658
- import { eq as eq11 } from "drizzle-orm";
3844
+ import { eq as eq12 } from "drizzle-orm";
3659
3845
  function rowToRecord(row) {
3660
3846
  return {
3661
3847
  key: row.key,
@@ -3679,7 +3865,7 @@ function createProcessHandoffDedupKeyRepo(db) {
3679
3865
  },
3680
3866
  /** @internal */
3681
3867
  getByKey(key) {
3682
- const row = db.select().from(processHandoffDedupKeys).where(eq11(processHandoffDedupKeys.key, key)).get();
3868
+ const row = db.select().from(processHandoffDedupKeys).where(eq12(processHandoffDedupKeys.key, key)).get();
3683
3869
  return row ? rowToRecord(row) : null;
3684
3870
  }
3685
3871
  };
@@ -3687,7 +3873,7 @@ function createProcessHandoffDedupKeyRepo(db) {
3687
3873
 
3688
3874
  // src/db/process-input-repo.ts
3689
3875
  import { parseActorOrSystem, SYSTEM_ACTOR, serializeActor } from "@leitwerk-dev/domain";
3690
- import { and as and8, asc as asc5, eq as eq12, isNull as isNull2, max } from "drizzle-orm";
3876
+ import { and as and9, asc as asc6, eq as eq13, isNull as isNull2, max } from "drizzle-orm";
3691
3877
  function toProcessInputTarget(semanticRef, productName) {
3692
3878
  if (productName) {
3693
3879
  return { productName };
@@ -3710,11 +3896,11 @@ function rowToProcessInput(row) {
3710
3896
  }
3711
3897
  function createProcessInputRepo(db) {
3712
3898
  const list = (instanceId, unconsumed = false) => db.select().from(processInputs).where(
3713
- and8(
3714
- eq12(processInputs.instanceId, instanceId),
3899
+ and9(
3900
+ eq13(processInputs.instanceId, instanceId),
3715
3901
  unconsumed ? isNull2(processInputs.consumedAt) : void 0
3716
3902
  )
3717
- ).orderBy(asc5(processInputs.sequence)).all().map(rowToProcessInput);
3903
+ ).orderBy(asc6(processInputs.sequence)).all().map(rowToProcessInput);
3718
3904
  return {
3719
3905
  /** @internal */
3720
3906
  create(input) {
@@ -3742,17 +3928,17 @@ function createProcessInputRepo(db) {
3742
3928
  listUnconsumed: (instanceId) => list(instanceId, true),
3743
3929
  /** @internal */
3744
3930
  markConsumed(id) {
3745
- const result = db.update(processInputs).set({ consumedAt: now() }).where(eq12(processInputs.id, id)).run();
3931
+ const result = db.update(processInputs).set({ consumedAt: now() }).where(eq13(processInputs.id, id)).run();
3746
3932
  return result.changes > 0;
3747
3933
  },
3748
3934
  /** @internal */
3749
3935
  delete(id) {
3750
- const result = db.delete(processInputs).where(eq12(processInputs.id, id)).run();
3936
+ const result = db.delete(processInputs).where(eq13(processInputs.id, id)).run();
3751
3937
  return result.changes > 0;
3752
3938
  },
3753
3939
  /** @internal */
3754
3940
  getMaxSequence(instanceId) {
3755
- const row = db.select({ sequence: max(processInputs.sequence) }).from(processInputs).where(eq12(processInputs.instanceId, instanceId)).get();
3941
+ const row = db.select({ sequence: max(processInputs.sequence) }).from(processInputs).where(eq13(processInputs.instanceId, instanceId)).get();
3756
3942
  return row?.sequence ?? 0;
3757
3943
  }
3758
3944
  };
@@ -3762,7 +3948,7 @@ function createProcessInputRepo(db) {
3762
3948
  import {
3763
3949
  isProcessSelectedTurnModelSource
3764
3950
  } from "@leitwerk-dev/domain";
3765
- import { and as and9, asc as asc6, count as count2, desc as desc6, eq as eq13, inArray as inArray4, notInArray, or as or2, sql as sql4 } from "drizzle-orm";
3951
+ import { and as and10, asc as asc7, count as count2, desc as desc6, eq as eq14, inArray as inArray4, notInArray, or as or2, sql as sql4 } from "drizzle-orm";
3766
3952
 
3767
3953
  // src/launch-title.ts
3768
3954
  var MAX_PROCESS_TITLE_LENGTH = 80;
@@ -3809,7 +3995,7 @@ function overviewPredicates2(input) {
3809
3995
  const predicates = [];
3810
3996
  const processType = input.processType?.trim();
3811
3997
  if (processType) {
3812
- predicates.push(eq13(processInstances.processId, processType));
3998
+ predicates.push(eq14(processInstances.processId, processType));
3813
3999
  }
3814
4000
  switch (input.status ?? "all") {
3815
4001
  case "running":
@@ -3819,10 +4005,10 @@ function overviewPredicates2(input) {
3819
4005
  predicates.push(inArray4(processInstances.lifecycleStatus, ["waiting", "error"]));
3820
4006
  break;
3821
4007
  case "completed":
3822
- predicates.push(eq13(processInstances.lifecycleStatus, "completed"));
4008
+ predicates.push(eq14(processInstances.lifecycleStatus, "completed"));
3823
4009
  break;
3824
4010
  case "aborted":
3825
- predicates.push(eq13(processInstances.lifecycleStatus, "aborted"));
4011
+ predicates.push(eq14(processInstances.lifecycleStatus, "aborted"));
3826
4012
  break;
3827
4013
  case "scheduled":
3828
4014
  predicates.push(sql4`0 = 1`);
@@ -3844,7 +4030,7 @@ function overviewPredicates2(input) {
3844
4030
  }
3845
4031
  function overviewWhere2(input) {
3846
4032
  const predicates = overviewPredicates2(input);
3847
- return predicates.length ? and9(...predicates) : void 0;
4033
+ return predicates.length ? and10(...predicates) : void 0;
3848
4034
  }
3849
4035
  function parseLaunchIntent(raw) {
3850
4036
  if (!raw) return null;
@@ -3884,7 +4070,7 @@ function createProcessInstanceRepo(db) {
3884
4070
  return {
3885
4071
  /** @internal */
3886
4072
  getLaunchIntent(instanceId) {
3887
- const row = db.select({ launchIntentJson: processInstances.launchIntentJson }).from(processInstances).where(eq13(processInstances.id, instanceId)).get();
4073
+ const row = db.select({ launchIntentJson: processInstances.launchIntentJson }).from(processInstances).where(eq14(processInstances.id, instanceId)).get();
3888
4074
  return parseLaunchIntent(row?.launchIntentJson ?? null);
3889
4075
  },
3890
4076
  /** @public */
@@ -3921,7 +4107,7 @@ function createProcessInstanceRepo(db) {
3921
4107
  },
3922
4108
  /** @public */
3923
4109
  getById(id) {
3924
- const row = db.select().from(processInstances).where(eq13(processInstances.id, id)).get();
4110
+ const row = db.select().from(processInstances).where(eq14(processInstances.id, id)).get();
3925
4111
  return row ? rowToProcessInstance(row) : null;
3926
4112
  },
3927
4113
  /** @public */
@@ -3930,7 +4116,7 @@ function createProcessInstanceRepo(db) {
3930
4116
  },
3931
4117
  /** @internal */
3932
4118
  listCurrent(limit) {
3933
- return db.select().from(processInstances).where(notInArray(processInstances.lifecycleStatus, ["completed", "aborted"])).orderBy(desc6(processInstances.updatedAt), asc6(processInstances.id)).limit(limit).all().map(rowToProcessInstance);
4119
+ return db.select().from(processInstances).where(notInArray(processInstances.lifecycleStatus, ["completed", "aborted"])).orderBy(desc6(processInstances.updatedAt), asc7(processInstances.id)).limit(limit).all().map(rowToProcessInstance);
3934
4120
  },
3935
4121
  /** @internal */
3936
4122
  countCurrent() {
@@ -3956,7 +4142,7 @@ function createProcessInstanceRepo(db) {
3956
4142
  processId: processInstances.processId,
3957
4143
  /** @internal */
3958
4144
  value: count2()
3959
- }).from(processInstances).where(overviewWhere2(input)).groupBy(processInstances.processId).orderBy(asc6(processInstances.processId)).all();
4145
+ }).from(processInstances).where(overviewWhere2(input)).groupBy(processInstances.processId).orderBy(asc7(processInstances.processId)).all();
3960
4146
  },
3961
4147
  /** @internal */
3962
4148
  listOverviewWindow(input) {
@@ -3972,9 +4158,9 @@ function createProcessInstanceRepo(db) {
3972
4158
  else ${processInstances.updatedAt} end`;
3973
4159
  const primary = input.sortKey === "status" ? status : input.sortKey === "title" ? title : timeline;
3974
4160
  return db.select().from(processInstances).where(overviewWhere2(input)).orderBy(
3975
- input.sortDirection === "desc" ? desc6(primary) : asc6(primary),
3976
- asc6(title),
3977
- asc6(processInstances.id)
4161
+ input.sortDirection === "desc" ? desc6(primary) : asc7(primary),
4162
+ asc7(title),
4163
+ asc7(processInstances.id)
3978
4164
  ).limit(input.limit).all().map(rowToProcessInstance);
3979
4165
  },
3980
4166
  /** @internal */
@@ -3984,8 +4170,8 @@ function createProcessInstanceRepo(db) {
3984
4170
  return null;
3985
4171
  }
3986
4172
  const result = db.update(processInstances).set({ title: normalizedTitle, updatedAt: now() }).where(
3987
- and9(
3988
- eq13(processInstances.id, id),
4173
+ and10(
4174
+ eq14(processInstances.id, id),
3989
4175
  sql4`trim(coalesce(${processInstances.title}, '')) = ''`
3990
4176
  )
3991
4177
  ).run();
@@ -4019,19 +4205,19 @@ function createProcessInstanceRepo(db) {
4019
4205
  if (isTerminalLifecycleStatus(input.lifecycleStatus)) {
4020
4206
  setValues.closedAt = sql4`coalesce(${processInstances.closedAt}, ${ts})`;
4021
4207
  }
4022
- db.update(processInstances).set(setValues).where(eq13(processInstances.id, id)).run();
4208
+ db.update(processInstances).set(setValues).where(eq14(processInstances.id, id)).run();
4023
4209
  return this.getById(id);
4024
4210
  },
4025
4211
  /** @internal */
4026
4212
  delete(id) {
4027
- const result = db.delete(processInstances).where(eq13(processInstances.id, id)).run();
4213
+ const result = db.delete(processInstances).where(eq14(processInstances.id, id)).run();
4028
4214
  return result.changes > 0;
4029
4215
  }
4030
4216
  };
4031
4217
  }
4032
4218
 
4033
4219
  // src/db/process-leaf-outcome-snapshot-repo.ts
4034
- import { and as and10, asc as asc7, desc as desc7, eq as eq14, sql as sql5 } from "drizzle-orm";
4220
+ import { and as and11, asc as asc8, desc as desc7, eq as eq15, sql as sql5 } from "drizzle-orm";
4035
4221
  function rowToProcessLeafOutcomeSnapshot(row) {
4036
4222
  return {
4037
4223
  id: row.id,
@@ -4073,17 +4259,17 @@ function createProcessLeafOutcomeSnapshotRepo(db) {
4073
4259
  },
4074
4260
  /** @internal */
4075
4261
  listByInstance(instanceId) {
4076
- return db.select().from(processLeafOutcomeSnapshots).where(eq14(processLeafOutcomeSnapshots.instanceId, instanceId)).orderBy(
4077
- asc7(processLeafOutcomeSnapshots.anchoredAt),
4078
- asc7(processLeafOutcomeSnapshots.createdAt)
4262
+ return db.select().from(processLeafOutcomeSnapshots).where(eq15(processLeafOutcomeSnapshots.instanceId, instanceId)).orderBy(
4263
+ asc8(processLeafOutcomeSnapshots.anchoredAt),
4264
+ asc8(processLeafOutcomeSnapshots.createdAt)
4079
4265
  ).all().map(rowToProcessLeafOutcomeSnapshot);
4080
4266
  },
4081
4267
  /** @internal */
4082
4268
  getByInstanceAndLeafEntryId(instanceId, leafEntryId) {
4083
4269
  const row = db.select().from(processLeafOutcomeSnapshots).where(
4084
- and10(
4085
- eq14(processLeafOutcomeSnapshots.instanceId, instanceId),
4086
- eq14(processLeafOutcomeSnapshots.leafEntryId, leafEntryId)
4270
+ and11(
4271
+ eq15(processLeafOutcomeSnapshots.instanceId, instanceId),
4272
+ eq15(processLeafOutcomeSnapshots.leafEntryId, leafEntryId)
4087
4273
  )
4088
4274
  ).orderBy(desc7(processLeafOutcomeSnapshots.createdAt), desc7(sql5`rowid`)).limit(1).get();
4089
4275
  return row ? rowToProcessLeafOutcomeSnapshot(row) : null;
@@ -4096,7 +4282,7 @@ import {
4096
4282
  assertRepoLocator,
4097
4283
  detectRepoLocatorKind
4098
4284
  } from "@leitwerk-dev/domain";
4099
- import { and as and11, eq as eq15, inArray as inArray5 } from "drizzle-orm";
4285
+ import { and as and12, eq as eq16, inArray as inArray5 } from "drizzle-orm";
4100
4286
  function rowToProcessProject(row) {
4101
4287
  return {
4102
4288
  id: row.id,
@@ -4142,12 +4328,12 @@ function createProcessProjectRepo(db) {
4142
4328
  },
4143
4329
  /** @internal */
4144
4330
  getById(id) {
4145
- const row = db.select().from(processProjects).where(eq15(processProjects.id, id)).get();
4331
+ const row = db.select().from(processProjects).where(eq16(processProjects.id, id)).get();
4146
4332
  return row ? rowToProcessProject(row) : null;
4147
4333
  },
4148
4334
  /** @public */
4149
4335
  listByInstance(instanceId) {
4150
- return db.select().from(processProjects).where(eq15(processProjects.instanceId, instanceId)).all().map(rowToProcessProject);
4336
+ return db.select().from(processProjects).where(eq16(processProjects.instanceId, instanceId)).all().map(rowToProcessProject);
4151
4337
  },
4152
4338
  /** @internal */
4153
4339
  listByInstances(instanceIds) {
@@ -4158,7 +4344,7 @@ function createProcessProjectRepo(db) {
4158
4344
  },
4159
4345
  /** @internal */
4160
4346
  getByInstanceAndKey(instanceId, key) {
4161
- const row = db.select().from(processProjects).where(and11(eq15(processProjects.instanceId, instanceId), eq15(processProjects.key, key))).get();
4347
+ const row = db.select().from(processProjects).where(and12(eq16(processProjects.instanceId, instanceId), eq16(processProjects.key, key))).get();
4162
4348
  return row ? rowToProcessProject(row) : null;
4163
4349
  },
4164
4350
  /** @public */
@@ -4183,15 +4369,15 @@ function createProcessProjectRepo(db) {
4183
4369
  }
4184
4370
  if (input.metadata !== void 0)
4185
4371
  setValues.metadata = input.metadata ? JSON.stringify(input.metadata) : null;
4186
- db.update(processProjects).set(setValues).where(eq15(processProjects.id, id)).run();
4187
- const row = db.select().from(processProjects).where(eq15(processProjects.id, id)).get();
4372
+ db.update(processProjects).set(setValues).where(eq16(processProjects.id, id)).run();
4373
+ const row = db.select().from(processProjects).where(eq16(processProjects.id, id)).get();
4188
4374
  return row ? rowToProcessProject(row) : null;
4189
4375
  }
4190
4376
  };
4191
4377
  }
4192
4378
 
4193
4379
  // src/db/process-question-request-repo.ts
4194
- import { and as and12, asc as asc8, eq as eq16 } from "drizzle-orm";
4380
+ import { and as and13, asc as asc9, eq as eq17 } from "drizzle-orm";
4195
4381
  function map(row) {
4196
4382
  return {
4197
4383
  id: row.id,
@@ -4209,15 +4395,15 @@ function map(row) {
4209
4395
  }
4210
4396
  function createProcessQuestionRequestRepo(db) {
4211
4397
  const getById = (id) => {
4212
- const row = db.select().from(processQuestionRequests).where(eq16(processQuestionRequests.id, id)).get();
4398
+ const row = db.select().from(processQuestionRequests).where(eq17(processQuestionRequests.id, id)).get();
4213
4399
  return row ? map(row) : null;
4214
4400
  };
4215
4401
  const list = (instanceId, openOnly = false) => {
4216
4402
  const filters = [
4217
- ...instanceId ? [eq16(processQuestionRequests.instanceId, instanceId)] : [],
4218
- ...openOnly ? [eq16(processQuestionRequests.status, "open")] : []
4403
+ ...instanceId ? [eq17(processQuestionRequests.instanceId, instanceId)] : [],
4404
+ ...openOnly ? [eq17(processQuestionRequests.status, "open")] : []
4219
4405
  ];
4220
- return db.select().from(processQuestionRequests).where(filters.length ? and12(...filters) : void 0).orderBy(asc8(processQuestionRequests.askedAt)).all().map(map);
4406
+ return db.select().from(processQuestionRequests).where(filters.length ? and13(...filters) : void 0).orderBy(asc9(processQuestionRequests.askedAt)).all().map(map);
4221
4407
  };
4222
4408
  return {
4223
4409
  /** @internal */
@@ -4229,10 +4415,10 @@ function createProcessQuestionRequestRepo(db) {
4229
4415
  /** @internal */
4230
4416
  createIdempotent(input) {
4231
4417
  const existingRow = db.select().from(processQuestionRequests).where(
4232
- and12(
4233
- eq16(processQuestionRequests.instanceId, input.instanceId),
4234
- eq16(processQuestionRequests.turnRecordId, input.turnRecordId),
4235
- eq16(processQuestionRequests.toolCallId, input.toolCallId)
4418
+ and13(
4419
+ eq17(processQuestionRequests.instanceId, input.instanceId),
4420
+ eq17(processQuestionRequests.turnRecordId, input.turnRecordId),
4421
+ eq17(processQuestionRequests.toolCallId, input.toolCallId)
4236
4422
  )
4237
4423
  ).get();
4238
4424
  if (existingRow) {
@@ -4260,9 +4446,9 @@ function createProcessQuestionRequestRepo(db) {
4260
4446
  answeredAt: input.answeredAt ?? now(),
4261
4447
  answeredByJson: JSON.stringify(input.actor)
4262
4448
  }).where(
4263
- and12(
4264
- eq16(processQuestionRequests.id, input.id),
4265
- eq16(processQuestionRequests.status, "open")
4449
+ and13(
4450
+ eq17(processQuestionRequests.id, input.id),
4451
+ eq17(processQuestionRequests.status, "open")
4266
4452
  )
4267
4453
  ).returning().get();
4268
4454
  return row ? map(row) : null;
@@ -4271,10 +4457,10 @@ function createProcessQuestionRequestRepo(db) {
4271
4457
  cancelOpenByTurn(instanceId, turnRecordId) {
4272
4458
  return Number(
4273
4459
  db.update(processQuestionRequests).set({ status: "cancelled", cancelledAt: now() }).where(
4274
- and12(
4275
- eq16(processQuestionRequests.instanceId, instanceId),
4276
- eq16(processQuestionRequests.turnRecordId, turnRecordId),
4277
- eq16(processQuestionRequests.status, "open")
4460
+ and13(
4461
+ eq17(processQuestionRequests.instanceId, instanceId),
4462
+ eq17(processQuestionRequests.turnRecordId, turnRecordId),
4463
+ eq17(processQuestionRequests.status, "open")
4278
4464
  )
4279
4465
  ).run().changes
4280
4466
  );
@@ -4283,7 +4469,7 @@ function createProcessQuestionRequestRepo(db) {
4283
4469
  }
4284
4470
 
4285
4471
  // src/db/process-relation-repo.ts
4286
- import { asc as asc9, eq as eq17 } from "drizzle-orm";
4472
+ import { asc as asc10, eq as eq18 } from "drizzle-orm";
4287
4473
  function map2(row) {
4288
4474
  return {
4289
4475
  parentInstanceId: row.parentInstanceId,
@@ -4310,18 +4496,18 @@ function createProcessRelationRepo(db) {
4310
4496
  },
4311
4497
  /** @internal */
4312
4498
  getByChild(childInstanceId) {
4313
- const row = db.select().from(processRelations).where(eq17(processRelations.childInstanceId, childInstanceId)).get();
4499
+ const row = db.select().from(processRelations).where(eq18(processRelations.childInstanceId, childInstanceId)).get();
4314
4500
  return row ? map2(row) : null;
4315
4501
  },
4316
4502
  /** @internal */
4317
4503
  listByParent(parentInstanceId) {
4318
- return db.select().from(processRelations).where(eq17(processRelations.parentInstanceId, parentInstanceId)).orderBy(asc9(processRelations.createdAt)).all().map(map2);
4504
+ return db.select().from(processRelations).where(eq18(processRelations.parentInstanceId, parentInstanceId)).orderBy(asc10(processRelations.createdAt)).all().map(map2);
4319
4505
  }
4320
4506
  };
4321
4507
  }
4322
4508
 
4323
4509
  // src/db/process-skill-repo.ts
4324
- import { asc as asc10, eq as eq18 } from "drizzle-orm";
4510
+ import { asc as asc11, eq as eq19 } from "drizzle-orm";
4325
4511
 
4326
4512
  // src/pi-resources/resource-collector.ts
4327
4513
  import { constants } from "node:fs";
@@ -4508,7 +4694,7 @@ function createProcessSkillRepo(db) {
4508
4694
  if (seen.has(selection.skillId))
4509
4695
  throw new Error(`Duplicate skill selection '${selection.skillId}'`);
4510
4696
  seen.add(selection.skillId);
4511
- const revision = db.select().from(skillRevisions).where(eq18(skillRevisions.id, selection.revisionId)).get();
4697
+ const revision = db.select().from(skillRevisions).where(eq19(skillRevisions.id, selection.revisionId)).get();
4512
4698
  if (!revision || revision.skillId !== selection.skillId)
4513
4699
  throw new Error(`Invalid revision for skill '${selection.skillId}'`);
4514
4700
  db.insert(processSkills).values({
@@ -4524,14 +4710,14 @@ function createProcessSkillRepo(db) {
4524
4710
  return db.select({
4525
4711
  skillId: processSkills.skillId,
4526
4712
  revisionId: processSkills.skillRevisionId
4527
- }).from(processSkills).where(eq18(processSkills.instanceId, instanceId)).orderBy(asc10(processSkills.position)).all();
4713
+ }).from(processSkills).where(eq19(processSkills.instanceId, instanceId)).orderBy(asc11(processSkills.position)).all();
4528
4714
  },
4529
4715
  /** @internal */
4530
4716
  listResourceLayers(instanceId) {
4531
4717
  return db.select({
4532
4718
  digest: skillRevisions.bundleDigest,
4533
4719
  bytes: skillRevisions.bundleBytes
4534
- }).from(processSkills).innerJoin(skillRevisions, eq18(processSkills.skillRevisionId, skillRevisions.id)).where(eq18(processSkills.instanceId, instanceId)).orderBy(asc10(processSkills.position)).all().map(({ digest, bytes }) => ({
4720
+ }).from(processSkills).innerJoin(skillRevisions, eq19(processSkills.skillRevisionId, skillRevisions.id)).where(eq19(processSkills.instanceId, instanceId)).orderBy(asc11(processSkills.position)).all().map(({ digest, bytes }) => ({
4535
4721
  bundle: { digest, bytes },
4536
4722
  owner: SKILL_RESOURCE_OWNER
4537
4723
  }));
@@ -4540,10 +4726,10 @@ function createProcessSkillRepo(db) {
4540
4726
  }
4541
4727
 
4542
4728
  // src/db/process-title-job-repo.ts
4543
- import { and as and13, asc as asc11, eq as eq19, inArray as inArray6, lte as lte2, sql as sql6 } from "drizzle-orm";
4729
+ import { and as and14, asc as asc12, eq as eq20, inArray as inArray6, lte as lte2, sql as sql6 } from "drizzle-orm";
4544
4730
  function createProcessTitleJobRepo(db) {
4545
4731
  function transition(id, from, values) {
4546
- return db.update(processTitleJobs).set({ ...values, updatedAt: now() }).where(and13(eq19(processTitleJobs.id, id), inArray6(processTitleJobs.status, from))).returning().get() ?? null;
4732
+ return db.update(processTitleJobs).set({ ...values, updatedAt: now() }).where(and14(eq20(processTitleJobs.id, id), inArray6(processTitleJobs.status, from))).returning().get() ?? null;
4547
4733
  }
4548
4734
  return {
4549
4735
  /** @internal */
@@ -4559,9 +4745,9 @@ function createProcessTitleJobRepo(db) {
4559
4745
  expectedPayloadJson: input.expectedPayloadJson
4560
4746
  };
4561
4747
  db.update(processTitleJobs).set({ status: "superseded", updatedAt: ts }).where(
4562
- and13(
4748
+ and14(
4563
4749
  inArray6(processTitleJobs.status, ["pending", "running"]),
4564
- target2.targetKind === "process" ? eq19(processTitleJobs.processInstanceId, target2.processInstanceId) : eq19(processTitleJobs.futureExecutionId, target2.futureExecutionId)
4750
+ target2.targetKind === "process" ? eq20(processTitleJobs.processInstanceId, target2.processInstanceId) : eq20(processTitleJobs.futureExecutionId, target2.futureExecutionId)
4565
4751
  )
4566
4752
  ).run();
4567
4753
  return db.insert(processTitleJobs).values({
@@ -4579,22 +4765,22 @@ function createProcessTitleJobRepo(db) {
4579
4765
  },
4580
4766
  /** @internal */
4581
4767
  getById(id) {
4582
- const row = db.select().from(processTitleJobs).where(eq19(processTitleJobs.id, id)).get();
4768
+ const row = db.select().from(processTitleJobs).where(eq20(processTitleJobs.id, id)).get();
4583
4769
  return row ?? null;
4584
4770
  },
4585
4771
  /** @internal */
4586
4772
  listByProcessInstance(processInstanceId) {
4587
- return db.select().from(processTitleJobs).where(eq19(processTitleJobs.processInstanceId, processInstanceId)).orderBy(asc11(processTitleJobs.createdAt), asc11(processTitleJobs.id)).all();
4773
+ return db.select().from(processTitleJobs).where(eq20(processTitleJobs.processInstanceId, processInstanceId)).orderBy(asc12(processTitleJobs.createdAt), asc12(processTitleJobs.id)).all();
4588
4774
  },
4589
4775
  /** @internal */
4590
4776
  listAll() {
4591
- return db.select().from(processTitleJobs).orderBy(asc11(processTitleJobs.createdAt), asc11(processTitleJobs.id)).all();
4777
+ return db.select().from(processTitleJobs).orderBy(asc12(processTitleJobs.createdAt), asc12(processTitleJobs.id)).all();
4592
4778
  },
4593
4779
  /** @internal */
4594
4780
  listDuePending(asOf, limit) {
4595
4781
  return db.select().from(processTitleJobs).where(
4596
- and13(eq19(processTitleJobs.status, "pending"), lte2(processTitleJobs.nextRunAt, asOf))
4597
- ).orderBy(asc11(processTitleJobs.nextRunAt), asc11(processTitleJobs.createdAt)).limit(Math.max(0, limit)).all();
4782
+ and14(eq20(processTitleJobs.status, "pending"), lte2(processTitleJobs.nextRunAt, asOf))
4783
+ ).orderBy(asc12(processTitleJobs.nextRunAt), asc12(processTitleJobs.createdAt)).limit(Math.max(0, limit)).all();
4598
4784
  },
4599
4785
  /** @internal */
4600
4786
  markRunning(id) {
@@ -4624,7 +4810,7 @@ function createProcessTitleJobRepo(db) {
4624
4810
  }
4625
4811
 
4626
4812
  // src/db/process-tool-approval-request-repo.ts
4627
- import { and as and14, asc as asc12, eq as eq20 } from "drizzle-orm";
4813
+ import { and as and15, asc as asc13, eq as eq21 } from "drizzle-orm";
4628
4814
  function map3(row) {
4629
4815
  return {
4630
4816
  id: row.id,
@@ -4650,10 +4836,10 @@ function map3(row) {
4650
4836
  function createProcessToolApprovalRequestRepo(db) {
4651
4837
  const list = (instanceId, openOnly = false) => {
4652
4838
  const filters = [
4653
- ...instanceId ? [eq20(processToolApprovalRequests.instanceId, instanceId)] : [],
4654
- ...openOnly ? [eq20(processToolApprovalRequests.status, "open")] : []
4839
+ ...instanceId ? [eq21(processToolApprovalRequests.instanceId, instanceId)] : [],
4840
+ ...openOnly ? [eq21(processToolApprovalRequests.status, "open")] : []
4655
4841
  ];
4656
- return db.select().from(processToolApprovalRequests).where(filters.length ? and14(...filters) : void 0).orderBy(asc12(processToolApprovalRequests.requestedAt)).all().map(map3);
4842
+ return db.select().from(processToolApprovalRequests).where(filters.length ? and15(...filters) : void 0).orderBy(asc13(processToolApprovalRequests.requestedAt)).all().map(map3);
4657
4843
  };
4658
4844
  return {
4659
4845
  /** @internal */
@@ -4663,10 +4849,10 @@ function createProcessToolApprovalRequestRepo(db) {
4663
4849
  /** @internal */
4664
4850
  createIdempotent(input) {
4665
4851
  const existing = db.select().from(processToolApprovalRequests).where(
4666
- and14(
4667
- eq20(processToolApprovalRequests.instanceId, input.instanceId),
4668
- eq20(processToolApprovalRequests.turnRecordId, input.turnRecordId),
4669
- eq20(processToolApprovalRequests.toolCallId, input.toolCallId)
4852
+ and15(
4853
+ eq21(processToolApprovalRequests.instanceId, input.instanceId),
4854
+ eq21(processToolApprovalRequests.turnRecordId, input.turnRecordId),
4855
+ eq21(processToolApprovalRequests.toolCallId, input.toolCallId)
4670
4856
  )
4671
4857
  ).get();
4672
4858
  if (existing) {
@@ -4698,9 +4884,9 @@ function createProcessToolApprovalRequestRepo(db) {
4698
4884
  resolvedByJson: JSON.stringify(input.actor),
4699
4885
  feedback: input.feedback?.trim() ?? null
4700
4886
  }).where(
4701
- and14(
4702
- eq20(processToolApprovalRequests.id, input.id),
4703
- eq20(processToolApprovalRequests.status, "open")
4887
+ and15(
4888
+ eq21(processToolApprovalRequests.id, input.id),
4889
+ eq21(processToolApprovalRequests.status, "open")
4704
4890
  )
4705
4891
  ).returning().get();
4706
4892
  return row ? map3(row) : null;
@@ -4708,10 +4894,10 @@ function createProcessToolApprovalRequestRepo(db) {
4708
4894
  /** @internal */
4709
4895
  cancelOpenByTurn(instanceId, turnRecordId) {
4710
4896
  const result = db.update(processToolApprovalRequests).set({ status: "cancelled", resolvedAt: now() }).where(
4711
- and14(
4712
- eq20(processToolApprovalRequests.instanceId, instanceId),
4713
- eq20(processToolApprovalRequests.turnRecordId, turnRecordId),
4714
- eq20(processToolApprovalRequests.status, "open")
4897
+ and15(
4898
+ eq21(processToolApprovalRequests.instanceId, instanceId),
4899
+ eq21(processToolApprovalRequests.turnRecordId, turnRecordId),
4900
+ eq21(processToolApprovalRequests.status, "open")
4715
4901
  )
4716
4902
  ).run();
4717
4903
  return Number(result.changes);
@@ -4721,7 +4907,7 @@ function createProcessToolApprovalRequestRepo(db) {
4721
4907
 
4722
4908
  // src/db/process-turn-annotation-repo.ts
4723
4909
  import { parseTurnAnnotationReferences } from "@leitwerk-dev/domain";
4724
- import { and as and15, asc as asc13, eq as eq21 } from "drizzle-orm";
4910
+ import { and as and16, asc as asc14, eq as eq22 } from "drizzle-orm";
4725
4911
  function parseReferences(value) {
4726
4912
  try {
4727
4913
  return parseTurnAnnotationReferences(JSON.parse(value));
@@ -4763,7 +4949,7 @@ function createProcessTurnAnnotationRepo(db) {
4763
4949
  },
4764
4950
  /** @internal */
4765
4951
  getById(id) {
4766
- const row = db.select().from(turnAnnotations).where(eq21(turnAnnotations.id, id)).get();
4952
+ const row = db.select().from(turnAnnotations).where(eq22(turnAnnotations.id, id)).get();
4767
4953
  return row ? rowToProcessTurnAnnotation(row) : null;
4768
4954
  },
4769
4955
  /** @internal */
@@ -4773,16 +4959,16 @@ function createProcessTurnAnnotationRepo(db) {
4773
4959
  return null;
4774
4960
  }
4775
4961
  const row = db.select().from(turnAnnotations).where(
4776
- and15(
4777
- eq21(turnAnnotations.instanceId, instanceId),
4778
- eq21(turnAnnotations.annotationKey, key)
4962
+ and16(
4963
+ eq22(turnAnnotations.instanceId, instanceId),
4964
+ eq22(turnAnnotations.annotationKey, key)
4779
4965
  )
4780
4966
  ).get();
4781
4967
  return row ? rowToProcessTurnAnnotation(row) : null;
4782
4968
  },
4783
4969
  /** @internal */
4784
4970
  listByInstance(instanceId) {
4785
- return db.select().from(turnAnnotations).where(eq21(turnAnnotations.instanceId, instanceId)).orderBy(asc13(turnAnnotations.createdAt)).all().map(rowToProcessTurnAnnotation);
4971
+ return db.select().from(turnAnnotations).where(eq22(turnAnnotations.instanceId, instanceId)).orderBy(asc14(turnAnnotations.createdAt)).all().map(rowToProcessTurnAnnotation);
4786
4972
  },
4787
4973
  /** @internal */
4788
4974
  update(id, input) {
@@ -4794,19 +4980,19 @@ function createProcessTurnAnnotationRepo(db) {
4794
4980
  if (input.references !== void 0)
4795
4981
  setValues.referencesJson = JSON.stringify(input.references);
4796
4982
  if (input.payload !== void 0) setValues.payloadJson = JSON.stringify(input.payload);
4797
- db.update(turnAnnotations).set(setValues).where(eq21(turnAnnotations.id, id)).run();
4983
+ db.update(turnAnnotations).set(setValues).where(eq22(turnAnnotations.id, id)).run();
4798
4984
  return this.getById(id);
4799
4985
  },
4800
4986
  /** @internal */
4801
4987
  delete(id) {
4802
- const result = db.delete(turnAnnotations).where(eq21(turnAnnotations.id, id)).run();
4988
+ const result = db.delete(turnAnnotations).where(eq22(turnAnnotations.id, id)).run();
4803
4989
  return result.changes > 0;
4804
4990
  }
4805
4991
  };
4806
4992
  }
4807
4993
 
4808
4994
  // src/db/process-turn-record-repo.ts
4809
- import { asc as asc14, desc as desc8, eq as eq22 } from "drizzle-orm";
4995
+ import { asc as asc15, desc as desc8, eq as eq23 } from "drizzle-orm";
4810
4996
  function rowToProcessTurnRecord(row) {
4811
4997
  return {
4812
4998
  id: row.id,
@@ -4826,6 +5012,7 @@ function rowToProcessTurnRecord(row) {
4826
5012
  kind: row.modelSelectionKind,
4827
5013
  source: row.modelSelectionSource
4828
5014
  } : null,
5015
+ iteration: mappedItemRef(row),
4829
5016
  turnResultMarkdown: row.turnResultMarkdown ?? null,
4830
5017
  errorSummary: row.errorSummary ?? null,
4831
5018
  errorClass: row.errorClass ?? null,
@@ -4858,23 +5045,26 @@ function createProcessTurnRecordRepo(db) {
4858
5045
  errorSummary: input.errorSummary ?? null,
4859
5046
  errorClass: input.errorClass ?? null,
4860
5047
  startedAt: input.startedAt ?? now(),
4861
- endedAt: input.endedAt ?? null
5048
+ endedAt: input.endedAt ?? null,
5049
+ mappedRunId: input.iteration?.runId ?? null,
5050
+ mappedItemKey: input.iteration?.itemKey ?? null,
5051
+ mappedItemIndex: input.iteration?.itemIndex ?? null
4862
5052
  };
4863
5053
  db.insert(turnRecords).values(values).run();
4864
5054
  return rowToProcessTurnRecord(values);
4865
5055
  },
4866
5056
  /** @internal */
4867
5057
  getById(id) {
4868
- const row = db.select().from(turnRecords).where(eq22(turnRecords.id, id)).get();
5058
+ const row = db.select().from(turnRecords).where(eq23(turnRecords.id, id)).get();
4869
5059
  return row ? rowToProcessTurnRecord(row) : null;
4870
5060
  },
4871
5061
  /** @public */
4872
5062
  listByInstance(instanceId) {
4873
- return db.select().from(turnRecords).where(eq22(turnRecords.instanceId, instanceId)).orderBy(asc14(turnRecords.startedAt)).all().map(rowToProcessTurnRecord);
5063
+ return db.select().from(turnRecords).where(eq23(turnRecords.instanceId, instanceId)).orderBy(asc15(turnRecords.startedAt)).all().map(rowToProcessTurnRecord);
4874
5064
  },
4875
5065
  /** @internal */
4876
5066
  getLatestSucceededPrimaryByInstance(instanceId) {
4877
- const row = db.select().from(turnRecords).where(eq22(turnRecords.instanceId, instanceId)).orderBy(desc8(turnRecords.startedAt)).all().map(rowToProcessTurnRecord).find(
5067
+ const row = db.select().from(turnRecords).where(eq23(turnRecords.instanceId, instanceId)).orderBy(desc8(turnRecords.startedAt)).all().map(rowToProcessTurnRecord).find(
4878
5068
  (run) => run.status === "succeeded" && run.pathType === "primary" && typeof run.resultPiEntryId === "string" && run.resultPiEntryId.length > 0
4879
5069
  );
4880
5070
  return row ?? null;
@@ -4900,14 +5090,14 @@ function createProcessTurnRecordRepo(db) {
4900
5090
  setValues.modelSelectionKind = input.modelSelectionProvenance?.kind ?? null;
4901
5091
  setValues.modelSelectionSource = input.modelSelectionProvenance?.source ?? null;
4902
5092
  }
4903
- db.update(turnRecords).set(setValues).where(eq22(turnRecords.id, id)).run();
5093
+ db.update(turnRecords).set(setValues).where(eq23(turnRecords.id, id)).run();
4904
5094
  return this.getById(id);
4905
5095
  }
4906
5096
  };
4907
5097
  }
4908
5098
 
4909
5099
  // src/db/provider-credential-repo.ts
4910
- import { and as and16, count as count3, eq as eq23 } from "drizzle-orm";
5100
+ import { and as and17, count as count3, eq as eq24 } from "drizzle-orm";
4911
5101
  function createProviderCredentialRepo(db, cipher) {
4912
5102
  const row = (value) => ({
4913
5103
  providerId: value.providerId,
@@ -4923,7 +5113,7 @@ function createProviderCredentialRepo(db, cipher) {
4923
5113
  },
4924
5114
  /** @internal */
4925
5115
  get(providerId) {
4926
- const value = db.select().from(providerCredentials).where(eq23(providerCredentials.providerId, providerId)).get();
5116
+ const value = db.select().from(providerCredentials).where(eq24(providerCredentials.providerId, providerId)).get();
4927
5117
  return value ? row(value) : null;
4928
5118
  },
4929
5119
  /** @internal */
@@ -4954,9 +5144,9 @@ function createProviderCredentialRepo(db, cipher) {
4954
5144
  encryptedPayload: cipher.encrypt(input.payload),
4955
5145
  updatedAt: ts
4956
5146
  }).where(
4957
- and16(
4958
- eq23(providerCredentials.providerId, input.providerId),
4959
- eq23(providerCredentials.revision, input.expectedRevision)
5147
+ and17(
5148
+ eq24(providerCredentials.providerId, input.providerId),
5149
+ eq24(providerCredentials.revision, input.expectedRevision)
4960
5150
  )
4961
5151
  ).run();
4962
5152
  if (result.changes !== 1) return null;
@@ -4969,7 +5159,7 @@ function createProviderCredentialRepo(db, cipher) {
4969
5159
  import {
4970
5160
  sessionTransferAttemptStateForPhase
4971
5161
  } from "@leitwerk-dev/session-transfer";
4972
- import { and as and17, eq as eq24, inArray as inArray7, isNotNull, isNull as isNull3, lt as lt2, notExists, or as or3 } from "drizzle-orm";
5162
+ import { and as and18, eq as eq25, inArray as inArray7, isNotNull, isNull as isNull3, lt as lt2, notExists, or as or3 } from "drizzle-orm";
4973
5163
 
4974
5164
  // src/auth/auth-tokens.ts
4975
5165
  import { createHash, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
@@ -5028,20 +5218,20 @@ function createSessionTransferRepo(db) {
5028
5218
  },
5029
5219
  /** @internal */
5030
5220
  getGrant(id) {
5031
- return db.select().from(sessionTransferGrants).where(eq24(sessionTransferGrants.id, id)).get() ?? null;
5221
+ return db.select().from(sessionTransferGrants).where(eq25(sessionTransferGrants.id, id)).get() ?? null;
5032
5222
  },
5033
5223
  /** @internal */
5034
5224
  getAttempt(id) {
5035
5225
  return toAttempt(
5036
- db.select().from(sessionTransferAttempts).where(eq24(sessionTransferAttempts.id, id)).get()
5226
+ db.select().from(sessionTransferAttempts).where(eq25(sessionTransferAttempts.id, id)).get()
5037
5227
  );
5038
5228
  },
5039
5229
  /** @internal */
5040
5230
  getActiveByInstance(instanceId) {
5041
5231
  return toAttempt(
5042
5232
  db.select().from(sessionTransferAttempts).where(
5043
- and17(
5044
- eq24(sessionTransferAttempts.instanceId, instanceId),
5233
+ and18(
5234
+ eq25(sessionTransferAttempts.instanceId, instanceId),
5045
5235
  inArray7(sessionTransferAttempts.phase, ACTIVE_PHASES)
5046
5236
  )
5047
5237
  ).get()
@@ -5095,7 +5285,7 @@ function createSessionTransferRepo(db) {
5095
5285
  },
5096
5286
  /** @internal */
5097
5287
  updateAttempt(id, patch) {
5098
- db.update(sessionTransferAttempts).set(patch).where(eq24(sessionTransferAttempts.id, id)).run();
5288
+ db.update(sessionTransferAttempts).set(patch).where(eq25(sessionTransferAttempts.id, id)).run();
5099
5289
  return this.getAttempt(id);
5100
5290
  },
5101
5291
  /** @internal */
@@ -5117,17 +5307,17 @@ function createSessionTransferRepo(db) {
5117
5307
  return null;
5118
5308
  const completedAt = input.now.toISOString();
5119
5309
  db.update(sessionTransferAttempts).set({ phase: "consumed", completedAt }).where(
5120
- and17(
5121
- eq24(sessionTransferAttempts.id, attempt.id),
5122
- eq24(sessionTransferAttempts.phase, "awaiting_ack")
5310
+ and18(
5311
+ eq25(sessionTransferAttempts.id, attempt.id),
5312
+ eq25(sessionTransferAttempts.phase, "awaiting_ack")
5123
5313
  )
5124
5314
  ).run();
5125
5315
  db.update(sessionTransferGrants).set({
5126
5316
  consumedAt: completedAt,
5127
5317
  tombstoneUntil: new Date(input.now.getTime() + input.tombstoneMs).toISOString()
5128
5318
  }).where(
5129
- and17(
5130
- eq24(sessionTransferGrants.id, attempt.grantId),
5319
+ and18(
5320
+ eq25(sessionTransferGrants.id, attempt.grantId),
5131
5321
  isNull3(sessionTransferGrants.consumedAt)
5132
5322
  )
5133
5323
  ).run();
@@ -5135,27 +5325,27 @@ function createSessionTransferRepo(db) {
5135
5325
  },
5136
5326
  /** @internal */
5137
5327
  revokeProcess(instanceId) {
5138
- db.delete(sessionTransferGrants).where(eq24(sessionTransferGrants.instanceId, instanceId)).run();
5328
+ db.delete(sessionTransferGrants).where(eq25(sessionTransferGrants.instanceId, instanceId)).run();
5139
5329
  },
5140
5330
  /** @internal */
5141
5331
  cleanup(now2) {
5142
5332
  const cutoff = now2.toISOString();
5143
5333
  db.delete(sessionTransferGrants).where(
5144
- and17(
5334
+ and18(
5145
5335
  or3(
5146
- and17(
5336
+ and18(
5147
5337
  isNull3(sessionTransferGrants.consumedAt),
5148
5338
  lt2(sessionTransferGrants.expiresAt, cutoff)
5149
5339
  ),
5150
- and17(
5340
+ and18(
5151
5341
  isNotNull(sessionTransferGrants.tombstoneUntil),
5152
5342
  lt2(sessionTransferGrants.tombstoneUntil, cutoff)
5153
5343
  )
5154
5344
  ),
5155
5345
  notExists(
5156
5346
  db.select({ id: sessionTransferAttempts.id }).from(sessionTransferAttempts).where(
5157
- and17(
5158
- eq24(sessionTransferAttempts.grantId, sessionTransferGrants.id),
5347
+ and18(
5348
+ eq25(sessionTransferAttempts.grantId, sessionTransferGrants.id),
5159
5349
  inArray7(sessionTransferAttempts.phase, ACTIVE_PHASES)
5160
5350
  )
5161
5351
  )
@@ -5168,7 +5358,7 @@ function createSessionTransferRepo(db) {
5168
5358
 
5169
5359
  // src/db/skill-repo.ts
5170
5360
  import { verifyCanonicalPiResourceBundle as verifyCanonicalPiResourceBundle2 } from "@leitwerk-dev/worker-protocol";
5171
- import { and as and18, asc as asc15, count as count4, desc as desc9, eq as eq25, isNotNull as isNotNull2, max as max2, notExists as notExists2, notInArray as notInArray2, sql as sql7 } from "drizzle-orm";
5361
+ import { and as and19, asc as asc16, count as count4, desc as desc9, eq as eq26, isNotNull as isNotNull2, max as max2, notExists as notExists2, notInArray as notInArray2, sql as sql7 } from "drizzle-orm";
5172
5362
 
5173
5363
  // src/skills/skill-dependencies.ts
5174
5364
  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;
@@ -5205,9 +5395,9 @@ function isSkillModelInvocable(markdown) {
5205
5395
  // src/db/skill-repo.ts
5206
5396
  function revisionForBundle(db, item, timestamp) {
5207
5397
  const existing = db.select({ id: skillRevisions.id }).from(skillRevisions).where(
5208
- and18(
5209
- eq25(skillRevisions.skillId, item.skillId),
5210
- eq25(skillRevisions.bundleDigest, item.bundle.digest)
5398
+ and19(
5399
+ eq26(skillRevisions.skillId, item.skillId),
5400
+ eq26(skillRevisions.bundleDigest, item.bundle.digest)
5211
5401
  )
5212
5402
  ).get();
5213
5403
  if (existing) return existing.id;
@@ -5238,7 +5428,7 @@ function usageBySkill(db) {
5238
5428
  skillId: processSkills.skillId,
5239
5429
  allTime: count4(),
5240
5430
  last30Days: sql7`sum(case when ${processInstances.createdAt} >= ${cutoff} then 1 else 0 end)`
5241
- }).from(processSkills).innerJoin(processInstances, eq25(processSkills.instanceId, processInstances.id)).groupBy(processSkills.skillId).all()) {
5431
+ }).from(processSkills).innerJoin(processInstances, eq26(processSkills.instanceId, processInstances.id)).groupBy(processSkills.skillId).all()) {
5242
5432
  result.set(row.skillId, {
5243
5433
  ...usage(row.skillId),
5244
5434
  attachedAllTime: row.allTime,
@@ -5265,13 +5455,13 @@ function processUsage(db, skillId) {
5265
5455
  attachedAt: processInstances.createdAt,
5266
5456
  invocationCount: count4(skillInvocations.skillId),
5267
5457
  lastInvokedAt: max2(skillInvocations.invokedAt)
5268
- }).from(processSkills).innerJoin(processInstances, eq25(processSkills.instanceId, processInstances.id)).leftJoin(
5458
+ }).from(processSkills).innerJoin(processInstances, eq26(processSkills.instanceId, processInstances.id)).leftJoin(
5269
5459
  skillInvocations,
5270
- and18(
5271
- eq25(skillInvocations.instanceId, processSkills.instanceId),
5272
- eq25(skillInvocations.skillId, processSkills.skillId)
5460
+ and19(
5461
+ eq26(skillInvocations.instanceId, processSkills.instanceId),
5462
+ eq26(skillInvocations.skillId, processSkills.skillId)
5273
5463
  )
5274
- ).where(eq25(processSkills.skillId, skillId)).groupBy(
5464
+ ).where(eq26(processSkills.skillId, skillId)).groupBy(
5275
5465
  processSkills.instanceId,
5276
5466
  processInstances.title,
5277
5467
  processInstances.externalId,
@@ -5287,13 +5477,13 @@ function skillMarkdown(skillId, bytes, digest) {
5287
5477
  }
5288
5478
  function pruneNeverInstalledCatalogEntries(db) {
5289
5479
  db.delete(skillCatalogEntries).where(
5290
- and18(
5291
- eq25(skillCatalogEntries.available, false),
5480
+ and19(
5481
+ eq26(skillCatalogEntries.available, false),
5292
5482
  notExists2(
5293
5483
  db.select({ id: skillRevisions.id }).from(skillRevisions).where(
5294
- and18(
5295
- eq25(skillRevisions.skillId, skillCatalogEntries.skillId),
5296
- eq25(skillRevisions.bundleDigest, skillCatalogEntries.bundleDigest)
5484
+ and19(
5485
+ eq26(skillRevisions.skillId, skillCatalogEntries.skillId),
5486
+ eq26(skillRevisions.bundleDigest, skillCatalogEntries.bundleDigest)
5297
5487
  )
5298
5488
  )
5299
5489
  )
@@ -5301,7 +5491,7 @@ function pruneNeverInstalledCatalogEntries(db) {
5301
5491
  ).run();
5302
5492
  }
5303
5493
  function recordRevisionDependencies(db, revisionId, markdown) {
5304
- db.delete(skillRevisionDependencies).where(eq25(skillRevisionDependencies.skillRevisionId, revisionId)).run();
5494
+ db.delete(skillRevisionDependencies).where(eq26(skillRevisionDependencies.skillRevisionId, revisionId)).run();
5305
5495
  for (const [position, dependencySkillId] of explicitSkillReferenceIds(markdown).entries()) {
5306
5496
  db.insert(skillRevisionDependencies).values({ skillRevisionId: revisionId, dependencySkillId, position }).run();
5307
5497
  }
@@ -5324,7 +5514,7 @@ function activateSkill(db, item, registrationKind, timestamp, markdown = skillMa
5324
5514
  activeRevisionId: revisionId,
5325
5515
  registrationKind,
5326
5516
  updatedAt: timestamp
5327
- }).where(eq25(skills.id, item.skillId)).run();
5517
+ }).where(eq26(skills.id, item.skillId)).run();
5328
5518
  return revisionId;
5329
5519
  }
5330
5520
  function catalogView(db) {
@@ -5339,7 +5529,7 @@ function catalogView(db) {
5339
5529
  activeDigest: skillRevisions.bundleDigest,
5340
5530
  activeBundleBytes: skillRevisions.bundleBytes,
5341
5531
  registrationKind: skills.registrationKind
5342
- }).from(skills).innerJoin(skillRevisions, eq25(skills.activeRevisionId, skillRevisions.id)).orderBy(asc15(skills.label), asc15(skills.id)).all();
5532
+ }).from(skills).innerJoin(skillRevisions, eq26(skills.activeRevisionId, skillRevisions.id)).orderBy(asc16(skills.label), asc16(skills.id)).all();
5343
5533
  const installedById = new Map(installedRows.map((row) => [row.id, row]));
5344
5534
  const availableSkills = candidates.map((candidate2) => {
5345
5535
  const active = installedById.get(candidate2.skillId);
@@ -5392,11 +5582,11 @@ function createSkillRepo(db) {
5392
5582
  return {
5393
5583
  /** @internal */
5394
5584
  listAvailable() {
5395
- return db.select({ id: skills.id, label: skills.label, description: skills.description }).from(skills).where(isNotNull2(skills.activeRevisionId)).orderBy(asc15(skills.label), asc15(skills.id)).all();
5585
+ return db.select({ id: skills.id, label: skills.label, description: skills.description }).from(skills).where(isNotNull2(skills.activeRevisionId)).orderBy(asc16(skills.label), asc16(skills.id)).all();
5396
5586
  },
5397
5587
  /** @internal */
5398
5588
  resolveActive(ids) {
5399
- const activeSkills = db.select({ id: skills.id, revisionId: skillRevisions.id }).from(skills).innerJoin(skillRevisions, eq25(skills.activeRevisionId, skillRevisions.id)).all();
5589
+ const activeSkills = db.select({ id: skills.id, revisionId: skillRevisions.id }).from(skills).innerJoin(skillRevisions, eq26(skills.activeRevisionId, skillRevisions.id)).all();
5400
5590
  const byId = new Map(activeSkills.map((skill) => [skill.id, skill]));
5401
5591
  const dependencies = /* @__PURE__ */ new Map();
5402
5592
  for (const dependency of db.select().from(skillRevisionDependencies).all()) {
@@ -5424,8 +5614,8 @@ function createSkillRepo(db) {
5424
5614
  reconcile(imported) {
5425
5615
  const timestamp = now();
5426
5616
  db.update(skills).set({ activeRevisionId: null, updatedAt: timestamp }).where(
5427
- and18(
5428
- eq25(skills.registrationKind, "configuration"),
5617
+ and19(
5618
+ eq26(skills.registrationKind, "configuration"),
5429
5619
  notInArray2(
5430
5620
  skills.id,
5431
5621
  imported.map((item) => item.skillId)
@@ -5452,7 +5642,7 @@ function createSkillRepo(db) {
5452
5642
  /** @internal */
5453
5643
  mergeCatalog(repositoryId, imported) {
5454
5644
  const timestamp = now();
5455
- db.update(skillCatalogEntries).set({ available: false }).where(eq25(skillCatalogEntries.repositoryId, repositoryId)).run();
5645
+ db.update(skillCatalogEntries).set({ available: false }).where(eq26(skillCatalogEntries.repositoryId, repositoryId)).run();
5456
5646
  for (const item of imported) {
5457
5647
  const values = {
5458
5648
  label: item.label,
@@ -5473,7 +5663,7 @@ function createSkillRepo(db) {
5473
5663
  },
5474
5664
  /** @internal */
5475
5665
  registerCatalogEntry(repositoryId, skillId) {
5476
- const candidates = db.select().from(skillCatalogEntries).where(eq25(skillCatalogEntries.available, true)).all();
5666
+ const candidates = db.select().from(skillCatalogEntries).where(eq26(skillCatalogEntries.available, true)).all();
5477
5667
  const availableIds = new Set(candidates.map((candidate2) => candidate2.skillId));
5478
5668
  const installedIds = new Set(
5479
5669
  db.select({ id: skills.id }).from(skills).where(isNotNull2(skills.activeRevisionId)).all().map((skill) => skill.id)
@@ -5493,7 +5683,7 @@ function createSkillRepo(db) {
5493
5683
  `Remote skill '${requestedRepositoryId ? `${requestedRepositoryId}/` : ""}${id}' is no longer available`
5494
5684
  );
5495
5685
  }
5496
- const current = db.select().from(skills).where(eq25(skills.id, id)).get();
5686
+ const current = db.select().from(skills).where(eq26(skills.id, id)).get();
5497
5687
  if (current?.activeRevisionId && current.registrationKind === "configuration") {
5498
5688
  throw new Error(`Skill '${id}' is managed by configuration`);
5499
5689
  }
@@ -5526,9 +5716,9 @@ function createSkillRepo(db) {
5526
5716
  },
5527
5717
  /** @internal */
5528
5718
  remove(skillId) {
5529
- const current = db.select().from(skills).where(eq25(skills.id, skillId)).get();
5719
+ const current = db.select().from(skills).where(eq26(skills.id, skillId)).get();
5530
5720
  if (!current?.activeRevisionId || current.registrationKind !== "catalog") return false;
5531
- db.update(skills).set({ activeRevisionId: null, updatedAt: now() }).where(eq25(skills.id, skillId)).run();
5721
+ db.update(skills).set({ activeRevisionId: null, updatedAt: now() }).where(eq26(skills.id, skillId)).run();
5532
5722
  return true;
5533
5723
  },
5534
5724
  /** @internal */
@@ -5545,9 +5735,9 @@ function createSkillRepo(db) {
5545
5735
  bytes: skillCatalogEntries.bundleBytes,
5546
5736
  digest: skillCatalogEntries.bundleDigest
5547
5737
  }).from(skillCatalogEntries).where(
5548
- and18(
5549
- eq25(skillCatalogEntries.repositoryId, repositoryId),
5550
- eq25(skillCatalogEntries.skillId, skillId)
5738
+ and19(
5739
+ eq26(skillCatalogEntries.repositoryId, repositoryId),
5740
+ eq26(skillCatalogEntries.skillId, skillId)
5551
5741
  )
5552
5742
  ).get();
5553
5743
  if (!candidate2) return null;
@@ -5561,13 +5751,13 @@ function createSkillRepo(db) {
5561
5751
  getInstalledDetail(skillId) {
5562
5752
  const item = catalogView(db).installedSkills.find((candidate2) => candidate2.id === skillId);
5563
5753
  if (!item) return null;
5564
- const revision = db.select({ bytes: skillRevisions.bundleBytes, digest: skillRevisions.bundleDigest }).from(skillRevisions).where(eq25(skillRevisions.id, item.activeRevisionId)).get();
5754
+ const revision = db.select({ bytes: skillRevisions.bundleBytes, digest: skillRevisions.bundleDigest }).from(skillRevisions).where(eq26(skillRevisions.id, item.activeRevisionId)).get();
5565
5755
  if (!revision) return null;
5566
5756
  const revisions = db.select({
5567
5757
  id: skillRevisions.id,
5568
5758
  sourceRevision: skillRevisions.sourceRevision,
5569
5759
  importedAt: skillRevisions.importedAt
5570
- }).from(skillRevisions).where(eq25(skillRevisions.skillId, skillId)).all().map((candidate2) => ({
5760
+ }).from(skillRevisions).where(eq26(skillRevisions.skillId, skillId)).all().map((candidate2) => ({
5571
5761
  ...candidate2,
5572
5762
  active: candidate2.id === item.activeRevisionId
5573
5763
  })).sort((left, right) => right.importedAt.localeCompare(left.importedAt));
@@ -5580,7 +5770,7 @@ function createSkillRepo(db) {
5580
5770
  },
5581
5771
  /** @internal */
5582
5772
  recordInvocations(input) {
5583
- const selections = db.select().from(processSkills).where(eq25(processSkills.instanceId, input.instanceId)).all();
5773
+ const selections = db.select().from(processSkills).where(eq26(processSkills.instanceId, input.instanceId)).all();
5584
5774
  const uniqueInvocations = new Map(
5585
5775
  input.invocations.map((invocation) => [invocation.skillId, invocation])
5586
5776
  );
@@ -5600,7 +5790,7 @@ function createSkillRepo(db) {
5600
5790
  }
5601
5791
 
5602
5792
  // src/db/ticket-destination-recent-repo.ts
5603
- import { and as and19, desc as desc10, eq as eq26 } from "drizzle-orm";
5793
+ import { and as and20, desc as desc10, eq as eq27 } from "drizzle-orm";
5604
5794
  function map4(row) {
5605
5795
  return { ...row };
5606
5796
  }
@@ -5609,9 +5799,9 @@ function createTicketDestinationRecentRepo(db) {
5609
5799
  /** @internal */
5610
5800
  list(actorKey, toolName, limit = 5) {
5611
5801
  return db.select().from(ticketDestinationRecents).where(
5612
- and19(
5613
- eq26(ticketDestinationRecents.actorKey, actorKey),
5614
- eq26(ticketDestinationRecents.toolName, toolName)
5802
+ and20(
5803
+ eq27(ticketDestinationRecents.actorKey, actorKey),
5804
+ eq27(ticketDestinationRecents.toolName, toolName)
5615
5805
  )
5616
5806
  ).orderBy(
5617
5807
  desc10(ticketDestinationRecents.updatedAt),
@@ -5620,10 +5810,10 @@ function createTicketDestinationRecentRepo(db) {
5620
5810
  },
5621
5811
  /** @internal */
5622
5812
  record(input) {
5623
- const match = and19(
5624
- eq26(ticketDestinationRecents.actorKey, input.actorKey),
5625
- eq26(ticketDestinationRecents.toolName, input.toolName),
5626
- eq26(ticketDestinationRecents.destinationId, input.destinationId)
5813
+ const match = and20(
5814
+ eq27(ticketDestinationRecents.actorKey, input.actorKey),
5815
+ eq27(ticketDestinationRecents.toolName, input.toolName),
5816
+ eq27(ticketDestinationRecents.destinationId, input.destinationId)
5627
5817
  );
5628
5818
  const existing = db.select().from(ticketDestinationRecents).where(match).get();
5629
5819
  const updatedAt = now();
@@ -5644,16 +5834,16 @@ function createTicketDestinationRecentRepo(db) {
5644
5834
  result = row;
5645
5835
  }
5646
5836
  const stale = db.select({ id: ticketDestinationRecents.id }).from(ticketDestinationRecents).where(
5647
- and19(
5648
- eq26(ticketDestinationRecents.actorKey, input.actorKey),
5649
- eq26(ticketDestinationRecents.toolName, input.toolName)
5837
+ and20(
5838
+ eq27(ticketDestinationRecents.actorKey, input.actorKey),
5839
+ eq27(ticketDestinationRecents.toolName, input.toolName)
5650
5840
  )
5651
5841
  ).orderBy(
5652
5842
  desc10(ticketDestinationRecents.updatedAt),
5653
5843
  desc10(ticketDestinationRecents.createdAt)
5654
5844
  ).all().slice(input.limit ?? 5);
5655
5845
  for (const entry of stale) {
5656
- db.delete(ticketDestinationRecents).where(eq26(ticketDestinationRecents.id, entry.id)).run();
5846
+ db.delete(ticketDestinationRecents).where(eq27(ticketDestinationRecents.id, entry.id)).run();
5657
5847
  }
5658
5848
  return result;
5659
5849
  }
@@ -5661,7 +5851,7 @@ function createTicketDestinationRecentRepo(db) {
5661
5851
  }
5662
5852
 
5663
5853
  // src/db/turn-start-record-repo.ts
5664
- import { and as and20, eq as eq27 } from "drizzle-orm";
5854
+ import { and as and21, eq as eq28 } from "drizzle-orm";
5665
5855
  function map5(row) {
5666
5856
  return {
5667
5857
  id: row.id,
@@ -5673,6 +5863,7 @@ function map5(row) {
5673
5863
  recoveryTurnRecordId: row.recoveryTurnRecordId ?? null,
5674
5864
  continuation: row.continuationJson ? parsePersistedJson(row.continuationJson, "turn start continuation") : null,
5675
5865
  state: parsePersistedJson(row.stateJson, "turn start state"),
5866
+ iteration: mappedItemRef(row),
5676
5867
  createdAt: row.createdAt,
5677
5868
  updatedAt: row.updatedAt
5678
5869
  };
@@ -5694,28 +5885,31 @@ function createTurnStartRecordRepo(db) {
5694
5885
  continuationJson: input.continuation ? JSON.stringify(input.continuation) : null,
5695
5886
  stateJson: JSON.stringify(input.state),
5696
5887
  createdAt: ts,
5697
- updatedAt: ts
5888
+ updatedAt: ts,
5889
+ mappedRunId: input.iteration?.runId ?? null,
5890
+ mappedItemKey: input.iteration?.itemKey ?? null,
5891
+ mappedItemIndex: input.iteration?.itemIndex ?? null
5698
5892
  };
5699
5893
  db.insert(turnStartRecords).values(value).run();
5700
5894
  return map5(value);
5701
5895
  },
5702
5896
  /** @internal */
5703
5897
  getById(id) {
5704
- const value = db.select().from(turnStartRecords).where(eq27(turnStartRecords.id, id)).get();
5898
+ const value = db.select().from(turnStartRecords).where(eq28(turnStartRecords.id, id)).get();
5705
5899
  return value ? map5(value) : null;
5706
5900
  },
5707
5901
  /** @internal */
5708
5902
  listByInstance(instanceId) {
5709
- return db.select().from(turnStartRecords).where(eq27(turnStartRecords.instanceId, instanceId)).all().map(map5);
5903
+ return db.select().from(turnStartRecords).where(eq28(turnStartRecords.instanceId, instanceId)).all().map(map5);
5710
5904
  },
5711
5905
  /** @internal */
5712
5906
  compareAndSetState(input) {
5713
5907
  const current = this.getById(input.id);
5714
5908
  if (!current || current.state.kind !== input.expectedKind) return null;
5715
5909
  const result = db.update(turnStartRecords).set({ stateJson: JSON.stringify(input.state), updatedAt: now() }).where(
5716
- and20(
5717
- eq27(turnStartRecords.id, input.id),
5718
- eq27(turnStartRecords.stateJson, JSON.stringify(current.state))
5910
+ and21(
5911
+ eq28(turnStartRecords.id, input.id),
5912
+ eq28(turnStartRecords.stateJson, JSON.stringify(current.state))
5719
5913
  )
5720
5914
  ).run();
5721
5915
  return result.changes === 1 ? this.getById(input.id) : null;
@@ -5724,7 +5918,7 @@ function createTurnStartRecordRepo(db) {
5724
5918
  }
5725
5919
 
5726
5920
  // src/db/worker-lease-repo.ts
5727
- import { and as and21, asc as asc16, eq as eq28, isNull as isNull4 } from "drizzle-orm";
5921
+ import { and as and22, asc as asc17, eq as eq29, isNull as isNull4 } from "drizzle-orm";
5728
5922
  function rowToWorkerLease(row) {
5729
5923
  return {
5730
5924
  id: row.id,
@@ -5774,17 +5968,17 @@ function createWorkerLeaseRepo(db) {
5774
5968
  },
5775
5969
  /** @internal */
5776
5970
  getByInstance(instanceId) {
5777
- const row = db.select().from(workerLeases).where(and21(eq28(workerLeases.instanceId, instanceId), isNull4(workerLeases.exitedAt))).get();
5971
+ const row = db.select().from(workerLeases).where(and22(eq29(workerLeases.instanceId, instanceId), isNull4(workerLeases.exitedAt))).get();
5778
5972
  return row ? rowToWorkerLease(row) : null;
5779
5973
  },
5780
5974
  /** @internal */
5781
5975
  getById(id) {
5782
- const row = db.select().from(workerLeases).where(eq28(workerLeases.id, id)).get();
5976
+ const row = db.select().from(workerLeases).where(eq29(workerLeases.id, id)).get();
5783
5977
  return row ? rowToWorkerLease(row) : null;
5784
5978
  },
5785
5979
  /** @internal */
5786
5980
  listByInstance(instanceId) {
5787
- return db.select().from(workerLeases).where(eq28(workerLeases.instanceId, instanceId)).orderBy(asc16(workerLeases.startedAt), asc16(workerLeases.id)).all().map(rowToWorkerLease);
5981
+ return db.select().from(workerLeases).where(eq29(workerLeases.instanceId, instanceId)).orderBy(asc17(workerLeases.startedAt), asc17(workerLeases.id)).all().map(rowToWorkerLease);
5788
5982
  },
5789
5983
  /** @internal */
5790
5984
  listActive() {
@@ -5804,29 +5998,29 @@ function createWorkerLeaseRepo(db) {
5804
5998
  readyAt: input.readyAt,
5805
5999
  exitedAt: input.exitedAt
5806
6000
  };
5807
- db.update(workerLeases).set(setValues).where(eq28(workerLeases.id, id)).run();
5808
- const row = db.select().from(workerLeases).where(eq28(workerLeases.id, id)).get();
6001
+ db.update(workerLeases).set(setValues).where(eq29(workerLeases.id, id)).run();
6002
+ const row = db.select().from(workerLeases).where(eq29(workerLeases.id, id)).get();
5809
6003
  return row ? rowToWorkerLease(row) : null;
5810
6004
  },
5811
6005
  /** @internal */
5812
6006
  observeTimestamp(id, field) {
5813
6007
  const column = workerLeases[field];
5814
- db.update(workerLeases).set({ [field]: now() }).where(and21(eq28(workerLeases.id, id), isNull4(column))).run();
6008
+ db.update(workerLeases).set({ [field]: now() }).where(and22(eq29(workerLeases.id, id), isNull4(column))).run();
5815
6009
  return this.getById(id);
5816
6010
  },
5817
6011
  /** @internal */
5818
6012
  updateHeartbeat(workerId) {
5819
- const result = db.update(workerLeases).set({ lastHeartbeatAt: now() }).where(eq28(workerLeases.workerId, workerId)).run();
6013
+ const result = db.update(workerLeases).set({ lastHeartbeatAt: now() }).where(eq29(workerLeases.workerId, workerId)).run();
5820
6014
  return result.changes > 0;
5821
6015
  },
5822
6016
  /** Stores the first receipt only. Exact replay is accepted; changed receipts are rejected. @internal */
5823
6017
  compareAndSetBootstrapReceipt(id, receipt) {
5824
- const existing = db.select().from(workerLeases).where(eq28(workerLeases.id, id)).get();
6018
+ const existing = db.select().from(workerLeases).where(eq29(workerLeases.id, id)).get();
5825
6019
  if (!existing) return "missing";
5826
6020
  const encoded = JSON.stringify(receipt);
5827
6021
  if (existing.bootstrapReceiptJson !== null)
5828
6022
  return existing.bootstrapReceiptJson === encoded ? "replay" : "changed";
5829
- const result = db.update(workerLeases).set({ bootstrapReceiptJson: encoded }).where(and21(eq28(workerLeases.id, id), isNull4(workerLeases.bootstrapReceiptJson))).run();
6023
+ const result = db.update(workerLeases).set({ bootstrapReceiptJson: encoded }).where(and22(eq29(workerLeases.id, id), isNull4(workerLeases.bootstrapReceiptJson))).run();
5830
6024
  return result.changes === 1 ? "stored" : "changed";
5831
6025
  }
5832
6026
  };
@@ -5856,6 +6050,7 @@ function createAllRepos(db, options = {}) {
5856
6050
  turnRecords: createProcessTurnRecordRepo(db),
5857
6051
  turnStarts: createTurnStartRecordRepo(db),
5858
6052
  turnAnnotations: createProcessTurnAnnotationRepo(db),
6053
+ mappedRuns: createMappedLlmRunRepo(db),
5859
6054
  leases: createWorkerLeaseRepo(db),
5860
6055
  providerCredentials: createProviderCredentialRepo(db, credentialCipher),
5861
6056
  externalWrites: createExternalWriteLogRepo(db),
@@ -9303,83 +9498,276 @@ function normalizeExternalObservation(value) {
9303
9498
  };
9304
9499
  }
9305
9500
 
9306
- // src/physical-worker-starts.ts
9307
- import {
9308
- startupInterval
9309
- } from "@leitwerk-dev/domain";
9310
- function physicalWorkerStarts(input) {
9311
- return input.leases.map((lease) => {
9312
- const start = input.turnStarts.find((start2) => start2.id === lease.turnStartRecordId);
9313
- const turn = input.turnRecords.filter(
9314
- (turn2) => turn2.acceptedWorkerLeaseId === lease.id && turn2.turnStartRecordId === start?.id
9315
- ).sort((a, b) => a.startedAt.localeCompare(b.startedAt))[0];
9316
- const observations = input.observations.filter((o) => o.workerLeaseId === lease.id);
9317
- const observation = (milestone) => observations.find((o) => o.milestone === milestone);
9318
- const receipt = (milestone) => observation(milestone)?.observedAt;
9319
- const source = (milestone) => observation(milestone)?.sourceAt;
9320
- return {
9321
- workerLeaseId: lease.id,
9322
- workerId: lease.workerId,
9323
- turnStartRecordId: lease.turnStartRecordId ?? null,
9324
- turnRecordId: turn?.id ?? null,
9325
- state: lease.state,
9326
- observations,
9327
- intervals: {
9328
- launchPreparation: startupInterval(start?.createdAt, lease.startedAt),
9329
- requestToConnection: startupInterval(lease.startedAt, lease.connectedAt),
9330
- connectionToReadiness: startupInterval(lease.connectedAt, lease.readyAt),
9331
- readinessToAcceptance: startupInterval(lease.readyAt, turn?.startedAt),
9332
- acceptanceToPrompt: startupInterval(turn?.startedAt, receipt("prompt_started")),
9333
- promptToFirstText: startupInterval(receipt("prompt_started"), receipt("first_text")),
9334
- total: startupInterval(start?.createdAt, receipt("first_text")),
9335
- pvcRequest: startupInterval(receipt("pvc_requested"), receipt("pvc_acknowledged")),
9336
- podRequest: startupInterval(receipt("pod_requested"), receipt("pod_acknowledged")),
9337
- bindingWindow: startupInterval(observation("pvc_bound")?.notBefore, receipt("pvc_bound")),
9338
- containerObservedToConnection: startupInterval(
9339
- receipt("container_started"),
9340
- lease.connectedAt
9341
- ),
9342
- scheduling: startupInterval(source("pod_created"), source("pod_scheduled"), "kubernetes"),
9343
- schedulingToContainer: startupInterval(
9344
- source("pod_scheduled"),
9345
- source("container_started"),
9346
- "kubernetes"
9347
- ),
9348
- imagePull: startupInterval(
9349
- source("image_pull_started"),
9350
- source("image_pull_finished"),
9351
- "kubernetes"
9352
- )
9353
- }
9354
- };
9355
- });
9356
- }
9501
+ // src/future-execution-presenter.ts
9502
+ import { parseFutureActionPayloadJson, parseFutureLaunchPayloadJson } from "@leitwerk-dev/protocol";
9357
9503
 
9358
- // src/process-instance-tree-presenter.ts
9359
- function titleCase(value) {
9360
- return value.replaceAll(/[-_]+/g, " ").replaceAll(/\b\w/g, (character) => character.toUpperCase());
9504
+ // src/process-action-presenter.ts
9505
+ import { isLlmTurnDefinition as isLlmTurnDefinition2 } from "@leitwerk-dev/process-sdk";
9506
+ function actionHasPurePlan(deps, process2, actionId) {
9507
+ const action = deps.processActionRegistry?.getAction(process2.processId, actionId);
9508
+ return typeof action?.plan === "function";
9361
9509
  }
9362
- function payloadString(annotation, key) {
9363
- const value = annotation.payload[key];
9364
- return typeof value === "string" && value.trim() ? value.trim() : null;
9510
+ function buildActionSummaryForProcess(deps, process2, action, visibleAction, labelOverride, overrides = {}) {
9511
+ const actionId = action.id;
9512
+ const preview = visibleAction?.preview ?? deps.processActionRegistry?.resolveActionPreview(process2.processId, process2, actionId) ?? null;
9513
+ const supportsScheduling = overrides.supportsScheduling ?? Boolean(
9514
+ actionHasPurePlan(deps, process2, actionId) && deps.processActionRegistry?.resolveActionScheduling(process2.processId, process2, actionId)
9515
+ );
9516
+ const label = labelOverride ?? visibleAction?.label ?? action.label;
9517
+ return {
9518
+ id: action.id,
9519
+ label: label.trim() ? label : action.label,
9520
+ description: visibleAction?.description ?? null,
9521
+ preview: buildProcessActionPreviewSummary(deps, preview, process2),
9522
+ supportsScheduling,
9523
+ supportsNextTurnModelOverride: previewSupportsNextTurnModelOverride(
9524
+ deps,
9525
+ process2,
9526
+ actionId,
9527
+ preview
9528
+ ),
9529
+ ...action.form ? {
9530
+ form: {
9531
+ id: action.form.id,
9532
+ title: action.form.title,
9533
+ submitLabel: action.form.submitLabel,
9534
+ fields: action.form.fields.map((field) => ({ ...field }))
9535
+ }
9536
+ } : {}
9537
+ };
9365
9538
  }
9366
- function nextLlmAfterAutomatic(automatic, allRecords) {
9367
- const start = allRecords.findIndex((record3) => record3.id === automatic.id) + 1;
9368
- for (let index2 = start; index2 > 0 && index2 < allRecords.length; index2 += 1) {
9369
- const record3 = allRecords[index2];
9370
- if (record3.turnType === "human" || record3.turnType === "external") return void 0;
9371
- if (record3.turnType === "llm") return record3;
9372
- }
9373
- return void 0;
9539
+ function listVisibleActionsForProcess2(deps, process2) {
9540
+ return listVisibleActionsForProcess(deps, process2).map(
9541
+ (action) => buildActionSummaryForProcess(deps, process2, action, action, action.label)
9542
+ );
9374
9543
  }
9375
- function actionDecisions(process2, annotations, allRecords, llmRecords) {
9376
- const llmById = new Map(llmRecords.map((record3) => [record3.id, record3]));
9377
- const claimedTargets = /* @__PURE__ */ new Set();
9378
- const decisions = [];
9379
- const candidates = annotations.filter(
9380
- (annotation) => annotation.annotationType === "acceptance_state" || annotation.annotationType === "external_trigger"
9381
- ).sort(
9382
- (left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id)
9544
+ function buildProcessActionPreviewSummary(deps, preview, process2) {
9545
+ if (!preview) {
9546
+ return null;
9547
+ }
9548
+ if (!preview.candidateSelectedTurnId) {
9549
+ return {
9550
+ kind: "terminal",
9551
+ turnId: null,
9552
+ turnKind: null,
9553
+ description: preview.lifecycleStatus === "aborted" ? "Abort process" : "Complete process"
9554
+ };
9555
+ }
9556
+ const turnDef = deps.processActionRegistry?.getTurnDefinition(
9557
+ process2.processId,
9558
+ preview.candidateSelectedTurnId
9559
+ );
9560
+ if (!turnDef) {
9561
+ return null;
9562
+ }
9563
+ return {
9564
+ kind: "turn",
9565
+ turnId: preview.candidateSelectedTurnId,
9566
+ turnKind: turnDef.kind,
9567
+ description: turnDef.description
9568
+ };
9569
+ }
9570
+ function previewSupportsNextTurnModelOverride(deps, process2, actionId, preview) {
9571
+ if (!preview?.candidateSelectedTurnId) {
9572
+ return false;
9573
+ }
9574
+ if (!actionHasPurePlan(deps, process2, actionId)) {
9575
+ return false;
9576
+ }
9577
+ const turnDef = deps.processActionRegistry?.getTurnDefinition(
9578
+ process2.processId,
9579
+ preview.candidateSelectedTurnId
9580
+ );
9581
+ return Boolean(turnDef && isLlmTurnDefinition2(turnDef));
9582
+ }
9583
+
9584
+ // src/future-execution-presenter.ts
9585
+ function futureSummaryState(execution) {
9586
+ return {
9587
+ id: execution.id,
9588
+ nextRunAt: execution.nextRunAt,
9589
+ status: execution.blockedReason ? "blocked" : "scheduled",
9590
+ modelSelection: execution.modelSelection ?? null,
9591
+ blockedReason: execution.blockedReason ?? null
9592
+ };
9593
+ }
9594
+ function futureActionLabel(label, fallback) {
9595
+ return typeof label === "string" && label.trim() !== "" ? label : fallback;
9596
+ }
9597
+ function buildFutureExecutionListView(deps, execution) {
9598
+ const summary = {
9599
+ ...futureSummaryState(execution),
9600
+ scheduleKind: execution.scheduleKind,
9601
+ processId: execution.processId,
9602
+ cronExpression: execution.cronExpression
9603
+ };
9604
+ if (execution.kind === "launch") {
9605
+ const launcher = deps.launcherService.listUiLaunchers().find((candidate2) => candidate2.id === execution.launcherId);
9606
+ const parsedPayload2 = parseFutureLaunchPayloadJson(execution.payloadJson);
9607
+ if (!parsedPayload2.ok) {
9608
+ const launcherLabel = launcher?.label ?? execution.launcherId ?? execution.processId;
9609
+ return {
9610
+ ...summary,
9611
+ kind: "launch",
9612
+ title: launcher?.card.title ?? launcherLabel,
9613
+ subtitle: `${launcherLabel} \xB7 invalid scheduled start`,
9614
+ launcherId: execution.launcherId ?? execution.processId,
9615
+ launcherLabel,
9616
+ launchTitle: null,
9617
+ launcherInput: {},
9618
+ skillIds: [],
9619
+ modelConfig: {}
9620
+ };
9621
+ }
9622
+ const payload2 = parsedPayload2.value;
9623
+ const title = typeof payload2.launchPlan.processInput.title === "string" && payload2.launchPlan.processInput.title.trim() !== "" ? payload2.launchPlan.processInput.title : typeof payload2.launchPlan.processInput.externalId === "string" && payload2.launchPlan.processInput.externalId.trim() !== "" ? payload2.launchPlan.processInput.externalId : launcher?.card.title ?? launcher?.label ?? payload2.launchPlan.processId;
9624
+ const subtitle = execution.scheduleKind === "cron" ? `${launcher?.label ?? payload2.launchPlan.processId} \xB7 recurring cron` : `${launcher?.label ?? payload2.launchPlan.processId} \xB7 scheduled start`;
9625
+ return {
9626
+ ...summary,
9627
+ kind: "launch",
9628
+ title,
9629
+ subtitle,
9630
+ launcherId: execution.launcherId ?? payload2.launchPlan.launcherId,
9631
+ launcherLabel: launcher?.label ?? payload2.launchPlan.launcherId,
9632
+ launchTitle: payload2.launchPlan.processInput.title,
9633
+ launcherInput: payload2.launcherInput,
9634
+ skillIds: [...payload2.selectedSkillIds],
9635
+ modelConfig: payload2.modelConfig
9636
+ };
9637
+ }
9638
+ if (!execution.instanceId || !execution.actionId) {
9639
+ return null;
9640
+ }
9641
+ const process2 = deps.processes.getById(execution.instanceId);
9642
+ const parsedPayload = parseFutureActionPayloadJson(execution.payloadJson);
9643
+ const payload = parsedPayload.ok ? parsedPayload.value : null;
9644
+ const actionLabel = futureActionLabel(payload?.actionLabel ?? null, execution.actionId);
9645
+ return {
9646
+ ...summary,
9647
+ kind: "action",
9648
+ title: process2?.title ?? process2?.externalId ?? actionLabel,
9649
+ subtitle: `${actionLabel} \xB7 ${payload ? "scheduled action" : "invalid scheduled action"}`,
9650
+ instanceId: execution.instanceId,
9651
+ actionId: execution.actionId,
9652
+ actionLabel,
9653
+ nextTurnModelProfileId: payload?.nextTurnModelProfileId ?? null
9654
+ };
9655
+ }
9656
+ function buildFutureExecutionSummaries(deps, executions) {
9657
+ return executions.map((execution) => buildFutureExecutionListView(deps, execution)).filter((execution) => execution !== null);
9658
+ }
9659
+ function getScheduledActionDetailForProcess(deps, process2) {
9660
+ if (!deps.processActionRegistry) {
9661
+ return null;
9662
+ }
9663
+ const scheduledAction = deps.futureExecutions.getScheduledActionByInstance(process2.id);
9664
+ if (!scheduledAction?.actionId) {
9665
+ return null;
9666
+ }
9667
+ const action = deps.processActionRegistry.getAction(process2.processId, scheduledAction.actionId);
9668
+ if (!action) {
9669
+ return null;
9670
+ }
9671
+ const parsedPayload = parseFutureActionPayloadJson(scheduledAction.payloadJson);
9672
+ if (!parsedPayload.ok) {
9673
+ return null;
9674
+ }
9675
+ const payload = parsedPayload.value;
9676
+ const actionLabel = futureActionLabel(payload.actionLabel, action.label);
9677
+ return {
9678
+ ...futureSummaryState(scheduledAction),
9679
+ actionId: scheduledAction.actionId,
9680
+ actionLabel,
9681
+ input: payload.input,
9682
+ nextTurnModelProfileId: payload.nextTurnModelProfileId,
9683
+ action: buildActionSummaryForProcess(
9684
+ deps,
9685
+ process2,
9686
+ action,
9687
+ listCurrentVisibleActions(deps, process2).find((candidate2) => candidate2.id === action.id),
9688
+ actionLabel,
9689
+ { supportsScheduling: true }
9690
+ )
9691
+ };
9692
+ }
9693
+
9694
+ // src/physical-worker-starts.ts
9695
+ import {
9696
+ startupInterval
9697
+ } from "@leitwerk-dev/domain";
9698
+ function physicalWorkerStarts(input) {
9699
+ return input.leases.map((lease) => {
9700
+ const start = input.turnStarts.find((start2) => start2.id === lease.turnStartRecordId);
9701
+ const turn = input.turnRecords.filter(
9702
+ (turn2) => turn2.acceptedWorkerLeaseId === lease.id && turn2.turnStartRecordId === start?.id
9703
+ ).sort((a, b) => a.startedAt.localeCompare(b.startedAt))[0];
9704
+ const observations = input.observations.filter((o) => o.workerLeaseId === lease.id);
9705
+ const observation = (milestone) => observations.find((o) => o.milestone === milestone);
9706
+ const receipt = (milestone) => observation(milestone)?.observedAt;
9707
+ const source = (milestone) => observation(milestone)?.sourceAt;
9708
+ return {
9709
+ workerLeaseId: lease.id,
9710
+ workerId: lease.workerId,
9711
+ turnStartRecordId: lease.turnStartRecordId ?? null,
9712
+ turnRecordId: turn?.id ?? null,
9713
+ state: lease.state,
9714
+ observations,
9715
+ intervals: {
9716
+ launchPreparation: startupInterval(start?.createdAt, lease.startedAt),
9717
+ requestToConnection: startupInterval(lease.startedAt, lease.connectedAt),
9718
+ connectionToReadiness: startupInterval(lease.connectedAt, lease.readyAt),
9719
+ readinessToAcceptance: startupInterval(lease.readyAt, turn?.startedAt),
9720
+ acceptanceToPrompt: startupInterval(turn?.startedAt, receipt("prompt_started")),
9721
+ promptToFirstText: startupInterval(receipt("prompt_started"), receipt("first_text")),
9722
+ total: startupInterval(start?.createdAt, receipt("first_text")),
9723
+ pvcRequest: startupInterval(receipt("pvc_requested"), receipt("pvc_acknowledged")),
9724
+ podRequest: startupInterval(receipt("pod_requested"), receipt("pod_acknowledged")),
9725
+ bindingWindow: startupInterval(observation("pvc_bound")?.notBefore, receipt("pvc_bound")),
9726
+ containerObservedToConnection: startupInterval(
9727
+ receipt("container_started"),
9728
+ lease.connectedAt
9729
+ ),
9730
+ scheduling: startupInterval(source("pod_created"), source("pod_scheduled"), "kubernetes"),
9731
+ schedulingToContainer: startupInterval(
9732
+ source("pod_scheduled"),
9733
+ source("container_started"),
9734
+ "kubernetes"
9735
+ ),
9736
+ imagePull: startupInterval(
9737
+ source("image_pull_started"),
9738
+ source("image_pull_finished"),
9739
+ "kubernetes"
9740
+ )
9741
+ }
9742
+ };
9743
+ });
9744
+ }
9745
+
9746
+ // src/process-instance-tree-presenter.ts
9747
+ function titleCase(value) {
9748
+ return value.replaceAll(/[-_]+/g, " ").replaceAll(/\b\w/g, (character) => character.toUpperCase());
9749
+ }
9750
+ function payloadString(annotation, key) {
9751
+ const value = annotation.payload[key];
9752
+ return typeof value === "string" && value.trim() ? value.trim() : null;
9753
+ }
9754
+ function nextLlmAfterAutomatic(automatic, allRecords) {
9755
+ const start = allRecords.findIndex((record3) => record3.id === automatic.id) + 1;
9756
+ for (let index2 = start; index2 > 0 && index2 < allRecords.length; index2 += 1) {
9757
+ const record3 = allRecords[index2];
9758
+ if (record3.turnType === "human" || record3.turnType === "external") return void 0;
9759
+ if (record3.turnType === "llm") return record3;
9760
+ }
9761
+ return void 0;
9762
+ }
9763
+ function actionDecisions(process2, annotations, allRecords, llmRecords) {
9764
+ const llmById = new Map(llmRecords.map((record3) => [record3.id, record3]));
9765
+ const claimedTargets = /* @__PURE__ */ new Set();
9766
+ const decisions = [];
9767
+ const candidates = annotations.filter(
9768
+ (annotation) => annotation.annotationType === "acceptance_state" || annotation.annotationType === "external_trigger"
9769
+ ).sort(
9770
+ (left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id)
9383
9771
  );
9384
9772
  for (const annotation of candidates) {
9385
9773
  const actionLabel = payloadString(annotation, "actionLabel") ?? payloadString(annotation, "triggerLabel");
@@ -9591,17 +9979,58 @@ function presentProcessModelConfiguration(projection) {
9591
9979
  }
9592
9980
 
9593
9981
  // src/process-turn-navigation.ts
9982
+ function iterationFor(run, item, index2, itemKey) {
9983
+ return {
9984
+ runId: run.id,
9985
+ itemKey,
9986
+ index: index2,
9987
+ count: run.itemCount,
9988
+ label: item?.label ?? itemKey
9989
+ };
9990
+ }
9991
+ function withItemLabel(description, iteration) {
9992
+ return `${description}: ${iteration.label}`;
9993
+ }
9594
9994
  function presentProcessTurnNavigation(input) {
9995
+ const runs = new Map(input.mapped?.runs.map((run) => [run.id, run]) ?? []);
9996
+ const items = new Map(
9997
+ input.mapped?.items.map((item) => [`${item.runId}:${item.itemIndex}`, item]) ?? []
9998
+ );
9999
+ const iterationsByRecordId = /* @__PURE__ */ new Map();
10000
+ for (const record3 of input.turnRecords ?? []) {
10001
+ const ref = record3.iteration;
10002
+ const run = ref ? runs.get(ref.runId) : void 0;
10003
+ if (!ref || !run) continue;
10004
+ iterationsByRecordId.set(
10005
+ record3.id,
10006
+ iterationFor(run, items.get(`${ref.runId}:${ref.itemIndex}`), ref.itemIndex, ref.itemKey)
10007
+ );
10008
+ }
10009
+ const describe = (turnId) => input.graph.turns.get(turnId)?.description.trim();
10010
+ const activeRun = input.mapped?.runs.find(
10011
+ (run) => run.status === "active" && run.turnId === input.selectedTurnId
10012
+ );
10013
+ const nextItem = input.lifecycleStatus === "active" && activeRun ? items.get(`${activeRun.id}:${activeRun.nextIndex + 1}`) : void 0;
9595
10014
  const path6 = input.graph.happyPath ?? [];
9596
10015
  const currentIndex = path6.indexOf(input.selectedTurnId ?? "");
9597
10016
  const nextId = input.lifecycleStatus === "active" && currentIndex >= 0 ? path6[currentIndex + 1] : void 0;
9598
10017
  const next = nextId ? input.graph.turns.get(nextId) : void 0;
10018
+ let plannedNextTurn = next && nextId ? { turnId: nextId, description: next.description } : null;
10019
+ if (activeRun && nextItem) {
10020
+ const iteration = iterationFor(activeRun, nextItem, nextItem.itemIndex, nextItem.itemKey);
10021
+ plannedNextTurn = {
10022
+ turnId: activeRun.turnId,
10023
+ description: withItemLabel(describe(activeRun.turnId) || activeRun.turnId, iteration),
10024
+ iteration
10025
+ };
10026
+ }
9599
10027
  return {
9600
- turns: input.turns.map((turn) => ({
9601
- ...turn,
9602
- displayTurn: input.graph.turns.get(turn.turnId)?.description.trim() || turn.displayTurn
9603
- })),
9604
- plannedNextTurn: next && nextId ? { turnId: nextId, description: next.description } : null
10028
+ turns: input.turns.map((turn) => {
10029
+ const displayTurn = describe(turn.turnId) || turn.displayTurn;
10030
+ const iteration = iterationsByRecordId.get(turn.id);
10031
+ return iteration ? { ...turn, displayTurn: withItemLabel(displayTurn, iteration), iteration } : { ...turn, displayTurn };
10032
+ }),
10033
+ plannedNextTurn
9605
10034
  };
9606
10035
  }
9607
10036
 
@@ -9613,7 +10042,7 @@ import {
9613
10042
  } from "@leitwerk-dev/domain";
9614
10043
  import {
9615
10044
  findUiLauncherById,
9616
- isLlmTurnDefinition as isLlmTurnDefinition2
10045
+ isLlmTurnDefinition as isLlmTurnDefinition3
9617
10046
  } from "@leitwerk-dev/process-sdk";
9618
10047
  import {
9619
10048
  createTemplateContext,
@@ -9627,116 +10056,6 @@ import {
9627
10056
  } from "@leitwerk-dev/protocol";
9628
10057
  import * as v2 from "valibot";
9629
10058
 
9630
- // src/future-execution-presenter.ts
9631
- import { parseFutureActionPayloadJson, parseFutureLaunchPayloadJson } from "@leitwerk-dev/protocol";
9632
- function futureSummaryState(execution) {
9633
- return {
9634
- id: execution.id,
9635
- nextRunAt: execution.nextRunAt,
9636
- status: execution.blockedReason ? "blocked" : "scheduled",
9637
- modelSelection: execution.modelSelection ?? null,
9638
- blockedReason: execution.blockedReason ?? null
9639
- };
9640
- }
9641
- function futureActionLabel(label, fallback) {
9642
- return typeof label === "string" && label.trim() !== "" ? label : fallback;
9643
- }
9644
- function buildFutureExecutionListView(deps, execution) {
9645
- const summary = {
9646
- ...futureSummaryState(execution),
9647
- scheduleKind: execution.scheduleKind,
9648
- processId: execution.processId,
9649
- cronExpression: execution.cronExpression
9650
- };
9651
- if (execution.kind === "launch") {
9652
- const launcher = deps.launcherService.listUiLaunchers().find((candidate2) => candidate2.id === execution.launcherId);
9653
- const parsedPayload2 = parseFutureLaunchPayloadJson(execution.payloadJson);
9654
- if (!parsedPayload2.ok) {
9655
- const launcherLabel = launcher?.label ?? execution.launcherId ?? execution.processId;
9656
- return {
9657
- ...summary,
9658
- kind: "launch",
9659
- title: launcher?.card.title ?? launcherLabel,
9660
- subtitle: `${launcherLabel} \xB7 invalid scheduled start`,
9661
- launcherId: execution.launcherId ?? execution.processId,
9662
- launcherLabel,
9663
- launchTitle: null,
9664
- launcherInput: {},
9665
- skillIds: [],
9666
- modelConfig: {}
9667
- };
9668
- }
9669
- const payload2 = parsedPayload2.value;
9670
- const title = typeof payload2.launchPlan.processInput.title === "string" && payload2.launchPlan.processInput.title.trim() !== "" ? payload2.launchPlan.processInput.title : typeof payload2.launchPlan.processInput.externalId === "string" && payload2.launchPlan.processInput.externalId.trim() !== "" ? payload2.launchPlan.processInput.externalId : launcher?.card.title ?? launcher?.label ?? payload2.launchPlan.processId;
9671
- const subtitle = execution.scheduleKind === "cron" ? `${launcher?.label ?? payload2.launchPlan.processId} \xB7 recurring cron` : `${launcher?.label ?? payload2.launchPlan.processId} \xB7 scheduled start`;
9672
- return {
9673
- ...summary,
9674
- kind: "launch",
9675
- title,
9676
- subtitle,
9677
- launcherId: execution.launcherId ?? payload2.launchPlan.launcherId,
9678
- launcherLabel: launcher?.label ?? payload2.launchPlan.launcherId,
9679
- launchTitle: payload2.launchPlan.processInput.title,
9680
- launcherInput: payload2.launcherInput,
9681
- skillIds: [...payload2.selectedSkillIds],
9682
- modelConfig: payload2.modelConfig
9683
- };
9684
- }
9685
- if (!execution.instanceId || !execution.actionId) {
9686
- return null;
9687
- }
9688
- const process2 = deps.processes.getById(execution.instanceId);
9689
- const parsedPayload = parseFutureActionPayloadJson(execution.payloadJson);
9690
- const payload = parsedPayload.ok ? parsedPayload.value : null;
9691
- const actionLabel = futureActionLabel(payload?.actionLabel ?? null, execution.actionId);
9692
- return {
9693
- ...summary,
9694
- kind: "action",
9695
- title: process2?.title ?? process2?.externalId ?? actionLabel,
9696
- subtitle: `${actionLabel} \xB7 ${payload ? "scheduled action" : "invalid scheduled action"}`,
9697
- instanceId: execution.instanceId,
9698
- actionId: execution.actionId,
9699
- actionLabel,
9700
- nextTurnModelProfileId: payload?.nextTurnModelProfileId ?? null
9701
- };
9702
- }
9703
- function buildFutureExecutionSummaries(deps, executions) {
9704
- return executions.map((execution) => buildFutureExecutionListView(deps, execution)).filter((execution) => execution !== null);
9705
- }
9706
- function getScheduledActionDetailForProcess(deps, process2) {
9707
- if (!deps.processActionRegistry) {
9708
- return null;
9709
- }
9710
- const scheduledAction = deps.futureExecutions.getScheduledActionByInstance(process2.id);
9711
- if (!scheduledAction?.actionId) {
9712
- return null;
9713
- }
9714
- const action = deps.processActionRegistry.getAction(process2.processId, scheduledAction.actionId);
9715
- if (!action) {
9716
- return null;
9717
- }
9718
- const parsedPayload = parseFutureActionPayloadJson(scheduledAction.payloadJson);
9719
- if (!parsedPayload.ok) {
9720
- return null;
9721
- }
9722
- const payload = parsedPayload.value;
9723
- const actionLabel = futureActionLabel(payload.actionLabel, action.label);
9724
- return {
9725
- ...futureSummaryState(scheduledAction),
9726
- actionId: scheduledAction.actionId,
9727
- actionLabel,
9728
- input: payload.input,
9729
- nextTurnModelProfileId: payload.nextTurnModelProfileId,
9730
- action: deps.buildActionSummaryForProcess(
9731
- process2,
9732
- scheduledAction.actionId,
9733
- action,
9734
- actionLabel,
9735
- { supportsScheduling: true }
9736
- )
9737
- };
9738
- }
9739
-
9740
10059
  // src/process-engine/internal-failures.ts
9741
10060
  function isInternalEngineFailureCode(code) {
9742
10061
  return code === "operation_failed" || code === "record_failed" || code === "post_commit_failed";
@@ -9909,7 +10228,7 @@ function buildProcessRunDetailsView(deps, process2, projects) {
9909
10228
  continue;
9910
10229
  }
9911
10230
  const turnDef = deps.processActionRegistry?.getTurnDefinition(process2.processId, turnId);
9912
- if (!turnDef || !isLlmTurnDefinition2(turnDef)) {
10231
+ if (!turnDef || !isLlmTurnDefinition3(turnDef)) {
9913
10232
  continue;
9914
10233
  }
9915
10234
  turns.push({
@@ -9949,35 +10268,6 @@ function buildProcessRunDetailsView(deps, process2, projects) {
9949
10268
  turns
9950
10269
  };
9951
10270
  }
9952
- function actionHasPurePlan(deps, process2, actionId) {
9953
- const action = deps.processActionRegistry?.getAction(process2.processId, actionId);
9954
- return typeof action?.plan === "function";
9955
- }
9956
- function buildActionSummaryForProcess(deps, process2, actionId, action, labelOverride, overrides = {}) {
9957
- const visibleAction = listCurrentVisibleActions(deps, process2).find(
9958
- (candidate2) => candidate2.id === actionId
9959
- );
9960
- const preview = visibleAction?.preview ?? deps.processActionRegistry?.resolveActionPreview(process2.processId, process2, actionId) ?? null;
9961
- const supportsScheduling = overrides.supportsScheduling ?? Boolean(
9962
- actionHasPurePlan(deps, process2, actionId) && deps.processActionRegistry?.resolveActionScheduling(process2.processId, process2, actionId)
9963
- );
9964
- return buildProcessActionSummary(action, labelOverride ?? visibleAction?.label ?? action.label, {
9965
- description: visibleAction?.description ?? null,
9966
- preview: buildProcessActionPreviewSummary(deps, preview, process2),
9967
- supportsScheduling,
9968
- supportsNextTurnModelOverride: previewSupportsNextTurnModelOverride(
9969
- deps,
9970
- process2,
9971
- actionId,
9972
- preview
9973
- )
9974
- });
9975
- }
9976
- function listVisibleActionsForProcess2(deps, process2) {
9977
- return listVisibleActionsForProcess(deps, process2).map(
9978
- (action) => buildActionSummaryForProcess(deps, process2, action.id, action, action.label)
9979
- );
9980
- }
9981
10271
  function processDefinesLeafOutcome(deps, process2) {
9982
10272
  return deps.processUiRegistry?.getLeafOutcomeDefinition(process2.processId) != null;
9983
10273
  }
@@ -10110,72 +10400,6 @@ function normalizeRecoveryModelRequest(value) {
10110
10400
  });
10111
10401
  return parsed.ok ? { ok: true, request: parsed.request } : parsed;
10112
10402
  }
10113
- function buildProcessActionPreviewSummary(deps, preview, process2) {
10114
- if (!preview) {
10115
- return null;
10116
- }
10117
- if (!preview.candidateSelectedTurnId) {
10118
- return {
10119
- kind: "terminal",
10120
- turnId: null,
10121
- turnKind: null,
10122
- description: preview.lifecycleStatus === "aborted" ? "Abort process" : "Complete process"
10123
- };
10124
- }
10125
- const turnDef = deps.processActionRegistry?.getTurnDefinition(
10126
- process2.processId,
10127
- preview.candidateSelectedTurnId
10128
- );
10129
- if (!turnDef) {
10130
- return null;
10131
- }
10132
- return {
10133
- kind: "turn",
10134
- turnId: preview.candidateSelectedTurnId,
10135
- turnKind: turnDef.kind,
10136
- description: turnDef.description
10137
- };
10138
- }
10139
- function previewSupportsNextTurnModelOverride(deps, process2, actionId, preview) {
10140
- if (!preview?.candidateSelectedTurnId) {
10141
- return false;
10142
- }
10143
- if (!actionHasPurePlan(deps, process2, actionId)) {
10144
- return false;
10145
- }
10146
- const turnDef = deps.processActionRegistry?.getTurnDefinition(
10147
- process2.processId,
10148
- preview.candidateSelectedTurnId
10149
- );
10150
- return Boolean(turnDef && isLlmTurnDefinition2(turnDef));
10151
- }
10152
- function buildProcessActionSummary(action, labelOverride, opts = {}) {
10153
- return {
10154
- id: action.id,
10155
- label: labelOverride?.trim() ? labelOverride : action.label,
10156
- description: opts.description ?? null,
10157
- preview: opts.preview ?? null,
10158
- supportsScheduling: opts.supportsScheduling === true,
10159
- supportsNextTurnModelOverride: opts.supportsNextTurnModelOverride === true,
10160
- ...action.form ? {
10161
- form: {
10162
- id: action.form.id,
10163
- title: action.form.title,
10164
- submitLabel: action.form.submitLabel,
10165
- fields: action.form.fields.map((field) => ({ ...field }))
10166
- }
10167
- } : {}
10168
- };
10169
- }
10170
- function getScheduledActionDetailForProcess2(deps, process2) {
10171
- return getScheduledActionDetailForProcess(
10172
- {
10173
- ...deps,
10174
- buildActionSummaryForProcess: (process3, actionId, action, labelOverride, overrides) => buildActionSummaryForProcess(deps, process3, actionId, action, labelOverride, overrides)
10175
- },
10176
- process2
10177
- );
10178
- }
10179
10403
  function buildLauncherModelConfigSchema(deps, processId) {
10180
10404
  return presentLauncherModelConfigSchema(
10181
10405
  deps.processModelPolicy.project({
@@ -10243,7 +10467,7 @@ function sendScheduledActionMutationResponse(reply, deps, outcome) {
10243
10467
  const lockedProcess = deps.processes.getById(outcome.instanceId);
10244
10468
  const body = {
10245
10469
  kind: "scheduled",
10246
- scheduledAction: lockedProcess ? getScheduledActionDetailForProcess2(deps, lockedProcess) : null,
10470
+ scheduledAction: lockedProcess ? getScheduledActionDetailForProcess(deps, lockedProcess) : null,
10247
10471
  ...outcome.kind === "committed_with_reaction_error" ? { error: outcome.error, code: outcome.code } : {}
10248
10472
  };
10249
10473
  return reply.code(outcome.kind === "scheduled" && outcome.operation === "created" ? 201 : 200).send(body);
@@ -11275,6 +11499,10 @@ var ProcessUiSnapshotAssembler = class {
11275
11499
  }
11276
11500
  const projects = this.deps.projects.listByInstance(instanceId);
11277
11501
  const turnRecords2 = this.deps.turnRecords.listByInstance(instanceId);
11502
+ const mapped = {
11503
+ runs: this.deps.mappedRuns?.listByInstance(instanceId) ?? [],
11504
+ items: this.deps.mappedRuns?.listItemsByInstance(instanceId) ?? []
11505
+ };
11278
11506
  const events = compactDetailEvents(this.deps, instanceId, turnRecords2);
11279
11507
  const turnAnnotations2 = this.deps.turnAnnotations.listByInstance(instanceId);
11280
11508
  const inputs = this.deps.inputs.listByInstance(instanceId);
@@ -11373,7 +11601,9 @@ var ProcessUiSnapshotAssembler = class {
11373
11601
  graph: getProcessGraph2(this.deps.processGraphs, process2.processId),
11374
11602
  turns: projections.timeline.turns,
11375
11603
  selectedTurnId: process2.selectedTurnId,
11376
- lifecycleStatus: process2.lifecycleStatus
11604
+ lifecycleStatus: process2.lifecycleStatus,
11605
+ turnRecords: turnRecords2,
11606
+ mapped
11377
11607
  });
11378
11608
  return {
11379
11609
  ...projections,
@@ -11393,7 +11623,7 @@ var ProcessUiSnapshotAssembler = class {
11393
11623
  processFlow: buildProcessFlowViewForProcess(this.deps.processGraphs, process2.processId),
11394
11624
  definesLeafOutcome: processDefinesLeafOutcome(this.deps, process2),
11395
11625
  selectedTurn,
11396
- scheduledAction: getScheduledActionDetailForProcess2(this.deps, process2),
11626
+ scheduledAction: getScheduledActionDetailForProcess(this.deps, process2),
11397
11627
  modelConfiguration,
11398
11628
  runDetails,
11399
11629
  launchConfiguration: buildProcessLaunchConfigurationView(this.deps, process2, projects),
@@ -11853,6 +12083,7 @@ function createWrites(init = {}) {
11853
12083
  ...init.projectWrite ? { projectWrite: init.projectWrite } : {},
11854
12084
  turnRecordWrites: [...init.turnRecordWrites ?? []],
11855
12085
  turnStartWrites: [...init.turnStartWrites ?? []],
12086
+ mappedRunWrites: [...init.mappedRunWrites ?? []],
11856
12087
  turnAnnotationWrites: [...init.turnAnnotationWrites ?? []],
11857
12088
  leafOutcomeSnapshotWrites: [...init.leafOutcomeSnapshotWrites ?? []],
11858
12089
  events: [...init.events ?? []],
@@ -11880,6 +12111,7 @@ function mergeWrites(...writesList) {
11880
12111
  }
11881
12112
  merged.turnRecordWrites.push(...writes.turnRecordWrites);
11882
12113
  merged.turnStartWrites.push(...writes.turnStartWrites);
12114
+ merged.mappedRunWrites.push(...writes.mappedRunWrites);
11883
12115
  merged.turnAnnotationWrites.push(...writes.turnAnnotationWrites);
11884
12116
  merged.leafOutcomeSnapshotWrites.push(...writes.leafOutcomeSnapshotWrites);
11885
12117
  merged.events.push(...writes.events);
@@ -12055,13 +12287,14 @@ export {
12055
12287
  authenticateBrowserRequest,
12056
12288
  authenticateRequest,
12057
12289
  requireApiActor,
12290
+ listVisibleActionsForProcess2,
12058
12291
  buildFutureExecutionListView,
12059
12292
  buildFutureExecutionSummaries,
12293
+ getScheduledActionDetailForProcess,
12060
12294
  PRIMARY_PATH_ACTIVE_TURN_EVENT_LIMIT,
12061
12295
  routeConfig,
12062
12296
  buildProcessLaunchConfigurationView,
12063
12297
  buildProcessRunDetailsView,
12064
- listVisibleActionsForProcess2,
12065
12298
  processDefinesLeafOutcome,
12066
12299
  getProcessOrReply,
12067
12300
  normalizeLauncherRequest,
@@ -12070,7 +12303,6 @@ export {
12070
12303
  sendActionRequestNormalizationError,
12071
12304
  normalizeContinueRequest,
12072
12305
  normalizeRecoveryModelRequest,
12073
- getScheduledActionDetailForProcess2 as getScheduledActionDetailForProcess,
12074
12306
  buildLauncherModelConfigSchema,
12075
12307
  sendLauncherLookupFailure,
12076
12308
  sendLauncherMutationResponse,
@@ -12086,4 +12318,4 @@ export {
12086
12318
  createProjectedSessionSnapshotStore,
12087
12319
  createBroadcaster
12088
12320
  };
12089
- //# sourceMappingURL=chunk-KIOQNNG6.js.map
12321
+ //# sourceMappingURL=chunk-HK6BLLHA.js.map