@atolis-hq/wake 0.4.102 → 0.4.104

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/src/activities/pr/policy.d.ts +2 -0
  2. package/dist/src/activities/pr/policy.js +9 -1
  3. package/dist/src/bootstrap/artifact-mcp.js +20 -1
  4. package/dist/src/bootstrap/surface-api-delivery.js +6 -2
  5. package/dist/src/bootstrap/version.js +1 -1
  6. package/dist/src/integrations/application/delegation-outputs.js +41 -5
  7. package/dist/src/orchestration/application/conversation-command-reactor.js +25 -0
  8. package/dist/src/orchestration/application/delegated-work.d.ts +55 -2
  9. package/dist/src/orchestration/application/delegated-work.js +170 -23
  10. package/dist/src/orchestration/application/delegation-attention-escalations.d.ts +11 -0
  11. package/dist/src/orchestration/application/delegation-attention-escalations.js +36 -0
  12. package/dist/src/orchestration/application/delegation-attention-state.d.ts +53 -0
  13. package/dist/src/orchestration/application/delegation-attention-state.js +194 -0
  14. package/dist/src/orchestration/application/delegation-attention.d.ts +58 -0
  15. package/dist/src/orchestration/application/delegation-attention.js +206 -0
  16. package/dist/src/orchestration/application/delegation-commands.d.ts +52 -1
  17. package/dist/src/orchestration/application/delegation-commands.js +22 -3
  18. package/dist/src/orchestration/application/delegation-gate.d.ts +8 -3
  19. package/dist/src/orchestration/application/delegation-gate.js +45 -11
  20. package/dist/src/orchestration/application/delegation-ledger.d.ts +2 -0
  21. package/dist/src/orchestration/application/delegation-ledger.js +8 -0
  22. package/dist/src/orchestration/application/delegation-prerequisites.d.ts +28 -0
  23. package/dist/src/orchestration/application/delegation-prerequisites.js +118 -0
  24. package/dist/src/orchestration/application/delegation-reservation.js +1 -1
  25. package/dist/src/orchestration/application/delegation-wait-graph.d.ts +7 -0
  26. package/dist/src/orchestration/application/delegation-wait-graph.js +122 -0
  27. package/dist/src/orchestration/application/orchestration-repository.d.ts +5 -0
  28. package/dist/src/orchestration/application/orchestration-repository.js +3 -0
  29. package/dist/src/orchestration/application/orchestration-service.d.ts +103 -1
  30. package/dist/src/orchestration/application/orchestration-service.js +40 -2
  31. package/dist/src/orchestration/application/prerequisite-readiness.d.ts +68 -0
  32. package/dist/src/orchestration/application/prerequisite-readiness.js +217 -0
  33. package/dist/src/orchestration/contracts/delegation-ports.d.ts +2 -1
  34. package/dist/src/orchestration/contracts/delegation.d.ts +150 -0
  35. package/dist/src/orchestration/contracts/delegation.js +84 -1
  36. package/dist/src/orchestration/contracts/event-decoder.js +11 -1
  37. package/dist/src/orchestration/contracts/event-factory.js +12 -5
  38. package/dist/src/orchestration/contracts/events.d.ts +27 -1
  39. package/dist/src/orchestration/contracts/events.js +6 -0
  40. package/dist/src/orchestration/contracts/views.d.ts +6 -0
  41. package/dist/src/orchestration/contracts/vocabulary.d.ts +45 -0
  42. package/dist/src/orchestration/contracts/vocabulary.js +41 -0
  43. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +1 -0
  44. package/dist/src/orchestration/domain/workflow-instance-events.js +31 -0
  45. package/dist/src/orchestration/index.d.ts +3 -3
  46. package/dist/src/orchestration/index.js +2 -2
  47. package/dist/src/surfaces/mcp/delegation.js +37 -10
  48. package/package.json +1 -1
