@atolis-hq/wake 0.4.103 → 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 (32) hide show
  1. package/dist/src/bootstrap/artifact-mcp.js +20 -1
  2. package/dist/src/bootstrap/version.js +1 -1
  3. package/dist/src/orchestration/application/conversation-command-reactor.js +25 -0
  4. package/dist/src/orchestration/application/delegated-work.d.ts +9 -0
  5. package/dist/src/orchestration/application/delegated-work.js +53 -20
  6. package/dist/src/orchestration/application/delegation-attention-escalations.d.ts +11 -0
  7. package/dist/src/orchestration/application/delegation-attention-escalations.js +36 -0
  8. package/dist/src/orchestration/application/delegation-attention-state.d.ts +53 -0
  9. package/dist/src/orchestration/application/delegation-attention-state.js +194 -0
  10. package/dist/src/orchestration/application/delegation-attention.d.ts +58 -0
  11. package/dist/src/orchestration/application/delegation-attention.js +206 -0
  12. package/dist/src/orchestration/application/delegation-commands.d.ts +5 -1
  13. package/dist/src/orchestration/application/delegation-commands.js +18 -1
  14. package/dist/src/orchestration/application/delegation-gate.d.ts +4 -1
  15. package/dist/src/orchestration/application/delegation-gate.js +15 -3
  16. package/dist/src/orchestration/application/orchestration-service.d.ts +16 -1
  17. package/dist/src/orchestration/application/orchestration-service.js +38 -1
  18. package/dist/src/orchestration/contracts/delegation.d.ts +63 -1
  19. package/dist/src/orchestration/contracts/delegation.js +49 -1
  20. package/dist/src/orchestration/contracts/event-decoder.js +4 -1
  21. package/dist/src/orchestration/contracts/event-factory.js +7 -1
  22. package/dist/src/orchestration/contracts/events.d.ts +15 -1
  23. package/dist/src/orchestration/contracts/events.js +3 -0
  24. package/dist/src/orchestration/contracts/views.d.ts +6 -0
  25. package/dist/src/orchestration/contracts/vocabulary.d.ts +18 -0
  26. package/dist/src/orchestration/contracts/vocabulary.js +16 -0
  27. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +1 -0
  28. package/dist/src/orchestration/domain/workflow-instance-events.js +28 -0
  29. package/dist/src/orchestration/index.d.ts +3 -3
  30. package/dist/src/orchestration/index.js +2 -2
  31. package/dist/src/surfaces/mcp/delegation.js +20 -1
  32. package/package.json +1 -1
