@atolis-hq/wake 0.4.94 → 0.4.96

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 (74) hide show
  1. package/dist/src/artifacts/application/delegation-artifacts.d.ts +26 -0
  2. package/dist/src/artifacts/application/delegation-artifacts.js +33 -0
  3. package/dist/src/artifacts/index.d.ts +1 -0
  4. package/dist/src/artifacts/index.js +1 -0
  5. package/dist/src/bootstrap/composition-root.js +16 -3
  6. package/dist/src/bootstrap/doctor-processor-health.js +19 -3
  7. package/dist/src/bootstrap/integration-runtime.d.ts +2 -1
  8. package/dist/src/bootstrap/integration-runtime.js +13 -16
  9. package/dist/src/bootstrap/poll-coordinator.d.ts +36 -0
  10. package/dist/src/bootstrap/poll-coordinator.js +93 -0
  11. package/dist/src/bootstrap/version.js +1 -1
  12. package/dist/src/control-plane/application/activation-scheduler.js +28 -43
  13. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +0 -13
  14. package/dist/src/control-plane/application/advance-once-dispatch.js +10 -24
  15. package/dist/src/control-plane/application/in-process-scheduler-serialiser.d.ts +1 -0
  16. package/dist/src/control-plane/application/in-process-scheduler-serialiser.js +15 -0
  17. package/dist/src/control-plane/application/runner-quota-outcome.d.ts +13 -0
  18. package/dist/src/control-plane/application/runner-quota-outcome.js +23 -0
  19. package/dist/src/integrations/application/adapter-health-tracker.d.ts +2 -0
  20. package/dist/src/integrations/application/adapter-health-tracker.js +3 -0
  21. package/dist/src/integrations/application/poll-service.js +4 -1
  22. package/dist/src/integrations/contracts/provider.d.ts +4 -0
  23. package/dist/src/integrations/github/infrastructure/source.js +13 -5
  24. package/dist/src/integrations/github/provider.d.ts +2 -0
  25. package/dist/src/integrations/github/provider.js +28 -2
  26. package/dist/src/orchestration/application/accept-signal.d.ts +3 -1
  27. package/dist/src/orchestration/application/accept-signal.js +2 -0
  28. package/dist/src/orchestration/application/advance-workflow.d.ts +0 -1
  29. package/dist/src/orchestration/application/advance-workflow.js +0 -4
  30. package/dist/src/orchestration/application/deferred-signals.d.ts +21 -0
  31. package/dist/src/orchestration/application/deferred-signals.js +119 -0
  32. package/dist/src/orchestration/application/delegated-work.d.ts +51 -0
  33. package/dist/src/orchestration/application/delegated-work.js +420 -0
  34. package/dist/src/orchestration/application/delegation-gate.d.ts +17 -0
  35. package/dist/src/orchestration/application/delegation-gate.js +31 -0
  36. package/dist/src/orchestration/application/delegation-ledger.d.ts +28 -0
  37. package/dist/src/orchestration/application/delegation-ledger.js +79 -0
  38. package/dist/src/orchestration/application/delegation-reservation.d.ts +15 -0
  39. package/dist/src/orchestration/application/delegation-reservation.js +54 -0
  40. package/dist/src/orchestration/application/expire-timed-out-waits.d.ts +1 -1
  41. package/dist/src/orchestration/application/expire-timed-out-waits.js +2 -2
  42. package/dist/src/orchestration/application/orchestration-projection.js +5 -1
  43. package/dist/src/orchestration/application/orchestration-repository.d.ts +5 -0
  44. package/dist/src/orchestration/application/orchestration-repository.js +69 -11
  45. package/dist/src/orchestration/application/orchestration-service.d.ts +28 -3
  46. package/dist/src/orchestration/application/orchestration-service.js +69 -20
  47. package/dist/src/orchestration/application/resource-transition-matching.js +11 -6
  48. package/dist/src/orchestration/application/start-workflow.js +4 -2
  49. package/dist/src/orchestration/application/workflow-definition-registry.d.ts +5 -1
  50. package/dist/src/orchestration/application/workflow-definition-registry.js +16 -3
  51. package/dist/src/orchestration/contracts/commands.d.ts +1 -0
  52. package/dist/src/orchestration/contracts/delegation-ports.d.ts +14 -0
  53. package/dist/src/orchestration/contracts/delegation-ports.js +1 -0
  54. package/dist/src/orchestration/contracts/delegation.d.ts +98 -0
  55. package/dist/src/orchestration/contracts/delegation.js +70 -0
  56. package/dist/src/orchestration/contracts/event-decoder.js +19 -0
  57. package/dist/src/orchestration/contracts/event-factory.js +16 -0
  58. package/dist/src/orchestration/contracts/events.d.ts +39 -0
  59. package/dist/src/orchestration/contracts/events.js +8 -0
  60. package/dist/src/orchestration/contracts/views.d.ts +8 -0
  61. package/dist/src/orchestration/domain/workflow-completion.d.ts +3 -0
  62. package/dist/src/orchestration/domain/workflow-completion.js +9 -0
  63. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +2 -0
  64. package/dist/src/orchestration/domain/workflow-instance-events.js +37 -0
  65. package/dist/src/orchestration/index.d.ts +2 -0
  66. package/dist/src/orchestration/index.js +1 -0
  67. package/dist/src/work/application/work-projection.js +3 -0
  68. package/dist/src/work/application/work-service.js +16 -0
  69. package/dist/src/work/contracts/commands.d.ts +6 -0
  70. package/dist/src/work/contracts/events.d.ts +2 -1
  71. package/dist/src/work/contracts/events.js +8 -0
  72. package/dist/src/work/contracts/views.d.ts +2 -1
  73. package/dist/src/work/domain/work-item.js +3 -0
  74. package/package.json +1 -1
@@ -6,9 +6,11 @@ export function createAdapterHealthTracker(options = {}) {
6
6
  let failureCount = 0;
7
7
  let consecutiveFailures = 0;
8
8
  let degradedDetail;
9
+ let lastSuccessAt;
9
10
  return {
10
11
  recordSuccess() {
11
12
  successCount += 1;
13
+ lastSuccessAt = now();
12
14
  consecutiveFailures = 0;
13
15
  degradedDetail = undefined;
14
16
  },
@@ -32,6 +34,7 @@ export function createAdapterHealthTracker(options = {}) {
32
34
  ...(degradedDetail === undefined ? {} : { detail: degradedDetail }),
33
35
  successCount,
34
36
  failureCount,
37
+ ...(lastSuccessAt === undefined ? {} : { lastSuccessAt }),
35
38
  };
36
39
  },
37
40
  };
@@ -13,6 +13,9 @@ export class PollService {
13
13
  let appended = 0;
14
14
  let failed = 0;
15
15
  for (const draft of drafts) {
16
+ // A run past its deadline may be leaked; it must not persist or advance state.
17
+ if (signal.aborted)
18
+ return { appended, failed: failed + 1 };
16
19
  try {
17
20
  if (!this.instance.eventTypes.includes(draft.eventType))
18
21
  throw new Error(`Provider ${adapter} emitted an unknown event type`);
@@ -28,7 +31,7 @@ export class PollService {
28
31
  console.error(`Polling ${adapter} could not persist ${draft.eventId}`, error);
29
32
  }
30
33
  }
31
- if (failed === 0)
34
+ if (failed === 0 && !signal.aborted)
32
35
  await this.instance.source.markPollPersisted?.();
33
36
  return { appended, failed };
34
37
  }
@@ -55,6 +55,8 @@ export interface AdapterHealthCheck {
55
55
  readonly detail?: string;
56
56
  readonly successCount: number;
57
57
  readonly failureCount: number;
58
+ /** Epoch milliseconds of the latest success, for adapters that derive stall from it. */
59
+ readonly lastSuccessAt?: number;
58
60
  }
59
61
  export interface AdapterCommand {
60
62
  readonly syntax: string;
@@ -77,6 +79,8 @@ export interface ProviderInstance {
77
79
  }): Promise<VerifiedArtifact | ArtifactVerificationResult>;
78
80
  readonly checkConnectivity?: () => Promise<void>;
79
81
  readonly health?: () => readonly AdapterHealthCheck[];
82
+ /** Lets the poll runner report whole-poll failures (lock contention, timeouts) as health. */
83
+ readonly recordPollFailure?: (error: unknown) => void;
80
84
  readonly commands?: () => readonly AdapterCommand[];
81
85
  readonly replyPublication?: ReplyPublicationConfig | undefined;
82
86
  readonly webhook?: ProviderWebhook | undefined;
@@ -15,12 +15,16 @@ export function createGitHubSource(config, client, adapter, requests = createGit
15
15
  // This cache avoids returning unchanged issue observations within one process.
16
16
  const lastEventIds = new Map();
17
17
  const pendingWatermarks = new Map();
18
+ let pendingSignal;
18
19
  const now = state?.now ?? Date.now;
19
20
  // In-memory only: an extra real poll after a process restart is harmless,
20
21
  // the same tradeoff already made for lastEventIds above.
21
22
  let lastPolledAt;
22
23
  return {
23
24
  async poll(signal, options) {
25
+ // Uncommitted cursors belong only to the attempt that produced them.
26
+ pendingWatermarks.clear();
27
+ pendingSignal = undefined;
24
28
  const currentTime = now();
25
29
  if (options?.bypassInterval !== true &&
26
30
  lastPolledAt !== undefined &&
@@ -38,10 +42,13 @@ export function createGitHubSource(config, client, adapter, requests = createGit
38
42
  watermark: await loadWatermark(state?.checkpoints, adapter, owner, repo),
39
43
  health,
40
44
  })));
45
+ const drafts = await consecutivePullRequestObservations(perRepository.flatMap((result) => result.drafts), state?.journal, adapter);
46
+ // Journal reads can outlive the deadline too; never publish leaked cursors.
47
+ signal.throwIfAborted();
48
+ pendingSignal = signal;
41
49
  for (const result of perRepository)
42
50
  if (result.watermark !== undefined)
43
51
  pendingWatermarks.set(result.repository, result.watermark);
44
- const drafts = await consecutivePullRequestObservations(perRepository.flatMap((result) => result.drafts), state?.journal, adapter);
45
52
  return drafts.filter((draft) => {
46
53
  if (draft.eventType !== GitHubEventType.WorkObserved)
47
54
  return true;
@@ -53,13 +60,14 @@ export function createGitHubSource(config, client, adapter, requests = createGit
53
60
  });
54
61
  },
55
62
  async markPollPersisted() {
56
- if (state?.checkpoints === undefined)
63
+ if (state?.checkpoints === undefined || pendingSignal?.aborted === true)
57
64
  return;
58
65
  const checkpoints = state.checkpoints;
59
- for (const [repository, watermark] of pendingWatermarks) {
66
+ // Detach before awaiting saves: a deadline may let the next attempt start.
67
+ const committed = [...pendingWatermarks];
68
+ pendingWatermarks.clear();
69
+ for (const [repository, watermark] of committed)
60
70
  await checkpoints.save(watermarkCheckpoint(adapter, repository), watermark);
61
- pendingWatermarks.delete(repository);
62
- }
63
71
  },
64
72
  };
65
73
  }
