@atolis-hq/wake 0.4.102 → 0.4.104

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 (48) hide show
  1. package/dist/src/activities/pr/policy.d.ts +2 -0
  2. package/dist/src/activities/pr/policy.js +9 -1
  3. package/dist/src/bootstrap/artifact-mcp.js +20 -1
  4. package/dist/src/bootstrap/surface-api-delivery.js +6 -2
  5. package/dist/src/bootstrap/version.js +1 -1
  6. package/dist/src/integrations/application/delegation-outputs.js +41 -5
  7. package/dist/src/orchestration/application/conversation-command-reactor.js +25 -0
  8. package/dist/src/orchestration/application/delegated-work.d.ts +55 -2
  9. package/dist/src/orchestration/application/delegated-work.js +170 -23
  10. package/dist/src/orchestration/application/delegation-attention-escalations.d.ts +11 -0
  11. package/dist/src/orchestration/application/delegation-attention-escalations.js +36 -0
  12. package/dist/src/orchestration/application/delegation-attention-state.d.ts +53 -0
  13. package/dist/src/orchestration/application/delegation-attention-state.js +194 -0
  14. package/dist/src/orchestration/application/delegation-attention.d.ts +58 -0
  15. package/dist/src/orchestration/application/delegation-attention.js +206 -0
  16. package/dist/src/orchestration/application/delegation-commands.d.ts +52 -1
  17. package/dist/src/orchestration/application/delegation-commands.js +22 -3
  18. package/dist/src/orchestration/application/delegation-gate.d.ts +8 -3
  19. package/dist/src/orchestration/application/delegation-gate.js +45 -11
  20. package/dist/src/orchestration/application/delegation-ledger.d.ts +2 -0
  21. package/dist/src/orchestration/application/delegation-ledger.js +8 -0
  22. package/dist/src/orchestration/application/delegation-prerequisites.d.ts +28 -0
  23. package/dist/src/orchestration/application/delegation-prerequisites.js +118 -0
  24. package/dist/src/orchestration/application/delegation-reservation.js +1 -1
  25. package/dist/src/orchestration/application/delegation-wait-graph.d.ts +7 -0
  26. package/dist/src/orchestration/application/delegation-wait-graph.js +122 -0
  27. package/dist/src/orchestration/application/orchestration-repository.d.ts +5 -0
  28. package/dist/src/orchestration/application/orchestration-repository.js +3 -0
  29. package/dist/src/orchestration/application/orchestration-service.d.ts +103 -1
  30. package/dist/src/orchestration/application/orchestration-service.js +40 -2
  31. package/dist/src/orchestration/application/prerequisite-readiness.d.ts +68 -0
  32. package/dist/src/orchestration/application/prerequisite-readiness.js +217 -0
  33. package/dist/src/orchestration/contracts/delegation-ports.d.ts +2 -1
  34. package/dist/src/orchestration/contracts/delegation.d.ts +150 -0
  35. package/dist/src/orchestration/contracts/delegation.js +84 -1
  36. package/dist/src/orchestration/contracts/event-decoder.js +11 -1
  37. package/dist/src/orchestration/contracts/event-factory.js +12 -5
  38. package/dist/src/orchestration/contracts/events.d.ts +27 -1
  39. package/dist/src/orchestration/contracts/events.js +6 -0
  40. package/dist/src/orchestration/contracts/views.d.ts +6 -0
  41. package/dist/src/orchestration/contracts/vocabulary.d.ts +45 -0
  42. package/dist/src/orchestration/contracts/vocabulary.js +41 -0
  43. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +1 -0
  44. package/dist/src/orchestration/domain/workflow-instance-events.js +31 -0
  45. package/dist/src/orchestration/index.d.ts +3 -3
  46. package/dist/src/orchestration/index.js +2 -2
  47. package/dist/src/surfaces/mcp/delegation.js +37 -10
  48. package/package.json +1 -1