@@ -0,0 +1,58 @@
1
+ import { type CommandContext } from '@atolis-hq/eventing';
2
+ import { type ActivityName } from '../../activities/index.js';
3
+ import type { DelegationArtifacts } from '../contracts/delegation-ports.js';
4
+ import type { DelegationAttentionBlocker, DelegationAttentionReply, DelegationCaller, DelegationReservation } from '../contracts/delegation.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 { type AttentionVerdict, type OpenAttention } from './delegation-attention-state.js';
9
+ import { type DelegationLedger } from './delegation-ledger.js';
10
+ import type { OrchestrationRepository } from './orchestration-repository.js';
11
+ export interface DelegationAttentionDependencies {
12
+ readonly artifacts: DelegationArtifacts;
13
+ /** True when the delegating activity can handle a typed attention activation. */
14
+ readonly supportsAttention: (activity: ActivityName) => boolean;
15
+ /** Resumes a child workflow blocked for clarification; idempotent per command id. */
16
+ readonly resumeChild: (id: WorkflowInstanceId, context: CommandContext) => Promise<WorkflowInstanceView | null>;
17
+ /** Work items whose artifacts the parent may reference (its own hierarchy). */
18
+ readonly contextWorkItems: (parent: WorkflowInstanceView) => Promise<ReadonlySet<string>>;
19
+ /** Run end and delivery availability gate every attention continuation, like the join. */
20
+ readonly canContinue: (reservation: DelegationReservation) => Promise<boolean>;
21
+ }
22
+ /** Durable cohort/blocker state for the parent attention protocol. */
23
+ export declare class DelegationAttention {
24
+ private readonly repository;
25
+ private readonly ledger;
26
+ private readonly dependencies;
27
+ constructor(repository: OrchestrationRepository, ledger: DelegationLedger, dependencies: DelegationAttentionDependencies);
28
+ /** Unresolved reasons for the cohort: recorded child blockers plus live clarification requests. */
29
+ blockers(reservation: DelegationReservation, events: readonly WorkflowOrchestrationEvent[]): Promise<DelegationAttentionBlocker[]>;
30
+ /**
31
+ * Starts one coalesced assessment at the delegating stage when an unassessed reason exists.
32
+ * Join and attention share the parent's single activation: this only acts from the cohort wait.
33
+ * Callers settle fully terminal batches through the ordinary unsuccessful continuation instead.
34
+ */
35
+ raise(reservation: DelegationReservation, context: CommandContext): Promise<void>;
36
+ /** Only the parked cohort wait may start an assessment; a running one coalesces new reasons. */
37
+ private canRequest;
38
+ /** Returns false when a concurrent append won and the caller must re-read. */
39
+ private request;
40
+ /** The open attention request for a parent, with the replies already accepted. */
41
+ current(parent: WorkflowInstanceView): Promise<OpenAttention | null>;
42
+ /**
43
+ * Accepts a parent reply for one context blocker. Everything Wake relies on is re-derived here;
44
+ * a restart replays an accepted reply to completion because each step is idempotent.
45
+ */
46
+ respond(caller: DelegationCaller, reply: DelegationAttentionReply, context: CommandContext): Promise<void>;
47
+ /** Ends the assessment and restores the unresolved wait; a pending join then proceeds. */
48
+ resolve(parentId: WorkflowInstanceId, attentionActivation: string, context: CommandContext, verdict?: AttentionVerdict): Promise<WorkflowInstanceView>;
49
+ private priorFailures;
50
+ /**
51
+ * Children whose assignment-context blocker the parent escalated to a human and which are still
52
+ * blocked on it. A human reply on the parent is routed to exactly these, so a published question
53
+ * always has an answer path that moves the delivery without settling or joining the cohort.
54
+ */
55
+ escalatedTargets(parent: WorkflowInstanceView): Promise<readonly {
56
+ readonly childWorkItemId: string;
57
+ }[]>;
58
+ }
@@ -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';
@@ -49,15 +49,27 @@ 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
  }>;
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;
61
73
  inspect(caller: DelegationCaller, context: CommandContext): Promise<{
62
74
  policy: {
63
75
  workflows: string[];
@@ -67,10 +79,40 @@ export declare class DelegationCommands {
67
79
  repositories?: string[] | undefined;
68
80
  } | null;
69
81
  repositories: string[];
82
+ planRevision: number;
83
+ attention: import("./delegation-attention-state.js").OpenAttention | null;
70
84
  tree: {
71
85
  settled: boolean;
86
+ failureReason: string | undefined;
72
87
  children: {
73
88
  work: import("../../work/index.js").WorkItemView | null;
89
+ prerequisiteBlocker: string | undefined;
90
+ consumedInputs: {
91
+ childWorkItemId: import("../../work/index.js").WorkItemId;
92
+ consumed: {
93
+ name: string;
94
+ reference: {
95
+ workItemId: import("../../work/index.js").WorkItemId;
96
+ revisionId: string;
97
+ } | {
98
+ workItemId: import("../../work/index.js").WorkItemId;
99
+ resourceId: string;
100
+ repositoryResourceId: string;
101
+ revision: string;
102
+ branch: string;
103
+ pullRequestBase: string;
104
+ runId: string;
105
+ baseRevision?: string | undefined;
106
+ merged?: true | undefined;
107
+ };
108
+ }[];
109
+ repository?: {
110
+ resourceId: string;
111
+ sourceRef: string;
112
+ pullRequestBase: string;
113
+ sourceRevision: string;
114
+ } | undefined;
115
+ } | undefined;
74
116
  workflow: WorkflowInstanceView | null;
75
117
  assignmentId: string;
76
118
  objective: string;
@@ -94,12 +136,20 @@ export declare class DelegationCommands {
94
136
  workflowInstanceId: import("../index.js").WorkflowInstanceId;
95
137
  grantId: string;
96
138
  repositoryResourceIds?: string[] | undefined;
139
+ prerequisites?: {
140
+ assignmentId: string;
141
+ output: string;
142
+ condition: "accepted-output" | "pushed-change" | "delivery-ready" | "merged-change";
143
+ cohortId?: string | undefined;
144
+ useAsBase?: boolean | undefined;
145
+ }[] | undefined;
97
146
  repository?: {
98
147
  resourceId: string;
99
148
  sourceRef: string;
100
149
  pullRequestBase: string;
101
150
  sourceRevision: string;
102
151
  } | undefined;
152
+ prerequisiteWorkItemIds?: import("../../work/index.js").WorkItemId[] | undefined;
103
153
  }[];
104
154
  cohortId: string;
105
155
  parentWorkflowInstanceId: import("../index.js").WorkflowInstanceId;
@@ -110,6 +160,7 @@ export declare class DelegationCommands {
110
160
  ancestors: import("../../work/index.js").WorkItemId[];
111
161
  maxDepth: number;
112
162
  maxDescendants: number;
163
+ planRevision?: number | undefined;
113
164
  maxConcurrentRuns?: number | undefined;
114
165
  }[];
115
166
  }>;
@@ -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 {
@@ -60,17 +60,36 @@ export class DelegationCommands {
60
60
  maxDepth: policy.maxDepth,
61
61
  maxDescendants: policy.maxDescendants,
62
62
  maxConcurrentRuns: policy.maxConcurrentRuns,
63
- });
63
+ }, command.expectedPlanRevision);
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);
64
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);
68
83
  const policy = (await this.workflows.definitionFor(parent)).delegation;
