@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,79 @@
1
+ import { EventSourceKind, WrongExpectedSequenceError, } from '@atolis-hq/eventing';
2
+ import { OrchestrationEventType, } from '../contracts/events.js';
3
+ import { workflowEventData } from '../domain/decision-events.js';
4
+ /** Deterministic event identity makes every delegation append replay-safe. */
5
+ export function delegationEventId(id, key) {
6
+ return `delegation:${id}:${key}`;
7
+ }
8
+ export function delegationDraft(context, key, input, id) {
9
+ return workflowEventData({
10
+ ...input,
11
+ eventId: delegationEventId(id, key),
12
+ occurredAt: context.occurredAt,
13
+ correlationId: context.correlationId,
14
+ causationId: context.commandId,
15
+ actor: context.actor,
16
+ source: { kind: EventSourceKind.Internal, id: 'delegation' },
17
+ });
18
+ }
19
+ /** Read side and idempotent append helpers over the journal-owned delegation facts. */
20
+ export class DelegationLedger {
21
+ repository;
22
+ constructor(repository) {
23
+ this.repository = repository;
24
+ }
25
+ events() {
26
+ return this.repository.events();
27
+ }
28
+ async reservations() {
29
+ return reservationsOf(await this.events());
30
+ }
31
+ /** Appends once per key, retrying optimistic-concurrency conflicts against fresh stream state. */
32
+ async appendOnce(id, context, key, input) {
33
+ for (;;) {
34
+ const { events, sequence } = await this.repository.history(id);
35
+ if (events.some((event) => event.event.eventId === delegationEventId(id, key)))
36
+ return;
37
+ try {
38
+ await this.repository.append(id, sequence, [delegationDraft(context, key, input, id)]);
39
+ return;
40
+ }
41
+ catch (error) {
42
+ if (!(error instanceof WrongExpectedSequenceError))
43
+ throw error;
44
+ }
45
+ }
46
+ }
47
+ }
48
+ export function reservationsOf(events) {
49
+ return events.flatMap((event) => event.event.eventType === OrchestrationEventType.DelegationReserved
50
+ ? [event.event.payload]
51
+ : []);
52
+ }
53
+ export function isJoined(events, reservation) {
54
+ return events.some((event) => event.stream.id === reservation.parentWorkflowInstanceId &&
55
+ event.event.eventType === OrchestrationEventType.DelegationJoined &&
56
+ event.event.payload.cohortId === reservation.cohortId);
57
+ }
58
+ export function isSettled(events, reservation) {
59
+ return (isJoined(events, reservation) ||
60
+ events.some((entry) => entry.stream.id === reservation.parentWorkflowInstanceId &&
61
+ entry.event.eventType === OrchestrationEventType.DelegationFailed &&
62
+ entry.event.payload.cohortId === reservation.cohortId));
63
+ }
64
+ export function selectedResults(events, reservation) {
65
+ const children = new Set(reservation.children.map((child) => child.workItemId));
66
+ return events.flatMap((event) => event.event.eventType === OrchestrationEventType.DelegationResultSelected &&
67
+ event.event.payload.cohortId === reservation.cohortId &&
68
+ children.has(event.event.payload.childWorkItemId)
69
+ ? [event.event.payload]
70
+ : []);
71
+ }
72
+ export function reservedEvent(events, reservation) {
73
+ const found = events.find((entry) => entry.event.eventType === OrchestrationEventType.DelegationReserved &&
74
+ entry.event.payload.rootWorkItemId === reservation.rootWorkItemId &&
75
+ entry.event.payload.cohortId === reservation.cohortId);
76
+ if (found === undefined)
77
+ throw new Error('Missing delegation reservation');
78
+ return found;
79
+ }
@@ -0,0 +1,15 @@
1
+ import { type WorkItemId } from '../../work/index.js';
2
+ import { type DelegatedAssignment, type DelegationCaller, type DelegationLimits, type DelegationReservation } from '../contracts/delegation.js';
3
+ import { type WorkflowInstanceId } from '../contracts/identifiers.js';
4
+ export interface ReservationParent {
5
+ readonly workflowInstanceId: WorkflowInstanceId;
6
+ readonly workItemId: WorkItemId;
7
+ readonly rootWorkItemId: WorkItemId;
8
+ readonly ancestors: readonly WorkItemId[];
9
+ }
10
+ /** Child identities derive from root, cohort and assignment so replays name the same children. */
11
+ export declare function buildReservation(parent: ReservationParent, caller: DelegationCaller, cohortId: string, assignments: readonly DelegatedAssignment[], limits: DelegationLimits): DelegationReservation;
12
+ /** Bounds are fixed by the first reservation under a root so nesting cannot widen them. */
13
+ export declare function assertWithinRootLimits(existing: readonly DelegationReservation[], reservation: DelegationReservation, limits: DelegationLimits): void;
14
+ /** A replay of a branch request retains the originally resolved commit. */
15
+ export declare function matchesAssignments(reservation: DelegationReservation, assignments: readonly DelegatedAssignment[]): boolean;
@@ -0,0 +1,77 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { UlidIdGenerator } from '../../kernel/index.js';
3
+ import { workItemId } from '../../work/index.js';
4
+ import { delegatedAssignmentSchema, delegationReservationSchema, } from '../contracts/delegation.js';
5
+ import { workflowInstanceId } from '../contracts/identifiers.js';
6
+ import { DelegationOutputKind } from '../contracts/vocabulary.js';
7
+ const ids = new UlidIdGenerator();
8
+ /** Child identities derive from root, cohort and assignment so replays name the same children. */
9
+ export function buildReservation(parent, caller, cohortId, assignments, limits) {
10
+ const parsed = assignments.map((assignment) => delegatedAssignmentSchema.parse(assignment));
11
+ if (new Set(parsed.map((assignment) => assignment.assignmentId)).size !== parsed.length)
12
+ throw new Error('Duplicate assignment identity');
13
+ for (const assignment of parsed) {
14
+ if (assignment.outputs.filter((output) => 'kind' in output && output.kind === DelegationOutputKind.Change).length > 1)
15
+ throw new Error('One change output per child is currently supported');
16
+ if (assignment.outputs.some((output) => 'kind' in output && output.kind === DelegationOutputKind.Change) &&
17
+ assignment.repository === undefined)
18
+ throw new Error('Change outputs require an explicit repository assignment');
19
+ if (new Set(assignment.outputs.map((output) => output.name)).size !== assignment.outputs.length)
20
+ throw new Error('Duplicate named output');
21
+ }
22
+ return delegationReservationSchema.parse({
23
+ cohortId,
24
+ parentWorkflowInstanceId: parent.workflowInstanceId,
25
+ parentWorkItemId: parent.workItemId,
26
+ rootWorkItemId: parent.rootWorkItemId,
27
+ activationId: caller.activationId,
28
+ runId: caller.runId,
29
+ ancestors: parent.ancestors,
30
+ ...limits,
31
+ children: parsed.map((assignment) => {
32
+ const minted = ids.next('work');
33
+ return {
34
+ ...assignment,
35
+ workItemId: workItemId(minted),
36
+ workflowInstanceId: workflowInstanceId(`delegated:${minted}`),
37
+ grantId: `child-${minted}`,
38
+ };
39
+ }),
40
+ });
41
+ }
42
+ /** Bounds are fixed by the first reservation under a root so nesting cannot widen them. */
43
+ export function assertWithinRootLimits(existing, reservation, limits) {
44
+ const rootLimits = existing[0] ?? limits;
45
+ const reserved = existing.reduce((count, entry) => count + entry.children.length, 0);
46
+ if (reservation.ancestors.length > rootLimits.maxDepth ||
47
+ reserved + reservation.children.length > rootLimits.maxDescendants)
48
+ throw new Error('Delegation root reservation limit exceeded');
49
+ }
50
+ /** A replay of a branch request retains the originally resolved commit. */
51
+ export function matchesAssignments(reservation, assignments) {
52
+ if (assignments.some((assignment) => assignment.repository?.sourceRevision !== undefined &&
53
+ reservation.children.find((child) => child.assignmentId === assignment.assignmentId)
54
+ ?.repository?.sourceRevision !== assignment.repository.sourceRevision))
55
+ return false;
56
+ return isDeepStrictEqual(reservation.children.map(({ workItemId: _w, workflowInstanceId: _i, grantId: _g, ...assignment }) => ({
57
+ ...assignment,
58
+ ...(assignment.repository === undefined
59
+ ? {}
60
+ : {
61
+ repository: {
62
+ ...assignment.repository,
63
+ sourceRevision: assignments.find((entry) => entry.assignmentId === assignment.assignmentId)?.repository?.sourceRevision,
64
+ },
65
+ }),
66
+ })), assignments.map((assignment) => ({
67
+ ...delegatedAssignmentSchema.parse(assignment),
68
+ ...(assignment.repository === undefined
69
+ ? {}
70
+ : {
71
+ repository: {
72
+ ...assignment.repository,
73
+ sourceRevision: assignment.repository.sourceRevision,
74
+ },
75
+ }),
76
+ })));
77
+ }
@@ -1,3 +1,3 @@
1
1
  import type { CommandContext } from '@atolis-hq/eventing';