@@ -0,0 +1,118 @@
1
+ import { OrchestrationEventType } from '../contracts/events.js';
2
+ import { PrerequisiteBlockCode } from '../contracts/vocabulary.js';
3
+ import { PrerequisiteReadiness } from './prerequisite-readiness.js';
4
+ /** Immutable consumption receipts and live eligibility; never chooses a repair. */
5
+ export class DelegationPrerequisites {
6
+ repository;
7
+ ledger;
8
+ artifacts;
9
+ repositories;
10
+ work;
11
+ constructor(repository, ledger, artifacts, repositories, work) {
12
+ this.repository = repository;
13
+ this.ledger = ledger;
14
+ this.artifacts = artifacts;
15
+ this.repositories = repositories;
16
+ this.work = work;
17
+ }
18
+ async inputs(id) {
19
+ return (await this.ledger.events()).flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationInputsResolved &&
20
+ event.payload.childWorkItemId === id
21
+ ? [event.payload]
22
+ : [])[0];
23
+ }
24
+ async read(workSnapshot) {
25
+ const snapshot = await this.repository.snapshot();
26
+ return new PrerequisiteReadiness(snapshot, workSnapshot ?? (await this.work.deliverySnapshot()), this.artifacts, this.repositories);
27
+ }
28
+ async reasons(ids, workSnapshot) {
29
+ if (ids.length === 0)
30
+ return new Map();
31
+ const read = await this.read(workSnapshot);
32
+ return new Map(await Promise.all(ids.map(async (id) => [id, { reason: await read.reason(id), abandoned: read.abandoned(id) }])));
33
+ }
34
+ async reason(id) {
35
+ return (await this.read()).reason(id);
36
+ }
37
+ async prepare(reservation, child, context, readiness) {
38
+ if ((child.prerequisites?.length ?? 0) === 0)
39
+ return true;
40
+ const read = readiness ?? (await this.read());
41
+ const stored = read.inputs(child.workItemId);
42
+ if (stored !== undefined) {
43
+ await this.grant(reservation, child, stored, context);
44
+ return this.check(reservation, child, context, read);
45
+ }
46
+ const consumed = await read.select(child, new Set([child.workItemId]));
47
+ if (!Array.isArray(consumed)) {
48
+ await this.diagnostic(reservation, child, consumed.reason, context);
49
+ if (consumed.code === PrerequisiteBlockCode.Changed ||
50
+ consumed.code === PrerequisiteBlockCode.Failed)
51
+ await this.block(reservation, child, consumed.reason, context);
52
+ return false;
53
+ }
54
+ const repository = await this.resolveBase(reservation, child, consumed);
55
+ await this.ledger.appendOnce(reservation.parentWorkflowInstanceId, context, `inputs:${child.grantId}`, {
56
+ eventType: OrchestrationEventType.DelegationInputsResolved,
57
+ payload: {
58
+ childWorkItemId: child.workItemId,
59
+ consumed,
60
+ ...(repository === undefined ? {} : { repository }),
61
+ },
62
+ });
63
+ const pinned = await this.inputs(child.workItemId);
64
+ if (pinned === undefined)
65
+ throw new Error('Missing committed prerequisite inputs');
66
+ await this.grant(reservation, child, pinned, context);
67
+ return true;
68
+ }
69
+ async resolveBase(reservation, child, consumed) {
70
+ const index = child.prerequisites?.findIndex((edge) => edge.useAsBase) ?? -1;
71
+ if (index < 0)
72
+ return child.repository;
73
+ const reference = consumed[index].reference;
74
+ if (!('revision' in reference) ||
75
+ child.repository === undefined ||
76
+ this.repositories === undefined)
77
+ throw new Error('Upstream Git base resolver unavailable');
78
+ const parent = (await this.repository.loadRequired(reservation.parentWorkflowInstanceId)).view;
79
+ return this.repositories.resolve(parent, {
80
+ resourceId: child.repository.resourceId,
81
+ sourceRef: reference.branch,
82
+ sourceRevision: reference.revision,
83
+ pullRequestBase: reference.branch,
84
+ });
85
+ }
86
+ async grant(reservation, child, inputs, context) {
87
+ const references = inputs.consumed.flatMap(({ reference }) => 'revisionId' in reference ? [reference] : []);
88
+ await this.artifacts.registerChild({
89
+ delegationId: `${child.grantId}:prerequisites`,
90
+ parentWorkItemId: reservation.parentWorkItemId,
91
+ childWorkItemId: child.workItemId,
92
+ childReferences: references,
93
+ }, context);
94
+ }
95
+ async check(reservation, child, context, readiness) {
96
+ const read = readiness ?? (await this.read());
97
+ const blocked = await read.block(child.workItemId);
98
+ if (blocked === undefined)
99
+ return true;
100
+ await this.diagnostic(reservation, child, blocked.reason, context);
101
+ if (blocked.code === PrerequisiteBlockCode.Changed ||
102
+ blocked.code === PrerequisiteBlockCode.Failed)
103
+ await this.block(reservation, child, blocked.reason, context);
104
+ return false;
105
+ }
106
+ async block(reservation, child, reason, context) {
107
+ await this.ledger.appendOnce(reservation.parentWorkflowInstanceId, context, 'child-blocked:' + child.grantId, {
108
+ eventType: OrchestrationEventType.DelegationChildBlocked,
109
+ payload: { childWorkItemId: child.workItemId, reason },
110
+ });
111
+ }
112
+ async diagnostic(reservation, child, reason, context) {
113
+ await this.ledger.appendOnce(reservation.parentWorkflowInstanceId, context, `prerequisite:${child.grantId}:${PrerequisiteBlockCode.Blocked}`, {
114
+ eventType: OrchestrationEventType.DelegationPrerequisiteBlocked,
115
+ payload: { childWorkItemId: child.workItemId, reason },
116
+ });
117
+ }
118
+ }
@@ -53,7 +53,7 @@ export function matchesAssignments(reservation, assignments) {
53
53
  reservation.children.find((child) => child.assignmentId === assignment.assignmentId)
54
54
  ?.repository?.sourceRevision !== assignment.repository.sourceRevision))
