@atolis-hq/wake 0.4.99 → 0.4.101

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 (62) hide show
  1. package/dist/src/activities/agent/agent-activity.js +17 -2
  2. package/dist/src/bootstrap/artifact-mcp.d.ts +1 -0
  3. package/dist/src/bootstrap/artifact-mcp.js +27 -1
  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 +4 -2
  9. package/dist/src/bootstrap/surface-api-delivery.d.ts +4 -0
  10. package/dist/src/bootstrap/surface-api-delivery.js +35 -0
  11. package/dist/src/bootstrap/surface-api-work-applications.js +2 -0
  12. package/dist/src/bootstrap/version.js +1 -1
  13. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +3 -1
  14. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +2 -11
  15. package/dist/src/control-plane/application/advance-once-dispatch.js +11 -24
  16. package/dist/src/control-plane/application/trigger-recovery.js +2 -1
  17. package/dist/src/control-plane/application/trigger-workflow.d.ts +2 -1
  18. package/dist/src/control-plane/application/work-cancellation-policy.d.ts +1 -0
  19. package/dist/src/control-plane/application/work-cancellation-policy.js +6 -1
  20. package/dist/src/control-plane/domain/delivery-capacity.d.ts +12 -0
  21. package/dist/src/control-plane/domain/delivery-capacity.js +41 -0
  22. package/dist/src/control-plane/domain/dispatch-policy.d.ts +1 -0
  23. package/dist/src/control-plane/domain/dispatch-policy.js +6 -0
  24. package/dist/src/control-plane/domain/open-work-policy.d.ts +3 -0
  25. package/dist/src/control-plane/domain/open-work-policy.js +12 -8
  26. package/dist/src/execution/application/repository-assignments.d.ts +1 -1
  27. package/dist/src/execution/application/repository-assignments.js +7 -4
  28. package/dist/src/execution/application/run-repository.d.ts +2 -2
  29. package/dist/src/execution/application/run-repository.js +3 -3
  30. package/dist/src/orchestration/application/delegated-work.d.ts +52 -0
  31. package/dist/src/orchestration/application/delegated-work.js +61 -2
  32. package/dist/src/orchestration/application/delegation-commands.d.ts +119 -0
  33. package/dist/src/orchestration/application/delegation-commands.js +100 -0
  34. package/dist/src/orchestration/application/delegation-gate.d.ts +4 -1
  35. package/dist/src/orchestration/application/delegation-gate.js +17 -3
  36. package/dist/src/orchestration/application/orchestration-service.d.ts +150 -2
  37. package/dist/src/orchestration/application/orchestration-service.js +45 -4
  38. package/dist/src/orchestration/contracts/config.d.ts +16 -0
  39. package/dist/src/orchestration/contracts/config.js +10 -0
  40. package/dist/src/orchestration/contracts/delegation-ports.d.ts +10 -1
  41. package/dist/src/orchestration/contracts/delegation.d.ts +34 -0
  42. package/dist/src/orchestration/contracts/delegation.js +8 -0
  43. package/dist/src/orchestration/domain/compiler.js +7 -0
  44. package/dist/src/orchestration/index.d.ts +3 -0
  45. package/dist/src/orchestration/index.js +1 -0
  46. package/dist/src/surfaces/api/contracts/work.d.ts +14 -0
  47. package/dist/src/surfaces/index.d.ts +1 -0
  48. package/dist/src/surfaces/index.js +1 -0
  49. package/dist/src/surfaces/mcp/delegation.d.ts +9 -0
  50. package/dist/src/surfaces/mcp/delegation.js +25 -0
  51. package/dist/src/surfaces/web-assets/assets/index-C5R-aWzH.js +1192 -0
  52. package/dist/src/surfaces/web-assets/index.html +1 -1
  53. package/dist/src/work/application/delivery-availability.d.ts +17 -0
  54. package/dist/src/work/application/delivery-availability.js +20 -0
  55. package/dist/src/work/application/work-repository.d.ts +2 -2
  56. package/dist/src/work/application/work-repository.js +2 -2
  57. package/dist/src/work/application/work-service.d.ts +2 -2
  58. package/dist/src/work/application/work-service.js +2 -2
  59. package/dist/src/work/index.d.ts +1 -0
  60. package/dist/src/work/index.js +1 -0
  61. package/package.json +1 -1
  62. package/dist/src/surfaces/web-assets/assets/index-s9CWgq-s.js +0 -1192