84
+ const tree = await this.delegated.inspect(parent.workItemId);
69
85
  return {
70
86
  policy: policy ?? null,
71
87
  // Resource IDs an explicit repository selection may name; empty when none is authorized.
72
88
  repositories: policy === undefined ? [] : (await this.scopeFor(parent, policy, context)).permitted,
73
- tree: await this.delegated.inspect(parent.workItemId),
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),
92
+ tree,
74
93
  };
75
94
  }
76
95
  /** Effective repository scope: the parent's inherited scope bounded by parent and root policy. */
@@ -1,23 +1,28 @@
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);
11
13
  /** Standalone work keeps existing freeze semantics; only delegated trees and fenced parents are held. */
12
14
  private heldBy;
13
15
  /** Commit-boundary check for one instance; batches use `filterAvailable`. */
14
16
  unavailable(view: WorkflowInstanceView): Promise<boolean>;
15
17
  allows(view: WorkflowInstanceView): boolean;
18
+ /** The attention activation is the one parent activation a fenced cohort may dispatch. */
19
+ private dispatchable;
16
20
  fenced(id: WorkflowInstanceId): Promise<boolean>;
17
21
  /** The subset of `ids` whose workflow is fenced or held, against one Work synchronisation. */
18
22
  fencedAmong(ids: readonly WorkflowInstanceId[]): Promise<ReadonlySet<WorkflowInstanceId>>;
19
23
  run<T>(id: WorkflowInstanceId, operation: () => Promise<T>): Promise<T>;