55
55
  return false;
56
- return isDeepStrictEqual(reservation.children.map(({ workItemId: _w, workflowInstanceId: _i, grantId: _g, ...assignment }) => ({
56
+ return isDeepStrictEqual(reservation.children.map(({ workItemId: _w, workflowInstanceId: _i, grantId: _g, prerequisiteWorkItemIds: _p, ...assignment }) => ({
57
57
  ...assignment,
58
58
  ...(assignment.repository === undefined
59
59
  ? {}
@@ -0,0 +1,7 @@
1
+ import { type DelegationReservation } from '../contracts/delegation.js';
2
+ import { type DelegationLedger } from './delegation-ledger.js';
3
+ import type { WorkflowDefinitionRegistry } from './workflow-definition-registry.js';
4
+ type Child = DelegationReservation['children'][number];
5
+ /** Resolve local keys once under the root reservation's sequence guard. */
6
+ export declare function resolvePrerequisites(candidate: DelegationReservation, existing: readonly DelegationReservation[], ledger: DelegationLedger, definitions: WorkflowDefinitionRegistry, mergeAvailable: (target: Child, output: string) => Promise<boolean>): Promise<DelegationReservation>;
7
+ export {};
@@ -0,0 +1,122 @@
1
+ import { ActivityResourceRole, BuiltInActivityName, pullRequestMergeInputSchema, } from '../../activities/index.js';
2
+ import { DelegationConflictError, } from '../contracts/delegation.js';
3
+ import { DelegationConflictCode as Code, DelegationPrerequisiteCondition as Condition, } from '../contracts/vocabulary.js';
4
+ import { isSettled } from './delegation-ledger.js';
5
+ /** Resolve local keys once under the root reservation's sequence guard. */
6
+ export async function resolvePrerequisites(candidate, existing, ledger, definitions, mergeAvailable) {
7
+ const all = [...existing, candidate];
8
+ const resolved = {
9
+ ...candidate,
10
+ children: candidate.children.map((child) => resolveChild(candidate, child, all)),
11
+ };
12
+ const graph = new Map();
13
+ const add = (from, to) => graph.set(from, [...(graph.get(from) ?? []), to]);
14
+ const events = await ledger.events();
15
+ const reservations = [...existing, resolved];
16
+ for (const reservation of reservations) {
17
+ const unsettled = reservation === resolved || !isSettled(events, reservation);
18
+ for (const child of reservation.children) {
19
+ if (unsettled)
20
+ add(reservation.parentWorkItemId, child.workItemId);
21
+ for (const id of child.prerequisiteWorkItemIds ?? [])
22
+ add(child.workItemId, id);
23
+ const waits = await mergeWaits(child, reservations, definitions, mergeAvailable);
24
+ for (const [from, to] of waits)
25
+ if (unsettled)
26
+ add(from, to);
27
+ }
28
+ }
29
+ assertAcyclic(graph);
30
+ return resolved;
31
+ }
32
+ function resolveChild(candidate, child, all) {
33
+ if (child.prerequisites === undefined)
34
+ return child;
35
+ if (child.prerequisites.filter((edge) => edge.useAsBase).length > 1)
36
+ reject(Code.MultipleBases, 'Select at most one upstream Git base');
37
+ return {
38
+ ...child,
39
+ prerequisiteWorkItemIds: child.prerequisites.map((edge) => {
40
+ const cohort = all.find((entry) => entry.cohortId === (edge.cohortId ?? candidate.cohortId));
41
+ const target = cohort?.children.find((entry) => entry.assignmentId === edge.assignmentId);
42
+ if (target === undefined)
43
+ reject(Code.MissingTarget, 'Prerequisite target is outside this delivery or does not exist');
44
+ if (target.workItemId === child.workItemId)
45
+ reject(Code.SelfDependency, 'A child cannot depend on itself');
46
+ validateOutput(child, target, edge);
47
+ return target.workItemId;
48
+ }),
49
+ };
50
+ }
51
+ function validateOutput(child, target, edge) {
52
+ const output = target.outputs.find((entry) => entry.name === edge.output);
53
+ if (output === undefined)
54
+ reject(Code.MissingOutput, 'Prerequisite must select a declared named output');
55
+ if ((edge.condition === Condition.AcceptedOutput && !('path' in output)) ||
56
+ (requiresChange(edge) && !('kind' in output)))
57
+ reject(Code.OutputKind, 'Prerequisite condition does not match the named output kind');
58
+ if (edge.useAsBase)
59
+ validateBase(child, target, edge);
60
+ if (child.repository?.resourceId !== target.repository?.resourceId && 'kind' in output)
61
+ reject(Code.CrossRepositoryChange, 'Cross-repository prerequisites must select accepted context outputs');
62
+ }
63
+ function validateBase(child, target, edge) {
64
+ if (edge.condition === Condition.AcceptedOutput ||
65
+ child.repository === undefined ||
66
+ target.repository?.resourceId !== child.repository.resourceId)
67
+ reject(Code.CrossRepositoryBase, 'Git bases require a same-repository change prerequisite');
68
+ }
69
+ async function mergeWaits(child, all, definitions, available) {
70
+ const waits = [];
71
+ for (const [index, edge] of (child.prerequisites ?? []).entries()) {
72
+ if (edge.condition !== Condition.MergedChange)
73
+ continue;
74
+ const upstream = all.find((entry) => entry.children.some((target) => target.workItemId === child.prerequisiteWorkItemIds?.[index]));
75
+ const target = upstream?.children.find((entry) => entry.workItemId === child.prerequisiteWorkItemIds?.[index]);
76
+ if (upstream === undefined || target === undefined || (await available(target, edge.output)))
77
+ continue;
78
+ const workflow = await definitions.resolve({
79
+ workflowName: target.workflowName,
80
+ workflowDefinitionFingerprint: target.workflowFingerprint,
81
+ }, { journalFallback: true });
82
+ // A delivery-ready child's parent must join before it can merge the child's output.
83
+ if (!hasOwnMergeLane(workflow))
84
+ waits.push([target.workItemId, upstream.parentWorkItemId]);
85
+ }
86
+ return waits;
87
+ }
88
+ function assertAcyclic(graph) {
89
+ const visiting = new Set();
90
+ const done = new Set();
91
+ function visit(node) {
92
+ if (visiting.has(node))
93
+ reject(Code.WaitCycle, 'Prerequisites create an explicit or implicit join/merge wait cycle');
94
+ if (done.has(node))
95
+ return;
96
+ visiting.add(node);
97
+ for (const target of graph.get(node) ?? [])
98
+ visit(target);
99
+ visiting.delete(node);
100
+ done.add(node);
101
+ }
102
+ for (const node of graph.keys())
103
+ visit(node);
104
+ }
105
+ function reject(code, message) {
106
+ throw new DelegationConflictError(code, message);
107
+ }
108
+ function requiresChange(edge) {
109
+ return (edge.condition === Condition.PushedChange ||
110
+ edge.condition === Condition.MergedChange ||
111
+ edge.useAsBase === true);
112
+ }
113
+ function hasOwnMergeLane(workflow) {
114
+ return Object.values(workflow.stages).some((stage) => mergesPrimary(stage.activity, stage.with) ||
115
+ Object.values(stage.on).some((route) => route.activities?.some((activity) => mergesPrimary(activity.use, activity.with))));
116
+ }
117
+ function mergesPrimary(activity, input) {
118
+ if (activity !== BuiltInActivityName.PullRequestMerge)
119
+ return false;
120
+ const parsed = pullRequestMergeInputSchema.safeParse(input);
121
+ return parsed.success && parsed.data.target === ActivityResourceRole.Primary;
122
+ }
@@ -13,6 +13,11 @@ export declare class OrchestrationRepository {
13
13
  sequence: number;
14
14
  view: WorkflowInstanceView | null;
15
15
  }>;
16
+ snapshot(): Promise<{
17
+ instances: readonly ListedInstance[];
18
+ events: readonly WorkflowOrchestrationEvent[];
19
+ inherited: ReadonlyMap<string, readonly WorkflowOrchestrationEvent[]>;
20
+ }>;
16
21
  events(): Promise<readonly WorkflowOrchestrationEvent[]>;
17
22
  history(id: string): Promise<{
18
23
  sequence: number;
@@ -36,6 +36,9 @@ export class OrchestrationRepository {
36
36
  });
37
37
  return { sequence, view: foldWorkflowInstance([...own, ...inherited]) };
38
38
  }
39
+ snapshot() {
40
+ return this.listed.get();
41
+ }
39
42
  events() {
40
43
  return this.listed.get().then((snapshot) => snapshot.events);
41
44
  }
@@ -1,5 +1,5 @@
1
1
  import type { DelegationArtifacts, DelegationAuthority, DelegationRepositories } from '../contracts/delegation-ports.js';
2
- import type { DelegationCaller, DelegationSubmission } from '../contracts/delegation.js';
2
+ import type { DelegationAttentionReply, DelegationCaller, DelegationSubmission } from '../contracts/delegation.js';
3
3
  import type { ResourceTransitionEvidence } from './resource-transition-evidence.js';
4
4
  import type { CommandContext, EventJournal, ProjectionStore } from '@atolis-hq/eventing';
5
5
  import { type ActivationId, type ActivityOutcome } from '../../activities/index.js';
@@ -17,6 +17,8 @@ export declare class OrchestrationService {
17
17
  private readonly delegationCommands;
18
18
  private readonly delegationGate;
19
19
  private readonly delegatedWork;
20
+ private readonly prerequisiteReasons;
21
+ private readonly resumeClarification;
20
22
  private readonly repository;
21
23
  private readonly deferredSignals;
22
24
  private readonly startWorkflow;
@@ -73,13 +75,22 @@ export declare class OrchestrationService {
73
75
  workflowInstanceId: WorkflowInstanceId;
74
76
  grantId: string;
75
77
  repositoryResourceIds?: string[] | undefined;
78
+ prerequisites?: {
79
+ assignmentId: string;
80
+ output: string;
81
+ condition: "accepted-output" | "pushed-change" | "delivery-ready" | "merged-change";
82
+ cohortId?: string | undefined;
83
+ useAsBase?: boolean | undefined;
84
+ }[] | undefined;
76
85
  repository?: {
77
86
  resourceId: string;
78
87
  sourceRef: string;
79
88
  pullRequestBase: string;
80
89
  sourceRevision: string;
81
90
  } | undefined;
91
+ prerequisiteWorkItemIds?: WorkItemId[] | undefined;
82
92
  }[];
93
+ planRevision?: number | undefined;
83
94
  maxConcurrentRuns?: number | undefined;
84
95
  }>;
85
96
  inspectDelegation(caller: DelegationCaller, context: CommandContext): Promise<{
@@ -91,10 +102,40 @@ export declare class OrchestrationService {
91
102
  repositories?: string[] | undefined;
92
103
  } | null;
93
104
  repositories: string[];
105
+ planRevision: number;
106
+ attention: import("./delegation-attention-state.js").OpenAttention | null;
94
107
  tree: {
95
108
  settled: boolean;
109
+ failureReason: string | undefined;
96
110
  children: {
97
111
  work: WorkItemView | null;
112
+ prerequisiteBlocker: string | undefined;
113
+ consumedInputs: {
114
+ childWorkItemId: WorkItemId;
115
+ consumed: {
116
+ name: string;
117
+ reference: {
118
+ workItemId: WorkItemId;
119
+ revisionId: string;
120
+ } | {
121
+ workItemId: WorkItemId;
122
+ resourceId: string;
123
+ repositoryResourceId: string;
124
+ revision: string;
125
+ branch: string;
126
+ pullRequestBase: string;
127
+ runId: string;
128
+ baseRevision?: string | undefined;
129
+ merged?: true | undefined;
130
+ };
131
+ }[];
132
+ repository?: {
133
+ resourceId: string;
134
+ sourceRef: string;
135
+ pullRequestBase: string;
136
+ sourceRevision: string;
137
+ } | undefined;
138
+ } | undefined;
98
139
  workflow: WorkflowInstanceView | null;
99
140
  assignmentId: string;
100
141
  objective: string;
@@ -118,12 +159,20 @@ export declare class OrchestrationService {
118
159
  workflowInstanceId: WorkflowInstanceId;
119
160
  grantId: string;
120
161
  repositoryResourceIds?: string[] | undefined;
162
+ prerequisites?: {
163
+ assignmentId: string;
164
+ output: string;
165
+ condition: "accepted-output" | "pushed-change" | "delivery-ready" | "merged-change";
166
+ cohortId?: string | undefined;
167
+ useAsBase?: boolean | undefined;
168
+ }[] | undefined;
121
169
  repository?: {
122
170
  resourceId: string;
123
171
  sourceRef: string;
124
172
  pullRequestBase: string;
125
173
  sourceRevision: string;
126
174
  } | undefined;
175
+ prerequisiteWorkItemIds?: WorkItemId[] | undefined;
127
176
  }[];
128
177
  cohortId: string;
129
178
  parentWorkflowInstanceId: WorkflowInstanceId;
@@ -134,13 +183,42 @@ export declare class OrchestrationService {
134
183
  ancestors: WorkItemId[];
135
184
  maxDepth: number;
136
185
  maxDescendants: number;
186
+ planRevision?: number | undefined;
137
187
  maxConcurrentRuns?: number | undefined;
138
188
  }[];
139
189
  }>;
140
190
  deliveryTree(id: WorkItemId): Promise<{
141
191
  settled: boolean;
192
+ failureReason: string | undefined;
142
193
  children: {
143
194
  work: WorkItemView | null;
195
+ prerequisiteBlocker: string | undefined;
196
+ consumedInputs: {
197
+ childWorkItemId: WorkItemId;
198
+ consumed: {
199
+ name: string;
200
+ reference: {
201
+ workItemId: WorkItemId;
202
+ revisionId: string;
203
+ } | {
204
+ workItemId: WorkItemId;
205
+ resourceId: string;
206
+ repositoryResourceId: string;
207
+ revision: string;
208
+ branch: string;
209
+ pullRequestBase: string;
210
+ runId: string;
211
+ baseRevision?: string | undefined;
212
+ merged?: true | undefined;
213
+ };
214
+ }[];
215
+ repository?: {
216
+ resourceId: string;
217
+ sourceRef: string;
218
+ pullRequestBase: string;
219
+ sourceRevision: string;
220
+ } | undefined;
221
+ } | undefined;
144
222
  workflow: WorkflowInstanceView | null;
145
223
  assignmentId: string;
146
224
  objective: string;
@@ -164,12 +242,20 @@ export declare class OrchestrationService {
164
242
  workflowInstanceId: WorkflowInstanceId;
165
243
  grantId: string;
166
244
  repositoryResourceIds?: string[] | undefined;
245
+ prerequisites?: {
246
+ assignmentId: string;
247
+ output: string;
248
+ condition: "accepted-output" | "pushed-change" | "delivery-ready" | "merged-change";
249
+ cohortId?: string | undefined;
250
+ useAsBase?: boolean | undefined;
251
+ }[] | undefined;
167
252
  repository?: {
168
253
  resourceId: string;
169
254
  sourceRef: string;
170
255
  pullRequestBase: string;
171
256
  sourceRevision: string;
172
257
  } | undefined;
258
+ prerequisiteWorkItemIds?: WorkItemId[] | undefined;
173
259
  }[];
174
260
  cohortId: string;
175
261
  parentWorkflowInstanceId: WorkflowInstanceId;
@@ -180,6 +266,7 @@ export declare class OrchestrationService {
180
266
  ancestors: WorkItemId[];
181
267
  maxDepth: number;
182
268
  maxDescendants: number;
269
+ planRevision?: number | undefined;
183
270
  maxConcurrentRuns?: number | undefined;
184
271
  }[]>;
185
272
  deliveryRunLimit(id: WorkItemId): Promise<number | undefined>;
@@ -200,6 +287,8 @@ export declare class OrchestrationService {
200
287
  branch: string;
201
288
  pullRequestBase: string;
202
289
  runId: string;
290
+ baseRevision?: string | undefined;
291
+ merged?: true | undefined;
203
292
  };
204
293
  }[];
205
294
  }[]>;
@@ -213,6 +302,19 @@ export declare class OrchestrationService {
213
302
  activationId: ActivationId;
214
303
  outcome: ActivityOutcome;
215
304
  }, context: CommandContext): Promise<WorkflowInstanceView>;
305
+ /**
306
+ * Every ending restores the cohort wait, so independent members keep running and their
307
+ * results stay joinable (a join that completed meanwhile then proceeds). A structured
308
+ * human question is also recorded as an accepted outcome, which the ordinary publication
309
+ * route delivers to a human; a failed assessment run is recorded and re-raised a bounded
310
+ * number of times. The cohort is never settled or cancelled by the assessment itself.
311
+ */
312
+ private endAttention;
313
+ /** Delegated children still blocked on a question this work item's parent escalated to a human. */
314
+ escalatedReplyTargets(workItemId: WorkItemId): Promise<WorkItemId[]>;
315
+ /** The open attention request when `activationId` is the attention activation, else null. */
316
+ openDelegationAttention(id: WorkflowInstanceId, activationId: ActivationId): Promise<import("./delegation-attention-state.js").OpenAttention | null>;
317
+ respondToDelegationAttention(caller: DelegationCaller, reply: DelegationAttentionReply, context: CommandContext): Promise<import("./delegation-attention-state.js").OpenAttention | null>;
216
318
  waitForSignal(workflowInstanceId: WorkflowInstanceId, expectation: SignalExpectation, context: CommandContext): Promise<WorkflowInstanceView>;
217
319
  acceptSignal(workflowInstanceId: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext): Promise<WorkflowInstanceView>;
218
320
  setAcceptSignalOperationCoordinator(coordinator: OperationCoordinator): void;
@@ -17,6 +17,7 @@ import { AcceptSignal } from './accept-signal.js';
17
17
  import { AdvanceWorkflow } from './advance-workflow.js';
18
18
  import { applyBuiltInConversationCommand, continuationCommandRejection, conversationCommand, } from './conversation-command.js';
19
19
  import { CoordinationClaims } from './coordination-claims.js';
20
+ import { attentionVerdict } from './delegation-attention-state.js';
20
21
  import { GroupBudgetRecorder } from './group-budget-recorder.js';
21
22
  import { workflowsByWorkItemProjection } from './orchestration-projection.js';
22
23
  import { OrchestrationRepository } from './orchestration-repository.js';
@@ -28,6 +29,8 @@ export class OrchestrationService {
28
29
  delegationCommands;
29
30
  delegationGate;
30
31
  delegatedWork;
32
+ prerequisiteReasons = (ids, snapshot) => this.delegatedWork.prerequisites.reasons(ids, snapshot);
33
+ resumeClarification = (id, context) => this.advanceWorkflow.resumeNeedsClarificationStage(id, context);
31
34
  repository;
32
35
  deferredSignals;
33
36
  startWorkflow;
@@ -42,13 +45,15 @@ export class OrchestrationService {
42
45
  journal;
43
46
  definitions;
44
47
  work;
48
+ // Composition root for the module's services; splitting it would only scatter the wiring.
49
+ // eslint-disable-next-line max-lines-per-function
45
50
  constructor(journal, work, definitions, projections, isAgentActivity, delegation) {
46
51
  this.projections = projections;
47
52
  this.journal = journal;
48
53
  this.work = work;
49
54
  const repository = new OrchestrationRepository(journal);
50
55
  this.repository = repository;
51
- this.delegationGate = new DelegationGate(repository, work);
56
+ this.delegationGate = new DelegationGate(repository, work, delegation === undefined ? undefined : this.prerequisiteReasons);
52
57
  const dependencies = delegation?.({
53
58
  isActivationAccepted: (id, item) => this.isActivationAccepted(id, item),
54
59
  });
@@ -60,6 +65,8 @@ export class OrchestrationService {
60
65
  artifacts: dependencies?.artifacts ?? unavailableArtifacts,
61
66
  repositories: dependencies?.repositories,
62
67
  runHasEnded: dependencies?.runHasEnded ?? unavailableRunCompletion,
68
+ supportsAttention: isAgentActivity,
69
+ resumeChild: this.resumeClarification,
63
70
  });
64
71
  this.delegationCommands = new DelegationCommands(repository, work, this.startWorkflow, this.definitions, this.delegatedWork, dependencies?.authority ?? unavailableDelegationAuthority);
65
72
  this.advanceWorkflow = new AdvanceWorkflow(repository, this.startWorkflow, (command, context) => this.acceptOutcome(command, context), isAgentActivity);
@@ -124,7 +131,38 @@ export class OrchestrationService {
124
131
  return this.transitionWatchChildren(context, () => this.delegationGate.outcome(command.workflowInstanceId, command.activationId, () => this.acceptActivityOutcome.execute(command, context), async () => {
125
132
  await this.reconcileChildCompletions(context);
126
133
  return (await this.repository.loadRequired(command.workflowInstanceId)).view;
127
- }));
134
+ }, async (view) => view, () => this.endAttention(command, context)));
135
+ }
136
+ /**
137
+ * Every ending restores the cohort wait, so independent members keep running and their
138
+ * results stay joinable (a join that completed meanwhile then proceeds). A structured
139
+ * human question is also recorded as an accepted outcome, which the ordinary publication
140
+ * route delivers to a human; a failed assessment run is recorded and re-raised a bounded
141
+ * number of times. The cohort is never settled or cancelled by the assessment itself.
142
+ */
143
+ async endAttention(command, context) {
144
+ await this.delegatedWork.attention.resolve(command.workflowInstanceId, command.activationId, context, attentionVerdict(command.outcome));
145
+ await this.delegatedWork.reconcile(context);
146
+ return (await this.repository.loadRequired(command.workflowInstanceId)).view;
147
+ }
148
+ /** Delegated children still blocked on a question this work item's parent escalated to a human. */
149
+ async escalatedReplyTargets(workItemId) {
150
+ const targets = [];
151
+ for (const parent of await this.advanceWorkflow.listAll())
152
+ if (parent.workItemId === workItemId)
153
+ for (const target of await this.delegatedWork.attention.escalatedTargets(parent))
154
+ targets.push(target.childWorkItemId);
155
+ return targets;
156
+ }
157
+ /** The open attention request when `activationId` is the attention activation, else null. */
158
+ async openDelegationAttention(id, activationId) {
159
+ const view = (await this.repository.load(id)).view;
160
+ if (view?.delegationAttention?.activationId !== activationId)
161
+ return null;
162
+ return this.delegatedWork.attention.current(view);
163
+ }
164
+ respondToDelegationAttention(caller, reply, context) {
165
+ return this.delegationCommands.respond(caller, reply, context);
128
166
  }
129
167
  waitForSignal(workflowInstanceId, expectation, context) {
130
168
  return this.transitionWatchChildren(context, async () => {
@@ -0,0 +1,68 @@
1
+ import type { DeliverySnapshot } from '../../work/index.js';
2
+ import type { DelegationArtifacts, DelegationRepositories } from '../contracts/delegation-ports.js';
3
+ import type { DelegationInputs, DelegationReservation } from '../contracts/delegation.js';
4
+ import type { WorkflowInstanceView } from '../contracts/views.js';
5
+ import { PrerequisiteBlockCode as Code } from '../contracts/vocabulary.js';
6
+ import type { OrchestrationRepository } from './orchestration-repository.js';
7
+ type Child = DelegationReservation['children'][number];
8
+ export interface PrerequisiteAdmission {
9
+ readonly reason: string | undefined;
10
+ readonly abandoned: boolean;
11
+ }
12
+ export interface PrerequisiteBlock {
13
+ readonly code: Code;
14
+ readonly reason: string;
15
+ }
16
+ /** A bounded read pass: one journal/Work snapshot and one lookup per declared input. */
17
+ export declare class PrerequisiteReadiness {
18
+ private readonly work;
19
+ private readonly artifacts;
20
+ private readonly repositories;
21
+ private readonly failedChildren;
22
+ private readonly children;
23
+ private readonly owners;
24
+ private readonly receipts;
25
+ private readonly workflows;
26
+ private readonly blockers;
27
+ private readonly evaluated;
28
+ private readonly selected;
29
+ private readonly bases;
30
+ constructor(snapshot: Awaited<ReturnType<OrchestrationRepository['snapshot']>>, work: DeliverySnapshot, artifacts: DelegationArtifacts, repositories: DelegationRepositories | undefined);
31
+ abandoned(id: string): boolean;
32
+ inputs(id: string): {
33
+ childWorkItemId: import("../../work/index.js").WorkItemId;
34
+ consumed: {
35
+ name: string;
36
+ reference: {
37
+ workItemId: import("../../work/index.js").WorkItemId;
38
+ revisionId: string;
39
+ } | {
40
+ workItemId: import("../../work/index.js").WorkItemId;
41
+ resourceId: string;
42
+ repositoryResourceId: string;
43
+ revision: string;
44
+ branch: string;
45
+ pullRequestBase: string;
46
+ runId: string;
47
+ baseRevision?: string | undefined;
48
+ merged?: true | undefined;
49
+ };
50
+ }[];
51
+ repository?: {
52
+ resourceId: string;
53
+ sourceRef: string;
54
+ pullRequestBase: string;
55
+ sourceRevision: string;
56
+ } | undefined;
57
+ } | undefined;
58
+ workflow(id: string): WorkflowInstanceView | undefined;
59
+ reason(id: string): Promise<string | undefined>;
60
+ block(id: string, seen?: Set<string>): Promise<PrerequisiteBlock | undefined>;
61
+ private evaluate;
62
+ select(child: Child, seen: Set<string>): Promise<DelegationInputs['consumed'] | PrerequisiteBlock>;
63
+ private baseReason;
64
+ private selectOne;
65
+ private upstreamAvailability;
66
+ private verifyBase;
67
+ }
68
+ export {};