@@ -1,4 +1,4 @@
1
- import { ActivityFailureCode, ActivityOutcomeKind, ActivityRunnerTransportStatus, ClaudeAuthenticationFailureKind, } from '../contracts/vocabulary.js';
1
+ import { ActivityFailureCode, ActivityOutcomeKind, ActivityRunnerTransportStatus, AgentResultStatus, ClaudeAuthenticationFailureKind, } from '../contracts/vocabulary.js';
2
2
  import { translateAgentResult } from './agent-result.js';
3
3
  export function createAgentActivity(templates, contextReader) {
4
4
  return {
@@ -139,7 +139,7 @@ function escapeUntrustedJson(json) {
139
139
  function requestFrom(input, runId, template, runnerContext, resumeSessionId, usageBaseline, workspace, mcpServers, mcpPrompt, reportRunnerTimeout) {
140
140
  return {
141
141
  runId,
142
- prompt: appendMcpPrompt(appendWorkspacePrompt(input.prompt ?? template.prompt, workspace), mcpPrompt),
142
+ prompt: appendResponseContract(appendMcpPrompt(appendWorkspacePrompt(input.prompt ?? template.prompt, workspace), mcpPrompt)),
143
143
  ...modelField(input.model ?? template?.model ?? runnerContext?.model),
144
144
  ...effortField(runnerContext?.effort),
145
145
  allowedTools: input.allowedTools ?? template?.allowedTools ?? [],
@@ -152,6 +152,21 @@ function requestFrom(input, runId, template, runnerContext, resumeSessionId, usa
152
152
  ...(reportRunnerTimeout === undefined ? {} : { onTimeout: reportRunnerTimeout }),
153
153
  };
154
154
  }
155
+ function appendResponseContract(prompt) {
156
+ return [
157
+ prompt,
158
+ '',
159
+ 'Wake response contract (trusted instructions):',
160
+ 'Report your actual outcome honestly. End your response with exactly one status marker on its own final line, using one of these exact forms:',
161
+ `[[STATUS: ${AgentResultStatus.Done}]] — the requested work is complete.`,
162
+ `[[STATUS: ${AgentResultStatus.Rejected}]] — you deliberately declined the request.`,
163
+ `[[STATUS: ${AgentResultStatus.Blocked}]] — an external blocker prevents further progress.`,
164
+ `[[STATUS: ${AgentResultStatus.NeedsClarification}]] — a human answer is needed to proceed.`,
165
+ `[[STATUS: ${AgentResultStatus.Failed}]] — the attempt failed.`,
166
+ 'Bare status words such as “DONE” or prose alone are not valid results. Structured JSON with a recognized status field remains supported.',
167
+ 'These instructions specify result reporting only. Preserve task requirements, untrusted-context boundaries, artifact reporting, provider verification, and review authority.',
168
+ ].join('\n');
169
+ }
155
170
  function appendMcpPrompt(prompt, mcpPrompt) {
156
171
  return mcpPrompt === undefined ? prompt : `${prompt}\n\n${mcpPrompt}`;
157
172
  }
@@ -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,29 @@ 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
+ fresh: true,
89
+ })).view;
90
+ if (run === null || run.activationId !== descriptor.activationId)
91
+ throw new Error('Delegation Run is unavailable');
92
+ const parent = await root.orchestration.get(workflowInstanceId(run.workflowInstanceId));
93
+ if (parent?.workItemId !== descriptor.workItemId)
94
+ throw new Error('Delegation parent does not match session');
95
+ return {
96
+ workflowInstanceId: parent.workflowInstanceId,
97
+ activationId: toActivationId(descriptor.activationId),
98
+ runId: descriptor.runId,
99
+ };
100
+ },
101
+ });
76
102
  return server;
