@atolis-hq/wake 0.4.104 → 0.4.106

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 (161) hide show
  1. package/dist/src/activities/agent/agent-activity.js +10 -0
  2. package/dist/src/activities/contracts/activity.d.ts +28 -0
  3. package/dist/src/activities/contracts/event-schema.d.ts +314 -8
  4. package/dist/src/activities/contracts/event-schema.js +20 -2
  5. package/dist/src/activities/contracts/events.d.ts +10 -0
  6. package/dist/src/activities/contracts/vocabulary.d.ts +2 -0
  7. package/dist/src/activities/contracts/vocabulary.js +2 -0
  8. package/dist/src/activities/index.d.ts +2 -0
  9. package/dist/src/activities/index.js +2 -0
  10. package/dist/src/activities/pr/activity-support.d.ts +1 -1
  11. package/dist/src/activities/pr/activity-support.js +10 -0
  12. package/dist/src/activities/pr/application.js +8 -1
  13. package/dist/src/activities/pr/approve.d.ts +2 -1
  14. package/dist/src/activities/pr/approve.js +33 -11
  15. package/dist/src/activities/pr/check-evidence.d.ts +10 -0
  16. package/dist/src/activities/pr/check-evidence.js +16 -0
  17. package/dist/src/activities/pr/contracts.d.ts +14 -0
  18. package/dist/src/activities/pr/event-data.js +5 -1
  19. package/dist/src/activities/pr/merge.d.ts +2 -1
  20. package/dist/src/activities/pr/merge.js +54 -38
  21. package/dist/src/activities/pr/parent-scope.d.ts +65 -0
  22. package/dist/src/activities/pr/parent-scope.js +24 -0
  23. package/dist/src/activities/pr/parent-target.d.ts +45 -0
  24. package/dist/src/activities/pr/parent-target.js +59 -0
  25. package/dist/src/activities/pr/projection.js +10 -2
  26. package/dist/src/activities/pr/vocabulary.d.ts +8 -0
  27. package/dist/src/activities/pr/vocabulary.js +8 -0
  28. package/dist/src/bootstrap/activity-registry.d.ts +2 -2
  29. package/dist/src/bootstrap/activity-registry.js +3 -3
  30. package/dist/src/bootstrap/composition-root.js +11 -2
  31. package/dist/src/bootstrap/config/root-schema.d.ts +22 -0
  32. package/dist/src/bootstrap/delegation-authority.js +17 -0
  33. package/dist/src/bootstrap/delivery-integration.d.ts +9 -0
  34. package/dist/src/bootstrap/delivery-integration.js +46 -0
  35. package/dist/src/bootstrap/surface-api-delivery.js +52 -0
  36. package/dist/src/bootstrap/version.js +1 -1
  37. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +5 -1
  38. package/dist/src/control-plane/application/advance-once-dispatch.js +12 -6
  39. package/dist/src/execution/application/candidate-workspaces.d.ts +13 -0
  40. package/dist/src/execution/application/candidate-workspaces.js +75 -0
  41. package/dist/src/execution/application/execution-service.js +37 -11
  42. package/dist/src/execution/application/maintenance-workspaces.d.ts +17 -0
  43. package/dist/src/execution/application/maintenance-workspaces.js +84 -0
  44. package/dist/src/execution/application/run-lifecycle.js +2 -0
  45. package/dist/src/execution/contracts/candidate.d.ts +31 -0
  46. package/dist/src/execution/contracts/candidate.js +40 -0
  47. package/dist/src/execution/contracts/commands.d.ts +4 -0
  48. package/dist/src/execution/contracts/events.d.ts +24 -0
  49. package/dist/src/execution/contracts/events.js +4 -0
  50. package/dist/src/execution/contracts/maintenance.d.ts +36 -0
  51. package/dist/src/execution/contracts/maintenance.js +44 -0
  52. package/dist/src/execution/contracts/repository-assignment.d.ts +5 -0
  53. package/dist/src/execution/contracts/repository-assignment.js +8 -0
  54. package/dist/src/execution/contracts/views.d.ts +4 -0
  55. package/dist/src/execution/contracts/vocabulary.d.ts +5 -0
  56. package/dist/src/execution/contracts/vocabulary.js +4 -0
  57. package/dist/src/execution/contracts/workspace.d.ts +8 -0
  58. package/dist/src/execution/index.d.ts +2 -0
  59. package/dist/src/execution/index.js +2 -0
  60. package/dist/src/execution/infrastructure/workspace/git-source.d.ts +2 -2
  61. package/dist/src/execution/infrastructure/workspace/git-source.js +18 -1
  62. package/dist/src/execution/infrastructure/workspace/git-workspace.d.ts +2 -4
  63. package/dist/src/execution/infrastructure/workspace/git-workspace.js +12 -1
  64. package/dist/src/integrations/application/delegation-outputs.js +1 -1
  65. package/dist/src/integrations/application/delivery-integration-verification.d.ts +13 -0
  66. package/dist/src/integrations/application/delivery-integration-verification.js +68 -0
  67. package/dist/src/integrations/delivery/application/delivery-projector.js +3 -0
  68. package/dist/src/integrations/delivery/application/merged-delivery-evidence.js +9 -1
  69. package/dist/src/integrations/delivery/contracts/views.d.ts +2 -0
  70. package/dist/src/integrations/fake/external-source.d.ts +5 -2
  71. package/dist/src/integrations/fake/external-source.js +12 -2
  72. package/dist/src/integrations/fake/inbound-translator.js +7 -2
  73. package/dist/src/integrations/fake/provider.d.ts +17 -0
  74. package/dist/src/integrations/fake/provider.js +18 -2
  75. package/dist/src/integrations/github/application/pull-request-translation.js +2 -0
  76. package/dist/src/integrations/github/contracts/events.d.ts +3 -1
  77. package/dist/src/integrations/github/contracts/events.js +3 -1
  78. package/dist/src/integrations/github/contracts/payloads.d.ts +23 -0
  79. package/dist/src/integrations/github/infrastructure/check-execution.d.ts +9 -0
  80. package/dist/src/integrations/github/infrastructure/check-execution.js +68 -0
  81. package/dist/src/integrations/github/infrastructure/checkout-revision.d.ts +2 -0
  82. package/dist/src/integrations/github/infrastructure/checkout-revision.js +23 -0
  83. package/dist/src/integrations/github/infrastructure/client.d.ts +2 -0
  84. package/dist/src/integrations/github/infrastructure/client.js +4 -0
  85. package/dist/src/integrations/github/infrastructure/pr-check-subject.d.ts +7 -0
  86. package/dist/src/integrations/github/infrastructure/pr-check-subject.js +77 -0
  87. package/dist/src/integrations/github/infrastructure/pr-evidence.d.ts +6 -3
  88. package/dist/src/integrations/github/infrastructure/pr-evidence.js +1 -1
  89. package/dist/src/integrations/github/infrastructure/pr-source.d.ts +3 -5
  90. package/dist/src/integrations/github/infrastructure/pr-source.js +11 -1
  91. package/dist/src/integrations/github/infrastructure/workflow-run-evidence.d.ts +5 -0
  92. package/dist/src/integrations/github/infrastructure/workflow-run-evidence.js +22 -0
  93. package/dist/src/integrations/index.d.ts +1 -0
  94. package/dist/src/integrations/index.js +1 -0
  95. package/dist/src/orchestration/application/delegated-work.d.ts +5 -0
  96. package/dist/src/orchestration/application/delegated-work.js +10 -0
  97. package/dist/src/orchestration/application/delegation-commands.d.ts +16 -0
  98. package/dist/src/orchestration/application/delivery-coordinator.d.ts +348 -0
  99. package/dist/src/orchestration/application/delivery-coordinator.js +239 -0
  100. package/dist/src/orchestration/application/delivery-facts-reader.d.ts +9 -0
  101. package/dist/src/orchestration/application/delivery-facts-reader.js +47 -0
  102. package/dist/src/orchestration/application/delivery-integration-reader.d.ts +9 -0
  103. package/dist/src/orchestration/application/delivery-integration-reader.js +23 -0
  104. package/dist/src/orchestration/application/delivery-integration-service.d.ts +50 -0
  105. package/dist/src/orchestration/application/delivery-integration-service.js +228 -0
  106. package/dist/src/orchestration/application/delivery-preparation.d.ts +16 -0
  107. package/dist/src/orchestration/application/delivery-preparation.js +105 -0
  108. package/dist/src/orchestration/application/delivery-sources.d.ts +10 -0
  109. package/dist/src/orchestration/application/delivery-sources.js +41 -0
  110. package/dist/src/orchestration/application/orchestration-repository.d.ts +3 -1
  111. package/dist/src/orchestration/application/orchestration-repository.js +10 -1
  112. package/dist/src/orchestration/application/orchestration-service.d.ts +341 -2
  113. package/dist/src/orchestration/application/orchestration-service.js +86 -4
  114. package/dist/src/orchestration/contracts/config.d.ts +22 -0
  115. package/dist/src/orchestration/contracts/config.js +13 -1
  116. package/dist/src/orchestration/contracts/delegation-ports.d.ts +4 -0
  117. package/dist/src/orchestration/contracts/delegation.d.ts +13 -1
  118. package/dist/src/orchestration/contracts/delegation.js +5 -0
  119. package/dist/src/orchestration/contracts/delivery-ports.d.ts +53 -0
  120. package/dist/src/orchestration/contracts/delivery-ports.js +1 -0
  121. package/dist/src/orchestration/contracts/delivery.d.ts +310 -0
  122. package/dist/src/orchestration/contracts/delivery.js +186 -0
  123. package/dist/src/orchestration/contracts/event-decoder.js +14 -1
  124. package/dist/src/orchestration/contracts/event-factory.js +8 -0
  125. package/dist/src/orchestration/contracts/events.d.ts +10 -0
  126. package/dist/src/orchestration/contracts/events.js +4 -0
  127. package/dist/src/orchestration/contracts/views.d.ts +3 -0
  128. package/dist/src/orchestration/contracts/vocabulary.d.ts +90 -0
  129. package/dist/src/orchestration/contracts/vocabulary.js +82 -0
  130. package/dist/src/orchestration/domain/compile-diagnostics.d.ts +1 -1
  131. package/dist/src/orchestration/domain/compile-diagnostics.js +5 -0
  132. package/dist/src/orchestration/domain/compiler.js +2 -0
  133. package/dist/src/orchestration/domain/delivery-candidate.d.ts +9 -0
  134. package/dist/src/orchestration/domain/delivery-candidate.js +105 -0
  135. package/dist/src/orchestration/domain/delivery-facts.d.ts +89 -0
  136. package/dist/src/orchestration/domain/delivery-facts.js +66 -0
  137. package/dist/src/orchestration/domain/delivery-integration-policy.d.ts +7 -0
  138. package/dist/src/orchestration/domain/delivery-integration-policy.js +15 -0
  139. package/dist/src/orchestration/domain/delivery-integration.d.ts +54 -0
  140. package/dist/src/orchestration/domain/delivery-integration.js +144 -0
  141. package/dist/src/orchestration/domain/delivery-qa.d.ts +33 -0
  142. package/dist/src/orchestration/domain/delivery-qa.js +97 -0
  143. package/dist/src/orchestration/domain/delivery-replacement.d.ts +9 -0
  144. package/dist/src/orchestration/domain/delivery-replacement.js +54 -0
  145. package/dist/src/orchestration/domain/delivery-selection.d.ts +17 -0
  146. package/dist/src/orchestration/domain/delivery-selection.js +132 -0
  147. package/dist/src/orchestration/domain/delivery-workflow-policy.d.ts +6 -0
  148. package/dist/src/orchestration/domain/delivery-workflow-policy.js +32 -0
  149. package/dist/src/orchestration/domain/operator-retry-policy.js +24 -13
  150. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +1 -0
  151. package/dist/src/orchestration/domain/workflow-instance-events.js +12 -0
  152. package/dist/src/orchestration/index.d.ts +3 -0
  153. package/dist/src/orchestration/index.js +1 -0
  154. package/dist/src/surfaces/api/contracts/transport-values.js +1 -0
  155. package/dist/src/surfaces/api/contracts/work.d.ts +42 -0
  156. package/dist/src/surfaces/api/presenters/execution.js +1 -0
  157. package/dist/src/surfaces/mcp/delegation.js +36 -1
  158. package/dist/src/surfaces/web-assets/assets/index-ih1h3dxC.js +1192 -0
  159. package/dist/src/surfaces/web-assets/index.html +1 -1
  160. package/package.json +1 -1
  161. package/dist/src/surfaces/web-assets/assets/index-C5R-aWzH.js +0 -1192
