@atolis-hq/wake 0.4.101 → 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 (74) 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/artifacts/application/operator-instructions-service.js +2 -2
  4. package/dist/src/bootstrap/artifact-mcp.js +3 -4
  5. package/dist/src/bootstrap/delegation-authority.js +1 -1
  6. package/dist/src/bootstrap/integration-runtime.js +1 -1
  7. package/dist/src/bootstrap/persistence-composition.js +1 -1
  8. package/dist/src/bootstrap/surface-api-delivery.d.ts +1 -1
  9. package/dist/src/bootstrap/surface-api-delivery.js +8 -4
  10. package/dist/src/bootstrap/version.js +1 -1
  11. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +2 -1
  12. package/dist/src/control-plane/application/activation-scheduler.js +2 -1
  13. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +2 -4
  14. package/dist/src/control-plane/application/advance-once-dispatch.js +6 -4
  15. package/dist/src/control-plane/domain/delivery-capacity.d.ts +2 -5
  16. package/dist/src/control-plane/domain/delivery-capacity.js +3 -4
  17. package/dist/src/control-plane/domain/open-work-policy.d.ts +2 -10
  18. package/dist/src/control-plane/domain/open-work-policy.js +2 -3
  19. package/dist/src/execution/application/run-repository.d.ts +2 -2
  20. package/dist/src/execution/application/run-repository.js +3 -3
  21. package/dist/src/integrations/application/delegation-outputs.js +41 -5
  22. package/dist/src/node_modules/@atolis-hq/eventing/dist/runtime/cached-journal-view.d.ts +9 -1
  23. package/dist/src/node_modules/@atolis-hq/eventing/dist/runtime/cached-journal-view.d.ts.map +1 -1
  24. package/dist/src/node_modules/@atolis-hq/eventing/dist/runtime/cached-journal-view.js +62 -7
  25. package/dist/src/node_modules/@atolis-hq/eventing/dist/store/event-journal.d.ts +2 -5
  26. package/dist/src/node_modules/@atolis-hq/eventing/dist/store/event-journal.d.ts.map +1 -1
  27. package/dist/src/node_modules/@atolis-hq/eventing-filesystem/dist/file-event-journal.d.ts +12 -13
  28. package/dist/src/node_modules/@atolis-hq/eventing-filesystem/dist/file-event-journal.d.ts.map +1 -1
  29. package/dist/src/node_modules/@atolis-hq/eventing-filesystem/dist/file-event-journal.js +168 -109
  30. package/dist/src/orchestration/application/deferred-signals.d.ts +4 -2
  31. package/dist/src/orchestration/application/deferred-signals.js +47 -37
  32. package/dist/src/orchestration/application/delegated-work.d.ts +48 -2
  33. package/dist/src/orchestration/application/delegated-work.js +145 -27
  34. package/dist/src/orchestration/application/delegation-commands.d.ts +48 -1
  35. package/dist/src/orchestration/application/delegation-commands.js +5 -4
  36. package/dist/src/orchestration/application/delegation-gate.d.ts +16 -7
  37. package/dist/src/orchestration/application/delegation-gate.js +62 -14
  38. package/dist/src/orchestration/application/delegation-ledger.d.ts +2 -0
  39. package/dist/src/orchestration/application/delegation-ledger.js +8 -0
  40. package/dist/src/orchestration/application/delegation-prerequisites.d.ts +28 -0
  41. package/dist/src/orchestration/application/delegation-prerequisites.js +118 -0
  42. package/dist/src/orchestration/application/delegation-reservation.js +1 -1
  43. package/dist/src/orchestration/application/delegation-wait-graph.d.ts +7 -0
  44. package/dist/src/orchestration/application/delegation-wait-graph.js +122 -0
  45. package/dist/src/orchestration/application/orchestration-repository.d.ts +5 -0
  46. package/dist/src/orchestration/application/orchestration-repository.js +3 -0
  47. package/dist/src/orchestration/application/orchestration-service.d.ts +87 -0
  48. package/dist/src/orchestration/application/orchestration-service.js +13 -7
  49. package/dist/src/orchestration/application/prerequisite-readiness.d.ts +68 -0
  50. package/dist/src/orchestration/application/prerequisite-readiness.js +217 -0
  51. package/dist/src/orchestration/contracts/delegation-ports.d.ts +2 -1
  52. package/dist/src/orchestration/contracts/delegation.d.ts +88 -0
  53. package/dist/src/orchestration/contracts/delegation.js +36 -1
  54. package/dist/src/orchestration/contracts/event-decoder.js +8 -1
  55. package/dist/src/orchestration/contracts/event-factory.js +5 -4
  56. package/dist/src/orchestration/contracts/events.d.ts +13 -1
  57. package/dist/src/orchestration/contracts/events.js +3 -0
  58. package/dist/src/orchestration/contracts/vocabulary.d.ts +27 -0
  59. package/dist/src/orchestration/contracts/vocabulary.js +25 -0
  60. package/dist/src/orchestration/domain/workflow-instance-events.js +3 -0
  61. package/dist/src/orchestration/index.d.ts +2 -2
  62. package/dist/src/orchestration/index.js +1 -1
  63. package/dist/src/surfaces/mcp/delegation.js +18 -10
  64. package/dist/src/work/application/work-index.d.ts +21 -0
  65. package/dist/src/work/application/work-index.js +73 -0
  66. package/dist/src/work/application/work-repository.d.ts +2 -2
  67. package/dist/src/work/application/work-repository.js +2 -2
  68. package/dist/src/work/application/work-service.d.ts +5 -2
  69. package/dist/src/work/application/work-service.js +5 -2
  70. package/dist/src/work/{application → domain}/delivery-availability.d.ts +4 -7
  71. package/dist/src/work/{application → domain}/delivery-availability.js +3 -3
  72. package/dist/src/work/index.d.ts +2 -1
  73. package/dist/src/work/index.js +2 -1
  74. package/package.json +2 -1
