@proofoftech/flowsafe 0.23.0 → 0.24.0

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 (109) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +57 -7
  3. package/dist/agent-host/thread-host.d.ts.map +1 -1
  4. package/dist/agent-host/thread-host.js +6 -0
  5. package/dist/agent-host/thread-host.js.map +1 -1
  6. package/dist/agent-runner/durable-agent-runner.d.ts +11 -17
  7. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  8. package/dist/agent-runner/durable-agent-runner.js +488 -368
  9. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  10. package/dist/approval-ui/use-approval-dashboard.js +6 -6
  11. package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
  12. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  13. package/dist/background-tasks/d1-storage.js +2 -3
  14. package/dist/background-tasks/d1-storage.js.map +1 -1
  15. package/dist/background-tasks/host.d.ts.map +1 -1
  16. package/dist/background-tasks/host.js +27 -38
  17. package/dist/background-tasks/host.js.map +1 -1
  18. package/dist/do-runner/cause-chain.d.ts +5 -0
  19. package/dist/do-runner/cause-chain.d.ts.map +1 -1
  20. package/dist/do-runner/cause-chain.js +12 -0
  21. package/dist/do-runner/cause-chain.js.map +1 -1
  22. package/dist/do-runner/cf-types.d.ts +3 -0
  23. package/dist/do-runner/cf-types.d.ts.map +1 -1
  24. package/dist/do-runner/cf-types.js.map +1 -1
  25. package/dist/do-runner/constants.d.ts +1 -1
  26. package/dist/do-runner/constants.d.ts.map +1 -1
  27. package/dist/do-runner/constants.js +1 -1
  28. package/dist/do-runner/constants.js.map +1 -1
  29. package/dist/do-runner/core-events-nonce.d.ts +2 -0
  30. package/dist/do-runner/core-events-nonce.d.ts.map +1 -0
  31. package/dist/do-runner/core-events-nonce.js +16 -0
  32. package/dist/do-runner/core-events-nonce.js.map +1 -0
  33. package/dist/do-runner/d1-storage.js +1 -9
  34. package/dist/do-runner/d1-storage.js.map +1 -1
  35. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  36. package/dist/do-runner/do-error-response.js +2 -1
  37. package/dist/do-runner/do-error-response.js.map +1 -1
  38. package/dist/do-runner/durable-object.d.ts +17 -2
  39. package/dist/do-runner/durable-object.d.ts.map +1 -1
  40. package/dist/do-runner/durable-object.js +441 -54
  41. package/dist/do-runner/durable-object.js.map +1 -1
  42. package/dist/do-runner/fenced-workflow-capability.d.ts +24 -0
  43. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  44. package/dist/do-runner/fenced-workflows-d1.d.ts +5 -1
  45. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  46. package/dist/do-runner/fenced-workflows-d1.js +149 -48
  47. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  48. package/dist/do-runner/index.d.ts +2 -2
  49. package/dist/do-runner/index.d.ts.map +1 -1
  50. package/dist/do-runner/index.js +2 -2
  51. package/dist/do-runner/index.js.map +1 -1
  52. package/dist/do-runner/init.d.ts +2 -3
  53. package/dist/do-runner/init.d.ts.map +1 -1
  54. package/dist/do-runner/init.js.map +1 -1
  55. package/dist/do-runner/memory-id.js +1 -1
  56. package/dist/do-runner/memory-id.js.map +1 -1
  57. package/dist/do-runner/pubsub.d.ts +6 -2
  58. package/dist/do-runner/pubsub.d.ts.map +1 -1
  59. package/dist/do-runner/pubsub.js +12 -22
  60. package/dist/do-runner/pubsub.js.map +1 -1
  61. package/dist/do-runner/run-lifecycle.d.ts +42 -2
  62. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  63. package/dist/do-runner/run-lifecycle.js +57 -1
  64. package/dist/do-runner/run-lifecycle.js.map +1 -1
  65. package/dist/do-runner/run-terminal-state.d.ts +2 -0
  66. package/dist/do-runner/run-terminal-state.d.ts.map +1 -1
  67. package/dist/do-runner/run-terminal-state.js +4 -0
  68. package/dist/do-runner/run-terminal-state.js.map +1 -1
  69. package/dist/do-runner/runtime.d.ts +72 -15
  70. package/dist/do-runner/runtime.d.ts.map +1 -1
  71. package/dist/do-runner/runtime.js +292 -125
  72. package/dist/do-runner/runtime.js.map +1 -1
  73. package/dist/do-runner/suspension-deadline.d.ts +25 -17
  74. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  75. package/dist/do-runner/suspension-deadline.js +44 -21
  76. package/dist/do-runner/suspension-deadline.js.map +1 -1
  77. package/dist/do-runner/workflow-snapshot-row.d.ts +7 -0
  78. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  79. package/dist/do-runner/workflow-snapshot-row.js +21 -0
  80. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  81. package/dist/host-kit/approval-bridge.d.ts +11 -8
  82. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  83. package/dist/host-kit/approval-bridge.js +15 -9
  84. package/dist/host-kit/approval-bridge.js.map +1 -1
  85. package/dist/host-kit/do-response.d.ts.map +1 -1
  86. package/dist/host-kit/do-response.js +7 -1
  87. package/dist/host-kit/do-response.js.map +1 -1
  88. package/dist/host-kit/flowsafe-worker.d.ts +2 -1
  89. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  90. package/dist/host-kit/flowsafe-worker.js +4 -2
  91. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  92. package/dist/host-kit/run-router.d.ts.map +1 -1
  93. package/dist/host-kit/run-router.js +3 -2
  94. package/dist/host-kit/run-router.js.map +1 -1
  95. package/dist/schedules/schedules-d1.d.ts +1 -0
  96. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  97. package/dist/schedules/schedules-d1.js +35 -22
  98. package/dist/schedules/schedules-d1.js.map +1 -1
  99. package/dist/schedules/tick.d.ts +17 -2
  100. package/dist/schedules/tick.d.ts.map +1 -1
  101. package/dist/schedules/tick.js +63 -44
  102. package/dist/schedules/tick.js.map +1 -1
  103. package/dist/signals/d1-shared.js +1 -1
  104. package/dist/signals/d1-shared.js.map +1 -1
  105. package/dist/signals/thread-do-routes.d.ts +8 -1
  106. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  107. package/dist/signals/thread-do-routes.js +40 -44
  108. package/dist/signals/thread-do-routes.js.map +1 -1
  109. package/package.json +10 -7