@@ -0,0 +1,239 @@
1
+ import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
2
+ import { DelegationConflictError, delegationSubmissionSchema, } from '../contracts/delegation.js';
3
+ import { DeliveryRejectionError, deliveryCandidateCommandSchema, deliveryMaintenanceCommandSchema, deliveryQaCommandSchema, deliverySelectionCommandSchema, } from '../contracts/delivery.js';
4
+ import { OrchestrationEventType } from '../contracts/events.js';
5
+ import { stageName } from '../contracts/identifiers.js';
6
+ import { DelegationConflictCode, DeliveryCompletion, DeliveryRejection, QaVerdict, WorkflowStatus, } from '../contracts/vocabulary.js';
7
+ import { planCandidate } from '../domain/delivery-candidate.js';
8
+ import { currentSelection, requirements } from '../domain/delivery-facts.js';
9
+ import { assertQa, completionDecision, deliveryState } from '../domain/delivery-qa.js';
10
+ import { originalOf } from '../domain/delivery-replacement.js';
11
+ import { reviseSelection } from '../domain/delivery-selection.js';
12
+ import { delegationDraft } from './delegation-ledger.js';
13
+ import { readDeliveryFacts } from './delivery-facts-reader.js';
14
+ import { DeliveryIntegrationService } from './delivery-integration-service.js';
15
+ import { DeliveryPreparation } from './delivery-preparation.js';
16
+ import { verifyCandidateSources } from './delivery-sources.js';
17
+ /**
18
+ * Agent-led parent QA over the delegated delivery. The parent agent chooses what to select,
19
+ * assemble, test and repair; Wake only records those choices against exact outputs and revisions,
20
+ * rejects anything that would waive a requirement or vouch for different code, and reports what
21
+ * is stale, blocked or exhausted. Every fact lives in the parent's journal stream.
22
+ */
23
+ export class DeliveryCoordinator {
24
+ repository;
25
+ dependencies;
26
+ preparation;
27
+ integration;
28
+ constructor(repository, dependencies) {
29
+ this.repository = repository;
30
+ this.dependencies = dependencies;
31
+ this.preparation = new DeliveryPreparation(repository, dependencies);
32
+ this.integration = new DeliveryIntegrationService(repository, dependencies);
33
+ }
34
+ authorizeParentAction(request) {
35
+ return this.integration.authorize(request);
36
+ }
37
+ /** The targets the configured maintenance stage will lease, or undefined for other stages. */
38
+ async maintenanceTargets(id) {
39
+ const parent = (await this.repository.loadRequired(id)).view;
40
+ const stage = (await this.dependencies.definitionFor(parent)).delegation?.maintenance?.stage;
41
+ if (stage === undefined || parent.pendingActivation?.stage !== stage)
42
+ return undefined;
43
+ return this.integration.maintenanceTargets(parent);
44
+ }
45
+ /** Records what the maintaining agent actually produced as a new immutable subject. */
46
+ async recordMaintenance(caller, input, context) {
47
+ const command = deliveryMaintenanceCommandSchema.parse(input);
48
+ const parent = await this.parent(caller);
49
+ await this.assertCoordinatorStage(parent);
50
+ return this.commit(parent, context, `maintenance:${command.maintenanceId}`, (facts) => this.integration.planMaintenance(facts, command, caller, context.occurredAt));
51
+ }
52
+ async select(caller, input, context) {
53
+ const command = deliverySelectionCommandSchema.parse(input);
54
+ const parent = await this.parent(caller);
55
+ await this.assertCoordinatorStage(parent);
56
+ return this.commit(parent, context, `selection:${command.requestId}`, async (facts) => {
57
+ const { selection, replay } = reviseSelection(facts, command);
58
+ return {
59
+ result: { selection, replay },
60
+ draft: replay
61
+ ? undefined
62
+ : { eventType: OrchestrationEventType.DeliverySelectionRevised, payload: selection },
63
+ };
64
+ });
65
+ }
66
+ async recordCandidate(caller, input, context) {
67
+ const command = deliveryCandidateCommandSchema.parse(input);
68
+ const parent = await this.parent(caller);
69
+ await this.assertCoordinatorStage(parent);
70
+ const policy = (await this.dependencies.definitionFor(parent)).delegation?.qa;
71
+ return this.commit(parent, context, `candidate:${command.candidateId}`, async (facts) => {
72
+ const root = facts.reservations[0]?.rootWorkItemId;
73
+ if (root === undefined)
74
+ throw new DeliveryRejectionError(DeliveryRejection.NoSelection, 'No delegated work');
75
+ const { candidate } = planCandidate(facts, command, root);
76
+ const existing = facts.candidates.find((entry) => entry.candidateId === command.candidateId);
77
+ if (existing !== undefined && JSON.stringify(existing) !== JSON.stringify(candidate))
78
+ throw new DeliveryRejectionError(DeliveryRejection.Conflict, `Candidate ${command.candidateId} already exists with different contents`);
79
+ if (policy !== undefined && policy.recipe !== command.recipe)
80
+ throw new Error('Candidate must use the configured QA recipe');
81
+ // A replay re-proves the sources, so a restart cannot revive a candidate whose ref is gone.
82
+ await verifyCandidateSources(parent, this.dependencies.repositories, candidate, facts);
83
+ return {
84
+ result: { candidate, replay: existing !== undefined },
85
+ draft: existing !== undefined
86
+ ? undefined
87
+ : { eventType: OrchestrationEventType.DeliveryCandidateRecorded, payload: candidate },
88
+ };
89
+ });
90
+ }
91
+ async recordQa(caller, input, context) {
92
+ const command = deliveryQaCommandSchema.parse(input);
93
+ const parent = await this.parent(caller);
94
+ const definition = await this.dependencies.definitionFor(parent);
95
+ const policy = definition.delegation?.qa;
96
+ if (policy === undefined || parent.pendingActivation?.stage !== policy.stage)
97
+ throw new Error('QA verdicts require the configured QA stage');
98
+ return this.commit(parent, context, `qa:${command.qaId}`, async (facts) => {
99
+ const qa = assertQa(facts, command);
100
+ const candidate = facts.candidates.find((entry) => entry.candidateId === qa.candidateId);
101
+ await this.assertQaActor(caller, facts, candidate, qa, policy.recipe);
102
+ const recorded = facts.qa.find((entry) => entry.qaId === command.qaId);
103
+ if (recorded !== undefined) {
104
+ if (JSON.stringify({
105
+ ...recorded,
106
+ exhausted: undefined,
107
+ runId: undefined,
108
+ activationId: undefined,
109
+ }) !== JSON.stringify(qa))
110
+ throw new DeliveryRejectionError(DeliveryRejection.Conflict, `QA ${command.qaId} was already recorded differently`);
111
+ return { result: { qa: recorded, replay: true }, draft: undefined };
112
+ }
113
+ if (qa.verdict === QaVerdict.Pass) {
114
+ // A pass is only meaningful while the exact sources remain reconstructable.
115
+ const candidate = facts.candidates.find((entry) => entry.candidateId === qa.candidateId);
116
+ await verifyCandidateSources(parent, this.dependencies.repositories, candidate, facts);
117
+ }
118
+ const route = definition.stages[stageName(policy.stage)]?.on.failed;
119
+ const routeExhausted = route?.repeat !== undefined && (parent.repeatCounts[route.id] ?? 0) >= route.repeat.max;
120
+ const exhausted = qa.verdict === QaVerdict.Fail &&
121
+ (routeExhausted || (await this.preparation.noDescendantCapacity(facts)));
122
+ const payload = {
123
+ ...qa,
124
+ runId: caller.runId,
125
+ activationId: caller.activationId,
126
+ ...(exhausted ? { exhausted } : {}),
127
+ };
128
+ return {
129
+ result: { qa: payload, replay: false },
130
+ draft: { eventType: OrchestrationEventType.DeliveryQaRecorded, payload },
131
+ };
132
+ });
133
+ }
134
+ /** The inspectable delivery state: selection, staleness, candidate, QA, repair and completion. */
135
+ async inspectFor(caller) {
136
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
137
+ await this.dependencies.authority.assertCaller(caller, parent);
138
+ return this.inspect(parent.workflowInstanceId);
139
+ }
140
+ async inspect(id) {
141
+ const parent = (await this.repository.loadRequired(id)).view;
142
+ const facts = await this.facts(parent);
143
+ const state = deliveryState(facts);
144
+ const mode = (await this.dependencies.definitionFor(parent)).delegation?.completion ??
145
+ DeliveryCompletion.QaApproved;
146
+ // Only merge-required deliveries pay for provider reads; QA-approved ones never integrate.
147
+ const integration = mode === DeliveryCompletion.MergeRequired ? await this.integration.assess(facts) : null;
148
+ return {
149
+ ...state,
150
+ integration,
151
+ maintenance: facts.maintenance,
152
+ required: requirements(facts.reservations).map((requirement) => ({
153
+ cohortId: requirement.cohortId,
154
+ assignmentId: requirement.assignmentId,
155
+ outputName: requirement.outputName,
156
+ childWorkItemId: requirement.child.workItemId,
157
+ })),
158
+ selection: currentSelection(facts) ?? null,
159
+ history: facts.qa,
160
+ completion: parent.deliveryGateBlock !== undefined
161
+ ? { complete: false, reason: parent.blockReason }
162
+ : completionDecision(state, mode, integration ?? undefined),
163
+ };
164
+ }
165
+ /**
166
+ * Replacement children keep the original acceptance criteria and repository; a terminal original
167
+ * is replaced by a new child, while correcting a still-running one is not supported.
168
+ */
169
+ async assertReplacements(caller, input) {
170
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
171
+ await this.assertCoordinatorStage(parent);
172
+ const submission = delegationSubmissionSchema.safeParse(input);
173
+ const replacements = submission.success
174
+ ? submission.data.assignments.filter((entry) => entry.replaces !== undefined)
175
+ : [];
176
+ if (replacements.length === 0)
177
+ return;
178
+ await this.dependencies.authority.assertCaller(caller, parent);
179
+ const facts = await this.facts(parent);
180
+ for (const assignment of replacements) {
181
+ const original = originalOf(facts, assignment.replaces);
182
+ const view = (await this.repository.load(original.workflowInstanceId)).view;
183
+ if (view?.status !== WorkflowStatus.Completed && view?.status !== WorkflowStatus.Superseded)
184
+ throw new DelegationConflictError(DelegationConflictCode.ReplacementUnsupported, 'Correcting a child that is still running is not supported; replace it once it is complete or superseded');
185
+ }
186
+ }
187
+ completionBlock(id) {
188
+ return this.preparation.completionBlock(id);
189
+ }
190
+ prepare(id) {
191
+ return this.preparation.prepare(id);
192
+ }
193
+ async assertQaActor(caller, facts, candidate, qa, recipe) {
194
+ if (!deliveryState(facts).candidateCurrent ||
195
+ facts.candidates.at(-1)?.candidateId !== qa.candidateId)
196
+ throw new Error('QA candidate is no longer current');
197
+ if (this.dependencies.authority.assertQaCaller === undefined)
198
+ throw new Error('QA Run authority is unavailable');
199
+ await this.dependencies.authority.assertQaCaller(caller, qa.candidateId, candidate.selectionRevision, qa.revisions);
200
+ if (qa.environment.recipe !== recipe)
201
+ throw new Error('QA must use the configured recipe');
202
+ }
203
+ async assertCoordinatorStage(parent) {
204
+ const policy = (await this.dependencies.definitionFor(parent)).delegation?.qa;
205
+ if (policy !== undefined && parent.pendingActivation?.stage === policy.stage)
206
+ throw new Error('The QA stage cannot choose its own candidate or selection');
207
+ }
208
+ async parent(caller) {
209
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
210
+ await this.dependencies.authority.assertCaller(caller, parent);
211
+ if (parent.pendingActivation?.activationId !== caller.activationId ||
212
+ (parent.status !== WorkflowStatus.Active && parent.status !== WorkflowStatus.Waiting))
213
+ throw new Error('Delivery changes require the current active activation');
214
+ return parent;
215
+ }
216
+ async facts(parent) {
217
+ const { events } = await this.repository.history(parent.workflowInstanceId);
218
+ return readDeliveryFacts(this.repository, parent, events);
219
+ }
220
+ /** Re-derives facts from fresh history on every optimistic-concurrency retry. */
221
+ async commit(parent, context, key, build) {
222
+ for (;;) {
223
+ const { events, sequence } = await this.repository.history(parent.workflowInstanceId);
224
+ const { result, draft } = await build(await readDeliveryFacts(this.repository, parent, events));
225
+ if (draft === undefined)
226
+ return result;
227
+ try {
228
+ await this.repository.append(parent.workflowInstanceId, sequence, [
229
+ delegationDraft(context, key, draft, parent.workflowInstanceId),
230
+ ]);
231
+ return result;
232
+ }
233
+ catch (error) {
234
+ if (!(error instanceof WrongExpectedSequenceError))
235
+ throw error;
236
+ }
237
+ }
238
+ }
239
+ }
@@ -0,0 +1,9 @@
1
+ import { type WorkflowOrchestrationEvent } from '../contracts/events.js';
2
+ import type { WorkflowInstanceView } from '../contracts/views.js';
3
+ import type { DeliveryFacts } from '../domain/delivery-facts.js';
4
+ import type { OrchestrationRepository } from './orchestration-repository.js';
5
+ /**
6
+ * Journal-derived facts for one parent delivery: its cohorts and their selected results, what each
7
+ * child consumed, and the parent's own selection, candidate and QA facts.
8
+ */
9
+ export declare function readDeliveryFacts(repository: OrchestrationRepository, parent: WorkflowInstanceView, own: readonly WorkflowOrchestrationEvent[]): Promise<DeliveryFacts>;
@@ -0,0 +1,47 @@
1
+ import { OrchestrationEventType } from '../contracts/events.js';
2
+ /**
3
+ * Journal-derived facts for one parent delivery: its cohorts and their selected results, what each
4
+ * child consumed, and the parent's own selection, candidate and QA facts.
5
+ */
6
+ export async function readDeliveryFacts(repository, parent, own) {
7
+ const all = await repository.events();
8
+ const reservations = distinctCohorts(all.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationReserved &&
9
+ event.payload.parentWorkflowInstanceId === parent.workflowInstanceId
10
+ ? [event.payload]
11
+ : []));
12
+ const instances = new Map(reservations.flatMap((reservation) => reservation.children.map((child) => [child.workflowInstanceId, child.workItemId])));
13
+ const results = all.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationResultSelected &&
14
+ [...instances.values()].includes(event.payload.childWorkItemId)
15
+ ? [event.payload]
16
+ : []);
17
+ const consumed = new Map();
18
+ for (const { event } of all) {
19
+ if (event.eventType !== OrchestrationEventType.DelegationInputsResolved)
20
+ continue;
21
+ // Consumption receipts belong to the parent stream and identify their child in the payload.
22
+ const child = event.payload.childWorkItemId;
23
+ if (![...instances.values()].includes(child))
24
+ continue;
25
+ consumed.set(child, [...(consumed.get(child) ?? []), ...event.payload.consumed]);
26
+ }
27
+ const mine = own.map(({ event }) => event);
28
+ return {
29
+ reservations,
30
+ results,
31
+ consumed,
32
+ selections: mine.flatMap((event) => event.eventType === OrchestrationEventType.DeliverySelectionRevised ? [event.payload] : []),
33
+ candidates: mine.flatMap((event) => event.eventType === OrchestrationEventType.DeliveryCandidateRecorded ? [event.payload] : []),
34
+ qa: mine.flatMap((event) => event.eventType === OrchestrationEventType.DeliveryQaRecorded ? [event.payload] : []),
35
+ maintenance: mine.flatMap((event) => event.eventType === OrchestrationEventType.DeliveryMaintenanceRecorded ? [event.payload] : []),
36
+ };
37
+ }
38
+ function distinctCohorts(reservations) {
39
+ const seen = new Set();
40
+ return reservations.filter((entry) => {
41
+ const key = `${entry.parentWorkflowInstanceId}/${entry.cohortId}`;
42
+ if (seen.has(key))
43
+ return false;
44
+ seen.add(key);
45
+ return true;
46
+ });
47
+ }
@@ -0,0 +1,9 @@
1
+ import type { DeliveryDependencies } from '../contracts/delivery-ports.js';
2
+ import { type DeliveryFacts } from '../domain/delivery-facts.js';
3
+ import { type IntegrationAssessment } from '../domain/delivery-integration.js';
4
+ /** Reads the provider and Work facts the pure integration decision needs, fresh on every call. */
5
+ export declare class DeliveryIntegrationReader {
6
+ private readonly dependencies;
7
+ constructor(dependencies: DeliveryDependencies);
8
+ assess(facts: DeliveryFacts): Promise<IntegrationAssessment>;
9
+ }
@@ -0,0 +1,23 @@
1
+ import { currentSelection, isChange } from '../domain/delivery-facts.js';
2
+ import { assessIntegration, } from '../domain/delivery-integration.js';
3
+ /** Reads the provider and Work facts the pure integration decision needs, fresh on every call. */
4
+ export class DeliveryIntegrationReader {
5
+ dependencies;
6
+ constructor(dependencies) {
7
+ this.dependencies = dependencies;
8
+ }
9
+ async assess(facts) {
10
+ const changes = (currentSelection(facts)?.entries ?? []).flatMap((entry) => isChange(entry.output)
11
+ ? [{ child: entry.childWorkItemId, reference: entry.output.reference }]
12
+ : []);
13
+ const observations = new Map();
14
+ for (const { reference } of changes) {
15
+ const observed = await this.dependencies.integration?.observe(reference.resourceId);
16
+ if (observed !== undefined && observed !== null)
17
+ observations.set(reference.resourceId, observed);
18
+ }
19
+ const held = (await this.dependencies.unavailable?.(changes.map((change) => change.child))) ??
20
+ new Map();
21
+ return assessIntegration(facts, observations, held);
22
+ }
23
+ }
@@ -0,0 +1,50 @@
1
+ import { type ParentActionDecision, type ParentActionRequest } from '../../activities/index.js';
2
+ import type { DelegationCaller } from '../contracts/delegation.js';
3
+ import type { DeliveryDependencies } from '../contracts/delivery-ports.js';
4
+ import { type DeliveryMaintenance, type DeliveryMaintenanceCommand } from '../contracts/delivery.js';
5
+ import { OrchestrationEventType } from '../contracts/events.js';
6
+ import type { WorkflowInstanceView } from '../contracts/views.js';
7
+ import { type DeliveryFacts } from '../domain/delivery-facts.js';
8
+ import { type IntegrationAssessment } from '../domain/delivery-integration.js';
9
+ import type { OrchestrationRepository } from './orchestration-repository.js';
10
+ /**
11
+ * Governed integration of child-owned pull requests by their parent delivery. Wake derives the
12
+ * one planned next action from the parent's journal and provider facts, authorizes exactly that
13
+ * target, and verifies what a maintaining agent actually produced. The agent chooses the repair;
14
+ * nothing here authors a change, reopens a child or transfers a pull request.
15
+ */
16
+ export declare class DeliveryIntegrationService {
17
+ private readonly repository;
18
+ private readonly dependencies;
19
+ private readonly reader;
20
+ constructor(repository: OrchestrationRepository, dependencies: DeliveryDependencies);
21
+ assess(facts: DeliveryFacts): Promise<IntegrationAssessment>;
22
+ authorize(request: ParentActionRequest): Promise<ParentActionDecision>;
23
+ private verifySelected;
24
+ /**
25
+ * Validates one maintenance report against the selected subject and the provider. The result is
26
+ * a new immutable subject; the replaced head, its reviews, checks and QA stay historical.
27
+ */
28
+ planMaintenance(facts: DeliveryFacts, input: DeliveryMaintenanceCommand, caller: DelegationCaller, recordedAt: string): Promise<MaintenancePlan>;
29
+ /** Only the invocation Wake dispatched for this parent may ask, and only for its own action. */
30
+ private dispatchedMerge;
31
+ private assertAvailable;
32
+ private observeOpen;
33
+ /**
34
+ * The open pull requests a maintenance stage may lease. Merged, closed or held targets cannot
35
+ * be written to, so they are never offered.
36
+ */
37
+ maintenanceTargets(parent: WorkflowInstanceView): Promise<import("../domain/delivery-integration.js").IntegrationTarget[]>;
38
+ private facts;
39
+ }
40
+ interface MaintenancePlan {
41
+ readonly result: {
42
+ readonly maintenance: DeliveryMaintenance;
43
+ readonly replay: boolean;
44
+ };
45
+ readonly draft: {
46
+ readonly eventType: typeof OrchestrationEventType.DeliveryMaintenanceRecorded;
47
+ readonly payload: DeliveryMaintenance;
48
+ } | undefined;
49
+ }
50
+ export {};
@@ -0,0 +1,228 @@
1
+ import { BuiltInActivityName, ParentActionKind, PullRequestDenialCode, PullRequestState, } from '../../activities/index.js';
2
+ import { resourceId } from '../../resources/index.js';
3
+ import { DeliveryRejectionError, deliveryMaintenanceCommandSchema, } from '../contracts/delivery.js';
4
+ import { OrchestrationEventType } from '../contracts/events.js';
5
+ import { DeliveryCompletion, DeliveryRejection, IntegrationState, QaVerdict, } from '../contracts/vocabulary.js';
6
+ import { currentSelection, isChange, outputKey, } from '../domain/delivery-facts.js';
7
+ import { targetRequirements } from '../domain/delivery-integration-policy.js';
8
+ import { known, sameRevision } from '../domain/delivery-integration.js';
9
+ import { deliveryState } from '../domain/delivery-qa.js';
10
+ import { readDeliveryFacts } from './delivery-facts-reader.js';
11
+ import { DeliveryIntegrationReader } from './delivery-integration-reader.js';
12
+ /**
13
+ * Governed integration of child-owned pull requests by their parent delivery. Wake derives the
14
+ * one planned next action from the parent's journal and provider facts, authorizes exactly that
15
+ * target, and verifies what a maintaining agent actually produced. The agent chooses the repair;
16
+ * nothing here authors a change, reopens a child or transfers a pull request.
17
+ */
18
+ export class DeliveryIntegrationService {
19
+ repository;
20
+ dependencies;
21
+ reader;
22
+ constructor(repository, dependencies) {
23
+ this.repository = repository;
24
+ this.dependencies = dependencies;
25
+ this.reader = new DeliveryIntegrationReader(dependencies);
26
+ }
27
+ assess(facts) {
28
+ return this.reader.assess(facts);
29
+ }
30
+ async authorize(request) {
31
+ const denied = (reason) => ({
32
+ kind: 'denied',
33
+ reason,
34
+ });
35
+ const parent = (await this.repository.load(request.workflowInstanceId)).view;
36
+ if (parent === null)
37
+ return denied(PullRequestDenialCode.OutsideDelivery);
38
+ if (!(await this.dispatchedMerge(parent, request)))
39
+ return denied(PullRequestDenialCode.OutsideDelivery);
40
+ const facts = await this.facts(parent);
41
+ const state = deliveryState(facts);
42
+ if (!state.candidateCurrent || !state.qaEffective || state.qa?.verdict !== QaVerdict.Pass)
43
+ return denied(PullRequestDenialCode.DeliveryNotReady);
44
+ // Current and effective imply a candidate and QA exist; narrow them for the context below.
45
+ if (state.candidate === null || state.qa === null)
46
+ return denied(PullRequestDenialCode.DeliveryNotReady);
47
+ const assessment = await this.reader.assess(facts);
48
+ if (assessment.complete)
49
+ return { kind: 'fully-integrated' };
50
+ const { next, blocking } = assessment;
51
+ if (next === null)
52
+ return denied(blockReason(blocking));
53
+ if (!(await this.verifySelected(facts, next.output, request.action)))
54
+ return denied(PullRequestDenialCode.DeliveryNotReady);
55
+ const context = {
56
+ requestingWorkItemId: parent.workItemId,
57
+ ownerWorkItemId: next.ownerWorkItemId,
58
+ output: { childWorkItemId: next.output.childWorkItemId, outputName: next.output.outputName },
59
+ candidateId: state.candidate.candidateId,
60
+ selectionRevision: state.selectionRevision,
61
+ qaId: state.qa.qaId,
62
+ };
63
+ return {
64
+ kind: 'target',
65
+ context,
66
+ resourceId: resourceId(next.resourceId),
67
+ revision: next.revision,
68
+ };
69
+ }
70
+ async verifySelected(facts, output, action) {
71
+ const { reference } = selectedChange(facts, output);
72
+ const maintenance = facts.maintenance
73
+ .filter((item) => outputKey(item.target) === outputKey(output))
74
+ .at(-1);
75
+ return ((await this.dependencies.integration?.verifyTarget({
76
+ ...reference,
77
+ maintenanceRunId: maintenance?.producer.runId,
78
+ maintenanceRecordedAt: maintenance?.recordedAt,
79
+ ownerWorkItemId: reference.workItemId,
80
+ ...targetRequirements(facts, output, action),
81
+ })) === true);
82
+ }
83
+ /**
84
+ * Validates one maintenance report against the selected subject and the provider. The result is
85
+ * a new immutable subject; the replaced head, its reviews, checks and QA stay historical.
86
+ */
87
+ async planMaintenance(facts, input, caller, recordedAt) {
88
+ const command = deliveryMaintenanceCommandSchema.parse(input);
89
+ const { reference, childWorkItemId } = selectedChange(facts, command.target);
90
+ const recorded = facts.maintenance.find((item) => item.maintenanceId === command.maintenanceId);
91
+ if (recorded !== undefined)
92
+ return replayPlan(recorded, command);
93
+ if (!sameRevision(command.expectedRevision, reference.revision))
94
+ throw new DeliveryRejectionError(DeliveryRejection.MaintenanceMismatch, `Maintenance must start from the current subject ${reference.revision}, not ${command.expectedRevision}`);
95
+ await this.assertAvailable(childWorkItemId);
96
+ const observed = await this.observeOpen(reference.resourceId);
97
+ if (!sameRevision(observed.headRevision, command.revision))
98
+ throw new DeliveryRejectionError(DeliveryRejection.MaintenanceMismatch, `The provider reports head ${observed.headRevision}, not the reported ${command.revision}`);
99
+ if (sameRevision(command.revision, reference.revision) &&
100
+ command.pullRequestBase === reference.pullRequestBase &&
101
+ observed.baseRevision === reference.baseRevision)
102
+ throw new DeliveryRejectionError(DeliveryRejection.NotMaintainable, 'Maintenance changed neither the head nor the base subject');
103
+ if (!(await this.dependencies.integration?.verifyTarget({
104
+ ...reference,
105
+ ownerWorkItemId: reference.workItemId,
106
+ revision: command.revision,
107
+ pullRequestBase: command.pullRequestBase,
108
+ requireReview: false,
109
+ requireChecks: false,
110
+ })))
111
+ throw new DeliveryRejectionError(DeliveryRejection.MaintenanceMismatch, 'The provider must verify the maintained repository, branch, head, base and original owner');
112
+ // The Run must hold this target's branch lease, and no earlier writer may be unresolved.
113
+ await this.dependencies.integration.assertMaintenanceWriter({
114
+ workflowInstanceId: caller.workflowInstanceId,
115
+ activationId: caller.activationId,
116
+ runId: caller.runId,
117
+ childWorkItemId: reference.workItemId,
118
+ resourceId: reference.resourceId,
119
+ revision: reference.revision,
120
+ });
121
+ const maintenance = {
122
+ maintenanceId: command.maintenanceId,
123
+ target: command.target,
124
+ kind: command.kind,
125
+ resourceId: reference.resourceId,
126
+ repositoryResourceId: reference.repositoryResourceId,
127
+ previous: {
128
+ revision: reference.revision,
129
+ pullRequestBase: reference.pullRequestBase,
130
+ ...(reference.baseRevision === undefined ? {} : { baseRevision: reference.baseRevision }),
131
+ },
132
+ current: {
133
+ revision: command.revision,
134
+ pullRequestBase: command.pullRequestBase,
135
+ ...(known(observed.baseRevision) ? { baseRevision: observed.baseRevision } : {}),
136
+ },
137
+ recordedAt,
138
+ producer: { runId: caller.runId, activationId: caller.activationId },
139
+ };
140
+ return {
141
+ result: { maintenance, replay: false },
142
+ draft: {
143
+ eventType: OrchestrationEventType.DeliveryMaintenanceRecorded,
144
+ payload: maintenance,
145
+ },
146
+ };
147
+ }
148
+ /** Only the invocation Wake dispatched for this parent may ask, and only for its own action. */
149
+ async dispatchedMerge(parent, request) {
150
+ const policy = (await this.dependencies.definitionFor(parent)).delegation;
151
+ const expected = request.action === ParentActionKind.Merge
152
+ ? BuiltInActivityName.PullRequestMerge
153
+ : BuiltInActivityName.PullRequestApprove;
154
+ return (policy?.qa !== undefined &&
155
+ policy.completion === DeliveryCompletion.MergeRequired &&
156
+ parent.pendingActivation?.activationId === request.activationId &&
157
+ parent.pendingActivation.activity === expected);
158
+ }
159
+ async assertAvailable(childWorkItemId) {
160
+ const unavailable = await this.dependencies.unavailable?.([childWorkItemId]);
161
+ if (unavailable?.has(childWorkItemId) === true)
162
+ throw new DeliveryRejectionError(DeliveryRejection.NotMaintainable, unavailable.get(childWorkItemId));
163
+ }
164
+ async observeOpen(resourceId) {
165
+ const integration = this.dependencies.integration;
166
+ if (integration === undefined)
167
+ throw new DeliveryRejectionError(DeliveryRejection.MaintenanceMismatch, 'Provider verification of maintenance is unavailable');
168
+ const observed = await integration.observe(resourceId);
169
+ if (observed === null)
170
+ throw new DeliveryRejectionError(DeliveryRejection.MaintenanceMismatch, 'The pull request has not been observed from the provider');
171
+ if (observed.state !== PullRequestState.Open)
172
+ throw new DeliveryRejectionError(DeliveryRejection.NotMaintainable, `A ${observed.state} pull request cannot be maintained`);
173
+ return observed;
174
+ }
175
+ /**
176
+ * The open pull requests a maintenance stage may lease. Merged, closed or held targets cannot
177
+ * be written to, so they are never offered.
178
+ */
179
+ async maintenanceTargets(parent) {
180
+ const assessment = await this.reader.assess(await this.facts(parent));
181
+ const open = [
182
+ IntegrationState.Ready,
183
+ IntegrationState.AwaitingLowerLayer,
184
+ IntegrationState.MaintenanceRequired,
185
+ ];
186
+ return assessment.targets.filter((target) => open.includes(target.state));
187
+ }
188
+ async facts(parent) {
189
+ const { events } = await this.repository.history(parent.workflowInstanceId);
190
+ return readDeliveryFacts(this.repository, parent, events);
191
+ }
192
+ }
193
+ function selectedChange(facts, target) {
194
+ const entry = currentSelection(facts)?.entries.find((candidate) => candidate.childWorkItemId === target.childWorkItemId &&
195
+ candidate.output.name === target.outputName);
196
+ if (entry === undefined || !isChange(entry.output))
197
+ throw new DeliveryRejectionError(DeliveryRejection.NotMaintainable, `${outputKey(target)} is not a selected change`);
198
+ return { reference: entry.output.reference, childWorkItemId: entry.childWorkItemId };
199
+ }
200
+ /** A repeated report is idempotent only when it says exactly what was recorded. */
201
+ function replayPlan(recorded, command) {
202
+ const same = outputKey(recorded.target) === outputKey(command.target) &&
203
+ recorded.kind === command.kind &&
204
+ sameRevision(recorded.current.revision, command.revision) &&
205
+ recorded.current.pullRequestBase === command.pullRequestBase &&
206
+ sameRevision(recorded.previous.revision, command.expectedRevision);
207
+ if (!same)
208
+ throw new DeliveryRejectionError(DeliveryRejection.Conflict, `Maintenance ${command.maintenanceId} was already recorded differently`);
209
+ return {
210
+ result: { maintenance: recorded, replay: true },
211
+ draft: undefined,
212
+ };
213
+ }
214
+ function blockReason(blocking) {
215
+ switch (blocking?.state) {
216
+ case IntegrationState.Held:
217
+ return PullRequestDenialCode.TargetHeld;
218
+ case IntegrationState.MaintenanceRequired:
219
+ case IntegrationState.AwaitingLowerLayer:
220
+ return PullRequestDenialCode.MaintenanceRequired;
221
+ case IntegrationState.Closed:
222
+ return PullRequestDenialCode.Closed;
223
+ case IntegrationState.Unobserved:
224
+ return PullRequestDenialCode.MissingResource;
225
+ default:
226
+ return PullRequestDenialCode.DeliveryNotReady;
227
+ }
228
+ }
@@ -0,0 +1,16 @@
1
+ import { type ExecutionCandidate } from '../../execution/index.js';
2
+ import type { DeliveryDependencies } from '../contracts/delivery-ports.js';
3
+ import type { DeliveryCompletionBlock } from '../contracts/delivery.js';
4
+ import { type DeliveryFacts } from '../domain/delivery-facts.js';
5
+ import type { OrchestrationRepository } from './orchestration-repository.js';
6
+ export declare class DeliveryPreparation {
7
+ private readonly repository;
8
+ private readonly dependencies;
9
+ private readonly integration;
10
+ constructor(repository: OrchestrationRepository, dependencies: DeliveryDependencies);
11
+ completionBlock(id: string): Promise<DeliveryCompletionBlock | undefined>;
12
+ prepare(id: string): Promise<ExecutionCandidate | undefined>;
13
+ noDescendantCapacity(facts: DeliveryFacts): Promise<boolean>;
14
+ private delegatingStage;
15
+ private facts;
16
+ }