@atolis-hq/wake 0.4.100 → 0.4.102

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 (72) hide show
  1. package/dist/src/artifacts/application/operator-instructions-service.js +2 -2
  2. package/dist/src/bootstrap/artifact-mcp.d.ts +1 -0
  3. package/dist/src/bootstrap/artifact-mcp.js +27 -2
  4. package/dist/src/bootstrap/composition-root.js +6 -1
  5. package/dist/src/bootstrap/config/root-schema.d.ts +14 -0
  6. package/dist/src/bootstrap/delegation-authority.d.ts +10 -0
  7. package/dist/src/bootstrap/delegation-authority.js +52 -0
  8. package/dist/src/bootstrap/integration-runtime.js +5 -3
  9. package/dist/src/bootstrap/persistence-composition.js +1 -1
  10. package/dist/src/bootstrap/surface-api-delivery.d.ts +4 -0
  11. package/dist/src/bootstrap/surface-api-delivery.js +35 -0
  12. package/dist/src/bootstrap/surface-api-work-applications.js +2 -0
  13. package/dist/src/bootstrap/version.js +1 -1
  14. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +4 -1
  15. package/dist/src/control-plane/application/activation-scheduler.js +2 -1
  16. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +4 -15
  17. package/dist/src/control-plane/application/advance-once-dispatch.js +15 -26
  18. package/dist/src/control-plane/application/trigger-recovery.js +2 -1
  19. package/dist/src/control-plane/application/trigger-workflow.d.ts +2 -1
  20. package/dist/src/control-plane/application/work-cancellation-policy.d.ts +1 -0
  21. package/dist/src/control-plane/application/work-cancellation-policy.js +6 -1
  22. package/dist/src/control-plane/domain/delivery-capacity.d.ts +9 -0
  23. package/dist/src/control-plane/domain/delivery-capacity.js +40 -0
  24. package/dist/src/control-plane/domain/dispatch-policy.d.ts +1 -0
  25. package/dist/src/control-plane/domain/dispatch-policy.js +6 -0
  26. package/dist/src/control-plane/domain/open-work-policy.d.ts +2 -7
  27. package/dist/src/control-plane/domain/open-work-policy.js +12 -9
  28. package/dist/src/execution/application/repository-assignments.d.ts +1 -1
  29. package/dist/src/execution/application/repository-assignments.js +7 -4
  30. package/dist/src/node_modules/@atolis-hq/eventing/dist/runtime/cached-journal-view.d.ts +9 -1
  31. package/dist/src/node_modules/@atolis-hq/eventing/dist/runtime/cached-journal-view.d.ts.map +1 -1
  32. package/dist/src/node_modules/@atolis-hq/eventing/dist/runtime/cached-journal-view.js +62 -7
  33. package/dist/src/node_modules/@atolis-hq/eventing/dist/store/event-journal.d.ts +2 -5
  34. package/dist/src/node_modules/@atolis-hq/eventing/dist/store/event-journal.d.ts.map +1 -1
  35. package/dist/src/node_modules/@atolis-hq/eventing-filesystem/dist/file-event-journal.d.ts +12 -13
  36. package/dist/src/node_modules/@atolis-hq/eventing-filesystem/dist/file-event-journal.d.ts.map +1 -1
  37. package/dist/src/node_modules/@atolis-hq/eventing-filesystem/dist/file-event-journal.js +168 -109
  38. package/dist/src/orchestration/application/deferred-signals.d.ts +4 -2
  39. package/dist/src/orchestration/application/deferred-signals.js +47 -37
  40. package/dist/src/orchestration/application/delegated-work.d.ts +54 -0
  41. package/dist/src/orchestration/application/delegated-work.js +64 -1
  42. package/dist/src/orchestration/application/delegation-commands.d.ts +119 -0
  43. package/dist/src/orchestration/application/delegation-commands.js +99 -0
  44. package/dist/src/orchestration/application/delegation-gate.d.ts +15 -5
  45. package/dist/src/orchestration/application/delegation-gate.js +44 -4
  46. package/dist/src/orchestration/application/orchestration-service.d.ts +150 -2
  47. package/dist/src/orchestration/application/orchestration-service.js +52 -6
  48. package/dist/src/orchestration/contracts/config.d.ts +16 -0
  49. package/dist/src/orchestration/contracts/config.js +10 -0
  50. package/dist/src/orchestration/contracts/delegation-ports.d.ts +10 -1
  51. package/dist/src/orchestration/contracts/delegation.d.ts +34 -0
  52. package/dist/src/orchestration/contracts/delegation.js +8 -0
  53. package/dist/src/orchestration/domain/compiler.js +7 -0
  54. package/dist/src/orchestration/index.d.ts +3 -0
  55. package/dist/src/orchestration/index.js +1 -0
  56. package/dist/src/surfaces/api/contracts/work.d.ts +14 -0
  57. package/dist/src/surfaces/index.d.ts +1 -0
  58. package/dist/src/surfaces/index.js +1 -0
  59. package/dist/src/surfaces/mcp/delegation.d.ts +9 -0
  60. package/dist/src/surfaces/mcp/delegation.js +25 -0
  61. package/dist/src/surfaces/web-assets/assets/index-C5R-aWzH.js +1192 -0
  62. package/dist/src/surfaces/web-assets/index.html +1 -1
  63. package/dist/src/work/application/work-index.d.ts +21 -0
  64. package/dist/src/work/application/work-index.js +73 -0
  65. package/dist/src/work/application/work-service.d.ts +3 -0
  66. package/dist/src/work/application/work-service.js +3 -0
  67. package/dist/src/work/domain/delivery-availability.d.ts +14 -0
  68. package/dist/src/work/domain/delivery-availability.js +20 -0
  69. package/dist/src/work/index.d.ts +2 -0
  70. package/dist/src/work/index.js +2 -0
  71. package/package.json +2 -1
  72. package/dist/src/surfaces/web-assets/assets/index-s9CWgq-s.js +0 -1192