@@ -0,0 +1,206 @@
1
+ import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
2
+ import { activationId } from '../../activities/index.js';
3
+ import { OrchestrationEventType } from '../contracts/events.js';
4
+ import { DelegationAttentionRejection, WorkflowStatus } from '../contracts/vocabulary.js';
5
+ import { nextOrdinal } from '../domain/decision-events.js';
6
+ import { escalatedTargets } from './delegation-attention-escalations.js';
7
+ import { assertReplyAllowed, assessedBlockers, attentionKeyOf, blockerOf, contextBlockerId, digest, MaxAssessmentAttempts, reject, resolutionDrafts, } from './delegation-attention-state.js';
8
+ import { delegationDraft, isSettled } from './delegation-ledger.js';
9
+ /** Durable cohort/blocker state for the parent attention protocol. */
10
+ export class DelegationAttention {
11
+ repository;
12
+ ledger;
13
+ dependencies;
14
+ constructor(repository, ledger, dependencies) {
15
+ this.repository = repository;
16
+ this.ledger = ledger;
17
+ this.dependencies = dependencies;
18
+ }
19
+ /** Unresolved reasons for the cohort: recorded child blockers plus live clarification requests. */
20
+ async blockers(reservation, events) {
21
+ const blockers = [];
22
+ for (const child of reservation.children) {
23
+ const recorded = events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationChildBlocked &&
24
+ event.payload.childWorkItemId === child.workItemId
25
+ ? [event.payload.reason]
26
+ : [])[0];
27
+ const view = recorded === undefined ? (await this.repository.load(child.workflowInstanceId)).view : null;
28
+ const blocker = blockerOf(child, recorded, view);
29
+ if (blocker !== undefined)
30
+ blockers.push(blocker);
31
+ }
32
+ return blockers;
33
+ }
34
+ /**
35
+ * Starts one coalesced assessment at the delegating stage when an unassessed reason exists.
36
+ * Join and attention share the parent's single activation: this only acts from the cohort wait.
37
+ * Callers settle fully terminal batches through the ordinary unsuccessful continuation instead.
38
+ */
39
+ async raise(reservation, context) {
40
+ const events = await this.ledger.events();
41
+ if (isSettled(events, reservation))
42
+ return;
43
+ const blockers = await this.blockers(reservation, events);
44
+ const assessed = assessedBlockers(events, reservation);
45
+ if (!blockers.some((blocker) => !assessed.has(blocker.blockerId)))
46
+ return;
47
+ if (!(await this.dependencies.canContinue(reservation)))
48
+ return;
49
+ const attentionKey = attentionKeyOf(reservation, blockers.map((blocker) => blocker.blockerId));
50
+ for (;;) {
51
+ const loaded = await this.repository.loadRequired(reservation.parentWorkflowInstanceId);
52
+ if (!this.canRequest(loaded.view, reservation))
53
+ return;
54
+ if (await this.request(reservation, loaded, { attentionKey, blockers }, context))
55
+ return;
56
+ }
57
+ }
58
+ /** Only the parked cohort wait may start an assessment; a running one coalesces new reasons. */
59
+ canRequest(view, reservation) {
60
+ return (view.status === WorkflowStatus.Waiting &&
61
+ view.delegationWait?.cohortId === reservation.cohortId &&
62
+ view.delegationAttention === undefined);
63
+ }
64
+ /** Returns false when a concurrent append won and the caller must re-read. */
65
+ async request(reservation, loaded, input, context) {
66
+ const id = reservation.parentWorkflowInstanceId;
67
+ const { events } = await this.repository.history(id);
68
+ const original = events.find((entry) => entry.event.eventType === OrchestrationEventType.ActivityRequested &&
69
+ entry.event.payload.activationId === reservation.activationId);
70
+ if (original?.event.eventType !== OrchestrationEventType.ActivityRequested)
71
+ throw new Error('Missing delegating activation');
72
+ const requested = original.event.payload;
73
+ const keyId = digest(input.attentionKey);
74
+ if (!this.dependencies.supportsAttention(requested.activity)) {
75
+ await this.ledger.appendOnce(id, context, `attention-unsupported:${keyId}`, {
76
+ eventType: OrchestrationEventType.DelegationReconciliationFailed,
77
+ payload: {
78
+ cohortId: reservation.cohortId,
79
+ reason: 'Child work needs attention but the delegating activity cannot assess it; ' +
80
+ 'an operator must inspect the blockers',
81
+ },
82
+ });
83
+ return true;
84
+ }
85
+ const ordinal = nextOrdinal(loaded.view);
86
+ const attentionActivation = activationId(`${id}:activity:${ordinal}`);
87
+ try {
88
+ await this.repository.append(id, loaded.sequence, [
89
+ delegationDraft(context, `attention:${keyId}:${ordinal}`, {
90
+ eventType: OrchestrationEventType.DelegationAttentionRequested,
91
+ payload: {
92
+ cohortId: reservation.cohortId,
93
+ attentionKey: input.attentionKey,
94
+ activationId: attentionActivation,
95
+ revision: reservation.planRevision ?? 1,
96
+ blockers: input.blockers,
97
+ },
98
+ }, id),
99
+ delegationDraft(context, `attention-activity:${keyId}:${ordinal}`, {
100
+ eventType: OrchestrationEventType.ActivityRequested,
101
+ payload: {
102
+ ...requested,
103
+ activationId: attentionActivation,
104
+ ordinal,
105
+ sessionPolicy: 'fresh',
106
+ },
107
+ }, id),
108
+ ]);
109
+ return true;
110
+ }
111
+ catch (error) {
112
+ if (error instanceof WrongExpectedSequenceError)
113
+ return false;
114
+ throw error;
115
+ }
116
+ }
117
+ /** The open attention request for a parent, with the replies already accepted. */
118
+ async current(parent) {
119
+ const attention = parent.delegationAttention;
120
+ if (attention === undefined)
121
+ return null;
122
+ const { events } = await this.repository.history(parent.workflowInstanceId);
123
+ const request = events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationAttentionRequested &&
124
+ event.payload.attentionKey === attention.attentionKey
125
+ ? [event.payload]
126
+ : [])[0];
127
+ if (request === undefined)
128
+ return null;
129
+ const responses = events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationAttentionResponded &&
130
+ event.payload.attentionKey === attention.attentionKey
131
+ ? [event.payload]
132
+ : []);
133
+ return { ...request, responses };
134
+ }
135
+ /**
136
+ * Accepts a parent reply for one context blocker. Everything Wake relies on is re-derived here;
137
+ * a restart replays an accepted reply to completion because each step is idempotent.
138
+ */
139
+ async respond(caller, reply, context) {
140
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
141
+ const attention = await this.current(parent);
142
+ const prior = assertReplyAllowed(parent, attention, caller, reply);
143
+ const reservation = (await this.ledger.reservations()).find((entry) => entry.parentWorkflowInstanceId === parent.workflowInstanceId &&
144
+ entry.cohortId === attention.cohortId);
145
+ const child = reservation?.children.find((entry) => entry.workItemId === reply.childWorkItemId);
146
+ if (reservation === undefined || child === undefined)
147
+ throw reject(DelegationAttentionRejection.UnknownBlocker, 'Unknown delegated child');
148
+ const allowed = await this.dependencies.contextWorkItems(parent);
149
+ if (reply.references.some((reference) => !allowed.has(reference.workItemId)))
150
+ throw reject(DelegationAttentionRejection.OutsideHierarchy, 'Delegation context is outside the parent hierarchy');
151
+ const childView = (await this.repository.load(child.workflowInstanceId)).view;
152
+ const stillBlocked = childView !== null && contextBlockerId(child, childView) === reply.blockerId;
153
+ if (!stillBlocked && prior === undefined)
154
+ throw reject(DelegationAttentionRejection.NotBlocked, 'The child is no longer blocked for this assignment context');
155
+ await this.dependencies.artifacts.validateInputs(parent, reply.references);
156
+ const key = digest(reply.blockerId);
157
+ await this.ledger.appendOnce(parent.workflowInstanceId, context, `response:${key}`, {
158
+ eventType: OrchestrationEventType.DelegationAttentionResponded,
159
+ payload: { cohortId: attention.cohortId, attentionKey: attention.attentionKey, ...reply },
160
+ });
161
+ await this.dependencies.artifacts.registerChild({
162
+ delegationId: `${child.grantId}:response:${key}`,
163
+ parentWorkItemId: reservation.parentWorkItemId,
164
+ childWorkItemId: child.workItemId,
165
+ childReferences: reply.references,
166
+ }, context);
167
+ if (stillBlocked)
168
+ await this.dependencies.resumeChild(child.workflowInstanceId, {
169
+ ...context,
170
+ commandId: `delegation-response:${key}`,
171
+ });
172
+ }
173
+ /** Ends the assessment and restores the unresolved wait; a pending join then proceeds. */
174
+ async resolve(parentId, attentionActivation, context, verdict = {}) {
175
+ for (;;) {
176
+ const loaded = await this.repository.loadRequired(parentId);
177
+ const attention = loaded.view.delegationAttention;
178
+ if (attention === undefined || attention.activationId !== attentionActivation)
179
+ return loaded.view;
180
+ const exhausted = verdict.failure !== undefined &&
181
+ (await this.priorFailures(parentId, attention.attentionKey)) + 1 >= MaxAssessmentAttempts;
182
+ try {
183
+ await this.repository.append(parentId, loaded.sequence, resolutionDrafts(context, parentId, attention, { ...verdict, exhausted }));
184
+ return (await this.repository.loadRequired(parentId)).view;
185
+ }
186
+ catch (error) {
187
+ if (!(error instanceof WrongExpectedSequenceError))
188
+ throw error;
189
+ }
190
+ }
191
+ }
192
+ async priorFailures(parentId, attentionKey) {
193
+ const { events } = await this.repository.history(parentId);
194
+ return events.filter(({ event }) => event.eventType === OrchestrationEventType.DelegationAttentionResolved &&
195
+ event.payload.attentionKey === attentionKey &&
196
+ event.payload.assessmentFailure !== undefined).length;
197
+ }
198
+ /**
199
+ * Children whose assignment-context blocker the parent escalated to a human and which are still
200
+ * blocked on it. A human reply on the parent is routed to exactly these, so a published question
201
+ * always has an answer path that moves the delivery without settling or joining the cohort.
202
+ */
203
+ escalatedTargets(parent) {
204
+ return escalatedTargets(this.repository, this.ledger, parent);
205
+ }
206
+ }
@@ -1,7 +1,7 @@
1
1
  import type { CommandContext } from '@atolis-hq/eventing';