@@ -30,12 +30,12 @@ import { FENCED_WORKFLOW_STORAGE, } from './fenced-workflow-capability.js';
30
30
  import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
31
31
  import { mastraRegistryEntries } from './mastra-registry.js';
32
32
  import { isPathSafeId } from './path-safe-id.js';
33
- import { canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext, nextLifecycleRevision, projectTerminalLifecycle, RUN_LIFECYCLE_CONTEXT_KEY, RunLifecycleBlockedError, terminalCleanupFor, } from './run-lifecycle.js';
33
+ import { advanceLifecycle, canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext, projectTerminalLifecycle, RUN_INTERRUPTED_MESSAGE, RUN_LIFECYCLE_CONTEXT_KEY, RunLifecycleBlockedError, terminalCleanupFor, } from './run-lifecycle.js';
34
34
  import { decodeProgressRunProvenance, decodeResumeCounts, nextResumeCount, runExecutionIdentityFor, } from './run-provenance.js';
35
- import { errorText, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
35
+ import { errorText, isDurableRunStatus, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
36
36
  import { captureReservation, } from './start-reservation-contract.js';
37
37
  import { validateTablePrefix } from './table-prefix.js';
38
- export { RunLifecycleBlockedError, } from './run-lifecycle.js';
38
+ export { RunLifecycleBlockedError, RunSettledConflictError, } from './run-lifecycle.js';
39
39
  export class UnknownWorkflowError extends Error {
40
40
  constructor(workflowId) {
41
41
  super(`unknown workflow '${workflowId}'`);
@@ -282,8 +282,14 @@ function summarizeState(runId, state, counts, requestedBy, requestedByKind) {
282
282
  if (state.status === 'success') {
283
283
  summary.result = state.result;
284
284
  }
285
- else if (state.status === 'failed' && state.error) {
286
- summary.error = errorText(state.error);
285
+ else if (state.status === 'failed') {
286
+ if (state.error)
287
+ summary.error = errorText(state.error);
288
+ if (lifecycle?.interruptedAt !== undefined)
289
+ summary.errorEnvelope = {
290
+ code: 'INTERRUPTED',
291
+ message: RUN_INTERRUPTED_MESSAGE,
292
+ };
287
293
  }
288
294
  else if (state.status === 'suspended') {
289
295
  const suspendedKeys = Object.keys(state.suspendedPaths ?? {});
@@ -363,6 +369,22 @@ function orderedRequestContext(runtimeContext, provided, scheduled) {
363
369
  ...identity,
364
370
  ]);
365
371
  }
372
+ /** @internal How often an executing leg marks its run row live. */
373
+ export const RUN_LEG_TOUCH_MS = 30_000;
374
+ // Longer than the largest Workers CPU limit (five minutes), which is the most
375
+ // a busy step can delay a touch timer: a row untouched this long has no leg
376
+ // left marking it, on this instance or one being replaced.
377
+ const RUN_LEG_SILENT_MS = 360_000;
378
+ /** Has no leg marked this row live within RUN_LEG_SILENT_MS? */
379
+ function rowSilent(raw, now) {
380
+ const touchedAt = Date.parse(raw.updatedAt);
381
+ if (!Number.isFinite(touchedAt))
382
+ throw new RunStateUnreadableError(raw.workflowId, raw.runId);
383
+ return now - touchedAt >= RUN_LEG_SILENT_MS;
384
+ }
385
+ /** A settlement compare-and-set found its row changed since the silence read. */
386
+ class SettlementMissError extends Error {
387
+ }
366
388
  const TERMINABLE_RUN_STATUSES = new Set([
367
389
  'running',
368
390
  'waiting',
@@ -578,8 +600,8 @@ export class RunnerRuntime {
578
600
  #activeRuns = new Map();
579
601
  #terminalAbortIntents = new Map();
580
602
  #lifecycleLocks = new Map();
581
- // The host DO's pubsub identity (RunnerRuntimeOptions.pubsub), threaded into
582
- // createRun so a configured host publishes and replays on ONE shared feed.
603
+ // The host DO's pubsub identity (RunnerRuntimeOptions.pubsub) is passed to
604
+ // Mastra and each createRun so a configured host shares one feed.
583
605
  // Undefined ⇒ core defaults a fresh emitter per run.
584
606
  #pubsub;
585
607
  #executionFence;
@@ -1085,9 +1107,7 @@ export class RunnerRuntime {
1085
1107
  return undefined;
1086
1108
  }
1087
1109
  const principals = canonicalReplayPrincipals(replayPrincipals);
1088
- const intent = {
1089
- ...(lifecycle ?? { version: 1, revision: 0 }),
1090
- revision: nextLifecycleRevision(lifecycle?.revision ?? 0),
1110
+ const intent = advanceLifecycle(lifecycle, {
1091
1111
  transitionIntent: {
1092
1112
  status: intendedStatus,
1093
1113
  requestedAt: now,
@@ -1099,7 +1119,7 @@ export class RunnerRuntime {
1099
1119
  }
1100
1120
  : {}),
1101
1121
  },
1102
- };
1122
+ });
1103
1123
  await this.#persistLifecycle(workflowId, runId, state, intent, now, source);
1104
1124
  if (active) {
1105
1125
  active.lifecycle = intent;
@@ -1144,98 +1164,108 @@ export class RunnerRuntime {
1144
1164
  }
1145
1165
  async #transitionTerminal(workflowId, runId, status, now, cas, replayPrincipals, replayingPrincipal) {
1146
1166
  this.#getWorkflow(workflowId);
1147
- return this.#withRunLock(workflowId, runId, async () => {
1148
- const source = await this.#captureWorkflowStorage(workflowId);
1149
- const state = await source.load.call(source.workflows, {
1150
- workflowName: workflowId,
1151
- runId,
1152
- });
1153
- if (!state)
1167
+ return this.#withRunLock(workflowId, runId, () => this.#transitionTerminalLocked(workflowId, runId, status, now, {
1168
+ cas,
1169
+ replayPrincipals,
1170
+ replayingPrincipal,
1171
+ }));
1172
+ }
1173
+ /**
1174
+ * #transitionTerminal's body, for a caller already holding the run lock.
1175
+ * With `expected`, the write is a compare-and-set against that exact row and
1176
+ * a miss throws SettlementMissError.
1177
+ */
1178
+ async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal, expected, } = {}) {
1179
+ const source = await this.#captureWorkflowStorage(workflowId);
1180
+ const state = await source.load.call(source.workflows, {
1181
+ workflowName: workflowId,
1182
+ runId,
1183
+ });
1184
+ if (!state)
1185
+ throw new UnknownRunError(workflowId, runId);
1186
+ if (state.runId !== runId)
1187
+ throw new RunStateUnreadableError(workflowId, runId);
1188
+ const lifecycle = lifecycleFromRequestContext(state.requestContext);
1189
+ if (lifecycle?.terminal) {
1190
+ if (replayingPrincipal &&
1191
+ !lifecycle.terminal.replayPrincipals.some((principal) => principal.kind === replayingPrincipal.kind &&
1192
+ principal.id === replayingPrincipal.id)) {
1154
1193
  throw new UnknownRunError(workflowId, runId);
1155
- if (state.runId !== runId)
1156
- throw new RunStateUnreadableError(workflowId, runId);
1157
- const lifecycle = lifecycleFromRequestContext(state.requestContext);
1158
- if (lifecycle?.terminal) {
1159
- if (replayingPrincipal &&
1160
- !lifecycle.terminal.replayPrincipals.some((principal) => principal.kind === replayingPrincipal.kind &&
1161
- principal.id === replayingPrincipal.id)) {
1162
- throw new UnknownRunError(workflowId, runId);
1163
- }
1164
- return {
1165
- summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
1166
- transitioned: false,
1167
- casMatched: cas === undefined ||
1168
- (lifecycle.terminal.status === 'timed_out' &&
1169
- lifecycle.deadlineAt === cas.expectedDeadlineAt),
1170
- cleanup: terminalCleanupFor(lifecycle),
1171
- };
1172
1194
  }
1173
- const transitionIntent = lifecycle?.transitionIntent;
1174
- const intentMatchesTransition = transitionIntent?.status === status &&
1175
- (cas === undefined ||
1176
- (transitionIntent.expectedRevision === cas.expectedRevision &&
1177
- transitionIntent.expectedDeadlineAt === cas.expectedDeadlineAt));
1178
- const intentMatchesCas = cas !== undefined && intentMatchesTransition;
1179
- if (cas !== undefined &&
1180
- !intentMatchesCas &&
1181
- (lifecycle?.revision !== cas.expectedRevision ||
1182
- lifecycle.deadlineAt !== cas.expectedDeadlineAt ||
1183
- lifecycle.deadlineAt === undefined ||
1184
- lifecycle.deadlineAt > now)) {
1185
- return {
1186
- summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
1187
- transitioned: false,
1188
- casMatched: false,
1189
- cleanup: {
1190
- revision: lifecycle?.revision ?? 0,
1191
- status,
1192
- cleanupCompleted: false,
1193
- ...(lifecycle?.scheduleDispatch
1194
- ? { scheduleDispatch: lifecycle.scheduleDispatch }
1195
- : {}),
1196
- },
1197
- };
1198
- }
1199
- if (hasDisputedSettlement(lifecycle)) {
1200
- throw new RunLifecycleBlockedError({
1201
- code: 'DISPUTED_SETTLEMENT',
1202
- message: 'run termination is blocked while an economic operation is disputed',
1203
- });
1204
- }
1205
- const currentStatus = state.status;
1206
- const abortIntent = this.#terminalAbortIntents.get(this.#runKey(workflowId, runId));
1207
- if (!TERMINABLE_RUN_STATUSES.has(currentStatus) &&
1208
- !intentMatchesTransition &&
1209
- !(currentStatus === 'canceled' && abortIntent === status)) {
1210
- throw new RunTerminalConflictError(workflowId, runId, currentStatus);
1211
- }
1212
- const provenance = runProvenance(state);
1213
- const fallbackPrincipal = provenance?.requestedBy && provenance.requestedByKind
1214
- ? {
1215
- kind: provenance.requestedByKind,
1216
- id: provenance.requestedBy,
1217
- }
1218
- : { kind: 'system', id: 'flowsafe-system' };
1219
- const principals = canonicalReplayPrincipals(replayPrincipals ??
1220
- transitionIntent?.replayPrincipals ?? [fallbackPrincipal]);
1221
- const next = projectTerminalLifecycle(lifecycle, status, now, principals);
1222
- await this.#persistLifecycle(workflowId, runId, {
1223
- ...state,
1224
- ...terminalStateFields(status),
1225
- error: {
1226
- name: status === 'cancelled' ? 'RunCancelledError' : 'RunTimedOutError',
1227
- message: next.terminal.error.message,
1228
- },
1229
- timestamp: now,
1230
- }, next, now, source);
1231
- this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
1232
1195
  return {
1233
1196
  summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
1234
- transitioned: true,
1235
- casMatched: true,
1236
- cleanup: terminalCleanupFor(next),
1197
+ transitioned: false,
1198
+ casMatched: cas === undefined ||
1199
+ (lifecycle.terminal.status === 'timed_out' &&
1200
+ lifecycle.deadlineAt === cas.expectedDeadlineAt),
1201
+ cleanup: terminalCleanupFor(lifecycle),
1237
1202
  };
1238
- });
1203
+ }
1204
+ const transitionIntent = lifecycle?.transitionIntent;
1205
+ const intentMatchesTransition = transitionIntent?.status === status &&
1206
+ (cas === undefined ||
1207
+ (transitionIntent.expectedRevision === cas.expectedRevision &&
1208
+ transitionIntent.expectedDeadlineAt === cas.expectedDeadlineAt));
1209
+ const intentMatchesCas = cas !== undefined && intentMatchesTransition;
1210
+ if (cas !== undefined &&
1211
+ !intentMatchesCas &&
1212
+ (lifecycle?.revision !== cas.expectedRevision ||
1213
+ lifecycle.deadlineAt !== cas.expectedDeadlineAt ||
1214
+ lifecycle.deadlineAt === undefined ||
1215
+ lifecycle.deadlineAt > now)) {
1216
+ return {
1217
+ summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
1218
+ transitioned: false,
1219
+ casMatched: false,
1220
+ cleanup: {
1221
+ revision: lifecycle?.revision ?? 0,
1222
+ status,
1223
+ cleanupCompleted: false,
1224
+ ...(lifecycle?.scheduleDispatch
1225
+ ? { scheduleDispatch: lifecycle.scheduleDispatch }
1226
+ : {}),
1227
+ },
1228
+ };
1229
+ }
1230
+ if (hasDisputedSettlement(lifecycle)) {
1231
+ throw new RunLifecycleBlockedError({
1232
+ code: 'DISPUTED_SETTLEMENT',
1233
+ message: 'run termination is blocked while an economic operation is disputed',
1234
+ });
1235
+ }
1236
+ const currentStatus = state.status;
1237
+ const abortIntent = this.#terminalAbortIntents.get(this.#runKey(workflowId, runId));
1238
+ if (!TERMINABLE_RUN_STATUSES.has(currentStatus) &&
1239
+ !intentMatchesTransition &&
1240
+ !(currentStatus === 'canceled' && abortIntent === status)) {
1241
+ throw new RunTerminalConflictError(workflowId, runId, currentStatus);
1242
+ }
1243
+ const provenance = runProvenance(state);
1244
+ const fallbackPrincipal = provenance?.requestedBy && provenance.requestedByKind
1245
+ ? {
1246
+ kind: provenance.requestedByKind,
1247
+ id: provenance.requestedBy,
1248
+ }
1249
+ : { kind: 'system', id: 'flowsafe-system' };
1250
+ const principals = canonicalReplayPrincipals(replayPrincipals ??
1251
+ transitionIntent?.replayPrincipals ?? [fallbackPrincipal]);
1252
+ const next = projectTerminalLifecycle(lifecycle, status, now, principals);
1253
+ await this.#persistLifecycle(workflowId, runId, {
1254
+ ...state,
1255
+ ...terminalStateFields(status),
1256
+ error: {
1257
+ name: status === 'cancelled' ? 'RunCancelledError' : 'RunTimedOutError',
1258
+ message: next.terminal.error.message,
1259
+ },
1260
+ timestamp: now,
1261
+ }, next, now, source, expected);
1262
+ this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
1263
+ return {
1264
+ summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
1265
+ transitioned: true,
1266
+ casMatched: true,
1267
+ cleanup: terminalCleanupFor(next),
1268
+ };
1239
1269
  }