@@ -46,7 +46,7 @@ export class OperatorInstructionsService {
46
46
  if (bytes.byteLength > this.config.maxWriteBytes)
47
47
  throw new Error(`Operator instructions exceed ${this.config.maxWriteBytes} byte limit`);
48
48
  const stream = artifactContextStream(input.contextScope);
49
- const events = await this.journal.readStream(stream, { fresh: true });
49
+ const events = await this.journal.readStream(stream);
50
50
  const revisions = this.selectRevisions(events);
51
51
  const existing = revisions.find((item) => item.revisionId === input.revisionId);
52
52
  if (existing !== undefined) {
@@ -88,7 +88,7 @@ export class OperatorInstructionsService {
88
88
  }
89
89
  async revisions(contextScope) {
90
90
  artifactSharedContextNameSchema.parse(contextScope);
91
- return this.selectRevisions(await this.journal.readStream(artifactContextStream(contextScope), { fresh: true }));
91
+ return this.selectRevisions(await this.journal.readStream(artifactContextStream(contextScope)));
92
92
  }
93
93
  selectRevisions(events) {
94
94
  return events.flatMap((envelope) => {
@@ -25,6 +25,7 @@ export declare function createArtifactMcpServerForSession(root: ArtifactMcpRoot,
25
25
  readonly nextId: () => string;
26
26
  }): Promise<import("@modelcontextprotocol/sdk/server/mcp").McpServer>;
27
27
  interface ArtifactMcpRoot {
28
+ readonly journal?: EventJournal;
28
29
  readonly artifacts: ArtifactService;
29
30
  readonly orchestration: OrchestrationService;
30
31
  }
@@ -1,7 +1,10 @@
1
1
  import { correlationId, EventActorKind } from '@atolis-hq/eventing';
2
2
  import { randomUUID } from 'node:crypto';
3
+ import { activationId as toActivationId } from '../activities/index.js';
3
4
  import { createArtifactMcpServer, } from '../artifacts/index.js';
4
- import { ExecutionEventType, runId as executionRunId, runStream, selectRunExecutionEvent, WakeMcpServerName, } from '../execution/index.js';
5
+ import { ExecutionEventType, runId as executionRunId, RunRepository, runStream, selectRunExecutionEvent, WakeMcpServerName, } from '../execution/index.js';
6
+ import { workflowInstanceId } from '../orchestration/index.js';
7
+ import { registerDelegationTools } from '../surfaces/index.js';
5
8
  const sessionLifetimeMs = 2 * 60 * 60 * 1000;
6
9
  /** Bootstrap binds Artifact's generic policy to verified Execution and Orchestration facts. */
7
10
  export function createArtifactMcpProvisioner(input) {
@@ -73,6 +76,28 @@ export async function createArtifactMcpServerForSession(root, sessions, path, to
73
76
  await sessions.read(path, token);
74
77
  },
75
78
  });
79
+ if (root.journal !== undefined)
80
+ registerDelegationTools(server, {
81
+ orchestration: root.orchestration,
82
+ commandContext: () => commandContext(options.now(), descriptor),
83
+ caller: async () => {
84
+ await sessions.read(path, token);
85
+ if (root.journal === undefined)
86
+ throw new Error('Delegation journal is unavailable');
87
+ const run = (await new RunRepository(root.journal).load(executionRunId(descriptor.runId)))
88
+ .view;
89
+ if (run === null || run.activationId !== descriptor.activationId)
90
+ throw new Error('Delegation Run is unavailable');
91
+ const parent = await root.orchestration.get(workflowInstanceId(run.workflowInstanceId));
92
+ if (parent?.workItemId !== descriptor.workItemId)
93
+ throw new Error('Delegation parent does not match session');
94
+ return {
95
+ workflowInstanceId: parent.workflowInstanceId,
96
+ activationId: toActivationId(descriptor.activationId),
97
+ runId: descriptor.runId,
98
+ };
99
+ },
100
+ });
76
101
  return server;
77
102
  }
78
103
  function commandContext(occurredAt, descriptor) {
@@ -120,7 +145,7 @@ function operatorInstructionsPrompt(instructions) {
120
145
  async function instructionsForRun(input, runId, contextScope) {
121
146
  const prior = input.journal === undefined
122
147
  ? undefined
123
- : (await input.journal.readStream(runStream(executionRunId(runId)), { fresh: true }))
148
+ : (await input.journal.readStream(runStream(executionRunId(runId))))
124
149
  .flatMap((envelope) => {
125
150
  const event = selectRunExecutionEvent(envelope);
126
151
  return event?.event.eventType === ExecutionEventType.RunOperatorInstructionsCaptured
@@ -15,6 +15,7 @@ import { createBuiltInActivityRegistry } from './activity-registry.js';
15
15
  import { createArtifactMcpProvisioner } from './artifact-mcp.js';
16
16
  import { createArtifactTriggerContext } from './artifact-trigger-context.js';
17
17
  import { loadConfig } from './config/load-config.js';
18
+ import { createDelegationAuthority } from './delegation-authority.js';
18
19
  import { EventProcessorRuntime } from './event-processor-runtime.js';
19
20
  import { loadFakeScenarios } from './fake-scenarios.js';
20
21
  import { composeIntegrationRuntime, composeProviders } from './integration-runtime.js';
@@ -67,7 +68,11 @@ async function createApplicationServices(wakeRoot, options = {}) {
67
68
  const providerInstances = createProviderBinding();
68
69
  const cloneResolver = createCloneResolver(resources, options);
69
70
  const orchestration = createOrchestrationService(journal, work, definitions, projections, createAgentActivityClassifier(activities), (queries) => ({
70
- repositories: createRepositoryAssignments(resources, (request) => resolveGitSource(cloneResolver, request), (id) => orchestration.repositoryAssignment(id)),
71
+ authority: createDelegationAuthority(journal, resources, activities, {
72
+ ids,
73
+ repositoryIdentity: resolveResourceRepositoryIdentity,
74
+ }),
75
+ repositories: createRepositoryAssignments(resources, (request) => resolveGitSource(cloneResolver, request), (id) => orchestration.repositoryAssignment(id), (id) => orchestration.repositoryAuthority(id)),
71
76
  artifacts: createDelegationOutputs({
72
77
  providers: () => providerInstances.promise,
73
78
  resources,
@@ -10,6 +10,13 @@ import { type WorkConfig } from '../../work/index.js';
10
10
  declare const orchestrationConfigSchema: z.ZodDefault<z.ZodObject<{
11
11
  workflows: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
12
12
  entry: z.ZodOptional<z.ZodString>;
13
+ delegation: z.ZodOptional<z.ZodObject<{
14
+ workflows: z.ZodArray<z.ZodString>;
15
+ repositories: z.ZodOptional<z.ZodArray<z.ZodString>>;
16
+ maxDepth: z.ZodNumber;
17
+ maxDescendants: z.ZodNumber;
18
+ maxConcurrentRuns: z.ZodNumber;
19
+ }, z.core.$strict>>;
13
20
  commands: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
14
21
  activity: z.ZodString;
15
22
  with: z.ZodOptional<z.ZodUnknown>;
@@ -171,6 +178,13 @@ export declare const rootConfigSchema: z.ZodObject<{
171
178
  orchestration: z.ZodDefault<z.ZodObject<{
172
179
  workflows: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
173
180
  entry: z.ZodOptional<z.ZodString>;
181
+ delegation: z.ZodOptional<z.ZodObject<{
182
+ workflows: z.ZodArray<z.ZodString>;
183
+ repositories: z.ZodOptional<z.ZodArray<z.ZodString>>;
184
+ maxDepth: z.ZodNumber;
185
+ maxDescendants: z.ZodNumber;
186
+ maxConcurrentRuns: z.ZodNumber;
187
+ }, z.core.$strict>>;
174
188
  commands: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
175
189
  activity: z.ZodString;
176
190
  with: z.ZodOptional<z.ZodUnknown>;
@@ -0,0 +1,10 @@
1
+ import type { EventJournal } from '@atolis-hq/eventing';
2
+ import { type ActivityRegistry } from '../activities/index.js';
3
+ import type { IdGenerator } from '../kernel/index.js';
4
+ import type { DelegationAuthority } from '../orchestration/index.js';
5
+ import { type ResourceRepositoryIdentityResolver, type ResourceService } from '../resources/index.js';
6
+ /** Bind delegation to durable Run identity; credentials and audit actors alone are insufficient. */
7
+ export declare function createDelegationAuthority(journal: EventJournal, resources: ResourceService, activities: ActivityRegistry, binding: {
8
+ readonly ids: IdGenerator;
9
+ readonly repositoryIdentity: ResourceRepositoryIdentityResolver;
10
+ }): DelegationAuthority;
@@ -0,0 +1,52 @@
1
+ import { ActivityExecutionKind } from '../activities/index.js';
2
+ import { isActiveRunStatus, runId, RunRepository } from '../execution/index.js';
3
+ import { BuiltInResourceKind, ResourceCorrelationRole, resourceId, ResourceStreamKind, } from '../resources/index.js';
4
+ /** Bind delegation to durable Run identity; credentials and audit actors alone are insufficient. */
5
+ export function createDelegationAuthority(journal, resources, activities, binding) {
6
+ const runs = new RunRepository(journal);
7
+ const repositories = async (workItemId) => {
8
+ const correlated = await resources.correlationsForWork(workItemId);
9
+ const views = await Promise.all(correlated.map((entry) => resources.get(entry.resourceId)));
10
+ return views
11
+ .filter((view) => view?.kind === BuiltInResourceKind.Repository)
12
+ .map((view) => view.resourceId);
13
+ };
14
+ return {
15
+ async assertCaller(caller, parent) {
16
+ const run = (await runs.load(runId(caller.runId))).view;
17
+ if (run === null ||
18
+ !isActiveRunStatus(run.status) ||
19
+ run.cancellation !== undefined ||
20
+ run.workflowInstanceId !== parent.workflowInstanceId ||
21
+ run.activationId !== caller.activationId ||
22
+ (parent.pendingActivation?.activationId ?? parent.delegationFence?.activationId) !==
23
+ caller.activationId ||
24
+ activities.describe(run.activity).executionKind !== ActivityExecutionKind.Agent)
25
+ throw new Error('Delegation capability is stale or does not own the parent activation');
26
+ },
27
+ repositories: (parent) => repositories(parent.workItemId),
28
+ // The scope is the repository the provider observed the root Issue in, never an agent claim.
29
+ // Any Repository Resource already correlated to the root (for example operator-declared)
30
+ // is the explicit scope and is left untouched.
31
+ async bindRepositoryScope(root, context) {
32
+ if ((await repositories(root.workItemId)).length > 0)
33
+ return;
34
+ const primary = (await resources.correlationsForWork(root.workItemId)).find((entry) => entry.role === ResourceCorrelationRole.Primary);
35
+ const origin = primary === undefined ? null : await resources.get(primary.resourceId);
36
+ if (origin === null || origin.kind !== BuiltInResourceKind.Issue)
37
+ return;
38
+ const identity = binding.repositoryIdentity(origin.externalKey);
39
+ if (identity === undefined)
40
+ return;
41
+ const externalKey = { adapter: origin.externalKey.adapter, key: identity };
42
+ const repository = (await resources.findByExternalKey(externalKey)) ??
43
+ (await resources.discover({
44
+ resourceId: resourceId(binding.ids.next(ResourceStreamKind.Resource)),
45
+ kind: BuiltInResourceKind.Repository,
46
+ externalKey,
47
+ capabilities: [],
48
+ }, context));
49
+ await resources.correlate(repository.resourceId, root.workItemId, ResourceCorrelationRole.Secondary, context);
50
+ },
51
+ };
52
+ }
@@ -8,7 +8,7 @@ import { ExecutionStreamKind, NoEligibleRunnerError, RunRepository, createRuntim
8
8
  import { AgentRunPublicationReactor, ArtifactRegistrationReactor, DeliveryOutcomeReactor, DeliveryService, IntegrationStreamKind, ProviderRegistry, deliveryProjectionDefinitions, fakeProviderDefinition, publishConversationCommandFeedback, reconcileMergedDeliveries, } from '../integrations/index.js';
9
9
  import { compileWorkflowSelectors, createConversationCommandReactor, createPullRequestTransitionEvidence, createResourceTransitionReactor, createWatchReactor, createWatchReconciler, isWorkflowInstanceStream, selectWorkflow, workflowInstanceId, workflowName, } from '../orchestration/index.js';
10
10
  import { BuiltInResourceCapability, resourceId, } from '../resources/index.js';
11
- import { isWorkItemStream } from '../work/index.js';
11
+ import { isWorkItemStream, workItemId } from '../work/index.js';
12
12
  import { decodeCanonicalEvent } from './canonical-events.js';
13
13
  import { hydrateFakeProviderEvidence } from './fake-provider-files.js';
14
14
  import { createPollCoordinator } from './poll-coordinator.js';
@@ -59,7 +59,9 @@ export async function composeIntegrationRuntime(input) {
59
59
  return (await input.projections.list(triggerInvocationProjection.name)).flatMap(({ value }) => (value === null ? [] : [value]));
60
60
  },
61
61
  invocationScope: async (item) => {
62
- const claim = (await input.journal.readStream(triggerInvocationStream(item)))
62
+ const work = await input.work.get(workItemId(item));
63
+ const origin = work?.delegation?.rootWorkItemId ?? item;
64
+ const claim = (await input.journal.readStream(triggerInvocationStream(origin)))
63
65
  .map(selectControlEvent)
64
66
  .find((event) => event?.event.eventType === ControlEventType.TriggerInvocationClaimed);
65
67
  return claim?.event.eventType === ControlEventType.TriggerInvocationClaimed
@@ -132,7 +134,7 @@ export async function composeIntegrationRuntime(input) {
132
134
  async function openWorkCapacityAvailable() {
133
135
  const limit = input.config.controlPlane.maxOpenWorkItems ?? null;
134
136
  return (limit === null ||
135
- hasOpenWorkCapacity(await readOpenWorkItemIds(await input.orchestration.listAll(), input.work), limit));
137
+ hasOpenWorkCapacity(readOpenWorkItemIds(await input.orchestration.listAll(), await input.work.deliverySnapshot()), limit));
136
138
  }
137
139
  const triggerReactors = input.config.controlPlane.triggers.map((config) => createTriggerReactor(triggers, config, decodeCanonicalEvent));
138
140
  // Registration starts at the current journal boundary; historical facts are not sources.
@@ -10,7 +10,7 @@ function serializeJournalAppends(journal) {
10
10
  appendTail = appended.then(() => undefined, () => undefined);
11
11
  return appended;
12
12
  },
13
- readStream: (stream, options) => journal.readStream(stream, options),
13
+ readStream: (stream) => journal.readStream(stream),
14
14
  ...(journal.scanAll === undefined
15
15
  ? {}
16
16
  : { scanAll: (signal) => journal.scanAll(signal) }),
@@ -0,0 +1,4 @@
1
+ import { type WorkDetailResponse } from '../surfaces/index.js';
2
+ import type { WorkItemView } from '../work/index.js';
3
+ import type { CompositionRoot } from './composition-root.js';
4
+ export declare function presentDelivery(root: CompositionRoot, work: WorkItemView): Promise<Pick<WorkDetailResponse, 'delegation'>>;
@@ -0,0 +1,35 @@
1
+ import { presentResource, toWorkItemKey } from '../surfaces/index.js';
2
+ export async function presentDelivery(root, work) {
3
+ if (root.orchestration?.deliveryTree === undefined)
4
+ return {};
5
+ const cohorts = await root.orchestration.deliveryTree(work.workItemId);
6
+ if (cohorts.length === 0 && work.delegation === undefined)
7
+ return {};
8
+ const delivery = await root.work.deliverySnapshot();
9
+ return {
10
+ delegation: {
11
+ rootWorkItemKey: toWorkItemKey(work.delegation?.rootWorkItemId ?? work.workItemId),
12
+ ...(work.delegation === undefined
13
+ ? {}
14
+ : { parentWorkItemKey: toWorkItemKey(work.delegation.parentWorkItemId) }),
15
+ children: await Promise.all(cohorts.flatMap((cohort) => cohort.children.map(async (child) => {
16
+ const availability = delivery.availability(child.workItemId);
17
+ const resources = await Promise.all((await root.resources.correlationsForWork(child.workItemId)).map((entry) => root.resources.get(entry.resourceId)));
18
+ return {
19
+ workItemKey: toWorkItemKey(child.workItemId),
20
+ parentWorkItemKey: toWorkItemKey(cohort.parentWorkItemId),
21
+ objective: child.objective,
22
+ workflowName: child.workflowName,
23
+ status: child.workflow?.status ?? 'registration-pending',
24
+ cohortId: cohort.cohortId,
25
+ ...((availability.reason ?? child.workflow?.blockReason)
26
+ ? { blockReason: (availability.reason ?? child.workflow?.blockReason) }
27
+ : {}),
28
+ resources: resources
29
+ .filter((entry) => entry !== null)
30
+ .map(presentResource(root.resolveResourceLink)),
31
+ };
32
+ }))),
33
+ },
34
+ };
35
+ }
@@ -8,6 +8,7 @@ import { workCorrelationsProjection, } from '../resources/index.js';
8
8
  import { ApiCommandStatus, fromWorkItemKey, presentResource, presentRun, presentWorkflowInstance, presentWorkItem, toWorkItemKey, } from '../surfaces/index.js';
9
9
  import { workItemId, WorkStatus } from '../work/index.js';
10
10
  import { primaryExternalRef } from './external-ref.js';
11
+ import { presentDelivery } from './surface-api-delivery.js';
11
12
  import { presentPrimaryWorkflow } from './surface-api-merge-policy.js';
12
13
  import { projectionMeta } from './surface-api-metadata.js';
13
14
  import { projectionPage } from './surface-api-projection-pages.js';
@@ -222,6 +223,7 @@ async function workDetail(root, key, now) {
222
223
  // the production root always composes Conversations.
223
224
  const conversation = await conversationForWorkItem(root, id);
224
225
  const data = {
226
+ ...(await presentDelivery(root, work)),
225
227
  ...(await triggerOriginForWork(root, id)),
226
228
  work: presentDetailWork(work, externalRef, runs),
227
229
  resources: resources.map(presentResource(root.resolveResourceLink)),
@@ -124,6 +124,6 @@ export function resolveWakeVersion(options = {}) {
124
124
  return `g${headHash.slice(0, 7)}`;
125
125
  return '0.1.0-dev';
126
126
  }
127
- export const wakeVersion = "v0.4.100";
127
+ export const wakeVersion = "v0.4.102";
128
128
  /** The registry-installable version used by packaged sandbox images. */
129
129
  export const wakePackageVersion = packageVersion(defaultRepoRoot) ?? wakeVersion;
@@ -3,7 +3,7 @@ import type { ExecutionFailureCode, RepositoryAssignment, RunView, WorkspaceReco
3
3
  import type { IdGenerator } from '../../kernel/index.js';
4
4
  import type { ActivityActivationView, PendingActivationPriority, WorkflowInstanceView } from '../../orchestration/index.js';
5
5
  import type { ResourceService } from '../../resources/index.js';
6
- import type { WorkStatus } from '../../work/index.js';
6
+ import type { DeliverySnapshot, WorkDelegation, WorkItemId, WorkStatus } from '../../work/index.js';
7
7
  import type { DispatchPolicy } from '../domain/dispatch-policy.js';
8
8
  export interface OrchestrationPort {
9
9
  reconcileChildCompletions(context: CommandContext): Promise<void>;
@@ -17,6 +17,7 @@ export interface OrchestrationPort {
17
17
  get?(workflowInstanceId: string): Promise<WorkflowInstanceView | null>;
18
18
  expireTimedOutWaits?(context: CommandContext): Promise<readonly WorkflowInstanceView[]>;
19
19
  listAll?(): Promise<readonly WorkflowInstanceView[]>;
20
+ deliveryRunLimit?(id: WorkItemId): Promise<number | undefined>;
20
21
  validateActivationDispatch?(workflowInstanceId: string, context: CommandContext): Promise<boolean>;
21
22
  acceptOutcome(command: {
22
23
  workflowInstanceId: string;
@@ -59,9 +60,11 @@ export interface ActivationSchedulerDependencies {
59
60
  readonly work?: {
60
61
  get(workItemId: string): Promise<{
61
62
  readonly state: WorkStatus;
63
+ readonly delegation?: WorkDelegation;
62
64
  readonly frozen?: boolean;
63
65
  readonly deleted?: boolean;
64
66
  } | null>;
67
+ deliverySnapshot(): Promise<DeliverySnapshot>;
65
68
  };
66
69
  readonly runnerIneligibility?: () => Promise<ReadonlySet<string>>;
67
70
  readonly isDispatchPaused?: () => Promise<boolean>;
@@ -105,11 +105,12 @@ export function createActivationScheduler(orchestration, execution, resources, c
105
105
  return { kind: 'paused' };
106
106
  }
107
107
  const rawPending = await orchestration.listPendingActivations(options.workItemId);
108
+ const delivery = rawPending.length === 0 ? undefined : await dependencies.work?.deliverySnapshot();
108
109
  const pending = (await Promise.all(rawPending.map(async (candidate) => {
109
110
  if (candidate.activation.notBefore !== undefined &&
110
111
  Date.parse(candidate.activation.notBefore) > clock.now().getTime())
111
112
  return null;
112
- const work = await dependencies.work?.get(candidate.workflow.workItemId);
113
+ const work = delivery?.get(candidate.workflow.workItemId);
113
114
  return work?.frozen || work?.deleted ? null : candidate;
114
115
  }))).filter((candidate) => candidate !== null);
115
116
  const blocked = ((await orchestration.listAll?.()) ?? []).flatMap((workflow) => workflow.status === WorkflowStatus.Blocked &&
@@ -1,9 +1,9 @@
1
1
  import type { CommandContext } from '@atolis-hq/eventing';
2
2
  import type { ActivityActivationView, PendingActivationPriority, WorkflowInstanceView } from '../../orchestration/index.js';
3
3
  import { type ResourceService } from '../../resources/index.js';
4
+ import type { WorkService } from '../../work/index.js';
4
5
  import type { AdvanceResult } from '../contracts/views.js';
5
- import type { DispatchPolicy } from '../domain/dispatch-policy.js';
6
- import { type WorkAvailability } from '../domain/open-work-policy.js';
6
+ import { type DispatchPolicy } from '../domain/dispatch-policy.js';
7
7
  import type { ExecutionPort, OrchestrationPort } from './activation-scheduler-ports.js';
8
8
  export interface DispatchLoopContext {
9
9
  readonly orchestration: OrchestrationPort;
@@ -13,9 +13,7 @@ export interface DispatchLoopContext {
13
13
  readonly maxConcurrentRuns: number;
14
14
  readonly maxDispatches: number;
15
15
  readonly maxOpenWorkItems: number | null;
16
- readonly work: {
17
- get(id: string): Promise<WorkAvailability | null>;
18
- } | undefined;
16
+ readonly work: Pick<WorkService, 'deliverySnapshot'> | undefined;
19
17
  readonly runnerIneligibility: () => Promise<ReadonlySet<string>>;
20
18
  readonly isDispatchPaused: () => Promise<boolean>;
21
19
  readonly commandContext: (cause: string) => CommandContext;
@@ -28,15 +26,6 @@ interface PendingActivation {
28
26
  export declare function advancementWasDurablyApplied(orchestration: OrchestrationPort, workflowInstanceId: WorkflowInstanceView['workflowInstanceId'], activationId: ActivityActivationView['activationId']): Promise<boolean>;
29
27
  export declare function isolatedWorkflowReason(error: unknown): string;
30
28
  export declare function blockIsolatedWorkflow(orchestration: OrchestrationPort, workflowInstanceId: string, error: unknown, context: CommandContext): Promise<string>;
31
- /**
32
- * Fills open capacity within one Advancement call: dispatches ready
33
- * activations one at a time, rechecking `maxConcurrentRuns` and reselecting
34
- * fresh candidates after every dispatch (per #346's capacity-recheck
35
- * principle), until capacity, the per-call `maxDispatches` burst cap, or
36
- * eligible candidates are exhausted. Candidates dispatched earlier in the
37
- * same call are excluded from later selection via `dispatchedIds`, since
38
- * their Run lifecycle event is not guaranteed visible through
39
- * `execution.list()` yet.
40
- */
29
+ /** Recheck capacity and select a fresh candidate after each dispatch. */
41
30
  export declare function runDispatchLoop(pending: readonly PendingActivation[], ctx: DispatchLoopContext): Promise<AdvanceResult>;
42
31
  export {};
@@ -1,15 +1,11 @@
1
+ import { deliveryCapacity } from '../domain/delivery-capacity.js';
1
2
  import { dispatchResources } from './dispatch-resources.js';
2
3
  import { isRunnerQuotaOutcome, reportUnappliedRunnerQuotaRetry, runnerQuotaMessage, } from './runner-quota-outcome.js';
3
4
  import { ActivationClaimConflictError, isActiveRunStatus, NoEligibleRunnerError, RunStatus, WorkspaceMode, } from '../../execution/index.js';
4
5
  import { DelegationPendingError, WorkflowStatus } from '../../orchestration/index.js';
5
- import { canDispatchWorkItem, readOpenWorkItemIds, } from '../domain/open-work-policy.js';
6
+ import { neutralDispatchPriority } from '../domain/dispatch-policy.js';
7
+ import { canDispatchWorkItem, readOpenWorkItemIds } from '../domain/open-work-policy.js';
6
8
  import { isExecutionFailureTerminal } from './execution-reconciliation.js';
7
- // Ports without priority (older fakes) rank neutrally and fall back to oldest-first.
8
- const neutralPriority = {
9
- remainingAgentSteps: 0,
10
- watchDriven: false,
11
- retried: false,
12
- };
13
9
  export async function advancementWasDurablyApplied(orchestration, workflowInstanceId, activationId) {
14
10
  const current = await orchestration.get?.(workflowInstanceId);
15
11
  return (current !== undefined && current !== null && current.acceptedOutcomes.includes(activationId));
@@ -28,16 +24,7 @@ export async function blockIsolatedWorkflow(orchestration, workflowInstanceId, e
28
24
  await orchestration.block(workflowInstanceId, reason, context);
29
25
  return reason;
30
26
  }
31
- /**
32
- * Fills open capacity within one Advancement call: dispatches ready
33
- * activations one at a time, rechecking `maxConcurrentRuns` and reselecting
34
- * fresh candidates after every dispatch (per #346's capacity-recheck
35
- * principle), until capacity, the per-call `maxDispatches` burst cap, or
36
- * eligible candidates are exhausted. Candidates dispatched earlier in the
37
- * same call are excluded from later selection via `dispatchedIds`, since
38
- * their Run lifecycle event is not guaranteed visible through
39
- * `execution.list()` yet.
40
- */
27
+ /** Recheck capacity and select a fresh candidate after each dispatch. */
41
28
  export async function runDispatchLoop(pending, ctx) {
42
29
  const dispatched = [];
43
30
  const dispatchedIds = new Set();
@@ -55,20 +42,26 @@ export async function runDispatchLoop(pending, ctx) {
55
42
  stopReason = { kind: 'no-work' };
56
43
  break;
57
44
  }
45
+ const inventory = (await ctx.orchestration.listAll?.()) ?? pending.map((item) => item.workflow);
46
+ // One synchronisation with Work per pass; every item is then answered from memory.
47
+ const delivery = await ctx.work?.deliverySnapshot();
48
+ const capacity = await deliveryCapacity(inventory, allRuns, delivery, ctx.orchestration.deliveryRunLimit?.bind(ctx.orchestration));
58
49
  // Legacy test ports may omit listAll; production supplies the journal-backed inventory.
59
50
  const open = ctx.maxOpenWorkItems === null
60
51
  ? new Set()
61
- : await readOpenWorkItemIds(((await ctx.orchestration.listAll?.()) ?? pending.map((item) => item.workflow)).map((workflow) => startedWorkflowIds.has(workflow.workflowInstanceId)
52
+ : readOpenWorkItemIds(inventory.map((workflow) => startedWorkflowIds.has(workflow.workflowInstanceId)
62
53
  ? { ...workflow, hasStartedActivation: true }
63
- : workflow), ctx.work);
54
+ : workflow), delivery);
64
55
  const selectedCandidate = ctx.dispatchPolicy.select(pending
65
56
  .filter((item) => !isolatedIds.has(item.workflow.workflowInstanceId) &&
66
- canDispatchWorkItem(item.workflow.workItemId, open, ctx.maxOpenWorkItems))
57
+ !capacity.unavailable.has(item.workflow.workItemId) &&
58
+ !capacity.full.has(capacity.roots.get(item.workflow.workItemId) ?? item.workflow.workItemId) &&
59
+ canDispatchWorkItem(capacity.roots.get(item.workflow.workItemId) ?? item.workflow.workItemId, open, ctx.maxOpenWorkItems))
67
60
  .map((item, requestedPosition) => ({
68
61
  workItemId: item.workflow.workItemId,
69
62
  activationId: item.activation.activationId,
70
63
  requestedPosition,
71
- priority: item.priority ?? neutralPriority,
64
+ priority: item.priority ?? neutralDispatchPriority,
72
65
  hasActiveRun: dispatchedIds.has(item.activation.activationId) ||
73
66
  activeActivationIds.has(item.activation.activationId) ||
74
67
  branchActiveWorkflowIds.has(item.workflow.workflowInstanceId),
@@ -169,11 +162,7 @@ export async function runDispatchLoop(pending, ctx) {
169
162
  };
170
163
  continue;
171
164
  }
172
- if (error instanceof ActivationClaimConflictError) {
173
- stopReason = { kind: 'no-work' };
174
- break;
175
- }
176
- if (error instanceof NoEligibleRunnerError) {
165
+ if (error instanceof ActivationClaimConflictError || error instanceof NoEligibleRunnerError) {
177
166
  stopReason = { kind: 'no-work' };
178
167
  break;
179
168
  }
@@ -45,7 +45,8 @@ export async function recoverTriggerInvocation(dependencies, invocation, context
45
45
  }, context, `${workflow}:pause:${instance.acceptedOutcomes.length}`);
46
46
  }
47
47
  const status = finishedStatus(instance);
48
- if (status === undefined)
48
+ if (status === undefined ||
49
+ (await dependencies.orchestration.hasLiveDelegatedWork?.(workItemId(claim.workItemId))))
49
50
  return;
50
51
  await dependencies.emit({
51
52
  eventType: ControlEventType.TriggerInvocationFinished,
@@ -1,6 +1,6 @@
1
1
  import type { CommandContext } from '@atolis-hq/eventing';
2
2
  import { workflowInstanceId, type StartWorkflowInstance, type WorkflowInstanceView } from '../../orchestration/index.js';
3
- import { type CreateWorkItem } from '../../work/index.js';
3
+ import { workItemId, type CreateWorkItem } from '../../work/index.js';
4
4
  import type { ControlEventPayloads, ControlEventType } from '../contracts/events.js';
5
5
  type Claim = ControlEventPayloads[typeof ControlEventType.TriggerInvocationClaimed];
6
6
  export interface TriggerWorkflowPorts {
@@ -10,6 +10,7 @@ export interface TriggerWorkflowPorts {
10
10
  readonly orchestration: {
11
11
  start(command: StartWorkflowInstance, context: CommandContext): Promise<unknown>;
12
12
  get(id: ReturnType<typeof workflowInstanceId>): Promise<WorkflowInstanceView | null>;
13
+ hasLiveDelegatedWork?(id: ReturnType<typeof workItemId>): Promise<boolean>;
13
14
  };
14
15
  }
15
16
  /** Creates the top-level invocation WorkItem and workflow once; replays only read. */
@@ -4,6 +4,7 @@ import { type Clock, type IdGenerator } from '../../kernel/index.js';
4
4
  import type { WorkflowInstanceView } from '../../orchestration/index.js';
5
5
  import type { WorkItemId, WorkItemView } from '../../work/index.js';
6
6
  interface WorkPort {
7
+ get?(id: WorkItemId): Promise<WorkItemView | null>;
7
8
  close(workItemId: WorkItemId, reason: string, context: CommandContext): Promise<WorkItemView>;
8
9
  cancel(workItemId: WorkItemId, reason: string, context: CommandContext): Promise<WorkItemView>;
9
10
  }
@@ -6,7 +6,12 @@ export function createWorkCancellationPolicy(work, orchestration, execution, clo
6
6
  async function conclude(workItemId, reason, workAction, executionReason, blockReasonPrefix) {
7
7
  const context = commandContext(clock, ids, workItemId);
8
8
  const concluded = await workAction(context);
9
- const workflows = (await orchestration.listAll()).filter((workflow) => workflow.workItemId === workItemId);
9
+ const all = await orchestration.listAll();
10
+ const descendants = await Promise.all(all.map(async (workflow) => ({ workflow, work: await work.get?.(workflow.workItemId) })));
11
+ const workflows = descendants
12
+ .filter((entry) => entry.workflow.workItemId === workItemId ||
13
+ entry.work?.delegation?.ancestors.includes(workItemId))
14
+ .map((entry) => entry.workflow);
10
15
  await execution.cancelActive(workflows.map((workflow) => workflow.workflowInstanceId), executionReason);
11
16
  for (const workflow of workflows)
12
17
  await orchestration.block(workflow.workflowInstanceId, `${blockReasonPrefix}: ${reason}`, context);
@@ -0,0 +1,9 @@
1
+ import type { RunView } from '../../execution/index.js';
2
+ import { type WorkflowInstanceView } from '../../orchestration/index.js';
3
+ import type { DeliverySnapshot, WorkItemId } from '../../work/index.js';
4
+ /** A waiting workflow is not a Run; every actual Run, including watches, counts. */
5
+ export declare function deliveryCapacity(workflows: readonly WorkflowInstanceView[], runs: readonly RunView[], work: DeliverySnapshot | undefined, runLimit: ((id: WorkItemId) => Promise<number | undefined>) | undefined): Promise<{
6
+ roots: ReadonlyMap<string, string>;
7
+ unavailable: ReadonlySet<string>;
8
+ full: ReadonlySet<string>;
9
+ }>;
@@ -0,0 +1,40 @@
1
+ import { isActiveRunStatus } from '../../execution/index.js';
2
+ import { WorkflowStatus } from '../../orchestration/index.js';
3
+ /** A waiting workflow is not a Run; every actual Run, including watches, counts. */
4
+ export async function deliveryCapacity(workflows, runs, work, runLimit) {
5
+ const activeWorkflowIds = new Set(runs.filter((run) => isActiveRunStatus(run.status)).map((run) => run.workflowInstanceId));
6
+ // Concluded history cannot dispatch or hold a Run, so it needs no ancestry reads.
7
+ const live = workflows.filter((workflow) => activeWorkflowIds.has(workflow.workflowInstanceId) ||
8
+ (workflow.status !== WorkflowStatus.Completed &&
9
+ workflow.status !== WorkflowStatus.Superseded));
10
+ const roots = new Map();
11
+ const unavailable = new Set();
12
+ for (const id of new Set(live.map((workflow) => workflow.workItemId))) {
13
+ const delivery = work === undefined ? { rootWorkItemId: id } : work.availability(id);
14
+ roots.set(id, delivery.rootWorkItemId);
15
+ if (delivery.reason !== undefined)
16
+ unavailable.add(id);
17
+ }
18
+ const full = new Set();
19
+ // A root without an active Run cannot be at a positive limit.
20
+ await Promise.all([...activeRunCounts(live, runs, roots)].map(async ([root, count]) => {
21
+ const limit = await runLimit?.(root);
22
+ if (limit !== undefined && count >= limit)
23
+ full.add(root);
24
+ }));
25
+ return { roots, unavailable, full };
26
+ }
27
+ function activeRunCounts(workflows, runs, roots) {
28
+ const byId = new Map(workflows.map((workflow) => [workflow.workflowInstanceId, workflow]));
29
+ const counts = new Map();
30
+ for (const run of runs) {
31
+ if (!isActiveRunStatus(run.status))
32
+ continue;
33
+ const workflow = byId.get(run.workflowInstanceId);
34
+ if (workflow === undefined)
35
+ continue;
36
+ const root = roots.get(workflow.workItemId);
37
+ counts.set(root, (counts.get(root) ?? 0) + 1);
38
+ }
39
+ return counts;
40
+ }
@@ -22,3 +22,4 @@ export declare class DispatchPolicy {
22
22
  constructor(options: DispatchPolicyOptions);
23
23
  select(candidates: readonly DispatchCandidate[], state?: DispatchPolicyState): readonly DispatchCandidate[];
24
24
  }
25
+ export declare const neutralDispatchPriority: DispatchPriority;
@@ -16,3 +16,9 @@ export class DispatchPolicy {
16
16
  .slice(0, this.options.maxDispatches);
17
17
  }
18
18
  }
19
+ // Ports without priority rank neutrally and fall back to oldest-first.
20
+ export const neutralDispatchPriority = {
21
+ remainingAgentSteps: 0,
22
+ watchDriven: false,
23
+ retried: false,
24
+ };
@@ -1,12 +1,7 @@
1
1
  import { type WorkflowInstanceView } from '../../orchestration/index.js';
2
- export interface WorkAvailability {
3
- readonly frozen?: boolean;
4
- readonly deleted?: boolean;
5
- }
2
+ import type { DeliverySnapshot } from '../../work/index.js';
6
3
  /** Distinct started items with any nonterminal workflow, including waiting children. */
7
4
  export declare function deriveOpenWorkItemIds(workflows: readonly WorkflowInstanceView[], unavailable?: ReadonlySet<string>): ReadonlySet<string>;
8
5
  export declare function hasOpenWorkCapacity(open: ReadonlySet<string>, limit: number | null): boolean;
9
6
  export declare function canDispatchWorkItem(workItemId: string, open: ReadonlySet<string>, limit: number | null): boolean;
10
- export declare function readOpenWorkItemIds(workflows: readonly WorkflowInstanceView[], work?: {
11
- get(id: string): Promise<WorkAvailability | null>;
12
- }): Promise<ReadonlySet<string>>;
7
+ export declare function readOpenWorkItemIds(workflows: readonly WorkflowInstanceView[], work?: DeliverySnapshot): ReadonlySet<string>;