@atolis-hq/wake 0.4.95 → 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 (62) 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/version.js +1 -1
  7. package/dist/src/control-plane/application/activation-scheduler.js +28 -43
  8. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +0 -13
  9. package/dist/src/control-plane/application/advance-once-dispatch.js +10 -24
  10. package/dist/src/control-plane/application/in-process-scheduler-serialiser.d.ts +1 -0
  11. package/dist/src/control-plane/application/in-process-scheduler-serialiser.js +15 -0
  12. package/dist/src/control-plane/application/runner-quota-outcome.d.ts +13 -0
  13. package/dist/src/control-plane/application/runner-quota-outcome.js +23 -0
  14. package/dist/src/orchestration/application/accept-signal.d.ts +3 -1
  15. package/dist/src/orchestration/application/accept-signal.js +2 -0
  16. package/dist/src/orchestration/application/advance-workflow.d.ts +0 -1
  17. package/dist/src/orchestration/application/advance-workflow.js +0 -4
  18. package/dist/src/orchestration/application/deferred-signals.d.ts +21 -0
  19. package/dist/src/orchestration/application/deferred-signals.js +119 -0
  20. package/dist/src/orchestration/application/delegated-work.d.ts +51 -0
  21. package/dist/src/orchestration/application/delegated-work.js +420 -0
  22. package/dist/src/orchestration/application/delegation-gate.d.ts +17 -0
  23. package/dist/src/orchestration/application/delegation-gate.js +31 -0
  24. package/dist/src/orchestration/application/delegation-ledger.d.ts +28 -0
  25. package/dist/src/orchestration/application/delegation-ledger.js +79 -0
  26. package/dist/src/orchestration/application/delegation-reservation.d.ts +15 -0
  27. package/dist/src/orchestration/application/delegation-reservation.js +54 -0
  28. package/dist/src/orchestration/application/expire-timed-out-waits.d.ts +1 -1
  29. package/dist/src/orchestration/application/expire-timed-out-waits.js +2 -2
  30. package/dist/src/orchestration/application/orchestration-projection.js +5 -1
  31. package/dist/src/orchestration/application/orchestration-repository.d.ts +5 -0
  32. package/dist/src/orchestration/application/orchestration-repository.js +69 -11
  33. package/dist/src/orchestration/application/orchestration-service.d.ts +28 -3
  34. package/dist/src/orchestration/application/orchestration-service.js +69 -20
  35. package/dist/src/orchestration/application/resource-transition-matching.js +11 -6
  36. package/dist/src/orchestration/application/start-workflow.js +4 -2
  37. package/dist/src/orchestration/application/workflow-definition-registry.d.ts +5 -1
  38. package/dist/src/orchestration/application/workflow-definition-registry.js +16 -3
  39. package/dist/src/orchestration/contracts/commands.d.ts +1 -0
  40. package/dist/src/orchestration/contracts/delegation-ports.d.ts +14 -0
  41. package/dist/src/orchestration/contracts/delegation-ports.js +1 -0
  42. package/dist/src/orchestration/contracts/delegation.d.ts +98 -0
  43. package/dist/src/orchestration/contracts/delegation.js +70 -0
  44. package/dist/src/orchestration/contracts/event-decoder.js +19 -0
  45. package/dist/src/orchestration/contracts/event-factory.js +16 -0
  46. package/dist/src/orchestration/contracts/events.d.ts +39 -0
  47. package/dist/src/orchestration/contracts/events.js +8 -0
  48. package/dist/src/orchestration/contracts/views.d.ts +8 -0
  49. package/dist/src/orchestration/domain/workflow-completion.d.ts +3 -0
  50. package/dist/src/orchestration/domain/workflow-completion.js +9 -0
  51. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +2 -0
  52. package/dist/src/orchestration/domain/workflow-instance-events.js +37 -0
  53. package/dist/src/orchestration/index.d.ts +2 -0
  54. package/dist/src/orchestration/index.js +1 -0
  55. package/dist/src/work/application/work-projection.js +3 -0
  56. package/dist/src/work/application/work-service.js +16 -0
  57. package/dist/src/work/contracts/commands.d.ts +6 -0
  58. package/dist/src/work/contracts/events.d.ts +2 -1
  59. package/dist/src/work/contracts/events.js +8 -0
  60. package/dist/src/work/contracts/views.d.ts +2 -1
  61. package/dist/src/work/domain/work-item.js +3 -0
  62. package/package.json +1 -1