1240
1270
  /** Marks idempotent terminal side-effect cleanup after every hook succeeds. */
1241
1271
  async completeTerminalCleanup(workflowId, runId, expectedRevision, now = Date.now()) {
@@ -1260,14 +1290,9 @@ export class RunnerRuntime {
1260
1290
  if (lifecycle.revision !== expectedRevision) {
1261
1291
  throw new Error('run terminal cleanup CAS no longer matches');
1262
1292
  }
1263
- const next = {
1264
- ...lifecycle,
1265
- revision: nextLifecycleRevision(lifecycle.revision),
1266
- terminal: {
1267
- ...lifecycle.terminal,
1268
- cleanupCompletedAt: now,
1269
- },
1270
- };
1293
+ const next = advanceLifecycle(lifecycle, {
1294
+ terminal: { ...lifecycle.terminal, cleanupCompletedAt: now },
1295
+ });
1271
1296
  await this.#persistLifecycle(workflowId, runId, state, next, now, source);
1272
1297
  return this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state));
1273
1298
  });
@@ -1292,16 +1317,11 @@ export class RunnerRuntime {
1292
1317
  * status() for a caller about to CONCLUDE something irreversible from what it
1293
1318
  * reads — delete a wake record, spend an abandonment budget, resume a run.
1294
1319
  *
1295
- * Mastra answers a state read from an in-memory Run whenever storage is
1296
- * unavailable or the row lookup comes back empty while this isolate still
1297
- * holds the run, and that fallback reports the Run object's own status
1298
- * ('pending' until something updates it) with no suspended paths and no
1299
- * requestContext at all. Projecting it is indistinguishable from evidence
1300
- * about the run. Mastra stamps `isFromInMemory` on it at its single
1301
- * construction site and the persisted branch builds its result field by
1302
- * field without ever copying the marker, so this throws on exactly the reads
1303
- * that did not reach storage. `null` still means the read SUCCEEDED and
1304
- * found nothing.
1320
+ * Workflow.getInMemoryRunAsWorkflowState reports the retained Run's lifecycle
1321
+ * status with isFromInMemory: true, without suspended paths or requestContext.
1322
+ * Refusing that marker prevents an approximation from authorizing an
1323
+ * irreversible action; after non-suspended completion the Run leaves the
1324
+ * in-memory map, so the fallback is null.
1305
1325
  *
1306
1326
  * A valid v2 pending row is refused before lifecycle projection; it has no
1307
1327
  * durable execution outcome yet.
@@ -1341,11 +1361,13 @@ export class RunnerRuntime {
1341
1361
  }
1342
1362
  if (capability === null || typeof capability !== 'object')
1343
1363
  throw new Error('workflow capability is malformed');
1344
- const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, } = capability;
1364
+ const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, touchRun: touch, replaceSnapshot: replace, } = capability;
1345
1365
  if (typeof prefix !== 'string' ||
1346
1366
  typeof readSnapshot !== 'function' ||
1347
1367
  typeof admit !== 'function' ||
1348
1368
  typeof terminalize !== 'function' ||
1369
+ (touch !== undefined && typeof touch !== 'function') ||
1370
+ (replace !== undefined && typeof replace !== 'function') ||
1349
1371
  !database ||
1350
1372
  typeof database.prepare !== 'function' ||
1351
1373
  typeof database.batch !== 'function')
