@atolis-hq/wake 0.4.95 → 0.4.96

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/artifacts/application/delegation-artifacts.d.ts +26 -0
  2. package/dist/src/artifacts/application/delegation-artifacts.js +33 -0
  3. package/dist/src/artifacts/index.d.ts +1 -0
  4. package/dist/src/artifacts/index.js +1 -0
  5. package/dist/src/bootstrap/composition-root.js +16 -3
  6. package/dist/src/bootstrap/version.js +1 -1
  7. package/dist/src/control-plane/application/activation-scheduler.js +28 -43
  8. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +0 -13
  9. package/dist/src/control-plane/application/advance-once-dispatch.js +10 -24
  10. package/dist/src/control-plane/application/in-process-scheduler-serialiser.d.ts +1 -0
  11. package/dist/src/control-plane/application/in-process-scheduler-serialiser.js +15 -0
  12. package/dist/src/control-plane/application/runner-quota-outcome.d.ts +13 -0
  13. package/dist/src/control-plane/application/runner-quota-outcome.js +23 -0
  14. package/dist/src/orchestration/application/accept-signal.d.ts +3 -1
  15. package/dist/src/orchestration/application/accept-signal.js +2 -0
  16. package/dist/src/orchestration/application/advance-workflow.d.ts +0 -1
  17. package/dist/src/orchestration/application/advance-workflow.js +0 -4
  18. package/dist/src/orchestration/application/deferred-signals.d.ts +21 -0
  19. package/dist/src/orchestration/application/deferred-signals.js +119 -0
  20. package/dist/src/orchestration/application/delegated-work.d.ts +51 -0
  21. package/dist/src/orchestration/application/delegated-work.js +420 -0
  22. package/dist/src/orchestration/application/delegation-gate.d.ts +17 -0
  23. package/dist/src/orchestration/application/delegation-gate.js +31 -0
  24. package/dist/src/orchestration/application/delegation-ledger.d.ts +28 -0
  25. package/dist/src/orchestration/application/delegation-ledger.js +79 -0
  26. package/dist/src/orchestration/application/delegation-reservation.d.ts +15 -0
  27. package/dist/src/orchestration/application/delegation-reservation.js +54 -0
  28. package/dist/src/orchestration/application/expire-timed-out-waits.d.ts +1 -1
  29. package/dist/src/orchestration/application/expire-timed-out-waits.js +2 -2
  30. package/dist/src/orchestration/application/orchestration-projection.js +5 -1
  31. package/dist/src/orchestration/application/orchestration-repository.d.ts +5 -0
  32. package/dist/src/orchestration/application/orchestration-repository.js +69 -11
  33. package/dist/src/orchestration/application/orchestration-service.d.ts +28 -3
  34. package/dist/src/orchestration/application/orchestration-service.js +69 -20
  35. package/dist/src/orchestration/application/resource-transition-matching.js +11 -6
  36. package/dist/src/orchestration/application/start-workflow.js +4 -2
  37. package/dist/src/orchestration/application/workflow-definition-registry.d.ts +5 -1
  38. package/dist/src/orchestration/application/workflow-definition-registry.js +16 -3
  39. package/dist/src/orchestration/contracts/commands.d.ts +1 -0
  40. package/dist/src/orchestration/contracts/delegation-ports.d.ts +14 -0
  41. package/dist/src/orchestration/contracts/delegation-ports.js +1 -0
  42. package/dist/src/orchestration/contracts/delegation.d.ts +98 -0
  43. package/dist/src/orchestration/contracts/delegation.js +70 -0
  44. package/dist/src/orchestration/contracts/event-decoder.js +19 -0
  45. package/dist/src/orchestration/contracts/event-factory.js +16 -0
  46. package/dist/src/orchestration/contracts/events.d.ts +39 -0
  47. package/dist/src/orchestration/contracts/events.js +8 -0
  48. package/dist/src/orchestration/contracts/views.d.ts +8 -0
  49. package/dist/src/orchestration/domain/workflow-completion.d.ts +3 -0
  50. package/dist/src/orchestration/domain/workflow-completion.js +9 -0
  51. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +2 -0
  52. package/dist/src/orchestration/domain/workflow-instance-events.js +37 -0
  53. package/dist/src/orchestration/index.d.ts +2 -0
  54. package/dist/src/orchestration/index.js +1 -0
  55. package/dist/src/work/application/work-projection.js +3 -0
  56. package/dist/src/work/application/work-service.js +16 -0
  57. package/dist/src/work/contracts/commands.d.ts +6 -0
  58. package/dist/src/work/contracts/events.d.ts +2 -1
  59. package/dist/src/work/contracts/events.js +8 -0
  60. package/dist/src/work/contracts/views.d.ts +2 -1
  61. package/dist/src/work/domain/work-item.js +3 -0
  62. package/package.json +1 -1
