@atolis-hq/wake 0.4.104 → 0.4.105

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 (84) hide show
  1. package/dist/src/activities/agent/agent-activity.js +3 -0
  2. package/dist/src/activities/contracts/activity.d.ts +16 -0
  3. package/dist/src/bootstrap/config/root-schema.d.ts +16 -0
  4. package/dist/src/bootstrap/delegation-authority.js +17 -0
  5. package/dist/src/bootstrap/surface-api-delivery.js +25 -0
  6. package/dist/src/bootstrap/version.js +1 -1
  7. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +3 -1
  8. package/dist/src/control-plane/application/advance-once-dispatch.js +4 -2
  9. package/dist/src/execution/application/candidate-workspaces.d.ts +13 -0
  10. package/dist/src/execution/application/candidate-workspaces.js +75 -0
  11. package/dist/src/execution/application/execution-service.js +27 -11
  12. package/dist/src/execution/application/run-lifecycle.js +1 -0
  13. package/dist/src/execution/contracts/candidate.d.ts +31 -0
  14. package/dist/src/execution/contracts/candidate.js +40 -0
  15. package/dist/src/execution/contracts/commands.d.ts +2 -0
  16. package/dist/src/execution/contracts/events.d.ts +11 -0
  17. package/dist/src/execution/contracts/events.js +2 -0
  18. package/dist/src/execution/contracts/repository-assignment.d.ts +5 -0
  19. package/dist/src/execution/contracts/repository-assignment.js +8 -0
  20. package/dist/src/execution/contracts/views.d.ts +2 -0
  21. package/dist/src/execution/contracts/vocabulary.d.ts +5 -0
  22. package/dist/src/execution/contracts/vocabulary.js +4 -0
  23. package/dist/src/execution/contracts/workspace.d.ts +6 -0
  24. package/dist/src/execution/index.d.ts +1 -0
  25. package/dist/src/execution/index.js +1 -0
  26. package/dist/src/execution/infrastructure/workspace/git-source.d.ts +2 -2
  27. package/dist/src/execution/infrastructure/workspace/git-source.js +18 -1
  28. package/dist/src/execution/infrastructure/workspace/git-workspace.d.ts +2 -4
  29. package/dist/src/execution/infrastructure/workspace/git-workspace.js +12 -1
  30. package/dist/src/orchestration/application/delegated-work.d.ts +5 -0
  31. package/dist/src/orchestration/application/delegated-work.js +10 -0
  32. package/dist/src/orchestration/application/delegation-commands.d.ts +13 -0
  33. package/dist/src/orchestration/application/delivery-coordinator.d.ts +279 -0
  34. package/dist/src/orchestration/application/delivery-coordinator.js +213 -0
  35. package/dist/src/orchestration/application/delivery-facts-reader.d.ts +9 -0
  36. package/dist/src/orchestration/application/delivery-facts-reader.js +46 -0
  37. package/dist/src/orchestration/application/delivery-preparation.d.ts +15 -0
  38. package/dist/src/orchestration/application/delivery-preparation.js +100 -0
  39. package/dist/src/orchestration/application/delivery-sources.d.ts +10 -0
  40. package/dist/src/orchestration/application/delivery-sources.js +41 -0
  41. package/dist/src/orchestration/application/orchestration-repository.d.ts +3 -1
  42. package/dist/src/orchestration/application/orchestration-repository.js +10 -1
  43. package/dist/src/orchestration/application/orchestration-service.d.ts +268 -0
  44. package/dist/src/orchestration/application/orchestration-service.js +33 -4
  45. package/dist/src/orchestration/contracts/config.d.ts +16 -0
  46. package/dist/src/orchestration/contracts/config.js +7 -1
  47. package/dist/src/orchestration/contracts/delegation-ports.d.ts +4 -0
  48. package/dist/src/orchestration/contracts/delegation.d.ts +13 -1
  49. package/dist/src/orchestration/contracts/delegation.js +5 -0
  50. package/dist/src/orchestration/contracts/delivery-ports.d.ts +9 -0
  51. package/dist/src/orchestration/contracts/delivery-ports.js +1 -0
  52. package/dist/src/orchestration/contracts/delivery.d.ts +252 -0
  53. package/dist/src/orchestration/contracts/delivery.js +134 -0
  54. package/dist/src/orchestration/contracts/event-decoder.js +13 -1
  55. package/dist/src/orchestration/contracts/event-factory.js +6 -0
  56. package/dist/src/orchestration/contracts/events.d.ts +8 -0
  57. package/dist/src/orchestration/contracts/events.js +3 -0
  58. package/dist/src/orchestration/contracts/views.d.ts +3 -0
  59. package/dist/src/orchestration/contracts/vocabulary.d.ts +47 -0
  60. package/dist/src/orchestration/contracts/vocabulary.js +43 -0
  61. package/dist/src/orchestration/domain/compiler.js +2 -0
  62. package/dist/src/orchestration/domain/delivery-candidate.d.ts +9 -0
  63. package/dist/src/orchestration/domain/delivery-candidate.js +92 -0
  64. package/dist/src/orchestration/domain/delivery-facts.d.ts +83 -0
  65. package/dist/src/orchestration/domain/delivery-facts.js +34 -0
  66. package/dist/src/orchestration/domain/delivery-qa.d.ts +32 -0
  67. package/dist/src/orchestration/domain/delivery-qa.js +77 -0
  68. package/dist/src/orchestration/domain/delivery-replacement.d.ts +9 -0
  69. package/dist/src/orchestration/domain/delivery-replacement.js +54 -0
  70. package/dist/src/orchestration/domain/delivery-selection.d.ts +17 -0
  71. package/dist/src/orchestration/domain/delivery-selection.js +132 -0
  72. package/dist/src/orchestration/domain/delivery-workflow-policy.d.ts +4 -0
  73. package/dist/src/orchestration/domain/delivery-workflow-policy.js +13 -0
  74. package/dist/src/orchestration/domain/operator-retry-policy.js +24 -13
  75. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +1 -0
  76. package/dist/src/orchestration/domain/workflow-instance-events.js +11 -0
  77. package/dist/src/orchestration/index.d.ts +2 -0
  78. package/dist/src/orchestration/index.js +1 -0
  79. package/dist/src/surfaces/api/contracts/work.d.ts +16 -0
  80. package/dist/src/surfaces/mcp/delegation.js +32 -1
  81. package/dist/src/surfaces/web-assets/assets/index-BfhxlN_h.js +1192 -0
  82. package/dist/src/surfaces/web-assets/index.html +1 -1
  83. package/package.json +1 -1
  84. package/dist/src/surfaces/web-assets/assets/index-C5R-aWzH.js +0 -1192