20
- outcome<T>(id: WorkflowInstanceId, activationId: ActivationId, operation: () => Promise<T>, held: () => 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;
21
26
  /**
22
27
  * Admits the items whose workflow may advance, against one synchronisation
23
28
  * with Work however many items there are. Nothing is read when none are
@@ -3,9 +3,11 @@ import { DelegationPendingError } from '../contracts/delegation.js';
3
3
  export class DelegationGate {
4
4
  repository;
5
5
  work;
6
- constructor(repository, work) {
6
+ prerequisiteReasons;
7
+ constructor(repository, work, prerequisiteReasons) {
7
8
  this.repository = repository;
8
9
  this.work = work;
10
+ this.prerequisiteReasons = prerequisiteReasons;
9
11
  }
10
12
  /** Standalone work keeps existing freeze semantics; only delegated trees and fenced parents are held. */
11
13
  heldBy(snapshot, view) {
@@ -18,24 +20,40 @@ export class DelegationGate {
18
20
  }
19
21
  /** Commit-boundary check for one instance; batches use `filterAvailable`. */
20
22
  async unavailable(view) {
21
- return this.heldBy(await this.work.deliverySnapshot(), view);
23
+ const snapshot = await this.work.deliverySnapshot();
24
+ return (this.heldBy(snapshot, view) ||
25
+ (await this.prerequisiteReasons?.([view.workItemId], snapshot))?.get(view.workItemId)
26
+ ?.reason !== undefined);
22
27
  }
23
28
  allows(view) {
24
29
  return view.delegationFence === undefined;
25
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
+ }
26
37
  async fenced(id) {
27
38
  const view = (await this.repository.load(id)).view;
28
39
  return view !== null && (!this.allows(view) || (await this.unavailable(view)));
29
40
  }
30
41
  /** The subset of `ids` whose workflow is fenced or held, against one Work synchronisation. */
31
42
  async fencedAmong(ids) {
32
- const loaded = await Promise.all(ids.map(async (id) => [id, (await this.repository.load(id)).view]));
33
- const views = loaded.filter((entry) => entry[1] !== null);
43
+ if (ids.length === 0)
44
+ return new Set();
45
+ const requested = new Set(ids);
46
+ const views = (await this.repository.list()).flatMap(({ view }) => view !== null && requested.has(view.workflowInstanceId)
47
+ ? [[view.workflowInstanceId, view]]
48
+ : []);
34
49
  const snapshot = views.some(([, view]) => this.allows(view))
35
50
  ? await this.work.deliverySnapshot()
36
51
  : undefined;
52
+ const reasons = await this.prerequisiteReasons?.(views.filter(([, view]) => this.allows(view)).map(([, view]) => view.workItemId), snapshot);
37
53
  return new Set(views
38
- .filter(([, view]) => !this.allows(view) || this.heldBy(snapshot, view))
54
+ .filter(([, view]) => !this.allows(view) ||
55
+ this.heldBy(snapshot, view) ||
56
+ reasons?.get(view.workItemId)?.reason !== undefined)
39
57
  .map(([id]) => id));
40
58
  }
41
59
  async run(id, operation) {
@@ -43,14 +61,28 @@ export class DelegationGate {
43
61
  throw new DelegationPendingError(id);
44
62
  return operation();
45
63
  }
46
- async outcome(id, activationId, operation, held) {
64
+ async outcome(id, activationId, operation, held, historical, attention) {
47
65
  const view = (await this.repository.load(id)).view;
48
- if (view !== null && (await this.unavailable(view)))
66
+ if (view === null)
67
+ return operation();
68
+ const snapshot = await this.work.deliverySnapshot();
69
+ if (this.heldBy(snapshot, view))
49
70
  throw new DelegationPendingError(id);
50
- if (view === null || this.allows(view))
71
+ const admission = (await this.prerequisiteReasons?.([view.workItemId]))?.get(view.workItemId);
72
+ if (admission?.abandoned === true)
73
+ return historical(view);
74
+ if (admission?.reason !== undefined)
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) {
82
+ if (this.allows(view))
51
83
  return operation();
52
84
  if (view.delegationFence?.activationId !== activationId)
53
- throw new DelegationPendingError(id);
85
+ throw new DelegationPendingError(view.workflowInstanceId);
54
86
  return held();
55
87
  }
56
88
  /**
@@ -61,11 +93,13 @@ export class DelegationGate {
61
93
  async filterAvailable(items, viewOf) {
62
94
  const unfenced = items.filter((item) => {
63
95
  const view = viewOf(item);
64
- return view !== null && this.allows(view);
96
+ return view !== null && this.dispatchable(view);
65
97
  });
66
98
  if (unfenced.length === 0)
67
99
  return [];
68
100
  const snapshot = await this.work.deliverySnapshot();
69
- return unfenced.filter((item) => !this.heldBy(snapshot, viewOf(item)));
101
+ const reasons = await this.prerequisiteReasons?.(unfenced.map((item) => viewOf(item).workItemId), snapshot);
102
+ return unfenced.filter((item) => !this.heldBy(snapshot, viewOf(item)) &&
103
+ reasons?.get(viewOf(item).workItemId)?.reason === undefined);
70
104
  }
71
105
  }
@@ -25,4 +25,6 @@ export declare function isJoined(events: readonly WorkflowOrchestrationEvent[],
25
25
  export declare function isSettled(events: readonly WorkflowOrchestrationEvent[], reservation: DelegationReservation): boolean;
26
26
  export declare function selectedResults(events: readonly WorkflowOrchestrationEvent[], reservation: DelegationReservation): readonly DelegationResult[];
27
27
  export declare function reservedEvent(events: readonly WorkflowOrchestrationEvent[], reservation: DelegationReservation): WorkflowOrchestrationEvent;
28
+ /** Terminal membership is indexed once for a reconciliation pass, independent of history size. */
29
+ export declare function unsettledReservations(events: readonly WorkflowOrchestrationEvent[]): readonly DelegationReservation[];
28
30
  export {};
@@ -77,3 +77,11 @@ export function reservedEvent(events, reservation) {
77
77
  throw new Error('Missing delegation reservation');
78
78
  return found;
79
79
  }
80
+ /** Terminal membership is indexed once for a reconciliation pass, independent of history size. */
81
+ export function unsettledReservations(events) {
82
+ const settled = new Set(events.flatMap(({ event, stream }) => event.eventType === OrchestrationEventType.DelegationJoined ||
83
+ event.eventType === OrchestrationEventType.DelegationFailed
84
+ ? [JSON.stringify([stream.id, event.payload.cohortId])]
85
+ : []));
86
+ return reservationsOf(events).filter((reservation) => !settled.has(JSON.stringify([reservation.parentWorkflowInstanceId, reservation.cohortId])));
87
+ }
@@ -0,0 +1,28 @@
1
+ import type { CommandContext } from '@atolis-hq/eventing';
2
+ import type { DeliverySnapshot, WorkService } from '../../work/index.js';
3
+ import type { DelegationArtifacts, DelegationRepositories } from '../contracts/delegation-ports.js';
4
+ import type { DelegationInputs, DelegationReservation } from '../contracts/delegation.js';
5
+ import type { DelegationLedger } from './delegation-ledger.js';
6
+ import type { OrchestrationRepository } from './orchestration-repository.js';
7
+ import { PrerequisiteReadiness, type PrerequisiteAdmission } from './prerequisite-readiness.js';
8
+ type Child = DelegationReservation['children'][number];
9
+ /** Immutable consumption receipts and live eligibility; never chooses a repair. */
10
+ export declare class DelegationPrerequisites {
11
+ private readonly repository;
12
+ private readonly ledger;
13
+ private readonly artifacts;
14
+ private readonly repositories;
15
+ private readonly work;
16
+ constructor(repository: OrchestrationRepository, ledger: DelegationLedger, artifacts: DelegationArtifacts, repositories: DelegationRepositories | undefined, work: WorkService);
17
+ inputs(id: string): Promise<DelegationInputs | undefined>;
18
+ read(workSnapshot?: DeliverySnapshot): Promise<PrerequisiteReadiness>;
19
+ reasons(ids: readonly string[], workSnapshot?: DeliverySnapshot): Promise<ReadonlyMap<string, PrerequisiteAdmission>>;
20
+ reason(id: string): Promise<string | undefined>;
21
+ prepare(reservation: DelegationReservation, child: Child, context: CommandContext, readiness?: PrerequisiteReadiness): Promise<boolean>;
22
+ private resolveBase;
23
+ private grant;
24
+ check(reservation: DelegationReservation, child: Child, context: CommandContext, readiness?: PrerequisiteReadiness): Promise<boolean>;
25
+ private block;
26
+ private diagnostic;
27
+ }
28
+ export {};