@@ -7,7 +7,11 @@ export const orchestrationProjection = {
7
7
  select(event) {
8
8
  const owned = selectWorkflowOrchestrationEvent(event);
9
9
  return owned !== null && isWorkflowInstanceStream(owned.stream)
10
- ? { key: owned.stream.id }
10
+ ? {
11
+ key: owned.event.eventType === OrchestrationEventType.DelegationReserved
12
+ ? owned.event.payload.parentWorkflowInstanceId
13
+ : owned.stream.id,
14
+ }
11
15
  : null;
12
16
  },
13
17
  initial: () => null,
@@ -13,6 +13,11 @@ export declare class OrchestrationRepository {
13
13
  sequence: number;
14
14
  view: WorkflowInstanceView | null;
15
15
  }>;
16
+ events(): Promise<readonly WorkflowOrchestrationEvent[]>;
17
+ history(id: string): Promise<{
18
+ sequence: number;
19
+ events: WorkflowOrchestrationEvent[];
20
+ }>;
16
21
  loadRequired(id: string): Promise<{
17
22
  sequence: number;
18
23
  view: WorkflowInstanceView;
@@ -1,5 +1,6 @@
1
1
  import { cachedJournalView } from '@atolis-hq/eventing';
2
2
  import { decodeOrchestrationEvent, selectWorkflowOrchestrationEvent, } from '../contracts/event-decoder.js';
3
+ import { OrchestrationEventType } from '../contracts/events.js';
3
4
  import { workflowInstanceId } from '../contracts/identifiers.js';
4
5
  import { isWorkflowInstanceStream, workflowInstanceStream } from '../contracts/streams.js';
5
6
  import { foldWorkflowInstance } from '../domain/workflow-instance.js';
@@ -8,14 +9,43 @@ export class OrchestrationRepository {
8
9
  listed;
9
10
  constructor(journal) {
10
11
  this.journal = journal;
11
- this.listed = cachedJournalView(journal, (events) => deriveList(events));
12
+ this.listed = cachedJournalView(journal, (events) => {
13
+ const owned = events.flatMap((entry) => {
14
+ const decoded = selectWorkflowOrchestrationEvent(entry);
15
+ return decoded === null ? [] : [decoded];
16
+ });
17
+ return {
18
+ instances: deriveList(events, owned),
19
+ events: owned,
20
+ inherited: inheritedReservations(owned),
21
+ };
22
+ });
12
23
  }
13
24
  async load(id) {
14
- const events = await this.journal.readStream(workflowInstanceStream(workflowInstanceId(id)));
15
- const owned = events
16
- .map(selectWorkflowOrchestrationEvent)
17
- .filter((event) => event !== null && isWorkflowInstanceStream(event.stream));
18
- return { sequence: events.length, view: foldWorkflowInstance(owned) };
25
+ const { events: own, sequence } = await this.history(id);
26
+ const inherited = ((await this.listed.get()).inherited.get(id) ?? []).filter((entry) => {
27
+ const fact = entry.event;
28
+ if (entry.stream.id === id ||
29
+ fact.eventType !== OrchestrationEventType.DelegationReserved ||
30
+ fact.payload.parentWorkflowInstanceId !== id)
31
+ return false;
32
+ const cohortId = fact.payload.cohortId;
33
+ return !own.some((event) => (event.event.eventType === OrchestrationEventType.DelegationJoined ||
34
+ event.event.eventType === OrchestrationEventType.DelegationFailed) &&
35
+ event.event.payload.cohortId === cohortId);
36
+ });
37
+ return { sequence, view: foldWorkflowInstance([...own, ...inherited]) };
38
+ }
39
+ events() {
40
+ return this.listed.get().then((snapshot) => snapshot.events);
41
+ }
42
+ async history(id) {
43
+ const raw = await this.journal.readStream(workflowInstanceStream(workflowInstanceId(id)));
44
+ const events = raw.flatMap((entry) => {
45
+ const owned = selectWorkflowOrchestrationEvent(entry);
46
+ return owned === null ? [] : [owned];
47
+ });
48
+ return { sequence: raw.length, events };
19
49
  }
20
50
  async loadRequired(id) {
21
51
  const loaded = await this.load(id);
@@ -38,7 +68,7 @@ export class OrchestrationRepository {
38
68
  return events.map(decodeOrchestrationEvent).filter(isWorkflowEvent);
39
69
  }
40
70
  async list() {
41
- return this.listed.get();
71
+ return (await this.listed.get()).instances;
42
72
  }
43
73
  }
44
74
  function isWorkflowEvent(event) {
@@ -46,7 +76,7 @@ function isWorkflowEvent(event) {
46
76
  }
47
77
  // `sequence` counts every event on the stream, matching readStream, while the
48
78
  // fold sees only owned orchestration events — exactly what load() computes.
49
- function deriveList(events) {
79
+ function deriveList(events, owned) {
50
80
  const streams = new Map();
51
81
  for (const event of events) {
52
82
  if (!isWorkflowInstanceStream(event.stream))
@@ -57,10 +87,38 @@ function deriveList(events) {
57
87
  else
58
88
  existing.push(event);
59
89
  }
90
+ const grouped = new Map();
91
+ const add = (id, event) => {
92
+ const group = grouped.get(id);
93
+ if (group === undefined)
94
+ grouped.set(id, [event]);
95
+ else
96
+ group.push(event);
97
+ };
98
+ for (const event of owned) {
99
+ add(event.stream.id, event);
100
+ if (event.event.eventType === OrchestrationEventType.DelegationReserved &&
101
+ event.event.payload.parentWorkflowInstanceId !== event.stream.id)
102
+ add(event.event.payload.parentWorkflowInstanceId, event);
103
+ }
60
104
  return [...streams.values()].map((streamEvents) => ({
61
105
  sequence: streamEvents.length,
62
- view: foldWorkflowInstance(streamEvents
63
- .map(selectWorkflowOrchestrationEvent)
64
- .filter((event) => event !== null && isWorkflowInstanceStream(event.stream))),
106
+ view: foldWorkflowInstance(grouped.get(streamEvents[0].stream.id) ?? []),
65
107
  }));
66
108
  }
109
+ function inheritedReservations(events) {
110
+ const inherited = new Map();
111
+ for (const entry of events) {
112
+ if (entry.event.eventType !== OrchestrationEventType.DelegationReserved)
113
+ continue;
114
+ const id = entry.event.payload.parentWorkflowInstanceId;
115
+ if (entry.stream.id === id)
116
+ continue;
117
+ const prior = inherited.get(id);
118
+ if (prior === undefined)
119
+ inherited.set(id, [entry]);
120
+ else
121
+ prior.push(entry);
122
+ }
123
+ return inherited;
124
+ }
@@ -1,3 +1,4 @@
1
+ import type { DelegationArtifacts } from '../contracts/delegation-ports.js';
1
2
  import type { ResourceTransitionEvidence } from './resource-transition-evidence.js';
2
3
  import type { CommandContext, EventJournal, ProjectionStore } from '@atolis-hq/eventing';
3
4
  import { type ActivationId, type ActivityOutcome } from '../../activities/index.js';
@@ -12,6 +13,10 @@ import { AdvanceWorkflow } from './advance-workflow.js';
12
13
  import { type ConversationCommandInput, type ConversationCommandResult } from './conversation-command.js';
13
14
  import type { AgentActivityClassifier } from './pending-activations.js';
14
15
  export declare class OrchestrationService {
16
+ private readonly delegationGate;
17
+ private readonly delegatedWork;
18
+ private readonly repository;
19
+ private readonly deferredSignals;
15
20
  private readonly startWorkflow;
16
21
  private readonly acceptActivityOutcome;
17
22
  private readonly acceptWorkflowSignal;
@@ -24,7 +29,19 @@ export declare class OrchestrationService {
24
29
  private readonly journal;
25
30
  private readonly definitions;
26
31
  private readonly work;
27
- constructor(journal: EventJournal, work: WorkService, definitions: Readonly<Record<string, CompiledWorkflow>>, projections?: ProjectionStore, isAgentActivity?: AgentActivityClassifier);
32
+ constructor(journal: EventJournal, work: WorkService, definitions: Readonly<Record<string, CompiledWorkflow>>, projections?: ProjectionStore, isAgentActivity?: AgentActivityClassifier, delegation?: DelegationDependenciesFactory);
33
+ isActivationAccepted(id: string, item?: string): Promise<boolean>;
34
+ joinedDelegationResults(id: WorkflowInstanceId, cohortId: string): Promise<readonly {
35
+ cohortId: string;
36
+ childWorkItemId: WorkItemId;
37
+ outputs: {
38
+ name: string;
39
+ reference: {
40
+ workItemId: WorkItemId;
41
+ revisionId: string;
42
+ };
43
+ }[];
44
+ }[]>;
28
45
  start(command: StartWorkflowInstance, context: CommandContext): Promise<WorkflowInstanceView>;
29
46
  requestChild(request: ChildWorkflowRequest & {
30
47
  readonly maxPerGroup: number;
@@ -69,7 +86,7 @@ export declare class OrchestrationService {
69
86
  }, context: CommandContext): Promise<import("../contracts/views.js").GroupBudgetExhaustedView | WorkflowInstanceView>;
70
87
  get(id: WorkflowInstanceId): Promise<WorkflowInstanceView | null>;
71
88
  getPrimaryWorkflowInstanceId(workItemId: WorkItemId): Promise<string | undefined>;
72
- listPendingActivations(workItemId?: string): Promise<readonly import("./pending-activations.js").PendingActivationEntry[]>;
89
+ listPendingActivations(workItemId?: string): Promise<import("./pending-activations.js").PendingActivationEntry[]>;
73
90
  listWaiting(signalKind?: SignalName): Promise<WorkflowInstanceView[]>;
74
91
  expireTimedOutWaits(context: CommandContext): Promise<WorkflowInstanceView[]>;
75
92
  listAll(): Promise<WorkflowInstanceView[]>;
@@ -101,4 +118,12 @@ export type OperationCoordinator = <Result>(operation: () => Promise<Result>) =>
101
118
  export interface WatchChildCancellation {
102
119
  cancelSupersededWatchChildren(workflowInstanceIds: readonly string[]): Promise<unknown>;
103
120
  }
104
- export declare const createOrchestrationService: (journal: EventJournal, work: WorkService, definitions: Readonly<Record<string, CompiledWorkflow>>, projections?: ProjectionStore, isAgentActivity?: AgentActivityClassifier) => OrchestrationService;
121
+ export declare const createOrchestrationService: (journal: EventJournal, work: WorkService, definitions: Readonly<Record<string, CompiledWorkflow>>, projections?: ProjectionStore, isAgentActivity?: AgentActivityClassifier, delegation?: DelegationDependenciesFactory) => OrchestrationService;
122
+ /** Immutable dependencies are resolved once; callbacks may refer to services composed later. */
123
+ type DelegationDependenciesFactory = (queries: {
124
+ isActivationAccepted: (activationId: string, workItemId?: string) => Promise<boolean>;
125
+ }) => {
126
+ artifacts: DelegationArtifacts;
127
+ runHasEnded: (runId: string) => Promise<boolean>;
128
+ };
129
+ export {};
@@ -1,3 +1,7 @@
1
+ import { DeferredSignals } from './deferred-signals.js';
2
+ import { DelegatedWork } from './delegated-work.js';
3
+ import { DelegationGate } from './delegation-gate.js';
4
+ import { expireTimedOutWaits } from './expire-timed-out-waits.js';
1
5
  import { recoverPolicyBlockedMerges } from './policy-blocked-merge-recovery.js';
2
6
  import { WorkStatus, } from '../../work/index.js';
3
7
  import { selectOrchestrationEvent } from '../contracts/event-decoder.js';
@@ -19,6 +23,10 @@ import { StartWorkflow } from './start-workflow.js';
19
23
  import { continuesWaitingForSameWatchGate } from './watch-child-transitions.js';
20
24
  import { WorkflowDefinitionRegistry } from './workflow-definition-registry.js';
21
25
  export class OrchestrationService {
26
+ delegationGate;
27
+ delegatedWork;
28
+ repository;
29
+ deferredSignals;
22
30
  startWorkflow;
23
31
  acceptActivityOutcome;
24
32
  acceptWorkflowSignal;
@@ -31,18 +39,40 @@ export class OrchestrationService {
31
39
  journal;
32
40
  definitions;
33
41
  work;
34
- constructor(journal, work, definitions, projections, isAgentActivity) {
42
+ constructor(journal, work, definitions, projections, isAgentActivity, delegation) {
35
43
  this.projections = projections;
36
44
  this.journal = journal;
37
45
  this.work = work;
38
46
  const repository = new OrchestrationRepository(journal);
47
+ this.repository = repository;
48
+ this.delegationGate = new DelegationGate(repository);
49
+ const dependencies = delegation?.({
50
+ isActivationAccepted: (id, item) => this.isActivationAccepted(id, item),
51
+ });
39
52
  this.claims = new CoordinationClaims(journal);
40
53
  this.definitions = new WorkflowDefinitionRegistry(journal, projections, definitions);
41
54
  this.startWorkflow = new StartWorkflow(repository, this.claims, work, this.definitions);
42
- this.advanceWorkflow = new AdvanceWorkflow(repository, this.startWorkflow, (command, context) => this.acceptActivityOutcome.execute(command, context), isAgentActivity);
55
+ this.delegatedWork = new DelegatedWork(repository, work, this.claims, this.definitions, this.startWorkflow, {
56
+ artifacts: dependencies?.artifacts ?? unavailableArtifacts,
57
+ runHasEnded: dependencies?.runHasEnded ?? unavailableRunCompletion,
58
+ });
59
+ this.advanceWorkflow = new AdvanceWorkflow(repository, this.startWorkflow, (command, context) => this.acceptOutcome(command, context), isAgentActivity);
43
60
  this.acceptWorkflowSignal = new AcceptSignal(repository, this.startWorkflow, work);
61
+ this.deferredSignals = new DeferredSignals(repository, (id, signal, context) => this.delegationGate.run(id, () => this.acceptWorkflowSignal.execute(id, signal, context)), (id, target, evidenceId, context) => this.delegationGate.run(id, () => this.advanceWorkflow.applyResourceTransition(id, target, evidenceId, context)), (id) => this.delegationGate.fenced(id));
44
62
  this.childWorkflows = new RequestChild(repository, this.claims, new GroupBudgetRecorder(journal), this.startWorkflow, this.advanceWorkflow);
45
- this.acceptActivityOutcome = new AcceptActivityOutcome(repository, this.startWorkflow, (context) => this.childWorkflows.reconcileChildCompletions(context));
63
+ this.acceptActivityOutcome = new AcceptActivityOutcome(repository, this.startWorkflow, async (context) => {
64
+ await this.delegatedWork.reconcile(context);
65
+ await this.childWorkflows.reconcileChildCompletions(context);
66
+ await this.deferredSignals.reconcile(context);
67
+ });
68
+ }
69
+ async isActivationAccepted(id, item) {
70
+ return (await this.repository.list()).some(({ view }) => view !== null &&
71
+ (item === undefined || view.workItemId === item) &&
72
+ view.acceptedOutcomes.some((accepted) => accepted === id));
73
+ }
74
+ joinedDelegationResults(id, cohortId) {
75
+ return this.delegatedWork.results(id, cohortId);
46
76
  }
47
77
  start(command, context) {
48
78
  return this.startWorkflow.execute(command, context);
@@ -54,13 +84,19 @@ export class OrchestrationService {
54
84
  return this.childWorkflows.rejectCausalActivation(request, context);
55
85
  }
56
86
  acceptOutcome(command, context) {
57
- return this.transitionWatchChildren(context, () => this.acceptActivityOutcome.execute(command, context));
87
+ return this.transitionWatchChildren(context, () => this.delegationGate.outcome(command.workflowInstanceId, command.activationId, () => this.acceptActivityOutcome.execute(command, context), async () => {
88
+ await this.reconcileChildCompletions(context);
89
+ return (await this.repository.loadRequired(command.workflowInstanceId)).view;
90
+ }));
58
91
  }
59
92
  waitForSignal(workflowInstanceId, expectation, context) {
60
- return this.transitionWatchChildren(context, () => this.acceptWorkflowSignal.wait(workflowInstanceId, expectation, context));
93
+ return this.transitionWatchChildren(context, async () => {
94
+ await this.delegationGate.run(workflowInstanceId, () => this.acceptWorkflowSignal.wait(workflowInstanceId, expectation, context));
95
+ return this.deferredSignals.reconcileWorkflow(workflowInstanceId, context);
96
+ });
61
97
  }
62
98
  acceptSignal(workflowInstanceId, signal, context) {
63
- return this.coordinateAcceptSignal(() => this.transitionWatchChildren(context, () => this.acceptWorkflowSignal.execute(workflowInstanceId, signal, context)));
99
+ return this.coordinateAcceptSignal(() => this.transitionWatchChildren(context, () => this.deferredSignals.accept(workflowInstanceId, signal, context)));
64
100
  }
65
101
  setAcceptSignalOperationCoordinator(coordinator) {
66
102
  this.coordinateAcceptSignal = coordinator;
@@ -69,7 +105,7 @@ export class OrchestrationService {
69
105
  this.watchChildCancellation = cancellation;
70
106
  }
71
107
  requestSupplementalActivity(workflowInstanceId, request, context) {
72
- return this.advanceWorkflow.requestSupplementalActivity(workflowInstanceId, request, context);
108
+ return this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.requestSupplementalActivity(workflowInstanceId, request, context));
73
109
  }
74
110
  async applyConversationCommand(workItemId, input, context) {
75
111
  return (await this.applyConversationCommandWithFeedback(workItemId, input, context)).applied;
@@ -156,16 +192,16 @@ export class OrchestrationService {
156
192
  return this.transitionWatchChildren(context, () => this.advanceWorkflow.blockAwaitingActivation(workflowInstanceId, activationId, reason, context));
157
193
  }
158
194
  resolveExecutionFailure(workflowInstanceId, input, context) {
159
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.resolveExecutionFailure(workflowInstanceId, input, context));
195
+ return this.transitionWatchChildren(context, () => this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.resolveExecutionFailure(workflowInstanceId, input, context)));
160
196
  }
161
197
  retryRunnerQuotaFailure(workflowInstanceId, input, context) {
162
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.retryRunnerQuotaFailure(workflowInstanceId, input, context));
198
+ return this.transitionWatchChildren(context, () => this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.retryRunnerQuotaFailure(workflowInstanceId, input, context)));
163
199
  }
164
200
  retryBlockedFailedStage(workflowInstanceId, context) {
165
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.retryBlockedFailedStage(workflowInstanceId, context));
201
+ return this.transitionWatchChildren(context, () => this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.retryBlockedFailedStage(workflowInstanceId, context)));
166
202
  }
167
203
  restartBlockedFailedStage(workflowInstanceId, context) {
168
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.restartBlockedFailedStage(workflowInstanceId, context));
204
+ return this.transitionWatchChildren(context, () => this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.restartBlockedFailedStage(workflowInstanceId, context)));
169
205
  }
170
206
  async resumeBlockedStageForChanges(workflowInstanceId, context) {
171
207
  const current = await this.advanceWorkflow.get(workflowInstanceId);
@@ -177,7 +213,7 @@ export class OrchestrationService {
177
213
  if (!current.operatorRetryCommandIds.includes(context.commandId) &&
178
214
  !selectChangesResumeTargets((await this.advanceWorkflow.listAll()).filter((workflow) => workflow.workItemId === current.workItemId)).some((workflow) => workflow.workflowInstanceId === workflowInstanceId))
179
215
  return current;
180
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.resumeBlockedStageForChanges(workflowInstanceId, context));
216
+ return this.transitionWatchChildren(context, () => this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.resumeBlockedStageForChanges(workflowInstanceId, context)));
181
217
  }
182
218
  async resumeBlockedStageForReply(workflowInstanceId, context) {
183
219
  const current = await this.advanceWorkflow.get(workflowInstanceId);
@@ -222,14 +258,15 @@ export class OrchestrationService {
222
258
  getPrimaryWorkflowInstanceId(workItemId) {
223
259
  return this.childWorkflows.getPrimaryWorkflowInstanceId(workItemId);
224
260
  }
225
- listPendingActivations(workItemId) {
226
- return this.advanceWorkflow.listPendingActivations(workItemId);
261
+ async listPendingActivations(workItemId) {
262
+ const entries = await this.advanceWorkflow.listPendingActivations(workItemId);
263
+ return entries.filter((entry) => this.delegationGate.allows(entry.workflow));
227
264
  }
228
265
  listWaiting(signalKind) {
229
266
  return this.advanceWorkflow.listWaiting(signalKind);
230
267
  }
231
- expireTimedOutWaits(context) {
232
- return this.advanceWorkflow.expireTimedOutWaits(context);
268
+ async expireTimedOutWaits(context) {
269
+ return expireTimedOutWaits(this.repository, context, await this.delegationGate.availableInstances());
233
270
  }
234
271
  listAll() {
235
272
  return this.advanceWorkflow.listAll();
@@ -254,8 +291,12 @@ export class OrchestrationService {
254
291
  const workflows = await Promise.all((stored?.value ?? []).map((workflowInstanceId) => this.advanceWorkflow.get(workflowInstanceId)));
255
292
  return workflows.filter((workflow) => workflow !== null);
256
293
  }
257
- reconcileChildCompletions(context) {
258
- return this.transitionWatchChildren(context, () => this.childWorkflows.reconcileChildCompletions(context));
294
+ async reconcileChildCompletions(context) {
295
+ await this.delegatedWork.reconcile(context);
296
+ return this.transitionWatchChildren(context, async () => {
297
+ await this.childWorkflows.reconcileChildCompletions(context);
298
+ await this.deferredSignals.reconcile(context);
299
+ });
259
300
  }
260
301
  async transitionWatchChildren(context, operation) {
261
302
  const before = await this.advanceWorkflow.listAll();
@@ -286,7 +327,7 @@ export class OrchestrationService {
286
327
  return this.advanceWorkflow.listResourceTransitionMatches(event);
287
328
  }
288
329
  applyResourceTransition(workflowInstanceId, target, evidenceId, context) {
289
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.applyResourceTransition(workflowInstanceId, target, evidenceId, context));
330
+ return this.transitionWatchChildren(context, () => this.deferredSignals.applyTransition(workflowInstanceId, target, evidenceId, context));
290
331
  }
291
332
  }
292
333
  export class GroupBudgetExtensionIneligibleError extends Error {
@@ -303,7 +344,7 @@ async function journalGroupBudgetExhaustion(journal, workflowInstanceId) {
303
344
  : [];
304
345
  });
305
346
  }
306
- export const createOrchestrationService = (journal, work, definitions, projections, isAgentActivity) => new OrchestrationService(journal, work, definitions, projections, isAgentActivity);
347
+ export const createOrchestrationService = (journal, work, definitions, projections, isAgentActivity, delegation) => new OrchestrationService(journal, work, definitions, projections, isAgentActivity, delegation);
307
348
  function isWorkControllable(work) {
308
349
  return work !== null && !work.deleted && !work.frozen && work.state === WorkStatus.Open;
309
350
  }
@@ -316,3 +357,11 @@ function isReviewConversationCommand(command) {
316
357
  command === ConversationBuiltInCommand.Accepted ||
317
358
  command === ConversationBuiltInCommand.Changes);
318
359
  }
360
+ async function unavailableRunCompletion() {
361
+ throw new Error('Delegation adapters unavailable');
362
+ }
363
+ const unavailableArtifacts = {
364
+ validateInputs: unavailableRunCompletion,
365
+ registerChild: unavailableRunCompletion,
366
+ qualifyingOutputs: unavailableRunCompletion,
367
+ };
@@ -69,12 +69,7 @@ export async function acceptResourceTransition(repository, workflows, id, target
69
69
  return (await repository.load(id)).view;
70
70
  }
71
71
  const decision = decideSignal(definition, { ...loaded.view, waitingFor: { ...loaded.view.waitingFor, resume: target } }, {
72
- signal: {
73
- kind: loaded.view.waitingFor.signalKind,
74
- actorId: 'resource-transition',
75
- actorDecision: { authorized: true, evidenceId },
76
- providerEventId: evidenceId,
77
- },
72
+ signal: resourceWaitSignal(loaded.view.waitingFor, evidenceId),
78
73
  occurredAt: context.occurredAt,
79
74
  causationId: `${context.commandId}:${evidenceId}`,
80
75
  consent: true,
@@ -110,3 +105,13 @@ function retryDraft(view, evidenceId, context) {
110
105
  }
111
106
  : { eventType: OrchestrationEventType.RetryCounted, payload: { retryKey: retry.key, count } }, 100);
112
107
  }
108
+ function resourceWaitSignal(wait, evidenceId) {
109
+ return {
110
+ kind: wait.signalKind,
111
+ ...(wait.resourceId === undefined ? {} : { resourceId: wait.resourceId }),
112
+ ...(wait.revision === undefined ? {} : { revision: wait.revision }),
113
+ actorId: 'resource-transition',
114
+ actorDecision: { authorized: true, evidenceId },
115
+ providerEventId: evidenceId,
116
+ };
117
+ }
@@ -26,7 +26,9 @@ export class StartWorkflow {
26
26
  async execute(command, context) {
27
27
  if (!(await this.isWorkItemOpen(command.workItemId)))
28
28
  throw new Error('WorkItem must exist and be open');
29
- const { definition, fingerprint } = this.definitions.currentDefinition(command.workflowName);
29
+ const fingerprint = command.workflowDefinitionFingerprint ??
30
+ this.definitions.currentDefinition(command.workflowName).fingerprint;
31
+ const definition = await this.definitions.resolve({ workflowName: command.workflowName, workflowDefinitionFingerprint: fingerprint }, { journalFallback: command.workflowDefinitionFingerprint !== undefined });
30
32
  const existing = await this.repository.load(command.workflowInstanceId);
31
33
  if (existing.view !== null)
32
34
  return existing.view;
@@ -64,7 +66,7 @@ export class StartWorkflow {
64
66
  }
65
67
  async isWorkItemOpen(workItemId) {
66
68
  const item = await this.work.get(workItemId);
67
- if (item === null || item.state !== WorkStatus.Open)
69
+ if (item === null || item.state !== WorkStatus.Open || item.deleted)
68
70
  return false;
69
71
  return true;
70
72
  }
@@ -28,5 +28,9 @@ export declare class WorkflowDefinitionRegistry {
28
28
  readonly commandId: string;
29
29
  }): Promise<void>;
30
30
  private isRegistered;
31
- resolve(view: Pick<WorkflowInstanceView, 'workflowName' | 'workflowDefinitionFingerprint'>): Promise<CompiledWorkflow>;
31
+ resolve(view: Pick<WorkflowInstanceView, 'workflowName' | 'workflowDefinitionFingerprint'>, options?: {
32
+ readonly journalFallback?: boolean;
33
+ }): Promise<CompiledWorkflow>;
34
+ /** Committed delegation recovery cannot depend on projection catch-up or current configuration. */
35
+ private fromJournal;
32
36
  }
@@ -101,7 +101,7 @@ export class WorkflowDefinitionRegistry {
101
101
  this.knownRegistered.add(key);
102
102
  return found;
103
103
  }
104
- async resolve(view) {
104
+ async resolve(view, options = {}) {
105
105
  if (view.workflowDefinitionFingerprint === undefined)
106
106
  return this.currentDefinition(view.workflowName).definition;
107
107
  const current = this.current[view.workflowName];
@@ -109,8 +109,21 @@ export class WorkflowDefinitionRegistry {
109
109
  workflowDefinitionFingerprint(current) === view.workflowDefinitionFingerprint)
110
110
  return current;
111
111
  const stored = await this.projections?.read(workflowDefinitionsProjection.name, workflowDefinitionKey(view.workflowName, view.workflowDefinitionFingerprint));
112
- if (stored === null || stored === undefined)
112
+ if (stored !== null && stored !== undefined)
113
+ return stored.value;
114
+ if (options.journalFallback !== true)
113
115
  throw new WorkflowDefinitionUnavailableError();
114
- return stored.value;
116
+ return this.fromJournal(view.workflowName, view.workflowDefinitionFingerprint);
117
+ }
118
+ /** Committed delegation recovery cannot depend on projection catch-up or current configuration. */
119
+ async fromJournal(name, fingerprint) {
120
+ for (const event of await this.journal.readStream(workflowDefinitionsStream())) {
121
+ const owned = selectOrchestrationEvent(event);
122
+ if (owned?.event.eventType === OrchestrationEventType.WorkflowDefinitionRegistered &&
123
+ owned.event.payload.workflowName === name &&
124
+ owned.event.payload.fingerprint === fingerprint)
125
+ return owned.event.payload.compiledDefinition;
126
+ }
127
+ throw new WorkflowDefinitionUnavailableError();
115
128
  }
116
129
  }
@@ -5,6 +5,7 @@ interface StartWorkflowBase {
5
5
  readonly workflowInstanceId: WorkflowInstanceId;
6
6
  readonly workItemId: WorkItemId;
7
7
  readonly workflowName: WorkflowName;
8
+ readonly workflowDefinitionFingerprint?: string;
8
9
  readonly orchestrationGroupId: OrchestrationGroupId;
9
10
  }
10
11
  type PrimaryWorkflowStart = {
@@ -0,0 +1,14 @@
1
+ import type { CommandContext } from '@atolis-hq/eventing';
2
+ import type { DelegatedAssignment, DelegationReservation, DelegationResult, DelegationRevisionReference } from './delegation.js';
3
+ import type { WorkflowInstanceView } from './views.js';
4
+ /** Trusted Bootstrap adapters; no provider, Run or session authority is supplied by assignments. */
5
+ export interface DelegationArtifacts {
6
+ validateInputs(parent: WorkflowInstanceView, references: readonly DelegationRevisionReference[]): Promise<void>;
7
+ registerChild(grant: {
8
+ readonly delegationId: string;
9
+ readonly parentWorkItemId: DelegationReservation['parentWorkItemId'];
10
+ readonly childWorkItemId: DelegationReservation['parentWorkItemId'];
11
+ readonly childReferences: readonly DelegationRevisionReference[];
12
+ }, context: CommandContext): Promise<void>;
13
+ qualifyingOutputs(child: WorkflowInstanceView, outputs: DelegatedAssignment['outputs']): Promise<DelegationResult['outputs'] | null>;
14
+ }
@@ -0,0 +1,98 @@
1
+ import { z } from 'zod';
2
+ import { activationId } from '../../activities/index.js';
3
+ import { workflowInstanceId } from './identifiers.js';
4
+ export declare const delegationRevisionReferenceSchema: z.ZodObject<{
5
+ workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
6
+ revisionId: z.ZodString;
7
+ }, z.core.$strict>;
8
+ export type DelegationRevisionReference = z.infer<typeof delegationRevisionReferenceSchema>;
9
+ export declare const delegatedAssignmentSchema: z.ZodObject<{
10
+ assignmentId: z.ZodString;
11
+ objective: z.ZodString;
12
+ criteria: z.ZodArray<z.ZodString>;
13
+ workflowName: z.ZodPipe<z.ZodString, z.ZodTransform<import("./identifiers.js").WorkflowName, string>>;
14
+ workflowFingerprint: z.ZodString;
15
+ context: z.ZodArray<z.ZodObject<{
16
+ workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
17
+ revisionId: z.ZodString;
18
+ }, z.core.$strict>>;
19
+ outputs: z.ZodArray<z.ZodObject<{
20
+ name: z.ZodString;
21
+ path: z.ZodString;
22
+ }, z.core.$strict>>;
23
+ }, z.core.$strict>;
24
+ export type DelegatedAssignment = z.infer<typeof delegatedAssignmentSchema>;
25
+ export declare const delegationReservationSchema: z.ZodObject<{
26
+ cohortId: z.ZodString;
27
+ parentWorkflowInstanceId: z.ZodPipe<z.ZodString, z.ZodTransform<import("./identifiers.js").WorkflowInstanceId, string>>;
28
+ parentWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
29
+ rootWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
30
+ activationId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../activities/index.js").ActivationId, string>>;
31
+ runId: z.ZodString;
32
+ ancestors: z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>>;
33
+ maxDepth: z.ZodNumber;
34
+ maxDescendants: z.ZodNumber;
35
+ children: z.ZodArray<z.ZodObject<{
36
+ assignmentId: z.ZodString;
37
+ objective: z.ZodString;
38
+ criteria: z.ZodArray<z.ZodString>;
39
+ workflowName: z.ZodPipe<z.ZodString, z.ZodTransform<import("./identifiers.js").WorkflowName, string>>;
40
+ workflowFingerprint: z.ZodString;
41
+ context: z.ZodArray<z.ZodObject<{
42
+ workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
43
+ revisionId: z.ZodString;
44
+ }, z.core.$strict>>;
45
+ outputs: z.ZodArray<z.ZodObject<{
46
+ name: z.ZodString;
47
+ path: z.ZodString;
48
+ }, z.core.$strict>>;
49
+ workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
50
+ workflowInstanceId: z.ZodPipe<z.ZodString, z.ZodTransform<import("./identifiers.js").WorkflowInstanceId, string>>;
51
+ grantId: z.ZodString;
52
+ }, z.core.$strict>>;
53
+ }, z.core.$strict>;
54
+ export type DelegationReservation = z.infer<typeof delegationReservationSchema>;
55
+ export declare const delegationResultSchema: z.ZodObject<{
56
+ cohortId: z.ZodString;
57
+ childWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
58
+ outputs: z.ZodArray<z.ZodObject<{
59
+ name: z.ZodString;
60
+ reference: z.ZodObject<{
61
+ workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
62
+ revisionId: z.ZodString;
63
+ }, z.core.$strict>;
64
+ }, z.core.$strict>>;
65
+ }, z.core.$strict>;
66
+ export type DelegationResult = z.infer<typeof delegationResultSchema>;
67
+ export declare const delegationWaitSchema: z.ZodObject<{
68
+ cohortId: z.ZodString;
69
+ activationId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../activities/index.js").ActivationId, string>>;
70
+ }, z.core.$strict>;
71
+ export declare const delegationJoinSchema: z.ZodObject<{
72
+ cohortId: z.ZodString;
73
+ results: z.ZodArray<z.ZodObject<{
74
+ cohortId: z.ZodString;
75
+ childWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
76
+ outputs: z.ZodArray<z.ZodObject<{
77
+ name: z.ZodString;
78
+ reference: z.ZodObject<{
79
+ workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
80
+ revisionId: z.ZodString;
81
+ }, z.core.$strict>;
82
+ }, z.core.$strict>>;
83
+ }, z.core.$strict>>;
84
+ }, z.core.$strict>;
85
+ export interface DelegationLimits {
86
+ readonly maxDepth: number;
87
+ readonly maxDescendants: number;
88
+ }
89
+ /** Obtained from the active Run capability, never from an assignment payload. */
90
+ export interface DelegationCaller {
91
+ readonly workflowInstanceId: ReturnType<typeof workflowInstanceId>;
92
+ readonly activationId: ReturnType<typeof activationId>;
93
+ readonly runId: string;
94
+ }
95
+ /** Retryable rejection: callers retain their signal or execution evidence until the cohort settles. */
96
+ export declare class DelegationPendingError extends Error {
97
+ constructor(id: string);
98
+ }