2
2
  import type { WorkService } from '../../work/index.js';
3
3
  import type { DelegationAuthority } from '../contracts/delegation-ports.js';
4
- import { type DelegationCaller, type DelegationSubmission } from '../contracts/delegation.js';
4
+ import { type DelegationAttentionReply, type DelegationCaller, type DelegationSubmission } from '../contracts/delegation.js';
5
5
  import type { WorkflowInstanceView } from '../contracts/views.js';
6
6
  import type { DelegatedWork } from './delegated-work.js';
7
7
  import type { OrchestrationRepository } from './orchestration-repository.js';
@@ -67,6 +67,9 @@ export declare class DelegationCommands {
67
67
  planRevision?: number | undefined;
68
68
  maxConcurrentRuns?: number | undefined;
69
69
  }>;
70
+ /** Run-bound reply to a coalesced attention request; authority is the caller's own activation. */
71
+ respond(caller: DelegationCaller, input: DelegationAttentionReply, context: CommandContext): Promise<import("./delegation-attention-state.js").OpenAttention | null>;
72
+ private attentionView;
70
73
  inspect(caller: DelegationCaller, context: CommandContext): Promise<{
71
74
  policy: {
72
75
  workflows: string[];
@@ -77,6 +80,7 @@ export declare class DelegationCommands {
77
80
  } | null;
78
81
  repositories: string[];
79
82
  planRevision: number;
83
+ attention: import("./delegation-attention-state.js").OpenAttention | null;
80
84
  tree: {
81
85
  settled: boolean;
82
86
  failureReason: string | undefined;
@@ -1,4 +1,4 @@
1
- import { delegationSubmissionSchema, } from '../contracts/delegation.js';
1
+ import { delegationAttentionReplySchema, delegationSubmissionSchema, } from '../contracts/delegation.js';
2
2
  import { WorkflowStatus } from '../contracts/vocabulary.js';
3
3
  /** Agent inputs describe work; authority comes from the current Run and workflow. */
4
4
  export class DelegationCommands {
@@ -62,6 +62,21 @@ export class DelegationCommands {
62
62
  maxConcurrentRuns: policy.maxConcurrentRuns,
63
63
  }, command.expectedPlanRevision);
64
64
  }
65
+ /** Run-bound reply to a coalesced attention request; authority is the caller's own activation. */
66
+ async respond(caller, input, context) {
67
+ const reply = delegationAttentionReplySchema.parse(input);
68
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
69
+ await this.authority.assertCaller(caller, parent);
70
+ const availability = (await this.work.deliverySnapshot()).availability(parent.workItemId);
71
+ if (availability.reason !== undefined)
72
+ throw new Error(availability.reason);
73
+ await this.delegated.attention.respond(caller, reply, context);
74
+ return this.attentionView(caller.workflowInstanceId);
75
+ }
76
+ async attentionView(id) {
77
+ const parent = (await this.repository.loadRequired(id)).view;
78
+ return this.delegated.attention.current(parent);
79
+ }
65
80
  async inspect(caller, context) {
66
81
  const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
67
82
  await this.authority.assertCaller(caller, parent);
@@ -72,6 +87,8 @@ export class DelegationCommands {
72
87
  // Resource IDs an explicit repository selection may name; empty when none is authorized.
73
88
  repositories: policy === undefined ? [] : (await this.scopeFor(parent, policy, context)).permitted,
74
89
  planRevision: tree.length,
90
+ // The open coalesced assessment for this activation, if any; replies name its blockers.
91
+ attention: await this.delegated.attention.current(parent),
75
92
  tree,
76
93
  };
77
94
  }
@@ -15,11 +15,14 @@ export declare class DelegationGate {
15
15
  /** Commit-boundary check for one instance; batches use `filterAvailable`. */
16
16
  unavailable(view: WorkflowInstanceView): Promise<boolean>;
17
17
  allows(view: WorkflowInstanceView): boolean;
18
+ /** The attention activation is the one parent activation a fenced cohort may dispatch. */
19
+ private dispatchable;
18
20
  fenced(id: WorkflowInstanceId): Promise<boolean>;
19
21
  /** The subset of `ids` whose workflow is fenced or held, against one Work synchronisation. */
20
22
  fencedAmong(ids: readonly WorkflowInstanceId[]): Promise<ReadonlySet<WorkflowInstanceId>>;
21
23
  run<T>(id: WorkflowInstanceId, operation: () => Promise<T>): Promise<T>;
22
- outcome<T>(id: WorkflowInstanceId, activationId: ActivationId, operation: () => Promise<T>, held: () => Promise<T>, historical: (view: WorkflowInstanceView) => Promise<T>): Promise<T>;
24
+ outcome<T>(id: WorkflowInstanceId, activationId: ActivationId, operation: () => Promise<T>, held: () => Promise<T>, historical: (view: WorkflowInstanceView) => Promise<T>, attention?: () => Promise<T>): Promise<T>;
25
+ private fencedOutcome;
23
26
  /**
24
27
  * Admits the items whose workflow may advance, against one synchronisation
25
28
  * with Work however many items there are. Nothing is read when none are
@@ -28,6 +28,12 @@ export class DelegationGate {
28
28
  allows(view) {
29
29
  return view.delegationFence === undefined;
30
30
  }
31
+ /** The attention activation is the one parent activation a fenced cohort may dispatch. */
32
+ dispatchable(view) {
33
+ return (this.allows(view) ||
34
+ (view.delegationAttention !== undefined &&
35
+ view.delegationAttention.activationId === view.pendingActivation?.activationId));
36
+ }
31
37
  async fenced(id) {
32
38
  const view = (await this.repository.load(id)).view;
33
39
  return view !== null && (!this.allows(view) || (await this.unavailable(view)));
@@ -55,7 +61,7 @@ export class DelegationGate {
55
61
  throw new DelegationPendingError(id);
56
62
  return operation();
57
63
  }
58
- async outcome(id, activationId, operation, held, historical) {
64
+ async outcome(id, activationId, operation, held, historical, attention) {
59
65
  const view = (await this.repository.load(id)).view;
60
66
  if (view === null)
61
67
  return operation();
@@ -67,10 +73,16 @@ export class DelegationGate {
67
73
  return historical(view);
68
74
  if (admission?.reason !== undefined)
69
75
  throw new DelegationPendingError(id);
76
+ // An attention outcome restores the cohort wait; it never reaches ordinary routing.
77
+ if (attention !== undefined && view.delegationAttention?.activationId === activationId)
78
+ return attention();
79
+ return this.fencedOutcome(view, activationId, operation, held);
80
+ }
81
+ fencedOutcome(view, activationId, operation, held) {
70
82
  if (this.allows(view))
71
83
  return operation();
72
84
  if (view.delegationFence?.activationId !== activationId)
73
- throw new DelegationPendingError(id);
85
+ throw new DelegationPendingError(view.workflowInstanceId);
74
86
  return held();
75
87
  }
76
88
  /**
@@ -81,7 +93,7 @@ export class DelegationGate {
81
93
  async filterAvailable(items, viewOf) {
82
94
  const unfenced = items.filter((item) => {
83
95
  const view = viewOf(item);
84
- return view !== null && this.allows(view);
96
+ return view !== null && this.dispatchable(view);
85
97
  });
86
98
  if (unfenced.length === 0)
87
99
  return [];
@@ -1,5 +1,5 @@
1
1
  import type { DelegationArtifacts, DelegationAuthority, DelegationRepositories } from '../contracts/delegation-ports.js';
2
- import type { DelegationCaller, DelegationSubmission } from '../contracts/delegation.js';
2
+ import type { DelegationAttentionReply, DelegationCaller, DelegationSubmission } from '../contracts/delegation.js';
3
3
  import type { ResourceTransitionEvidence } from './resource-transition-evidence.js';
4
4
  import type { CommandContext, EventJournal, ProjectionStore } from '@atolis-hq/eventing';
5
5
  import { type ActivationId, type ActivityOutcome } from '../../activities/index.js';
@@ -18,6 +18,7 @@ export declare class OrchestrationService {
18
18
  private readonly delegationGate;
19
19
  private readonly delegatedWork;
20
20
  private readonly prerequisiteReasons;
21
+ private readonly resumeClarification;
21
22
  private readonly repository;
22
23
  private readonly deferredSignals;
23
24
  private readonly startWorkflow;
@@ -102,6 +103,7 @@ export declare class OrchestrationService {
102
103
  } | null;
103
104
  repositories: string[];
104
105
  planRevision: number;
106
+ attention: import("./delegation-attention-state.js").OpenAttention | null;
105
107
  tree: {
106
108
  settled: boolean;
107
109
  failureReason: string | undefined;
@@ -300,6 +302,19 @@ export declare class OrchestrationService {
300
302
  activationId: ActivationId;
301
303
  outcome: ActivityOutcome;
302
304
  }, context: CommandContext): Promise<WorkflowInstanceView>;
305
+ /**
306
+ * Every ending restores the cohort wait, so independent members keep running and their
307
+ * results stay joinable (a join that completed meanwhile then proceeds). A structured
308
+ * human question is also recorded as an accepted outcome, which the ordinary publication
309
+ * route delivers to a human; a failed assessment run is recorded and re-raised a bounded
310
+ * number of times. The cohort is never settled or cancelled by the assessment itself.
311
+ */
312
+ private endAttention;
313
+ /** Delegated children still blocked on a question this work item's parent escalated to a human. */
314
+ escalatedReplyTargets(workItemId: WorkItemId): Promise<WorkItemId[]>;
315
+ /** The open attention request when `activationId` is the attention activation, else null. */
316
+ openDelegationAttention(id: WorkflowInstanceId, activationId: ActivationId): Promise<import("./delegation-attention-state.js").OpenAttention | null>;
317
+ respondToDelegationAttention(caller: DelegationCaller, reply: DelegationAttentionReply, context: CommandContext): Promise<import("./delegation-attention-state.js").OpenAttention | null>;
303
318
  waitForSignal(workflowInstanceId: WorkflowInstanceId, expectation: SignalExpectation, context: CommandContext): Promise<WorkflowInstanceView>;
304
319
  acceptSignal(workflowInstanceId: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext): Promise<WorkflowInstanceView>;
305
320
  setAcceptSignalOperationCoordinator(coordinator: OperationCoordinator): void;
@@ -17,6 +17,7 @@ import { AcceptSignal } from './accept-signal.js';
17
17
  import { AdvanceWorkflow } from './advance-workflow.js';
18
18
  import { applyBuiltInConversationCommand, continuationCommandRejection, conversationCommand, } from './conversation-command.js';
19
19
  import { CoordinationClaims } from './coordination-claims.js';
20
+ import { attentionVerdict } from './delegation-attention-state.js';
20
21
  import { GroupBudgetRecorder } from './group-budget-recorder.js';
21
22
  import { workflowsByWorkItemProjection } from './orchestration-projection.js';
22
23
  import { OrchestrationRepository } from './orchestration-repository.js';
@@ -29,6 +30,7 @@ export class OrchestrationService {
29
30
  delegationGate;
30
31
  delegatedWork;
31
32
  prerequisiteReasons = (ids, snapshot) => this.delegatedWork.prerequisites.reasons(ids, snapshot);
33
+ resumeClarification = (id, context) => this.advanceWorkflow.resumeNeedsClarificationStage(id, context);
32
34
  repository;
33
35
  deferredSignals;
34
36
  startWorkflow;
@@ -43,6 +45,8 @@ export class OrchestrationService {
43
45
  journal;
44
46
  definitions;
45
47
  work;
48
+ // Composition root for the module's services; splitting it would only scatter the wiring.
49
+ // eslint-disable-next-line max-lines-per-function
46
50
  constructor(journal, work, definitions, projections, isAgentActivity, delegation) {
47
51
  this.projections = projections;
48
52
  this.journal = journal;
@@ -61,6 +65,8 @@ export class OrchestrationService {
61
65
  artifacts: dependencies?.artifacts ?? unavailableArtifacts,
62
66
  repositories: dependencies?.repositories,
63
67
  runHasEnded: dependencies?.runHasEnded ?? unavailableRunCompletion,
68
+ supportsAttention: isAgentActivity,
69
+ resumeChild: this.resumeClarification,
64
70
  });
65
71
  this.delegationCommands = new DelegationCommands(repository, work, this.startWorkflow, this.definitions, this.delegatedWork, dependencies?.authority ?? unavailableDelegationAuthority);
66
72
  this.advanceWorkflow = new AdvanceWorkflow(repository, this.startWorkflow, (command, context) => this.acceptOutcome(command, context), isAgentActivity);
@@ -125,7 +131,38 @@ export class OrchestrationService {
125
131
  return this.transitionWatchChildren(context, () => this.delegationGate.outcome(command.workflowInstanceId, command.activationId, () => this.acceptActivityOutcome.execute(command, context), async () => {
126
132
  await this.reconcileChildCompletions(context);
127
133
  return (await this.repository.loadRequired(command.workflowInstanceId)).view;
128
- }, async (view) => view));
134
+ }, async (view) => view, () => this.endAttention(command, context)));
135
+ }
136
+ /**
137
+ * Every ending restores the cohort wait, so independent members keep running and their
138
+ * results stay joinable (a join that completed meanwhile then proceeds). A structured
139
+ * human question is also recorded as an accepted outcome, which the ordinary publication
140
+ * route delivers to a human; a failed assessment run is recorded and re-raised a bounded
141
+ * number of times. The cohort is never settled or cancelled by the assessment itself.
142
+ */
143
+ async endAttention(command, context) {
144
+ await this.delegatedWork.attention.resolve(command.workflowInstanceId, command.activationId, context, attentionVerdict(command.outcome));
145
+ await this.delegatedWork.reconcile(context);
146
+ return (await this.repository.loadRequired(command.workflowInstanceId)).view;
147
+ }
148
+ /** Delegated children still blocked on a question this work item's parent escalated to a human. */
149
+ async escalatedReplyTargets(workItemId) {
150
+ const targets = [];
151
+ for (const parent of await this.advanceWorkflow.listAll())
152
+ if (parent.workItemId === workItemId)
153
+ for (const target of await this.delegatedWork.attention.escalatedTargets(parent))
154
+ targets.push(target.childWorkItemId);
155
+ return targets;
156
+ }
157
+ /** The open attention request when `activationId` is the attention activation, else null. */
158
+ async openDelegationAttention(id, activationId) {
159
+ const view = (await this.repository.load(id)).view;
160
+ if (view?.delegationAttention?.activationId !== activationId)
161
+ return null;
162
+ return this.delegatedWork.attention.current(view);
163
+ }
164
+ respondToDelegationAttention(caller, reply, context) {
165
+ return this.delegationCommands.respond(caller, reply, context);
129
166
  }
130
167
  waitForSignal(workflowInstanceId, expectation, context) {
131
168
  return this.transitionWatchChildren(context, async () => {
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { activationId } from '../../activities/index.js';
3
3
  import { workflowInstanceId } from './identifiers.js';
4
- import { type DelegationConflictCode } from './vocabulary.js';
4
+ import { type DelegationAttentionRejection, type DelegationConflictCode } from './vocabulary.js';
5
5
  export declare const delegationPrerequisiteSchema: z.ZodObject<{
6
6
  cohortId: z.ZodOptional<z.ZodString>;
7
7
  assignmentId: z.ZodString;
@@ -220,6 +220,68 @@ export declare class DelegationConflictError extends Error {
220
220
  readonly code: DelegationConflictCode;
221
221
  constructor(code: DelegationConflictCode, message: string);
222
222
  }
223
+ export declare const delegationAttentionBlockerSchema: z.ZodObject<{
224
+ blockerId: z.ZodString;
225
+ childWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
226
+ kind: z.ZodEnum<{
227
+ readonly Failed: "failed";
228
+ readonly Context: "assignment-context";
229
+ }>;
230
+ reason: z.ZodString;
231
+ }, z.core.$strict>;
232
+ export type DelegationAttentionBlocker = z.infer<typeof delegationAttentionBlockerSchema>;
233
+ /** One coalesced assessment of the unresolved reasons, keyed by cohort revision and blockers. */
234
+ export declare const delegationAttentionRequestSchema: z.ZodObject<{
235
+ cohortId: z.ZodString;
236
+ attentionKey: z.ZodString;
237
+ activationId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../activities/index.js").ActivationId, string>>;
238
+ revision: z.ZodNumber;
239
+ blockers: z.ZodArray<z.ZodObject<{
240
+ blockerId: z.ZodString;
241
+ childWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
242
+ kind: z.ZodEnum<{
243
+ readonly Failed: "failed";
244
+ readonly Context: "assignment-context";
245
+ }>;
246
+ reason: z.ZodString;
247
+ }, z.core.$strict>>;
248
+ }, z.core.$strict>;
249
+ export type DelegationAttentionRequest = z.infer<typeof delegationAttentionRequestSchema>;
250
+ /** Names the child, blocker and assignment revision; context references are exact revisions. */
251
+ export declare const delegationAttentionReplySchema: z.ZodObject<{
252
+ childWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
253
+ blockerId: z.ZodString;
254
+ expectedRevision: z.ZodNumber;
255
+ references: z.ZodArray<z.ZodObject<{
256
+ workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
257
+ revisionId: z.ZodString;
258
+ }, z.core.$strict>>;
259
+ }, z.core.$strict>;
260
+ export type DelegationAttentionReply = z.infer<typeof delegationAttentionReplySchema>;
261
+ export declare const delegationAttentionResponseSchema: z.ZodObject<{
262
+ childWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
263
+ blockerId: z.ZodString;
264
+ expectedRevision: z.ZodNumber;
265
+ references: z.ZodArray<z.ZodObject<{
266
+ workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
267
+ revisionId: z.ZodString;
268
+ }, z.core.$strict>>;
269
+ cohortId: z.ZodString;
270
+ attentionKey: z.ZodString;
271
+ }, z.core.$strict>;
272
+ export type DelegationAttentionResponse = z.infer<typeof delegationAttentionResponseSchema>;
273
+ export declare const delegationAttentionResolvedSchema: z.ZodObject<{
274
+ cohortId: z.ZodString;
275
+ attentionKey: z.ZodString;
276
+ activationId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../activities/index.js").ActivationId, string>>;
277
+ escalation: z.ZodOptional<z.ZodString>;
278
+ assessmentFailure: z.ZodOptional<z.ZodString>;
279
+ }, z.core.$strict>;
280
+ /** Rejected replies never resume work; the code names the boundary that refused them. */
281
+ export declare class DelegationAttentionError extends Error {
282
+ readonly code: DelegationAttentionRejection;
283
+ constructor(code: DelegationAttentionRejection, message: string);
284
+ }
223
285
  export declare const delegationWaitSchema: z.ZodObject<{
224
286
  cohortId: z.ZodString;
225
287
  activationId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../activities/index.js").ActivationId, string>>;
@@ -3,7 +3,7 @@ import { activationId } from '../../activities/index.js';
3
3
  import { brandedStringSchema } from '../../kernel/index.js';
4
4
  import { workItemId } from '../../work/index.js';
5
5
  import { workflowInstanceId, workflowName } from './identifiers.js';
6
- import { DelegationOutputKind, DelegationPrerequisiteCondition, } from './vocabulary.js';
6
+ import { DelegationBlockerKind, DelegationOutputKind, DelegationPrerequisiteCondition, } from './vocabulary.js';
7
7
  export const delegationPrerequisiteSchema = z
8
8
  .object({
9
9
  cohortId: z.string().min(1).optional(),
@@ -143,6 +143,54 @@ export class DelegationConflictError extends Error {
143
143
  this.name = 'DelegationConflictError';
144
144
  }
145
145
  }
146
+ export const delegationAttentionBlockerSchema = z
147
+ .object({
148
+ blockerId: z.string().min(1),
149
+ childWorkItemId: brandedStringSchema(workItemId),
150
+ kind: z.enum(DelegationBlockerKind),
151
+ reason: z.string().min(1),
152
+ })
153
+ .strict();
154
+ /** One coalesced assessment of the unresolved reasons, keyed by cohort revision and blockers. */
155
+ export const delegationAttentionRequestSchema = z
156
+ .object({
157
+ cohortId: z.string().min(1),
158
+ attentionKey: z.string().min(1),
159
+ activationId: brandedStringSchema(activationId),
160
+ revision: z.number().int().positive(),
161
+ blockers: z.array(delegationAttentionBlockerSchema).min(1),
162
+ })
163
+ .strict();
164
+ /** Names the child, blocker and assignment revision; context references are exact revisions. */
165
+ export const delegationAttentionReplySchema = z
166
+ .object({
167
+ childWorkItemId: brandedStringSchema(workItemId),
168
+ blockerId: z.string().min(1),
169
+ expectedRevision: z.number().int().positive(),
170
+ references: z.array(delegationRevisionReferenceSchema),
171
+ })
172
+ .strict();
173
+ export const delegationAttentionResponseSchema = delegationAttentionReplySchema
174
+ .extend({ cohortId: z.string().min(1), attentionKey: z.string().min(1) })
175
+ .strict();
176
+ export const delegationAttentionResolvedSchema = z
177
+ .object({
178
+ cohortId: z.string().min(1),
179
+ attentionKey: z.string().min(1),
180
+ activationId: brandedStringSchema(activationId),
181
+ escalation: z.string().min(1).optional(),
182
+ assessmentFailure: z.string().min(1).optional(),
183
+ })
184
+ .strict();
185
+ /** Rejected replies never resume work; the code names the boundary that refused them. */
186
+ export class DelegationAttentionError extends Error {
187
+ code;
188
+ constructor(code, message) {
189
+ super(message);
190
+ this.code = code;
191
+ this.name = 'DelegationAttentionError';
192
+ }
193
+ }
146
194
  export const delegationWaitSchema = z
147
195
  .object({ cohortId: z.string().min(1), activationId: brandedStringSchema(activationId) })
148
196
  .strict();
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable max-lines */
2
2
  import { z } from 'zod';
3
- import { delegationInputsSchema, delegationJoinSchema, delegationReservationSchema, delegationResultSchema, delegationWaitSchema, } from './delegation.js';
3
+ import { delegationAttentionRequestSchema, delegationAttentionResolvedSchema, delegationAttentionResponseSchema, delegationInputsSchema, delegationJoinSchema, delegationReservationSchema, delegationResultSchema, delegationWaitSchema, } from './delegation.js';
4
4
  import { eventDataSchema, eventEnvelopeSchema } from '@atolis-hq/eventing';
5
5
  import { activationId, ActivityEventType, activityName, ActivityOutcomeKind, PullRequestCheckState, PullRequestMergeability, PullRequestState, } from '../../activities/index.js';
6
6
  import { WorkspaceMode } from '../../execution/index.js';
@@ -223,6 +223,9 @@ const eventSchemas = {
223
223
  [OrchestrationEventType.DelegationPrerequisiteBlocked]: workflowEnvelope(OrchestrationEventType.DelegationPrerequisiteBlocked, z
224
224
  .object({ childWorkItemId: brandedStringSchema(workItemId), reason: z.string().min(1) })
225
225
  .strict()),
226
+ [OrchestrationEventType.DelegationAttentionRequested]: workflowEnvelope(OrchestrationEventType.DelegationAttentionRequested, delegationAttentionRequestSchema),
227
+ [OrchestrationEventType.DelegationAttentionResponded]: workflowEnvelope(OrchestrationEventType.DelegationAttentionResponded, delegationAttentionResponseSchema),
228
+ [OrchestrationEventType.DelegationAttentionResolved]: workflowEnvelope(OrchestrationEventType.DelegationAttentionResolved, delegationAttentionResolvedSchema),
226
229
  [OrchestrationEventType.DelegationFailed]: workflowEnvelope(OrchestrationEventType.DelegationFailed, z.object({ cohortId: z.string().min(1), reason: z.string().min(1) }).strict()),
227
230
  [OrchestrationEventType.DelegationReconciliationFailed]: workflowEnvelope(OrchestrationEventType.DelegationReconciliationFailed, z.object({ cohortId: z.string().min(1), reason: z.string().min(1) }).strict()),
228
231
  [OrchestrationEventType.DelegationReserved]: workflowEnvelope(OrchestrationEventType.DelegationReserved, delegationReservationSchema),
@@ -1,7 +1,7 @@
1
1
  import { createEventData } from '@atolis-hq/eventing';
2
2
  import { OrchestrationEventType, } from './events.js';
3
3
  // Exhaustive dispatch preserves the closed event-to-payload mapping.
4
- // eslint-disable-next-line complexity
4
+ // eslint-disable-next-line complexity, max-lines-per-function
5
5
  export function createOrchestrationEventData(input) {
6
6
  switch (input.eventType) {
7
7
  case OrchestrationEventType.DelegationInputsResolved:
@@ -12,6 +12,12 @@ export function createOrchestrationEventData(input) {
12
12
  case OrchestrationEventType.DelegationFailed:
13
13
  case OrchestrationEventType.DelegationReconciliationFailed:
14
14
  return createEventData(input);
15
+ case OrchestrationEventType.DelegationAttentionRequested:
16
+ return createEventData(input);
17
+ case OrchestrationEventType.DelegationAttentionResponded:
18
+ return createEventData(input);
19
+ case OrchestrationEventType.DelegationAttentionResolved:
20
+ return createEventData(input);
15
21
  case OrchestrationEventType.DelegationReserved:
16
22
  return createEventData(input);
17
23
  case OrchestrationEventType.DelegationRegistered: