@atolis-hq/wake 0.4.95 → 0.4.97

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 (107) hide show
  1. package/dist/src/activities/agent/agent-activity.js +12 -1
  2. package/dist/src/activities/agent/agent-result.d.ts +1 -0
  3. package/dist/src/activities/agent/agent-result.js +1 -0
  4. package/dist/src/activities/contracts/activity.d.ts +7 -0
  5. package/dist/src/artifacts/application/delegation-artifacts.d.ts +29 -0
  6. package/dist/src/artifacts/application/delegation-artifacts.js +37 -0
  7. package/dist/src/artifacts/index.d.ts +1 -0
  8. package/dist/src/artifacts/index.js +1 -0
  9. package/dist/src/bootstrap/composition-root.d.ts +6 -1
  10. package/dist/src/bootstrap/composition-root.js +50 -12
  11. package/dist/src/bootstrap/version.js +1 -1
  12. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +3 -1
  13. package/dist/src/control-plane/application/activation-scheduler.js +28 -43
  14. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +1 -14
  15. package/dist/src/control-plane/application/advance-once-dispatch.js +14 -26
  16. package/dist/src/control-plane/application/dispatch-resources.d.ts +4 -0
  17. package/dist/src/control-plane/application/dispatch-resources.js +13 -0
  18. package/dist/src/control-plane/application/in-process-scheduler-serialiser.d.ts +1 -0
  19. package/dist/src/control-plane/application/in-process-scheduler-serialiser.js +15 -0
  20. package/dist/src/control-plane/application/runner-quota-outcome.d.ts +13 -0
  21. package/dist/src/control-plane/application/runner-quota-outcome.js +23 -0
  22. package/dist/src/execution/application/execution-service.js +27 -5
  23. package/dist/src/execution/application/execution-validation.d.ts +6 -1
  24. package/dist/src/execution/application/execution-validation.js +29 -11
  25. package/dist/src/execution/application/repository-assignments.d.ts +11 -0
  26. package/dist/src/execution/application/repository-assignments.js +18 -0
  27. package/dist/src/execution/application/run-lifecycle.d.ts +1 -0
  28. package/dist/src/execution/application/run-lifecycle.js +30 -10
  29. package/dist/src/execution/contracts/commands.d.ts +2 -0
  30. package/dist/src/execution/contracts/events.d.ts +20 -0
  31. package/dist/src/execution/contracts/events.js +9 -0
  32. package/dist/src/execution/contracts/repository-assignment.d.ts +17 -0
  33. package/dist/src/execution/contracts/repository-assignment.js +9 -0
  34. package/dist/src/execution/contracts/views.d.ts +5 -0
  35. package/dist/src/execution/contracts/workspace.d.ts +6 -0
  36. package/dist/src/execution/domain/run.js +9 -0
  37. package/dist/src/execution/index.d.ts +3 -0
  38. package/dist/src/execution/index.js +3 -0
  39. package/dist/src/execution/infrastructure/workspace/git-source.d.ts +6 -0
  40. package/dist/src/execution/infrastructure/workspace/git-source.js +35 -0
  41. package/dist/src/execution/infrastructure/workspace/git-workspace.d.ts +5 -0
  42. package/dist/src/execution/infrastructure/workspace/git-workspace.js +50 -3
  43. package/dist/src/integrations/application/artifact-registration-reactor.d.ts +6 -0
  44. package/dist/src/integrations/application/artifact-registration-reactor.js +35 -11
  45. package/dist/src/integrations/application/artifact-source.d.ts +9 -0
  46. package/dist/src/integrations/application/artifact-source.js +12 -0
  47. package/dist/src/integrations/application/delegation-outputs.d.ts +15 -0
  48. package/dist/src/integrations/application/delegation-outputs.js +118 -0
  49. package/dist/src/integrations/contracts/provider.d.ts +3 -0
  50. package/dist/src/integrations/fake/external-source.d.ts +1 -0
  51. package/dist/src/integrations/fake/inbound-translator.js +1 -0
  52. package/dist/src/integrations/fake/provider.d.ts +1 -0
  53. package/dist/src/integrations/fake/provider.js +11 -2
  54. package/dist/src/integrations/github/provider.js +7 -1
  55. package/dist/src/integrations/index.d.ts +1 -0
  56. package/dist/src/integrations/index.js +1 -0
  57. package/dist/src/orchestration/application/accept-signal.d.ts +3 -1
  58. package/dist/src/orchestration/application/accept-signal.js +2 -0
  59. package/dist/src/orchestration/application/advance-workflow.d.ts +0 -1
  60. package/dist/src/orchestration/application/advance-workflow.js +0 -4
  61. package/dist/src/orchestration/application/deferred-signals.d.ts +21 -0
  62. package/dist/src/orchestration/application/deferred-signals.js +119 -0
  63. package/dist/src/orchestration/application/delegated-work.d.ts +60 -0
  64. package/dist/src/orchestration/application/delegated-work.js +456 -0
  65. package/dist/src/orchestration/application/delegation-gate.d.ts +17 -0
  66. package/dist/src/orchestration/application/delegation-gate.js +31 -0
  67. package/dist/src/orchestration/application/delegation-ledger.d.ts +28 -0
  68. package/dist/src/orchestration/application/delegation-ledger.js +79 -0
  69. package/dist/src/orchestration/application/delegation-reservation.d.ts +15 -0
  70. package/dist/src/orchestration/application/delegation-reservation.js +77 -0
  71. package/dist/src/orchestration/application/expire-timed-out-waits.d.ts +1 -1
  72. package/dist/src/orchestration/application/expire-timed-out-waits.js +2 -2
  73. package/dist/src/orchestration/application/orchestration-projection.js +5 -1
  74. package/dist/src/orchestration/application/orchestration-repository.d.ts +5 -0
  75. package/dist/src/orchestration/application/orchestration-repository.js +69 -11
  76. package/dist/src/orchestration/application/orchestration-service.d.ts +43 -3
  77. package/dist/src/orchestration/application/orchestration-service.js +73 -20
  78. package/dist/src/orchestration/application/resource-transition-matching.js +11 -6
  79. package/dist/src/orchestration/application/start-workflow.js +4 -2
  80. package/dist/src/orchestration/application/workflow-definition-registry.d.ts +5 -1
  81. package/dist/src/orchestration/application/workflow-definition-registry.js +16 -3
  82. package/dist/src/orchestration/contracts/commands.d.ts +1 -0
  83. package/dist/src/orchestration/contracts/delegation-ports.d.ts +19 -0
  84. package/dist/src/orchestration/contracts/delegation-ports.js +1 -0
  85. package/dist/src/orchestration/contracts/delegation.d.ts +143 -0
  86. package/dist/src/orchestration/contracts/delegation.js +115 -0
  87. package/dist/src/orchestration/contracts/event-decoder.js +19 -0
  88. package/dist/src/orchestration/contracts/event-factory.js +16 -0
  89. package/dist/src/orchestration/contracts/events.d.ts +39 -0
  90. package/dist/src/orchestration/contracts/events.js +8 -0
  91. package/dist/src/orchestration/contracts/views.d.ts +8 -0
  92. package/dist/src/orchestration/contracts/vocabulary.d.ts +3 -0
  93. package/dist/src/orchestration/contracts/vocabulary.js +1 -0
  94. package/dist/src/orchestration/domain/workflow-completion.d.ts +3 -0
  95. package/dist/src/orchestration/domain/workflow-completion.js +9 -0
  96. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +2 -0
  97. package/dist/src/orchestration/domain/workflow-instance-events.js +37 -0
  98. package/dist/src/orchestration/index.d.ts +2 -0
  99. package/dist/src/orchestration/index.js +1 -0
  100. package/dist/src/work/application/work-projection.js +3 -0
  101. package/dist/src/work/application/work-service.js +16 -0
  102. package/dist/src/work/contracts/commands.d.ts +6 -0
  103. package/dist/src/work/contracts/events.d.ts +2 -1
  104. package/dist/src/work/contracts/events.js +8 -0
  105. package/dist/src/work/contracts/views.d.ts +2 -1
  106. package/dist/src/work/domain/work-item.js +3 -0
  107. package/package.json +1 -1
@@ -0,0 +1,60 @@
1
+ import { type CommandContext } from '@atolis-hq/eventing';
2
+ import { type WorkService } from '../../work/index.js';
3
+ import type { DelegationArtifacts, DelegationRepositories } 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 repositories;
24
+ private readonly runHasEnded;
25
+ constructor(repository: OrchestrationRepository, work: WorkService, claims: CoordinationClaims, definitions: WorkflowDefinitionRegistry, workflows: StartWorkflow, dependencies: {
26
+ readonly artifacts: DelegationArtifacts;
27
+ readonly repositories?: DelegationRepositories | undefined;
28
+ readonly runHasEnded: (runId: string) => Promise<boolean>;
29
+ });
30
+ repositoryFor(workItemId: string): Promise<{
31
+ resourceId: string;
32
+ sourceRef: string;
33
+ pullRequestBase: string;
34
+ sourceRevision: string;
35
+ } | undefined>;
36
+ contextWorkItems(parent: WorkflowInstanceView): Promise<ReadonlySet<string>>;
37
+ results(id: WorkflowInstanceId, cohortId: string): Promise<readonly DelegationResult[]>;
38
+ reserve(caller: DelegationCaller, cohortId: string, assignments: readonly DelegatedAssignment[], context: CommandContext, limits?: DelegationLimits): Promise<DelegationReservation>;
39
+ private pinAssignments;
40
+ reconcile(context: CommandContext): Promise<void>;
41
+ private capacityReservations;
42
+ private parentIdentity;
43
+ private assertReservable;
44
+ /** Validates inputs and pins the selected definition before anything is committed. */
45
+ private prepareChild;
46
+ /** Appends the reservation only if the root stream is unchanged since `events` was read. */
47
+ private commit;
48
+ private reconcileReservation;
49
+ private ensureWait;
50
+ private fail;
51
+ /** WorkItem, primary claim and artifact grant are each idempotent; none starts a workflow. */
52
+ private registerChildren;
53
+ /** Starts the pinned definition, then records the result only once the child qualifies. */
54
+ private advanceChild;
55
+ private childWorkTerminated;
56
+ private missingOutputs;
57
+ private endedRun;
58
+ /** Join and continuation commit together, so a duplicate trigger cannot resume the parent twice. */
59
+ private join;
60
+ }
@@ -0,0 +1,456 @@
1
+ /* eslint-disable max-lines */
2
+ import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
3
+ import { activationId } from '../../activities/index.js';
4
+ import { WorkspaceMode } from '../../execution/index.js';
5
+ import { WorkStatus } from '../../work/index.js';
6
+ import { OrchestrationEventType } from '../contracts/events.js';
7
+ import { orchestrationGroupId, workflowInstanceId, } from '../contracts/identifiers.js';
8
+ import { WorkflowStatus } from '../contracts/vocabulary.js';
9
+ import { nextOrdinal } from '../domain/decision-events.js';
10
+ import { isSuccessfulWorkflowCompletion } from '../domain/workflow-completion.js';
11
+ import { delegationDraft, delegationEventId, DelegationLedger, isJoined, isSettled, reservationsOf, reservedEvent, selectedResults, } from './delegation-ledger.js';
12
+ import { assertWithinRootLimits, buildReservation, matchesAssignments, } from './delegation-reservation.js';
13
+ const defaultLimits = { maxDepth: 1, maxDescendants: 8 };
14
+ /**
15
+ * Durable delegation of independent child WorkItems. Reservation is the single commit point;
16
+ * every later boundary is reconciled idempotently from it, and the parent stays fenced until join.
17
+ */
18
+ export class DelegatedWork {
19
+ repository;
20
+ work;
21
+ claims;
22
+ definitions;
23
+ workflows;
24
+ ledger;
25
+ artifacts;
26
+ repositories;
27
+ runHasEnded;
28
+ constructor(repository, work, claims, definitions, workflows, dependencies) {
29
+ this.repository = repository;
30
+ this.work = work;
31
+ this.claims = claims;
32
+ this.definitions = definitions;
33
+ this.workflows = workflows;
34
+ this.ledger = new DelegationLedger(repository);
35
+ this.artifacts = dependencies.artifacts;
36
+ this.repositories = dependencies.repositories;
37
+ this.runHasEnded = dependencies.runHasEnded;
38
+ }
39
+ async repositoryFor(workItemId) {
40
+ return (await this.ledger.reservations())
41
+ .flatMap((entry) => entry.children)
42
+ .find((child) => child.workItemId === workItemId)?.repository;
43
+ }
44
+ async contextWorkItems(parent) {
45
+ const item = await this.work.get(parent.workItemId);
46
+ const allowed = new Set([parent.workItemId, ...(item?.delegation?.ancestors ?? [])]);
47
+ for (const reservation of await this.ledger.reservations())
48
+ if (reservation.parentWorkItemId === parent.workItemId)
49
+ for (const child of reservation.children)
50
+ allowed.add(child.workItemId);
51
+ return allowed;
52
+ }
53
+ async results(id, cohortId) {
54
+ const events = await this.ledger.events();
55
+ const joined = events.find((entry) => entry.stream.id === id &&
56
+ entry.event.eventType === OrchestrationEventType.DelegationJoined &&
57
+ entry.event.payload.cohortId === cohortId);
58
+ return joined?.event.eventType === OrchestrationEventType.DelegationJoined
59
+ ? joined.event.payload.results
60
+ : [];
61
+ }
62
+ async reserve(caller, cohortId, assignments, context, limits = defaultLimits) {
63
+ const artifacts = this.artifacts;
64
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
65
+ const identity = await this.parentIdentity(parent);
66
+ const prior = (await this.ledger.reservations()).find((entry) => entry.rootWorkItemId === identity.parent.rootWorkItemId && entry.cohortId === cohortId);
67
+ if (prior !== undefined) {
68
+ assertReplay(prior, caller, assignments);
69
+ await this.reconcile(context);
70
+ return prior;
71
+ }
72
+ const pinned = await this.pinAssignments(parent, assignments);
73
+ let reservation = buildReservation(identity.parent, caller, cohortId, pinned, limits);
74
+ for (let attempt = 0; attempt < 8; attempt++) {
75
+ const { events: rootFacts, sequence } = await this.repository.history(identity.root);
76
+ const events = await this.ledger.events();
77
+ const all = reservationsOf(rootFacts).filter((entry) => entry.rootWorkItemId === reservation.rootWorkItemId);
78
+ const rootLimits = {
79
+ maxDepth: all[0]?.maxDepth ?? limits.maxDepth,
80
+ maxDescendants: all[0]?.maxDescendants ?? limits.maxDescendants,
81
+ };
82
+ reservation = buildReservation(identity.parent, caller, cohortId, pinned, rootLimits);
83
+ const prior = all.find((entry) => entry.cohortId === cohortId);
84
+ if (prior !== undefined) {
85
+ assertReplay(prior, caller, assignments);
86
+ await this.reconcile(context);
87
+ return prior;
88
+ }
89
+ await this.assertReservable(caller, await this.capacityReservations(all, events), reservation, rootLimits);
90
+ for (const child of reservation.children)
91
+ await this.prepareChild(artifacts, parent, child, context);
92
+ if (await this.commit(identity.root, sequence, reservation, context)) {
93
+ await this.reconcile(context);
94
+ return reservation;
95
+ }
96
+ }
97
+ throw new Error('Delegation reservation contention exceeded retry limit');
98
+ }
99
+ async pinAssignments(parent, assignments) {
100
+ return Promise.all(assignments.map(async (assignment) => {
101
+ if (assignment.repository === undefined)
102
+ return assignment;
103
+ if (this.repositories === undefined)
104
+ throw new Error('Delegation repository resolver unavailable');
105
+ return {
106
+ ...assignment,
107
+ repository: await this.repositories.resolve(parent, assignment.repository),
108
+ };
109
+ }));
110
+ }
111
+ async reconcile(context) {
112
+ const all = await this.ledger.reservations();
113
+ if (all.length === 0)
114
+ return;
115
+ const events = await this.ledger.events();
116
+ const reservations = all.filter((reservation) => !isSettled(events, reservation));
117
+ if (reservations.length === 0)
118
+ return;
119
+ const artifacts = this.artifacts;
120
+ for (const reservation of reservations) {
121
+ try {
122
+ await this.reconcileReservation(artifacts, reservation, context);
123
+ }
124
+ catch (error) {
125
+ // Registration faults remain retryable, but cannot interrupt other cohorts or watch children.
126
+ const reason = error instanceof Error && error.message.length > 0
127
+ ? error.message
128
+ : 'Delegation reconciliation failed';
129
+ const reasonCode = 'reconciliation-unavailable';
130
+ try {
131
+ await this.ledger.appendOnce(reservation.parentWorkflowInstanceId, context, `reconcile-failed:${reservation.cohortId}:${reasonCode}`, {
132
+ eventType: OrchestrationEventType.DelegationReconciliationFailed,
133
+ payload: { cohortId: reservation.cohortId, reason },
134
+ });
135
+ }
136
+ catch (diagnosticError) {
137
+ console.warn(`Delegation ${reservation.cohortId} diagnostic could not be persisted`, diagnosticError);
138
+ }
139
+ }
140
+ }
141
+ }
142
+ async capacityReservations(reservations, events) {
143
+ const capacity = [];
144
+ for (const reservation of reservations) {
145
+ // Only a failed cohort releases capacity, and only for children that have terminated;
146
+ // joined and unsettled cohorts keep every reservation so the root bound stays durable.
147
+ if (isJoined(events, reservation) || !isSettled(events, reservation)) {
148
+ capacity.push(reservation);
149
+ continue;
150
+ }
151
+ const children = [];
152
+ for (const child of reservation.children) {
153
+ const view = (await this.repository.load(child.workflowInstanceId)).view;
154
+ if (view?.status === WorkflowStatus.Active ||
155
+ view?.status === WorkflowStatus.Waiting ||
156
+ view?.status === WorkflowStatus.Blocked)
157
+ children.push(child);
158
+ }
159
+ capacity.push({ ...reservation, children });
160
+ }
161
+ return capacity;
162
+ }
163
+ async parentIdentity(parent) {
164
+ const item = await this.work.get(parent.workItemId);
165
+ if (item === null || item.state !== WorkStatus.Open || item.frozen || item.deleted)
166
+ throw new Error('Delegation requires open, unfrozen work');
167
+ if (parent.parentWorkflowInstanceId !== undefined)
168
+ throw new Error('Watch workflows cannot delegate independent work');
169
+ const rootWorkItemId = item.delegation?.rootWorkItemId ?? item.workItemId;
170
+ const rootClaim = await this.claims.primaryWorkflowInstanceId(rootWorkItemId);
171
+ if (rootClaim === undefined)
172
+ throw new Error('Delegation root has no primary workflow');
173
+ return {
174
+ root: workflowInstanceId(rootClaim),
175
+ parent: {
176
+ workflowInstanceId: parent.workflowInstanceId,
177
+ workItemId: item.workItemId,
178
+ rootWorkItemId,
179
+ ancestors: [...(item.delegation?.ancestors ?? []), item.workItemId],
180
+ },
181
+ };
182
+ }
183
+ async assertReservable(caller, existing, reservation, limits) {
184
+ const current = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
185
+ if (current.pendingActivation?.activationId !== caller.activationId ||
186
+ current.status !== WorkflowStatus.Active)
187
+ throw new Error('Delegation requires the current active activation');
188
+ if (existing.some((entry) => entry.parentWorkflowInstanceId === reservation.parentWorkflowInstanceId &&
189
+ entry.activationId === caller.activationId))
190
+ throw new Error('Activation already committed a cohort');
191
+ assertWithinRootLimits(existing, reservation, limits);
192
+ }
193
+ /** Validates inputs and pins the selected definition before anything is committed. */
194
+ async prepareChild(artifacts, parent, child, context) {
195
+ const allowed = await this.contextWorkItems(parent);
196
+ if (child.context.some((reference) => !allowed.has(reference.workItemId)))
197
+ throw new Error('Delegation context is outside the parent hierarchy');
198
+ await artifacts.validateInputs(parent, child.context);
199
+ const current = this.definitions.currentDefinition(child.workflowName);
200
+ if (current.fingerprint !== child.workflowFingerprint)
201
+ throw new Error('Delegation workflow fingerprint must match current configuration');
202
+ const definition = current.definition;
203
+ if (child.repository === undefined &&
204
+ Object.values(definition.stages).some((stage) => stage.execution?.workspace === WorkspaceMode.Branch ||
205
+ stage.execution?.workspace === WorkspaceMode.ReadOnly))
206
+ throw new Error('Workspace-using child workflows require an explicit repository assignment');
207
+ await this.definitions.register(child.workflowName, child.workflowFingerprint, definition, context);
208
+ }
209
+ /** Appends the reservation only if the root stream is unchanged since `events` was read. */
210
+ async commit(root, expectedSequence, reservation, context) {
211
+ try {
212
+ await this.repository.append(root, expectedSequence, [
213
+ delegationDraft(context, `reserve:${reservation.cohortId}`, { eventType: OrchestrationEventType.DelegationReserved, payload: reservation }, root),
214
+ ]);
215
+ return true;
216
+ }
217
+ catch (error) {
218
+ if (error instanceof WrongExpectedSequenceError)
219
+ return false;
220
+ throw error;
221
+ }
222
+ }
223
+ async reconcileReservation(artifacts, reservation, context) {
224
+ if (isSettled(await this.ledger.events(), reservation))
225
+ return;
226
+ const parent = (await this.repository.loadRequired(reservation.parentWorkflowInstanceId)).view;
227
+ if (parent.status !== WorkflowStatus.Active && parent.status !== WorkflowStatus.Waiting) {
228
+ await this.fail(reservation, 'Delegating parent is no longer active or waiting', context);
229
+ return;
230
+ }
231
+ if (!(await this.ensureWait(reservation, context)))
232
+ return;
233
+ const root = await this.registerChildren(artifacts, reservation, context);
234
+ for (const child of reservation.children) {
235
+ if (isSettled(await this.ledger.events(), reservation))
236
+ break;
237
+ await this.advanceChild(artifacts, root, reservation, child, context);
238
+ }
239
+ const results = selectedResults(await this.ledger.events(), reservation);
240
+ if (reservation.children.every((c) => results.some((r) => r.childWorkItemId === c.workItemId)))
241
+ await this.join(reservation, results, context);
242
+ }
243
+ async ensureWait(reservation, context) {
244
+ const id = reservation.parentWorkflowInstanceId;
245
+ for (;;) {
246
+ const loaded = await this.repository.loadRequired(id);
247
+ if (loaded.view.status !== WorkflowStatus.Active &&
248
+ loaded.view.status !== WorkflowStatus.Waiting)
249
+ return false;
250
+ if (loaded.view.delegationWait?.cohortId === reservation.cohortId)
251
+ return true;
252
+ // The reservation commits on the root stream, so the parent's delegating activation is
253
+ // re-validated here under the parent's own sequence guard before any child can start.
254
+ if (loaded.view.pendingActivation?.activationId !== reservation.activationId) {
255
+ await this.fail(reservation, 'Delegating activation is no longer current', context);
256
+ return false;
257
+ }
258
+ try {
259
+ await this.repository.append(id, loaded.sequence, [
260
+ delegationDraft(context, `wait:${reservation.cohortId}`, {
261
+ eventType: OrchestrationEventType.DelegationWaitStarted,
262
+ payload: { cohortId: reservation.cohortId, activationId: reservation.activationId },
263
+ }, id),
264
+ ]);
265
+ return true;
266
+ }
267
+ catch (error) {
268
+ if (!(error instanceof WrongExpectedSequenceError))
269
+ throw error;
270
+ }
271
+ }
272
+ }
273
+ async fail(reservation, reason, context) {
274
+ const id = reservation.parentWorkflowInstanceId;
275
+ for (;;) {
276
+ const loaded = await this.repository.loadRequired(id);
277
+ if (isSettled(await this.ledger.events(), reservation))
278
+ return;
279
+ const drafts = [
280
+ delegationDraft(context, `failed:${reservation.cohortId}`, {
281
+ eventType: OrchestrationEventType.DelegationFailed,
282
+ payload: { cohortId: reservation.cohortId, reason },
283
+ }, id),
284
+ ];
285
+ if (loaded.view.status === WorkflowStatus.Active ||
286
+ loaded.view.status === WorkflowStatus.Waiting)
287
+ drafts.push(delegationDraft(context, `block:${reservation.cohortId}`, {
288
+ eventType: OrchestrationEventType.InstanceBlocked,
289
+ payload: { reason },
290
+ }, id));
291
+ try {
292
+ await this.repository.append(id, loaded.sequence, drafts);
293
+ return;
294
+ }
295
+ catch (error) {
296
+ if (!(error instanceof WrongExpectedSequenceError))
297
+ throw error;
298
+ }
299
+ }
300
+ }
301
+ /** WorkItem, primary claim and artifact grant are each idempotent; none starts a workflow. */
302
+ async registerChildren(artifacts, reservation, context) {
303
+ const committed = reservedEvent(await this.ledger.events(), reservation).event;
304
+ for (const child of reservation.children) {
305
+ const childContext = {
306
+ commandId: `delegation:${child.grantId}`,
307
+ occurredAt: committed.occurredAt,
308
+ correlationId: committed.correlationId,
309
+ actor: committed.actor,
310
+ };
311
+ await this.work.create({
312
+ workItemId: child.workItemId,
313
+ objective: child.objective,
314
+ delegation: {
315
+ parentWorkItemId: reservation.parentWorkItemId,
316
+ rootWorkItemId: reservation.rootWorkItemId,
317
+ ancestors: reservation.ancestors,
318
+ },
319
+ }, childContext);
320
+ await this.claims.claimPrimary(child.workItemId, child.workflowInstanceId, childContext);
321
+ await artifacts.registerChild({
322
+ delegationId: child.grantId,
323
+ parentWorkItemId: reservation.parentWorkItemId,
324
+ childWorkItemId: child.workItemId,
325
+ childReferences: child.context,
326
+ }, childContext);
327
+ }
328
+ const rootClaim = await this.claims.primaryWorkflowInstanceId(reservation.rootWorkItemId);
329
+ if (rootClaim === undefined)
330
+ throw new Error('Missing delegation root');
331
+ const root = workflowInstanceId(rootClaim);
332
+ await this.ledger.appendOnce(root, context, `registered:${reservation.cohortId}`, {
333
+ eventType: OrchestrationEventType.DelegationRegistered,
334
+ payload: { cohortId: reservation.cohortId },
335
+ });
336
+ return root;
337
+ }
338
+ /** Starts the pinned definition, then records the result only once the child qualifies. */
339
+ async advanceChild(artifacts, root, reservation, child, context) {
340
+ const existing = await this.repository.load(child.workflowInstanceId);
341
+ if (await this.childWorkTerminated(child.workItemId, existing.view)) {
342
+ await this.fail(reservation, 'Delegated child work is no longer open', context);
343
+ return;
344
+ }
345
+ const workflow = existing.view ??
346
+ (await this.workflows.execute({
347
+ workflowInstanceId: child.workflowInstanceId,
348
+ workItemId: child.workItemId,
349
+ workflowName: child.workflowName,
350
+ workflowDefinitionFingerprint: child.workflowFingerprint,
351
+ orchestrationGroupId: orchestrationGroupId(`primary:${child.workItemId}`),
352
+ }, { ...context, commandId: `delegation-start:${child.grantId}` }));
353
+ // Accepted activation alone never qualifies: the workflow must complete successfully.
354
+ if (workflow.status === WorkflowStatus.Superseded ||
355
+ (workflow.status === WorkflowStatus.Completed && !isSuccessfulWorkflowCompletion(workflow))) {
356
+ await this.fail(reservation, `Child ${child.workItemId} terminated without success`, context);
357
+ return;
358
+ }
359
+ if (workflow.status !== WorkflowStatus.Completed)
360
+ return;
361
+ const selected = selectedResults(await this.ledger.events(), reservation);
362
+ if (selected.some((result) => result.childWorkItemId === child.workItemId))
363
+ return;
364
+ const outputs = await artifacts.qualifyingOutputs(workflow, child.outputs);
365
+ if (outputs === null) {
366
+ await this.missingOutputs(root, reservation, child, context);
367
+ return;
368
+ }
369
+ const satisfied = outputs.length === child.outputs.length &&
370
+ child.outputs.every((required) => outputs.filter((output) => output.name === required.name && output.reference.workItemId === child.workItemId).length === 1);
371
+ if (!satisfied) {
372
+ await this.fail(reservation, 'Invalid qualifying output contract', context);
373
+ return;
374
+ }
375
+ await this.ledger.appendOnce(root, context, `result:${child.grantId}`, {
376
+ eventType: OrchestrationEventType.DelegationResultSelected,
377
+ payload: { cohortId: reservation.cohortId, childWorkItemId: child.workItemId, outputs },
378
+ });
379
+ }
380
+ async childWorkTerminated(id, view) {
381
+ if (view?.status === WorkflowStatus.Completed)
382
+ return false;
383
+ const item = await this.work.get(id);
384
+ return item === null || item.deleted === true || item.state !== WorkStatus.Open;
385
+ }
386
+ async missingOutputs(root, reservation, child, context) {
387
+ const key = `outputs-pending:${child.grantId}`;
388
+ const observed = (await this.ledger.events()).find((entry) => entry.event.eventId === delegationEventId(root, key));
389
+ if (observed === undefined) {
390
+ await this.ledger.appendOnce(root, context, key, {
391
+ eventType: OrchestrationEventType.DelegationReconciliationFailed,
392
+ payload: {
393
+ cohortId: reservation.cohortId,
394
+ reason: 'Completed child outputs are not yet visible',
395
+ },
396
+ });
397
+ return;
398
+ }
399
+ if (observed.event.causationId !== context.commandId)
400
+ await this.fail(reservation, `Child ${child.workItemId} completed without required outputs`, context);
401
+ }
402
+ endedRun(id) {
403
+ return this.runHasEnded(id);
404
+ }
405
+ /** Join and continuation commit together, so a duplicate trigger cannot resume the parent twice. */
406
+ async join(reservation, results, context) {
407
+ if (!(await this.endedRun(reservation.runId)))
408
+ return;
409
+ const parentId = reservation.parentWorkflowInstanceId;
410
+ for (;;) {
411
+ const loaded = await this.repository.loadRequired(parentId);
412
+ const joinId = delegationEventId(parentId, `join:${reservation.cohortId}`);
413
+ const { events } = await this.repository.history(parentId);
414
+ if (events.some((event) => event.event.eventId === joinId))
415
+ return;
416
+ if (loaded.view.status !== WorkflowStatus.Waiting ||
417
+ loaded.view.delegationWait?.cohortId !== reservation.cohortId ||
418
+ isSettled(await this.ledger.events(), reservation))
419
+ return;
420
+ const original = events.find((entry) => entry?.event.eventType === OrchestrationEventType.ActivityRequested &&
421
+ entry.event.payload.activationId === reservation.activationId);
422
+ if (original?.event.eventType !== OrchestrationEventType.ActivityRequested)
423
+ throw new Error('Missing delegating activation');
424
+ const requested = original.event.payload;
425
+ const drafts = [
426
+ delegationDraft(context, `join:${reservation.cohortId}`, {
427
+ eventType: OrchestrationEventType.DelegationJoined,
428
+ payload: { cohortId: reservation.cohortId, results },
429
+ }, parentId),
430
+ delegationDraft(context, `continue:${reservation.cohortId}`, {
431
+ eventType: OrchestrationEventType.ActivityRequested,
432
+ payload: {
433
+ ...requested,
434
+ activationId: activationId(`${parentId}:activity:${nextOrdinal(loaded.view)}`),
435
+ ordinal: nextOrdinal(loaded.view),
436
+ sessionPolicy: 'fresh',
437
+ },
438
+ }, parentId),
439
+ ];
440
+ try {
441
+ await this.repository.append(parentId, loaded.sequence, drafts);
442
+ return;
443
+ }
444
+ catch (error) {
445
+ if (!(error instanceof WrongExpectedSequenceError))
446
+ throw error;
447
+ }
448
+ }
449
+ }
450
+ }
451
+ function assertReplay(prior, caller, assignments) {
452
+ if (prior.parentWorkflowInstanceId !== caller.workflowInstanceId ||
453
+ prior.activationId !== caller.activationId ||
454
+ !matchesAssignments(prior, assignments))
455
+ throw new Error('Delegation replay conflict');
456
+ }
@@ -0,0 +1,17 @@
1
+ import type { ActivationId } from '../../activities/index.js';
2
+ import type { WorkflowInstanceId } from '../contracts/identifiers.js';
3
+ import type { WorkflowInstanceView } from '../contracts/views.js';
4
+ import type { OrchestrationRepository } from './orchestration-repository.js';
5
+ /** One admission policy for ordinary advancement while a committed cohort owns the parent. */
6
+ export declare class DelegationGate {
7
+ private readonly repository;
8
+ constructor(repository: OrchestrationRepository);
9
+ allows(view: WorkflowInstanceView): boolean;
10
+ fenced(id: WorkflowInstanceId): Promise<boolean>;
11
+ run<T>(id: WorkflowInstanceId, operation: () => Promise<T>): Promise<T>;
12
+ outcome<T>(id: WorkflowInstanceId, activationId: ActivationId, operation: () => Promise<T>, held: () => Promise<T>): Promise<T>;
13
+ availableInstances(): Promise<{
14
+ readonly sequence: number;
15
+ readonly view: WorkflowInstanceView | null;
16
+ }[]>;
17
+ }
@@ -0,0 +1,31 @@
1
+ import { DelegationPendingError } from '../contracts/delegation.js';
2
+ /** One admission policy for ordinary advancement while a committed cohort owns the parent. */
3
+ export class DelegationGate {
4
+ repository;
5
+ constructor(repository) {
6
+ this.repository = repository;
7
+ }
8
+ allows(view) {
9
+ return view.delegationFence === undefined;
10
+ }
11
+ async fenced(id) {
12
+ const view = (await this.repository.load(id)).view;
13
+ return view !== null && !this.allows(view);
14
+ }
15
+ async run(id, operation) {
16
+ if (await this.fenced(id))
17
+ throw new DelegationPendingError(id);
18
+ return operation();
19
+ }
20
+ async outcome(id, activationId, operation, held) {
21
+ const view = (await this.repository.load(id)).view;
22
+ if (view === null || this.allows(view))
23
+ return operation();
24
+ if (view.delegationFence?.activationId !== activationId)
25
+ throw new DelegationPendingError(id);
26
+ return held();
27
+ }
28
+ async availableInstances() {
29
+ return (await this.repository.list()).filter(({ view }) => view !== null && this.allows(view));
30
+ }
31
+ }
@@ -0,0 +1,28 @@
1
+ import { type CommandContext } from '@atolis-hq/eventing';
2
+ import type { DelegationReservation, DelegationResult } from '../contracts/delegation.js';
3
+ import { type WorkflowOrchestrationEvent, type WorkflowOrchestrationEventData } from '../contracts/events.js';
4
+ import type { WorkflowInstanceId } from '../contracts/identifiers.js';
5
+ import type { OrchestrationRepository } from './orchestration-repository.js';
6
+ type DelegationDraft = {
7
+ [T in WorkflowOrchestrationEventData['eventType']]: Pick<Extract<WorkflowOrchestrationEventData, {
8
+ eventType: T;
9
+ }>, 'eventType' | 'payload'>;
10
+ }[WorkflowOrchestrationEventData['eventType']];
11
+ /** Deterministic event identity makes every delegation append replay-safe. */
12
+ export declare function delegationEventId(id: string, key: string): string;
13
+ export declare function delegationDraft(context: CommandContext, key: string, input: DelegationDraft, id: string): WorkflowOrchestrationEventData;
14
+ /** Read side and idempotent append helpers over the journal-owned delegation facts. */
15
+ export declare class DelegationLedger {
16
+ private readonly repository;
17
+ constructor(repository: OrchestrationRepository);
18
+ events(): Promise<readonly WorkflowOrchestrationEvent[]>;
19
+ reservations(): Promise<readonly DelegationReservation[]>;
20
+ /** Appends once per key, retrying optimistic-concurrency conflicts against fresh stream state. */
21
+ appendOnce(id: WorkflowInstanceId, context: CommandContext, key: string, input: DelegationDraft): Promise<void>;
22
+ }
23
+ export declare function reservationsOf(events: readonly WorkflowOrchestrationEvent[]): readonly DelegationReservation[];
24
+ export declare function isJoined(events: readonly WorkflowOrchestrationEvent[], reservation: DelegationReservation): boolean;
25
+ export declare function isSettled(events: readonly WorkflowOrchestrationEvent[], reservation: DelegationReservation): boolean;
26
+ export declare function selectedResults(events: readonly WorkflowOrchestrationEvent[], reservation: DelegationReservation): readonly DelegationResult[];
27
+ export declare function reservedEvent(events: readonly WorkflowOrchestrationEvent[], reservation: DelegationReservation): WorkflowOrchestrationEvent;
28
+ export {};