@atolis-hq/wake 0.4.102 → 0.4.103

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 (38) 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/surface-api-delivery.js +6 -2
  4. package/dist/src/bootstrap/version.js +1 -1
  5. package/dist/src/integrations/application/delegation-outputs.js +41 -5
  6. package/dist/src/orchestration/application/delegated-work.d.ts +46 -2
  7. package/dist/src/orchestration/application/delegated-work.js +135 -21
  8. package/dist/src/orchestration/application/delegation-commands.d.ts +47 -0
  9. package/dist/src/orchestration/application/delegation-commands.js +4 -2
  10. package/dist/src/orchestration/application/delegation-gate.d.ts +5 -3
  11. package/dist/src/orchestration/application/delegation-gate.js +31 -9
  12. package/dist/src/orchestration/application/delegation-ledger.d.ts +2 -0
  13. package/dist/src/orchestration/application/delegation-ledger.js +8 -0
  14. package/dist/src/orchestration/application/delegation-prerequisites.d.ts +28 -0
  15. package/dist/src/orchestration/application/delegation-prerequisites.js +118 -0
  16. package/dist/src/orchestration/application/delegation-reservation.js +1 -1
  17. package/dist/src/orchestration/application/delegation-wait-graph.d.ts +7 -0
  18. package/dist/src/orchestration/application/delegation-wait-graph.js +122 -0
  19. package/dist/src/orchestration/application/orchestration-repository.d.ts +5 -0
  20. package/dist/src/orchestration/application/orchestration-repository.js +3 -0
  21. package/dist/src/orchestration/application/orchestration-service.d.ts +87 -0
  22. package/dist/src/orchestration/application/orchestration-service.js +3 -2
  23. package/dist/src/orchestration/application/prerequisite-readiness.d.ts +68 -0
  24. package/dist/src/orchestration/application/prerequisite-readiness.js +217 -0
  25. package/dist/src/orchestration/contracts/delegation-ports.d.ts +2 -1
  26. package/dist/src/orchestration/contracts/delegation.d.ts +88 -0
  27. package/dist/src/orchestration/contracts/delegation.js +36 -1
  28. package/dist/src/orchestration/contracts/event-decoder.js +8 -1
  29. package/dist/src/orchestration/contracts/event-factory.js +5 -4
  30. package/dist/src/orchestration/contracts/events.d.ts +13 -1
  31. package/dist/src/orchestration/contracts/events.js +3 -0
  32. package/dist/src/orchestration/contracts/vocabulary.d.ts +27 -0
  33. package/dist/src/orchestration/contracts/vocabulary.js +25 -0
  34. package/dist/src/orchestration/domain/workflow-instance-events.js +3 -0
  35. package/dist/src/orchestration/index.d.ts +2 -2
  36. package/dist/src/orchestration/index.js +1 -1
  37. package/dist/src/surfaces/mcp/delegation.js +18 -10
  38. package/package.json +1 -1
@@ -1,6 +1,8 @@
1
1
  import { ActivityEventType } from '../contracts/events.js';
2
2
  import type { PullRequestAuthorityDecision, PullRequestAuthorityInput, PullRequestAuthorityOptions, PullRequestResourceView, PullRequestView } from './contracts.js';
3
3
  export declare function decidePullRequestAuthority(input: PullRequestAuthorityInput, options?: PullRequestAuthorityOptions): PullRequestAuthorityDecision;