@@ -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,16 +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;
153
+ /** Commit-boundary read: observes appends from other hosts, then answers from memory. */
154
+ private deliveryAvailability;
109
155
  private canJoin;
110
- /** 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. */
111
157
  private join;
112
158
  }
@@ -2,14 +2,17 @@
2
2
  import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
3
3
  import { activationId } from '../../activities/index.js';
4
4
  import { WorkspaceMode } from '../../execution/index.js';
5
- import { readDeliveryAvailability, WorkStatus } from '../../work/index.js';
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;
@@ -202,7 +224,7 @@ export class DelegatedWork {
202
224
  return capacity;
203
225
  }
204
226
  async parentIdentity(parent) {
205
- const availability = await readDeliveryAvailability(parent.workItemId, this.work);
227
+ const availability = await this.deliveryAvailability(parent.workItemId);
206
228
  if (availability.reason !== undefined)
207
229
  throw new Error(availability.reason);
208
230
  const item = await this.work.get(parent.workItemId);
@@ -225,7 +247,7 @@ export class DelegatedWork {
225
247
  };
226
248
  }
227
249
  async assertReservable(caller, existing, reservation, limits) {
228
- const availability = await readDeliveryAvailability(reservation.parentWorkItemId, this.work);
250
+ const availability = await this.deliveryAvailability(reservation.parentWorkItemId);
229
251
  if (availability.reason !== undefined)
230
252
  throw new Error(availability.reason);
231
253
  const current = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
@@ -270,7 +292,7 @@ export class DelegatedWork {
270
292
  async reconcileReservation(artifacts, reservation, context) {
271
293
  if (isSettled(await this.ledger.events(), reservation))
272
294
  return;
273
- if ((await readDeliveryAvailability(reservation.parentWorkItemId, this.work)).reason !== undefined)
295
+ if ((await this.deliveryAvailability(reservation.parentWorkItemId)).reason !== undefined)
274
296
  return;
275
297
  const parent = (await this.repository.loadRequired(reservation.parentWorkflowInstanceId)).view;
276
298
  if (parent.status !== WorkflowStatus.Active && parent.status !== WorkflowStatus.Waiting) {
@@ -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 (;;) {
@@ -386,11 +472,11 @@ export class DelegatedWork {
386
472
  }
387
473
  /** Starts the pinned definition, then records the result only once the child qualifies. */
388
474
  async advanceChild(artifacts, root, reservation, child, context) {
389
- if ((await readDeliveryAvailability(reservation.parentWorkItemId, this.work)).reason !== undefined)
475
+ if ((await this.deliveryAvailability(reservation.parentWorkItemId)).reason !== undefined)
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,17 +544,21 @@ 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);
455
551
  }
552
+ /** Commit-boundary read: observes appends from other hosts, then answers from memory. */
553
+ async deliveryAvailability(id) {
554
+ return (await this.work.deliverySnapshot()).availability(id);
555
+ }
456
556
  async canJoin(reservation) {
457
557
  return ((await this.endedRun(reservation.runId)) &&
458
- (await readDeliveryAvailability(reservation.parentWorkItemId, this.work)).reason === undefined);
558
+ (await this.deliveryAvailability(reservation.parentWorkItemId)).reason === undefined);
459
559
  }
460
- /** Join and continuation commit together, so a duplicate trigger cannot resume the parent twice. */
461
- 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) {
462
562
  if (!(await this.canJoin(reservation)))
463
563
  return;
464
564
  const parentId = reservation.parentWorkflowInstanceId;
@@ -478,10 +578,7 @@ export class DelegatedWork {
478
578
  throw new Error('Missing delegating activation');
479
579
  const requested = original.event.payload;
480
580
  const drafts = [
481
- delegationDraft(context, `join:${reservation.cohortId}`, {
482
- eventType: OrchestrationEventType.DelegationJoined,
483
- payload: { cohortId: reservation.cohortId, results },
484
- }, parentId),
581
+ settlementDraft(context, reservation, results, failureReason),
485
582
  delegationDraft(context, `continue:${reservation.cohortId}`, {
486
583
  eventType: OrchestrationEventType.ActivityRequested,
487
584
  payload: {
@@ -513,3 +610,24 @@ function assertReplay(prior, caller, assignments) {
513
610
  !matchesAssignments(prior, assignments))
514
611
  throw new Error('Delegation replay conflict');
515
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
+ }
@@ -1,5 +1,5 @@
1
1
  import type { CommandContext } from '@atolis-hq/eventing';
2
- import { type WorkService } from '../../work/index.js';
2
+ import type { WorkService } from '../../work/index.js';
3
3
  import type { DelegationAuthority } from '../contracts/delegation-ports.js';
4
4
  import { type DelegationCaller, type DelegationSubmission } from '../contracts/delegation.js';
5
5
  import type { WorkflowInstanceView } from '../contracts/views.js';
@@ -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
  }>;
@@ -1,4 +1,3 @@
1
- import { readDeliveryAvailability } from '../../work/index.js';
2
1
  import { delegationSubmissionSchema, } from '../contracts/delegation.js';
3
2
  import { WorkflowStatus } from '../contracts/vocabulary.js';
4
3
  /** Agent inputs describe work; authority comes from the current Run and workflow. */
@@ -25,7 +24,7 @@ export class DelegationCommands {
25
24
  caller.activationId ||
26
25
  (parent.status !== WorkflowStatus.Active && parent.status !== WorkflowStatus.Waiting))
27
26
  throw new Error('Delegation requires the current active activation');
28
- const availability = await readDeliveryAvailability(parent.workItemId, this.work);
27
+ const availability = (await this.work.deliverySnapshot()).availability(parent.workItemId);
29
28
  if (availability.reason !== undefined)
30
29
  throw new Error(availability.reason);
31
30
  const policy = (await this.workflows.definitionFor(parent)).delegation;
@@ -61,17 +60,19 @@ export class DelegationCommands {
61
60
  maxDepth: policy.maxDepth,
62
61
  maxDescendants: policy.maxDescendants,
63
62
  maxConcurrentRuns: policy.maxConcurrentRuns,
64
- });
63
+ }, command.expectedPlanRevision);
65
64
  }
66
65
  async inspect(caller, context) {
67
66
  const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
68
67
  await this.authority.assertCaller(caller, parent);
69
68
  const policy = (await this.workflows.definitionFor(parent)).delegation;
69
+ const tree = await this.delegated.inspect(parent.workItemId);
70
70
  return {
71
71
  policy: policy ?? null,
72
72
  // Resource IDs an explicit repository selection may name; empty when none is authorized.
73
73
  repositories: policy === undefined ? [] : (await this.scopeFor(parent, policy, context)).permitted,
74
- tree: await this.delegated.inspect(parent.workItemId),
74
+ planRevision: tree.length,
75
+ tree,
75
76
  };
76
77
  }
77
78
  /** Effective repository scope: the parent's inherited scope bounded by parent and root policy. */
@@ -1,20 +1,29 @@
1
1
  import type { ActivationId } from '../../activities/index.js';
2
- import { type WorkService } from '../../work/index.js';
2
+ import type { DeliverySnapshot, WorkService } from '../../work/index.js';
3
3
  import type { WorkflowInstanceId } from '../contracts/identifiers.js';
4
4
  import type { WorkflowInstanceView } from '../contracts/views.js';
5
5
  import type { OrchestrationRepository } from './orchestration-repository.js';
6
+ import type { PrerequisiteAdmission } from './prerequisite-readiness.js';
6
7
  /** One admission policy for ordinary advancement while a committed cohort owns the parent. */
7
8
  export declare class DelegationGate {
8
9
  private readonly repository;
9
10
  private readonly work;
10
- constructor(repository: OrchestrationRepository, work: WorkService);
11
+ private readonly prerequisiteReasons?;
12
+ constructor(repository: OrchestrationRepository, work: WorkService, prerequisiteReasons?: ((ids: readonly string[], snapshot?: DeliverySnapshot) => Promise<ReadonlyMap<string, PrerequisiteAdmission>>) | undefined);
13
+ /** Standalone work keeps existing freeze semantics; only delegated trees and fenced parents are held. */
14
+ private heldBy;
15
+ /** Commit-boundary check for one instance; batches use `filterAvailable`. */
11
16
  unavailable(view: WorkflowInstanceView): Promise<boolean>;
12
17
  allows(view: WorkflowInstanceView): boolean;
13
18
  fenced(id: WorkflowInstanceId): Promise<boolean>;
19
+ /** The subset of `ids` whose workflow is fenced or held, against one Work synchronisation. */
20
+ fencedAmong(ids: readonly WorkflowInstanceId[]): Promise<ReadonlySet<WorkflowInstanceId>>;
14
21
  run<T>(id: WorkflowInstanceId, operation: () => Promise<T>): Promise<T>;
15
- outcome<T>(id: WorkflowInstanceId, activationId: ActivationId, operation: () => Promise<T>, held: () => Promise<T>): Promise<T>;
16
- availableInstances(): Promise<{
17
- readonly sequence: number;
18
- readonly view: WorkflowInstanceView | null;
19
- }[]>;
22
+ outcome<T>(id: WorkflowInstanceId, activationId: ActivationId, operation: () => Promise<T>, held: () => Promise<T>, historical: (view: WorkflowInstanceView) => Promise<T>): Promise<T>;
23
+ /**
24
+ * Admits the items whose workflow may advance, against one synchronisation
25
+ * with Work however many items there are. Nothing is read when none are
26
+ * unfenced, so a quiet tick costs no storage round trip.
27
+ */
28
+ filterAvailable<T>(items: readonly T[], viewOf: (item: T) => WorkflowInstanceView | null): Promise<T[]>;
20
29
  }