@@ -1,10 +1,8 @@
1
1
  import { type RepositoryAssignment } from '../../contracts/repository-assignment.js';
2
2
  import type { RunView } from '../../contracts/views.js';
3
- import type { WorkspaceLockProvider, WorkspaceProvider, WorkspaceRecovery, WorkspaceRecoveryOptions, WorkspaceRecoveryResult, WorkspaceRequest } from '../../contracts/workspace.js';
3
+ import type { RepositoryCloneResolver, WorkspaceLockProvider, WorkspaceProvider, WorkspaceRecovery, WorkspaceRecoveryOptions, WorkspaceRecoveryResult, WorkspaceRequest } from '../../contracts/workspace.js';
4
4
  import { type WorkspacePrepareHook } from './prepare-workspace.js';
5
- export interface RepositoryCloneResolver {
6
- cloneLocator(resourceId: string, signal: AbortSignal): Promise<string>;
7
- }
5
+ export type { RepositoryCloneResolver } from '../../contracts/workspace.js';
8
6
  export type GitRunner = (arguments_: readonly string[], signal: AbortSignal) => Promise<string | void>;
9
7
  export interface WorkspaceRecoveryFileSystem {
10
8
  remove(path: string): Promise<void>;
@@ -5,6 +5,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:pat
5
5
  import { isDeepStrictEqual, promisify } from 'node:util';
6
6
  import { repositoryAssignmentSchema, } from '../../contracts/repository-assignment.js';
7
7
  import { isActiveRunStatus, RunStatus, WorkspaceMode } from '../../contracts/vocabulary.js';
8
+ import { resolveGitSource } from './git-source.js';
8
9
  import { prepareWorkspace } from './prepare-workspace.js';
9
10
  const exec = promisify(execFile);
10
11
  export class GitWorkspaceProvider {
@@ -33,6 +34,15 @@ export class GitWorkspaceProvider {
33
34
  async acquire(request) {
34
35
  const { signal } = request;
35
36
  signal.throwIfAborted();
37
+ if (request.requiredSourceRef !== undefined) {
38
+ const source = await resolveGitSource(this.resolver, {
39
+ resourceId: request.repositoryResource.resourceId,
40
+ sourceRef: request.requiredSourceRef,
41
+ pullRequestBase: request.assignment?.pullRequestBase ?? request.requiredSourceRef,
42
+ });
43
+ if (source.sourceRevision !== request.checkoutRevision)
44
+ throw new Error('Candidate source moved from its exact revision');
45
+ }
36
46
  const locator = await this.resolver.cloneLocator(request.repositoryResource.resourceId, signal);
37
47
  signal.throwIfAborted();
38
48
  const name = `${request.workItemId}-${request.mode}-${slug(locator)}`;
@@ -509,7 +519,8 @@ function assertAssignment(previousMarker, request) {
509
519
  (previousMarker.assignment !== undefined || request.assignment !== undefined) &&
510
520
  previousMarker.repositoryResourceId !== request.repositoryResource.resourceId)
511
521
  throw new Error('Workspace belongs to a different Repository Resource');
512
- if (previousMarker?.assignment !== undefined &&
522
+ if (request.mode === WorkspaceMode.Branch &&
523
+ previousMarker?.assignment !== undefined &&
513
524
  !isDeepStrictEqual(previousMarker.assignment, request.assignment))
514
525
  throw new Error('Workspace repository assignment changed; reconcile the existing branch before retrying');
515
526
  }
@@ -100,6 +100,10 @@ export declare class DelegatedWork {
100
100
  cohortId?: string | undefined;
101
101
  useAsBase?: boolean | undefined;
102
102
  }[] | undefined;
103
+ replaces?: {
104
+ cohortId: string;
105
+ assignmentId: string;
106
+ } | undefined;
103
107
  repository?: {
104
108
  resourceId: string;
105
109
  sourceRef: string;
@@ -131,6 +135,7 @@ export declare class DelegatedWork {
131
135
  contextWorkItems(parent: WorkflowInstanceView): Promise<ReadonlySet<string>>;
132
136
  results(id: WorkflowInstanceId, cohortId: string): Promise<readonly DelegationResult[]>;
133
137
  reserve(caller: DelegationCaller, cohortId: string, assignments: readonly DelegatedAssignment[], context: CommandContext, limits?: DelegationLimits, expectedPlanRevision?: number): Promise<DelegationReservation>;
138
+ private assertPinnedReplacements;
134
139
  private pinAssignments;
135
140
  reconcile(context: CommandContext): Promise<void>;
136
141
  private capacityReservations;
@@ -8,12 +8,14 @@ import { OrchestrationEventType } from '../contracts/events.js';
8
8
  import { orchestrationGroupId, workflowInstanceId, } from '../contracts/identifiers.js';
9
9
  import { DelegationConflictCode, DelegationPrerequisiteCondition, WorkflowStatus, } from '../contracts/vocabulary.js';
10
10
  import { nextOrdinal } from '../domain/decision-events.js';
11
+ import { assertCriteriaPreserving, originalOf } from '../domain/delivery-replacement.js';
11
12
  import { isSuccessfulWorkflowCompletion } from '../domain/workflow-completion.js';
12
13
  import { DelegationAttention, } from './delegation-attention.js';
13
14
  import { delegationDraft, delegationEventId, DelegationLedger, isJoined, isSettled, reservationsOf, reservedEvent, selectedResults, unsettledReservations, } from './delegation-ledger.js';
14
15
  import { DelegationPrerequisites } from './delegation-prerequisites.js';
15
16
  import { assertWithinRootLimits, buildReservation, matchesAssignments, } from './delegation-reservation.js';
16
17
  import { resolvePrerequisites } from './delegation-wait-graph.js';
18
+ import { readDeliveryFacts } from './delivery-facts-reader.js';
17
19
  const defaultLimits = { maxDepth: 1, maxDescendants: 8 };
18
20
  /**
19
21
  * Durable delegation of independent child WorkItems. Reservation is the single commit point;
@@ -135,6 +137,7 @@ export class DelegatedWork {
135
137
  return prior;
136
138
  }
137
139
  const pinned = await this.pinAssignments(parent, assignments);
140
+ await this.assertPinnedReplacements(parent, pinned);
138
141
  let reservation = buildReservation(identity.parent, caller, cohortId, pinned, limits);
139
142
  for (let attempt = 0; attempt < 8; attempt++) {
140
143
  const { events: rootFacts, sequence } = await this.repository.history(identity.root);
@@ -171,6 +174,13 @@ export class DelegatedWork {
171
174
  }
172
175
  throw new Error('Delegation reservation contention exceeded retry limit');
173
176
  }
177
+ async assertPinnedReplacements(parent, pinned) {
178
+ const replacementFacts = await readDeliveryFacts(this.repository, parent, (await this.repository.history(parent.workflowInstanceId)).events);
179
+ for (const assignment of pinned) {
180
+ if (assignment.replaces !== undefined)
181
+ assertCriteriaPreserving(replacementFacts, originalOf(replacementFacts, assignment.replaces), assignment);
182
+ }
183
+ }
174
184
  async pinAssignments(parent, assignments) {
175
185
  return Promise.all(assignments.map(async (assignment) => {
176
186
  if (assignment.repository === undefined)
@@ -56,6 +56,10 @@ export declare class DelegationCommands {
56
56
  cohortId?: string | undefined;
57
57
  useAsBase?: boolean | undefined;
58
58
  }[] | undefined;
59
+ replaces?: {
60
+ cohortId: string;
61
+ assignmentId: string;
62
+ } | undefined;
59
63
  repository?: {
60
64
  resourceId: string;
61
65
  sourceRef: string;
@@ -77,6 +81,11 @@ export declare class DelegationCommands {
77
81
  maxDescendants: number;
78
82
  maxConcurrentRuns: number;
79
83
  repositories?: string[] | undefined;
84
+ completion?: "qa-approved" | "merge-required" | undefined;
85
+ qa?: {
86
+ stage: string;
87
+ recipe?: string | undefined;
88
+ } | undefined;
80
89
  } | null;
81
90
  repositories: string[];
82
91
  planRevision: number;
@@ -143,6 +152,10 @@ export declare class DelegationCommands {
143
152
  cohortId?: string | undefined;
144
153
  useAsBase?: boolean | undefined;
145
154
  }[] | undefined;
155
+ replaces?: {
156
+ cohortId: string;
157
+ assignmentId: string;
158
+ } | undefined;
146
159
  repository?: {
147
160
  resourceId: string;
148
161
  sourceRef: string;
@@ -0,0 +1,279 @@
1
+ import { type CommandContext } from '@atolis-hq/eventing';
2
+ import { type DelegationCaller } from '../contracts/delegation.js';
3
+ import type { DeliveryDependencies } from '../contracts/delivery-ports.js';
4
+ import { type DeliveryCandidate, type DeliveryCandidateCommand, type DeliveryQa, type DeliveryQaCommand, type DeliverySelectionCommand } from '../contracts/delivery.js';
5
+ import type { OrchestrationRepository } from './orchestration-repository.js';
6
+ /**
7
+ * Agent-led parent QA over the delegated delivery. The parent agent chooses what to select,
8
+ * assemble, test and repair; Wake only records those choices against exact outputs and revisions,
9
+ * rejects anything that would waive a requirement or vouch for different code, and reports what
10
+ * is stale, blocked or exhausted. Every fact lives in the parent's journal stream.
11
+ */
12
+ export declare class DeliveryCoordinator {
13
+ private readonly repository;
14
+ private readonly dependencies;
15
+ private readonly preparation;
16
+ constructor(repository: OrchestrationRepository, dependencies: DeliveryDependencies);
17
+ select(caller: DelegationCaller, input: DeliverySelectionCommand, context: CommandContext): Promise<{
18
+ selection: {
19
+ requestId: string;
20
+ revision: number;
21
+ entries: {
22
+ cohortId: string;
23
+ assignmentId: string;
24
+ childWorkItemId: import("../../work/index.js").WorkItemId;
25
+ output: {
26
+ name: string;
27
+ reference: {
28
+ workItemId: import("../../work/index.js").WorkItemId;
29
+ revisionId: string;
30
+ } | {
31
+ workItemId: import("../../work/index.js").WorkItemId;
32
+ resourceId: string;
33
+ repositoryResourceId: string;
34
+ revision: string;
35
+ branch: string;
36
+ pullRequestBase: string;
37
+ runId: string;
38
+ baseRevision?: string | undefined;
39
+ merged?: true | undefined;
40
+ };
41
+ };
42
+ replaces?: {
43
+ childWorkItemId: import("../../work/index.js").WorkItemId;
44
+ outputName: string;
45
+ } | undefined;
46
+ }[];
47
+ };
48
+ replay: boolean;
49
+ }>;
50
+ recordCandidate(caller: DelegationCaller, input: DeliveryCandidateCommand, context: CommandContext): Promise<{
51
+ candidate: {
52
+ candidateId: string;
53
+ selectionRevision: number;
54
+ repositories: {
55
+ resourceId: string;
56
+ revision: string;
57
+ pullRequestBase: string;
58
+ source: {
59
+ kind: "output";
60
+ tip: {
61
+ childWorkItemId: import("../../work/index.js").WorkItemId;
62
+ outputName: string;
63
+ };
64
+ } | {
65
+ kind: "retained-ref";
66
+ ref: string;
67
+ };
68
+ contributions: {
69
+ childWorkItemId: import("../../work/index.js").WorkItemId;
70
+ outputName: string;
71
+ }[];
72
+ }[];
73
+ context: {
74
+ childWorkItemId: import("../../work/index.js").WorkItemId;
75
+ outputName: string;
76
+ }[];
77
+ criteria: string[];
78
+ recipe?: string | undefined;
79
+ };
80
+ replay: boolean;
81
+ }>;
82
+ recordQa(caller: DelegationCaller, input: DeliveryQaCommand, context: CommandContext): Promise<{
83
+ qa: {
84
+ qaId: string;
85
+ candidateId: string;
86
+ verdict: "blocked" | "pass" | "fail";
87
+ revisions: {
88
+ resourceId: string;
89
+ revision: string;
90
+ }[];
91
+ environment: {
92
+ available: boolean;
93
+ recipe?: string | undefined;
94
+ };
95
+ findings: string[];
96
+ evidence?: {
97
+ workItemId: import("../../work/index.js").WorkItemId;
98
+ revisionId: string;
99
+ }[] | undefined;
100
+ exhausted?: boolean | undefined;
101
+ runId?: string | undefined;
102
+ activationId?: string | undefined;
103
+ };
104
+ replay: boolean;
105
+ }>;
106
+ /** The inspectable delivery state: selection, staleness, candidate, QA, repair and completion. */
107
+ inspectFor(caller: DelegationCaller): Promise<{
108
+ required: {
109
+ cohortId: string;
110
+ assignmentId: string;
111
+ outputName: string;
112
+ childWorkItemId: import("../../work/index.js").WorkItemId;
113
+ }[];
114
+ selection: {
115
+ requestId: string;
116
+ revision: number;
117
+ entries: {
118
+ cohortId: string;
119
+ assignmentId: string;
120
+ childWorkItemId: import("../../work/index.js").WorkItemId;
121
+ output: {
122
+ name: string;
123
+ reference: {
124
+ workItemId: import("../../work/index.js").WorkItemId;
125
+ revisionId: string;
126
+ } | {
127
+ workItemId: import("../../work/index.js").WorkItemId;
128
+ resourceId: string;
129
+ repositoryResourceId: string;
130
+ revision: string;
131
+ branch: string;
132
+ pullRequestBase: string;
133
+ runId: string;
134
+ baseRevision?: string | undefined;
135
+ merged?: true | undefined;
136
+ };
137
+ };
138
+ replaces?: {
139
+ childWorkItemId: import("../../work/index.js").WorkItemId;
140
+ outputName: string;
141
+ } | undefined;
142
+ }[];
143
+ } | null;
144
+ history: readonly {
145
+ qaId: string;
146
+ candidateId: string;
147
+ verdict: "blocked" | "pass" | "fail";
148
+ revisions: {
149
+ resourceId: string;
150
+ revision: string;
151
+ }[];
152
+ environment: {
153
+ available: boolean;
154
+ recipe?: string | undefined;
155
+ };
156
+ findings: string[];
157
+ evidence?: {
158
+ workItemId: import("../../work/index.js").WorkItemId;
159
+ revisionId: string;
160
+ }[] | undefined;
161
+ exhausted?: boolean | undefined;
162
+ runId?: string | undefined;
163
+ activationId?: string | undefined;
164
+ }[];
165
+ completion: import("../domain/delivery-qa.js").CompletionDecision;
166
+ selectionRevision: number;
167
+ stale: readonly string[];
168
+ candidate: DeliveryCandidate | null;
169
+ candidateCurrent: boolean;
170
+ qa: DeliveryQa | null;
171
+ qaEffective: boolean;
172
+ repair: {
173
+ readonly failedRounds: number;
174
+ readonly exhausted: boolean;
175
+ readonly unresolvedFindings: readonly string[];
176
+ };
177
+ }>;
178
+ inspect(id: string): Promise<{
179
+ required: {
180
+ cohortId: string;
181
+ assignmentId: string;
182
+ outputName: string;
183
+ childWorkItemId: import("../../work/index.js").WorkItemId;
184
+ }[];
185
+ selection: {
186
+ requestId: string;
187
+ revision: number;
188
+ entries: {
189
+ cohortId: string;
190
+ assignmentId: string;
191
+ childWorkItemId: import("../../work/index.js").WorkItemId;
192
+ output: {
193
+ name: string;
194
+ reference: {
195
+ workItemId: import("../../work/index.js").WorkItemId;
196
+ revisionId: string;
197
+ } | {
198
+ workItemId: import("../../work/index.js").WorkItemId;
199
+ resourceId: string;
200
+ repositoryResourceId: string;
201
+ revision: string;
202
+ branch: string;
203
+ pullRequestBase: string;
204
+ runId: string;
205
+ baseRevision?: string | undefined;
206
+ merged?: true | undefined;
207
+ };
208
+ };
209
+ replaces?: {
210
+ childWorkItemId: import("../../work/index.js").WorkItemId;
211
+ outputName: string;
212
+ } | undefined;
213
+ }[];
214
+ } | null;
215
+ history: readonly {
216
+ qaId: string;
217
+ candidateId: string;
218
+ verdict: "blocked" | "pass" | "fail";
219
+ revisions: {
220
+ resourceId: string;
221
+ revision: string;
222
+ }[];
223
+ environment: {
224
+ available: boolean;
225
+ recipe?: string | undefined;
226
+ };
227
+ findings: string[];
228
+ evidence?: {
229
+ workItemId: import("../../work/index.js").WorkItemId;
230
+ revisionId: string;
231
+ }[] | undefined;
232
+ exhausted?: boolean | undefined;
233
+ runId?: string | undefined;
234
+ activationId?: string | undefined;
235
+ }[];
236
+ completion: import("../domain/delivery-qa.js").CompletionDecision;
237
+ selectionRevision: number;
238
+ stale: readonly string[];
239
+ candidate: DeliveryCandidate | null;
240
+ candidateCurrent: boolean;
241
+ qa: DeliveryQa | null;
242
+ qaEffective: boolean;
243
+ repair: {
244
+ readonly failedRounds: number;
245
+ readonly exhausted: boolean;
246
+ readonly unresolvedFindings: readonly string[];
247
+ };
248
+ }>;
249
+ /**
250
+ * Replacement children keep the original acceptance criteria and repository; a terminal original
251
+ * is replaced by a new child, while correcting a still-running one is not supported.
252
+ */
253
+ assertReplacements(caller: DelegationCaller, input: unknown): Promise<void>;
254
+ completionBlock(id: string): Promise<import("../contracts/delivery.js").DeliveryCompletionBlock | undefined>;
255
+ prepare(id: string): Promise<{
256
+ candidateId: string;
257
+ selectionRevision: number;
258
+ criteria: string[];
259
+ inputs: {
260
+ workItemId: string;
261
+ outputName: string;
262
+ revision: string;
263
+ }[];
264
+ repositories: {
265
+ resourceId: string;
266
+ sourceRef: string;
267
+ sourceRevision: string;
268
+ pullRequestBase: string;
269
+ requiredSourceRef?: string | undefined;
270
+ }[];
271
+ recipe?: string | undefined;
272
+ } | undefined>;
273
+ private assertQaActor;
274
+ private assertCoordinatorStage;
275
+ private parent;
276
+ private facts;
277
+ /** Re-derives facts from fresh history on every optimistic-concurrency retry. */
278
+ private commit;
279
+ }
@@ -0,0 +1,213 @@
1
+ import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
2
+ import { DelegationConflictError, delegationSubmissionSchema, } from '../contracts/delegation.js';
3
+ import { DeliveryRejectionError, deliveryCandidateCommandSchema, 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 { 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 { DeliveryPreparation } from './delivery-preparation.js';
15
+ import { verifyCandidateSources } from './delivery-sources.js';
16
+ /**
17
+ * Agent-led parent QA over the delegated delivery. The parent agent chooses what to select,
18
+ * assemble, test and repair; Wake only records those choices against exact outputs and revisions,
19
+ * rejects anything that would waive a requirement or vouch for different code, and reports what
20
+ * is stale, blocked or exhausted. Every fact lives in the parent's journal stream.
21
+ */
22
+ export class DeliveryCoordinator {
23
+ repository;
24
+ dependencies;
25
+ preparation;
26
+ constructor(repository, dependencies) {
27
+ this.repository = repository;
28
+ this.dependencies = dependencies;
29
+ this.preparation = new DeliveryPreparation(repository, dependencies);
30
+ }
31
+ async select(caller, input, context) {
32
+ const command = deliverySelectionCommandSchema.parse(input);
33
+ const parent = await this.parent(caller);
34
+ await this.assertCoordinatorStage(parent);
35
+ return this.commit(parent, context, `selection:${command.requestId}`, async (facts) => {
36
+ const { selection, replay } = reviseSelection(facts, command);
37
+ return {
38
+ result: { selection, replay },
39
+ draft: replay
40
+ ? undefined
41
+ : { eventType: OrchestrationEventType.DeliverySelectionRevised, payload: selection },
42
+ };
43
+ });
44
+ }
45
+ async recordCandidate(caller, input, context) {
46
+ const command = deliveryCandidateCommandSchema.parse(input);
47
+ const parent = await this.parent(caller);
48
+ await this.assertCoordinatorStage(parent);
49
+ const policy = (await this.dependencies.definitionFor(parent)).delegation?.qa;
50
+ return this.commit(parent, context, `candidate:${command.candidateId}`, async (facts) => {
51
+ const root = facts.reservations[0]?.rootWorkItemId;
52
+ if (root === undefined)
53
+ throw new DeliveryRejectionError(DeliveryRejection.NoSelection, 'No delegated work');
54
+ const { candidate } = planCandidate(facts, command, root);
55
+ const existing = facts.candidates.find((entry) => entry.candidateId === command.candidateId);
56
+ if (existing !== undefined && JSON.stringify(existing) !== JSON.stringify(candidate))
57
+ throw new DeliveryRejectionError(DeliveryRejection.Conflict, `Candidate ${command.candidateId} already exists with different contents`);
58
+ if (policy !== undefined && policy.recipe !== command.recipe)
59
+ throw new Error('Candidate must use the configured QA recipe');
60
+ // A replay re-proves the sources, so a restart cannot revive a candidate whose ref is gone.
61
+ await verifyCandidateSources(parent, this.dependencies.repositories, candidate, facts);
62
+ return {
63
+ result: { candidate, replay: existing !== undefined },
64
+ draft: existing !== undefined
65
+ ? undefined
66
+ : { eventType: OrchestrationEventType.DeliveryCandidateRecorded, payload: candidate },
67
+ };
68
+ });
69
+ }
70
+ async recordQa(caller, input, context) {
71
+ const command = deliveryQaCommandSchema.parse(input);
72
+ const parent = await this.parent(caller);
73
+ const definition = await this.dependencies.definitionFor(parent);
74
+ const policy = definition.delegation?.qa;
75
+ if (policy === undefined || parent.pendingActivation?.stage !== policy.stage)
76
+ throw new Error('QA verdicts require the configured QA stage');
77
+ return this.commit(parent, context, `qa:${command.qaId}`, async (facts) => {
78
+ const qa = assertQa(facts, command);
79
+ const candidate = facts.candidates.find((entry) => entry.candidateId === qa.candidateId);
80
+ await this.assertQaActor(caller, facts, candidate, qa, policy.recipe);
81
+ const recorded = facts.qa.find((entry) => entry.qaId === command.qaId);
82
+ if (recorded !== undefined) {
83
+ if (JSON.stringify({
84
+ ...recorded,
85
+ exhausted: undefined,
86
+ runId: undefined,
87
+ activationId: undefined,
88
+ }) !== JSON.stringify(qa))
89
+ throw new DeliveryRejectionError(DeliveryRejection.Conflict, `QA ${command.qaId} was already recorded differently`);
90
+ return { result: { qa: recorded, replay: true }, draft: undefined };
91
+ }
92
+ if (qa.verdict === QaVerdict.Pass) {
93
+ // A pass is only meaningful while the exact sources remain reconstructable.
94
+ const candidate = facts.candidates.find((entry) => entry.candidateId === qa.candidateId);
95
+ await verifyCandidateSources(parent, this.dependencies.repositories, candidate, facts);
96
+ }
97
+ const route = definition.stages[stageName(policy.stage)]?.on.failed;
98
+ const routeExhausted = route?.repeat !== undefined && (parent.repeatCounts[route.id] ?? 0) >= route.repeat.max;
99
+ const exhausted = qa.verdict === QaVerdict.Fail &&
100
+ (routeExhausted || (await this.preparation.noDescendantCapacity(facts)));
101
+ const payload = {
102
+ ...qa,
103
+ runId: caller.runId,
104
+ activationId: caller.activationId,
105
+ ...(exhausted ? { exhausted } : {}),
106
+ };
107
+ return {
108
+ result: { qa: payload, replay: false },
109
+ draft: { eventType: OrchestrationEventType.DeliveryQaRecorded, payload },
110
+ };
111
+ });
112
+ }
113
+ /** The inspectable delivery state: selection, staleness, candidate, QA, repair and completion. */
114
+ async inspectFor(caller) {
115
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
116
+ await this.dependencies.authority.assertCaller(caller, parent);
117
+ return this.inspect(parent.workflowInstanceId);
118
+ }
119
+ async inspect(id) {
120
+ const parent = (await this.repository.loadRequired(id)).view;
121
+ const facts = await this.facts(parent);
122
+ const state = deliveryState(facts);
123
+ return {
124
+ ...state,
125
+ required: requirements(facts.reservations).map((requirement) => ({
126
+ cohortId: requirement.cohortId,
127
+ assignmentId: requirement.assignmentId,
128
+ outputName: requirement.outputName,
129
+ childWorkItemId: requirement.child.workItemId,
130
+ })),
131
+ selection: facts.selections.at(-1) ?? null,
132
+ history: facts.qa,
133
+ completion: parent.deliveryGateBlock !== undefined
134
+ ? { complete: false, reason: parent.blockReason }
135
+ : completionDecision(state, (await this.dependencies.definitionFor(parent)).delegation?.completion ??
136
+ DeliveryCompletion.QaApproved),
137
+ };
138
+ }
139
+ /**
140
+ * Replacement children keep the original acceptance criteria and repository; a terminal original
141
+ * is replaced by a new child, while correcting a still-running one is not supported.
142
+ */
143
+ async assertReplacements(caller, input) {
144
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
145
+ await this.assertCoordinatorStage(parent);
146
+ const submission = delegationSubmissionSchema.safeParse(input);
147
+ const replacements = submission.success
148
+ ? submission.data.assignments.filter((entry) => entry.replaces !== undefined)
149
+ : [];
150
+ if (replacements.length === 0)
151
+ return;
152
+ await this.dependencies.authority.assertCaller(caller, parent);
153
+ const facts = await this.facts(parent);
154
+ for (const assignment of replacements) {
155
+ const original = originalOf(facts, assignment.replaces);
156
+ const view = (await this.repository.load(original.workflowInstanceId)).view;
157
+ if (view?.status !== WorkflowStatus.Completed && view?.status !== WorkflowStatus.Superseded)
158
+ throw new DelegationConflictError(DelegationConflictCode.ReplacementUnsupported, 'Correcting a child that is still running is not supported; replace it once it is complete or superseded');
159
+ }
160
+ }
161
+ completionBlock(id) {
162
+ return this.preparation.completionBlock(id);
163
+ }
164
+ prepare(id) {
165
+ return this.preparation.prepare(id);
166
+ }
167
+ async assertQaActor(caller, facts, candidate, qa, recipe) {
168
+ if (!deliveryState(facts).candidateCurrent ||
169
+ facts.candidates.at(-1)?.candidateId !== qa.candidateId)
170
+ throw new Error('QA candidate is no longer current');
171
+ if (this.dependencies.authority.assertQaCaller === undefined)
172
+ throw new Error('QA Run authority is unavailable');
173
+ await this.dependencies.authority.assertQaCaller(caller, qa.candidateId, candidate.selectionRevision, qa.revisions);
174
+ if (qa.environment.recipe !== recipe)
175
+ throw new Error('QA must use the configured recipe');
176
+ }
177
+ async assertCoordinatorStage(parent) {
178
+ const policy = (await this.dependencies.definitionFor(parent)).delegation?.qa;
179
+ if (policy !== undefined && parent.pendingActivation?.stage === policy.stage)
180
+ throw new Error('The QA stage cannot choose its own candidate or selection');
181
+ }
182
+ async parent(caller) {
183
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
184
+ await this.dependencies.authority.assertCaller(caller, parent);
185
+ if (parent.pendingActivation?.activationId !== caller.activationId ||
186
+ (parent.status !== WorkflowStatus.Active && parent.status !== WorkflowStatus.Waiting))
187
+ throw new Error('Delivery changes require the current active activation');
188
+ return parent;
189
+ }
190
+ async facts(parent) {
191
+ const { events } = await this.repository.history(parent.workflowInstanceId);
192
+ return readDeliveryFacts(this.repository, parent, events);
193
+ }
194
+ /** Re-derives facts from fresh history on every optimistic-concurrency retry. */
195
+ async commit(parent, context, key, build) {
196
+ for (;;) {
197
+ const { events, sequence } = await this.repository.history(parent.workflowInstanceId);
198
+ const { result, draft } = await build(await readDeliveryFacts(this.repository, parent, events));
199
+ if (draft === undefined)
200
+ return result;
201
+ try {
202
+ await this.repository.append(parent.workflowInstanceId, sequence, [
203
+ delegationDraft(context, key, draft, parent.workflowInstanceId),
204
+ ]);
205
+ return result;
206
+ }
207
+ catch (error) {
208
+ if (!(error instanceof WrongExpectedSequenceError))
209
+ throw error;
210
+ }
211
+ }
212
+ }
213
+ }
@@ -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>;