77
103
  }
78
104
  function commandContext(occurredAt, descriptor) {
@@ -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), { fresh: true })).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
@@ -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
+ import { readDeliveryAvailability } from '../work/index.js';
3
+ export async function presentDelivery(root, work) {
4
+ if (root.orchestration?.deliveryTree === undefined)
5
+ return {};
6
+ const cohorts = await root.orchestration.deliveryTree(work.workItemId);
7
+ if (cohorts.length === 0 && work.delegation === undefined)
8
+ return {};
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 = await readDeliveryAvailability(child.workItemId, root.work);
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.99";
127
+ export const wakeVersion = "v0.4.101";
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 { 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,6 +60,7 @@ 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>;
@@ -2,7 +2,7 @@ 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
4
  import type { AdvanceResult } from '../contracts/views.js';
5
- import type { DispatchPolicy } from '../domain/dispatch-policy.js';
5
+ import { type DispatchPolicy } from '../domain/dispatch-policy.js';
6
6
  import { type WorkAvailability } from '../domain/open-work-policy.js';
7
7
  import type { ExecutionPort, OrchestrationPort } from './activation-scheduler-ports.js';
8
8
  export interface DispatchLoopContext {
@@ -28,15 +28,6 @@ interface PendingActivation {
28
28
  export declare function advancementWasDurablyApplied(orchestration: OrchestrationPort, workflowInstanceId: WorkflowInstanceView['workflowInstanceId'], activationId: ActivityActivationView['activationId']): Promise<boolean>;
29
29
  export declare function isolatedWorkflowReason(error: unknown): string;
30
30
  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
- */
31
+ /** Recheck capacity and select a fresh candidate after each dispatch. */
41
32
  export declare function runDispatchLoop(pending: readonly PendingActivation[], ctx: DispatchLoopContext): Promise<AdvanceResult>;
42
33
  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';
6
+ import { neutralDispatchPriority } from '../domain/dispatch-policy.js';
5
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,24 @@ 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
+ const capacity = await deliveryCapacity(inventory, allRuns, ctx.work, ctx.orchestration.deliveryRunLimit?.bind(ctx.orchestration));
58
47
  // Legacy test ports may omit listAll; production supplies the journal-backed inventory.
59
48
  const open = ctx.maxOpenWorkItems === null
60
49
  ? new Set()
61
- : await readOpenWorkItemIds(((await ctx.orchestration.listAll?.()) ?? pending.map((item) => item.workflow)).map((workflow) => startedWorkflowIds.has(workflow.workflowInstanceId)
50
+ : await readOpenWorkItemIds(inventory.map((workflow) => startedWorkflowIds.has(workflow.workflowInstanceId)
62
51
  ? { ...workflow, hasStartedActivation: true }
63
52
  : workflow), ctx.work);
64
53
  const selectedCandidate = ctx.dispatchPolicy.select(pending
65
54
  .filter((item) => !isolatedIds.has(item.workflow.workflowInstanceId) &&
66
- canDispatchWorkItem(item.workflow.workItemId, open, ctx.maxOpenWorkItems))
55
+ !capacity.unavailable.has(item.workflow.workItemId) &&
56
+ !capacity.full.has(capacity.roots.get(item.workflow.workItemId) ?? item.workflow.workItemId) &&
57
+ canDispatchWorkItem(capacity.roots.get(item.workflow.workItemId) ?? item.workflow.workItemId, open, ctx.maxOpenWorkItems))
67
58
  .map((item, requestedPosition) => ({
68
59
  workItemId: item.workflow.workItemId,
69
60
  activationId: item.activation.activationId,
70
61
  requestedPosition,
71
- priority: item.priority ?? neutralPriority,
62
+ priority: item.priority ?? neutralDispatchPriority,
72
63
  hasActiveRun: dispatchedIds.has(item.activation.activationId) ||
73
64
  activeActivationIds.has(item.activation.activationId) ||
74
65
  branchActiveWorkflowIds.has(item.workflow.workflowInstanceId),
@@ -169,11 +160,7 @@ export async function runDispatchLoop(pending, ctx) {
169
160
  };
170
161
  continue;
171
162
  }
172
- if (error instanceof ActivationClaimConflictError) {
173
- stopReason = { kind: 'no-work' };
174
- break;
175
- }
176
- if (error instanceof NoEligibleRunnerError) {
163
+ if (error instanceof ActivationClaimConflictError || error instanceof NoEligibleRunnerError) {
177
164
  stopReason = { kind: 'no-work' };
178
165
  break;
179
166
  }
@@ -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,12 @@
1
+ import type { RunView } from '../../execution/index.js';
2
+ import { type WorkflowInstanceView } from '../../orchestration/index.js';
3
+ import { type WorkItemId } from '../../work/index.js';
4
+ import type { WorkAvailability } from './open-work-policy.js';
5
+ /** A waiting workflow is not a Run; every actual Run, including watches, counts. */
6
+ export declare function deliveryCapacity(workflows: readonly WorkflowInstanceView[], runs: readonly RunView[], work: {
7
+ get(id: string): Promise<WorkAvailability | null>;
8
+ } | undefined, runLimit: ((id: WorkItemId) => Promise<number | undefined>) | undefined): Promise<{
9
+ roots: ReadonlyMap<string, string>;
10
+ unavailable: ReadonlySet<string>;
11
+ full: ReadonlySet<string>;
12
+ }>;
@@ -0,0 +1,41 @@
1
+ import { isActiveRunStatus } from '../../execution/index.js';
2
+ import { WorkflowStatus } from '../../orchestration/index.js';
3
+ import { readDeliveryAvailability } from '../../work/index.js';
4
+ /** A waiting workflow is not a Run; every actual Run, including watches, counts. */
5
+ export async function deliveryCapacity(workflows, runs, work, runLimit) {
6
+ const activeWorkflowIds = new Set(runs.filter((run) => isActiveRunStatus(run.status)).map((run) => run.workflowInstanceId));
7
+ // Concluded history cannot dispatch or hold a Run, so it needs no ancestry reads.
8
+ const live = workflows.filter((workflow) => activeWorkflowIds.has(workflow.workflowInstanceId) ||
9
+ (workflow.status !== WorkflowStatus.Completed &&
10
+ workflow.status !== WorkflowStatus.Superseded));
11
+ const roots = new Map();
12
+ const unavailable = new Set();
13
+ await Promise.all([...new Set(live.map((workflow) => workflow.workItemId))].map(async (id) => {
14
+ const delivery = work === undefined ? { rootWorkItemId: id } : await readDeliveryAvailability(id, work);
15
+ roots.set(id, delivery.rootWorkItemId);
16
+ if (delivery.reason !== undefined)
17
+ unavailable.add(id);
18
+ }));
19
+ const full = new Set();
20
+ // A root without an active Run cannot be at a positive limit.
21
+ await Promise.all([...activeRunCounts(live, runs, roots)].map(async ([root, count]) => {
22
+ const limit = await runLimit?.(root);
23
+ if (limit !== undefined && count >= limit)
24
+ full.add(root);
25
+ }));
26
+ return { roots, unavailable, full };
27
+ }
28
+ function activeRunCounts(workflows, runs, roots) {
29
+ const byId = new Map(workflows.map((workflow) => [workflow.workflowInstanceId, workflow]));
30
+ const counts = new Map();
31
+ for (const run of runs) {
32
+ if (!isActiveRunStatus(run.status))
33
+ continue;
34
+ const workflow = byId.get(run.workflowInstanceId);
35
+ if (workflow === undefined)
36
+ continue;
37
+ const root = roots.get(workflow.workItemId);
38
+ counts.set(root, (counts.get(root) ?? 0) + 1);
39
+ }
40
+ return counts;
41
+ }
@@ -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,5 +1,8 @@
1
1
  import { type WorkflowInstanceView } from '../../orchestration/index.js';
2
+ import type { WorkDelegation } from '../../work/index.js';
2
3
  export interface WorkAvailability {
4
+ readonly state?: string;
5
+ readonly delegation?: WorkDelegation;
3
6
  readonly frozen?: boolean;
4
7
  readonly deleted?: boolean;
5
8
  }
@@ -1,4 +1,5 @@
1
1
  import { ActivityActivationStatus, WorkflowStatus, } from '../../orchestration/index.js';
2
+ import { readDeliveryAvailability } from '../../work/index.js';
2
3
  /** Distinct started items with any nonterminal workflow, including waiting children. */
3
4
  export function deriveOpenWorkItemIds(workflows, unavailable = new Set()) {
4
5
  const started = new Set();
@@ -24,12 +25,15 @@ export function canDispatchWorkItem(workItemId, open, limit) {
24
25
  return open.has(workItemId) || hasOpenWorkCapacity(open, limit);
25
26
  }
26
27
  export async function readOpenWorkItemIds(workflows, work) {
27
- const open = deriveOpenWorkItemIds(workflows);
28
- const unavailable = new Set();
29
- await Promise.all([...open].map(async (id) => {
30
- const item = await work?.get(id);
31
- if (item?.frozen === true || item?.deleted === true)
32
- unavailable.add(id);
33
- }));
34
- return new Set([...open].filter((id) => !unavailable.has(id)));
28
+ const roots = new Set();
29
+ for (const id of deriveOpenWorkItemIds(workflows)) {
30
+ if (work === undefined) {
31
+ roots.add(id);
32
+ continue;
33
+ }
34
+ const delivery = await readDeliveryAvailability(id, work);
35
+ if (delivery.reason === undefined)
36
+ roots.add(delivery.rootWorkItemId);
37
+ }
38
+ return roots;
35
39
  }
@@ -4,7 +4,7 @@ import type { RepositoryAssignment, RepositoryAssignmentRequest } from '../contr
4
4
  /** Correlations are the parent's explicit repository authority, not the provider catalogue. */
5
5
  export declare function createRepositoryAssignments(resources: ResourceService, resolveSource: (request: RepositoryAssignmentRequest) => Promise<RepositoryAssignment>, inherited: (workItemId: string) => Promise<{
6
6
  readonly resourceId: string;
7
- } | undefined>): {
7
+ } | undefined>, permitted?: (workItemId: string) => Promise<readonly string[] | undefined>): {
8
8
  resolve(parent: {
9
9
  readonly workItemId: WorkItemId;
10
10
  }, request: RepositoryAssignmentRequest): Promise<RepositoryAssignment>;
@@ -1,6 +1,6 @@
1
1
  import { BuiltInResourceKind, resourceId } from '../../resources/index.js';
2
2
  /** Correlations are the parent's explicit repository authority, not the provider catalogue. */
3
- export function createRepositoryAssignments(resources, resolveSource, inherited) {
3
+ export function createRepositoryAssignments(resources, resolveSource, inherited, permitted) {
4
4
  return {
5
5
  async resolve(parent, request) {
6
6
  const repository = await resources.get(resourceId(request.resourceId));
@@ -8,9 +8,12 @@ export function createRepositoryAssignments(resources, resolveSource, inherited)
8
8
  throw new Error(`Repository Resource ${request.resourceId} is unavailable; select an existing Repository Resource`);
9
9
  const correlations = await resources.correlationsForWork(parent.workItemId);
10
10
  const scope = await inherited(parent.workItemId);
11
- if (scope === undefined
12
- ? !correlations.some((entry) => entry.resourceId === repository.resourceId)
13
- : scope.resourceId !== repository.resourceId)
11
+ const authority = await permitted?.(parent.workItemId);
12
+ if (authority !== undefined
13
+ ? !authority.includes(repository.resourceId)
14
+ : scope === undefined
15
+ ? !correlations.some((entry) => entry.resourceId === repository.resourceId)
16
+ : scope.resourceId !== repository.resourceId)
14
17
  throw new Error(`Repository ${request.resourceId} is outside the parent assignment; explicitly authorize the repository before delegating`);
15
18
  return resolveSource(request);
16
19
  },