2
2
  import type { OrchestrationRepository } from './orchestration-repository.js';
3
- export declare function expireTimedOutWaits(repository: OrchestrationRepository, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView[]>;
3
+ export declare function expireTimedOutWaits(repository: OrchestrationRepository, context: CommandContext, instances?: Awaited<ReturnType<OrchestrationRepository['list']>>): Promise<import("../index.js").WorkflowInstanceView[]>;
@@ -1,7 +1,7 @@
1
1
  import { expireTimedOutAwait } from '../domain/interpreter.js';
2
- export async function expireTimedOutWaits(repository, context) {
2
+ export async function expireTimedOutWaits(repository, context, instances) {
3
3
  const expired = [];
4
- for (const loaded of await repository.list()) {
4
+ for (const loaded of instances ?? (await repository.list())) {
5
5
  if (loaded.view === null)
6
6
  continue;
7
7
  const decision = expireTimedOutAwait(loaded.view, {
@@ -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, DelegationRepositories } 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,33 @@ 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
+ repositoryAssignment(workItemId: string): Promise<{
34
+ resourceId: string;
35
+ sourceRef: string;
36
+ pullRequestBase: string;
37
+ sourceRevision: string;
38
+ } | undefined>;
39
+ isActivationAccepted(id: string, item?: string): Promise<boolean>;
40
+ joinedDelegationResults(id: WorkflowInstanceId, cohortId: string): Promise<readonly {
41
+ cohortId: string;
42
+ childWorkItemId: WorkItemId;
43
+ outputs: {
44
+ name: string;
45
+ reference: {
46
+ workItemId: WorkItemId;
47
+ revisionId: string;
48
+ } | {
49
+ workItemId: WorkItemId;
50
+ resourceId: string;
51
+ repositoryResourceId: string;
52
+ revision: string;
53
+ branch: string;
54
+ pullRequestBase: string;
55
+ runId: string;
56
+ };
57
+ }[];
58
+ }[]>;
28
59
  start(command: StartWorkflowInstance, context: CommandContext): Promise<WorkflowInstanceView>;
29
60
  requestChild(request: ChildWorkflowRequest & {
30
61
  readonly maxPerGroup: number;
@@ -69,7 +100,7 @@ export declare class OrchestrationService {
69
100
  }, context: CommandContext): Promise<import("../contracts/views.js").GroupBudgetExhaustedView | WorkflowInstanceView>;
70
101
  get(id: WorkflowInstanceId): Promise<WorkflowInstanceView | null>;
71
102
  getPrimaryWorkflowInstanceId(workItemId: WorkItemId): Promise<string | undefined>;
72
- listPendingActivations(workItemId?: string): Promise<readonly import("./pending-activations.js").PendingActivationEntry[]>;
103
+ listPendingActivations(workItemId?: string): Promise<import("./pending-activations.js").PendingActivationEntry[]>;
73
104
  listWaiting(signalKind?: SignalName): Promise<WorkflowInstanceView[]>;
74
105
  expireTimedOutWaits(context: CommandContext): Promise<WorkflowInstanceView[]>;
75
106
  listAll(): Promise<WorkflowInstanceView[]>;
@@ -101,4 +132,13 @@ export type OperationCoordinator = <Result>(operation: () => Promise<Result>) =>
101
132
  export interface WatchChildCancellation {
102
133
  cancelSupersededWatchChildren(workflowInstanceIds: readonly string[]): Promise<unknown>;
103
134
  }
104
- export declare const createOrchestrationService: (journal: EventJournal, work: WorkService, definitions: Readonly<Record<string, CompiledWorkflow>>, projections?: ProjectionStore, isAgentActivity?: AgentActivityClassifier) => OrchestrationService;
135
+ export declare const createOrchestrationService: (journal: EventJournal, work: WorkService, definitions: Readonly<Record<string, CompiledWorkflow>>, projections?: ProjectionStore, isAgentActivity?: AgentActivityClassifier, delegation?: DelegationDependenciesFactory) => OrchestrationService;
136
+ /** Immutable dependencies are resolved once; callbacks may refer to services composed later. */
137
+ type DelegationDependenciesFactory = (queries: {
138
+ isActivationAccepted: (activationId: string, workItemId?: string) => Promise<boolean>;
139
+ }) => {
140
+ artifacts: DelegationArtifacts;
141
+ repositories?: DelegationRepositories;
142
+ runHasEnded: (runId: string) => Promise<boolean>;
143
+ };
144
+ 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,44 @@ 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
+ repositories: dependencies?.repositories,
58
+ runHasEnded: dependencies?.runHasEnded ?? unavailableRunCompletion,
59
+ });
60
+ this.advanceWorkflow = new AdvanceWorkflow(repository, this.startWorkflow, (command, context) => this.acceptOutcome(command, context), isAgentActivity);
43
61
  this.acceptWorkflowSignal = new AcceptSignal(repository, this.startWorkflow, work);
62
+ 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
63
  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));
64
+ this.acceptActivityOutcome = new AcceptActivityOutcome(repository, this.startWorkflow, async (context) => {
65
+ await this.delegatedWork.reconcile(context);
66
+ await this.childWorkflows.reconcileChildCompletions(context);
67
+ await this.deferredSignals.reconcile(context);
68
+ });
69
+ }
70
+ repositoryAssignment(workItemId) {
71
+ return this.delegatedWork.repositoryFor(workItemId);
72
+ }
73
+ async isActivationAccepted(id, item) {
74
+ return (await this.repository.list()).some(({ view }) => view !== null &&
75
+ (item === undefined || view.workItemId === item) &&
76
+ view.acceptedOutcomes.some((accepted) => accepted === id));
77
+ }
78
+ joinedDelegationResults(id, cohortId) {
79
+ return this.delegatedWork.results(id, cohortId);
46
80
  }
47
81
  start(command, context) {
48
82
  return this.startWorkflow.execute(command, context);
@@ -54,13 +88,19 @@ export class OrchestrationService {
54
88
  return this.childWorkflows.rejectCausalActivation(request, context);
55
89
  }
56
90
  acceptOutcome(command, context) {
57
- return this.transitionWatchChildren(context, () => this.acceptActivityOutcome.execute(command, context));
91
+ return this.transitionWatchChildren(context, () => this.delegationGate.outcome(command.workflowInstanceId, command.activationId, () => this.acceptActivityOutcome.execute(command, context), async () => {
92
+ await this.reconcileChildCompletions(context);
93
+ return (await this.repository.loadRequired(command.workflowInstanceId)).view;
94
+ }));
58
95
  }
59
96
  waitForSignal(workflowInstanceId, expectation, context) {
60
- return this.transitionWatchChildren(context, () => this.acceptWorkflowSignal.wait(workflowInstanceId, expectation, context));
97
+ return this.transitionWatchChildren(context, async () => {
98
+ await this.delegationGate.run(workflowInstanceId, () => this.acceptWorkflowSignal.wait(workflowInstanceId, expectation, context));
99
+ return this.deferredSignals.reconcileWorkflow(workflowInstanceId, context);
100
+ });
61
101
  }
62
102
  acceptSignal(workflowInstanceId, signal, context) {
63
- return this.coordinateAcceptSignal(() => this.transitionWatchChildren(context, () => this.acceptWorkflowSignal.execute(workflowInstanceId, signal, context)));
103
+ return this.coordinateAcceptSignal(() => this.transitionWatchChildren(context, () => this.deferredSignals.accept(workflowInstanceId, signal, context)));
64
104
  }
65
105
  setAcceptSignalOperationCoordinator(coordinator) {
66
106
  this.coordinateAcceptSignal = coordinator;
@@ -69,7 +109,7 @@ export class OrchestrationService {
69
109
  this.watchChildCancellation = cancellation;
70
110
  }
71
111
  requestSupplementalActivity(workflowInstanceId, request, context) {
72
- return this.advanceWorkflow.requestSupplementalActivity(workflowInstanceId, request, context);
112
+ return this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.requestSupplementalActivity(workflowInstanceId, request, context));
73
113
  }
74
114
  async applyConversationCommand(workItemId, input, context) {
75
115
  return (await this.applyConversationCommandWithFeedback(workItemId, input, context)).applied;
@@ -156,16 +196,16 @@ export class OrchestrationService {
156
196
  return this.transitionWatchChildren(context, () => this.advanceWorkflow.blockAwaitingActivation(workflowInstanceId, activationId, reason, context));
157
197
  }
158
198
  resolveExecutionFailure(workflowInstanceId, input, context) {
159
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.resolveExecutionFailure(workflowInstanceId, input, context));
199
+ return this.transitionWatchChildren(context, () => this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.resolveExecutionFailure(workflowInstanceId, input, context)));
160
200
  }
161
201
  retryRunnerQuotaFailure(workflowInstanceId, input, context) {
162
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.retryRunnerQuotaFailure(workflowInstanceId, input, context));
202
+ return this.transitionWatchChildren(context, () => this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.retryRunnerQuotaFailure(workflowInstanceId, input, context)));
163
203
  }