@@ -1,3 +1,5 @@
1
1
  import { type ProviderDefinition } from '../contracts/provider.js';
2
2
  import { type GitHubConfig } from './contracts/config.js';
3
3
  export declare const gitHubProviderDefinition: ProviderDefinition<GitHubConfig>;
4
+ /** Multiple of the poll interval without a success before observation counts as stalled. */
5
+ export declare const POLL_STALL_INTERVALS = 3;
@@ -2,7 +2,7 @@ import { BuiltInActivityName, PullRequestState } from '../../activities/index.js
2
2
  import { ConversationSurfaceCapability } from '../../orchestration/index.js';
3
3
  import { BuiltInResourceCapability, BuiltInResourceKind, ResourceCorrelationRole, resourceId, resourceKind, } from '../../resources/index.js';
4
4
  import { ArtifactVerificationResult } from '../contracts/artifact-vocabulary.js';
5
- import { AdapterHealthStatus } from '../contracts/provider.js';
5
+ import { AdapterHealthStatus, } from '../contracts/provider.js';
6
6
  import { InboundTranslator } from './application/inbound-translator.js';
7
7
  import { translateGitHubOutbound } from './application/outbound-translator.js';
8
8
  import { createGitHubWakeLabelReconciler } from './application/wake-labels.js';
