@proofoftech/flowsafe 0.36.0 → 0.37.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 (87) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/agent-runner/durable-agent-runner.d.ts +1 -2
  3. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  4. package/dist/agent-runner/durable-agent-runner.js +1 -1
  5. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  6. package/dist/do-runner/child-run-ledger.d.ts +84 -0
  7. package/dist/do-runner/child-run-ledger.d.ts.map +1 -0
  8. package/dist/do-runner/child-run-ledger.js +272 -0
  9. package/dist/do-runner/child-run-ledger.js.map +1 -0
  10. package/dist/do-runner/child-runs.d.ts +95 -0
  11. package/dist/do-runner/child-runs.d.ts.map +1 -0
  12. package/dist/do-runner/child-runs.js +185 -0
  13. package/dist/do-runner/child-runs.js.map +1 -0
  14. package/dist/do-runner/constants.d.ts +1 -1
  15. package/dist/do-runner/constants.d.ts.map +1 -1
  16. package/dist/do-runner/constants.js +1 -1
  17. package/dist/do-runner/constants.js.map +1 -1
  18. package/dist/do-runner/d1-storage.d.ts +1 -0
  19. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  20. package/dist/do-runner/d1-storage.js +76 -40
  21. package/dist/do-runner/d1-storage.js.map +1 -1
  22. package/dist/do-runner/durable-object.d.ts +16 -2
  23. package/dist/do-runner/durable-object.d.ts.map +1 -1
  24. package/dist/do-runner/durable-object.js +1273 -65
  25. package/dist/do-runner/durable-object.js.map +1 -1
  26. package/dist/do-runner/execution-context.d.ts.map +1 -1
  27. package/dist/do-runner/execution-context.js +2 -0
  28. package/dist/do-runner/execution-context.js.map +1 -1
  29. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  30. package/dist/do-runner/fenced-workflows-d1.js +4 -1
  31. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  32. package/dist/do-runner/index.d.ts +5 -3
  33. package/dist/do-runner/index.d.ts.map +1 -1
  34. package/dist/do-runner/index.js +3 -1
  35. package/dist/do-runner/index.js.map +1 -1
  36. package/dist/do-runner/init.d.ts +2 -1
  37. package/dist/do-runner/init.d.ts.map +1 -1
  38. package/dist/do-runner/init.js +1 -0
  39. package/dist/do-runner/init.js.map +1 -1
  40. package/dist/do-runner/inventory.d.ts +2 -2
  41. package/dist/do-runner/inventory.d.ts.map +1 -1
  42. package/dist/do-runner/inventory.js +55 -4
  43. package/dist/do-runner/inventory.js.map +1 -1
  44. package/dist/do-runner/resume-refusal-codes.d.ts +3 -0
  45. package/dist/do-runner/resume-refusal-codes.d.ts.map +1 -0
  46. package/dist/do-runner/resume-refusal-codes.js +4 -0
  47. package/dist/do-runner/resume-refusal-codes.js.map +1 -0
  48. package/dist/do-runner/run-lifecycle.d.ts +19 -2
  49. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  50. package/dist/do-runner/run-lifecycle.js +23 -0
  51. package/dist/do-runner/run-lifecycle.js.map +1 -1
  52. package/dist/do-runner/run-lineage.d.ts +26 -0
  53. package/dist/do-runner/run-lineage.d.ts.map +1 -0
  54. package/dist/do-runner/run-lineage.js +38 -0
  55. package/dist/do-runner/run-lineage.js.map +1 -0
  56. package/dist/do-runner/runtime.d.ts +56 -3
  57. package/dist/do-runner/runtime.d.ts.map +1 -1
  58. package/dist/do-runner/runtime.js +281 -80
  59. package/dist/do-runner/runtime.js.map +1 -1
  60. package/dist/do-runner/suspension-deadline.d.ts +4 -1
  61. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  62. package/dist/do-runner/suspension-deadline.js +24 -4
  63. package/dist/do-runner/suspension-deadline.js.map +1 -1
  64. package/dist/do-runner/suspension-kinds.d.ts +9 -0
  65. package/dist/do-runner/suspension-kinds.d.ts.map +1 -1
  66. package/dist/do-runner/suspension-kinds.js +37 -5
  67. package/dist/do-runner/suspension-kinds.js.map +1 -1
  68. package/dist/durable-agent-workflow-id.d.ts +2 -0
  69. package/dist/durable-agent-workflow-id.d.ts.map +1 -0
  70. package/dist/durable-agent-workflow-id.js +3 -0
  71. package/dist/durable-agent-workflow-id.js.map +1 -0
  72. package/dist/host-kit/do-response.d.ts.map +1 -1
  73. package/dist/host-kit/do-response.js +20 -0
  74. package/dist/host-kit/do-response.js.map +1 -1
  75. package/dist/host-kit/do-run-topology.d.ts +3 -1
  76. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  77. package/dist/host-kit/do-run-topology.js +60 -0
  78. package/dist/host-kit/do-run-topology.js.map +1 -1
  79. package/dist/host-kit/flowsafe-worker.d.ts +7 -3
  80. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  81. package/dist/host-kit/flowsafe-worker.js +48 -6
  82. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  83. package/dist/host-kit/run-router.d.ts +4 -0
  84. package/dist/host-kit/run-router.d.ts.map +1 -1
  85. package/dist/host-kit/run-router.js +17 -15
  86. package/dist/host-kit/run-router.js.map +1 -1
  87. package/package.json +1 -1
@@ -18,6 +18,7 @@
18
18
  // exact failure an approval product must not have. Both locks are per runtime instance;
19
19
  // cross-instance serialization comes from routing one DO instance per run
20
20
  // (see durable-object.ts).
21
+ import { AsyncLocalStorage } from 'node:async_hooks';
21
22
  import { Mastra } from '@mastra/core/mastra';
22
23
  import { RequestContext } from '@mastra/core/request-context';
23
24
  import { createEmptyWorkflowSnapshot, } from '@mastra/core/storage';
@@ -33,8 +34,10 @@ import { FENCED_WORKFLOW_STORAGE, isEntryBoundarySnapshot, } from './fenced-work
33
34
  import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
34
35
  import { mastraRegistryEntries } from './mastra-registry.js';
35
36
  import { isPathSafeId } from './path-safe-id.js';
37
+ import { RUN_NOT_SUSPENDED, SUSPENSION_CHANGED, } from './resume-refusal-codes.js';
36
38
  import { exceedsRunInputDepth, runInputDepthMessage, } from './run-input-depth.js';