164
204
  retryBlockedFailedStage(workflowInstanceId, context) {
165
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.retryBlockedFailedStage(workflowInstanceId, context));
205
+ return this.transitionWatchChildren(context, () => this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.retryBlockedFailedStage(workflowInstanceId, context)));
166
206
  }
167
207
  restartBlockedFailedStage(workflowInstanceId, context) {
168
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.restartBlockedFailedStage(workflowInstanceId, context));
208
+ return this.transitionWatchChildren(context, () => this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.restartBlockedFailedStage(workflowInstanceId, context)));
169
209
  }
170
210
  async resumeBlockedStageForChanges(workflowInstanceId, context) {
171
211
  const current = await this.advanceWorkflow.get(workflowInstanceId);
@@ -177,7 +217,7 @@ export class OrchestrationService {
177
217
  if (!current.operatorRetryCommandIds.includes(context.commandId) &&
178
218
  !selectChangesResumeTargets((await this.advanceWorkflow.listAll()).filter((workflow) => workflow.workItemId === current.workItemId)).some((workflow) => workflow.workflowInstanceId === workflowInstanceId))
179
219
  return current;
180
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.resumeBlockedStageForChanges(workflowInstanceId, context));
220
+ return this.transitionWatchChildren(context, () => this.delegationGate.run(workflowInstanceId, () => this.advanceWorkflow.resumeBlockedStageForChanges(workflowInstanceId, context)));
181
221
  }
