@atolis-hq/wake 0.4.103 → 0.4.105

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 (95) hide show
  1. package/dist/src/activities/agent/agent-activity.js +3 -0
  2. package/dist/src/activities/contracts/activity.d.ts +16 -0
  3. package/dist/src/bootstrap/artifact-mcp.js +20 -1
  4. package/dist/src/bootstrap/config/root-schema.d.ts +16 -0
  5. package/dist/src/bootstrap/delegation-authority.js +17 -0
  6. package/dist/src/bootstrap/surface-api-delivery.js +25 -0
  7. package/dist/src/bootstrap/version.js +1 -1
  8. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +3 -1
  9. package/dist/src/control-plane/application/advance-once-dispatch.js +4 -2
  10. package/dist/src/execution/application/candidate-workspaces.d.ts +13 -0
  11. package/dist/src/execution/application/candidate-workspaces.js +75 -0
  12. package/dist/src/execution/application/execution-service.js +27 -11
  13. package/dist/src/execution/application/run-lifecycle.js +1 -0
  14. package/dist/src/execution/contracts/candidate.d.ts +31 -0
  15. package/dist/src/execution/contracts/candidate.js +40 -0
  16. package/dist/src/execution/contracts/commands.d.ts +2 -0
  17. package/dist/src/execution/contracts/events.d.ts +11 -0
  18. package/dist/src/execution/contracts/events.js +2 -0
  19. package/dist/src/execution/contracts/repository-assignment.d.ts +5 -0
  20. package/dist/src/execution/contracts/repository-assignment.js +8 -0
  21. package/dist/src/execution/contracts/views.d.ts +2 -0
  22. package/dist/src/execution/contracts/vocabulary.d.ts +5 -0
  23. package/dist/src/execution/contracts/vocabulary.js +4 -0
  24. package/dist/src/execution/contracts/workspace.d.ts +6 -0
  25. package/dist/src/execution/index.d.ts +1 -0
  26. package/dist/src/execution/index.js +1 -0
  27. package/dist/src/execution/infrastructure/workspace/git-source.d.ts +2 -2
  28. package/dist/src/execution/infrastructure/workspace/git-source.js +18 -1
  29. package/dist/src/execution/infrastructure/workspace/git-workspace.d.ts +2 -4
  30. package/dist/src/execution/infrastructure/workspace/git-workspace.js +12 -1
  31. package/dist/src/orchestration/application/conversation-command-reactor.js +25 -0
  32. package/dist/src/orchestration/application/delegated-work.d.ts +14 -0
  33. package/dist/src/orchestration/application/delegated-work.js +63 -20
  34. package/dist/src/orchestration/application/delegation-attention-escalations.d.ts +11 -0
  35. package/dist/src/orchestration/application/delegation-attention-escalations.js +36 -0
  36. package/dist/src/orchestration/application/delegation-attention-state.d.ts +53 -0
  37. package/dist/src/orchestration/application/delegation-attention-state.js +194 -0
  38. package/dist/src/orchestration/application/delegation-attention.d.ts +58 -0
  39. package/dist/src/orchestration/application/delegation-attention.js +206 -0
  40. package/dist/src/orchestration/application/delegation-commands.d.ts +18 -1
  41. package/dist/src/orchestration/application/delegation-commands.js +18 -1
  42. package/dist/src/orchestration/application/delegation-gate.d.ts +4 -1
  43. package/dist/src/orchestration/application/delegation-gate.js +15 -3
  44. package/dist/src/orchestration/application/delivery-coordinator.d.ts +279 -0
  45. package/dist/src/orchestration/application/delivery-coordinator.js +213 -0
  46. package/dist/src/orchestration/application/delivery-facts-reader.d.ts +9 -0
  47. package/dist/src/orchestration/application/delivery-facts-reader.js +46 -0
  48. package/dist/src/orchestration/application/delivery-preparation.d.ts +15 -0
  49. package/dist/src/orchestration/application/delivery-preparation.js +100 -0
  50. package/dist/src/orchestration/application/delivery-sources.d.ts +10 -0
  51. package/dist/src/orchestration/application/delivery-sources.js +41 -0
  52. package/dist/src/orchestration/application/orchestration-repository.d.ts +3 -1
  53. package/dist/src/orchestration/application/orchestration-repository.js +10 -1
  54. package/dist/src/orchestration/application/orchestration-service.d.ts +284 -1
  55. package/dist/src/orchestration/application/orchestration-service.js +71 -5
  56. package/dist/src/orchestration/contracts/config.d.ts +16 -0
  57. package/dist/src/orchestration/contracts/config.js +7 -1
  58. package/dist/src/orchestration/contracts/delegation-ports.d.ts +4 -0
  59. package/dist/src/orchestration/contracts/delegation.d.ts +76 -2
  60. package/dist/src/orchestration/contracts/delegation.js +54 -1
  61. package/dist/src/orchestration/contracts/delivery-ports.d.ts +9 -0
  62. package/dist/src/orchestration/contracts/delivery-ports.js +1 -0
  63. package/dist/src/orchestration/contracts/delivery.d.ts +252 -0
  64. package/dist/src/orchestration/contracts/delivery.js +134 -0
  65. package/dist/src/orchestration/contracts/event-decoder.js +17 -2
  66. package/dist/src/orchestration/contracts/event-factory.js +13 -1
  67. package/dist/src/orchestration/contracts/events.d.ts +23 -1
  68. package/dist/src/orchestration/contracts/events.js +6 -0
  69. package/dist/src/orchestration/contracts/views.d.ts +9 -0
  70. package/dist/src/orchestration/contracts/vocabulary.d.ts +65 -0
  71. package/dist/src/orchestration/contracts/vocabulary.js +59 -0
  72. package/dist/src/orchestration/domain/compiler.js +2 -0
  73. package/dist/src/orchestration/domain/delivery-candidate.d.ts +9 -0
  74. package/dist/src/orchestration/domain/delivery-candidate.js +92 -0
  75. package/dist/src/orchestration/domain/delivery-facts.d.ts +83 -0
  76. package/dist/src/orchestration/domain/delivery-facts.js +34 -0
  77. package/dist/src/orchestration/domain/delivery-qa.d.ts +32 -0
  78. package/dist/src/orchestration/domain/delivery-qa.js +77 -0
  79. package/dist/src/orchestration/domain/delivery-replacement.d.ts +9 -0
  80. package/dist/src/orchestration/domain/delivery-replacement.js +54 -0
  81. package/dist/src/orchestration/domain/delivery-selection.d.ts +17 -0
  82. package/dist/src/orchestration/domain/delivery-selection.js +132 -0
  83. package/dist/src/orchestration/domain/delivery-workflow-policy.d.ts +4 -0
  84. package/dist/src/orchestration/domain/delivery-workflow-policy.js +13 -0
  85. package/dist/src/orchestration/domain/operator-retry-policy.js +24 -13
  86. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +2 -0
  87. package/dist/src/orchestration/domain/workflow-instance-events.js +39 -0
  88. package/dist/src/orchestration/index.d.ts +5 -3
  89. package/dist/src/orchestration/index.js +3 -2
  90. package/dist/src/surfaces/api/contracts/work.d.ts +16 -0
  91. package/dist/src/surfaces/mcp/delegation.js +51 -1
  92. package/dist/src/surfaces/web-assets/assets/index-BfhxlN_h.js +1192 -0
  93. package/dist/src/surfaces/web-assets/index.html +1 -1
  94. package/package.json +1 -1
  95. package/dist/src/surfaces/web-assets/assets/index-C5R-aWzH.js +0 -1192
