@osolmaz/pi-workflows 0.16.4 → 0.16.6

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 (173) hide show
  1. package/README.md +5 -5
  2. package/dist/builtins/autoimplement.workflow.d.ts +5 -1
  3. package/dist/builtins/autoimplement.workflow.js +29 -10
  4. package/dist/builtins/autoimplement.workflow.js.map +1 -1
  5. package/dist/client/client.js +3 -1
  6. package/dist/client/client.js.map +1 -1
  7. package/dist/client/protocol.d.ts +1 -1
  8. package/dist/client/protocol.js +18 -1
  9. package/dist/client/protocol.js.map +1 -1
  10. package/dist/client/view.d.ts +7 -5
  11. package/dist/extension/index.d.ts +2 -1
  12. package/dist/extension/index.js +115 -165
  13. package/dist/extension/index.js.map +1 -1
  14. package/dist/extension/recorder.d.ts +1 -1
  15. package/dist/extension/recorder.js +2 -2
  16. package/dist/extension/recorder.js.map +1 -1
  17. package/dist/extension/step-message.d.ts +1 -1
  18. package/dist/extension/step-message.js +4 -4
  19. package/dist/extension/step-message.js.map +1 -1
  20. package/dist/extension/workflow-message-coordinator.d.ts +12 -1
  21. package/dist/extension/workflow-message-coordinator.js +65 -54
  22. package/dist/extension/workflow-message-coordinator.js.map +1 -1
  23. package/dist/resource-managers/index.d.ts +1 -2
  24. package/dist/resource-managers/index.js +1 -2
  25. package/dist/resource-managers/index.js.map +1 -1
  26. package/dist/resource-managers/sqlite.d.ts +2 -295
  27. package/dist/resource-managers/sqlite.js +71 -1528
  28. package/dist/resource-managers/sqlite.js.map +1 -1
  29. package/dist/resource-managers/types.d.ts +2 -7
  30. package/dist/server/resource-runner-entry.js +2 -6
  31. package/dist/server/resource-runner-entry.js.map +1 -1
  32. package/dist/server/rpc-bridge.js +1 -1
  33. package/dist/server/rpc-bridge.js.map +1 -1
  34. package/dist/server/rpc-executor.js +2 -4
  35. package/dist/server/rpc-executor.js.map +1 -1
  36. package/dist/server/server-entry.js +3 -0
  37. package/dist/server/server-entry.js.map +1 -1
  38. package/dist/server/server.d.ts +22 -8
  39. package/dist/server/server.js +498 -543
  40. package/dist/server/server.js.map +1 -1
  41. package/dist/server/state.d.ts +16 -29
  42. package/dist/server/state.js +105 -319
  43. package/dist/server/state.js.map +1 -1
  44. package/dist/server/view.d.ts +4 -5
  45. package/dist/server/view.js +51 -51
  46. package/dist/server/view.js.map +1 -1
  47. package/dist/server/workflow-runner-entry.d.ts +1 -1
  48. package/dist/server/workflow-runner-entry.js +1 -49
  49. package/dist/server/workflow-runner-entry.js.map +1 -1
  50. package/dist/server/workflow-runner-protocol.d.ts +2 -7
  51. package/dist/server/workflow-runner-protocol.js +5 -10
  52. package/dist/server/workflow-runner-protocol.js.map +1 -1
  53. package/dist/server/workflow-runner-store.d.ts +5 -6
  54. package/dist/server/workflow-runner-store.js +7 -14
  55. package/dist/server/workflow-runner-store.js.map +1 -1
  56. package/dist/state/attempt-time.d.ts +21 -0
  57. package/dist/state/attempt-time.js +95 -0
  58. package/dist/state/attempt-time.js.map +1 -0
  59. package/dist/state/json.d.ts +2 -1
  60. package/dist/state/json.js.map +1 -1
  61. package/dist/state/project-store.d.ts +39 -0
  62. package/dist/state/project-store.js +154 -0
  63. package/dist/state/project-store.js.map +1 -0
  64. package/dist/state/prune.d.ts +28 -0
  65. package/dist/state/prune.js +278 -83
  66. package/dist/state/prune.js.map +1 -1
  67. package/dist/state/schema.js +23 -23
  68. package/dist/state/workflow-messages.d.ts +1 -1
  69. package/dist/state/workflow-messages.js +3 -1
  70. package/dist/state/workflow-messages.js.map +1 -1
  71. package/dist/viewer/backup.js +5 -0
  72. package/dist/viewer/backup.js.map +1 -1
  73. package/dist/workflows/diagnostics.d.ts +8 -0
  74. package/dist/workflows/diagnostics.js +61 -0
  75. package/dist/workflows/diagnostics.js.map +1 -0
  76. package/dist/workflows/engine.d.ts +2 -15
  77. package/dist/workflows/engine.js +125 -245
  78. package/dist/workflows/engine.js.map +1 -1
  79. package/dist/workflows/human-decision.d.ts +3 -7
  80. package/dist/workflows/human-decision.js +2 -56
  81. package/dist/workflows/human-decision.js.map +1 -1
  82. package/dist/workflows/index.d.ts +2 -1
  83. package/dist/workflows/index.js +1 -0
  84. package/dist/workflows/index.js.map +1 -1
  85. package/dist/workflows/queue.d.ts +267 -0
  86. package/dist/workflows/queue.js +1248 -0
  87. package/dist/workflows/queue.js.map +1 -0
  88. package/dist/workflows/requests.d.ts +47 -0
  89. package/dist/workflows/requests.js +158 -0
  90. package/dist/workflows/requests.js.map +1 -0
  91. package/dist/workflows/schema.js +2 -4
  92. package/dist/workflows/schema.js.map +1 -1
  93. package/dist/workflows/store.d.ts +11 -16
  94. package/dist/workflows/store.js +174 -169
  95. package/dist/workflows/store.js.map +1 -1
  96. package/dist/workflows/tool-input.d.ts +6 -9
  97. package/dist/workflows/tool-input.js +15 -12
  98. package/dist/workflows/tool-input.js.map +1 -1
  99. package/dist/workflows/transitions.d.ts +38 -0
  100. package/dist/workflows/transitions.js +276 -0
  101. package/dist/workflows/transitions.js.map +1 -0
  102. package/dist/workflows/types.d.ts +9 -42
  103. package/dist/workflows/workflow-message-content.d.ts +7 -1
  104. package/dist/workflows/workflow-message-content.js +22 -4
  105. package/dist/workflows/workflow-message-content.js.map +1 -1
  106. package/docs/2026-08-25-workflow-follow-ups.md +5 -5
  107. package/docs/2026-09-02-unify-workflow-messages-plan.md +2 -0
  108. package/docs/2026-09-04-workflow-run-state-plan.md +2 -0
  109. package/docs/2026-09-06-durable-execution-plan.md +176 -0
  110. package/docs/DEFERRED_TURNS.md +84 -105
  111. package/docs/HUMAN_DECISIONS.md +17 -19
  112. package/docs/HUMAN_DECISION_PRESENTATIONS.md +1 -1
  113. package/docs/SQLITE_STATE.md +87 -30
  114. package/docs/WORKFLOW_SERVER.md +50 -11
  115. package/docs/WORKFLOW_STEP_MESSAGES.md +72 -54
  116. package/docs/plans/2026-08-04-controller-runtime-plan.md +2 -0
  117. package/docs/plans/2026-08-21-deferred-turn-intents-plan.md +2 -0
  118. package/docs/plans/2026-08-27-workflow-terminal-restart-plan.md +2 -0
  119. package/docs/plans/2026-09-04-automatic-state-retention-plan.md +283 -0
  120. package/docs/workflows.md +109 -44
  121. package/examples/workflows/autoresearch.workflow.ts +0 -2
  122. package/examples/workflows/branch.workflow.ts +0 -4
  123. package/examples/workflows/echo.workflow.ts +0 -2
  124. package/examples/workflows/live-settings.workflow.ts +0 -2
  125. package/examples/workflows/two-turn.workflow.ts +0 -2
  126. package/herdr-plugin.toml +1 -1
  127. package/package.json +1 -1
  128. package/protocol/fixtures/client-v1.json +1 -1
  129. package/skills/pi-workflows/SKILL.md +8 -7
  130. package/src/builtins/autoimplement.workflow.ts +31 -10
  131. package/src/client/client.ts +3 -1
  132. package/src/client/protocol.ts +21 -1
  133. package/src/client/view.ts +9 -5
  134. package/src/extension/index.ts +117 -189
  135. package/src/extension/recorder.ts +2 -2
  136. package/src/extension/step-message.ts +4 -4
  137. package/src/extension/workflow-message-coordinator.ts +78 -50
  138. package/src/resource-managers/index.ts +1 -9
  139. package/src/resource-managers/sqlite.ts +330 -2655
  140. package/src/resource-managers/types.ts +2 -3
  141. package/src/server/resource-runner-entry.ts +2 -7
  142. package/src/server/rpc-bridge.ts +1 -1
  143. package/src/server/rpc-executor.ts +4 -9
  144. package/src/server/server-entry.ts +3 -0
  145. package/src/server/server.ts +568 -644
  146. package/src/server/state.ts +122 -466
  147. package/src/server/view.ts +56 -60
  148. package/src/server/workflow-runner-entry.ts +2 -55
  149. package/src/server/workflow-runner-protocol.ts +5 -15
  150. package/src/server/workflow-runner-store.ts +12 -27
  151. package/src/state/attempt-time.ts +122 -0
  152. package/src/state/json.ts +2 -1
  153. package/src/state/project-store.ts +218 -0
  154. package/src/state/prune.ts +408 -95
  155. package/src/state/schema.ts +23 -23
  156. package/src/state/workflow-messages.ts +4 -2
  157. package/src/viewer/backup.ts +7 -0
  158. package/src/workflows/diagnostics.ts +78 -0
  159. package/src/workflows/engine.ts +133 -291
  160. package/src/workflows/human-decision.ts +3 -81
  161. package/src/workflows/index.ts +8 -2
  162. package/src/workflows/queue.ts +2091 -0
  163. package/src/workflows/requests.ts +283 -0
  164. package/src/workflows/schema.ts +2 -6
  165. package/src/workflows/store.ts +223 -231
  166. package/src/workflows/tool-input.ts +20 -12
  167. package/src/workflows/transitions.ts +330 -0
  168. package/src/workflows/types.ts +9 -46
  169. package/src/workflows/workflow-message-content.ts +28 -4
  170. package/dist/resource-managers/runtime.d.ts +0 -59
  171. package/dist/resource-managers/runtime.js +0 -423
  172. package/dist/resource-managers/runtime.js.map +0 -1
  173. package/src/resource-managers/runtime.ts +0 -576