@@ -1363,6 +1385,8 @@ export class RunnerRuntime {
1363
1385
  readSnapshot,
1364
1386
  admit,
1365
1387
  terminalize,
1388
+ ...(touch === undefined ? {} : { touch }),
1389
+ ...(replace === undefined ? {} : { replace }),
1366
1390
  };
1367
1391
  }
1368
1392
  async #observeStartState(workflowId, runId) {
@@ -1515,7 +1539,7 @@ export class RunnerRuntime {
1515
1539
  /** @internal Recover only after the exact owning execution has unwound. */
1516
1540
  async recoverStartAttempt(value, recovery) {
1517
1541
  const execution = normalizeD1RunExecutionIdentity(value);
1518
- const { attemptToken, isOwnerQuiescent, startReservation: suppliedClaim, expectedTarget: suppliedTarget, } = recovery;
1542
+ const { attemptToken, isOwnerQuiescent, startReservation: suppliedClaim, expectedTarget: suppliedTarget, startLeg, } = recovery;
1519
1543
  let expectedTarget;
1520
1544
  if (suppliedTarget !== undefined) {
1521
1545
  if (suppliedTarget === null ||
@@ -1565,7 +1589,11 @@ export class RunnerRuntime {
1565
1589
  const claim = suppliedClaim === undefined
1566
1590
  ? undefined
1567
1591
  : captureReservation(suppliedClaim, 'started');
1568
- if (!isPathSafeId(attemptToken) || typeof isOwnerQuiescent !== 'function')
1592
+ if (!isPathSafeId(attemptToken) ||
1593
+ typeof isOwnerQuiescent !== 'function' ||
1594
+ (startLeg !== undefined &&
1595
+ startLeg !== 'unwound' &&
1596
+ startLeg !== 'touched'))
1569
1597
  throw new InvalidRunRequestError('start recovery authority is malformed');
1570
1598
  if (claim && !this.#startIdempotency)
1571
1599
  throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
@@ -1609,11 +1637,19 @@ export class RunnerRuntime {
1609
1637
  state.provenance.attemptToken !== attemptToken ||
1610
1638
  state.provenance.resumeCounts.length !== 0)
1611
1639
  throw new RunStartPendingError();
1640
+ const nowMs = Date.now();
1641
+ // A source without the touch keeps no silence evidence: its start
1642
+ // leg may still run, so it is repaired at once and unstamped.
1643
+ const waitsForSilence = startLeg === 'touched' && source.touch !== undefined;
1644
+ if (waitsForSilence && !rowSilent(state.raw, nowMs))
1645
+ throw new RunStartPendingError();
1646
+ const legStopped = startLeg === 'unwound' || waitsForSilence;
1612
1647
  const result = await source.terminalize.call(source.capability, {
1613
1648
  expected: state.raw,
1614
1649
  execution,
1615
1650
  attemptToken,
1616
- nowMs: Date.now(),
1651
+ nowMs,
1652
+ ...(legStopped ? { markOutcomeUnknown: true } : {}),
1617
1653
  });
1618
1654
  if (result.kind === 'conflict')
1619
1655
  throw new Error('initial terminalization conflicts');
@@ -1650,6 +1686,124 @@ export class RunnerRuntime {
1650
1686
  }
1651
1687
  }));
1652
1688
  }
1689
+ /**
1690
+ * @internal Mark this run's row live for an executing leg, from whichever
1691
+ * instance runs it; the evidence #silentRow reads. A storage source without
1692
+ * the touch leaves nothing to read, so its runs are never settled here.
1693
+ */
1694
+ async touchRun(workflowId, runId, now = Date.now()) {
1695
+ const source = await this.#captureWorkflowStorage(workflowId);
1696
+ if (source.storage === 'd1' && source.touch)
1697
+ await source.touch.call(source.capability, { workflowId, runId }, now);
1698
+ }
1699
+ /**
1700
+ * @internal Settle a run whose execution leg ended without a durable outcome.
1701
+ *
1702
+ * The caller is the run's own Durable Object after it has established that no
1703
+ * leg of its own drives the run; this runtime's `#activeRuns` covers the
1704
+ * in-process drivers. An object can be replaced while its leg keeps running
1705
+ * on the outgoing instance, so a run is written only after its row has gone
1706
+ * untouched for RUN_LEG_SILENT_MS (`live` otherwise).
1707
+ *
1708
+ * `durable` (suspended, or terminal with its cleanup done) and `absent` leave
1709
+ * the snapshot untouched. A recorded cancellation or timeout owns the
1710
+ * outcome: `transition` completes it, or replays a terminal one whose cleanup
1711
+ * is unfinished, and leaves the cleanup to the caller as the terminate and
1712
+ * deadline routes do. The pending initial row stays with start recovery,
1713
+ * which repairs it as an unknown outcome.
1714
+ *
1715
+ * Any other run becomes `failed` (`interrupted`), never re-executed: the step
1716
+ * that was in flight may already have had effects.
1717
+ */
1718
+ async settleInterruptedRun(workflowId, runId, now = Date.now()) {
1719
+ this.#getWorkflow(workflowId);
1720
+ // Checked before queueing: a live leg holds the run lock for its whole
1721
+ // length, and a caller waiting behind it would learn nothing.
1722
+ if (this.isRunActive(workflowId, runId))
1723
+ return { kind: 'live' };
1724
+ return this.#withRunLock(workflowId, runId, () => this.#withLifecycleLock(workflowId, runId, async () => {
1725
+ const source = await this.#captureWorkflowStorage(workflowId);
1726
+ const state = await source.load.call(source.workflows, {
1727
+ workflowName: workflowId,
1728
+ runId,
1729
+ });
1730
+ if (!state)
1731
+ return { kind: 'absent' };
1732
+ if (state.runId !== runId)
1733
+ throw new RunStateUnreadableError(workflowId, runId);
1734
+ const lifecycle = lifecycleFromRequestContext(state.requestContext);
1735
+ // Ahead of the status checks: a cancel that took effect leaves Mastra's
1736
+ // terminal `canceled` precursor, which only the recorded transition
1737
+ // turns into `cancelled` with its cleanup.
1738
+ const recorded = lifecycle?.terminal ?? lifecycle?.transitionIntent;
1739
+ if (lifecycle?.terminal?.cleanupCompletedAt !== undefined)
1740
+ return { kind: 'durable' };
1741
+ if (!recorded) {
1742
+ if (isDurableRunStatus(state.status))
1743
+ return { kind: 'durable' };
1744
+ if (state.status === 'pending')
1745
+ throw new RunStartPendingError();
1746
+ if (!TERMINABLE_RUN_STATUSES.has(state.status))
1747
+ throw new RunStateUnreadableError(workflowId, runId);
1748
+ }
1749
+ // Every settlement write below is a compare-and-set against this
1750
+ // silent row: a write that lands after the read makes it miss (`live`).
1751
+ const silent = await this.#silentRow(source, workflowId, runId, now);
1752
+ if (!silent)
1753
+ return { kind: 'live' };
1754
+ try {
1755
+ if (recorded)
1756
+ return {
1757
+ kind: 'transition',
1758
+ replayPrincipal: recorded
1759
+ .replayPrincipals[0],
1760
+ transition: await this.#transitionTerminalLocked(workflowId, runId, recorded.status, now, { expected: silent }),
1761
+ };
1762
+ // The write replaces the silent row, so it is built from that row;
1763
+ // one that moved since the decision above waits for the next wake.
1764
+ const current = JSON.parse(silent.snapshot);
1765
+ if (current.runId !== runId)
1766
+ throw new RunStateUnreadableError(workflowId, runId);
1767
+ const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
1768
+ if (current.status !== state.status ||
1769
+ currentLifecycle?.revision !== lifecycle?.revision ||
1770
+ currentLifecycle?.terminal ||
1771
+ currentLifecycle?.transitionIntent)
1772
+ return { kind: 'live' };
1773
+ await this.#persistLifecycle(workflowId, runId, {
1774
+ ...current,
1775
+ ...terminalStateFields('failed'),
1776
+ error: {
1777
+ name: 'RunInterruptedError',
1778
+ message: RUN_INTERRUPTED_MESSAGE,
1779
+ },
1780
+ timestamp: now,
1781
+ }, advanceLifecycle(currentLifecycle, { interruptedAt: now }), now, source, silent);
1782
+ }
1783
+ catch (error) {
1784
+ if (error instanceof SettlementMissError)
1785
+ return { kind: 'live' };
1786
+ throw error;
1787
+ }
1788
+ return {
1789
+ kind: 'interrupted',
1790
+ summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
1791
+ };
1792
+ }));
1793
+ }
1794
+ /**
1795
+ * The run's row, when no leg has marked it live within RUN_LEG_SILENT_MS and
1796
+ * the storage can compare-and-set it; `undefined` otherwise.
1797
+ */
1798
+ async #silentRow(source, workflowId, runId, now) {
1799
+ if (source.storage !== 'd1' || !source.touch || !source.replace)
1800
+ return undefined;
1801
+ const raw = await source.readSnapshot.call(source.capability, {
1802
+ workflowId,
1803
+ runId,
1804
+ });
1805
+ return raw && rowSilent(raw, now) ? raw : undefined;
1806
+ }
1653
1807
  /** @internal Settle the exact selected terminal generation before managed cleanup. */