@@ -0,0 +1,26 @@
1
+ import type { ArtifactRevisionReference } from '../contracts/context.js';
2
+ import type { ArtifactContextService } from './artifact-context-service.js';
3
+ import type { ArtifactService } from './artifact-service.js';
4
+ /** Binds delegation to Artifacts grants and accepted exact revisions; children never see the join. */
5
+ export declare function createDelegationArtifacts(input: {
6
+ readonly artifacts: ArtifactService;
7
+ readonly contexts: ArtifactContextService;
8
+ readonly accepted: (activationId: string, workItemId?: string) => Promise<boolean>;
9
+ }): {
10
+ validateInputs(_parent: {
11
+ readonly workItemId: string;
12
+ }, references: readonly ArtifactRevisionReference[]): Promise<void>;
13
+ registerChild: (args_0: import("../contracts/context.js").ArtifactDelegationGrant, args_1: import("@atolis-hq/eventing").CommandContext) => Promise<void>;
14
+ qualifyingOutputs(child: {
15
+ readonly workItemId: ArtifactRevisionReference["workItemId"];
16
+ }, outputs: readonly {
17
+ readonly name: string;
18
+ readonly path: string;
19
+ }[]): Promise<{
20
+ name: string;
21
+ reference: {
22
+ workItemId: import("../../work/index.js").WorkItemId;
23
+ revisionId: string;
24
+ };
25
+ }[] | null>;
26
+ };
@@ -0,0 +1,33 @@
1
+ /** Binds delegation to Artifacts grants and accepted exact revisions; children never see the join. */
2
+ export function createDelegationArtifacts(input) {
3
+ return {
4
+ async validateInputs(_parent, references) {
5
+ const accepted = input.accepted;
6
+ for (const reference of references) {
7
+ const revision = (await input.artifacts.get(reference.workItemId))?.revisions.find((candidate) => candidate.revisionId === reference.revisionId);
8
+ if (revision === undefined ||
9
+ revision.deleted ||
10
+ !(await accepted(revision.activationId, reference.workItemId)))
11
+ throw new Error('Delegation context must reference accepted artifact revisions');
12
+ }
13
+ },
14
+ registerChild: async (...args) => input.contexts.registerChild(args[0], input.accepted, args[1]),
15
+ async qualifyingOutputs(child, outputs) {
16
+ const published = await input.artifacts.latestPublished(child.workItemId, (activationId) => input.accepted(activationId, child.workItemId));
17
+ const selected = outputs.map((output) => ({
18
+ name: output.name,
19
+ revision: published.find((revision) => revision.path === output.path),
20
+ }));
21
+ const references = [];
22
+ for (const entry of selected) {
23
+ if (entry.revision === undefined)
24
+ return null;
25
+ references.push({
26
+ name: entry.name,
27
+ reference: { workItemId: child.workItemId, revisionId: entry.revision.revisionId },
28
+ });
29
+ }
30
+ return references;
31
+ },
32
+ };
33
+ }
@@ -18,3 +18,4 @@ export * from './contracts/context-events.js';
18
18
  export * from './contracts/context.js';
19
19
  export * from './application/operator-instructions-service.js';
20
20
  export * from './application/operator-instructions-projection.js';
21
+ export { createDelegationArtifacts } from './application/delegation-artifacts.js';
@@ -18,3 +18,4 @@ export * from './contracts/context-events.js';
18
18
  export * from './contracts/context.js';
19
19
  export * from './application/operator-instructions-service.js';
20
20
  export * from './application/operator-instructions-projection.js';
21
+ export { createDelegationArtifacts } from './application/delegation-artifacts.js';
@@ -1,9 +1,9 @@
1
1
  import { acquireFileLock } from '@atolis-hq/eventing-filesystem';
2
2
  import { createPullRequestService } from '../activities/index.js';
3
- import { ArtifactContextService, FileArtifactMcpSessionStore, FileArtifactStore, OperatorInstructionsService, createArtifactService, } from '../artifacts/index.js';
3
+ import { ArtifactContextService, FileArtifactMcpSessionStore, FileArtifactStore, OperatorInstructionsService, createArtifactService, createDelegationArtifacts, } from '../artifacts/index.js';
4
4
  import { DispatchPolicy, createActivationScheduler, createActivationSchedulerSubscriber, createControlPlaneService, createDurableRunnerIneligibility, createRunnerControlService, } from '../control-plane/index.js';
5
5
  import { createConversationService } from '../conversations/index.js';
6
- import { ExecutionCancellationReason, GitWorkspaceProvider, RecoveryService, TranscriptStore, createExecutionService, createLocalProcessInspector, createRunnerMemoryProfileDecorator, } from '../execution/index.js';
6
+ import { ExecutionCancellationReason, GitWorkspaceProvider, RecoveryService, RunStatus, TranscriptStore, createExecutionService, createLocalProcessInspector, createRunnerMemoryProfileDecorator, isActiveRunStatus, } from '../execution/index.js';
7
7
  import { createGitHubAgentContextReader, gitHubProviderDefinition, gitHubRepositoryIdentity, resolveGitHubResourceUrl, } from '../integrations/github/index.js';