@@ -0,0 +1,1248 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { closeRunTime } from "../state/attempt-time.js";
3
+ import { StateDatabase } from "../state/database.js";
4
+ import { canonicalJson } from "../state/json.js";
5
+ import { resourceIdFor, tokenHash } from "../state/mutation.js";
6
+ import { ProjectStore, isRecord, validTimestamp, epoch, isSequenceRow, } from "../state/project-store.js";
7
+ import { initializeViewerRun, recordViewerDeltas } from "../state/viewer.js";
8
+ import { WorkflowMessageStore } from "../state/workflow-messages.js";
9
+ function workflowRunSelect(clause) {
10
+ return `SELECT r.run_id AS runId, r.resource_id AS resourceId,
11
+ d.workflow_name AS workflowName, r.workflow_ref AS workflowRef, r.status AS runStatus,
12
+ r.paused, r.definition_digest AS definitionDigest, d.definition_hash AS definitionHash,
13
+ r.input_hash AS inputHash,
14
+ r.launch_options_hash AS launchOptionsHash,
15
+ q.status, q.available_at AS availableAt,
16
+ q.consecutive_errors AS consecutiveErrors, q.error_code AS errorCode,
17
+ q.error_hash AS errorHash, b.origin_session_id AS originSessionId,
18
+ b.execution_mode AS executionMode, r.parent_run_id AS parentRunId,
19
+ r.root_run_id AS rootRunId, r.lineage_kind AS lineageKind,
20
+ r.restart_number AS restartNumber,
21
+ r.parent_run_revision AS parentRunRevision,
22
+ q.created_at AS createdAt, q.updated_at AS updatedAt,
23
+ q.started_at AS startedAt, q.finished_at AS finishedAt,
24
+ l.generation AS leaseGeneration, l.owner_id AS ownerId, l.expires_at AS claimExpiresAt
25
+ FROM runs r JOIN workflow_definitions d ON d.definition_digest = r.definition_digest
26
+ JOIN run_queue q ON q.run_id = r.run_id
27
+ LEFT JOIN run_bindings b ON b.run_id = r.run_id
28
+ JOIN leases l ON l.resource_id = r.resource_id ${clause}`;
29
+ }
30
+ function workflowRunViewSelect(clause) {
31
+ return `SELECT r.run_id AS runId, d.workflow_name AS workflowName,
32
+ r.workflow_ref AS workflowRef, r.status AS runStatus, r.paused,
33
+ r.definition_digest AS definitionDigest, q.status,
34
+ b.origin_session_id AS originSessionId, b.execution_mode AS executionMode,
35
+ r.parent_run_id AS parentRunId, r.root_run_id AS rootRunId,
36
+ r.lineage_kind AS lineageKind, r.restart_number AS restartNumber,
37
+ r.parent_run_revision AS parentRunRevision,
38
+ q.error_code AS errorCode, CAST(error.content AS TEXT) AS errorMessage,
39
+ q.created_at AS createdAt, q.updated_at AS updatedAt,
40
+ q.started_at AS startedAt, q.finished_at AS finishedAt,
41
+ source.source_type AS sourceType, source.source_ref AS sourceRef,
42
+ source.source_revision AS sourceRevision
43
+ FROM runs r JOIN workflow_definitions d ON d.definition_digest = r.definition_digest
44
+ JOIN run_queue q ON q.run_id = r.run_id
45
+ LEFT JOIN run_bindings b ON b.run_id = r.run_id
46
+ LEFT JOIN run_sources source ON source.run_id = r.run_id AND source.mount_path = ''
47
+ LEFT JOIN blobs error ON error.blob_hash = q.error_hash ${clause}`;
48
+ }
49
+ function workflowRunViewRecord(row) {
50
+ const root = row.sourceType === "builtin"
51
+ ? { kind: "builtin", id: row.sourceRef, revision: row.sourceRevision }
52
+ : { kind: "file", path: row.sourceRef, hash: row.sourceRevision };
53
+ return {
54
+ runId: row.runId,
55
+ workflowName: row.workflowName,
56
+ workflowSourceRef: row.workflowRef,
57
+ workflowSource: { root, mounted: [] },
58
+ initialized: row.runStatus !== "queued",
59
+ definitionDigest: `sha256:${row.definitionDigest.toString("hex")}`,
60
+ runStateStatus: row.runStatus,
61
+ paused: row.paused === 1,
62
+ status: row.status,
63
+ originSessionId: row.executionMode === "headless" ? null : row.originSessionId,
64
+ executionMode: row.executionMode,
65
+ parentRunId: row.parentRunId,
66
+ rootRunId: row.rootRunId,
67
+ lineageKind: row.lineageKind,
68
+ restartNumber: row.restartNumber,
69
+ parentRunRevision: row.parentRunRevision,
70
+ errorCode: row.errorCode,
71
+ errorMessage: row.errorMessage,
72
+ createdAt: new Date(row.createdAt).toISOString(),
73
+ updatedAt: new Date(row.updatedAt).toISOString(),
74
+ startedAt: row.startedAt === null ? null : new Date(row.startedAt).toISOString(),
75
+ finishedAt: row.finishedAt === null ? null : new Date(row.finishedAt).toISOString(),
76
+ };
77
+ }
78
+ function isWorkflowRunViewRow(value) {
79
+ return (isRecord(value) &&
80
+ typeof value.runId === "string" &&
81
+ typeof value.workflowName === "string" &&
82
+ typeof value.workflowRef === "string" &&
83
+ typeof value.runStatus === "string" &&
84
+ typeof value.paused === "number" &&
85
+ Buffer.isBuffer(value.definitionDigest) &&
86
+ typeof value.status === "string" &&
87
+ (value.originSessionId === null || typeof value.originSessionId === "string") &&
88
+ (value.executionMode === "interactive" || value.executionMode === "headless") &&
89
+ (value.parentRunId === null || typeof value.parentRunId === "string") &&
90
+ typeof value.rootRunId === "string" &&
91
+ (value.lineageKind === null || value.lineageKind === "restart") &&
92
+ typeof value.restartNumber === "number" &&
93
+ (value.parentRunRevision === null || typeof value.parentRunRevision === "number") &&
94
+ (value.errorCode === null || typeof value.errorCode === "string") &&
95
+ (value.errorMessage === null || typeof value.errorMessage === "string") &&
96
+ typeof value.createdAt === "number" &&
97
+ typeof value.updatedAt === "number" &&
98
+ (value.startedAt === null || typeof value.startedAt === "number") &&
99
+ (value.finishedAt === null || typeof value.finishedAt === "number") &&
100
+ (value.sourceType === "builtin" || value.sourceType === "file") &&
101
+ typeof value.sourceRef === "string" &&
102
+ typeof value.sourceRevision === "string");
103
+ }
104
+ function isRunListRevisionRow(value) {
105
+ return (isRecord(value) &&
106
+ typeof value.count === "number" &&
107
+ typeof value.revisionSum === "number" &&
108
+ typeof value.updatedAt === "number");
109
+ }
110
+ function isRunRow(value) {
111
+ return isRecord(value);
112
+ }
113
+ function isRunSourceIdentityRow(value) {
114
+ return isRecord(value);
115
+ }
116
+ function isCancelledRunEffectRow(value) {
117
+ return (isRecord(value) &&
118
+ typeof value.effectId === "string" &&
119
+ typeof value.resourceId === "string" &&
120
+ (value.status === "pending" || value.status === "applying") &&
121
+ typeof value.attemptCount === "number");
122
+ }
123
+ function isExpiredInteractionRow(value) {
124
+ return (isRecord(value) && typeof value.requestId === "string" && typeof value.attemptId === "string");
125
+ }
126
+ function isRunEventRow(value) {
127
+ return isRecord(value);
128
+ }
129
+ function isCanonicalPathRow(value) {
130
+ return isRecord(value) && typeof value.canonicalPath === "string";
131
+ }
132
+ function isEffectIdentityRow(value) {
133
+ return isRecord(value);
134
+ }
135
+ function digestBuffer(value) {
136
+ const hex = value.startsWith("sha256:") ? value.slice(7) : value;
137
+ if (!/^[a-f0-9]{64}$/i.test(hex))
138
+ throw new Error("Expected a SHA-256 digest");
139
+ return Buffer.from(hex, "hex");
140
+ }
141
+ function queuedWorkflowSource(value) {
142
+ if (isWorkflowSource(value)) {
143
+ return { root: value, mounted: [] };
144
+ }
145
+ if (isRecord(value) &&
146
+ isWorkflowSource(value.root) &&
147
+ Array.isArray(value.mounted) &&
148
+ value.mounted.every(isMountedWorkflowSource)) {
149
+ return { root: value.root, mounted: value.mounted };
150
+ }
151
+ throw new Error("Stored workflow source identity is invalid");
152
+ }
153
+ function isWorkflowSource(value) {
154
+ return (isRecord(value) &&
155
+ ((value.kind === "builtin" &&
156
+ typeof value.id === "string" &&
157
+ typeof value.revision === "string") ||
158
+ (value.kind === "file" && typeof value.path === "string" && typeof value.hash === "string")));
159
+ }
160
+ function isMountedWorkflowSource(value) {
161
+ return (isRecord(value) &&
162
+ Array.isArray(value.mountPath) &&
163
+ value.mountPath.every((part) => typeof part === "string") &&
164
+ typeof value.workflowName === "string" &&
165
+ isWorkflowSource(value.source));
166
+ }
167
+ function insertQueuedRunSources(state, runId, value) {
168
+ const insert = state.connection.prepare(`INSERT INTO run_sources(run_id, mount_path, source_type, source_ref, source_revision)
169
+ VALUES (?, ?, ?, ?, ?)`);
170
+ const root = queuedSourceParts(value.root);
171
+ insert.run(runId, "", root.type, root.ref, root.revision);
172
+ for (const mounted of value.mounted) {
173
+ const source = queuedSourceParts(mounted.source);
174
+ insert.run(runId, mounted.mountPath.join("/"), source.type, source.ref, source.revision);
175
+ }
176
+ }
177
+ function queuedSourceParts(source) {
178
+ return source.kind === "builtin"
179
+ ? { type: "builtin", ref: source.id, revision: source.revision }
180
+ : { type: "file", ref: source.path, revision: source.hash };
181
+ }
182
+ function readQueuedRunSources(state, run) {
183
+ const rows = state.connection
184
+ .prepare(`SELECT mount_path AS mountPath, source_type AS sourceType,
185
+ source_ref AS sourceRef, source_revision AS sourceRevision
186
+ FROM run_sources WHERE run_id = ? ORDER BY mount_path`)
187
+ .all(run.runId)
188
+ .filter(isRunSourceIdentityRow);
189
+ const rootRow = rows.find((row) => row.mountPath === "");
190
+ if (rootRow === undefined)
191
+ throw new Error(`Workflow run source is missing: ${run.runId}`);
192
+ const snapshot = state.readJson(run.definitionHash);
193
+ const mounts = isRecord(snapshot) &&
194
+ isRecord(snapshot.composition) &&
195
+ Array.isArray(snapshot.composition.mounts)
196
+ ? snapshot.composition.mounts
197
+ : [];
198
+ const names = new Map(mounts.flatMap((mount) => {
199
+ if (!isRecord(mount) ||
200
+ !Array.isArray(mount.mountPath) ||
201
+ !mount.mountPath.every((part) => typeof part === "string") ||
202
+ typeof mount.workflowName !== "string") {
203
+ return [];
204
+ }
205
+ return [[mount.mountPath.join("/"), mount.workflowName]];
206
+ }));
207
+ return {
208
+ root: rowToSource(rootRow),
209
+ mounted: rows
210
+ .filter((row) => row.mountPath !== "")
211
+ .map((row) => ({
212
+ mountPath: row.mountPath.split("/"),
213
+ workflowName: names.get(row.mountPath) ?? row.mountPath,
214
+ source: rowToSource(row),
215
+ })),
216
+ };
217
+ }
218
+ function rowToSource(row) {
219
+ return row.sourceType === "builtin"
220
+ ? { kind: "builtin", id: row.sourceRef, revision: row.sourceRevision }
221
+ : { kind: "file", path: row.sourceRef, hash: row.sourceRevision };
222
+ }
223
+ function validateRunId(value) {
224
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(value))
225
+ throw new Error(`Invalid workflow run id: ${value}`);
226
+ }
227
+ export class WorkflowRunQueueStore extends ProjectStore {
228
+ workflowMessages = new WorkflowMessageStore(this.state);
229
+ reserveWorkflowRun(options) {
230
+ validateRunId(options.runId);
231
+ const now = epoch(validTimestamp(options.now));
232
+ const definitionDigest = digestBuffer(options.definitionDigest);
233
+ return this.state.transaction(() => this.reserveWorkflowRunInTransaction(options, now, definitionDigest));
234
+ }
235
+ reserveWorkflowRunInTransaction(options, now, definitionDigest) {
236
+ if (this.getWorkflowRun(options.runId) !== undefined) {
237
+ throw new Error(`Workflow run already reserved: ${options.runId}`);
238
+ }
239
+ const lineageKind = options.parentRunId === undefined ? null : (options.lineageKind ?? null);
240
+ if ((options.parentRunId === undefined && options.lineageKind !== undefined) ||
241
+ (options.parentRunId !== undefined && lineageKind !== "restart")) {
242
+ throw new Error("Only an explicit restart can declare a parent run");
243
+ }
244
+ let rootRunId = options.runId;
245
+ let restartNumber = 0;
246
+ let parentRunRevision = null;
247
+ if (options.parentRunId !== undefined) {
248
+ const parent = this.requireWorkflowRunRow(options.parentRunId);
249
+ if (parent.originSessionId !== options.originSessionId) {
250
+ throw new Error("Workflow parent belongs to another Pi session");
251
+ }
252
+ rootRunId = parent.rootRunId;
253
+ if (lineageKind === "restart") {
254
+ if (!["completed", "failed", "timed_out", "cancelled"].includes(parent.runStatus) ||
255
+ !["done", "failed", "cancelled"].includes(parent.status)) {
256
+ throw new Error("Restart parent is not terminal");
257
+ }
258
+ if (options.parentRunRevision === undefined ||
259
+ !Number.isSafeInteger(options.parentRunRevision) ||
260
+ options.parentRunRevision < 0) {
261
+ throw new Error("Restart requires the exact parent run revision");
262
+ }
263
+ if (options.parentRunRevision !== this.resourceRevision(parent.resourceId)) {
264
+ throw new Error("Restart parent revision changed");
265
+ }
266
+ parentRunRevision = options.parentRunRevision;
267
+ restartNumber = options.restartNumber ?? parent.restartNumber + 1;
268
+ if (restartNumber !== parent.restartNumber + 1) {
269
+ throw new Error("Restart number does not follow its parent");
270
+ }
271
+ }
272
+ }
273
+ else if (options.restartNumber !== undefined || options.parentRunRevision !== undefined) {
274
+ throw new Error("A root workflow run cannot declare restart metadata");
275
+ }
276
+ const resourceId = resourceIdFor("run", options.runId);
277
+ const definitionHash = this.state.putJson(options.definitionSnapshot, now);
278
+ const queuedSource = queuedWorkflowSource(options.workflowSource);
279
+ const inputHash = this.state.putJson(options.input ?? null, now);
280
+ const launchHash = this.state.putJson(options.launchOptions ?? {}, now);
281
+ this.state.connection
282
+ .prepare(`INSERT INTO workflow_definitions(
283
+ definition_digest, workflow_name, definition_hash, created_at
284
+ ) VALUES (?, ?, ?, ?)
285
+ ON CONFLICT(definition_digest) DO NOTHING`)
286
+ .run(definitionDigest, options.workflowName, definitionHash, now);
287
+ this.state.connection
288
+ .prepare(`INSERT INTO resources(resource_id, resource_type, aggregate_key, revision, created_at, updated_at)
289
+ VALUES (?, 'run', ?, 1, ?, ?)`)
290
+ .run(resourceId, options.runId, now, now);
291
+ this.state.connection
292
+ .prepare("INSERT INTO leases(resource_id, generation) VALUES (?, 0)")
293
+ .run(resourceId);
294
+ this.state.connection
295
+ .prepare(`INSERT INTO runs(
296
+ run_id, resource_id, project_id, parent_run_id, root_run_id, lineage_kind,
297
+ restart_number, parent_run_revision, definition_digest,
298
+ workflow_ref, launch_options_hash, status, paused,
299
+ input_hash, created_at, updated_at
300
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', 0, ?, ?, ?)`)
301
+ .run(options.runId, resourceId, this.requireProjectId(), options.parentRunId ?? null, rootRunId, lineageKind, restartNumber, parentRunRevision, definitionDigest, options.workflowSourceRef, launchHash, inputHash, now, now);
302
+ initializeViewerRun(this.state, options.runId, now);
303
+ insertQueuedRunSources(this.state, options.runId, queuedSource);
304
+ this.state.connection
305
+ .prepare(`INSERT INTO run_bindings(run_id, origin_session_id, execution_mode, created_at)
306
+ VALUES (?, ?, ?, ?)`)
307
+ .run(options.runId, options.originSessionId, options.executionMode ?? "interactive", now);
308
+ this.state.connection
309
+ .prepare(`INSERT INTO run_queue(
310
+ run_id, status, available_at, origin_session_id,
311
+ consecutive_errors, created_at, updated_at
312
+ ) VALUES (?, 'queued', ?, ?, 0, ?, ?)`)
313
+ .run(options.runId, now, options.executionMode === "headless" ? null : options.originSessionId, now, now);
314
+ this.insertEvent(resourceId, 1, "run.queued", "session", options.originSessionId, {}, now);
315
+ return this.requireWorkflowRun(options.runId);
316
+ }
317
+ reserveOrAdoptWorkflowRun(options) {
318
+ validateRunId(options.runId);
319
+ const now = epoch(validTimestamp(options.now));
320
+ const definitionDigest = digestBuffer(options.definitionDigest);
321
+ return this.state.transaction(() => {
322
+ const existing = this.workflowRunRow(options.runId);
323
+ if (existing !== undefined) {
324
+ this.assertWorkflowRunPreparationCompatible(existing, options, definitionDigest);
325
+ return { state: "adopted", run: this.mapWorkflowRun(existing) };
326
+ }
327
+ return {
328
+ state: "reserved",
329
+ run: this.reserveWorkflowRunInTransaction(options, now, definitionDigest),
330
+ };
331
+ });
332
+ }
333
+ getWorkflowRun(runId) {
334
+ const row = this.workflowRunRow(runId);
335
+ return row === undefined ? undefined : this.mapWorkflowRun(row);
336
+ }
337
+ getWorkflowRunView(runId) {
338
+ const row = this.workflowRunViewRows("WHERE r.run_id = ?", [runId])[0];
339
+ return row === undefined ? undefined : workflowRunViewRecord(row);
340
+ }
341
+ workflowRunListRevision() {
342
+ const row = this.state.connection
343
+ .prepare(`SELECT count(*) AS count, COALESCE(sum(res.revision), 0) AS revisionSum,
344
+ COALESCE(max(q.updated_at), 0) AS updatedAt
345
+ FROM runs r JOIN run_queue q ON q.run_id = r.run_id
346
+ JOIN resources res ON res.resource_id = r.resource_id`)
347
+ .get();
348
+ if (!isRunListRevisionRow(row))
349
+ throw new Error("Workflow run list revision is invalid");
350
+ return {
351
+ total: row.count,
352
+ revision: `${row.count}:${row.revisionSum}:${row.updatedAt}`,
353
+ };
354
+ }
355
+ listWorkflowRunViews(options) {
356
+ const current = this.workflowRunListRevision();
357
+ const rows = this.workflowRunViewRows("ORDER BY q.created_at DESC LIMIT ? OFFSET ?", [
358
+ options.limit,
359
+ options.offset,
360
+ ]);
361
+ return { ...current, runs: rows.map(workflowRunViewRecord) };
362
+ }
363
+ workflowRunProjectPath(runId) {
364
+ const row = this.state.connection
365
+ .prepare(`SELECT p.canonical_path AS canonicalPath
366
+ FROM runs r JOIN projects p ON p.project_id = r.project_id WHERE r.run_id = ?`)
367
+ .get(runId);
368
+ return isCanonicalPathRow(row) ? row.canonicalPath : undefined;
369
+ }
370
+ listWorkflowRuns(options = {}) {
371
+ const clauses = [];
372
+ const params = [];
373
+ if (this.projectId !== null) {
374
+ clauses.push("r.project_id = ?");
375
+ params.push(this.projectId);
376
+ }
377
+ if (options.statuses !== undefined && options.statuses.length > 0) {
378
+ clauses.push(`q.status IN (${options.statuses.map(() => "?").join(", ")})`);
379
+ params.push(...options.statuses);
380
+ }
381
+ if (options.excludeRunIds !== undefined && options.excludeRunIds.length > 0) {
382
+ clauses.push(`r.run_id NOT IN (${options.excludeRunIds.map(() => "?").join(", ")})`);
383
+ params.push(...options.excludeRunIds);
384
+ }
385
+ if (options.limit !== undefined)
386
+ params.push(options.limit);
387
+ const rows = this.state.connection
388
+ .prepare(workflowRunSelect(`${clauses.length === 0 ? "" : `WHERE ${clauses.join(" AND ")}`} ORDER BY q.created_at DESC${options.limit === undefined ? "" : " LIMIT ?"}`))
389
+ .all(...params);
390
+ return rows.filter(isRunRow).map((row) => this.mapWorkflowRun(row));
391
+ }
392
+ findSessionReservation(sessionId) {
393
+ const row = this.state.connection
394
+ .prepare(workflowRunSelect("WHERE b.origin_session_id = ? AND b.execution_mode = 'interactive' AND q.status NOT IN ('done', 'failed', 'cancelled') ORDER BY q.created_at DESC LIMIT 1"))
395
+ .get(sessionId);
396
+ return isRunRow(row) ? this.mapWorkflowRun(row) : undefined;
397
+ }
398
+ findSessionReservationView(sessionId) {
399
+ const row = this.workflowRunViewRows("WHERE b.origin_session_id = ? AND b.execution_mode = 'interactive' AND q.status NOT IN ('done', 'failed', 'cancelled') ORDER BY q.created_at DESC LIMIT 1", [sessionId])[0];
400
+ return row === undefined ? undefined : workflowRunViewRecord(row);
401
+ }
402
+ claimWorkflowRun(options) {
403
+ const now = epoch(validTimestamp(options.now));
404
+ return this.claimRun(options.runId, options.runnerId, options.claimToken, options.leaseMs, now);
405
+ }
406
+ /** Schedule a runner that validates one pending interactive submission. */
407
+ claimWorkflowRunForInteractionValidation(options) {
408
+ const now = epoch(validTimestamp(options.now));
409
+ return this.claimRun(options.runId, options.runnerId, options.claimToken, options.leaseMs, now, {
410
+ allowPendingInteraction: true,
411
+ });
412
+ }
413
+ /** Take a short server claim without scheduling a parked interactive run. */
414
+ claimWorkflowRunForControl(options) {
415
+ const now = epoch(validTimestamp(options.now));
416
+ return this.claimRun(options.runId, options.runnerId, options.claimToken, options.leaseMs, now, { allowPendingInteraction: true, preserveQueueStatus: true });
417
+ }
418
+ beginWorkflowRunInteractionTimeout(options) {
419
+ const now = epoch(validTimestamp(options.now));
420
+ return this.state.transaction(() => {
421
+ if (!this.verifyWorkflowRunClaim({
422
+ runId: options.runId,
423
+ claimToken: options.claimToken,
424
+ now: new Date(now).toISOString(),
425
+ })) {
426
+ return false;
427
+ }
428
+ const row = this.requireWorkflowRunRow(options.runId);
429
+ const interaction = this.state.connection
430
+ .prepare(`SELECT i.request_id AS requestId, i.attempt_id AS attemptId
431
+ FROM interactive_requests i
432
+ JOIN node_attempts a ON a.attempt_id = i.attempt_id
433
+ JOIN runs r ON r.run_id = i.run_id
434
+ WHERE i.run_id = ? AND i.target_session_id = ?
435
+ AND i.status = 'pending' AND r.paused = 0
436
+ AND a.timeout_ms > 0
437
+ AND (SELECT COALESCE(SUM(elapsed_ms), 0) FROM attempt_active_intervals t
438
+ WHERE t.attempt_id = a.attempt_id) >= a.timeout_ms
439
+ ORDER BY a.started_at, i.request_id LIMIT 1`)
440
+ .get(options.runId, options.targetSessionId);
441
+ if (!isExpiredInteractionRow(interaction))
442
+ return false;
443
+ closeRunTime(this.state, options.runId);
444
+ const request = this.state.connection
445
+ .prepare(`UPDATE interactive_requests
446
+ SET status = 'cancelled', revision = revision + 1, updated_at = ?
447
+ WHERE request_id = ? AND run_id = ? AND status = 'pending'`)
448
+ .run(now, interaction.requestId, options.runId);
449
+ const run = this.state.connection
450
+ .prepare(`UPDATE runs
451
+ SET status = 'running', status_detail = 'finishing expired interaction deadline',
452
+ updated_at = ?, finished_at = NULL
453
+ WHERE run_id = ? AND status = 'waiting'`)
454
+ .run(now, options.runId);
455
+ const queue = this.state.connection
456
+ .prepare(`UPDATE run_queue SET status = 'starting', error_code = NULL, error_hash = NULL,
457
+ updated_at = ?, finished_at = NULL
458
+ WHERE run_id = ? AND status = 'parked'`)
459
+ .run(now, options.runId);
460
+ /* istanbul ignore if -- the expired parked interaction was selected above */
461
+ if (request.changes !== 1 || run.changes !== 1 || queue.changes !== 1) {
462
+ throw new Error(`Workflow run ${options.runId} changed during interaction timeout`);
463
+ }
464
+ const error = "Workflow node model-turn deadline expired";
465
+ const receiptHash = this.state.putJson({ status: "rejected", error }, now);
466
+ this.state.connection
467
+ .prepare(`UPDATE interactive_submissions SET outcome = 'rejected', receipt_hash = ?
468
+ WHERE request_id = ? AND outcome = 'validating'`)
469
+ .run(receiptHash, interaction.requestId);
470
+ const revision = this.resourceRevision(row.resourceId);
471
+ const lease = this.requireLease(row.resourceId);
472
+ this.bumpResource(row.resourceId, revision, now);
473
+ this.insertEvent(row.resourceId, revision + 1, "run.interaction_timeout_started", lease.ownerType ?? "system", lease.ownerId, { requestId: interaction.requestId, attemptId: interaction.attemptId }, now, lease.generation || undefined);
474
+ recordViewerDeltas(this.state, options.runId, [{ targetType: "summary" }, { targetType: "replay" }, { targetType: "conversation" }], now);
475
+ return true;
476
+ });
477
+ }
478
+ markWorkflowRunRunning(options) {
479
+ return this.updateClaimedRunStatus(options.runId, options.claimToken, "running", options.now);
480
+ }
481
+ claimNextWorkflowRun(options) {
482
+ const now = epoch(validTimestamp(options.now));
483
+ const clauses = [
484
+ "q.status IN ('queued', 'parked', 'starting', 'running')",
485
+ "q.available_at <= ?",
486
+ "(l.owner_id IS NULL OR l.expires_at <= ? OR l.owner_id = ?)",
487
+ "NOT (q.status = 'parked' AND (r.status = 'waiting' OR r.paused = 1))",
488
+ "NOT EXISTS (SELECT 1 FROM interactive_requests i WHERE i.run_id = r.run_id AND i.status = 'pending')",
489
+ "(q.error_code IS NULL OR q.error_code NOT IN ('workflowSourceChanged', 'runnerNoProgress'))",
490
+ ];
491
+ const params = [now, now, options.runnerId];
492
+ if (this.projectId !== null) {
493
+ clauses.unshift("r.project_id = ?");
494
+ params.unshift(this.projectId);
495
+ }
496
+ if (options.excludeRunIds !== undefined && options.excludeRunIds.length > 0) {
497
+ clauses.push(`r.run_id NOT IN (${options.excludeRunIds.map(() => "?").join(", ")})`);
498
+ params.push(...options.excludeRunIds);
499
+ }
500
+ const row = this.state.connection
501
+ .prepare(workflowRunSelect(`WHERE ${clauses.join(" AND ")} ORDER BY q.available_at, q.created_at LIMIT 1`))
502
+ .get(...params);
503
+ if (!isRunRow(row))
504
+ return undefined;
505
+ return this.claimRun(row.runId, options.runnerId, options.claimToken, options.leaseMs, now);
506
+ }
507
+ renewWorkflowRunClaim(options) {
508
+ const now = epoch(validTimestamp(options.now));
509
+ return this.state.transaction(() => {
510
+ const row = this.workflowRunRow(options.runId);
511
+ if (row === undefined || row.ownerId === null)
512
+ return false;
513
+ const lease = this.requireLease(row.resourceId);
514
+ const result = this.state.connection
515
+ .prepare(`UPDATE leases SET heartbeat_at = ?, expires_at = ?
516
+ WHERE resource_id = ? AND owner_type = ? AND owner_id = ?
517
+ AND token_hash = ? AND generation = ? AND expires_at > ?`)
518
+ .run(now, now + options.leaseMs, row.resourceId, lease.ownerType, row.ownerId, tokenHash(options.claimToken), lease.generation, now);
519
+ if (result.changes === 1) {
520
+ recordViewerDeltas(this.state, options.runId, [{ targetType: "summary" }, { targetType: "replay" }], now);
521
+ return true;
522
+ }
523
+ return false;
524
+ });
525
+ }
526
+ verifyWorkflowRunClaim(options) {
527
+ const now = epoch(validTimestamp(options.now));
528
+ const row = this.workflowRunRow(options.runId);
529
+ if (row === undefined || row.ownerId === null || row.claimExpiresAt === null)
530
+ return false;
531
+ const lease = this.requireLease(row.resourceId);
532
+ return (lease.tokenHash !== null &&
533
+ lease.tokenHash.equals(tokenHash(options.claimToken)) &&
534
+ row.claimExpiresAt > now);
535
+ }
536
+ workflowRunAuthority(runId, claimToken) {
537
+ const row = this.workflowRunRow(runId);
538
+ if (row === undefined || row.ownerId === null || row.claimExpiresAt === null)
539
+ return undefined;
540
+ const lease = this.requireLease(row.resourceId);
541
+ if (lease.tokenHash === null || !lease.tokenHash.equals(tokenHash(claimToken)))
542
+ return undefined;
543
+ const ownerType = row.ownerId.startsWith("host-") ? "host" : "session";
544
+ return {
545
+ actor: { type: ownerType, id: row.ownerId },
546
+ ownerType,
547
+ ownerId: row.ownerId,
548
+ token: claimToken,
549
+ generation: row.leaseGeneration,
550
+ leaseMs: 30_000,
551
+ };
552
+ }
553
+ parkWorkflowRun(options) {
554
+ return this.releaseRunClaim(options.runId, options.claimToken, "parked", options.now);
555
+ }
556
+ parkWorkflowRunForRunnerNoProgress(options) {
557
+ const now = epoch(validTimestamp(options.now));
558
+ return this.state.transaction(() => {
559
+ if (!this.verifyWorkflowRunClaim({
560
+ runId: options.runId,
561
+ claimToken: options.claimToken,
562
+ now: new Date(now).toISOString(),
563
+ })) {
564
+ return false;
565
+ }
566
+ const row = this.requireWorkflowRunRow(options.runId);
567
+ const lease = this.requireLease(row.resourceId);
568
+ const detail = options.detail.slice(0, 8_192);
569
+ const errorHash = this.state.putText(detail, now);
570
+ const run = this.state.connection
571
+ .prepare(`UPDATE runs SET status_detail = ?, updated_at = ?, finished_at = NULL
572
+ WHERE run_id = ? AND status NOT IN ('completed', 'failed', 'timed_out', 'cancelled')`)
573
+ .run(detail, now, options.runId);
574
+ const queue = this.state.connection
575
+ .prepare(`UPDATE run_queue
576
+ SET status = 'parked', error_code = 'runnerNoProgress', error_hash = ?,
577
+ available_at = ?, updated_at = ?, finished_at = NULL
578
+ WHERE run_id = ? AND status IN ('queued', 'starting', 'running', 'parked')`)
579
+ .run(errorHash, now, now, options.runId);
580
+ if (run.changes !== 1 || queue.changes !== 1) {
581
+ throw new Error(`Workflow run ${options.runId} changed during runner recovery`);
582
+ }
583
+ const released = this.state.connection
584
+ .prepare(`UPDATE leases
585
+ SET owner_type = NULL, owner_id = NULL, token_hash = NULL,
586
+ acquired_at = NULL, heartbeat_at = NULL, expires_at = NULL
587
+ WHERE resource_id = ? AND token_hash = ? AND generation = ? AND expires_at > ?`)
588
+ .run(row.resourceId, tokenHash(options.claimToken), lease.generation, now);
589
+ /* istanbul ignore if -- the exact live claim is stable in this transaction */
590
+ if (released.changes !== 1) {
591
+ throw new Error(`Workflow run ${options.runId} claim changed during runner recovery`);
592
+ }
593
+ const revision = this.resourceRevision(row.resourceId);
594
+ this.bumpResource(row.resourceId, revision, now);
595
+ this.insertEvent(row.resourceId, revision + 1, "run.worker_no_progress", lease.ownerType ?? "system", lease.ownerId, { status: "parked", code: "runnerNoProgress" }, now, lease.generation || undefined);
596
+ recordViewerDeltas(this.state, options.runId, [{ targetType: "summary" }, { targetType: "replay" }], now);
597
+ return true;
598
+ });
599
+ }
600
+ pauseParkedWorkflowRun(options) {
601
+ const now = epoch(validTimestamp(options.now));
602
+ return this.state.transaction(() => {
603
+ const row = this.workflowRunRow(options.runId);
604
+ if (row === undefined || row.status !== "parked")
605
+ return false;
606
+ const lease = this.requireLease(row.resourceId);
607
+ if (lease.ownerId !== null && lease.expiresAt !== null && lease.expiresAt > now)
608
+ return false;
609
+ const pending = this.state.connection
610
+ .prepare(`SELECT 1 FROM interactive_requests
611
+ WHERE run_id = ? AND status = 'pending' LIMIT 1`)
612
+ .get(options.runId);
613
+ if (pending === undefined)
614
+ return false;
615
+ if (row.paused === 1)
616
+ return true;
617
+ if (!["running", "waiting"].includes(row.runStatus))
618
+ return false;
619
+ const changed = this.state.connection
620
+ .prepare(`UPDATE runs SET paused = 1, status_detail = 'paused', updated_at = ?
621
+ WHERE run_id = ? AND paused = 0 AND status IN ('running', 'waiting')`)
622
+ .run(now, options.runId);
623
+ if (changed.changes !== 1)
624
+ return false;
625
+ closeRunTime(this.state, options.runId);
626
+ const revision = this.resourceRevision(row.resourceId);
627
+ this.bumpResource(row.resourceId, revision, now);
628
+ this.insertEvent(row.resourceId, revision + 1, "run.paused", "control", null, { status: "parked" }, now);
629
+ recordViewerDeltas(this.state, options.runId, [{ targetType: "summary" }, { targetType: "replay" }], now);
630
+ return true;
631
+ });
632
+ }
633
+ resumePausedInteraction(options) {
634
+ const now = epoch(validTimestamp(options.now));
635
+ return this.state.transaction(() => {
636
+ const row = this.workflowRunRow(options.runId);
637
+ if (row === undefined ||
638
+ row.status !== "parked" ||
639
+ row.runStatus !== "waiting" ||
640
+ row.paused !== 1) {
641
+ return false;
642
+ }
643
+ const lease = this.requireLease(row.resourceId);
644
+ if (lease.ownerId !== null && lease.expiresAt !== null && lease.expiresAt > now)
645
+ return false;
646
+ const pending = this.state.connection
647
+ .prepare(`SELECT 1 FROM interactive_requests
648
+ WHERE run_id = ? AND status = 'pending' LIMIT 1`)
649
+ .get(options.runId);
650
+ if (pending === undefined)
651
+ return false;
652
+ const changed = this.state.connection
653
+ .prepare(`UPDATE runs
654
+ SET paused = 0, status_detail = 'waiting for origin-session input', updated_at = ?
655
+ WHERE run_id = ? AND status = 'waiting' AND paused = 1`)
656
+ .run(now, options.runId);
657
+ if (changed.changes !== 1)
658
+ return false;
659
+ const revision = this.resourceRevision(row.resourceId);
660
+ this.bumpResource(row.resourceId, revision, now);
661
+ this.insertEvent(row.resourceId, revision + 1, "run.resumed", "control", null, { status: "waiting" }, now);
662
+ recordViewerDeltas(this.state, options.runId, [{ targetType: "summary" }, { targetType: "replay" }], now);
663
+ return true;
664
+ });
665
+ }
666
+ requestWorkflowRunResume(options) {
667
+ const now = epoch(validTimestamp(options.now));
668
+ return this.state.transaction(() => {
669
+ const row = this.workflowRunRow(options.runId);
670
+ if (row === undefined || ["done", "failed", "cancelled"].includes(row.status))
671
+ return false;
672
+ const lease = this.requireLease(row.resourceId);
673
+ if (lease.ownerId !== null && lease.expiresAt !== null && lease.expiresAt > now)
674
+ return false;
675
+ if (this.state.connection
676
+ .prepare("SELECT 1 FROM interactive_requests WHERE run_id = ? AND status = 'pending'")
677
+ .get(options.runId) !== undefined)
678
+ return false;
679
+ this.state.connection
680
+ .prepare("UPDATE runs SET paused = 0, updated_at = ? WHERE run_id = ?")
681
+ .run(now, options.runId);
682
+ this.state.connection
683
+ .prepare("UPDATE run_queue SET status = 'queued', error_code = NULL, error_hash = NULL, available_at = ?, updated_at = ? WHERE run_id = ?")
684
+ .run(now, now, options.runId);
685
+ const revision = this.resourceRevision(row.resourceId);
686
+ this.bumpResource(row.resourceId, revision, now);
687
+ this.insertEvent(row.resourceId, revision + 1, "run.resume_requested", "control", null, { status: "queued" }, now);
688
+ recordViewerDeltas(this.state, options.runId, [{ targetType: "summary" }, { targetType: "replay" }], now);
689
+ return true;
690
+ });
691
+ }
692
+ isWorkflowRunPaused(runId) {
693
+ return this.workflowRunRow(runId)?.paused === 1;
694
+ }
695
+ parkWorkflowRunForSourceChange(options) {
696
+ const now = epoch(validTimestamp(options.now));
697
+ return this.state.transaction(() => {
698
+ const row = this.workflowRunRow(options.runId);
699
+ if (row === undefined ||
700
+ !this.verifyWorkflowRunClaim({
701
+ runId: options.runId,
702
+ claimToken: options.claimToken,
703
+ now: new Date(now).toISOString(),
704
+ })) {
705
+ return false;
706
+ }
707
+ const lease = this.requireLease(row.resourceId);
708
+ const detail = options.detail.slice(0, 8_192);
709
+ const errorHash = this.state.putText(detail, now);
710
+ const run = this.state.connection
711
+ .prepare(`UPDATE runs SET status_detail = ?, updated_at = ?, finished_at = NULL
712
+ WHERE run_id = ? AND status NOT IN ('completed', 'failed', 'timed_out', 'cancelled')`)
713
+ .run(detail, now, options.runId);
714
+ const queue = this.state.connection
715
+ .prepare(`UPDATE run_queue
716
+ SET status = 'parked', error_code = 'workflowSourceChanged', error_hash = ?,
717
+ available_at = ?, updated_at = ?, finished_at = NULL
718
+ WHERE run_id = ? AND status IN ('queued', 'starting', 'running', 'parked')`)
719
+ .run(errorHash, now, now, options.runId);
720
+ /* istanbul ignore if -- exact live claim and nonterminal checks make both updates mandatory */
721
+ if (run.changes !== 1 || queue.changes !== 1) {
722
+ throw new Error(`Workflow run ${options.runId} has inconsistent source-change state`);
723
+ }
724
+ const released = this.state.connection
725
+ .prepare(`UPDATE leases
726
+ SET owner_type = NULL, owner_id = NULL, token_hash = NULL,
727
+ acquired_at = NULL, heartbeat_at = NULL, expires_at = NULL
728
+ WHERE resource_id = ? AND token_hash = ? AND generation = ? AND expires_at > ?`)
729
+ .run(row.resourceId, tokenHash(options.claimToken), lease.generation, now);
730
+ /* istanbul ignore if -- the exact live claim is stable in this transaction */
731
+ if (released.changes !== 1) {
732
+ throw new Error(`Workflow run ${options.runId} claim changed during source recovery`);
733
+ }
734
+ const revision = this.resourceRevision(row.resourceId);
735
+ this.bumpResource(row.resourceId, revision, now);
736
+ this.insertEvent(row.resourceId, revision + 1, "run.source_changed", lease.ownerType ?? "system", lease.ownerId, { status: "parked", code: "workflowSourceChanged" }, now, lease.generation || undefined);
737
+ recordViewerDeltas(this.state, options.runId, [{ targetType: "summary" }, { targetType: "replay" }], now);
738
+ return true;
739
+ });
740
+ }
741
+ parkWorkflowRunForAmbiguousEffect(options) {
742
+ const now = epoch(validTimestamp(options.now));
743
+ return this.state.transaction(() => {
744
+ const row = this.workflowRunRow(options.runId);
745
+ if (row === undefined ||
746
+ !this.verifyWorkflowRunClaim({
747
+ runId: options.runId,
748
+ claimToken: options.claimToken,
749
+ now: new Date(now).toISOString(),
750
+ })) {
751
+ return false;
752
+ }
753
+ const lease = this.requireLease(row.resourceId);
754
+ const detail = "effect outcome is ambiguous; explicit recovery is required";
755
+ const errorHash = this.state.putText(detail, now);
756
+ this.state.connection
757
+ .prepare(`UPDATE node_attempts SET status = 'waiting', updated_at = ?
758
+ WHERE run_id = ? AND status IN ('pending', 'running')`)
759
+ .run(now, options.runId);
760
+ const run = this.state.connection
761
+ .prepare(`UPDATE runs SET status = 'waiting', status_detail = ?, updated_at = ?, finished_at = ?
762
+ WHERE run_id = ? AND status = 'running'`)
763
+ .run(detail, now, null, options.runId);
764
+ const queue = this.state.connection
765
+ .prepare(`UPDATE run_queue
766
+ SET status = 'parked', error_code = 'effectAmbiguous', error_hash = ?, updated_at = ?
767
+ WHERE run_id = ? AND status IN ('starting', 'running', 'parked')`)
768
+ .run(errorHash, now, options.runId);
769
+ /* istanbul ignore if -- exact live claim and run checks make both updates mandatory */
770
+ if (run.changes !== 1 || queue.changes !== 1) {
771
+ throw new Error(`Workflow run ${options.runId} has inconsistent ambiguous-effect state`);
772
+ }
773
+ const released = this.state.connection
774
+ .prepare(`UPDATE leases
775
+ SET owner_type = NULL, owner_id = NULL, token_hash = NULL,
776
+ acquired_at = NULL, heartbeat_at = NULL, expires_at = NULL
777
+ WHERE resource_id = ? AND token_hash = ? AND generation = ? AND expires_at > ?`)
778
+ .run(row.resourceId, tokenHash(options.claimToken), lease.generation, now);
779
+ /* istanbul ignore if -- the exact live claim is stable in this transaction */
780
+ if (released.changes !== 1) {
781
+ throw new Error(`Workflow run ${options.runId} claim changed during effect recovery`);
782
+ }
783
+ const revision = this.resourceRevision(row.resourceId);
784
+ this.bumpResource(row.resourceId, revision, now);
785
+ this.insertEvent(row.resourceId, revision + 1, "run.effect_ambiguous", lease.ownerType ?? "system", lease.ownerId, { status: "waiting", code: "effectAmbiguous" }, now, lease.generation || undefined);
786
+ recordViewerDeltas(this.state, options.runId, [{ targetType: "summary" }, { targetType: "replay" }], now);
787
+ return true;
788
+ });
789
+ }
790
+ failWorkflowRun(options) {
791
+ return this.terminalRun(options.runId, options.claimToken, "failed", options.errorCode, options.errorMessage, options.now);
792
+ }
793
+ cancelWorkflowRun(options) {
794
+ const cancelled = this.terminalRun(options.runId, options.claimToken, "cancelled", "cancelled", "Workflow run cancelled", options.now);
795
+ if (cancelled || options.claimToken !== undefined)
796
+ return cancelled;
797
+ return this.cancelStaleWorkflowRun({
798
+ runId: options.runId,
799
+ ...(options.now === undefined ? {} : { now: options.now }),
800
+ });
801
+ }
802
+ /** Cancel a nonterminal run only when its claim is absent or expired. */
803
+ cancelStaleWorkflowRun(options) {
804
+ const now = epoch(validTimestamp(options.now));
805
+ const controlId = options.controlId ?? "workflow-control";
806
+ const claimToken = options.claimToken ?? randomUUID();
807
+ return this.state.transaction(() => {
808
+ const row = this.workflowRunRow(options.runId);
809
+ if (row === undefined || ["done", "failed", "cancelled"].includes(row.status))
810
+ return false;
811
+ const lease = this.requireLease(row.resourceId);
812
+ if (lease.ownerId !== null && lease.expiresAt !== null && lease.expiresAt > now)
813
+ return false;
814
+ const generation = lease.generation + 1;
815
+ const claimed = this.state.connection
816
+ .prepare(`UPDATE leases
817
+ SET generation = ?, owner_type = 'system', owner_id = ?, token_hash = ?,
818
+ acquired_at = ?, heartbeat_at = ?, expires_at = ?
819
+ WHERE resource_id = ? AND generation = ?
820
+ AND (owner_id IS NULL OR expires_at IS NULL OR expires_at <= ?)`)
821
+ .run(generation, controlId, tokenHash(claimToken), now, now, now + 30_000, row.resourceId, lease.generation, now);
822
+ if (claimed.changes !== 1)
823
+ return false;
824
+ const errorHash = this.state.putText("Workflow run cancelled", now);
825
+ const queue = this.state.connection
826
+ .prepare(`UPDATE run_queue
827
+ SET status = 'cancelled', error_code = 'cancelled', error_hash = ?,
828
+ updated_at = ?, finished_at = ?
829
+ WHERE run_id = ? AND status NOT IN ('done', 'failed', 'cancelled')`)
830
+ .run(errorHash, now, now, options.runId);
831
+ /* istanbul ignore if -- the control claim selects one nonterminal queue row */
832
+ if (queue.changes !== 1) {
833
+ throw new Error(`Workflow run ${options.runId} has inconsistent queue state`);
834
+ }
835
+ const run = this.state.connection
836
+ .prepare(`UPDATE runs
837
+ SET status = 'cancelled', paused = 0, status_detail = NULL, error_hash = ?,
838
+ updated_at = ?, finished_at = ?
839
+ WHERE run_id = ? AND status NOT IN ('completed', 'failed', 'timed_out', 'cancelled')`)
840
+ .run(errorHash, now, now, options.runId);
841
+ /* istanbul ignore if -- the control claim selects one nonterminal durable run */
842
+ if (run.changes !== 1) {
843
+ throw new Error(`Workflow run ${options.runId} has inconsistent durable state`);
844
+ }
845
+ this.settleWorkflowRunMessages(options.runId, now);
846
+ this.cancelWorkflowRunDependents(options.runId, controlId, errorHash, now);
847
+ const released = this.state.connection
848
+ .prepare(`UPDATE leases
849
+ SET owner_type = NULL, owner_id = NULL, token_hash = NULL,
850
+ acquired_at = NULL, heartbeat_at = NULL, expires_at = NULL
851
+ WHERE resource_id = ? AND owner_type = 'system' AND owner_id = ?
852
+ AND token_hash = ? AND generation = ? AND expires_at > ?`)
853
+ .run(row.resourceId, controlId, tokenHash(claimToken), generation, now);
854
+ /* istanbul ignore if -- the exact control claim was written in this transaction */
855
+ if (released.changes !== 1) {
856
+ throw new Error(`Workflow run ${options.runId} control claim changed during cancellation`);
857
+ }
858
+ const revision = this.resourceRevision(row.resourceId);
859
+ this.bumpResource(row.resourceId, revision, now);
860
+ this.insertEvent(row.resourceId, revision + 1, "run.queue_cancelled", "control", controlId, { status: "cancelled", code: "cancelled", staleControl: true }, now, generation);
861
+ recordViewerDeltas(this.state, options.runId, [{ targetType: "summary" }, { targetType: "replay" }], now);
862
+ return true;
863
+ });
864
+ }
865
+ deleteWorkflowRun(options) {
866
+ const now = Date.now();
867
+ return this.state.transaction(() => {
868
+ const row = this.workflowRunRow(options.runId);
869
+ if (row === undefined)
870
+ return false;
871
+ const lease = this.requireLease(row.resourceId);
872
+ if (lease.ownerId === null ||
873
+ lease.tokenHash === null ||
874
+ lease.expiresAt === null ||
875
+ lease.expiresAt <= now ||
876
+ !lease.tokenHash.equals(tokenHash(options.claimToken))) {
877
+ return false;
878
+ }
879
+ return (this.state.connection
880
+ .prepare("DELETE FROM resources WHERE resource_id = ?")
881
+ .run(row.resourceId).changes === 1);
882
+ });
883
+ }
884
+ completeWorkflowRun(options) {
885
+ return this.releaseRunClaim(options.runId, options.claimToken, "done", options.now);
886
+ }
887
+ recordRunEvent(options) {
888
+ return this.state.transaction(() => {
889
+ const row = this.requireWorkflowRunRow(options.runId);
890
+ const now = epoch(validTimestamp(options.now));
891
+ const revision = this.resourceRevision(row.resourceId) + 1;
892
+ this.bumpResource(row.resourceId, revision - 1, now);
893
+ const eventId = this.insertEvent(row.resourceId, revision, options.type, options.runnerId?.startsWith("host-") ? "host" : "session", options.runnerId ?? null, options.payload ?? {}, now, row.leaseGeneration || undefined);
894
+ const seq = this.state.connection
895
+ .prepare("SELECT event_seq AS seq FROM events WHERE event_id = ?")
896
+ .get(eventId);
897
+ /* istanbul ignore if -- exact schema and internal query shape */
898
+ if (!isSequenceRow(seq))
899
+ throw new Error("Run event was not recorded");
900
+ return {
901
+ seq: seq.seq,
902
+ recordedAt: new Date(now).toISOString(),
903
+ runId: options.runId,
904
+ workflowRef: options.workflowRef,
905
+ type: options.type,
906
+ runnerId: options.runnerId ?? null,
907
+ payload: options.payload ?? {},
908
+ };
909
+ });
910
+ }
911
+ listRunEventsAfter(seq, options = {}) {
912
+ const rows = this.state.connection
913
+ .prepare(`SELECT e.event_seq AS seq, e.recorded_at AS recordedAt, r.run_id AS runId,
914
+ r.workflow_ref AS workflowRef, e.event_type AS eventType,
915
+ e.actor_id AS runnerId, e.payload_hash AS payloadHash
916
+ FROM events e JOIN runs r ON r.resource_id = e.resource_id
917
+ WHERE e.event_seq > ? ORDER BY e.event_seq LIMIT ?`)
918
+ .all(seq, options.limit ?? 100);
919
+ return rows.filter(isRunEventRow).map((row) => ({
920
+ seq: row.seq,
921
+ recordedAt: new Date(row.recordedAt).toISOString(),
922
+ runId: row.runId,
923
+ workflowRef: row.workflowRef,
924
+ type: row.eventType,
925
+ runnerId: row.runnerId,
926
+ payload: row.payloadHash === null ? {} : this.state.readJson(row.payloadHash),
927
+ }));
928
+ }
929
+ settleRunEffect(runId, effectType) {
930
+ const rows = this.state.connection
931
+ .prepare(`SELECT e.effect_id AS effectId, e.resource_id AS resourceId
932
+ FROM effects e JOIN runs r ON r.resource_id = e.source_resource_id
933
+ WHERE r.run_id = ? AND e.effect_type = ? AND e.status = 'pending'`)
934
+ .all(runId, effectType);
935
+ for (const row of rows) {
936
+ /* istanbul ignore if -- exact schema and internal query shape */
937
+ if (!isEffectIdentityRow(row))
938
+ continue;
939
+ this.state.transaction(() => {
940
+ const now = Date.now();
941
+ const revision = this.resourceRevision(row.resourceId);
942
+ this.state.connection
943
+ .prepare(`UPDATE effects SET status = 'applied', updated_at = ?, settled_at = ?
944
+ WHERE effect_id = ? AND status = 'pending'`)
945
+ .run(now, now, row.effectId);
946
+ this.bumpResource(row.resourceId, revision, now);
947
+ this.insertEvent(row.resourceId, revision + 1, "effect.applied", "system", null, { runId, effectType }, now);
948
+ });
949
+ }
950
+ }
951
+ workflowRunRow(runId) {
952
+ const row = this.state.connection.prepare(workflowRunSelect("WHERE r.run_id = ?")).get(runId);
953
+ return isRunRow(row) ? row : undefined;
954
+ }
955
+ requireWorkflowRunRow(runId) {
956
+ const row = this.workflowRunRow(runId);
957
+ if (row === undefined)
958
+ throw new Error(`Workflow run not found: ${runId}`);
959
+ return row;
960
+ }
961
+ requireWorkflowRun(runId) {
962
+ return this.mapWorkflowRun(this.requireWorkflowRunRow(runId));
963
+ }
964
+ assertWorkflowRunPreparationCompatible(row, options, definitionDigest) {
965
+ const expectedLineageKind = options.parentRunId === undefined ? null : (options.lineageKind ?? null);
966
+ const parent = options.parentRunId === undefined
967
+ ? undefined
968
+ : this.requireWorkflowRunRow(options.parentRunId);
969
+ const expectedRootRunId = parent?.rootRunId ?? options.runId;
970
+ const expectedRestartNumber = expectedLineageKind === "restart"
971
+ ? (options.restartNumber ?? (parent?.restartNumber ?? -1) + 1)
972
+ : (parent?.restartNumber ?? 0);
973
+ const expectedParentRunRevision = options.parentRunRevision ?? null;
974
+ const compatible = row.workflowName === options.workflowName &&
975
+ row.workflowRef === options.workflowSourceRef &&
976
+ row.definitionDigest.equals(definitionDigest) &&
977
+ canonicalJson(readQueuedRunSources(this.state, row)) ===
978
+ canonicalJson(queuedWorkflowSource(options.workflowSource)) &&
979
+ canonicalJson(this.state.readJson(row.inputHash)) === canonicalJson(options.input ?? null) &&
980
+ canonicalJson(this.state.readJson(row.launchOptionsHash)) ===
981
+ canonicalJson(options.launchOptions ?? {}) &&
982
+ row.originSessionId === options.originSessionId &&
983
+ row.executionMode === (options.executionMode ?? "interactive") &&
984
+ row.parentRunId === (options.parentRunId ?? null) &&
985
+ row.rootRunId === expectedRootRunId &&
986
+ row.lineageKind === expectedLineageKind &&
987
+ row.restartNumber === expectedRestartNumber &&
988
+ row.parentRunRevision === expectedParentRunRevision;
989
+ if (!compatible) {
990
+ throw new Error(`Workflow run preparation conflicts: ${options.runId}`);
991
+ }
992
+ }
993
+ workflowRunViewRows(clause, params) {
994
+ return this.state.connection
995
+ .prepare(workflowRunViewSelect(clause))
996
+ .all(...params)
997
+ .filter(isWorkflowRunViewRow);
998
+ }
999
+ /* istanbul ignore next -- pure projection covered by integration tests */
1000
+ mapWorkflowRun(row) {
1001
+ return {
1002
+ runId: row.runId,
1003
+ workflowName: row.workflowName,
1004
+ workflowSourceRef: row.workflowRef,
1005
+ workflowSource: readQueuedRunSources(this.state, row),
1006
+ initialized: row.runStatus !== "queued",
1007
+ definitionDigest: `sha256:${row.definitionDigest.toString("hex")}`,
1008
+ input: this.state.readJson(row.inputHash),
1009
+ launchOptions: this.state.readJson(row.launchOptionsHash),
1010
+ status: row.status,
1011
+ runnerId: row.ownerId,
1012
+ claimToken: null,
1013
+ claimGeneration: row.ownerId === null ? null : row.leaseGeneration,
1014
+ claimExpiresAt: row.claimExpiresAt === null ? null : new Date(row.claimExpiresAt).toISOString(),
1015
+ originSessionId: row.executionMode === "headless" ? null : row.originSessionId,
1016
+ executionMode: row.executionMode,
1017
+ parentRunId: row.parentRunId,
1018
+ rootRunId: row.rootRunId,
1019
+ lineageKind: row.lineageKind,
1020
+ restartNumber: row.restartNumber,
1021
+ parentRunRevision: row.parentRunRevision,
1022
+ errorCode: row.errorCode,
1023
+ errorMessage: row.errorHash === null
1024
+ ? null
1025
+ : (this.state.readBlob(row.errorHash)?.content.toString("utf8") ?? null),
1026
+ createdAt: new Date(row.createdAt).toISOString(),
1027
+ updatedAt: new Date(row.updatedAt).toISOString(),
1028
+ startedAt: row.startedAt === null ? null : new Date(row.startedAt).toISOString(),
1029
+ finishedAt: row.finishedAt === null ? null : new Date(row.finishedAt).toISOString(),
1030
+ };
1031
+ }
1032
+ claimRun(runId, runnerId, claimToken, leaseMs, now, options = {}) {
1033
+ return this.state.transaction(() => this.claimRunInTransaction(runId, runnerId, claimToken, leaseMs, now, options));
1034
+ }
1035
+ claimRunInTransaction(runId, runnerId, claimToken, leaseMs, now, options = {}) {
1036
+ const row = this.workflowRunRow(runId);
1037
+ if (row === undefined || ["done", "failed", "cancelled"].includes(row.status))
1038
+ return undefined;
1039
+ if (options.allowPendingInteraction !== true &&
1040
+ this.state.connection
1041
+ .prepare(`SELECT 1 FROM interactive_requests
1042
+ WHERE run_id = ? AND status = 'pending' LIMIT 1`)
1043
+ .get(runId) !== undefined) {
1044
+ return undefined;
1045
+ }
1046
+ const lease = this.requireLease(row.resourceId);
1047
+ if (lease.ownerId !== null &&
1048
+ lease.expiresAt !== null &&
1049
+ lease.expiresAt > now &&
1050
+ lease.ownerId !== runnerId)
1051
+ return undefined;
1052
+ const generation = lease.generation + 1;
1053
+ const expiresAt = now + leaseMs;
1054
+ const result = this.state.connection
1055
+ .prepare(`UPDATE leases SET generation = ?, owner_type = ?, owner_id = ?, token_hash = ?,
1056
+ acquired_at = ?, heartbeat_at = ?, expires_at = ?
1057
+ WHERE resource_id = ? AND generation = ?`)
1058
+ .run(generation, runnerId.startsWith("host-") ? "host" : "session", runnerId, tokenHash(claimToken), now, now, expiresAt, row.resourceId, lease.generation);
1059
+ /* istanbul ignore if -- impossible after exact schema and transaction checks */
1060
+ if (result.changes !== 1)
1061
+ return undefined;
1062
+ if (options.preserveQueueStatus !== true) {
1063
+ this.state.connection
1064
+ .prepare(`UPDATE run_queue
1065
+ SET status = 'starting', error_code = NULL, error_hash = NULL, updated_at = ?
1066
+ WHERE run_id = ?`)
1067
+ .run(now, runId);
1068
+ }
1069
+ const revision = this.resourceRevision(row.resourceId);
1070
+ this.bumpResource(row.resourceId, revision, now);
1071
+ this.insertEvent(row.resourceId, revision + 1, "lease.claimed", runnerId.startsWith("host-") ? "host" : "session", runnerId, { expiresAt }, now, generation);
1072
+ return { ...this.requireWorkflowRun(runId), claimToken };
1073
+ }
1074
+ updateClaimedRunStatus(runId, claimToken, status, nowValue) {
1075
+ const now = epoch(validTimestamp(nowValue));
1076
+ return this.state.transaction(() => {
1077
+ if (!this.verifyWorkflowRunClaim({
1078
+ runId,
1079
+ claimToken,
1080
+ now: new Date(now).toISOString(),
1081
+ })) {
1082
+ return false;
1083
+ }
1084
+ const row = this.requireWorkflowRunRow(runId);
1085
+ const changed = this.state.connection
1086
+ .prepare("UPDATE run_queue SET status = ?, started_at = COALESCE(started_at, ?), updated_at = ? WHERE run_id = ?")
1087
+ .run(status, now, now, runId).changes === 1;
1088
+ /* istanbul ignore if -- impossible after exact schema and transaction checks */
1089
+ if (!changed)
1090
+ return false;
1091
+ const revision = this.resourceRevision(row.resourceId);
1092
+ const lease = this.requireLease(row.resourceId);
1093
+ this.bumpResource(row.resourceId, revision, now);
1094
+ this.insertEvent(row.resourceId, revision + 1, `run.queue_${status}`, lease.ownerType ?? "system", lease.ownerId, { status }, now, lease.generation || undefined);
1095
+ return true;
1096
+ });
1097
+ }
1098
+ releaseRunClaim(runId, claimToken, status, nowValue) {
1099
+ const now = epoch(validTimestamp(nowValue));
1100
+ return this.state.transaction(() => {
1101
+ const row = this.workflowRunRow(runId);
1102
+ if (row === undefined ||
1103
+ !this.verifyWorkflowRunClaim({ runId, claimToken, now: new Date(now).toISOString() }))
1104
+ return false;
1105
+ this.state.connection
1106
+ .prepare("UPDATE run_queue SET status = ?, updated_at = ?, finished_at = ? WHERE run_id = ?")
1107
+ .run(status, now, status === "done" ? now : null, runId);
1108
+ const lease = this.requireLease(row.resourceId);
1109
+ const update = this.state.connection
1110
+ .prepare(`UPDATE leases SET owner_type = NULL, owner_id = NULL, token_hash = NULL,
1111
+ acquired_at = NULL, heartbeat_at = NULL, expires_at = NULL
1112
+ WHERE resource_id = ? AND token_hash = ? AND generation = ?`)
1113
+ .run(row.resourceId, tokenHash(claimToken), lease.generation);
1114
+ /* istanbul ignore if -- impossible after exact schema and transaction checks */
1115
+ if (update.changes !== 1)
1116
+ return false;
1117
+ const revision = this.resourceRevision(row.resourceId);
1118
+ this.bumpResource(row.resourceId, revision, now);
1119
+ this.insertEvent(row.resourceId, revision + 1, `run.queue_${status}`, lease.ownerType ?? "system", lease.ownerId, { status }, now, lease.generation || undefined);
1120
+ this.settleRunEffect(runId, status === "parked" ? "run.park_queue" : "run.settle_queue");
1121
+ recordViewerDeltas(this.state, runId, [{ targetType: "summary" }, { targetType: "replay" }], now);
1122
+ return true;
1123
+ });
1124
+ }
1125
+ terminalRun(runId, claimToken, status, code, error, nowValue) {
1126
+ const now = epoch(validTimestamp(nowValue));
1127
+ return this.state.transaction(() => {
1128
+ const row = this.workflowRunRow(runId);
1129
+ if (row === undefined || ["done", "failed", "cancelled"].includes(row.status))
1130
+ return false;
1131
+ const lease = this.requireLease(row.resourceId);
1132
+ if (claimToken === undefined) {
1133
+ if (!["queued", "starting"].includes(row.status)) {
1134
+ return false;
1135
+ }
1136
+ if (lease.ownerId !== null)
1137
+ return false;
1138
+ }
1139
+ else if (lease.ownerId === null ||
1140
+ lease.tokenHash === null ||
1141
+ lease.expiresAt === null ||
1142
+ lease.expiresAt <= now ||
1143
+ !lease.tokenHash.equals(tokenHash(claimToken))) {
1144
+ return false;
1145
+ }
1146
+ const revision = this.resourceRevision(row.resourceId);
1147
+ const errorHash = this.state.putText(error, now);
1148
+ const queueUpdate = this.state.connection
1149
+ .prepare(`UPDATE run_queue
1150
+ SET status = ?, error_code = ?, error_hash = ?, updated_at = ?, finished_at = ?
1151
+ WHERE run_id = ? AND status NOT IN ('done', 'failed', 'cancelled')`)
1152
+ .run(status, code, errorHash, now, now, runId);
1153
+ if (queueUpdate.changes !== 1)
1154
+ return false;
1155
+ if (claimToken !== undefined) {
1156
+ const leaseUpdate = this.state.connection
1157
+ .prepare(`UPDATE leases
1158
+ SET owner_type = NULL, owner_id = NULL, token_hash = NULL,
1159
+ acquired_at = NULL, heartbeat_at = NULL, expires_at = NULL
1160
+ WHERE resource_id = ? AND token_hash = ? AND generation = ? AND expires_at > ?`)
1161
+ .run(row.resourceId, tokenHash(claimToken), lease.generation, now);
1162
+ if (leaseUpdate.changes !== 1) {
1163
+ throw new Error(`Workflow run ${runId} claim changed during terminal transition`);
1164
+ }
1165
+ }
1166
+ this.state.connection
1167
+ .prepare(`UPDATE runs
1168
+ SET status = ?, paused = 0, status_detail = NULL, error_hash = ?,
1169
+ updated_at = ?, finished_at = ?
1170
+ WHERE run_id = ?`)
1171
+ .run(status, errorHash, now, now, runId);
1172
+ this.settleWorkflowRunMessages(runId, now);
1173
+ if (status === "cancelled") {
1174
+ this.cancelWorkflowRunDependents(runId, lease.ownerId ?? "workflow-control", errorHash, now);
1175
+ }
1176
+ this.bumpResource(row.resourceId, revision, now);
1177
+ this.insertEvent(row.resourceId, revision + 1, `run.queue_${status}`, lease.ownerType ?? "system", lease.ownerId, { status, code, error }, now, lease.generation || undefined);
1178
+ recordViewerDeltas(this.state, runId, [{ targetType: "summary" }, { targetType: "replay" }], now);
1179
+ return true;
1180
+ });
1181
+ }
1182
+ settleWorkflowRunMessages(runId, now) {
1183
+ this.workflowMessages.settleOpenTurnsForRun(runId, "lost", now);
1184
+ this.workflowMessages.cancelPendingForRun(runId, now);
1185
+ }
1186
+ cancelWorkflowRunDependents(runId, actorId, errorHash, now) {
1187
+ closeRunTime(this.state, runId);
1188
+ this.state.connection
1189
+ .prepare(`UPDATE node_attempts
1190
+ SET status = 'cancelled', error_hash = COALESCE(error_hash, ?),
1191
+ updated_at = ?, finished_at = COALESCE(finished_at, ?)
1192
+ WHERE run_id = ? AND status IN ('pending', 'running', 'waiting', 'interrupted')`)
1193
+ .run(errorHash, now, now, runId);
1194
+ const effects = this.state.connection
1195
+ .prepare(`SELECT e.effect_id AS effectId, e.resource_id AS resourceId,
1196
+ e.status, e.attempt_count AS attemptCount
1197
+ FROM effects e JOIN runs r ON r.resource_id = e.source_resource_id
1198
+ WHERE r.run_id = ? AND e.owner_scope = 'run' AND e.status IN ('pending', 'applying')
1199
+ ORDER BY e.effect_id`)
1200
+ .all(runId)
1201
+ .filter(isCancelledRunEffectRow);
1202
+ for (const effect of effects) {
1203
+ const status = effect.status === "applying" ? "ambiguous" : "cancelled";
1204
+ const revision = this.resourceRevision(effect.resourceId);
1205
+ const changed = this.state.connection
1206
+ .prepare(`UPDATE effects
1207
+ SET status = ?, next_attempt_at = NULL, error_hash = ?, updated_at = ?, settled_at = ?
1208
+ WHERE effect_id = ? AND status = ? AND attempt_count = ?`)
1209
+ .run(status, errorHash, now, now, effect.effectId, effect.status, effect.attemptCount);
1210
+ /* istanbul ignore if -- cancellation serializes the selected effect transition */
1211
+ if (changed.changes !== 1) {
1212
+ throw new Error(`Workflow effect ${effect.effectId} changed during cancellation`);
1213
+ }
1214
+ if (effect.status === "applying") {
1215
+ this.state.connection
1216
+ .prepare(`UPDATE effect_attempts
1217
+ SET finished_at = ?, outcome = 'interrupted', error_hash = ?
1218
+ WHERE effect_id = ? AND attempt_number = ? AND finished_at IS NULL`)
1219
+ .run(now, errorHash, effect.effectId, effect.attemptCount);
1220
+ }
1221
+ this.bumpResource(effect.resourceId, revision, now);
1222
+ this.insertEvent(effect.resourceId, revision + 1, `effect.${status}`, "control", actorId, { runId, reason: "workflowCancelled" }, now);
1223
+ }
1224
+ this.state.connection
1225
+ .prepare(`INSERT INTO human_decision_resolutions(
1226
+ decision_id, outcome, provenance, response_hash, reason, channel,
1227
+ actor_id, request_digest, resolved_at
1228
+ )
1229
+ SELECT d.decision_id, 'cancelled', 'explicit_cancel', NULL,
1230
+ 'Workflow run cancelled', NULL, ?, d.request_digest, ?
1231
+ FROM human_decisions d
1232
+ LEFT JOIN human_decision_resolutions r ON r.decision_id = d.decision_id
1233
+ WHERE d.run_id = ? AND r.decision_id IS NULL`)
1234
+ .run(actorId, now, runId);
1235
+ const receiptHash = this.state.putJson({ status: "rejected", error: "Workflow run cancelled" }, now);
1236
+ this.state.connection
1237
+ .prepare(`UPDATE interactive_submissions SET outcome = 'rejected', receipt_hash = ?
1238
+ WHERE outcome = 'validating'
1239
+ AND request_id IN (SELECT request_id FROM interactive_requests WHERE run_id = ?)`)
1240
+ .run(receiptHash, runId);
1241
+ this.state.connection
1242
+ .prepare(`UPDATE interactive_requests
1243
+ SET status = 'cancelled', revision = revision + 1, updated_at = ?
1244
+ WHERE run_id = ? AND status = 'pending'`)
1245
+ .run(now, runId);
1246
+ }
1247
+ }
1248
+ //# sourceMappingURL=queue.js.map