4
+ /** Qualifies an existing output without authorizing another approval or merge. */
5
+ export declare function decidePullRequestOutputAuthority(input: PullRequestAuthorityInput, options: PullRequestAuthorityOptions): PullRequestAuthorityDecision;
4
6
  export declare function createPullRequestMergeDenial(decision: PullRequestAuthorityDecision): {
5
7
  readonly eventType: typeof ActivityEventType.PrMergeDenied;
6
8
  readonly payload: {
@@ -8,6 +8,13 @@ export function decidePullRequestAuthority(input, options = {
8
8
  requireAcceptedReview: true,
9
9
  requireChecks: true,
10
10
  }) {
11
+ return decideAuthority(input, options, false);
12
+ }
13
+ /** Qualifies an existing output without authorizing another approval or merge. */
14
+ export function decidePullRequestOutputAuthority(input, options) {
15
+ return decideAuthority(input, options, true);
16
+ }
17
+ function decideAuthority(input, options, allowMerged) {
11
18
  if (input.work === null)
12
19
  return denied(PullRequestDenialCode.MissingResource);
13
20
  const resource = selectResource(input, input.work.workItemId, options.target);
@@ -16,7 +23,8 @@ export function decidePullRequestAuthority(input, options = {
16
23
  const pullRequest = selectPullRequest(input, resource, input.work.workItemId);
17
24
  if (isDenial(pullRequest))
18
25
  return pullRequest;
19
- if (pullRequest.state !== PullRequestState.Open)
26
+ if (pullRequest.state !== PullRequestState.Open &&
27
+ !(allowMerged && pullRequest.state === PullRequestState.Merged))
20
28
  return denied(PullRequestDenialCode.Closed);
21
29
  const authority = finalizeAuthority(input, resource, pullRequest, options);
22
30
  if (authority !== null)
@@ -22,8 +22,12 @@ export async function presentDelivery(root, work) {
22
22
  workflowName: child.workflowName,
23
23
  status: child.workflow?.status ?? 'registration-pending',
24
24
  cohortId: cohort.cohortId,
25
- ...((availability.reason ?? child.workflow?.blockReason)
26
- ? { blockReason: (availability.reason ?? child.workflow?.blockReason) }
25
+ ...((availability.reason ?? child.prerequisiteBlocker ?? child.workflow?.blockReason)
26
+ ? {
27
+ blockReason: (availability.reason ??
28
+ child.prerequisiteBlocker ??
29
+ child.workflow?.blockReason),
30
+ }
27
31
  : {}),
28
32
  resources: resources
29
33
  .filter((entry) => entry !== null)
@@ -124,6 +124,6 @@ export function resolveWakeVersion(options = {}) {
124
124
  return `g${headHash.slice(0, 7)}`;
125
125
  return '0.1.0-dev';
126
126
  }
127
- export const wakeVersion = "v0.4.102";
127
+ export const wakeVersion = "v0.4.103";
128
128
  /** The registry-installable version used by packaged sandbox images. */
129
129
  export const wakePackageVersion = packageVersion(defaultRepoRoot) ?? wakeVersion;
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
- import { reportedArtifactSchema } from '../../activities/index.js';
2
+ import { decidePullRequestOutputAuthority, PullRequestState, reportedArtifactSchema, } from '../../activities/index.js';
3
3
  import { RunStatus, WorkspaceMode } from '../../execution/index.js';
4
+ import { DelegationPrerequisiteCondition as Condition } from '../../orchestration/index.js';
4
5
  import { BuiltInResourceKind, ResourceCorrelationProvenance, ResourceCorrelationRole, resourceId, } from '../../resources/index.js';
5
6
  import { ArtifactVerificationResult } from '../contracts/artifact-vocabulary.js';
6
7
  const reportsSchema = z.object({ reportedArtifacts: z.array(reportedArtifactSchema) });
@@ -8,6 +9,15 @@ const reportsSchema = z.object({ reportedArtifacts: z.array(reportedArtifactSche
8
9
  export function createDelegationOutputs(input) {
9
10
  return {
10
11
  ...input.artifacts,
12
+ async prerequisiteOutput(child, output, condition) {
13
+ if ('path' in output &&
14
+ (condition === Condition.AcceptedOutput || condition === Condition.DeliveryReady)) {
15
+ return (await input.artifacts.qualifyingOutputs(child, [output]))?.[0] ?? null;
16
+ }
17
+ if (!('kind' in output))
18
+ return null;
19
+ return qualifyingChange(input, child, output, condition);
20
+ },
11
21
  async qualifyingOutputs(child, outputs) {
12
22
  const artifacts = outputs.filter((output) => 'path' in output);
13
23
  const references = artifacts.length === 0 ? [] : await input.artifacts.qualifyingOutputs(child, artifacts);
@@ -61,7 +71,7 @@ async function verifiedChange(input, report, source) {
61
71
  return null;
62
72
  return resource;
63
73
  }
64
- async function qualifyingChange(input, child, output) {
74
+ async function qualifyingChange(input, child, output, condition) {
65
75
  const runs = (await input.runs()).filter((run) => run.workflowInstanceId === child.workflowInstanceId &&
66
76
  run.status === RunStatus.Succeeded &&
67
77
  child.acceptedOutcomes.includes(run.activationId));
@@ -78,7 +88,8 @@ async function qualifyingChange(input, child, output) {
78
88
  const resource = await verifiedChange(input, latest.report, source);
79
89
  if (resource === null)
80
90
  return null;
81
- if (!(await hasOutputAuthority(input, child, output, resource.resourceId, revision)))
91
+ const observed = await qualifyingObservation(input, child, output, resource.resourceId, revision, condition);
92
+ if (observed === null)
82
93
  return null;
83
94
  return {
84
95
  name: output.name,
@@ -90,20 +101,45 @@ async function qualifyingChange(input, child, output) {
90
101
  branch,
91
102
  pullRequestBase: assignment.pullRequestBase,
92
103
  runId: run.runId,
104
+ ...(condition === undefined ? {} : { baseRevision: observed.baseRevision }),
105
+ ...(observed.state === PullRequestState.Merged ? { merged: true } : {}),
93
106
  },
94
107
  };
95
108
  }
109
+ async function qualifyingObservation(input, child, output, id, revision, condition) {
110
+ const owner = await input.resources.primaryCorrelation(id);
111
+ if (owner?.workItemId !== child.workItemId ||
112
+ owner.role !== ResourceCorrelationRole.Primary ||
113
+ owner.provenance !== ResourceCorrelationProvenance.AgentReported)
114
+ return null;
115
+ const observed = await input.pullRequests.get(id);
116
+ if (observed === null || observed.headRevision !== revision)
117
+ return null;
118
+ if (condition === Condition.MergedChange) {
119
+ if (observed.state !== PullRequestState.Merged)
120
+ return null;
121
+ }
122
+ else if (!(await hasOutputAuthority(input, child, condition === Condition.PushedChange
123
+ ? { ...output, requireReview: false, requireChecks: false }
124
+ : output, id, revision)))
125
+ return null;
126
+ return observed;
127
+ }
96
128
  async function hasOutputAuthority(input, child, output, id, revision) {
97
129
  const owner = await input.resources.primaryCorrelation(id);
98
130
  if (owner?.workItemId !== child.workItemId ||
99
131
  owner.role !== ResourceCorrelationRole.Primary ||
100
132
  owner.provenance !== ResourceCorrelationProvenance.AgentReported)
101
133
  return false;
102
- const authority = await input.pullRequests.decideAuthority(child.workItemId, {
134
+ const options = {
103
135
  target: { resourceId: id },
104
136
  requireAcceptedReview: output.requireReview ?? true,
105
137
  requireChecks: output.requireChecks ?? true,
106
- });
138
+ };
139
+ const observed = await input.pullRequests.get(id);
140
+ const authority = observed?.state === PullRequestState.Merged
141
+ ? decidePullRequestOutputAuthority(await input.pullRequests.authorityInput(child.workItemId), options)
142
+ : await input.pullRequests.decideAuthority(child.workItemId, options);
107
143
  if (!authority.allowed || authority.revision !== revision)
108
144
  return false;
109
145
  return true;
@@ -7,6 +7,7 @@ import type { DelegatedAssignment, DelegationCaller, DelegationLimits, Delegatio
7
7
  import { type WorkflowInstanceId } from '../contracts/identifiers.js';
8
8
  import type { WorkflowInstanceView } from '../contracts/views.js';
9
9
  import type { CoordinationClaims } from './coordination-claims.js';
10
+ import { DelegationPrerequisites } from './delegation-prerequisites.js';
10
11
  import type { OrchestrationRepository } from './orchestration-repository.js';
11
12
  import type { StartWorkflow } from './start-workflow.js';
12
13
  import type { WorkflowDefinitionRegistry } from './workflow-definition-registry.js';
@@ -22,6 +23,7 @@ export declare class DelegatedWork {
22
23
  private readonly workflows;
23
24
  private readonly dependencies;
24
25
  private readonly ledger;
26
+ readonly prerequisites: DelegationPrerequisites;
25
27
  private readonly artifacts;
26
28
  private readonly repositories;
27
29
  private readonly runHasEnded;
@@ -33,8 +35,36 @@ export declare class DelegatedWork {
33
35
  });
34
36
  inspect(id: WorkItemId): Promise<{
35
37
  settled: boolean;
38
+ failureReason: string | undefined;
36
39
  children: {
37
40
  work: import("../../work/index.js").WorkItemView | null;
41
+ prerequisiteBlocker: string | undefined;
42
+ consumedInputs: {
43
+ childWorkItemId: WorkItemId;
44
+ consumed: {
45
+ name: string;
46
+ reference: {
47
+ workItemId: WorkItemId;
48
+ revisionId: string;
49
+ } | {
50
+ workItemId: WorkItemId;
51
+ resourceId: string;
52
+ repositoryResourceId: string;
53
+ revision: string;
54
+ branch: string;
55
+ pullRequestBase: string;
56
+ runId: string;
57
+ baseRevision?: string | undefined;
58
+ merged?: true | undefined;
59
+ };
60
+ }[];
61
+ repository?: {
62
+ resourceId: string;
63
+ sourceRef: string;
64
+ pullRequestBase: string;
65
+ sourceRevision: string;
66
+ } | undefined;
67
+ } | undefined;
38
68
  workflow: WorkflowInstanceView | null;
39
69
  assignmentId: string;
40
70
  objective: string;
@@ -58,12 +88,20 @@ export declare class DelegatedWork {
58
88
  workflowInstanceId: WorkflowInstanceId;
59
89
  grantId: string;
60
90
  repositoryResourceIds?: string[] | undefined;
91
+ prerequisites?: {
92
+ assignmentId: string;
93
+ output: string;
94
+ condition: "accepted-output" | "pushed-change" | "delivery-ready" | "merged-change";
95
+ cohortId?: string | undefined;
96
+ useAsBase?: boolean | undefined;
97
+ }[] | undefined;
61
98
  repository?: {
62
99
  resourceId: string;
63
100
  sourceRef: string;
64
101
  pullRequestBase: string;
65
102
  sourceRevision: string;
66
103
  } | undefined;
104
+ prerequisiteWorkItemIds?: WorkItemId[] | undefined;
67
105
  }[];
68
106
  cohortId: string;
69
107
  parentWorkflowInstanceId: WorkflowInstanceId;
@@ -74,6 +112,7 @@ export declare class DelegatedWork {
74
112
  ancestors: WorkItemId[];
75
113
  maxDepth: number;
76
114
  maxDescendants: number;
115
+ planRevision?: number | undefined;
77
116
  maxConcurrentRuns?: number | undefined;
78
117
  }[]>;
79
118
  runLimit(id: WorkItemId): Promise<number | undefined>;
@@ -86,7 +125,7 @@ export declare class DelegatedWork {
86
125
  } | undefined>;
87
126
  contextWorkItems(parent: WorkflowInstanceView): Promise<ReadonlySet<string>>;
88
127
  results(id: WorkflowInstanceId, cohortId: string): Promise<readonly DelegationResult[]>;
89
- reserve(caller: DelegationCaller, cohortId: string, assignments: readonly DelegatedAssignment[], context: CommandContext, limits?: DelegationLimits): Promise<DelegationReservation>;
128
+ reserve(caller: DelegationCaller, cohortId: string, assignments: readonly DelegatedAssignment[], context: CommandContext, limits?: DelegationLimits, expectedPlanRevision?: number): Promise<DelegationReservation>;
90
129
  private pinAssignments;
91
130
  reconcile(context: CommandContext): Promise<void>;
92
131
  private capacityReservations;
@@ -97,18 +136,23 @@ export declare class DelegatedWork {
97
136
  /** Appends the reservation only if the root stream is unchanged since `events` was read. */
98
137
  private commit;
99
138
  private reconcileReservation;
139
+ private settleUnusable;
140
+ private abandon;
141
+ private preparePrerequisites;
142
+ private childrenQualified;
100
143
  private ensureWait;
101
144
  private fail;
102
145
  /** WorkItem, primary claim and artifact grant are each idempotent; none starts a workflow. */
103
146
  private registerChildren;
104
147
  /** Starts the pinned definition, then records the result only once the child qualifies. */
105
148
  private advanceChild;
149
+ private failChild;
106
150
  private childWorkTerminated;
107
151
  private missingOutputs;
108
152
  private endedRun;
109
153
  /** Commit-boundary read: observes appends from other hosts, then answers from memory. */
110
154
  private deliveryAvailability;
111
155
  private canJoin;
112
- /** Join and continuation commit together, so a duplicate trigger cannot resume the parent twice. */
156
+ /** Settlement and continuation commit together; failures request assessment without a successful join. */
113
157
  private join;
114
158
  }
@@ -3,13 +3,16 @@ import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
3
3
  import { activationId } from '../../activities/index.js';
4
4
  import { WorkspaceMode } from '../../execution/index.js';
5
5
  import { WorkStatus } from '../../work/index.js';
6
+ import { DelegationConflictError } from '../contracts/delegation.js';
6
7
  import { OrchestrationEventType } from '../contracts/events.js';
7
8
  import { orchestrationGroupId, workflowInstanceId, } from '../contracts/identifiers.js';
8
- import { WorkflowStatus } from '../contracts/vocabulary.js';
9
+ import { DelegationConflictCode, DelegationPrerequisiteCondition, WorkflowStatus, } from '../contracts/vocabulary.js';
9
10
  import { nextOrdinal } from '../domain/decision-events.js';
10
11
  import { isSuccessfulWorkflowCompletion } from '../domain/workflow-completion.js';
11
- import { delegationDraft, delegationEventId, DelegationLedger, isJoined, isSettled, reservationsOf, reservedEvent, selectedResults, } from './delegation-ledger.js';
12
+ import { delegationDraft, delegationEventId, DelegationLedger, isJoined, isSettled, reservationsOf, reservedEvent, selectedResults, unsettledReservations, } from './delegation-ledger.js';
13
+ import { DelegationPrerequisites } from './delegation-prerequisites.js';
12
14
  import { assertWithinRootLimits, buildReservation, matchesAssignments, } from './delegation-reservation.js';
15
+ import { resolvePrerequisites } from './delegation-wait-graph.js';
13
16
  const defaultLimits = { maxDepth: 1, maxDescendants: 8 };
14
17
  /**
15
18
  * Durable delegation of independent child WorkItems. Reservation is the single commit point;
@@ -23,6 +26,7 @@ export class DelegatedWork {
23
26
  workflows;
24
27
  dependencies;
25
28
  ledger;
29
+ prerequisites;
26
30
  artifacts;
27
31
  repositories;
28
32
  runHasEnded;
@@ -35,6 +39,7 @@ export class DelegatedWork {
35
39
  this.dependencies = dependencies;
36
40
  this.ledger = new DelegationLedger(repository);
37
41
  this.artifacts = dependencies.artifacts;
42
+ this.prerequisites = new DelegationPrerequisites(repository, this.ledger, dependencies.artifacts, dependencies.repositories, work);
38
43
  this.repositories = dependencies.repositories;
39
44
  this.runHasEnded = dependencies.runHasEnded;
40
45
  }
@@ -43,13 +48,21 @@ export class DelegatedWork {
43
48
  const root = item?.delegation?.rootWorkItemId ?? id;
44
49
  const events = await this.ledger.events();
45
50
  const reservations = reservationsOf(events).filter((entry) => entry.rootWorkItemId === root);
51
+ const read = await this.prerequisites.read();
46
52
  return Promise.all(reservations.map(async (reservation) => ({
47
53
  ...reservation,
48
54
  settled: isSettled(events, reservation),
55
+ failureReason: events.flatMap(({ event, stream }) => stream.id === reservation.parentWorkflowInstanceId &&
56
+ event.eventType === OrchestrationEventType.DelegationFailed &&
57
+ event.payload.cohortId === reservation.cohortId
58
+ ? [event.payload.reason]
59
+ : [])[0],
49
60
  children: await Promise.all(reservation.children.map(async (child) => ({
50
61
  ...child,
51
62
  work: await this.work.get(child.workItemId),
52
- workflow: (await this.repository.load(child.workflowInstanceId)).view,
63
+ prerequisiteBlocker: (await read.reason(child.workItemId)) ?? childBlocker(events, child.workItemId),
64
+ consumedInputs: read.inputs(child.workItemId),
65
+ workflow: read.workflow(child.workflowInstanceId) ?? null,
53
66
  }))),
54
67
  })));
55
68
  }
@@ -77,6 +90,9 @@ export class DelegatedWork {
77
90
  (child.repository === undefined ? [] : [child.repository.resourceId]));
78
91
  }
79
92
  async repositoryFor(workItemId) {
93
+ const inputs = await this.prerequisites.inputs(workItemId);
94
+ if (inputs?.repository !== undefined)
95
+ return inputs.repository;
80
96
  return (await this.ledger.reservations())
81
97
  .flatMap((entry) => entry.children)
82
98
  .find((child) => child.workItemId === workItemId)?.repository;
@@ -99,7 +115,7 @@ export class DelegatedWork {
99
115
  ? joined.event.payload.results
100
116
  : [];
101
117
  }
102
- async reserve(caller, cohortId, assignments, context, limits = defaultLimits) {
118
+ async reserve(caller, cohortId, assignments, context, limits = defaultLimits, expectedPlanRevision) {
103
119
  const artifacts = this.artifacts;
104
120
  const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
105
121
  const identity = await this.parentIdentity(parent);
@@ -128,6 +144,15 @@ export class DelegatedWork {
128
144
  return prior;
129
145
  }
130
146
  await this.assertReservable(caller, await this.capacityReservations(all, events), reservation, rootLimits);
147
+ assertPlanRevision(expectedPlanRevision, all.length);
148
+ reservation = { ...reservation, planRevision: all.length + 1 };
149
+ reservation = await resolvePrerequisites(reservation, all, this.ledger, this.definitions, async (target, name) => {
150
+ const view = (await this.repository.load(target.workflowInstanceId)).view;
151
+ const output = target.outputs.find((entry) => entry.name === name);
152
+ return (view !== null &&
153
+ output !== undefined &&
154
+ (await artifacts.prerequisiteOutput?.(view, output, DelegationPrerequisiteCondition.MergedChange)) != null);
155
+ });
131
156
  for (const child of reservation.children)
132
157
  await this.prepareChild(artifacts, parent, child, context);
133
158
  if (await this.commit(identity.root, sequence, reservation, context)) {
@@ -150,11 +175,8 @@ export class DelegatedWork {
150
175
  }));
151
176
  }
152
177
  async reconcile(context) {
153
- const all = await this.ledger.reservations();
154
- if (all.length === 0)
155
- return;
156
178
  const events = await this.ledger.events();
157
- const reservations = all.filter((reservation) => !isSettled(events, reservation));
179
+ const reservations = unsettledReservations(events);
158
180
  if (reservations.length === 0)
159
181
  return;
160
182
  const artifacts = this.artifacts;
@@ -280,15 +302,79 @@ export class DelegatedWork {
280
302
  if (!(await this.ensureWait(reservation, context)))
281
303
  return;
282
304
  const root = await this.registerChildren(artifacts, reservation, context);
305
+ const read = await this.prerequisites.read();
283
306
  for (const child of reservation.children) {
284
- if (isSettled(await this.ledger.events(), reservation))
307
+ const events = await this.ledger.events();
308
+ if (isSettled(events, reservation))
285
309
  break;
286
- await this.advanceChild(artifacts, root, reservation, child, context);
310
+ if (childBlocker(events, child.workItemId) !== undefined)
311
+ continue;
312
+ if (await this.preparePrerequisites(root, reservation, child, context, read))
313
+ await this.advanceChild(artifacts, root, reservation, child, context);
287
314
  }
315
+ if (await this.settleUnusable(reservation, context))
316
+ return;
288
317
  const results = selectedResults(await this.ledger.events(), reservation);
289
- if (reservation.children.every((c) => results.some((r) => r.childWorkItemId === c.workItemId)))
318
+ if (await this.childrenQualified(reservation, results, context))
290
319
  await this.join(reservation, results, context);
291
320
  }
321
+ async settleUnusable(reservation, context) {
322
+ const events = await this.ledger.events();
323
+ const failed = new Set(events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationChildBlocked
324
+ ? [event.payload.childWorkItemId]
325
+ : []));
326
+ const first = reservation.children.find((child) => failed.has(child.workItemId));
327
+ if (first === undefined)
328
+ return false;
329
+ for (let pass = 0; pass < reservation.children.length; pass++)
330
+ for (const child of reservation.children)
331
+ if (child.prerequisiteWorkItemIds?.some((id) => failed.has(id)))
332
+ failed.add(child.workItemId);
333
+ const selected = new Set(selectedResults(events, reservation).map((result) => result.childWorkItemId));
334
+ if (reservation.children.every((child) => failed.has(child.workItemId) || selected.has(child.workItemId))) {
335
+ if (!(await this.canJoin(reservation)))
336
+ return true;
337
+ await this.abandon(reservation, failed, context);
338
+ await this.join(reservation, [], context, 'Delegated inputs or child failed; inspect blockers and submit replacement work');
339
+ }
340
+ return true;
341
+ }
342
+ async abandon(reservation, failed, context) {
343
+ for (const child of reservation.children) {
344
+ if (!failed.has(child.workItemId))
345
+ continue;
346
+ const view = (await this.repository.load(child.workflowInstanceId)).view;
347
+ if (view === null ||
348
+ view.status === WorkflowStatus.Completed ||
349
+ view.status === WorkflowStatus.Superseded)
350
+ continue;
351
+ await this.ledger.appendOnce(child.workflowInstanceId, context, 'abandoned:' + child.grantId, { eventType: OrchestrationEventType.InstanceSuperseded, payload: {} });
352
+ }
353
+ }
354
+ async preparePrerequisites(root, reservation, child, context, read) {
355
+ try {
356
+ return await this.prerequisites.prepare(reservation, child, context, read);
357
+ }
358
+ catch (error) {
359
+ await this.ledger.appendOnce(root, context, 'child-unavailable:' + child.grantId, {
360
+ eventType: OrchestrationEventType.DelegationReconciliationFailed,
361
+ payload: {
362
+ cohortId: reservation.cohortId,
363
+ reason: 'Child ' +
364
+ child.assignmentId +
365
+ ': ' +
366
+ (error instanceof Error ? error.message : 'reconciliation unavailable'),
367
+ },
368
+ });
369
+ return false;
370
+ }
371
+ }
372
+ async childrenQualified(reservation, results, context) {
373
+ if (!reservation.children.every((child) => results.some((result) => result.childWorkItemId === child.workItemId)))
374
+ return false;
375
+ const read = await this.prerequisites.read();
376
+ return (await Promise.all(reservation.children.map((child) => this.prerequisites.check(reservation, child, context, read)))).every(Boolean);
377
+ }
292
378
  async ensureWait(reservation, context) {
293
379
  const id = reservation.parentWorkflowInstanceId;
294
380
  for (;;) {
@@ -390,7 +476,7 @@ export class DelegatedWork {
390
476
  return;
391
477
  const existing = await this.repository.load(child.workflowInstanceId);
392
478
  if (await this.childWorkTerminated(child.workItemId, existing.view)) {
393
- await this.fail(reservation, 'Delegated child work is no longer open', context);
479
+ await this.failChild(reservation, child, 'Delegated child work is no longer open', context);
394
480
  return;
395
481
  }
396
482
  const workflow = existing.view ??
@@ -404,7 +490,7 @@ export class DelegatedWork {
404
490
  // Accepted activation alone never qualifies: the workflow must complete successfully.
405
491
  if (workflow.status === WorkflowStatus.Superseded ||
406
492
  (workflow.status === WorkflowStatus.Completed && !isSuccessfulWorkflowCompletion(workflow))) {
407
- await this.fail(reservation, `Child ${child.workItemId} terminated without success`, context);
493
+ await this.failChild(reservation, child, `Child ${child.workItemId} terminated without success`, context);
408
494
  return;
409
495
  }
410
496
  if (workflow.status !== WorkflowStatus.Completed)
@@ -420,7 +506,7 @@ export class DelegatedWork {
420
506
  const satisfied = outputs.length === child.outputs.length &&
421
507
  child.outputs.every((required) => outputs.filter((output) => output.name === required.name && output.reference.workItemId === child.workItemId).length === 1);
422
508
  if (!satisfied) {
423
- await this.fail(reservation, 'Invalid qualifying output contract', context);
509
+ await this.failChild(reservation, child, 'Invalid qualifying output contract', context);
424
510
  return;
425
511
  }
426
512
  await this.ledger.appendOnce(root, context, `result:${child.grantId}`, {
@@ -428,6 +514,16 @@ export class DelegatedWork {
428
514
  payload: { cohortId: reservation.cohortId, childWorkItemId: child.workItemId, outputs },
429
515
  });
430
516
  }
517
+ async failChild(reservation, child, reason, context) {
518
+ if (!reservation.children.some((entry) => (entry.prerequisites?.length ?? 0) > 0)) {
519
+ await this.fail(reservation, reason, context);
520
+ return;
521
+ }
522
+ await this.ledger.appendOnce(reservation.parentWorkflowInstanceId, context, 'child-blocked:' + child.grantId, {
523
+ eventType: OrchestrationEventType.DelegationChildBlocked,
524
+ payload: { childWorkItemId: child.workItemId, reason },
525
+ });
526
+ }
431
527
  async childWorkTerminated(id, view) {
432
528
  if (view?.status === WorkflowStatus.Completed)
433
529
  return false;
@@ -448,7 +544,7 @@ export class DelegatedWork {
448
544
  return;
449
545
  }
450
546
  if (observed.event.causationId !== context.commandId)
451
- await this.fail(reservation, `Child ${child.workItemId} completed without required outputs`, context);
547
+ await this.failChild(reservation, child, `Child ${child.workItemId} completed without required outputs`, context);
452
548
  }
453
549
  endedRun(id) {
454
550
  return this.runHasEnded(id);
@@ -461,8 +557,8 @@ export class DelegatedWork {
461
557
  return ((await this.endedRun(reservation.runId)) &&
462
558
  (await this.deliveryAvailability(reservation.parentWorkItemId)).reason === undefined);
463
559
  }
464
- /** Join and continuation commit together, so a duplicate trigger cannot resume the parent twice. */
465
- async join(reservation, results, context) {
560
+ /** Settlement and continuation commit together; failures request assessment without a successful join. */
561
+ async join(reservation, results, context, failureReason) {
466
562
  if (!(await this.canJoin(reservation)))
467
563
  return;
468
564
  const parentId = reservation.parentWorkflowInstanceId;
@@ -482,10 +578,7 @@ export class DelegatedWork {
482
578
  throw new Error('Missing delegating activation');
483
579
  const requested = original.event.payload;
484
580
  const drafts = [
485
- delegationDraft(context, `join:${reservation.cohortId}`, {
486
- eventType: OrchestrationEventType.DelegationJoined,
487
- payload: { cohortId: reservation.cohortId, results },
488
- }, parentId),
581
+ settlementDraft(context, reservation, results, failureReason),
489
582
  delegationDraft(context, `continue:${reservation.cohortId}`, {
490
583
  eventType: OrchestrationEventType.ActivityRequested,
491
584
  payload: {
@@ -517,3 +610,24 @@ function assertReplay(prior, caller, assignments) {
517
610
  !matchesAssignments(prior, assignments))
518
611
  throw new Error('Delegation replay conflict');
519
612
  }
613
+ function assertPlanRevision(expected, actual) {
614
+ if (expected !== undefined && expected !== actual)
615
+ throw new DelegationConflictError(DelegationConflictCode.StalePlan, 'Delegation plan revision changed; inspect before submitting again');
616
+ }
617
+ function childBlocker(events, id) {
618
+ return events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationChildBlocked &&
619
+ event.payload.childWorkItemId === id
620
+ ? [event.payload.reason]
621
+ : [])[0];
622
+ }
623
+ function settlementDraft(context, reservation, results, reason) {
624
+ return delegationDraft(context, 'join:' + reservation.cohortId, reason === undefined
625
+ ? {
626
+ eventType: OrchestrationEventType.DelegationJoined,
627
+ payload: { cohortId: reservation.cohortId, results },
628
+ }
629
+ : {
630
+ eventType: OrchestrationEventType.DelegationFailed,
631
+ payload: { cohortId: reservation.cohortId, reason },
632
+ }, reservation.parentWorkflowInstanceId);
633
+ }
@@ -49,13 +49,22 @@ export declare class DelegationCommands {
49
49
  workflowInstanceId: import("../index.js").WorkflowInstanceId;
50
50
  grantId: string;
51
51
  repositoryResourceIds?: string[] | undefined;
52
+ prerequisites?: {
53
+ assignmentId: string;
54
+ output: string;
55
+ condition: "accepted-output" | "pushed-change" | "delivery-ready" | "merged-change";
56
+ cohortId?: string | undefined;
57
+ useAsBase?: boolean | undefined;
58
+ }[] | undefined;
52
59
  repository?: {
53
60
  resourceId: string;
54
61
  sourceRef: string;
55
62
  pullRequestBase: string;
56
63
  sourceRevision: string;
57
64
  } | undefined;
65
+ prerequisiteWorkItemIds?: import("../../work/index.js").WorkItemId[] | undefined;
58
66
  }[];
67
+ planRevision?: number | undefined;
59
68
  maxConcurrentRuns?: number | undefined;
60
69
  }>;
61
70
  inspect(caller: DelegationCaller, context: CommandContext): Promise<{
@@ -67,10 +76,39 @@ export declare class DelegationCommands {
67
76
  repositories?: string[] | undefined;
68
77
  } | null;
69
78
  repositories: string[];
79
+ planRevision: number;
70
80
  tree: {
71
81
  settled: boolean;
82
+ failureReason: string | undefined;
72
83
  children: {
73
84
  work: import("../../work/index.js").WorkItemView | null;
85
+ prerequisiteBlocker: string | undefined;
86
+ consumedInputs: {
87
+ childWorkItemId: import("../../work/index.js").WorkItemId;
88
+ consumed: {
89
+ name: string;
90
+ reference: {
91
+ workItemId: import("../../work/index.js").WorkItemId;
92
+ revisionId: string;
93
+ } | {
94
+ workItemId: import("../../work/index.js").WorkItemId;
95
+ resourceId: string;
96
+ repositoryResourceId: string;
97
+ revision: string;
98
+ branch: string;
99
+ pullRequestBase: string;
100
+ runId: string;
101
+ baseRevision?: string | undefined;
102
+ merged?: true | undefined;
103
+ };
104
+ }[];
105
+ repository?: {
106
+ resourceId: string;
107
+ sourceRef: string;
108
+ pullRequestBase: string;
109
+ sourceRevision: string;
110
+ } | undefined;
111
+ } | undefined;
74
112
  workflow: WorkflowInstanceView | null;
75
113
  assignmentId: string;
76
114
  objective: string;
@@ -94,12 +132,20 @@ export declare class DelegationCommands {
94
132
  workflowInstanceId: import("../index.js").WorkflowInstanceId;
95
133
  grantId: string;
96
134
  repositoryResourceIds?: string[] | undefined;
135
+ prerequisites?: {
136
+ assignmentId: string;
137
+ output: string;
138
+ condition: "accepted-output" | "pushed-change" | "delivery-ready" | "merged-change";
139
+ cohortId?: string | undefined;
140
+ useAsBase?: boolean | undefined;
141
+ }[] | undefined;
97
142
  repository?: {
98
143
  resourceId: string;
99
144
  sourceRef: string;
100
145
  pullRequestBase: string;
101
146
  sourceRevision: string;
102
147
  } | undefined;
148
+ prerequisiteWorkItemIds?: import("../../work/index.js").WorkItemId[] | undefined;
103
149
  }[];
104
150
  cohortId: string;
105
151
  parentWorkflowInstanceId: import("../index.js").WorkflowInstanceId;
@@ -110,6 +156,7 @@ export declare class DelegationCommands {
110
156
  ancestors: import("../../work/index.js").WorkItemId[];
111
157
  maxDepth: number;
112
158
  maxDescendants: number;
159
+ planRevision?: number | undefined;
113
160
  maxConcurrentRuns?: number | undefined;
114
161
  }[];
115
162
  }>;
@@ -60,17 +60,19 @@ export class DelegationCommands {
60
60
  maxDepth: policy.maxDepth,
61
61
  maxDescendants: policy.maxDescendants,
62
62
  maxConcurrentRuns: policy.maxConcurrentRuns,
63
- });
63
+ }, command.expectedPlanRevision);
64
64
  }
65
65
  async inspect(caller, context) {
66
66
  const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
67
67
  await this.authority.assertCaller(caller, parent);
68
68
  const policy = (await this.workflows.definitionFor(parent)).delegation;
69
+ const tree = await this.delegated.inspect(parent.workItemId);
69
70
  return {
70
71
  policy: policy ?? null,
71
72
  // Resource IDs an explicit repository selection may name; empty when none is authorized.
72
73
  repositories: policy === undefined ? [] : (await this.scopeFor(parent, policy, context)).permitted,
73
- tree: await this.delegated.inspect(parent.workItemId),
74
+ planRevision: tree.length,
75
+ tree,
74
76
  };
75
77
  }
76
78
  /** Effective repository scope: the parent's inherited scope bounded by parent and root policy. */