@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
@@ -3,13 +3,17 @@ 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 { DelegationAttention, } from './delegation-attention.js';
13
+ import { delegationDraft, delegationEventId, DelegationLedger, isJoined, isSettled, reservationsOf, reservedEvent, selectedResults, unsettledReservations, } from './delegation-ledger.js';
14
+ import { DelegationPrerequisites } from './delegation-prerequisites.js';
12
15
  import { assertWithinRootLimits, buildReservation, matchesAssignments, } from './delegation-reservation.js';
16
+ import { resolvePrerequisites } from './delegation-wait-graph.js';
13
17
  const defaultLimits = { maxDepth: 1, maxDescendants: 8 };
14
18
  /**
15
19
  * Durable delegation of independent child WorkItems. Reservation is the single commit point;
@@ -23,6 +27,8 @@ export class DelegatedWork {
23
27
  workflows;
24
28
  dependencies;
25
29
  ledger;
30
+ prerequisites;
31
+ attention;
26
32
  artifacts;
27
33
  repositories;
28
34
  runHasEnded;
@@ -35,6 +41,14 @@ export class DelegatedWork {
35
41
  this.dependencies = dependencies;
36
42
  this.ledger = new DelegationLedger(repository);
37
43
  this.artifacts = dependencies.artifacts;
44
+ this.attention = new DelegationAttention(repository, this.ledger, {
45
+ artifacts: dependencies.artifacts,
46
+ supportsAttention: (activity) => dependencies.supportsAttention?.(activity) ?? true,
47
+ resumeChild: (id, context) => dependencies.resumeChild?.(id, context) ?? Promise.resolve(null),
48
+ contextWorkItems: (parent) => this.contextWorkItems(parent),
49
+ canContinue: (reservation) => this.canJoin(reservation),
50
+ });
51
+ this.prerequisites = new DelegationPrerequisites(repository, this.ledger, dependencies.artifacts, dependencies.repositories, work);
38
52
  this.repositories = dependencies.repositories;
39
53
  this.runHasEnded = dependencies.runHasEnded;
40
54
  }
@@ -43,13 +57,21 @@ export class DelegatedWork {
43
57
  const root = item?.delegation?.rootWorkItemId ?? id;
44
58
  const events = await this.ledger.events();
45
59
  const reservations = reservationsOf(events).filter((entry) => entry.rootWorkItemId === root);
60
+ const read = await this.prerequisites.read();
46
61
  return Promise.all(reservations.map(async (reservation) => ({
47
62
  ...reservation,
48
63
  settled: isSettled(events, reservation),
64
+ failureReason: events.flatMap(({ event, stream }) => stream.id === reservation.parentWorkflowInstanceId &&
65
+ event.eventType === OrchestrationEventType.DelegationFailed &&
66
+ event.payload.cohortId === reservation.cohortId
67
+ ? [event.payload.reason]
68
+ : [])[0],
49
69
  children: await Promise.all(reservation.children.map(async (child) => ({
50
70
  ...child,
51
71
  work: await this.work.get(child.workItemId),
52
- workflow: (await this.repository.load(child.workflowInstanceId)).view,
72
+ prerequisiteBlocker: (await read.reason(child.workItemId)) ?? childBlocker(events, child.workItemId),
73
+ consumedInputs: read.inputs(child.workItemId),
74
+ workflow: read.workflow(child.workflowInstanceId) ?? null,
53
75
  }))),
54
76
  })));
55
77
  }
@@ -77,6 +99,9 @@ export class DelegatedWork {
77
99
  (child.repository === undefined ? [] : [child.repository.resourceId]));
78
100
  }
79
101
  async repositoryFor(workItemId) {
102
+ const inputs = await this.prerequisites.inputs(workItemId);
103
+ if (inputs?.repository !== undefined)
104
+ return inputs.repository;
80
105
  return (await this.ledger.reservations())
81
106
  .flatMap((entry) => entry.children)
82
107
  .find((child) => child.workItemId === workItemId)?.repository;
@@ -99,7 +124,7 @@ export class DelegatedWork {
99
124
  ? joined.event.payload.results
100
125
  : [];
101
126
  }
102
- async reserve(caller, cohortId, assignments, context, limits = defaultLimits) {
127
+ async reserve(caller, cohortId, assignments, context, limits = defaultLimits, expectedPlanRevision) {
103
128
  const artifacts = this.artifacts;
104
129
  const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
105
130
  const identity = await this.parentIdentity(parent);
@@ -128,6 +153,15 @@ export class DelegatedWork {
128
153
  return prior;
129
154
  }
130
155
  await this.assertReservable(caller, await this.capacityReservations(all, events), reservation, rootLimits);
156
+ assertPlanRevision(expectedPlanRevision, all.length);
157
+ reservation = { ...reservation, planRevision: all.length + 1 };
158
+ reservation = await resolvePrerequisites(reservation, all, this.ledger, this.definitions, async (target, name) => {
159
+ const view = (await this.repository.load(target.workflowInstanceId)).view;
160
+ const output = target.outputs.find((entry) => entry.name === name);
161
+ return (view !== null &&
162
+ output !== undefined &&
163
+ (await artifacts.prerequisiteOutput?.(view, output, DelegationPrerequisiteCondition.MergedChange)) != null);
164
+ });
131
165
  for (const child of reservation.children)
132
166
  await this.prepareChild(artifacts, parent, child, context);
133
167
  if (await this.commit(identity.root, sequence, reservation, context)) {
@@ -150,11 +184,8 @@ export class DelegatedWork {
150
184
  }));
151
185
  }
152
186
  async reconcile(context) {
153
- const all = await this.ledger.reservations();
154
- if (all.length === 0)
155
- return;
156
187
  const events = await this.ledger.events();
157
- const reservations = all.filter((reservation) => !isSettled(events, reservation));
188
+ const reservations = unsettledReservations(events);
158
189
  if (reservations.length === 0)
159
190
  return;
160
191
  const artifacts = this.artifacts;
@@ -229,6 +260,10 @@ export class DelegatedWork {
229
260
  if (availability.reason !== undefined)
230
261
  throw new Error(availability.reason);
231
262
  const current = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
263
+ // One unresolved cohort per parent: a second cohort cannot share the waiting parent, so
264
+ // replacements are submitted once the cohort settles and the parent is resumed.
265
+ if (current.delegationAttention !== undefined)
266
+ throw new DelegationConflictError(DelegationConflictCode.AttentionOpen, 'Submit replacement work after the cohort settles; an open attention assessment cannot start a second cohort');
232
267
  if (current.pendingActivation?.activationId !== caller.activationId ||
233
268
  current.status !== WorkflowStatus.Active)
234
269
  throw new Error('Delegation requires the current active activation');
@@ -280,14 +315,85 @@ export class DelegatedWork {
280
315
  if (!(await this.ensureWait(reservation, context)))
281
316
  return;
282
317
  const root = await this.registerChildren(artifacts, reservation, context);
318
+ await this.advanceMembers(artifacts, root, reservation, context);
319
+ // Live attention only while independent members are unfinished; a fully terminal batch takes
320
+ // the ordinary unsuccessful continuation, which already carries every blocker.
321
+ if (!this.allTerminal(await this.ledger.events(), reservation))
322
+ await this.attention.raise(reservation, context);
323
+ if (await this.settleUnusable(reservation, context))
324
+ return;
325
+ const results = selectedResults(await this.ledger.events(), reservation);
326
+ if (await this.childrenQualified(reservation, results, context))
327
+ await this.join(reservation, results, context);
328
+ }
329
+ /** Independent members keep advancing; a blocked member is skipped, never retried blindly. */
330
+ async advanceMembers(artifacts, root, reservation, context) {
331
+ const read = await this.prerequisites.read();
283
332
  for (const child of reservation.children) {
284
- if (isSettled(await this.ledger.events(), reservation))
333
+ const events = await this.ledger.events();
334
+ if (isSettled(events, reservation))
285
335
  break;
286
- await this.advanceChild(artifacts, root, reservation, child, context);
336
+ if (childBlocker(events, child.workItemId) !== undefined)
337
+ continue;
338
+ if (await this.preparePrerequisites(root, reservation, child, context, read))
339
+ await this.advanceChild(artifacts, root, reservation, child, context);
287
340
  }
288
- const results = selectedResults(await this.ledger.events(), reservation);
289
- if (reservation.children.every((c) => results.some((r) => r.childWorkItemId === c.workItemId)))
290
- await this.join(reservation, results, context);
341
+ }
342
+ async settleUnusable(reservation, context) {
343
+ const events = await this.ledger.events();
344
+ const failed = failedChildren(events, reservation);
345
+ if (failed.size === 0)
346
+ return false;
347
+ if (this.allTerminal(events, reservation)) {
348
+ if (!(await this.canJoin(reservation)))
349
+ return true;
350
+ await this.abandon(reservation, failed, context);
351
+ await this.join(reservation, [], context, 'Delegated inputs or child failed; inspect blockers and submit replacement work');
352
+ }
353
+ return true;
354
+ }
355
+ /** Every member either failed (with its dependents) or produced its selected result. */
356
+ allTerminal(events, reservation) {
357
+ const failed = failedChildren(events, reservation);
358
+ const selected = new Set(selectedResults(events, reservation).map((result) => result.childWorkItemId));
359
+ return (failed.size > 0 &&
360
+ reservation.children.every((child) => failed.has(child.workItemId) || selected.has(child.workItemId)));
361
+ }
362
+ async abandon(reservation, failed, context) {
363
+ for (const child of reservation.children) {
364
+ if (!failed.has(child.workItemId))
365
+ continue;
366
+ const view = (await this.repository.load(child.workflowInstanceId)).view;
367
+ if (view === null ||
368
+ view.status === WorkflowStatus.Completed ||
369
+ view.status === WorkflowStatus.Superseded)
370
+ continue;
371
+ await this.ledger.appendOnce(child.workflowInstanceId, context, 'abandoned:' + child.grantId, { eventType: OrchestrationEventType.InstanceSuperseded, payload: {} });
372
+ }
373
+ }
374
+ async preparePrerequisites(root, reservation, child, context, read) {
375
+ try {
376
+ return await this.prerequisites.prepare(reservation, child, context, read);
377
+ }
378
+ catch (error) {
379
+ await this.ledger.appendOnce(root, context, 'child-unavailable:' + child.grantId, {
380
+ eventType: OrchestrationEventType.DelegationReconciliationFailed,
381
+ payload: {
382
+ cohortId: reservation.cohortId,
383
+ reason: 'Child ' +
384
+ child.assignmentId +
385
+ ': ' +
386
+ (error instanceof Error ? error.message : 'reconciliation unavailable'),
387
+ },
388
+ });
389
+ return false;
390
+ }
391
+ }
392
+ async childrenQualified(reservation, results, context) {
393
+ if (!reservation.children.every((child) => results.some((result) => result.childWorkItemId === child.workItemId)))
394
+ return false;
395
+ const read = await this.prerequisites.read();
396
+ return (await Promise.all(reservation.children.map((child) => this.prerequisites.check(reservation, child, context, read)))).every(Boolean);
291
397
  }