8
8
  import { SystemClock, UlidIdGenerator } from '../kernel/index.js';
9
9
  import { compileWorkflow, createAgentActivityClassifier, createOrchestrationService, } from '../orchestration/index.js';
@@ -63,7 +63,20 @@ async function createApplicationServices(wakeRoot, options = {}) {
63
63
  process.stderr.write(`Warning: ${diagnostic.message}\n`);
64
64
  }),
65
65
  ]));
66
- const orchestration = createOrchestrationService(journal, work, definitions, projections, createAgentActivityClassifier(activities));
66
+ const orchestration = createOrchestrationService(journal, work, definitions, projections, createAgentActivityClassifier(activities), (queries) => ({
67
+ artifacts: createDelegationArtifacts({
68
+ artifacts,
69
+ contexts: artifactContexts,
70
+ accepted: queries.isActivationAccepted,
71
+ }),
72
+ runHasEnded: async (runId) => {
73
+ const run = (await execution.list()).find((entry) => entry.runId === runId);
74
+ return (run !== undefined &&
75
+ !isActiveRunStatus(run.status) &&
76
+ run.status !== RunStatus.Ambiguous &&
77
+ !execution.isLocallyActive(runId));
78
+ },
79
+ }));
67
80
  const workspaces = new GitWorkspaceProvider(paths.workspacesRoot, {
68
81
  async cloneLocator(id) {
69
82
  const resource = await resources.get(resourceId(id));
@@ -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.95";
127
+ export const wakeVersion = "v0.4.96";
128
128
  /** The registry-installable version used by packaged sandbox images. */
129
129
  export const wakePackageVersion = packageVersion(defaultRepoRoot) ?? wakeVersion;
@@ -1,11 +1,13 @@
1
+ import { createInProcessSerialiser } from './in-process-scheduler-serialiser.js';
2
+ import { isRunnerQuotaOutcome, reportUnappliedRunnerQuotaRetry, runnerQuotaMessage, } from './runner-quota-outcome.js';
1
3
  /* eslint-disable complexity, max-lines-per-function */
2
4
  import { correlationId, EventActorKind } from '@atolis-hq/eventing';
3
5
  import { ExecutionFailureCode, RunStatus } from '../../execution/index.js';
4
- import { isAmbiguityResolutionBlock, WorkflowStatus, } from '../../orchestration/index.js';
6
+ import { DelegationPendingError, isAmbiguityResolutionBlock, WorkflowStatus, } from '../../orchestration/index.js';
5
7
  import { WorkStatus } from '../../work/index.js';
6
8
  import { ControlStreamKind } from '../contracts/streams.js';
7
9
  import { DispatchPolicy } from '../domain/dispatch-policy.js';
8
- import { advancementWasDurablyApplied, blockIsolatedWorkflow, isRunnerQuotaOutcome, reportUnappliedRunnerQuotaRetry, runDispatchLoop, runnerQuotaMessage, } from './advance-once-dispatch.js';
10
+ import { advancementWasDurablyApplied, blockIsolatedWorkflow, runDispatchLoop, } from './advance-once-dispatch.js';
9
11
  import { findUnresolvedSucceededTerminal, findUnresolvedTerminal, } from './execution-reconciliation.js';
10
12
  export function createActivationScheduler(orchestration, execution, resources, clock, dependencies) {
11
13
  const runnerIneligibility = dependencies.runnerIneligibility ?? (async () => new Set());
@@ -21,6 +23,19 @@ export function createActivationScheduler(orchestration, execution, resources, c
21
23
  occurredAt: clock.now().toISOString(),
22
24
  actor: { kind: EventActorKind.System, id: ControlStreamKind.Global },
23
25
  });
26
+ const dispatchContext = {
27
+ orchestration,
28
+ execution,
29
+ resources,
30
+ dispatchPolicy,
31
+ maxConcurrentRuns,
32
+ maxOpenWorkItems: dependencies.maxOpenWorkItems ?? null,
33
+ work: dependencies.work,
34
+ maxDispatches,
35
+ runnerIneligibility,
36
+ isDispatchPaused,
37
+ commandContext: context,
38
+ };
24
39
  const maintain = async () => {
25
40
  if (await isDispatchPaused())
26
41
  return { kind: 'paused' };
@@ -161,22 +176,19 @@ export function createActivationScheduler(orchestration, execution, resources, c
161
176
  };
162
177
  }
163
178
  catch (error) {
179
+ if (error instanceof DelegationPendingError) {
180
+ const result = await runDispatchLoop(pending.filter((item) => item.workflow.workflowInstanceId !== recovery.item.workflow.workflowInstanceId), dispatchContext);
181
+ return result.kind === 'no-work' || result.kind === WorkflowStatus.Waiting
182
+ ? {
183
+ kind: WorkflowStatus.Waiting,
184
+ workflowInstanceId: recovery.item.workflow.workflowInstanceId,
185
+ }
186
+ : result;
187
+ }
164
188
  if (await advancementWasDurablyApplied(orchestration, recovery.item.workflow.workflowInstanceId, recovery.item.activation.activationId))
165
189
  throw error;
166
190
  const reason = await blockIsolatedWorkflow(orchestration, recovery.item.workflow.workflowInstanceId, error, context(recovery.run.runId));
167
- const result = await runDispatchLoop(pending.filter((item) => item.workflow.workflowInstanceId !== recovery.item.workflow.workflowInstanceId), {
168
- orchestration,
169
- execution,
170
- resources,
171
- dispatchPolicy,
172
- maxConcurrentRuns,
173
- maxOpenWorkItems: dependencies.maxOpenWorkItems ?? null,
174
- work: dependencies.work,
175
- maxDispatches,
176
- runnerIneligibility,
177
- isDispatchPaused,
178
- commandContext: context,
179
- });
191
+ const result = await runDispatchLoop(pending.filter((item) => item.workflow.workflowInstanceId !== recovery.item.workflow.workflowInstanceId), dispatchContext);
180
192
  return result.kind === 'progressed'
181
193
  ? result
182
194
  : {
@@ -186,19 +198,7 @@ export function createActivationScheduler(orchestration, execution, resources, c
186
198
  };
187
199
  }
188
200
  }
189
- const result = await runDispatchLoop(pending, {
190
- orchestration,
191
- execution,
192
- resources,
193
- dispatchPolicy,
194
- maxConcurrentRuns,
195
- maxOpenWorkItems: dependencies.maxOpenWorkItems ?? null,
196
- work: dependencies.work,
197
- maxDispatches,
198
- runnerIneligibility,
199
- isDispatchPaused,
200
- commandContext: context,
201
- });
201
+ const result = await runDispatchLoop(pending, dispatchContext);
202
202
  if (expired.length === 0 ||
203
203
  (result.kind !== 'no-work' && result.kind !== WorkflowStatus.Waiting))
204
204
  return result;
@@ -221,18 +221,3 @@ export function createActivationScheduler(orchestration, execution, resources, c
221
221
  dispatch: (options, signal) => serialise(() => dispatch(options), signal),
222
222
  };
223
223
  }
224
- function createInProcessSerialiser() {
225
- let prior = Promise.resolve();
226
- return async (operation, signal) => {
227
- const current = prior.then(async () => {
228
- throwIfAborted(signal);
229
- return operation();
230
- });
231
- prior = current.then(() => undefined, () => undefined);
232
- return current;
233
- };
234
- }
235
- function throwIfAborted(signal) {
236
- if (signal?.aborted)
237
- throw signal.reason ?? new Error('Activation scheduler run aborted');
238
- }
@@ -1,5 +1,4 @@
1
1
  import type { CommandContext } from '@atolis-hq/eventing';
2
- import { type ActivityOutcome } from '../../activities/index.js';
3
2
  import type { ActivityActivationView, PendingActivationPriority, WorkflowInstanceView } from '../../orchestration/index.js';
4
3
  import type { ResourceService } from '../../resources/index.js';
5
4
  import type { AdvanceResult } from '../contracts/views.js';
@@ -29,18 +28,6 @@ interface PendingActivation {
29
28
  export declare function advancementWasDurablyApplied(orchestration: OrchestrationPort, workflowInstanceId: WorkflowInstanceView['workflowInstanceId'], activationId: ActivityActivationView['activationId']): Promise<boolean>;
30
29
  export declare function isolatedWorkflowReason(error: unknown): string;
31
30
  export declare function blockIsolatedWorkflow(orchestration: OrchestrationPort, workflowInstanceId: string, error: unknown, context: CommandContext): Promise<string>;
32
- export declare function isRunnerQuotaOutcome(outcome: ActivityOutcome): boolean;
33
- export declare function runnerQuotaMessage(outcome: ActivityOutcome): string;
34
- /**
35
- * A quota retry deliberately leaves the outcome unaccepted, so a port that
36
- * never applied it (absent method, or a workflow instance that vanished)
37
- * leaves the Run permanently unresolved. Surface that rather than going
38
- * silent; it is an operational defect, not a workflow state.
39
- */
40
- export declare function reportUnappliedRunnerQuotaRetry(result: unknown, input: {
41
- readonly activationId: string;
42
- readonly runId: string;
43
- }): void;
44
31
  /**
45
32
  * Fills open capacity within one Advancement call: dispatches ready
46
33
  * activations one at a time, rechecking `maxConcurrentRuns` and reselecting
@@ -1,6 +1,6 @@
1
- import { ActivityFailureCode, ActivityOutcomeKind, } from '../../activities/index.js';
1
+ import { isRunnerQuotaOutcome, reportUnappliedRunnerQuotaRetry, runnerQuotaMessage, } from './runner-quota-outcome.js';
2
2
  import { ActivationClaimConflictError, isActiveRunStatus, NoEligibleRunnerError, RunStatus, WorkspaceMode, } from '../../execution/index.js';
3
- import { WorkflowStatus } from '../../orchestration/index.js';
3
+ import { DelegationPendingError, WorkflowStatus } from '../../orchestration/index.js';
4
4
  import { canDispatchWorkItem, readOpenWorkItemIds, } from '../domain/open-work-policy.js';
5
5
  import { isExecutionFailureTerminal } from './execution-reconciliation.js';
6
6
  // Ports without priority (older fakes) rank neutrally and fall back to oldest-first.
@@ -27,28 +27,6 @@ export async function blockIsolatedWorkflow(orchestration, workflowInstanceId, e
27
27
  await orchestration.block(workflowInstanceId, reason, context);
28
28
  return reason;
29
29
  }
30
- export function isRunnerQuotaOutcome(outcome) {
31
- return (outcome.kind === ActivityOutcomeKind.Failed &&
32
- typeof outcome.data === 'object' &&
33
- outcome.data !== null &&
34
- 'reason' in outcome.data &&
35
- outcome.data.reason === ActivityFailureCode.RunnerQuotaExceeded);
36
- }
37
- export function runnerQuotaMessage(outcome) {
38
- const data = outcome.data;
39
- return typeof data.message === 'string' ? data.message : 'runner reported quota exhaustion';
40
- }
41
- /**
42
- * A quota retry deliberately leaves the outcome unaccepted, so a port that
43
- * never applied it (absent method, or a workflow instance that vanished)
44
- * leaves the Run permanently unresolved. Surface that rather than going
45
- * silent; it is an operational defect, not a workflow state.
46
- */
47
- export function reportUnappliedRunnerQuotaRetry(result, input) {
48
- if (result !== null && result !== undefined)
49
- return;
50
- console.error(`Runner-quota retry was not applied for activation ${input.activationId} (run ${input.runId}); its outcome remains unaccepted.`);
51
- }
52
30
  /**
53
31
  * Fills open capacity within one Advancement call: dispatches ready
54
32
  * activations one at a time, rechecking `maxConcurrentRuns` and reselecting
@@ -181,6 +159,14 @@ export async function runDispatchLoop(pending, ctx) {
181
159
  dispatchedIds.add(selected.activation.activationId);
182
160
  }
183
161
  catch (error) {
162
+ if (error instanceof DelegationPendingError) {
163
+ isolatedIds.add(selected.workflow.workflowInstanceId);
164
+ stopReason = {
165
+ kind: WorkflowStatus.Waiting,
166
+ workflowInstanceId: selected.workflow.workflowInstanceId,
167
+ };
168
+ continue;
169
+ }
184
170
  if (error instanceof ActivationClaimConflictError) {
185
171
  stopReason = { kind: 'no-work' };
186
172
  break;
@@ -0,0 +1 @@
1
+ export declare function createInProcessSerialiser(): <Value>(operation: () => Promise<Value>, signal?: AbortSignal) => Promise<Value>;
@@ -0,0 +1,15 @@
1
+ export function createInProcessSerialiser() {
2
+ let prior = Promise.resolve();
3
+ return async (operation, signal) => {
4
+ const current = prior.then(async () => {
5
+ throwIfAborted(signal);
6
+ return operation();
7
+ });
8
+ prior = current.then(() => undefined, () => undefined);
9
+ return current;
10
+ };
11
+ }
12
+ function throwIfAborted(signal) {
13
+ if (signal?.aborted)
14
+ throw signal.reason ?? new Error('Activation scheduler run aborted');
15
+ }
@@ -0,0 +1,13 @@
1
+ import { type ActivityOutcome } from '../../activities/index.js';
2
+ export declare function isRunnerQuotaOutcome(outcome: ActivityOutcome): boolean;
3
+ export declare function runnerQuotaMessage(outcome: ActivityOutcome): string;
4
+ /**
5
+ * A quota retry deliberately leaves the outcome unaccepted, so a port that
6
+ * never applied it (absent method, or a workflow instance that vanished)
7
+ * leaves the Run permanently unresolved. Surface that rather than going
8
+ * silent; it is an operational defect, not a workflow state.
9
+ */
10
+ export declare function reportUnappliedRunnerQuotaRetry(result: unknown, input: {
11
+ readonly activationId: string;
12
+ readonly runId: string;
13
+ }): void;
@@ -0,0 +1,23 @@
1
+ import { ActivityFailureCode, ActivityOutcomeKind, } from '../../activities/index.js';
2
+ export function isRunnerQuotaOutcome(outcome) {
3
+ return (outcome.kind === ActivityOutcomeKind.Failed &&
4
+ typeof outcome.data === 'object' &&
5
+ outcome.data !== null &&
6
+ 'reason' in outcome.data &&
7
+ outcome.data.reason === ActivityFailureCode.RunnerQuotaExceeded);
8
+ }
9
+ export function runnerQuotaMessage(outcome) {
10
+ const data = outcome.data;
11
+ return typeof data.message === 'string' ? data.message : 'runner reported quota exhaustion';
12
+ }
13
+ /**
14
+ * A quota retry deliberately leaves the outcome unaccepted, so a port that
15
+ * never applied it (absent method, or a workflow instance that vanished)
16
+ * leaves the Run permanently unresolved. Surface that rather than going
17
+ * silent; it is an operational defect, not a workflow state.
18
+ */
19
+ export function reportUnappliedRunnerQuotaRetry(result, input) {
20
+ if (result !== null && result !== undefined)
21
+ return;
22
+ console.error(`Runner-quota retry was not applied for activation ${input.activationId} (run ${input.runId}); its outcome remains unaccepted.`);
23
+ }
@@ -10,5 +10,7 @@ export declare class AcceptSignal {
10
10
  private readonly work;
11
11
  constructor(repository: OrchestrationRepository, workflows: StartWorkflow, work: WorkService);
12
12
  wait(workflowInstanceId: WorkflowInstanceId, expectation: SignalExpectation, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView>;
13
- execute(workflowInstanceId: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView>;
13
+ execute(workflowInstanceId: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext & {
14
+ readonly expectedSequence?: number;
15
+ }): Promise<import("../index.js").WorkflowInstanceView>;
14
16
  }
@@ -21,6 +21,8 @@ export class AcceptSignal {
21
21
  }
22
22
  async execute(workflowInstanceId, signal, context) {
23
23
  const loaded = await this.repository.loadRequired(workflowInstanceId);
24
+ if (context.expectedSequence !== undefined && context.expectedSequence !== loaded.sequence)
25
+ return loaded.view;
24
26
  const expiry = expireTimedOutAwait(loaded.view, {
25
27
  occurredAt: context.occurredAt,
26
28
  causationId: context.commandId,
@@ -22,7 +22,6 @@ export declare class AdvanceWorkflow {
22
22
  markActivationStarted(id: WorkflowInstanceId, activationId: ActivationId, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
23
23
  blockAwaitingActivation(id: WorkflowInstanceId, activationId: ActivationId, reason: string, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
24
24
  block(id: WorkflowInstanceId, reason: string, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
25
- expireTimedOutWaits(context: CommandContext): Promise<import("../index.js").WorkflowInstanceView[]>;
26
25
  resolveExecutionFailure(id: WorkflowInstanceId, input: ExecutionFailureInput, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
27
26
  retryRunnerQuotaFailure(id: WorkflowInstanceId, input: {
28
27
  readonly activationId: ActivationId;
@@ -6,7 +6,6 @@ import { workflowEventData } from '../domain/decision-events.js';
6
6
  import { requestChangesResume as decideChangesResume, requestFreshOperatorRetry as decideFreshOperatorRetry, requestOperatorRetry as decideOperatorRetry, requestSupplementalActivity as decideSupplementalActivity, isNeedsClarificationResumeEligible, requestRunnerQuotaRetry, } from '../domain/interpreter.js';
7
7
  import { isAuthorisedActor } from '../domain/supplemental-policy.js';
8
8
  import { appendWithIntentRecovery } from './durable-append.js';
9
- import { expireTimedOutWaits } from './expire-timed-out-waits.js';
10
9
  import { attributeOperatorRetry } from './operator-retry-attribution.js';
11
10
  import { prioritisePendingActivations, } from './pending-activations.js';
12
11
  import { resolveExecutionFailure, } from './resolve-execution-failure.js';
@@ -94,9 +93,6 @@ export class AdvanceWorkflow {
94
93
  await this.repository.append(id, loaded.sequence, [event]);
95
94
  return (await this.repository.load(id)).view;
96
95
  }
97
- async expireTimedOutWaits(context) {
98
- return expireTimedOutWaits(this.repository, context);
99
- }
100
96
  resolveExecutionFailure(id, input, context) {
101
97
  return resolveExecutionFailure(this.repository, this.acceptOutcome, id, input, context);
102
98
  }
@@ -0,0 +1,21 @@
1
+ import { type CommandContext } from '@atolis-hq/eventing';
2
+ import type { TransitionTarget } from '../contracts/config.js';
3
+ import { type OrchestrationSignal } from '../contracts/events.js';
4
+ import type { WorkflowInstanceId } from '../contracts/identifiers.js';
5
+ import type { WorkflowInstanceView } from '../contracts/views.js';
6
+ import type { OrchestrationRepository } from './orchestration-repository.js';
7
+ /** Retains authority-bearing inputs while delegation owns advancement; ordinary wait validation replays them. */
8
+ export declare class DeferredSignals {
9
+ private readonly repository;
10
+ private readonly deliver;
11
+ private readonly transition;
12
+ private readonly fenced;
13
+ private readonly ledger;
14
+ constructor(repository: OrchestrationRepository, deliver: (id: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext) => Promise<WorkflowInstanceView>, transition: (id: WorkflowInstanceId, target: TransitionTarget, evidenceId: string, context: CommandContext) => Promise<WorkflowInstanceView | null>, fenced: (id: WorkflowInstanceId) => Promise<boolean>);
15
+ accept(id: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext): Promise<WorkflowInstanceView>;
16
+ applyTransition(id: WorkflowInstanceId, target: TransitionTarget, evidenceId: string, context: CommandContext): Promise<WorkflowInstanceView | null>;
17
+ private record;
18
+ private hasDeferred;
19
+ reconcile(context: CommandContext): Promise<void>;
20
+ reconcileWorkflow(id: WorkflowInstanceId, context: CommandContext): Promise<WorkflowInstanceView>;
21
+ }
@@ -0,0 +1,119 @@
1
+ import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
2
+ import { DelegationPendingError } from '../contracts/delegation.js';
3
+ import { signalSchema } from '../contracts/event-decoder.js';
4
+ import { OrchestrationEventType, ResourceTransitionSignal, } from '../contracts/events.js';
5
+ import { DelegationLedger } from './delegation-ledger.js';
6
+ /** Retains authority-bearing inputs while delegation owns advancement; ordinary wait validation replays them. */
7
+ export class DeferredSignals {
8
+ repository;
9
+ deliver;
10
+ transition;
11
+ fenced;
12
+ ledger;
13
+ constructor(repository, deliver, transition, fenced) {
14
+ this.repository = repository;
15
+ this.deliver = deliver;
16
+ this.transition = transition;
17
+ this.fenced = fenced;
18
+ this.ledger = new DelegationLedger(repository);
19
+ }
20
+ async accept(id, signal, context) {
21
+ const scope = (await this.repository.loadRequired(id)).view;
22
+ try {
23
+ return await this.deliver(id, signal, context);
24
+ }
25
+ catch (error) {
26
+ if (!(error instanceof DelegationPendingError))
27
+ throw error;
28
+ return this.record(id, signal, context, scope);
29
+ }
30
+ }
31
+ async applyTransition(id, target, evidenceId, context) {
32
+ const scope = (await this.repository.loadRequired(id)).view;
33
+ try {
34
+ return await this.transition(id, target, evidenceId, context);
35
+ }
36
+ catch (error) {
37
+ if (!(error instanceof DelegationPendingError))
38
+ throw error;
39
+ return this.record(id, {
40
+ kind: scope.waitingFor?.signalKind ?? ResourceTransitionSignal,
41
+ actorId: 'resource-transition',
42
+ actorDecision: { authorized: true, evidenceId },
43
+ providerEventId: evidenceId,
44
+ }, context, scope, target);
45
+ }
46
+ }
47
+ async record(id, signal, context, view, target) {
48
+ const parsed = signalSchema.parse(signal);
49
+ await this.ledger.appendOnce(id, context, `defer:${signal.providerEventId}`, {
50
+ eventType: OrchestrationEventType.SignalDeferred,
51
+ payload: {
52
+ stage: view.currentStage,
53
+ ...(view.waitingFor?.intentEventId === undefined
54
+ ? {}
55
+ : { intentEventId: view.waitingFor.intentEventId }),
56
+ ...(view.waitingFor?.resourceId === undefined
57
+ ? {}
58
+ : { resourceId: view.waitingFor.resourceId }),
59
+ ...(view.waitingFor?.revision === undefined ? {} : { revision: view.waitingFor.revision }),
60
+ signal: parsed,
61
+ ...(target === undefined ? {} : { target }),
62
+ },
63
+ });
64
+ return view;
65
+ }
66
+ async hasDeferred() {
67
+ return (await this.repository.events()).some((entry) => entry.event.eventType === OrchestrationEventType.SignalDeferred);
68
+ }
69
+ async reconcile(context) {
70
+ if (!(await this.hasDeferred()))
71
+ return;
72
+ for (const loaded of await this.repository.list()) {
73
+ if (loaded.view !== null)
74
+ await this.reconcileWorkflow(loaded.view.workflowInstanceId, context);
75
+ }
76
+ }
77
+ async reconcileWorkflow(id, context) {
78
+ if ((await this.hasDeferred()) && !(await this.fenced(id))) {
79
+ const { events } = await this.repository.history(id);
80
+ for (const event of events) {
81
+ if (event?.event.eventType !== OrchestrationEventType.SignalDeferred)
82
+ continue;
83
+ const deferred = event.event.payload;
84
+ const loaded = await this.repository.loadRequired(id);
85
+ const view = loaded.view;
86
+ if (!matchesDeferredWait(view, deferred))
87
+ continue;
88
+ const deliveryContext = {
89
+ ...context,
90
+ commandId: `replay:${event.event.eventId}`,
91
+ expectedSequence: loaded.sequence,
92
+ correlationId: event.event.correlationId,
93
+ actor: event.event.actor,
94
+ };
95
+ try {
96
+ if (deferred.target === undefined)
97
+ await this.deliver(id, deferred.signal, deliveryContext);
98
+ else
99
+ await this.transition(id, deferred.target, deferred.signal.providerEventId, deliveryContext);
100
+ }
101
+ catch (error) {
102
+ if (!(error instanceof DelegationPendingError) &&
103
+ !(error instanceof WrongExpectedSequenceError))
104
+ throw error;
105
+ break;
106
+ }
107
+ }
108
+ }
109
+ return (await this.repository.loadRequired(id)).view;
110
+ }
111
+ }
112
+ function matchesDeferredWait(view, deferred) {
113
+ return (!view.acceptedSignalIds.includes(deferred.signal.providerEventId) &&
114
+ view.currentStage === deferred.stage &&
115
+ view.waitingFor !== undefined &&
116
+ view.waitingFor.intentEventId === deferred.intentEventId &&
117
+ view.waitingFor.resourceId === deferred.resourceId &&
118
+ view.waitingFor.revision === deferred.revision);
119
+ }
@@ -0,0 +1,51 @@
1
+ import { type CommandContext } from '@atolis-hq/eventing';
2
+ import { type WorkService } from '../../work/index.js';
3
+ import type { DelegationArtifacts } from '../contracts/delegation-ports.js';
4
+ import type { DelegatedAssignment, DelegationCaller, DelegationLimits, DelegationReservation, DelegationResult } from '../contracts/delegation.js';
5
+ import { type WorkflowInstanceId } from '../contracts/identifiers.js';
6
+ import type { WorkflowInstanceView } from '../contracts/views.js';
7
+ import type { CoordinationClaims } from './coordination-claims.js';
8
+ import type { OrchestrationRepository } from './orchestration-repository.js';
9
+ import type { StartWorkflow } from './start-workflow.js';
10
+ import type { WorkflowDefinitionRegistry } from './workflow-definition-registry.js';
11
+ /**
12
+ * Durable delegation of independent child WorkItems. Reservation is the single commit point;
13
+ * every later boundary is reconciled idempotently from it, and the parent stays fenced until join.
14
+ */
15
+ export declare class DelegatedWork {
16
+ private readonly repository;
17
+ private readonly work;
18
+ private readonly claims;
19
+ private readonly definitions;
20
+ private readonly workflows;
21
+ private readonly ledger;
22
+ private readonly artifacts;
23
+ private readonly runHasEnded;
24
+ constructor(repository: OrchestrationRepository, work: WorkService, claims: CoordinationClaims, definitions: WorkflowDefinitionRegistry, workflows: StartWorkflow, dependencies: {
25
+ readonly artifacts: DelegationArtifacts;
26
+ readonly runHasEnded: (runId: string) => Promise<boolean>;
27
+ });
28
+ contextWorkItems(parent: WorkflowInstanceView): Promise<ReadonlySet<string>>;
29
+ results(id: WorkflowInstanceId, cohortId: string): Promise<readonly DelegationResult[]>;
30
+ reserve(caller: DelegationCaller, cohortId: string, assignments: readonly DelegatedAssignment[], context: CommandContext, limits?: DelegationLimits): Promise<DelegationReservation>;
31
+ reconcile(context: CommandContext): Promise<void>;
32
+ private capacityReservations;
33
+ private parentIdentity;
34
+ private assertReservable;
35
+ /** Validates inputs and pins the selected definition before anything is committed. */
36
+ private prepareChild;
37
+ /** Appends the reservation only if the root stream is unchanged since `events` was read. */
38
+ private commit;
39
+ private reconcileReservation;
40
+ private ensureWait;
41
+ private fail;
42
+ /** WorkItem, primary claim and artifact grant are each idempotent; none starts a workflow. */
43
+ private registerChildren;
44
+ /** Starts the pinned definition, then records the result only once the child qualifies. */
45
+ private advanceChild;
46
+ private childWorkTerminated;
47
+ private missingOutputs;
48
+ private endedRun;
49
+ /** Join and continuation commit together, so a duplicate trigger cannot resume the parent twice. */
50
+ private join;
51
+ }