182
222
  async resumeBlockedStageForReply(workflowInstanceId, context) {
183
223
  const current = await this.advanceWorkflow.get(workflowInstanceId);
@@ -222,14 +262,15 @@ export class OrchestrationService {
222
262
  getPrimaryWorkflowInstanceId(workItemId) {
223
263
  return this.childWorkflows.getPrimaryWorkflowInstanceId(workItemId);
224
264
  }
225
- listPendingActivations(workItemId) {
226
- return this.advanceWorkflow.listPendingActivations(workItemId);
265
+ async listPendingActivations(workItemId) {
266
+ const entries = await this.advanceWorkflow.listPendingActivations(workItemId);
267
+ return entries.filter((entry) => this.delegationGate.allows(entry.workflow));
227
268
  }
228
269
  listWaiting(signalKind) {
229
270
  return this.advanceWorkflow.listWaiting(signalKind);
230
271
  }
231
- expireTimedOutWaits(context) {
232
- return this.advanceWorkflow.expireTimedOutWaits(context);
272
+ async expireTimedOutWaits(context) {
273
+ return expireTimedOutWaits(this.repository, context, await this.delegationGate.availableInstances());
233
274
  }
234
275
  listAll() {
235
276
  return this.advanceWorkflow.listAll();
@@ -254,8 +295,12 @@ export class OrchestrationService {
254
295
  const workflows = await Promise.all((stored?.value ?? []).map((workflowInstanceId) => this.advanceWorkflow.get(workflowInstanceId)));
255
296
  return workflows.filter((workflow) => workflow !== null);
256
297
  }
257
- reconcileChildCompletions(context) {
258
- return this.transitionWatchChildren(context, () => this.childWorkflows.reconcileChildCompletions(context));
298
+ async reconcileChildCompletions(context) {
299
+ await this.delegatedWork.reconcile(context);
300
+ return this.transitionWatchChildren(context, async () => {
301
+ await this.childWorkflows.reconcileChildCompletions(context);
302
+ await this.deferredSignals.reconcile(context);
303
+ });
259
304
  }
260
305
  async transitionWatchChildren(context, operation) {
261
306
  const before = await this.advanceWorkflow.listAll();
@@ -286,7 +331,7 @@ export class OrchestrationService {
286
331
  return this.advanceWorkflow.listResourceTransitionMatches(event);
287
332
  }
288
333
  applyResourceTransition(workflowInstanceId, target, evidenceId, context) {
289
- return this.transitionWatchChildren(context, () => this.advanceWorkflow.applyResourceTransition(workflowInstanceId, target, evidenceId, context));
334
+ return this.transitionWatchChildren(context, () => this.deferredSignals.applyTransition(workflowInstanceId, target, evidenceId, context));
290
335
  }
291
336
  }
292
337
  export class GroupBudgetExtensionIneligibleError extends Error {
@@ -303,7 +348,7 @@ async function journalGroupBudgetExhaustion(journal, workflowInstanceId) {
303
348
  : [];
304
349
  });
305
350
  }
306
- export const createOrchestrationService = (journal, work, definitions, projections, isAgentActivity) => new OrchestrationService(journal, work, definitions, projections, isAgentActivity);
351
+ export const createOrchestrationService = (journal, work, definitions, projections, isAgentActivity, delegation) => new OrchestrationService(journal, work, definitions, projections, isAgentActivity, delegation);
307
352
  function isWorkControllable(work) {
308
353
  return work !== null && !work.deleted && !work.frozen && work.state === WorkStatus.Open;
309
354
  }
@@ -316,3 +361,11 @@ function isReviewConversationCommand(command) {
316
361
  command === ConversationBuiltInCommand.Accepted ||
317
362
  command === ConversationBuiltInCommand.Changes);
318
363
  }
364
+ async function unavailableRunCompletion() {
365
+ throw new Error('Delegation adapters unavailable');
366
+ }
367
+ const unavailableArtifacts = {
368
+ validateInputs: unavailableRunCompletion,
369
+ registerChild: unavailableRunCompletion,
370
+ qualifyingOutputs: unavailableRunCompletion,
371
+ };
@@ -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
  }