292
398
  async ensureWait(reservation, context) {
293
399
  const id = reservation.parentWorkflowInstanceId;
@@ -390,7 +496,7 @@ export class DelegatedWork {
390
496
  return;
391
497
  const existing = await this.repository.load(child.workflowInstanceId);
392
498
  if (await this.childWorkTerminated(child.workItemId, existing.view)) {
393
- await this.fail(reservation, 'Delegated child work is no longer open', context);
499
+ await this.failChild(reservation, child, 'Delegated child work is no longer open', context);
394
500
  return;
395
501
  }
396
502
  const workflow = existing.view ??
@@ -404,7 +510,7 @@ export class DelegatedWork {
404
510
  // Accepted activation alone never qualifies: the workflow must complete successfully.
405
511
  if (workflow.status === WorkflowStatus.Superseded ||
406
512
  (workflow.status === WorkflowStatus.Completed && !isSuccessfulWorkflowCompletion(workflow))) {
407
- await this.fail(reservation, `Child ${child.workItemId} terminated without success`, context);
513
+ await this.failChild(reservation, child, `Child ${child.workItemId} terminated without success`, context);
408
514
  return;
409
515
  }
410
516
  if (workflow.status !== WorkflowStatus.Completed)
@@ -420,7 +526,7 @@ export class DelegatedWork {
420
526
  const satisfied = outputs.length === child.outputs.length &&
421
527
  child.outputs.every((required) => outputs.filter((output) => output.name === required.name && output.reference.workItemId === child.workItemId).length === 1);
422
528
  if (!satisfied) {
423
- await this.fail(reservation, 'Invalid qualifying output contract', context);
529
+ await this.failChild(reservation, child, 'Invalid qualifying output contract', context);
424
530
  return;
425
531
  }
426
532
  await this.ledger.appendOnce(root, context, `result:${child.grantId}`, {
@@ -428,6 +534,14 @@ export class DelegatedWork {
428
534
  payload: { cohortId: reservation.cohortId, childWorkItemId: child.workItemId, outputs },
429
535
  });
430
536
  }
537
+ async failChild(reservation, child, reason, context) {
538
+ // Every cohort keeps independent members running: the failure is a durable blocker the
539
+ // parent assesses, and the cohort settles unsuccessfully only once all members are terminal.
540
+ await this.ledger.appendOnce(reservation.parentWorkflowInstanceId, context, 'child-blocked:' + child.grantId, {
541
+ eventType: OrchestrationEventType.DelegationChildBlocked,
542
+ payload: { childWorkItemId: child.workItemId, reason },
543
+ });
544
+ }
431
545
  async childWorkTerminated(id, view) {
432
546
  if (view?.status === WorkflowStatus.Completed)
433
547
  return false;
@@ -448,7 +562,7 @@ export class DelegatedWork {
448
562
  return;
449
563
  }
450
564
  if (observed.event.causationId !== context.commandId)
451
- await this.fail(reservation, `Child ${child.workItemId} completed without required outputs`, context);
565
+ await this.failChild(reservation, child, `Child ${child.workItemId} completed without required outputs`, context);
452
566
  }
453
567
  endedRun(id) {
454
568
  return this.runHasEnded(id);
@@ -461,8 +575,8 @@ export class DelegatedWork {
461
575
  return ((await this.endedRun(reservation.runId)) &&
462
576
  (await this.deliveryAvailability(reservation.parentWorkItemId)).reason === undefined);
463
577
  }
464
- /** Join and continuation commit together, so a duplicate trigger cannot resume the parent twice. */
465
- async join(reservation, results, context) {
578
+ /** Settlement and continuation commit together; failures request assessment without a successful join. */
579
+ async join(reservation, results, context, failureReason) {
466
580
  if (!(await this.canJoin(reservation)))
467
581
  return;
468
582
  const parentId = reservation.parentWorkflowInstanceId;
@@ -482,10 +596,7 @@ export class DelegatedWork {
482
596
  throw new Error('Missing delegating activation');
483
597
  const requested = original.event.payload;
484
598
  const drafts = [
485
- delegationDraft(context, `join:${reservation.cohortId}`, {
486
- eventType: OrchestrationEventType.DelegationJoined,
487
- payload: { cohortId: reservation.cohortId, results },
488
- }, parentId),
599
+ settlementDraft(context, reservation, results, failureReason),
489
600
  delegationDraft(context, `continue:${reservation.cohortId}`, {
490
601
  eventType: OrchestrationEventType.ActivityRequested,
491
602
  payload: {
@@ -507,6 +618,21 @@ export class DelegatedWork {
507
618
  }
508
619
  }
509
620
  }
621
+ /** Recorded blockers plus the dependents that can no longer start. */
622
+ function failedChildren(events, reservation) {
623
+ const members = new Set(reservation.children.map((child) => child.workItemId));
624
+ const failed = new Set(events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationChildBlocked &&
625
+ members.has(event.payload.childWorkItemId)
626
+ ? [event.payload.childWorkItemId]
627
+ : []));
628
+ if (failed.size === 0)
629
+ return failed;
630
+ for (let pass = 0; pass < reservation.children.length; pass++)
631
+ for (const child of reservation.children)
632
+ if (child.prerequisiteWorkItemIds?.some((id) => failed.has(id)))
633
+ failed.add(child.workItemId);
634
+ return failed;
635
+ }
510
636
  function rootRunLimit(reservations, limits) {
511
637
  const maxConcurrentRuns = reservations[0]?.maxConcurrentRuns ?? limits.maxConcurrentRuns;
512
638
  return maxConcurrentRuns === undefined ? {} : { maxConcurrentRuns };
@@ -517,3 +643,24 @@ function assertReplay(prior, caller, assignments) {
517
643
  !matchesAssignments(prior, assignments))
518
644
  throw new Error('Delegation replay conflict');
519
645
  }
646
+ function assertPlanRevision(expected, actual) {
647
+ if (expected !== undefined && expected !== actual)
648
+ throw new DelegationConflictError(DelegationConflictCode.StalePlan, 'Delegation plan revision changed; inspect before submitting again');
649
+ }
650
+ function childBlocker(events, id) {
651
+ return events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationChildBlocked &&
652
+ event.payload.childWorkItemId === id
653
+ ? [event.payload.reason]
654
+ : [])[0];
655
+ }
656
+ function settlementDraft(context, reservation, results, reason) {
657
+ return delegationDraft(context, 'join:' + reservation.cohortId, reason === undefined
658
+ ? {
659
+ eventType: OrchestrationEventType.DelegationJoined,
660
+ payload: { cohortId: reservation.cohortId, results },
661
+ }
662
+ : {
663
+ eventType: OrchestrationEventType.DelegationFailed,
664
+ payload: { cohortId: reservation.cohortId, reason },
665
+ }, reservation.parentWorkflowInstanceId);
666
+ }
@@ -0,0 +1,11 @@
1
+ import type { WorkflowInstanceView } from '../contracts/views.js';
2
+ import type { DelegationLedger } from './delegation-ledger.js';
3
+ import type { OrchestrationRepository } from './orchestration-repository.js';
4
+ /**
5
+ * Children whose assignment-context blocker the parent escalated to a human and which are still
6
+ * blocked on it. A human reply on the parent is routed to exactly these, so a published question
7
+ * always has an answer path that moves the delivery without settling or joining the cohort.
8
+ */
9
+ export declare function escalatedTargets(repository: OrchestrationRepository, ledger: DelegationLedger, parent: WorkflowInstanceView): Promise<readonly {
10
+ readonly childWorkItemId: string;
11
+ }[]>;
@@ -0,0 +1,36 @@
1
+ import { OrchestrationEventType } from '../contracts/events.js';
2
+ import { DelegationBlockerKind } from '../contracts/vocabulary.js';
3
+ import { contextBlockerId } from './delegation-attention-state.js';
4
+ /**
5
+ * Children whose assignment-context blocker the parent escalated to a human and which are still
6
+ * blocked on it. A human reply on the parent is routed to exactly these, so a published question
7
+ * always has an answer path that moves the delivery without settling or joining the cohort.
8
+ */
9
+ export async function escalatedTargets(repository, ledger, parent) {
10
+ const cohortId = parent.delegationWait?.cohortId;
11
+ if (cohortId === undefined)
12
+ return [];
13
+ const { events } = await repository.history(parent.workflowInstanceId);
14
+ const escalated = new Set(events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationAttentionResolved &&
15
+ event.payload.cohortId === cohortId &&
16
+ event.payload.escalation !== undefined
17
+ ? [event.payload.attentionKey]
18
+ : []));
19
+ const reservation = (await ledger.reservations()).find((entry) => entry.parentWorkflowInstanceId === parent.workflowInstanceId && entry.cohortId === cohortId);
20
+ if (reservation === undefined || escalated.size === 0)
21
+ return [];
22
+ const targets = new Set();
23
+ const asked = events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationAttentionRequested &&
24
+ escalated.has(event.payload.attentionKey)
25
+ ? event.payload.blockers.filter((blocker) => blocker.kind === DelegationBlockerKind.Context)
26
+ : []);
27
+ for (const blocker of asked) {
28
+ const child = reservation.children.find((entry) => entry.workItemId === blocker.childWorkItemId);
29
+ if (child === undefined)
30
+ continue;
31
+ const view = (await repository.load(child.workflowInstanceId)).view;
32
+ if (view !== null && contextBlockerId(child, view) === blocker.blockerId)
33
+ targets.add(child.workItemId);
34
+ }
35
+ return [...targets].map((childWorkItemId) => ({ childWorkItemId }));
36
+ }
@@ -0,0 +1,53 @@
1
+ import type { CommandContext } from '@atolis-hq/eventing';
2
+ import { type ActivityOutcome } from '../../activities/index.js';
3
+ import { DelegationAttentionError, type DelegationAttentionBlocker, type DelegationAttentionReply, type DelegationAttentionRequest, type DelegationAttentionResponse, type DelegationCaller, type DelegationReservation } from '../contracts/delegation.js';
4
+ import type { WorkflowOrchestrationEventData } from '../contracts/events.js';
5
+ import { type WorkflowOrchestrationEvent } from '../contracts/events.js';
6
+ import type { WorkflowInstanceId } from '../contracts/identifiers.js';
7
+ import type { WorkflowInstanceView } from '../contracts/views.js';
8
+ import { DelegationAttentionRejection } from '../contracts/vocabulary.js';
9
+ type Child = DelegationReservation['children'][number];
10
+ export type OpenAttention = DelegationAttentionRequest & {
11
+ readonly responses: readonly DelegationAttentionResponse[];
12
+ };
13
+ export declare function digest(value: string): string;
14
+ export declare const failedBlockerId: (child: Child) => string;
15
+ /** Only a child blocked on an agent clarification (never a human gate) is answerable. */
16
+ export declare function contextBlockerId(child: Child, view: WorkflowInstanceView): string | undefined;
17
+ /**
18
+ * A child parked by its own routing: blocked (for example retries exhausted) or waiting on a
19
+ * human route after a failed outcome. Identified by the activation it is parked on.
20
+ */
21
+ export declare function parkedBlockerId(child: Child, view: WorkflowInstanceView): string | undefined;
22
+ /** The unresolved reason for one member, from its recorded blocker or its live workflow state. */
23
+ export declare function blockerOf(child: Child, recorded: string | undefined, view: WorkflowInstanceView | null): DelegationAttentionBlocker | undefined;
24
+ export declare const MaxAssessmentAttempts = 3;
25
+ /**
26
+ * A structured blocked/needs-clarification result, or a deliberate `FAILED` the agent reports
27
+ * itself, is a human-visible escalation. A failed, rejected or infrastructure-blocked run (runner
28
+ * failure, authentication, ambiguous or unverified completion) is only a failed assessment: it
29
+ * must never cancel or settle the cohort.
30
+ */
31
+ export declare function attentionVerdict(outcome: ActivityOutcome): AttentionVerdict;
32
+ /** How the parent's assessment ended; only a human question or a failed run is more than `done`. */
33
+ export interface AttentionVerdict {
34
+ /** The batched human question, published as an ordinary accepted agent outcome. */
35
+ readonly escalation?: string;
36
+ /** The assessment run itself failed (runner, transport or invalid result). */
37
+ readonly failure?: string;
38
+ /** Set by the ledger when this failure used the last allowed assessment attempt. */
39
+ readonly exhausted?: boolean;
40
+ readonly outcome?: ActivityOutcome;
41
+ }
42
+ /** Resolution never settles the cohort: it restores the wait, with the outcome when it asks a human. */
43
+ export declare function resolutionDrafts(context: CommandContext, parentId: WorkflowInstanceId, attention: NonNullable<WorkflowInstanceView['delegationAttention']>, verdict: AttentionVerdict): WorkflowOrchestrationEventData[];
44
+ /** Blockers already put to a parent assessment; each is raised once, never polled. */
45
+ export declare function assessedBlockers(events: readonly WorkflowOrchestrationEvent[], reservation: DelegationReservation): ReadonlySet<string>;
46
+ export declare function attentionKeyOf(reservation: DelegationReservation, blockerIds: readonly string[]): string;
47
+ export declare function reject(code: DelegationAttentionRejection, message: string): DelegationAttentionError;
48
+ /**
49
+ * Every boundary Wake relies on before accepting a reply: the Run-bound activation, the exact
50
+ * blocker and its kind, and the assignment revision. Returns the earlier identical reply, if any.
51
+ */
52
+ export declare function assertReplyAllowed(parent: WorkflowInstanceView, attention: OpenAttention | null, caller: DelegationCaller, reply: DelegationAttentionReply): DelegationAttentionResponse | undefined;
53
+ export {};
@@ -0,0 +1,194 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { ActivityOutcomeKind } from '../../activities/index.js';
4
+ import { DelegationAttentionError, } from '../contracts/delegation.js';
5
+ import { OrchestrationEventType } from '../contracts/events.js';
6
+ import { DelegationAttentionRejection, DelegationBlockerKind, WorkflowStatus, } from '../contracts/vocabulary.js';
7
+ import { isNeedsClarificationResumeEligible } from '../domain/interpreter.js';
8
+ import { delegationDraft } from './delegation-ledger.js';
9
+ export function digest(value) {
10
+ return createHash('sha256').update(value).digest('hex').slice(0, 16);
11
+ }
12
+ export const failedBlockerId = (child) => `${child.grantId}:failed`;
13
+ /** Only a child blocked on an agent clarification (never a human gate) is answerable. */
14
+ export function contextBlockerId(child, view) {
15
+ if (view.status !== WorkflowStatus.Blocked || !isNeedsClarificationResumeEligible(view))
16
+ return undefined;
17
+ const pending = view.pendingActivation;
18
+ return pending === undefined ? undefined : `${child.grantId}:context:${pending.activationId}`;
19
+ }
20
+ /**
21
+ * A child parked by its own routing: blocked (for example retries exhausted) or waiting on a
22
+ * human route after a failed outcome. Identified by the activation it is parked on.
23
+ */
24
+ export function parkedBlockerId(child, view) {
25
+ const pending = view.pendingActivation;
26
+ if (pending === undefined)
27
+ return undefined;
28
+ const parked = view.status === WorkflowStatus.Blocked ||
29
+ (view.status === WorkflowStatus.Waiting &&
30
+ view.waitingFor !== undefined &&
31
+ view.lastOutcome?.kind === ActivityOutcomeKind.Failed);
32
+ return parked ? `${child.grantId}:parked:${pending.activationId}` : undefined;
33
+ }
34
+ /** The unresolved reason for one member, from its recorded blocker or its live workflow state. */
35
+ export function blockerOf(child, recorded, view) {
36
+ const base = { childWorkItemId: child.workItemId };
37
+ if (recorded !== undefined)
38
+ return {
39
+ ...base,
40
+ blockerId: failedBlockerId(child),
41
+ kind: DelegationBlockerKind.Failed,
42
+ reason: recorded,
43
+ };
44
+ if (view === null)
45
+ return undefined;
46
+ const context = contextBlockerId(child, view);
47
+ if (context !== undefined)
48
+ return {
49
+ ...base,
50
+ blockerId: context,
51
+ kind: DelegationBlockerKind.Context,
52
+ reason: view.blockReason ?? 'Child needs assignment clarification',
53
+ };
54
+ const parked = parkedBlockerId(child, view);
55
+ return parked === undefined
56
+ ? undefined
57
+ : {
58
+ ...base,
59
+ blockerId: parked,
60
+ kind: DelegationBlockerKind.Failed,
61
+ reason: view.blockReason ?? 'Child is parked after a failed outcome',
62
+ };
63
+ }
64
+ export const MaxAssessmentAttempts = 3;
65
+ const structuredBlockSchema = z
66
+ .object({
67
+ status: z.string().min(1),
68
+ message: z.string().optional(),
69
+ question: z.string().optional(),
70
+ unverifiedCompletionReason: z.string().optional(),
71
+ })
72
+ .passthrough();
73
+ const failureDataSchema = z
74
+ .object({ reason: z.string().optional(), message: z.string().optional() })
75
+ .passthrough();
76
+ /**
77
+ * A structured blocked/needs-clarification result, or a deliberate `FAILED` the agent reports
78
+ * itself, is a human-visible escalation. A failed, rejected or infrastructure-blocked run (runner
79
+ * failure, authentication, ambiguous or unverified completion) is only a failed assessment: it
80
+ * must never cancel or settle the cohort.
81
+ */
82
+ export function attentionVerdict(outcome) {
83
+ if (outcome.kind === ActivityOutcomeKind.Done)
84
+ return {};
85
+ const question = humanQuestion(outcome);
86
+ return question === undefined
87
+ ? { failure: runFailure(outcome) }
88
+ : { escalation: question, outcome };
89
+ }
90
+ /** The agent's own structured block or failure, unless the run could not verify completion. */
91
+ function humanQuestion(outcome) {
92
+ if (outcome.kind !== ActivityOutcomeKind.Blocked && outcome.kind !== ActivityOutcomeKind.Failed)
93
+ return undefined;
94
+ const parsed = structuredBlockSchema.safeParse(outcome.data);
95
+ if (!parsed.success || parsed.data.unverifiedCompletionReason !== undefined)
96
+ return undefined;
97
+ return parsed.data.question ?? parsed.data.message ?? parsed.data.status;
98
+ }
99
+ function runFailure(outcome) {
100
+ const structured = structuredBlockSchema.safeParse(outcome.data);
101
+ if (structured.success && structured.data.unverifiedCompletionReason !== undefined)
102
+ return structured.data.unverifiedCompletionReason;
103
+ const detail = failureDataSchema.safeParse(outcome.data);
104
+ return (detail.success ? (detail.data.reason ?? detail.data.message) : undefined) ?? outcome.kind;
105
+ }
106
+ /** Resolution never settles the cohort: it restores the wait, with the outcome when it asks a human. */
107
+ export function resolutionDrafts(context, parentId, attention, verdict) {
108
+ const drafts = [];
109
+ if (verdict.escalation !== undefined && verdict.outcome !== undefined)
110
+ drafts.push(delegationDraft(context, `attention-outcome:${attention.activationId}`, {
111
+ eventType: OrchestrationEventType.ActivityOutcomeAccepted,
112
+ payload: { activationId: attention.activationId, outcome: verdict.outcome },
113
+ }, parentId));
114
+ drafts.push(delegationDraft(context, `attention-resolved:${attention.activationId}`, {
115
+ eventType: OrchestrationEventType.DelegationAttentionResolved,
116
+ payload: {
117
+ cohortId: attention.cohortId,
118
+ attentionKey: attention.attentionKey,
119
+ activationId: attention.activationId,
120
+ ...(verdict.escalation === undefined ? {} : { escalation: verdict.escalation }),
121
+ ...(verdict.failure === undefined ? {} : { assessmentFailure: verdict.failure }),
122
+ },
123
+ }, parentId));
124
+ if (verdict.failure !== undefined)
125
+ drafts.push(delegationDraft(context, `attention-failed:${attention.activationId}`, {
126
+ eventType: OrchestrationEventType.DelegationReconciliationFailed,
127
+ payload: {
128
+ cohortId: attention.cohortId,
129
+ reason: `Parent attention assessment failed (${verdict.failure}); the cohort is unchanged`,
130
+ },
131
+ }, parentId));
132
+ // The last allowed retry leaves one inspectable operator escalation, not a quiet stop.
133
+ if (verdict.failure !== undefined && verdict.exhausted === true)
134
+ drafts.push(delegationDraft(context, `attention-exhausted:${digest(attention.attentionKey)}`, {
135
+ eventType: OrchestrationEventType.DelegationReconciliationFailed,
136
+ payload: {
137
+ cohortId: attention.cohortId,
138
+ reason: `Parent attention assessment failed ${MaxAssessmentAttempts} times (${verdict.failure}); an operator must inspect the blockers`,
139
+ },
140
+ }, parentId));
141
+ return drafts;
142
+ }
143
+ /** Blockers already put to a parent assessment; each is raised once, never polled. */
144
+ export function assessedBlockers(events, reservation) {
145
+ const ours = events.filter(({ stream, event }) => stream.id === reservation.parentWorkflowInstanceId &&
146
+ 'cohortId' in event.payload &&
147
+ event.payload.cohortId === reservation.cohortId);
148
+ // A failed assessment run leaves its blockers unassessed so a later pass re-raises them, but
149
+ // only a bounded number of times: repeated failures stay visible as diagnostics, never a loop.
150
+ const failures = new Map();
151
+ const resolved = new Set();
152
+ for (const { event } of ours) {
153
+ if (event.eventType !== OrchestrationEventType.DelegationAttentionResolved)
154
+ continue;
155
+ const key = event.payload.attentionKey;
156
+ if (event.payload.assessmentFailure === undefined)
157
+ resolved.add(key);
158
+ else {
159
+ failures.set(key, (failures.get(key) ?? 0) + 1);
160
+ if ((failures.get(key) ?? 0) >= MaxAssessmentAttempts)
161
+ resolved.add(key);
162
+ }
163
+ }
164
+ return new Set(ours.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationAttentionRequested &&
165
+ resolved.has(event.payload.attentionKey)
166
+ ? event.payload.blockers.map((blocker) => blocker.blockerId)
167
+ : []));
168
+ }
169
+ export function attentionKeyOf(reservation, blockerIds) {
170
+ return `${reservation.cohortId}@${reservation.planRevision ?? 1}:${[...blockerIds].sort().join(',')}`;
171
+ }
172
+ export function reject(code, message) {
173
+ return new DelegationAttentionError(code, message);
174
+ }
175
+ /**
176
+ * Every boundary Wake relies on before accepting a reply: the Run-bound activation, the exact
177
+ * blocker and its kind, and the assignment revision. Returns the earlier identical reply, if any.
178
+ */
179
+ export function assertReplyAllowed(parent, attention, caller, reply) {
180
+ if (attention === null || parent.delegationAttention?.activationId !== caller.activationId)
181
+ throw reject(DelegationAttentionRejection.NoAttention, 'No parent attention is open for this activation');
182
+ const blocker = attention.blockers.find((entry) => entry.blockerId === reply.blockerId && entry.childWorkItemId === reply.childWorkItemId);
183
+ if (blocker === undefined)
184
+ throw reject(DelegationAttentionRejection.UnknownBlocker, 'The reply names a child or blocker outside this attention request');
185
+ // Terminal failures and human-only gates are never answered through this channel.
186
+ if (blocker.kind !== DelegationBlockerKind.Context)
187
+ throw reject(DelegationAttentionRejection.NotAnswerable, 'Only an assignment-context blocker accepts a reply; use follow-up work or escalate');
188
+ if (reply.expectedRevision !== attention.revision)
189
+ throw reject(DelegationAttentionRejection.StaleRevision, 'The assignment revision changed; inspect before replying');
190
+ const prior = attention.responses.find((entry) => entry.blockerId === reply.blockerId);
191
+ if (prior !== undefined && JSON.stringify(prior.references) !== JSON.stringify(reply.references))
192
+ throw reject(DelegationAttentionRejection.Duplicate, 'This blocker already has a different accepted reply');
193
+ return prior;
194
+ }