@@ -3,6 +3,8 @@ import { mkdtemp, rm } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { promisify } from 'node:util';
6
+ import { RepositorySourceError, } from '../../contracts/repository-assignment.js';
7
+ import { RepositorySourceFailure } from '../../contracts/vocabulary.js';
6
8
  const exec = promisify(execFile);
7
9
  /** Fetching into an empty repository proves availability in the selected source. */
8
10
  export async function resolveGitSource(resolver, request) {
@@ -10,6 +12,9 @@ export async function resolveGitSource(resolver, request) {
10
12
  const locator = await resolver.cloneLocator(request.resourceId, signal);
11
13
  const path = await mkdtemp(join(tmpdir(), 'wake-source-'));
12
14
  try {
15
+ if (request.sourceRevision === undefined &&
16
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(request.sourceRef))
17
+ await assertRemoteRef(locator, request, signal);
13
18
  await exec('git', ['init', '--bare', path], { signal });
14
19
  await exec('git', [
15
20
  '-C',
@@ -27,9 +32,21 @@ export async function resolveGitSource(resolver, request) {
27
32
  return { ...request, sourceRevision: revision };
28
33
  }
29
34
  catch (error) {
30
- throw new Error(`Repository ${request.resourceId} source ${request.sourceRevision ?? request.sourceRef} is unavailable; publish the source to the selected repository`, { cause: error });
35
+ if (error instanceof RepositorySourceError)
36
+ throw error;
37
+ throw new RepositorySourceError(RepositorySourceFailure.FetchFailed, `Repository ${request.resourceId} source ${request.sourceRevision ?? request.sourceRef} is unavailable: fetch failed; verify connectivity and permissions, and publish the source to the selected repository if missing`, { cause: error });
31
38
  }
32
39
  finally {
33
40
  await rm(path, { recursive: true, force: true });
34
41
  }
35
42
  }
43
+ async function assertRemoteRef(locator, request, signal) {
44
+ try {
45
+ await exec('git', ['ls-remote', '--exit-code', '--', locator, request.sourceRef], { signal });
46
+ }
47
+ catch (error) {
48
+ if (error instanceof Error && 'code' in error && error.code === 2)
49
+ throw new RepositorySourceError(RepositorySourceFailure.RefUnavailable, `Repository ${request.resourceId} source ${request.sourceRef} is unavailable; remote ref is missing`, { cause: error });
50
+ throw error;
51
+ }
52
+ }
@@ -1,10 +1,8 @@
1
1
  import { type RepositoryAssignment } from '../../contracts/repository-assignment.js';
2
2
  import type { RunView } from '../../contracts/views.js';
3
- import type { WorkspaceLockProvider, WorkspaceProvider, WorkspaceRecovery, WorkspaceRecoveryOptions, WorkspaceRecoveryResult, WorkspaceRequest } from '../../contracts/workspace.js';
3
+ import type { RepositoryCloneResolver, WorkspaceLockProvider, WorkspaceProvider, WorkspaceRecovery, WorkspaceRecoveryOptions, WorkspaceRecoveryResult, WorkspaceRequest } from '../../contracts/workspace.js';
4
4
  import { type WorkspacePrepareHook } from './prepare-workspace.js';
5
- export interface RepositoryCloneResolver {
6
- cloneLocator(resourceId: string, signal: AbortSignal): Promise<string>;
7
- }
5
+ export type { RepositoryCloneResolver } from '../../contracts/workspace.js';
8
6
  export type GitRunner = (arguments_: readonly string[], signal: AbortSignal) => Promise<string | void>;
9
7
  export interface WorkspaceRecoveryFileSystem {
10
8
  remove(path: string): Promise<void>;
@@ -5,6 +5,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:pat
5
5
  import { isDeepStrictEqual, promisify } from 'node:util';
6
6
  import { repositoryAssignmentSchema, } from '../../contracts/repository-assignment.js';
7
7
  import { isActiveRunStatus, RunStatus, WorkspaceMode } from '../../contracts/vocabulary.js';
8
+ import { resolveGitSource } from './git-source.js';
8
9
  import { prepareWorkspace } from './prepare-workspace.js';
9
10
  const exec = promisify(execFile);
10
11
  export class GitWorkspaceProvider {
@@ -33,6 +34,15 @@ export class GitWorkspaceProvider {
33
34
  async acquire(request) {
34
35
  const { signal } = request;
35
36
  signal.throwIfAborted();
37
+ if (request.requiredSourceRef !== undefined) {
38
+ const source = await resolveGitSource(this.resolver, {
39
+ resourceId: request.repositoryResource.resourceId,
40
+ sourceRef: request.requiredSourceRef,
41
+ pullRequestBase: request.assignment?.pullRequestBase ?? request.requiredSourceRef,
42
+ });
43
+ if (source.sourceRevision !== request.checkoutRevision)
44
+ throw new Error('Candidate source moved from its exact revision');
45
+ }
36
46
  const locator = await this.resolver.cloneLocator(request.repositoryResource.resourceId, signal);
37
47
  signal.throwIfAborted();
38
48
  const name = `${request.workItemId}-${request.mode}-${slug(locator)}`;
@@ -509,7 +519,8 @@ function assertAssignment(previousMarker, request) {
509
519
  (previousMarker.assignment !== undefined || request.assignment !== undefined) &&
510
520
  previousMarker.repositoryResourceId !== request.repositoryResource.resourceId)
511
521
  throw new Error('Workspace belongs to a different Repository Resource');
512
- if (previousMarker?.assignment !== undefined &&
522
+ if (request.mode === WorkspaceMode.Branch &&
523
+ previousMarker?.assignment !== undefined &&
513
524
  !isDeepStrictEqual(previousMarker.assignment, request.assignment))
514
525
  throw new Error('Workspace repository assignment changed; reconcile the existing branch before retrying');
515
526
  }
@@ -49,6 +49,7 @@ export function createConversationCommandReactor(orchestration, feedback) {
49
49
  }
50
50
  if (entry.origin.canClarify === false)
51
51
  return;
52
+ await routeEscalatedReply(orchestration, feedback, event, workItemId, entry.origin.adapter);
52
53
  for (const workflow of await orchestration.listAll()) {
53
54
  if (workflow.workItemId !== workItemId)
54
55
  continue;
@@ -66,6 +67,30 @@ export function createConversationCommandReactor(orchestration, feedback) {
66
67
  }),
67
68
  };
68
69
  }
70
+ /**
71
+ * A parent that escalated a delegated child's question to a human has no stage to resume. The
72
+ * human's reply is recorded on each asking child's own conversation, where the ordinary reply path
73
+ * resumes it; the cohort stays tracked and nothing is settled or joined.
74
+ */
75
+ async function routeEscalatedReply(orchestration, feedback, event, workItemId, adapter) {
76
+ if (feedback === undefined)
77
+ return;
78
+ const context = {
79
+ commandId: `${event.eventId}:escalated-reply`,
80
+ correlationId: correlationId(event.correlationId),
81
+ occurredAt: event.occurredAt,
82
+ actor: { kind: EventActorKind.Integration, id: adapter },
83
+ };
84
+ for (const childWorkItemId of await orchestration.escalatedReplyTargets(workItemId)) {
85
+ const conversation = await feedback.conversations.createForWorkItem(childWorkItemId, context);
86
+ await feedback.conversations.record({
87
+ conversationId: conversation.conversationId,
88
+ entryId: `${event.eventId}:routed:${childWorkItemId}`,
89
+ body: event.entry.body,
90
+ origin: event.entry.origin,
91
+ }, context);
92
+ }
93
+ }
69
94
  async function applyExternalCommand(orchestration, feedback, event, input, context) {
70
95
  const entryId = context.commandId + ':feedback';
71
96
  const canPublish = input.authorized || input.reviewAuthorized === true;
@@ -1,12 +1,14 @@
1
1
  import type { WorkItemId } from '../../work/index.js';
2
2
  import type { DelegationAuthority } from '../contracts/delegation-ports.js';
3
3
  import { type CommandContext } from '@atolis-hq/eventing';
4
+ import type { ActivityName } from '../../activities/index.js';
4
5
  import { type WorkService } from '../../work/index.js';
5
6
  import type { DelegationArtifacts, DelegationRepositories } from '../contracts/delegation-ports.js';
6
7
  import type { DelegatedAssignment, DelegationCaller, DelegationLimits, DelegationReservation, DelegationResult } from '../contracts/delegation.js';
7
8
  import { type WorkflowInstanceId } from '../contracts/identifiers.js';
8
9
  import type { WorkflowInstanceView } from '../contracts/views.js';
9
10
  import type { CoordinationClaims } from './coordination-claims.js';
11
+ import { DelegationAttention, type DelegationAttentionDependencies } from './delegation-attention.js';
10
12
  import { DelegationPrerequisites } from './delegation-prerequisites.js';
11
13
  import type { OrchestrationRepository } from './orchestration-repository.js';
12
14
  import type { StartWorkflow } from './start-workflow.js';
@@ -24,6 +26,7 @@ export declare class DelegatedWork {
24
26
  private readonly dependencies;
25
27
  private readonly ledger;
26
28
  readonly prerequisites: DelegationPrerequisites;
29
+ readonly attention: DelegationAttention;
27
30
  private readonly artifacts;
28
31
  private readonly repositories;
29
32
  private readonly runHasEnded;
@@ -32,6 +35,8 @@ export declare class DelegatedWork {
32
35
  readonly repositories?: DelegationRepositories | undefined;
33
36
  readonly runHasEnded: (runId: string) => Promise<boolean>;
34
37
  readonly authority?: DelegationAuthority | undefined;
38
+ readonly supportsAttention?: ((activity: ActivityName) => boolean) | undefined;
39
+ readonly resumeChild?: DelegationAttentionDependencies['resumeChild'] | undefined;
35
40
  });
36
41
  inspect(id: WorkItemId): Promise<{
37
42
  settled: boolean;
@@ -95,6 +100,10 @@ export declare class DelegatedWork {
95
100
  cohortId?: string | undefined;
96
101
  useAsBase?: boolean | undefined;
97
102
  }[] | undefined;
103
+ replaces?: {
104
+ cohortId: string;
105
+ assignmentId: string;
106
+ } | undefined;
98
107
  repository?: {
99
108
  resourceId: string;
100
109
  sourceRef: string;
@@ -126,6 +135,7 @@ export declare class DelegatedWork {
126
135
  contextWorkItems(parent: WorkflowInstanceView): Promise<ReadonlySet<string>>;
127
136
  results(id: WorkflowInstanceId, cohortId: string): Promise<readonly DelegationResult[]>;
128
137
  reserve(caller: DelegationCaller, cohortId: string, assignments: readonly DelegatedAssignment[], context: CommandContext, limits?: DelegationLimits, expectedPlanRevision?: number): Promise<DelegationReservation>;
138
+ private assertPinnedReplacements;
129
139
  private pinAssignments;
130
140
  reconcile(context: CommandContext): Promise<void>;
131
141
  private capacityReservations;
@@ -136,7 +146,11 @@ export declare class DelegatedWork {
136
146
  /** Appends the reservation only if the root stream is unchanged since `events` was read. */
137
147
  private commit;
138
148
  private reconcileReservation;
149
+ /** Independent members keep advancing; a blocked member is skipped, never retried blindly. */
150
+ private advanceMembers;
139
151
  private settleUnusable;
152
+ /** Every member either failed (with its dependents) or produced its selected result. */
153
+ private allTerminal;
140
154
  private abandon;
141
155
  private preparePrerequisites;
142
156
  private childrenQualified;
@@ -8,11 +8,14 @@ import { OrchestrationEventType } from '../contracts/events.js';
8
8
  import { orchestrationGroupId, workflowInstanceId, } from '../contracts/identifiers.js';
9
9
  import { DelegationConflictCode, DelegationPrerequisiteCondition, WorkflowStatus, } from '../contracts/vocabulary.js';
10
10
  import { nextOrdinal } from '../domain/decision-events.js';
11
+ import { assertCriteriaPreserving, originalOf } from '../domain/delivery-replacement.js';
11
12
  import { isSuccessfulWorkflowCompletion } from '../domain/workflow-completion.js';
13
+ import { DelegationAttention, } from './delegation-attention.js';
12
14
  import { delegationDraft, delegationEventId, DelegationLedger, isJoined, isSettled, reservationsOf, reservedEvent, selectedResults, unsettledReservations, } from './delegation-ledger.js';
13
15
  import { DelegationPrerequisites } from './delegation-prerequisites.js';
14
16
  import { assertWithinRootLimits, buildReservation, matchesAssignments, } from './delegation-reservation.js';
15
17
  import { resolvePrerequisites } from './delegation-wait-graph.js';
18
+ import { readDeliveryFacts } from './delivery-facts-reader.js';
16
19
  const defaultLimits = { maxDepth: 1, maxDescendants: 8 };
17
20
  /**
18
21
  * Durable delegation of independent child WorkItems. Reservation is the single commit point;
@@ -27,6 +30,7 @@ export class DelegatedWork {
27
30
  dependencies;
28
31
  ledger;
29
32
  prerequisites;
33
+ attention;
30
34
  artifacts;
31
35
  repositories;
32
36
  runHasEnded;
@@ -39,6 +43,13 @@ export class DelegatedWork {
39
43
  this.dependencies = dependencies;
40
44
  this.ledger = new DelegationLedger(repository);
41
45
  this.artifacts = dependencies.artifacts;
46
+ this.attention = new DelegationAttention(repository, this.ledger, {
47
+ artifacts: dependencies.artifacts,
48
+ supportsAttention: (activity) => dependencies.supportsAttention?.(activity) ?? true,
49
+ resumeChild: (id, context) => dependencies.resumeChild?.(id, context) ?? Promise.resolve(null),
50
+ contextWorkItems: (parent) => this.contextWorkItems(parent),
51
+ canContinue: (reservation) => this.canJoin(reservation),
52
+ });
42
53
  this.prerequisites = new DelegationPrerequisites(repository, this.ledger, dependencies.artifacts, dependencies.repositories, work);
43
54
  this.repositories = dependencies.repositories;
44
55
  this.runHasEnded = dependencies.runHasEnded;
@@ -126,6 +137,7 @@ export class DelegatedWork {
126
137
  return prior;
127
138
  }
128
139
  const pinned = await this.pinAssignments(parent, assignments);
140
+ await this.assertPinnedReplacements(parent, pinned);
129
141
  let reservation = buildReservation(identity.parent, caller, cohortId, pinned, limits);
130
142
  for (let attempt = 0; attempt < 8; attempt++) {
131
143
  const { events: rootFacts, sequence } = await this.repository.history(identity.root);
@@ -162,6 +174,13 @@ export class DelegatedWork {
162
174
  }
163
175
  throw new Error('Delegation reservation contention exceeded retry limit');
164
176
  }
177
+ async assertPinnedReplacements(parent, pinned) {
178
+ const replacementFacts = await readDeliveryFacts(this.repository, parent, (await this.repository.history(parent.workflowInstanceId)).events);
179
+ for (const assignment of pinned) {
180
+ if (assignment.replaces !== undefined)
181
+ assertCriteriaPreserving(replacementFacts, originalOf(replacementFacts, assignment.replaces), assignment);
182
+ }
183
+ }
165
184
  async pinAssignments(parent, assignments) {
166
185
  return Promise.all(assignments.map(async (assignment) => {
167
186
  if (assignment.repository === undefined)
@@ -251,6 +270,10 @@ export class DelegatedWork {
251
270
  if (availability.reason !== undefined)
252
271
  throw new Error(availability.reason);
253
272
  const current = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
273
+ // One unresolved cohort per parent: a second cohort cannot share the waiting parent, so
274
+ // replacements are submitted once the cohort settles and the parent is resumed.
275
+ if (current.delegationAttention !== undefined)
276
+ throw new DelegationConflictError(DelegationConflictCode.AttentionOpen, 'Submit replacement work after the cohort settles; an open attention assessment cannot start a second cohort');
254
277
  if (current.pendingActivation?.activationId !== caller.activationId ||
255
278
  current.status !== WorkflowStatus.Active)
256
279
  throw new Error('Delegation requires the current active activation');
@@ -302,6 +325,19 @@ export class DelegatedWork {
302
325
  if (!(await this.ensureWait(reservation, context)))
303
326
  return;
304
327
  const root = await this.registerChildren(artifacts, reservation, context);
328
+ await this.advanceMembers(artifacts, root, reservation, context);
329
+ // Live attention only while independent members are unfinished; a fully terminal batch takes
330
+ // the ordinary unsuccessful continuation, which already carries every blocker.
331
+ if (!this.allTerminal(await this.ledger.events(), reservation))
332
+ await this.attention.raise(reservation, context);
333
+ if (await this.settleUnusable(reservation, context))
334
+ return;
335
+ const results = selectedResults(await this.ledger.events(), reservation);
336
+ if (await this.childrenQualified(reservation, results, context))
337
+ await this.join(reservation, results, context);
338
+ }
339
+ /** Independent members keep advancing; a blocked member is skipped, never retried blindly. */
340
+ async advanceMembers(artifacts, root, reservation, context) {
305
341
  const read = await this.prerequisites.read();
306
342
  for (const child of reservation.children) {
307
343
  const events = await this.ledger.events();
@@ -312,26 +348,13 @@ export class DelegatedWork {
312
348
  if (await this.preparePrerequisites(root, reservation, child, context, read))
313
349
  await this.advanceChild(artifacts, root, reservation, child, context);
314
350
  }
315
- if (await this.settleUnusable(reservation, context))
316
- return;
317
- const results = selectedResults(await this.ledger.events(), reservation);
318
- if (await this.childrenQualified(reservation, results, context))
319
- await this.join(reservation, results, context);
320
351
  }
321
352
  async settleUnusable(reservation, context) {
322
353
  const events = await this.ledger.events();
323
- const failed = new Set(events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationChildBlocked
324
- ? [event.payload.childWorkItemId]
325
- : []));
326
- const first = reservation.children.find((child) => failed.has(child.workItemId));
327
- if (first === undefined)
354
+ const failed = failedChildren(events, reservation);
355
+ if (failed.size === 0)
328
356
  return false;
329
- for (let pass = 0; pass < reservation.children.length; pass++)
330
- for (const child of reservation.children)
331
- if (child.prerequisiteWorkItemIds?.some((id) => failed.has(id)))
332
- failed.add(child.workItemId);
333
- const selected = new Set(selectedResults(events, reservation).map((result) => result.childWorkItemId));
334
- if (reservation.children.every((child) => failed.has(child.workItemId) || selected.has(child.workItemId))) {
357
+ if (this.allTerminal(events, reservation)) {
335
358
  if (!(await this.canJoin(reservation)))
336
359
  return true;
337
360
  await this.abandon(reservation, failed, context);
@@ -339,6 +362,13 @@ export class DelegatedWork {
339
362
  }
340
363
  return true;
341
364
  }
365
+ /** Every member either failed (with its dependents) or produced its selected result. */
366
+ allTerminal(events, reservation) {
367
+ const failed = failedChildren(events, reservation);
368
+ const selected = new Set(selectedResults(events, reservation).map((result) => result.childWorkItemId));
369
+ return (failed.size > 0 &&
370
+ reservation.children.every((child) => failed.has(child.workItemId) || selected.has(child.workItemId)));
371
+ }
342
372
  async abandon(reservation, failed, context) {
343
373
  for (const child of reservation.children) {
344
374
  if (!failed.has(child.workItemId))
@@ -515,10 +545,8 @@ export class DelegatedWork {
515
545
  });
516
546
  }
517
547
  async failChild(reservation, child, reason, context) {
518
- if (!reservation.children.some((entry) => (entry.prerequisites?.length ?? 0) > 0)) {
519
- await this.fail(reservation, reason, context);
520
- return;
521
- }
548
+ // Every cohort keeps independent members running: the failure is a durable blocker the
549
+ // parent assesses, and the cohort settles unsuccessfully only once all members are terminal.
522
550
  await this.ledger.appendOnce(reservation.parentWorkflowInstanceId, context, 'child-blocked:' + child.grantId, {
523
551
  eventType: OrchestrationEventType.DelegationChildBlocked,
524
552
  payload: { childWorkItemId: child.workItemId, reason },
@@ -600,6 +628,21 @@ export class DelegatedWork {
600
628
  }
601
629
  }
602
630
  }
631
+ /** Recorded blockers plus the dependents that can no longer start. */
632
+ function failedChildren(events, reservation) {
633
+ const members = new Set(reservation.children.map((child) => child.workItemId));
634
+ const failed = new Set(events.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationChildBlocked &&
635
+ members.has(event.payload.childWorkItemId)
636
+ ? [event.payload.childWorkItemId]
637
+ : []));
638
+ if (failed.size === 0)
639
+ return failed;
640
+ for (let pass = 0; pass < reservation.children.length; pass++)
641
+ for (const child of reservation.children)
642
+ if (child.prerequisiteWorkItemIds?.some((id) => failed.has(id)))
643
+ failed.add(child.workItemId);
644
+ return failed;
645
+ }
603
646
  function rootRunLimit(reservations, limits) {
604
647
  const maxConcurrentRuns = reservations[0]?.maxConcurrentRuns ?? limits.maxConcurrentRuns;
605
648
  return maxConcurrentRuns === undefined ? {} : { maxConcurrentRuns };
@@ -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 {};