@@ -31,6 +31,7 @@ export const gitHubProviderDefinition = {
31
31
  maxConcurrent: config.polling.maxConcurrent,
32
32
  });
33
33
  const health = createGitHubAdapterHealthRegistry(config.repositories);
34
+ const healthStartedAt = Date.now();
34
35
  const inbound = new InboundTranslator(services.journal, services.work, services.resources, {
35
36
  pullRequests: services.pullRequests,
36
37
  ids: services.ids,
@@ -61,7 +62,17 @@ export const gitHubProviderDefinition = {
61
62
  setLabels: client.setIssueLabels,
62
63
  requests,
63
64
  }),
64
- health: () => health.snapshotAll().flatMap((check) => {
65
+ recordPollFailure: (error) => {
66
+ for (const { owner, repo } of config.repositories)
67
+ health.recordFailure(`${owner}/${repo}`, 'poll', error);
68
+ },
69
+ health: () => health.snapshotAll().flatMap(({ lastSuccessAt, ...check }) => {
70
+ // A process that never polled (standalone UI/API host) cannot judge a stall;
71
+ // the intake-owning process reports it.
72
+ if (check.channel === 'poll' && check.successCount + check.failureCount > 0)
73
+ return [
74
+ applyPollStall(check, lastSuccessAt ?? healthStartedAt, Date.now(), config.polling.intervalMs),
75
+ ];
65
76
  if (check.channel !== 'webhook')
66
77
  return [check];
67
78
  if (!config.webhooks.enabled)
@@ -197,6 +208,21 @@ export const gitHubProviderDefinition = {
197
208
  };
198
209
  },
199
210
  };
211
+ /** Multiple of the poll interval without a success before observation counts as stalled. */
212
+ export const POLL_STALL_INTERVALS = 3;
213
+ // Derived at read time so a wedged process cannot keep reporting a stale "ok".
214
+ function applyPollStall(check, lastProgressAt, nowMs, intervalMs) {
215
+ const silentMs = nowMs - lastProgressAt;
216
+ const thresholdMs = intervalMs * POLL_STALL_INTERVALS;
217
+ if (silentMs <= thresholdMs)
218
+ return check;
219
+ const stalled = `stalled: no successful poll for ${Math.round(silentMs / 1000)}s (threshold ${Math.round(thresholdMs / 1000)}s)`;
220
+ return {
221
+ ...check,
222
+ status: 'degraded',
223
+ detail: check.detail === undefined ? stalled : `${stalled}; ${check.detail}`,
224
+ };
225
+ }
200
226
  function parsePullRequestKey(key) {
201
227
  const match = /^(?<owner>[^/]+)\/(?<repo>[^#]+)#(?<number>[1-9]\d*)$/.exec(key);
202
228
  if (match?.groups === undefined)
@@ -10,5 +10,7 @@ export declare class AcceptSignal {
10
10
  private readonly work;
11
11
  constructor(repository: OrchestrationRepository, workflows: StartWorkflow, work: WorkService);
12
12
  wait(workflowInstanceId: WorkflowInstanceId, expectation: SignalExpectation, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView>;
13
- execute(workflowInstanceId: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView>;
13
+ execute(workflowInstanceId: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext & {
14
+ readonly expectedSequence?: number;
15
+ }): Promise<import("../index.js").WorkflowInstanceView>;
14
16
  }
@@ -21,6 +21,8 @@ export class AcceptSignal {
21
21
  }
22
22
  async execute(workflowInstanceId, signal, context) {
23
23
  const loaded = await this.repository.loadRequired(workflowInstanceId);
24
+ if (context.expectedSequence !== undefined && context.expectedSequence !== loaded.sequence)
25
+ return loaded.view;
24
26
  const expiry = expireTimedOutAwait(loaded.view, {
25
27
  occurredAt: context.occurredAt,
26
28
  causationId: context.commandId,
@@ -22,7 +22,6 @@ export declare class AdvanceWorkflow {
22
22
  markActivationStarted(id: WorkflowInstanceId, activationId: ActivationId, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
23
23
  blockAwaitingActivation(id: WorkflowInstanceId, activationId: ActivationId, reason: string, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
24
24
  block(id: WorkflowInstanceId, reason: string, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
25
- expireTimedOutWaits(context: CommandContext): Promise<import("../index.js").WorkflowInstanceView[]>;
26
25
  resolveExecutionFailure(id: WorkflowInstanceId, input: ExecutionFailureInput, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
27
26
  retryRunnerQuotaFailure(id: WorkflowInstanceId, input: {
28
27
  readonly activationId: ActivationId;
@@ -6,7 +6,6 @@ import { workflowEventData } from '../domain/decision-events.js';
6
6
  import { requestChangesResume as decideChangesResume, requestFreshOperatorRetry as decideFreshOperatorRetry, requestOperatorRetry as decideOperatorRetry, requestSupplementalActivity as decideSupplementalActivity, isNeedsClarificationResumeEligible, requestRunnerQuotaRetry, } from '../domain/interpreter.js';
7
7
  import { isAuthorisedActor } from '../domain/supplemental-policy.js';
8
8
  import { appendWithIntentRecovery } from './durable-append.js';
9
- import { expireTimedOutWaits } from './expire-timed-out-waits.js';
10
9
  import { attributeOperatorRetry } from './operator-retry-attribution.js';
11
10
  import { prioritisePendingActivations, } from './pending-activations.js';
12
11
  import { resolveExecutionFailure, } from './resolve-execution-failure.js';
@@ -94,9 +93,6 @@ export class AdvanceWorkflow {
94
93
  await this.repository.append(id, loaded.sequence, [event]);
95
94
  return (await this.repository.load(id)).view;
96
95
  }
97
- async expireTimedOutWaits(context) {
98
- return expireTimedOutWaits(this.repository, context);
99
- }
100
96
  resolveExecutionFailure(id, input, context) {
101
97
  return resolveExecutionFailure(this.repository, this.acceptOutcome, id, input, context);
102
98
  }
@@ -0,0 +1,21 @@
1
+ import { type CommandContext } from '@atolis-hq/eventing';
2
+ import type { TransitionTarget } from '../contracts/config.js';
3
+ import { type OrchestrationSignal } from '../contracts/events.js';
4
+ import type { WorkflowInstanceId } from '../contracts/identifiers.js';
5
+ import type { WorkflowInstanceView } from '../contracts/views.js';
6
+ import type { OrchestrationRepository } from './orchestration-repository.js';
7
+ /** Retains authority-bearing inputs while delegation owns advancement; ordinary wait validation replays them. */
8
+ export declare class DeferredSignals {
9
+ private readonly repository;
10
+ private readonly deliver;
11
+ private readonly transition;
12
+ private readonly fenced;
13
+ private readonly ledger;
14
+ constructor(repository: OrchestrationRepository, deliver: (id: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext) => Promise<WorkflowInstanceView>, transition: (id: WorkflowInstanceId, target: TransitionTarget, evidenceId: string, context: CommandContext) => Promise<WorkflowInstanceView | null>, fenced: (id: WorkflowInstanceId) => Promise<boolean>);
15
+ accept(id: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext): Promise<WorkflowInstanceView>;
16
+ applyTransition(id: WorkflowInstanceId, target: TransitionTarget, evidenceId: string, context: CommandContext): Promise<WorkflowInstanceView | null>;
17
+ private record;
18
+ private hasDeferred;
19
+ reconcile(context: CommandContext): Promise<void>;
20
+ reconcileWorkflow(id: WorkflowInstanceId, context: CommandContext): Promise<WorkflowInstanceView>;
21
+ }
@@ -0,0 +1,119 @@
1
+ import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
2
+ import { DelegationPendingError } from '../contracts/delegation.js';
3
+ import { signalSchema } from '../contracts/event-decoder.js';
4
+ import { OrchestrationEventType, ResourceTransitionSignal, } from '../contracts/events.js';
5
+ import { DelegationLedger } from './delegation-ledger.js';
6
+ /** Retains authority-bearing inputs while delegation owns advancement; ordinary wait validation replays them. */
7
+ export class DeferredSignals {
8
+ repository;
9
+ deliver;
10
+ transition;
11
+ fenced;
12
+ ledger;
13
+ constructor(repository, deliver, transition, fenced) {
14
+ this.repository = repository;
15
+ this.deliver = deliver;
16
+ this.transition = transition;
17
+ this.fenced = fenced;
18
+ this.ledger = new DelegationLedger(repository);
19
+ }
20
+ async accept(id, signal, context) {
21
+ const scope = (await this.repository.loadRequired(id)).view;
22
+ try {
23
+ return await this.deliver(id, signal, context);
24
+ }
25
+ catch (error) {
26
+ if (!(error instanceof DelegationPendingError))
27
+ throw error;
28
+ return this.record(id, signal, context, scope);
29
+ }
30
+ }
31
+ async applyTransition(id, target, evidenceId, context) {
32
+ const scope = (await this.repository.loadRequired(id)).view;
33
+ try {
34
+ return await this.transition(id, target, evidenceId, context);
35
+ }
36
+ catch (error) {
37
+ if (!(error instanceof DelegationPendingError))
38
+ throw error;
39
+ return this.record(id, {
40
+ kind: scope.waitingFor?.signalKind ?? ResourceTransitionSignal,
41
+ actorId: 'resource-transition',
42
+ actorDecision: { authorized: true, evidenceId },
43
+ providerEventId: evidenceId,
44
+ }, context, scope, target);
45
+ }
46
+ }
47
+ async record(id, signal, context, view, target) {
48
+ const parsed = signalSchema.parse(signal);
49
+ await this.ledger.appendOnce(id, context, `defer:${signal.providerEventId}`, {
50
+ eventType: OrchestrationEventType.SignalDeferred,
51
+ payload: {
52
+ stage: view.currentStage,
53
+ ...(view.waitingFor?.intentEventId === undefined
54
+ ? {}
55
+ : { intentEventId: view.waitingFor.intentEventId }),
56
+ ...(view.waitingFor?.resourceId === undefined
57
+ ? {}
58
+ : { resourceId: view.waitingFor.resourceId }),
59
+ ...(view.waitingFor?.revision === undefined ? {} : { revision: view.waitingFor.revision }),
60
+ signal: parsed,
61
+ ...(target === undefined ? {} : { target }),
62
+ },
63
+ });
64
+ return view;
65
+ }
66
+ async hasDeferred() {
67
+ return (await this.repository.events()).some((entry) => entry.event.eventType === OrchestrationEventType.SignalDeferred);
68
+ }
69
+ async reconcile(context) {
70
+ if (!(await this.hasDeferred()))
71
+ return;
72
+ for (const loaded of await this.repository.list()) {
73
+ if (loaded.view !== null)
74
+ await this.reconcileWorkflow(loaded.view.workflowInstanceId, context);
75
+ }
76
+ }
77
+ async reconcileWorkflow(id, context) {
78
+ if ((await this.hasDeferred()) && !(await this.fenced(id))) {
79
+ const { events } = await this.repository.history(id);
80
+ for (const event of events) {
81
+ if (event?.event.eventType !== OrchestrationEventType.SignalDeferred)
82
+ continue;
83
+ const deferred = event.event.payload;
84
+ const loaded = await this.repository.loadRequired(id);
85
+ const view = loaded.view;
86
+ if (!matchesDeferredWait(view, deferred))
87
+ continue;
88
+ const deliveryContext = {
89
+ ...context,
90
+ commandId: `replay:${event.event.eventId}`,
91
+ expectedSequence: loaded.sequence,
92
+ correlationId: event.event.correlationId,
93
+ actor: event.event.actor,
94
+ };
95
+ try {
96
+ if (deferred.target === undefined)
97
+ await this.deliver(id, deferred.signal, deliveryContext);
98
+ else
99
+ await this.transition(id, deferred.target, deferred.signal.providerEventId, deliveryContext);
100
+ }
101
+ catch (error) {
102
+ if (!(error instanceof DelegationPendingError) &&
103
+ !(error instanceof WrongExpectedSequenceError))
104
+ throw error;
105
+ break;
106
+ }
107
+ }
108
+ }
109
+ return (await this.repository.loadRequired(id)).view;
110
+ }
111
+ }
112
+ function matchesDeferredWait(view, deferred) {
113
+ return (!view.acceptedSignalIds.includes(deferred.signal.providerEventId) &&
114
+ view.currentStage === deferred.stage &&
115
+ view.waitingFor !== undefined &&
116
+ view.waitingFor.intentEventId === deferred.intentEventId &&
117
+ view.waitingFor.resourceId === deferred.resourceId &&
118
+ view.waitingFor.revision === deferred.revision);
119
+ }
@@ -0,0 +1,51 @@
1
+ import { type CommandContext } from '@atolis-hq/eventing';
2
+ import { type WorkService } from '../../work/index.js';
3
+ import type { DelegationArtifacts } from '../contracts/delegation-ports.js';
4
+ import type { DelegatedAssignment, DelegationCaller, DelegationLimits, DelegationReservation, DelegationResult } from '../contracts/delegation.js';
5
+ import { type WorkflowInstanceId } from '../contracts/identifiers.js';
6
+ import type { WorkflowInstanceView } from '../contracts/views.js';
7
+ import type { CoordinationClaims } from './coordination-claims.js';
8
+ import type { OrchestrationRepository } from './orchestration-repository.js';
9
+ import type { StartWorkflow } from './start-workflow.js';
10
+ import type { WorkflowDefinitionRegistry } from './workflow-definition-registry.js';
11
+ /**
12
+ * Durable delegation of independent child WorkItems. Reservation is the single commit point;
13
+ * every later boundary is reconciled idempotently from it, and the parent stays fenced until join.
14
+ */
15
+ export declare class DelegatedWork {
16
+ private readonly repository;
17
+ private readonly work;
18
+ private readonly claims;
19
+ private readonly definitions;
20
+ private readonly workflows;
21
+ private readonly ledger;
22
+ private readonly artifacts;
23
+ private readonly runHasEnded;
24
+ constructor(repository: OrchestrationRepository, work: WorkService, claims: CoordinationClaims, definitions: WorkflowDefinitionRegistry, workflows: StartWorkflow, dependencies: {
25
+ readonly artifacts: DelegationArtifacts;
26
+ readonly runHasEnded: (runId: string) => Promise<boolean>;
27
+ });
28
+ contextWorkItems(parent: WorkflowInstanceView): Promise<ReadonlySet<string>>;
29
+ results(id: WorkflowInstanceId, cohortId: string): Promise<readonly DelegationResult[]>;
30
+ reserve(caller: DelegationCaller, cohortId: string, assignments: readonly DelegatedAssignment[], context: CommandContext, limits?: DelegationLimits): Promise<DelegationReservation>;
31
+ reconcile(context: CommandContext): Promise<void>;
32
+ private capacityReservations;
33
+ private parentIdentity;
34
+ private assertReservable;
35
+ /** Validates inputs and pins the selected definition before anything is committed. */
36
+ private prepareChild;
37
+ /** Appends the reservation only if the root stream is unchanged since `events` was read. */
38
+ private commit;
39
+ private reconcileReservation;
40
+ private ensureWait;
41
+ private fail;
42
+ /** WorkItem, primary claim and artifact grant are each idempotent; none starts a workflow. */
43
+ private registerChildren;
44
+ /** Starts the pinned definition, then records the result only once the child qualifies. */
45
+ private advanceChild;
46
+ private childWorkTerminated;
47
+ private missingOutputs;
48
+ private endedRun;
49
+ /** Join and continuation commit together, so a duplicate trigger cannot resume the parent twice. */
50
+ private join;
51
+ }