1654
1808
  async settleStartExecution(state, originalClaim) {
1655
1809
  const claim = originalClaim === undefined
@@ -1769,16 +1923,14 @@ export class RunnerRuntime {
1769
1923
  const replacementOperations = canonicalEconomicOperations(economicOperations);
1770
1924
  const lifecycle = replacementDeadline === undefined && replacementOperations === undefined
1771
1925
  ? storedLifecycle
1772
- : {
1773
- ...(storedLifecycle ?? { version: 1, revision: 0 }),
1774
- revision: nextLifecycleRevision(storedLifecycle?.revision ?? 0),
1926
+ : advanceLifecycle(storedLifecycle, {
1775
1927
  ...(replacementDeadline === undefined
1776
1928
  ? {}
1777
1929
  : { deadlineAt: replacementDeadline }),
1778
1930
  ...(replacementOperations === undefined
1779
1931
  ? {}
1780
1932
  : { economicOperations: replacementOperations }),
1781
- };
1933
+ });
1782
1934
  const requestContext = await this.#requestContextFor(workflowId, runId, {
1783
1935
  kind: 'resume',
1784
1936
  step,
@@ -1800,7 +1952,11 @@ export class RunnerRuntime {
1800
1952
  withNestedWorkflows,
1801
1953
  });
1802
1954
  }
1803
- async #persistLifecycle(workflowId, runId, state, lifecycle, now, source) {
1955
+ /**
1956
+ * With `expected`, a compare-and-set against that exact row, serialized as
1957
+ * Mastra's own persist does; a miss throws SettlementMissError.
1958
+ */
1959
+ async #persistLifecycle(workflowId, runId, state, lifecycle, now, source, expected) {
1804
1960
  const workflows = source.workflows;
1805
1961
  const persisted = {
1806
1962
  ...state,
@@ -1810,6 +1966,17 @@ export class RunnerRuntime {
1810
1966
  },
1811
1967
  timestamp: now,
1812
1968
  };
1969
+ if (expected) {
1970
+ if (source.storage !== 'd1' || !source.replace)
1971
+ throw new Error('settlement storage cannot compare-and-set');
1972
+ const replaced = await source.replace.call(source.capability, expected, {
1973
+ snapshot: JSON.stringify(persisted),
1974
+ updatedAt: new Date(now).toISOString(),
1975
+ });
1976
+ if (!replaced)
1977
+ throw new SettlementMissError();
1978
+ return persisted;
1979
+ }
1813
1980
  await source.persist.call(workflows, {
1814
1981
  workflowName: workflowId,
1815
1982
  runId,