37
39
  import { advanceLifecycle, canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, failureEnvelope, hasDisputedSettlement, isPauseLegAbort, isPauseReason, isSettledLegAbort, legAbortReason, lifecycleFromRequestContext, nextLifecycleRevision, pauseLegAbortReason, projectTerminalLifecycle, RUN_FAILURE_MARKERS, RUN_LIFECYCLE_CONTEXT_KEY, RUN_SETTLING_MARKERS, RunLifecycleBlockedError, RunSettledConflictError, RunStateNotStorableError, runTerminalError, terminalCleanupFor, terminalLegAbortReason, } from './run-lifecycle.js';
40
+ import { parseRunLineage, projectRunLineage, RUN_LINEAGE_CONTEXT_KEY, } from './run-lineage.js';
38
41
  import { decodeProgressRunProvenance, decodeResumeCounts, nextResumeCount, runExecutionIdentityFor, } from './run-provenance.js';
39
42
  import { captureRunRequester } from './run-requester.js';
40
43
  import { errorText, isDurableRunStatus, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
@@ -68,7 +71,7 @@ export class UnknownRunError extends Error {
68
71
  */
69
72
  export class RunNotSuspendedError extends DoStatusError {
70
73
  status = 409;
71
- reason = { code: 'RUN_NOT_SUSPENDED' };
74
+ reason = { code: RUN_NOT_SUSPENDED };
72
75
  constructor(workflowId, runId, runStatus) {
73
76
  super(`run '${runId}' of workflow '${workflowId}' is '${runStatus}', not 'suspended'`);
74
77
  this.name = 'RunNotSuspendedError';
@@ -80,7 +83,7 @@ export class RunNotSuspendedError extends DoStatusError {
80
83
  */
81
84
  export class SuspensionChangedError extends DoStatusError {
82
85
  status = 409;
83
- reason = { code: 'SUSPENSION_CHANGED' };
86
+ reason = { code: SUSPENSION_CHANGED };
84
87
  constructor(workflowId, runId, step) {
85
88
  super(`step '${step}' of run '${runId}' of workflow '${workflowId}' is no longer at the suspension the resume names`);
86
89
  this.name = 'SuspensionChangedError';
@@ -145,6 +148,9 @@ export class InvalidRunRequestError extends Error {
145
148
  this.name = 'InvalidRunRequestError';
146
149
  }
147
150
  }
151
+ /** @internal The step's resume schema rejected the internally built envelope. */
152
+ export class ChildAwaitResumeSchemaError extends InvalidRunRequestError {
153
+ }
148
154
  export class PauseConflictError extends DoStatusError {
149
155
  status = 409;
150
156
  reason = { code: 'PAUSE_CONFLICT' };
@@ -297,7 +303,7 @@ function runProvenance(state) {
297
303
  resumeCounts: counts,
298
304
  };
299
305
  }
300
- function summarize(runId, result, counts, requestedBy, requestedByKind, deadlineAt) {
306
+ function summarize(workflowId, runId, result, lineage, counts, requestedBy, requestedByKind, deadlineAt) {
301
307
  let summary;
302
308
  switch (result.status) {
303
309
  case 'success':
@@ -347,7 +353,7 @@ function summarize(runId, result, counts, requestedBy, requestedByKind, deadline
347
353
  }
348
354
  if (deadlineAt !== undefined)
349
355
  summary.deadlineAt = deadlineAt;
350
- return summary;
356
+ return { ...summary, ...projectRunLineage(workflowId, runId, lineage) };
351
357
  }
352
358
  // Storage may hand timestamps back as Date or as a serialized string
353
359
  // depending on the adapter's snapshot round-trip; normalize defensively.
@@ -418,11 +424,14 @@ function byStep(suspendedKeys, lookup) {
418
424
  }
419
425
  return size > 0 ? map : undefined;
420
426
  }
421
- function summarizeState(runId, state, provenance) {
427
+ function summarizeState(workflowId, runId, state, provenance) {
422
428
  const lifecycle = lifecycleFromRequestContext(state.requestContext);
423
429
  const summary = {
424
430
  runId,
425
431
  status: lifecycle?.terminal?.status ?? state.status,
432
+ ...(state.isFromInMemory
433
+ ? {}
434
+ : projectRunLineage(workflowId, runId, parseRunLineage(state.requestContext?.[RUN_LINEAGE_CONTEXT_KEY]))),
426
435
  createdAt: toIso(state.createdAt),
427
436
  updatedAt: toIso(state.updatedAt),
428
437
  };
@@ -475,11 +484,11 @@ function summarizeState(runId, state, provenance) {
475
484
  }
476
485
  return summary;
477
486
  }
478
- function summaryFromSelectedSnapshot(runId, snapshot, timestamps, provenance) {
487
+ function summaryFromSelectedSnapshot(workflowId, runId, snapshot, timestamps, provenance) {
479
488
  const steps = Object.fromEntries(Object.entries(snapshot.context ?? {})
480
489
  .filter(([key]) => key !== 'input' && key !== '__state')
481
490
  .map(([key, value]) => [key, cleanStepResult(value)]));
482
- return summarizeState(runId, {
491
+ return summarizeState(workflowId, runId, {
483
492
  status: snapshot.status,
484
493
  result: snapshot.result,
485
494
  error: snapshot.error,
@@ -515,6 +524,7 @@ function orderedRequestContext(runtimeContext, provided, scheduled) {
515
524
  key === BREAKWATER_CONNECTOR_EXECUTION_KEY ||
516
525
  key === RUN_PROVENANCE_CONTEXT_KEY ||
517
526
  key === RUN_LIFECYCLE_CONTEXT_KEY ||
527
+ key === RUN_LINEAGE_CONTEXT_KEY ||
518
528
  key === 'runId') {
519
529
  continue;
520
530
  }
@@ -628,7 +638,7 @@ function isRunStateNotStorable(error) {
628
638
  return findInCauseChain(error, (link) => link instanceof RunStateNotStorableError, { rootOnly: false });
629
639
  }
630
640
  function captureStartRunOptions(source) {
631
- const { runId, inputData, initialState, storedRequestContext, attemptToken, deadlineMs, economicOperations: rawOperations, scheduleDispatch: rawDispatch, idempotencyKey, requestedBy, requestedByKind, runRequester: rawRequester, mutationEpoch: rawEpoch, startIdentity: rawIdentity, agentStart: rawAgentStart, onPreparedStartIdentity, pendingTerminal, runOwnerGuard: rawGuard, startReservation: rawReservation, legAbort, } = source;
641
+ const { runId, inputData, initialState, storedRequestContext, attemptToken, deadlineMs, economicOperations: rawOperations, scheduleDispatch: rawDispatch, idempotencyKey, requestedBy, requestedByKind, runRequester: rawRequester, mutationEpoch: rawEpoch, startIdentity: rawIdentity, child: rawChild, agentStart: rawAgentStart, onPreparedStartIdentity, onAdmittedStartIdentity, pendingTerminal, runOwnerGuard: rawGuard, startReservation: rawReservation, legAbort, } = source;
632
642
  assertLegAbort(legAbort);
633
643
  if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
634
644
  throw new InvalidRunRequestError('requestedBy is malformed');
@@ -645,6 +655,17 @@ function captureStartRunOptions(source) {
645
655
  throw new InvalidRunRequestError('runRequester is malformed');
646
656
  const mutationEpoch = normalizeMutationEpoch(rawEpoch);
647
657
  const startIdentity = rawIdentity === undefined ? undefined : normalizeStartIdentity(rawIdentity);
658
+ let child;
659
+ if (rawChild !== undefined) {
660
+ const lineage = parseRunLineage(rawChild.lineage);
661
+ const { parentDeadlineAt } = rawChild;
662
+ if (!lineage ||
663
+ (parentDeadlineAt !== undefined &&
664
+ (!Number.isSafeInteger(parentDeadlineAt) || parentDeadlineAt < 0))) {
665
+ throw new InvalidRunRequestError('child start authority is malformed');
666
+ }
667
+ child = Object.freeze({ lineage, parentDeadlineAt });
668
+ }
648
669
  const startReservation = rawReservation === undefined
649
670
  ? undefined
650
671
  : captureReservation(rawReservation, 'started');
@@ -675,6 +696,9 @@ function captureStartRunOptions(source) {
675
696
  typeof onPreparedStartIdentity !== 'function') {
676
697
  throw new InvalidRunRequestError('onPreparedStartIdentity is malformed');
677
698
  }
699
+ if (onAdmittedStartIdentity !== undefined &&
700
+ typeof onAdmittedStartIdentity !== 'function')
701
+ throw new InvalidRunRequestError('onAdmittedStartIdentity is malformed');
678
702
  if (pendingTerminal !== undefined && typeof pendingTerminal !== 'function')
679
703
  throw new InvalidRunRequestError('pendingTerminal is malformed');
680
704
  let runOwnerGuard;
@@ -749,8 +773,10 @@ function captureStartRunOptions(source) {
749
773
  idempotencyKey,
750
774
  mutationEpoch,
751
775
  startIdentity,
776
+ child,
752
777
  agentStart,
753
778
  onPreparedStartIdentity,
779
+ onAdmittedStartIdentity,
754
780
  pendingTerminal,
755
781
  runOwnerGuard,
756
782
  startReservation,
@@ -761,7 +787,11 @@ function captureStartRunOptions(source) {
761
787
  : captured);
762
788
  }
763
789
  function lifecycleForStart(options) {
764
- const deadlineAt = relativeDeadline(options.deadlineMs);
790
+ const requestedDeadlineAt = relativeDeadline(options.deadlineMs);
791
+ const parentDeadlineAt = options.child?.parentDeadlineAt;
792
+ const deadlineAt = requestedDeadlineAt === undefined || parentDeadlineAt === undefined
793
+ ? (requestedDeadlineAt ?? parentDeadlineAt)
794
+ : Math.min(requestedDeadlineAt, parentDeadlineAt);
765
795
  const economicOperations = canonicalEconomicOperations(options.economicOperations);
766
796
  const scheduleDispatch = canonicalScheduleDispatch(options.scheduleDispatch);
767
797
  if (deadlineAt === undefined &&
@@ -782,6 +812,8 @@ function effectiveLifecycle(persisted, active) {
782
812
  return active;
783
813
  if (!active)
784
814
  return persisted;
815
+ if (persisted.transitionIntent?.childCascadeStarted)
816
+ return persisted;
785
817
  // As lifecycleMergeSql decides: a stored intent never joins a lifecycle it
786
818
  // was not checked against.
787
819
  if (persisted.transitionIntent && hasDisputedSettlement(active))
@@ -836,6 +868,23 @@ function failedByMarker(marker, now) {
836
868
  timestamp: now,
837
869
  };
838
870
  }
871
+ const activeWorkflowLeg = new AsyncLocalStorage();
872
+ /** @internal The engine leg whose step is executing in this async context. */
873
+ export function currentWorkflowLeg() {
874
+ return activeWorkflowLeg.getStore();
875
+ }
876
+ function matchesSuspension(step, suspendedAt, resumeCount) {
877
+ return ({ state }, provenance) => {
878
+ const result = state.context?.[step];
879
+ const attempt = Array.isArray(result) ? result.at(-1) : result;
880
+ return (Object.hasOwn(state.suspendedPaths ?? {}, step) &&
881
+ attempt !== null &&
882
+ typeof attempt === 'object' &&
883
+ 'suspendedAt' in attempt &&
884
+ attempt.suspendedAt === suspendedAt &&
885
+ (new Map(provenance?.resumeCounts).get(step) ?? 0) === resumeCount);
886
+ };
887
+ }
839
888
  function sameExecution(a, b) {
840
889
  return (a.tablePrefix === b.tablePrefix &&
841
890
  a.workflowId === b.workflowId &&
@@ -857,6 +906,7 @@ function assertClaimIdentity(claim, execution, key = claim.key) {
857
906
  }
858
907
  }
859
908
  export class RunnerRuntime {
909
+ #childRunLimits;
860
910
  #storage;
861
911
  #logger;
862
912
  #requestContextForRun;
@@ -874,6 +924,14 @@ export class RunnerRuntime {
874
924
  #startIdempotency;
875
925
  #mastra;
876
926
  constructor(options) {
927
+ const { maxDepth = 4, maxChildrenPerRun = 16 } = options.childRuns ?? {};
928
+ if (!Number.isSafeInteger(maxDepth) ||
929
+ maxDepth < 0 ||
930
+ !Number.isSafeInteger(maxChildrenPerRun) ||
931
+ maxChildrenPerRun < 0) {
932
+ throw new Error('child run limits must be nonnegative safe integers');
933
+ }
934
+ this.#childRunLimits = Object.freeze({ maxDepth, maxChildrenPerRun });
877
935
  this.#storage = options.storage;
878
936
  this.#logger = options.logger ?? false;
879
937
  this.#requestContextForRun = options.requestContextForRun;
@@ -881,6 +939,10 @@ export class RunnerRuntime {
881
939
  this.#executionFence = options.executionFence;
882
940
  this.#startIdempotency = options.startIdempotency;
883
941
  }
942
+ /** @internal Limits used by the run object when reserving children. */
943
+ get childRunLimits() {
944
+ return this.#childRunLimits;
945
+ }
884
946
  /**
885
947
  * The deployment execution fence this runtime enforces, or undefined when
886
948
  * the host built an unfenced runtime. Exposed so the surfaces ABOVE the
@@ -1137,7 +1199,22 @@ export class RunnerRuntime {
1137
1199
  const lifecycle = lifecycleForStart(options);
1138
1200
  active.lifecycle = lifecycle;
1139
1201
  preflight = false;
1140
- const requestContext = await this.#requestContextFor(workflowId, runId, { kind: 'start' }, provenance, options.storedRequestContext, lifecycle);
1202
+ const lineage = options.child?.lineage;
1203
+ const requestContext = await this.#requestContextFor(workflowId, runId, lineage === undefined
1204
+ ? { kind: 'start' }
1205
+ : {
1206
+ kind: 'start',
1207
+ parent: Object.freeze({
1208
+ workflowId: lineage.parentWorkflowId,
1209
+ runId: lineage.parentRunId,
1210
+ rootRunId: lineage.rootRunId,
1211
+ depth: lineage.depth - 1,
1212
+ key: lineage.childKey,
1213
+ ...(options.runRequester === undefined
1214
+ ? {}
1215
+ : { runRequester: options.runRequester }),
1216
+ }),
1217
+ }, provenance, options.storedRequestContext, lifecycle, lineage);
1141
1218
  active.requestContext = requestContext;
1142
1219
  this.#enablePauseBoundary(active);
1143
1220
  if (options.onPreparedStartIdentity)
@@ -1214,14 +1291,16 @@ export class RunnerRuntime {
1214
1291
  active.lifecycle = intent;
1215
1292
  requestContext.set(RUN_LIFECYCLE_CONTEXT_KEY, intent);
1216
1293
  }
1294
+ if (initial && options.onAdmittedStartIdentity)
1295
+ await Reflect.apply(options.onAdmittedStartIdentity, undefined, [capturedExecution]);
1217
1296
  active.run = run;
1218
1297
  engineEntered = true;
1219
1298
  // Mastra's WorkflowResult omits the engine's 'canceled' status.
1220
- const startPromise = run.start({
1299
+ const startPromise = this.#inWorkflowLeg(workflowId, runId, active, () => run.start({
1221
1300
  inputData: options.inputData,
1222
1301
  initialState: options.initialState,
1223
1302
  requestContext,
1224
- });
1303
+ }));
1225
1304
  if (pending && !hasDisputedSettlement(active.lifecycle)) {
1226
1305
  this.#terminalAbortIntents.set(activeKey, pending.status);
1227
1306
  // Run.cancel reads storage before aborting, while start
@@ -1287,6 +1366,10 @@ export class RunnerRuntime {
1287
1366
  async resume(workflowId, runId, options = {}) {
1288
1367
  return this.#resume(workflowId, runId, options);
1289
1368
  }
1369
+ /** @internal Resume from persisted child outcomes under a suspension fingerprint. */
1370
+ resumeChildAwait(workflowId, runId, options) {
1371
+ return this.#resume(workflowId, runId, options, { kind: 'child-await' });
1372
+ }
1290
1373
  async resumePaused(workflowId, runId, principal, options) {
1291
1374
  const { expectedGeneration, legAbort } = options;
1292
1375
  assertLegAbort(legAbort);
@@ -1326,7 +1409,7 @@ export class RunnerRuntime {
1326
1409
  const next = advanceLifecycle(lifecycle, {});
1327
1410
  delete next.pause;
1328
1411
  await this.#persistIntent(workflowId, runId, state, next, now, source, row);
1329
- return summaryFromSelectedSnapshot(runId, {
1412
+ return summaryFromSelectedSnapshot(workflowId, runId, {
1330
1413
  ...state,
1331
1414
  requestContext: {
1332
1415
  ...state.requestContext,
@@ -1341,12 +1424,18 @@ export class RunnerRuntime {
1341
1424
  requestedBy: principal.id,
1342
1425
  requestedByKind: principal.kind,
1343
1426
  legAbort: options.legAbort,
1344
- }, { generation: options.expectedGeneration, onRestartState });
1427
+ }, {
1428
+ kind: 'restart',
1429
+ generation: options.expectedGeneration,
1430
+ onRestartState,
1431
+ });
1345
1432
  }
1346
- async #resume(workflowId, runId, options, restart) {
1433
+ async #resume(workflowId, runId, options, mode) {
1434
+ const restart = mode?.kind === 'restart' ? mode : undefined;
1347
1435
  const { legAbort } = options;
1348
1436
  assertLegAbort(legAbort);
1349
- assertRunInputDepth('resumeData', options.resumeData);
1437
+ if (mode?.kind !== 'child-await')
1438
+ assertRunInputDepth('resumeData', options.resumeData);
1350
1439
  const expectedSuspension = captureExpectedSuspension(options.expectedSuspension);
1351
1440
  this.#getWorkflow(workflowId);
1352
1441
  const proof = await this.#assertResumeFence(workflowId, runId);
@@ -1451,13 +1540,13 @@ export class RunnerRuntime {
1451
1540
  }
1452
1541
  active.run = run;
1453
1542
  engineEntered = true;
1454
- const legPromise = restart === undefined
1543
+ const legPromise = this.#inWorkflowLeg(workflowId, runId, active, () => restart === undefined
1455
1544
  ? run.resume({
1456
1545
  step: options.step,
1457
1546
  resumeData: options.resumeData,
1458
1547
  requestContext,
1459
1548
  })
1460
- : run.restart({ requestContext });
1549
+ : run.restart({ requestContext }));
1461
1550
  return { executionPromise: legPromise };
1462
1551
  });
1463
1552
  const resumed = await executionPromise;
@@ -1486,7 +1575,7 @@ export class RunnerRuntime {
1486
1575
  if (summary.pauseGeneration !== undefined)
1487
1576
  return summary;
1488
1577
  }
1489
- return summarize(runId, result, nextCounts, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
1578
+ return summarize(workflowId, runId, result, parseRunLineage(state.requestContext?.[RUN_LINEAGE_CONTEXT_KEY]), nextCounts, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
1490
1579
  }
1491
1580
  catch (error) {
1492
1581
  const claim = active.storedRunScope?.restart;
@@ -1512,6 +1601,10 @@ export class RunnerRuntime {
1512
1601
  if (recovered)
1513
1602
  return recovered;
1514
1603
  }
1604
+ if (mode?.kind === 'child-await' &&
1605
+ error instanceof Error &&
1606
+ isSchemaViolation(error))
1607
+ throw new ChildAwaitResumeSchemaError(error.message);
1515
1608
  throw asClientError(error) ?? error;
1516
1609
  }
1517
1610
  finally {
@@ -1540,7 +1633,7 @@ export class RunnerRuntime {
1540
1633
  const next = advanceLifecycle(lifecycle, {});
1541
1634
  delete next.pause;
1542
1635
  const running = await this.#persistLifecycle(workflowId, runId, { ...state, status: 'running' }, { ...next, pause: { ...pause, restartAttemptToken: attemptToken } }, now, source, row);
1543
- onRestartState?.(summaryFromSelectedSnapshot(runId, running, { ...row, updatedAt: new Date(now).toISOString() }, provenance));
1636
+ onRestartState?.(summaryFromSelectedSnapshot(workflowId, runId, running, { ...row, updatedAt: new Date(now).toISOString() }, provenance));
1544
1637
  return next;
1545
1638
  });
1546
1639
  }
@@ -1555,7 +1648,7 @@ export class RunnerRuntime {
1555
1648
  const pause = { ...lifecycle.pause };
1556
1649
  delete pause.restartAttemptToken;
1557
1650
  const paused = await this.#persistLifecycle(row.workflowId, row.runId, { ...state, status: 'paused' }, advanceLifecycle(lifecycle, { pause }), now, source, row);
1558
- return summaryFromSelectedSnapshot(row.runId, paused, { ...row, updatedAt: new Date(now).toISOString() }, runProvenance(state));
1651
+ return summaryFromSelectedSnapshot(row.workflowId, row.runId, paused, { ...row, updatedAt: new Date(now).toISOString() }, runProvenance(state));
1559
1652
  }
1560
1653
  /** Request a cooperative pause without waiting for the executing leg. */
1561
1654
  async requestPause(workflowId, runId, principal, options) {
@@ -1596,7 +1689,7 @@ export class RunnerRuntime {
1596
1689
  pause.requestedBy.kind !== requestedBy.kind ||
1597
1690
  pause.requestedBy.id !== requestedBy.id)
1598
1691
  throw new PauseConflictError();
1599
- return summaryFromSelectedSnapshot(runId, state, row, provenance);
1692
+ return summaryFromSelectedSnapshot(workflowId, runId, state, row, provenance);
1600
1693
  }
1601
1694
  if (state.status === 'paused')
1602
1695
  throw new PauseUnsupportedError('this paused run has no pause record');
@@ -1610,7 +1703,7 @@ export class RunnerRuntime {
1610
1703
  },
1611
1704
  });
1612
1705
  await this.#persistIntent(workflowId, runId, state, next, now, source, row);
1613
- return summaryFromSelectedSnapshot(runId, {
1706
+ return summaryFromSelectedSnapshot(workflowId, runId, {
1614
1707
  ...state,
1615
1708
  requestContext: {
1616
1709
  ...state.requestContext,
@@ -1646,11 +1739,11 @@ export class RunnerRuntime {
1646
1739
  cas !== undefined)
1647
1740
  throw read;
1648
1741
  }
1649
- const cancelTarget = () => {
1742
+ const cancelTarget = (status = intendedStatus) => {
1650
1743
  if (!active?.run)
1651
1744
  return undefined;
1652
- this.#terminalAbortIntents.set(key, intendedStatus);
1653
- return { run: active.run, legAbort: active.legAbort, key };
1745
+ this.#terminalAbortIntents.set(key, status);
1746
+ return { run: active.run, legAbort: active.legAbort, key, status };
1654
1747
  };
1655
1748
  const lifecycle = effectiveLifecycle(read instanceof UnknownRunError
1656
1749
  ? undefined
@@ -1675,6 +1768,14 @@ export class RunnerRuntime {
1675
1768
  }
1676
1769
  const { state, row } = read;
1677
1770
  const existingIntent = lifecycle?.transitionIntent;
1771
+ if (existingIntent?.childCascadeStarted) {
1772
+ if (cas &&
1773
+ (existingIntent.status !== intendedStatus ||
1774
+ existingIntent.expectedRevision !== cas.expectedRevision ||
1775
+ existingIntent.expectedDeadlineAt !== cas.expectedDeadlineAt))
1776
+ return undefined;
1777
+ return cancelTarget(existingIntent.status);
1778
+ }
1678
1779
  if (existingIntent?.status === intendedStatus &&
1679
1780
  (cas === undefined ||
1680
1781
  (existingIntent.expectedRevision === cas.expectedRevision &&
@@ -1737,12 +1838,16 @@ export class RunnerRuntime {
1737
1838
  }
1738
1839
  // After `run.cancel()` has aborted the engine run, so the engine's
1739
1840
  // cancellation precedes any abort error from a call in flight.
1740
- prepared.legAbort?.abort(terminalLegAbortReason(intendedStatus));
1841
+ prepared.legAbort?.abort(terminalLegAbortReason(prepared.status));
1741
1842
  return true;
1742
1843
  }
1743
1844
  /** Trusted host variant that persists the exact identities allowed to retry. */
1744
- terminateAsPrincipal(workflowId, runId, principal, owner, now = Date.now()) {
1745
- return this.#transitionTerminal(workflowId, runId, 'cancelled', now, undefined, [principal, owner], principal);
1845
+ terminateAsPrincipal(workflowId, runId, principal, owner, now = Date.now(), beforeCommit) {
1846
+ return this.#transitionTerminal(workflowId, runId, 'cancelled', now, {
1847
+ replayPrincipals: [principal, owner],
1848
+ replayingPrincipal: principal,
1849
+ beforeCommit,
1850
+ });
1746
1851
  }
1747
1852
  /** CAS-guarded deadline transition driven through the owner Durable Object. */
1748
1853
  timeOut(workflowId, runId, cas, now = Date.now()) {
@@ -1755,17 +1860,32 @@ export class RunnerRuntime {
1755
1860
  now < 0) {
1756
1861
  throw new InvalidRunRequestError('deadline transition CAS is malformed');
1757
1862
  }
1758
- return this.#transitionTerminal(workflowId, runId, 'timed_out', now, cas);
1863
+ return this.#transitionTerminal(workflowId, runId, 'timed_out', now, {
1864
+ cas,
1865
+ });
1759
1866
  }
1760
1867
  /** Trusted host deadline transition with retry principals persisted atomically. */
1761
- timeOutAsPrincipal(workflowId, runId, cas, principal, owner, now = Date.now()) {
1762
- return this.#transitionTerminal(workflowId, runId, 'timed_out', now, cas, [principal, owner], principal);
1868
+ timeOutAsPrincipal(workflowId, runId, cas, principal, owner, now = Date.now(), beforeCommit) {
1869
+ return this.#transitionTerminal(workflowId, runId, 'timed_out', now, {
1870
+ cas,
1871
+ replayPrincipals: [principal, owner],
1872
+ replayingPrincipal: principal,
1873
+ beforeCommit,
1874
+ });
1875
+ }
1876
+ /** @internal A verified parent cascade can end a child before its own deadline. */
1877
+ cascadeTerminateAsPrincipal(workflowId, runId, status, owner, beforeCommit, { recordedIntentOnly = false } = {}) {
1878
+ return this.#transitionTerminal(workflowId, runId, status, Date.now(), {
1879
+ beforeCommit,
1880
+ fallbackReplayPrincipal: owner,
1881
+ recordedIntentOnly,
1882
+ });
1763
1883
  }
1764
- async #transitionTerminal(workflowId, runId, status, now, cas, replayPrincipals, replayingPrincipal) {
1884
+ async #transitionTerminal(workflowId, runId, status, now, options = {}) {
1765
1885
  this.#getWorkflow(workflowId);
1766
1886
  return this.#withRunLock(workflowId, runId, async () => {
1767
1887
  const source = await this.#captureWorkflowStorage(workflowId);
1768
- return this.#retryOnRowChange(workflowId, runId, async () => this.#transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal }, source, await this.#readForTransition(source, workflowId, runId)));
1888
+ return this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => this.#transitionTerminalLocked(workflowId, runId, status, now, options, source, await this.#readForTransition(source, workflowId, runId))));
1769
1889
  });
1770
1890
  }
1771
1891
  /**
@@ -1773,8 +1893,9 @@ export class RunnerRuntime {
1773
1893
  * for a caller holding the run lock. Where the read carries the row, the
1774
1894
  * write is a compare-and-set against it and a miss throws RowChangedError.
1775
1895
  */
1776
- async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal }, source, { state, row }) {
1777
- const lifecycle = lifecycleFromRequestContext(state.requestContext);
1896
+ async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal, fallbackReplayPrincipal, recordedIntentOnly, beforeCommit, }, source, read) {
1897
+ let { state, row } = read;
1898
+ let lifecycle = lifecycleFromRequestContext(state.requestContext);
1778
1899
  if (lifecycle?.terminal) {
1779
1900
  if (replayingPrincipal &&
1780
1901
  !lifecycle.terminal.replayPrincipals.some((principal) => principal.kind === replayingPrincipal.kind &&
@@ -1791,6 +1912,13 @@ export class RunnerRuntime {
1791
1912
  };
1792
1913
  }
1793
1914
  const transitionIntent = lifecycle?.transitionIntent;
1915
+ if (recordedIntentOnly &&
1916
+ (!transitionIntent?.childCascadeStarted ||
1917
+ transitionIntent.status !== status)) {
1918
+ throw new RunTerminalConflictError(workflowId, runId, state.status);
1919
+ }
1920
+ if (transitionIntent?.childCascadeStarted && cas === undefined)
1921
+ status = transitionIntent.status;
1794
1922
  const intentMatchesTransition = transitionIntent?.status === status &&
1795
1923
  (cas === undefined ||
1796
1924
  (transitionIntent.expectedRevision === cas.expectedRevision &&
@@ -1822,6 +1950,8 @@ export class RunnerRuntime {
1822
1950
  message: 'run termination is blocked while an economic operation is disputed',
1823
1951
  });
1824
1952
  }
1953
+ if (transitionIntent?.childCascadeStarted && !beforeCommit)
1954
+ throw new RunStateUnreadableError(workflowId, runId);
1825
1955
  const currentStatus = state.status;
1826
1956
  const abortIntent = this.#terminalAbortIntents.get(this.#runKey(workflowId, runId));
1827
1957
  if (!TERMINABLE_RUN_STATUSES.has(currentStatus) &&
@@ -1834,14 +1964,52 @@ export class RunnerRuntime {
1834
1964
  throw new RunTerminalConflictError(workflowId, runId, currentStatus);
1835
1965
  }
1836
1966
  const provenance = runProvenance(state);
1837
- const fallbackPrincipal = provenance?.requestedBy && provenance.requestedByKind
1838
- ? {
1839
- kind: provenance.requestedByKind,
1840
- id: provenance.requestedBy,
1841
- }
1842
- : { kind: 'system', id: 'flowsafe-system' };
1843
- const principals = canonicalReplayPrincipals(replayPrincipals ??
1844
- transitionIntent?.replayPrincipals ?? [fallbackPrincipal]);
1967
+ const fallbackPrincipal = fallbackReplayPrincipal ??
1968
+ (provenance?.requestedBy && provenance.requestedByKind
1969
+ ? {
1970
+ kind: provenance.requestedByKind,
1971
+ id: provenance.requestedBy,
1972
+ }
1973
+ : { kind: 'system', id: 'flowsafe-system' });
1974
+ const principals = canonicalReplayPrincipals((transitionIntent?.childCascadeStarted
1975
+ ? transitionIntent.replayPrincipals
1976
+ : (replayPrincipals ?? transitionIntent?.replayPrincipals)) ?? [
1977
+ fallbackPrincipal,
1978
+ ]);
1979
+ if (beforeCommit) {
1980
+ await beforeCommit(status, async () => {
1981
+ if (!row)
1982
+ throw new RunStateUnreadableError(workflowId, runId);
1983
+ if (lifecycle?.transitionIntent?.childCascadeStarted)
1984
+ return;
1985
+ // The exact-row write decides whether the intent may fence the leg.
1986
+ // No child receives cancellation until that write succeeds.
1987
+ const existing = intentMatchesTransition ? transitionIntent : undefined;
1988
+ const intent = advanceLifecycle(lifecycle, {
1989
+ transitionIntent: {
1990
+ ...existing,
1991
+ status,
1992
+ requestedAt: existing?.requestedAt ?? now,
1993
+ replayPrincipals: principals,
1994
+ ...(cas
1995
+ ? {
1996
+ expectedRevision: cas.expectedRevision,
1997
+ expectedDeadlineAt: cas.expectedDeadlineAt,
1998
+ }
1999
+ : {}),
2000
+ childCascadeStarted: true,
2001
+ },
2002
+ });
2003
+ state = await this.#persistLifecycle(workflowId, runId, state, intent, now, source, row);
2004
+ row = {
2005
+ ...row,
2006
+ snapshot: JSON.stringify(state),
2007
+ updatedAt: new Date(now).toISOString(),
2008
+ };
2009
+ lifecycle = intent;
2010
+ });
2011
+ now = Date.now();
2012
+ }
1845
2013
  const next = projectTerminalLifecycle(lifecycle, status, now, principals);
1846
2014
  await this.#persistLifecycle(workflowId, runId, {
1847
2015
  ...state,
@@ -1901,7 +2069,7 @@ export class RunnerRuntime {
1901
2069
  const state = await this.#workflowState(workflowId, runId);
1902
2070
  if (!state)
1903
2071
  return null;
1904
- return this.#summaryFromState(runId, state);
2072
+ return this.#summaryFromState(workflowId, runId, state);
1905
2073
  }
1906
2074
  /**
1907
2075
  * status() for a caller about to CONCLUDE something irreversible from what it
@@ -1923,7 +2091,7 @@ export class RunnerRuntime {
1923
2091
  if (state.isFromInMemory === true) {
1924
2092
  throw new RunStateUnreadableError(workflowId, runId);
1925
2093
  }
1926
- return this.#summaryFromState(runId, state);
2094
+ return this.#summaryFromState(workflowId, runId, state);
1927
2095
  }
1928
2096
  async authoritativeStartState(workflowId, runId, options) {
1929
2097
  const includeLegacy = options?.includeLegacy === true;
@@ -2103,7 +2271,7 @@ export class RunnerRuntime {
2103
2271
  runId,
2104
2272
  }),
2105
2273
  snapshot,
2106
- summary: summaryFromSelectedSnapshot(runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
2274
+ summary: summaryFromSelectedSnapshot(workflowId, runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
2107
2275
  };
2108
2276
  const execution = runExecutionIdentityFor({ tablePrefix: physical.tablePrefix, workflowId, runId }, provenance);
2109
2277
  const state = snapshot.status === 'pending'
@@ -2112,7 +2280,7 @@ export class RunnerRuntime {
2112
2280
  kind: 'result',
2113
2281
  snapshot,
2114
2282
  provenance,
2115
- summary: summaryFromSelectedSnapshot(runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
2283
+ summary: summaryFromSelectedSnapshot(workflowId, runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
2116
2284
  };
2117
2285
  return physical.storage === 'd1'
2118
2286
  ? {
@@ -2221,10 +2389,12 @@ export class RunnerRuntime {
2221
2389
  }
2222
2390
  let selected = state;
2223
2391
  let transitioned = false;
2224
- let cleanup = terminalCleanupFor(lifecycleFromRequestContext(state.snapshot.requestContext));
2392
+ const lifecycle = lifecycleFromRequestContext(state.snapshot.requestContext);
2393
+ let cleanup = terminalCleanupFor(lifecycle);
2225
2394
  if (state.kind === 'initial') {
2226
2395
  if (!this.#executionFence ||
2227
2396
  state.storage !== 'd1' ||
2397
+ lifecycle?.transitionIntent?.childCascadeStarted ||
2228
2398
  state.provenance.initialAdmission !== true ||
2229
2399
  state.provenance.attemptToken !== attemptToken ||
2230
2400
  state.provenance.resumeCounts.length !== 0)
@@ -2408,6 +2578,18 @@ export class RunnerRuntime {
2408
2578
  ? withStoredRun(storedRunScope, operation)
2409
2579
  : operation();
2410
2580
  }
2581
+ #inWorkflowLeg(workflowId, runId, active, operation) {
2582
+ const key = this.#runKey(workflowId, runId);
2583
+ return activeWorkflowLeg.run({
2584
+ workflowId,
2585
+ runId,
2586
+ signal: active.run?.abortController.signal,
2587
+ isActive: () => this.#activeRuns.get(key) === active &&
2588
+ !this.#terminalAbortIntents.has(key) &&
2589
+ !active.pendingTerminal &&
2590
+ active.run?.abortController.signal.aborted === false,
2591
+ }, operation);
2592
+ }
2411
2593
  /**
2412
2594
  * @internal Settle a run whose execution leg ended without a durable outcome.
2413
2595
  *
@@ -2426,7 +2608,7 @@ export class RunnerRuntime {
2426
2608
  * Any other run becomes `failed` (`interrupted`), never re-executed: the step
2427
2609
  * that was in flight may already have had effects.
2428
2610
  */
2429
- async settleInterruptedRun(workflowId, runId, now = Date.now()) {
2611
+ async settleInterruptedRun(workflowId, runId, now = Date.now(), beforeCommit) {
2430
2612
  this.#getWorkflow(workflowId);
2431
2613
  // Checked before queueing: a live leg holds the run lock for its whole
2432
2614
  // length, and a caller waiting behind it would learn nothing.
@@ -2465,20 +2647,21 @@ export class RunnerRuntime {
2465
2647
  // The write replaces the silent row, so it is built from that row; one
2466
2648
  // that moved since the decision above waits for the next wake.
2467
2649
  const current = snapshotOfRow(silent);
2650
+ const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
2468
2651
  try {
2469
- if (recorded)
2652
+ if (current.status !== state.status ||
2653
+ currentLifecycle?.revision !== lifecycle?.revision)
2654
+ return { kind: 'live' };
2655
+ const currentRecorded = currentLifecycle?.terminal ?? currentLifecycle?.transitionIntent;
2656
+ if (recorded && !currentRecorded)
2657
+ return { kind: 'live' };
2658
+ if (currentRecorded)
2470
2659
  return {
2471
2660
  kind: 'transition',
2472
- replayPrincipal: recorded
2661
+ replayPrincipal: currentRecorded
2473
2662
  .replayPrincipals[0],
2474
- transition: await this.#transitionTerminalLocked(workflowId, runId, recorded.status, now, {}, source, { state: current, row: silent }),
2663
+ transition: await this.#transitionTerminalLocked(workflowId, runId, currentRecorded.status, now, { beforeCommit }, source, { state: current, row: silent }),
2475
2664
  };
2476
- const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
2477
- if (current.status !== state.status ||
2478
- currentLifecycle?.revision !== lifecycle?.revision ||
2479
- currentLifecycle?.terminal ||
2480
- currentLifecycle?.transitionIntent)
2481
- return { kind: 'live' };
2482
2665
  const restartAttempt = currentLifecycle?.pause?.restartAttemptToken;
2483
2666
  if (restartAttempt !== undefined) {
2484
2667
  const summary = await this.#restorePausedRestart(source, current, silent, now, restartAttempt);
@@ -2504,11 +2687,26 @@ export class RunnerRuntime {
2504
2687
  }));
2505
2688
  }
2506
2689
  /** @internal Fail a question resume after exhausting its retry budget. */
2507
- async failQuestionResume(workflowId, runId, { stepKey, suspendedAt, resumeCount, }) {
2690
+ failQuestionResume(workflowId, runId, { stepKey, suspendedAt, resumeCount, }) {
2691
+ return this.#failSuspendedRun(workflowId, runId, 'questionResumeFailedAt', matchesSuspension(stepKey, suspendedAt, resumeCount));
2692
+ }
2693
+ /** @internal Fail a child resume that could not advance its suspension. */
2694
+ failChildAwaitResume(workflowId, runId, { step, suspendedAt, resumeCount, }) {
2695
+ return this.#failSuspendedRun(workflowId, runId, 'childAwaitResumeFailedAt', matchesSuspension(step, suspendedAt, resumeCount));
2696
+ }
2697
+ /** @internal Fail an undeliverable child suspension at the leg boundary. */
2698
+ failInvalidChildAwait(workflowId, runId, invalid) {
2699
+ return this.#failSuspendedRun(workflowId, runId, 'invalidChildAwaitAt', ({ state, row }, provenance) => {
2700
+ const timestamp = new Date(state.timestamp).toISOString();
2701
+ return invalid(summaryFromSelectedSnapshot(workflowId, runId, state, row ?? { createdAt: timestamp, updatedAt: timestamp }, provenance));
2702
+ });
2703
+ }
2704
+ async #failSuspendedRun(workflowId, runId, marker, matches) {
2508
2705
  const proof = await this.#assertResumeFence(workflowId, runId);
2509
2706
  return this.#withRunLock(workflowId, runId, () => this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
2510
2707
  const source = await this.#captureWorkflowStorage(workflowId);
2511
- const { state, row } = await this.#readForTransition(source, workflowId, runId);
2708
+ const read = await this.#readForTransition(source, workflowId, runId);
2709
+ const { state, row } = read;
2512
2710
  const provenance = runProvenance(state);
2513
2711
  if (proof &&
2514
2712
  (provenance?.version !== 2 ||
@@ -2516,23 +2714,14 @@ export class RunnerRuntime {
2516
2714
  source.tablePrefix !== proof.tablePrefix))
2517
2715
  throw new RunStateUnreadableError(workflowId, runId);
2518
2716
  const lifecycle = lifecycleFromRequestContext(state.requestContext);
2519
- const result = state.context?.[stepKey];
2520
- const attempt = Array.isArray(result)
2521
- ? result.at(-1)
2522
- : result;
2523
- const counts = new Map(provenance?.resumeCounts);
2524
2717
  if (state.status !== 'suspended' ||
2525
2718
  lifecycle?.terminal ||
2526
2719
  lifecycle?.transitionIntent ||
2527
- !Object.hasOwn(state.suspendedPaths ?? {}, stepKey) ||
2528
- attempt === null ||
2529
- typeof attempt !== 'object' ||
2530
- !('suspendedAt' in attempt) ||
2531
- attempt.suspendedAt !== suspendedAt ||
2532
- (counts.get(stepKey) ?? 0) !== resumeCount)
2720
+ !matches(read, provenance))
2533
2721
  return undefined;
2534
2722
  const now = Date.now();
2535
- await this.#persistLifecycle(workflowId, runId, { ...state, ...failedByMarker('questionResumeFailedAt', now) }, advanceLifecycle(lifecycle, { questionResumeFailedAt: now }), now, source, row);
2723
+ const patch = { [marker]: now };
2724
+ await this.#persistLifecycle(workflowId, runId, { ...state, ...failedByMarker(marker, now) }, advanceLifecycle(lifecycle, patch), now, source, row);
2536
2725
  return this.#summaryAfterPersist(workflowId, runId, source, provenance);
2537
2726
  })));
2538
2727
  }
@@ -2625,7 +2814,7 @@ export class RunnerRuntime {
2625
2814
  // workflow is executing", so the scope is never client-suppliable. Provider values are partitioned into
2626
2815
  // stored application context, capabilities, and trusted identity so every
2627
2816
  // layer has an explicit order and a provider cannot replace runtime scope.
2628
- async #requestContextFor(workflowId, runId, leg, provenance, storedRequestContext, lifecycle) {
2817
+ async #requestContextFor(workflowId, runId, leg, provenance, storedRequestContext, lifecycle, lineage) {
2629
2818
  const base = {
2630
2819
  [BREAKWATER_WORKFLOW_SCOPE_KEY]: workflowId,
2631
2820
  runId,
@@ -2636,6 +2825,9 @@ export class RunnerRuntime {
2636
2825
  if (lifecycle !== undefined) {
2637
2826
  base[RUN_LIFECYCLE_CONTEXT_KEY] = lifecycle;
2638
2827
  }
2828
+ if (lineage !== undefined) {
2829
+ base[RUN_LINEAGE_CONTEXT_KEY] = lineage;
2830
+ }
2639
2831
  if (leg.kind === 'restart') {
2640
2832
  // Mastra fills missing keys from the prior snapshot.
2641
2833
  base[BREAKWATER_CONNECTOR_GRANTS_KEY] = [];
@@ -2730,7 +2922,16 @@ export class RunnerRuntime {
2730
2922
  resumeCounts: [...nextCounts],
2731
2923
  };
2732
2924
  const storedLifecycle = lifecycleFromRequestContext(state.requestContext);
2733
- const replacementDeadline = relativeDeadline(deadlineMs);
2925
+ const lineage = parseRunLineage(state.requestContext?.[RUN_LINEAGE_CONTEXT_KEY]);
2926
+ let replacementDeadline = relativeDeadline(deadlineMs);
2927
+ if (replacementDeadline !== undefined && lineage) {
2928
+ const parent = await this.authoritativeStartState(lineage.parentWorkflowId, lineage.parentRunId, { includeLegacy: true });
2929
+ if (!parent)
2930
+ throw new UnknownRunError(lineage.parentWorkflowId, lineage.parentRunId);
2931
+ const parentDeadline = lifecycleFromRequestContext(parent.snapshot.requestContext)?.deadlineAt;
2932
+ if (parentDeadline !== undefined)
2933
+ replacementDeadline = Math.min(replacementDeadline, parentDeadline);
2934
+ }
2734
2935
  const replacementOperations = canonicalEconomicOperations(economicOperations);
2735
2936
  const lifecycle = replacementDeadline === undefined && replacementOperations === undefined
2736
2937
  ? storedLifecycle
@@ -2742,7 +2943,7 @@ export class RunnerRuntime {
2742
2943
  ? {}
2743
2944
  : { economicOperations: replacementOperations }),
2744
2945
  });
2745
- const requestContext = await this.#requestContextFor(workflowId, runId, leg, provenance, undefined, lifecycle);
2946
+ const requestContext = await this.#requestContextFor(workflowId, runId, leg, provenance, undefined, lifecycle, lineage);
2746
2947
  return {
2747
2948
  nextCounts,
2748
2949
  provenance,
@@ -2827,13 +3028,13 @@ export class RunnerRuntime {
2827
3028
  const state = await this.#workflowState(workflowId, runId);
2828
3029
  if (!state)
2829
3030
  throw new UnknownRunError(workflowId, runId);
2830
- return this.#summaryFromState(runId, state);
3031
+ return this.#summaryFromState(workflowId, runId, state);
2831
3032
  }
2832
- #summaryFromState(runId, state) {
3033
+ #summaryFromState(workflowId, runId, state) {
2833
3034
  const provenance = runProvenance(state);
2834
3035
  if (state.status === 'pending' && provenance?.version === 2)
2835
3036
  throw new RunStartPendingError();
2836
- return summarizeState(runId, state, provenance);
3037
+ return summarizeState(workflowId, runId, state, provenance);
2837
3038
  }
2838
3039
  async #summaryForAttempt(workflowId, runId, expected) {
2839
3040
  try {
@@ -2859,7 +3060,7 @@ export class RunnerRuntime {
2859
3060
  if (provenance?.version !== expected.version ||
2860
3061
  provenance.attemptToken !== expected.attemptToken)
2861
3062
  return undefined;
2862
- return summarizeState(runId, persisted, provenance);
3063
+ return summarizeState(workflowId, runId, persisted, provenance);
2863
3064
  }
2864
3065
  catch {
2865
3066
  return undefined;