@atolis-hq/wake 0.4.77 → 0.4.79

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 (78) hide show
  1. package/dist/src/activities/contracts/event-schema.d.ts +30 -0
  2. package/dist/src/activities/contracts/event-schema.js +8 -2
  3. package/dist/src/activities/contracts/events.d.ts +3 -1
  4. package/dist/src/activities/pr/application.js +6 -3
  5. package/dist/src/activities/pr/contracts.d.ts +3 -1
  6. package/dist/src/activities/pr/event-data.js +4 -1
  7. package/dist/src/activities/pr/projection.js +4 -1
  8. package/dist/src/activities/pr/vocabulary.d.ts +6 -0
  9. package/dist/src/activities/pr/vocabulary.js +5 -0
  10. package/dist/src/bootstrap/composition-root.js +2 -2
  11. package/dist/src/bootstrap/config/root-schema.d.ts +18 -0
  12. package/dist/src/bootstrap/resource-transition-evidence.js +20 -14
  13. package/dist/src/bootstrap/version.js +1 -1
  14. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +2 -1
  15. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +2 -1
  16. package/dist/src/control-plane/application/advance-once-dispatch.js +7 -0
  17. package/dist/src/control-plane/domain/dispatch-policy.d.ts +6 -0
  18. package/dist/src/control-plane/domain/dispatch-policy.js +4 -1
  19. package/dist/src/integrations/application/agent-run-publication-reactor.d.ts +1 -0
  20. package/dist/src/integrations/application/agent-run-publication-reactor.js +49 -25
  21. package/dist/src/integrations/application/agent-run-publication-report.d.ts +10 -0
  22. package/dist/src/integrations/application/agent-run-publication-report.js +53 -0
  23. package/dist/src/integrations/application/terminal-agent-run-report.d.ts +4 -0
  24. package/dist/src/integrations/application/terminal-agent-run-report.js +4 -0
  25. package/dist/src/integrations/delivery/contracts/intents.d.ts +2 -0
  26. package/dist/src/integrations/delivery/contracts/intents.js +2 -0
  27. package/dist/src/integrations/github/application/agent-run-comment.d.ts +2 -0
  28. package/dist/src/integrations/github/application/agent-run-comment.js +26 -5
  29. package/dist/src/integrations/github/application/pull-request-translation.js +1 -0
  30. package/dist/src/integrations/github/contracts/events.d.ts +2 -1
  31. package/dist/src/integrations/github/contracts/events.js +8 -1
  32. package/dist/src/integrations/github/contracts/payloads.d.ts +1 -0
  33. package/dist/src/integrations/github/infrastructure/client-reads.d.ts +18 -6
  34. package/dist/src/integrations/github/infrastructure/client-reads.js +6 -1
  35. package/dist/src/integrations/github/infrastructure/client.d.ts +18 -6
  36. package/dist/src/integrations/github/infrastructure/consecutive-pr-observations.d.ts +4 -0
  37. package/dist/src/integrations/github/infrastructure/consecutive-pr-observations.js +33 -0
  38. package/dist/src/integrations/github/infrastructure/pr-source.js +6 -1
  39. package/dist/src/integrations/github/infrastructure/source.d.ts +6 -2
  40. package/dist/src/integrations/github/infrastructure/source.js +9 -9
  41. package/dist/src/integrations/github/provider.js +1 -0
  42. package/dist/src/orchestration/application/advance-workflow.d.ts +4 -5
  43. package/dist/src/orchestration/application/advance-workflow.js +6 -6
  44. package/dist/src/orchestration/application/orchestration-service.d.ts +4 -6
  45. package/dist/src/orchestration/application/orchestration-service.js +3 -3
  46. package/dist/src/orchestration/application/pending-activations.d.ts +13 -0
  47. package/dist/src/orchestration/application/pending-activations.js +32 -0
  48. package/dist/src/orchestration/application/policy-blocked-merge-recovery.d.ts +5 -0
  49. package/dist/src/orchestration/application/policy-blocked-merge-recovery.js +108 -21
  50. package/dist/src/orchestration/application/pull-request-transition-evidence.js +22 -1
  51. package/dist/src/orchestration/application/resource-transition-evidence.d.ts +6 -1
  52. package/dist/src/orchestration/application/resource-transition-matching.d.ts +5 -0
  53. package/dist/src/orchestration/application/resource-transition-matching.js +24 -1
  54. package/dist/src/orchestration/contracts/config.d.ts +43 -1
  55. package/dist/src/orchestration/contracts/config.js +9 -1
  56. package/dist/src/orchestration/contracts/event-decoder.d.ts +6 -0
  57. package/dist/src/orchestration/contracts/event-decoder.js +7 -1
  58. package/dist/src/orchestration/contracts/events.d.ts +2 -0
  59. package/dist/src/orchestration/contracts/views.d.ts +1 -0
  60. package/dist/src/orchestration/domain/compiler.js +4 -13
  61. package/dist/src/orchestration/domain/decision-events.d.ts +1 -0
  62. package/dist/src/orchestration/domain/decision-events.js +1 -0
  63. package/dist/src/orchestration/domain/dispatch-priority.d.ts +9 -0
  64. package/dist/src/orchestration/domain/dispatch-priority.js +16 -0
  65. package/dist/src/orchestration/domain/resource-transition-compiler.js +1 -0
  66. package/dist/src/orchestration/domain/runner-quota-retry-policy.js +1 -0
  67. package/dist/src/orchestration/domain/signal-policy.d.ts +2 -0
  68. package/dist/src/orchestration/domain/signal-policy.js +10 -4
  69. package/dist/src/orchestration/domain/transition-target.d.ts +4 -0
  70. package/dist/src/orchestration/domain/transition-target.js +14 -0
  71. package/dist/src/orchestration/domain/transition.d.ts +1 -1
  72. package/dist/src/orchestration/domain/transition.js +4 -3
  73. package/dist/src/orchestration/domain/workflow-graph.d.ts +8 -0
  74. package/dist/src/orchestration/domain/workflow-graph.js +41 -0
  75. package/dist/src/orchestration/domain/workflow-instance-events.js +1 -0
  76. package/dist/src/orchestration/index.d.ts +3 -0
  77. package/dist/src/orchestration/index.js +3 -0
  78. package/package.json +1 -1
@@ -1,39 +1,26 @@
1
- import { ActivityEventType, ActivityOutcomeKind, BuiltInActivityName, PullRequestState, readMergePolicyDenial, } from '../../activities/index.js';
1
+ import { ActivityEventType, ActivityOutcomeKind, BuiltInActivityName, PullRequestMergeability, PullRequestState, readMergePolicyDenial, } from '../../activities/index.js';
2
+ import { OrchestrationEventType, ResourceTransitionSignal, WatchGateVerdictSignal, } from '../contracts/events.js';
2
3
  import { TransitionTargetKind, WorkflowStatus } from '../contracts/vocabulary.js';
4
+ import { stateDraft } from '../domain/decision-events.js';
3
5
  import { acceptResourceTransition } from './resource-transition-matching.js';
4
6
  export async function recoverPolicyBlockedMerges(repository, workflows, evidence, context) {
5
7
  for (const loaded of await repository.list()) {
6
8
  const view = loaded.view;
7
- if (view === null || !isPolicyBlockedMergeWait(view))
9
+ if (view === null || !isMergeWait(view))
8
10
  continue;
9
11
  const definition = await workflows.definitionForOperation(view, loaded.sequence, context);
10
12
  if (definition === null)
11
13
  continue;
12
14
  const stage = definition.stages[view.currentStage];
13
- if (!isBlockedRouteWait(stage, view))
15
+ if (stage === undefined || !isConfiguredMergeWait(stage, view))
14
16
  continue;
15
- // The pinned definition supplies the completion destination, never current config.
16
- const transitions = mergedTransitions(stage);
17
- const activationId = view.acceptedOutcomes.at(-1);
18
- if (transitions === undefined || transitions.length !== 1 || activationId === undefined)
17
+ if (await reconcileMergeProblem(repository, workflows, evidence, loaded, definition, context))
19
18
  continue;
20
- const resolved = await evidence.resolve({
21
- workItemId: view.workItemId,
22
- transitions,
23
- mergeDenialActivationId: activationId,
24
- });
25
- if (resolved === null)
26
- continue;
27
- await acceptResourceTransition(repository, workflows, view.workflowInstanceId, resolved.transition.target, resolved.evidenceId, { ...context, expectedSequence: loaded.sequence });
19
+ await recoverMergedPolicyWait(repository, workflows, evidence, loaded, stage, context);
28
20
  }
29
21
  }
30
22
  export function isPolicyBlockedMergeWait(view) {
31
- return (view.status === WorkflowStatus.Waiting &&
32
- view.parentWorkflowInstanceId === undefined &&
33
- view.waitingFor !== undefined &&
34
- view.waitingFor.intentEventId === undefined &&
35
- view.pendingActivation?.activity === BuiltInActivityName.PullRequestMerge &&
36
- readMergePolicyDenial(view.lastOutcome) !== null);
23
+ return isMergeWait(view) && readMergePolicyDenial(view.lastOutcome) !== null;
37
24
  }
38
25
  function isBlockedRouteWait(stage, view) {
39
26
  const blocked = stage?.on[ActivityOutcomeKind.Blocked];
@@ -52,3 +39,103 @@ function isMergedTransition(transition) {
52
39
  function mergedTransitions(stage) {
53
40
  return stage?.on[ActivityOutcomeKind.Done]?.resourceTransitions?.filter(isMergedTransition);
54
41
  }
42
+ export const MergeWaitBlockReason = {
43
+ Closed: 'merge.pr-closed-unmerged: primary PR was closed without merging; restore the PR and resolve the workflow explicitly',
44
+ Conflict: 'merge.pr-conflicting: primary PR conflicts with its base; no safe bounded repair route in the pinned workflow',
45
+ Exhausted: 'merge.conflict-retry-exhausted: bounded conflict repair exhausted; resolve the PR and workflow explicitly',
46
+ };
47
+ async function reconcileMergeProblem(repository, workflows, evidence, loaded, definition, context) {
48
+ const view = loaded.view;
49
+ const observed = await evidence.mergeWaitState?.(view.workItemId);
50
+ if (observed === undefined || observed === null || observed.state === PullRequestState.Merged)
51
+ return false;
52
+ if (observed.state === PullRequestState.Closed) {
53
+ await blockMergeWait(repository, loaded, MergeWaitBlockReason.Closed, context);
54
+ return true;
55
+ }
56
+ if (observed.mergeability !== PullRequestMergeability.Conflicting)
57
+ return false;
58
+ const route = safeConflictRoute(definition.stages[view.currentStage], definition, view);
59
+ if (route === undefined) {
60
+ await blockMergeWait(repository, loaded, MergeWaitBlockReason.Conflict, context);
61
+ return true;
62
+ }
63
+ await acceptResourceTransition(repository, workflows, view.workflowInstanceId, route.target, `${observed.evidenceId}:${view.pendingActivation?.activationId}`, {
64
+ ...context,
65
+ expectedSequence: loaded.sequence,
66
+ retry: {
67
+ key: `${BuiltInActivityName.PullRequestMerge}:${PullRequestMergeability.Conflicting}`,
68
+ max: route.retry.max,
69
+ exhaustedReason: MergeWaitBlockReason.Exhausted,
70
+ },
71
+ });
72
+ return true;
73
+ }
74
+ async function blockMergeWait(repository, loaded, reason, context) {
75
+ const view = loaded.view;
76
+ await repository.append(view.workflowInstanceId, loaded.sequence, [
77
+ stateDraft(view, {
78
+ occurredAt: context.occurredAt,
79
+ causationId: `${context.commandId}:${view.workflowInstanceId}`,
80
+ }, { eventType: OrchestrationEventType.InstanceBlocked, payload: { reason } }, 1),
81
+ ]);
82
+ }
83
+ function isMergeWait(view) {
84
+ return (view.status === WorkflowStatus.Waiting &&
85
+ view.parentWorkflowInstanceId === undefined &&
86
+ view.pendingActivation?.activity === BuiltInActivityName.PullRequestMerge &&
87
+ view.pendingActivation.supplemental !== true &&
88
+ view.waitingFor !== undefined &&
89
+ view.waitingFor.intentEventId === undefined);
90
+ }
91
+ function isConfiguredMergeWait(stage, view) {
92
+ if (stage?.activity !== BuiltInActivityName.PullRequestMerge || view.lastOutcome === undefined)
93
+ return false;
94
+ const route = stage.on[view.lastOutcome.kind];
95
+ return route !== undefined && configuredWaitSignal(route) === view.waitingFor?.signalKind;
96
+ }
97
+ function configuredWaitSignal(route) {
98
+ if (route.watchGates !== undefined)
99
+ return WatchGateVerdictSignal;
100
+ if (route.resourceTransitions !== undefined)
101
+ return ResourceTransitionSignal;
102
+ if (route.await !== undefined)
103
+ return route.await.signal;
104
+ return route.target.kind === TransitionTargetKind.AwaitSignal ? route.target.signal : undefined;
105
+ }
106
+ function safeConflictRoute(stage, definition, view) {
107
+ const routes = stage.on[ActivityOutcomeKind.Done]?.resourceTransitions?.filter(isConflictTransition) ?? [];
108
+ const route = routes.length === 1 ? routes[0] : undefined;
109
+ if (route?.retry === undefined ||
110
+ route.retry.max > 2 ||
111
+ route.target.kind !== TransitionTargetKind.Stage)
112
+ return undefined;
113
+ if (route.target.stage === view.currentStage ||
114
+ definition.stages[route.target.stage]?.activity !== BuiltInActivityName.Agent)
115
+ return undefined;
116
+ return route;
117
+ }
118
+ function isConflictTransition(transition) {
119
+ return (transition.event === ActivityEventType.PrStateChanged &&
120
+ transition.where !== undefined &&
121
+ 'mergeability' in transition.where &&
122
+ transition.where.mergeability === PullRequestMergeability.Conflicting);
123
+ }
124
+ async function recoverMergedPolicyWait(repository, workflows, evidence, loaded, stage, context) {
125
+ const view = loaded.view;
126
+ if (!isPolicyBlockedMergeWait(view) || !isBlockedRouteWait(stage, view))
127
+ return;
128
+ // The pinned definition supplies the completion destination, never current config.
129
+ const transitions = mergedTransitions(stage);
130
+ const activationId = view.acceptedOutcomes.at(-1);
131
+ if (transitions === undefined || transitions.length !== 1 || activationId === undefined)
132
+ return;
133
+ const resolved = await evidence.resolve({
134
+ workItemId: view.workItemId,
135
+ transitions,
136
+ mergeDenialActivationId: activationId,
137
+ });
138
+ if (resolved === null)
139
+ return;
140
+ await acceptResourceTransition(repository, workflows, view.workflowInstanceId, resolved.transition.target, resolved.evidenceId, { ...context, expectedSequence: loaded.sequence });
141
+ }
@@ -1,4 +1,4 @@
1
- import { ActivityEventType, ActivityResourceRole, decidePullRequestAuthority, PullRequestCheckState, PullRequestDenialCode, PullRequestState, selectActivityEvent, selectPrimaryPullRequest, } from '../../activities/index.js';
1
+ import { ActivityEventType, ActivityResourceRole, decidePullRequestAuthority, PullRequestCheckState, PullRequestDenialCode, PullRequestMergeability, pullRequestProjection, PullRequestState, selectActivityEvent, selectPrimaryPullRequest, } from '../../activities/index.js';
2
2
  const triggers = [
3
3
  ActivityEventType.PrReviewAccepted,
4
4
  ActivityEventType.PrStateChanged,
@@ -7,6 +7,27 @@ const triggers = [
7
7
  export function createPullRequestTransitionEvidence(pullRequests) {
8
8
  return {
9
9
  triggers,
10
+ async mergeWaitState(workItemId) {
11
+ const selected = selectPrimaryPullRequest(await pullRequests.authorityInput(workItemId), workItemId);
12
+ if (selected === null)
13
+ return null;
14
+ const resourceId = selected.pullRequest.resourceId;
15
+ const facts = await pullRequests.factsFor(resourceId);
16
+ const pr = facts.reduce((view, event) => pullRequestProjection.project(view, event), pullRequestProjection.initial(resourceId));
17
+ if (pr === null)
18
+ return null;
19
+ const fact = [...facts]
20
+ .reverse()
21
+ .find((entry) => entry.event.eventType === ActivityEventType.PrStateChanged ||
22
+ entry.event.eventType === ActivityEventType.PrDiscovered);
23
+ if (fact === undefined)
24
+ return null;
25
+ return {
26
+ state: pr.state,
27
+ mergeability: pr.mergeability ?? PullRequestMergeability.Unknown,
28
+ evidenceId: fact.event.eventId,
29
+ };
30
+ },
10
31
  async resolve({ workItemId, transitions, fact, mergeDenialActivationId, }) {
11
32
  const input = await pullRequests.authorityInput(workItemId);
12
33
  const selected = selectPrimaryPullRequest(input, workItemId);
@@ -1,4 +1,4 @@
1
- import type { selectActivityEvent } from '../../activities/index.js';
1
+ import type { PullRequestMergeability, PullRequestState, selectActivityEvent } from '../../activities/index.js';
2
2
  import type { WorkItemId } from '../../work/index.js';
3
3
  import type { CompiledResourceTransition } from '../contracts/config.js';
4
4
  export type ResourceTransitionFact = Parameters<typeof selectActivityEvent>[0];
@@ -14,6 +14,11 @@ export interface ResourceTransitionEvidenceResolution {
14
14
  readonly evidenceId: string;
15
15
  }
16
16
  export interface ResourceTransitionEvidence {
17
+ mergeWaitState?(workItemId: WorkItemId): Promise<{
18
+ readonly state: PullRequestState;
19
+ readonly mergeability: PullRequestMergeability;
20
+ readonly evidenceId: string;
21
+ } | null>;
17
22
  /** Fact types the reactor tails on this policy's behalf. */
18
23
  readonly triggers: readonly string[];
19
24
  resolve(input: ResourceTransitionEvidenceInput): Promise<ResourceTransitionEvidenceResolution | null>;
@@ -17,5 +17,10 @@ export declare function matchResourceTransitions(loaded: readonly {
17
17
  }[], event: PersistedEvent): Promise<readonly ResourceTransitionMatch[]>;
18
18
  export declare function acceptResourceTransition(repository: OrchestrationRepository, workflows: StartWorkflow, id: WorkflowInstanceId, target: TransitionTarget, evidenceId: string, context: CommandContext & {
19
19
  readonly expectedSequence?: number;
20
+ readonly retry?: {
21
+ readonly key: string;
22
+ readonly max: number;
23
+ readonly exhaustedReason: string;
24
+ };
20
25
  }): Promise<WorkflowInstanceView | null>;
21
26
  export {};
@@ -1,5 +1,7 @@
1
1
  import { ActivityEventType, selectActivityEvent } from '../../activities/index.js';
2
+ import { OrchestrationEventType, } from '../contracts/events.js';
2
3
  import { WorkflowStatus } from '../contracts/vocabulary.js';
4
+ import { stateDraft } from '../domain/decision-events.js';
3
5
  import { acceptSignal as decideSignal } from '../domain/interpreter.js';
4
6
  import { appendWithIntentRecovery } from './durable-append.js';
5
7
  import { resolveTriggerWorkflowInstanceId } from './trigger-workflow-instance.js';
@@ -61,6 +63,11 @@ export async function acceptResourceTransition(repository, workflows, id, target
61
63
  const definition = await workflows.definitionForOperation(loaded.view, loaded.sequence, context);
62
64
  if (definition === null)
63
65
  return loaded.view;
66
+ const retry = retryDraft(loaded.view, evidenceId, context);
67
+ if (retry?.eventType === OrchestrationEventType.InstanceBlocked) {
68
+ await repository.append(id, loaded.sequence, [retry]);
69
+ return (await repository.load(id)).view;
70
+ }
64
71
  const decision = decideSignal(definition, { ...loaded.view, waitingFor: { ...loaded.view.waitingFor, resume: target } }, {
65
72
  signal: {
66
73
  kind: loaded.view.waitingFor.signalKind,
@@ -71,11 +78,15 @@ export async function acceptResourceTransition(repository, workflows, id, target
71
78
  occurredAt: context.occurredAt,
72
79
  causationId: `${context.commandId}:${evidenceId}`,
73
80
  consent: true,
81
+ resourceTransition: true,
74
82
  });
75
83
  if (decision.kind === 'append') {
76
84
  const recovered = await appendWithIntentRecovery({
77
85
  append: async () => {
78
- await repository.append(id, loaded.sequence, decision.events);
86
+ await repository.append(id, loaded.sequence, [
87
+ ...(retry === undefined ? [] : [retry]),
88
+ ...decision.events,
89
+ ]);
79
90
  },
80
91
  load: () => repository.load(id),
81
92
  alreadyApplied: (reloaded) => reloaded.view !== null &&
@@ -87,3 +98,15 @@ export async function acceptResourceTransition(repository, workflows, id, target
87
98
  }
88
99
  return (await repository.load(id)).view;
89
100
  }
101
+ function retryDraft(view, evidenceId, context) {
102
+ if (context.retry === undefined)
103
+ return undefined;
104
+ const retry = context.retry;
105
+ const count = (view.retryCounts[retry.key] ?? 0) + 1;
106
+ return stateDraft(view, { occurredAt: context.occurredAt, causationId: `${context.commandId}:${evidenceId}` }, count > retry.max
107
+ ? {
108
+ eventType: OrchestrationEventType.InstanceBlocked,
109
+ payload: { reason: retry.exhaustedReason },
110
+ }
111
+ : { eventType: OrchestrationEventType.RetryCounted, payload: { retryKey: retry.key, count } }, 100);
112
+ }
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { ApprovalAuthorityKind } from './vocabulary.js';
3
- import { ActivityEventType, PullRequestCheckState, PullRequestState, type ActivityName } from '../../activities/index.js';
3
+ import { ActivityEventType, PullRequestCheckState, PullRequestMergeability, PullRequestState, type ActivityName } from '../../activities/index.js';
4
4
  import { type WorkspaceMode as WorkspaceModeType } from '../../execution/index.js';
5
5
  import type { CommandName, SignalName, StageName, WatchId, WorkflowName } from './identifiers.js';
6
6
  import type { TransitionTargetKind } from './vocabulary.js';
@@ -23,6 +23,15 @@ declare const watchGateConfigSchema: z.ZodUnion<readonly [z.ZodString, z.ZodObje
23
23
  }, z.core.$strict>>;
24
24
  }, z.core.$strict>]>;
25
25
  declare const resourceTransitionConfigSchema: z.ZodUnion<readonly [z.ZodObject<{
26
+ events: z.ZodTuple<[z.ZodLiteral<"pr.state-changed">], null>;
27
+ where: z.ZodObject<{
28
+ mergeability: z.ZodLiteral<"conflicting">;
29
+ }, z.core.$strict>;
30
+ then: z.ZodString;
31
+ retry: z.ZodObject<{
32
+ max: z.ZodNumber;
33
+ }, z.core.$strict>;
34
+ }, z.core.$strict>, z.ZodObject<{
26
35
  events: z.ZodTuple<[z.ZodLiteral<"pr.review-accepted">], null>;
27
36
  then: z.ZodOptional<z.ZodString>;
28
37
  }, z.core.$strict>, z.ZodObject<{
@@ -96,6 +105,15 @@ export declare const outcomeRouteConfigSchema: z.ZodObject<{
96
105
  }, z.core.$strict>>;
97
106
  }, z.core.$strict>]>>>;
98
107
  resourceTransitions: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
108
+ events: z.ZodTuple<[z.ZodLiteral<"pr.state-changed">], null>;
109
+ where: z.ZodObject<{
110
+ mergeability: z.ZodLiteral<"conflicting">;
111
+ }, z.core.$strict>;
112
+ then: z.ZodString;
113
+ retry: z.ZodObject<{
114
+ max: z.ZodNumber;
115
+ }, z.core.$strict>;
116
+ }, z.core.$strict>, z.ZodObject<{
99
117
  events: z.ZodTuple<[z.ZodLiteral<"pr.review-accepted">], null>;
100
118
  then: z.ZodOptional<z.ZodString>;
101
119
  }, z.core.$strict>, z.ZodObject<{
@@ -150,6 +168,15 @@ export declare const stageConfigSchema: z.ZodObject<{
150
168
  }, z.core.$strict>>;
151
169
  }, z.core.$strict>]>>>;
152
170
  resourceTransitions: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
171
+ events: z.ZodTuple<[z.ZodLiteral<"pr.state-changed">], null>;
172
+ where: z.ZodObject<{
173
+ mergeability: z.ZodLiteral<"conflicting">;
174
+ }, z.core.$strict>;
175
+ then: z.ZodString;
176
+ retry: z.ZodObject<{
177
+ max: z.ZodNumber;
178
+ }, z.core.$strict>;
179
+ }, z.core.$strict>, z.ZodObject<{
153
180
  events: z.ZodTuple<[z.ZodLiteral<"pr.review-accepted">], null>;
154
181
  then: z.ZodOptional<z.ZodString>;
155
182
  }, z.core.$strict>, z.ZodObject<{
@@ -248,6 +275,15 @@ export declare const workflowDefinitionConfigSchema: z.ZodObject<{
248
275
  }, z.core.$strict>>;
249
276
  }, z.core.$strict>]>>>;
250
277
  resourceTransitions: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
278
+ events: z.ZodTuple<[z.ZodLiteral<"pr.state-changed">], null>;
279
+ where: z.ZodObject<{
280
+ mergeability: z.ZodLiteral<"conflicting">;
281
+ }, z.core.$strict>;
282
+ then: z.ZodString;
283
+ retry: z.ZodObject<{
284
+ max: z.ZodNumber;
285
+ }, z.core.$strict>;
286
+ }, z.core.$strict>, z.ZodObject<{
251
287
  events: z.ZodTuple<[z.ZodLiteral<"pr.review-accepted">], null>;
252
288
  then: z.ZodOptional<z.ZodString>;
253
289
  }, z.core.$strict>, z.ZodObject<{
@@ -334,7 +370,12 @@ export interface CompiledOutcomeRoute extends Omit<OutcomeRouteConfig, 'activiti
334
370
  }
335
371
  export interface CompiledResourceTransition {
336
372
  readonly event: typeof ActivityEventType.PrReviewAccepted | typeof ActivityEventType.PrStateChanged | typeof ActivityEventType.PrChecksChanged;
373
+ readonly retry?: {
374
+ readonly max: number;
375
+ };
337
376
  readonly where?: {
377
+ readonly mergeability: typeof PullRequestMergeability.Conflicting;
378
+ } | {
338
379
  readonly state: typeof PullRequestState.Merged;
339
380
  } | {
340
381
  readonly checks: typeof PullRequestCheckState.Failing;
@@ -358,6 +399,7 @@ export interface CompiledWatch extends Omit<WatchConfig, 'workflow' | 'while' |
358
399
  };
359
400
  }
360
401
  export interface CompiledWorkflow {
402
+ readonly remainingAgentSteps?: Readonly<Record<StageName, number>>;
361
403
  readonly name: WorkflowName;
362
404
  readonly entry: StageName;
363
405
  readonly commands: Readonly<Record<CommandName, CompiledSupplementalCommand>>;
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { ApprovalAuthorityKind, ConversationSurfaceCapability, WorkflowStatus, } from './vocabulary.js';
3
- import { ActivityEventType, PullRequestCheckState, PullRequestState, } from '../../activities/index.js';
3
+ import { ActivityEventType, PullRequestCheckState, PullRequestMergeability, PullRequestState, } from '../../activities/index.js';
4
4
  import { WorkspaceMode } from '../../execution/index.js';
5
5
  import { MatchMode } from '../../kernel/index.js';
6
6
  const identifier = z.string().trim().min(1);
@@ -33,6 +33,14 @@ const watchGateConfigSchema = z.union([
33
33
  .strict(),
34
34
  ]);
35
35
  const resourceTransitionConfigSchema = z.union([
36
+ z
37
+ .object({
38
+ events: z.tuple([z.literal(ActivityEventType.PrStateChanged)]),
39
+ where: z.object({ mergeability: z.literal(PullRequestMergeability.Conflicting) }).strict(),
40
+ then: identifier,
41
+ retry: z.object({ max: z.number().int().min(1).max(2) }).strict(),
42
+ })
43
+ .strict(),
36
44
  z
37
45
  .object({
38
46
  events: z.tuple([z.literal(ActivityEventType.PrReviewAccepted)]),
@@ -68,6 +68,7 @@ export declare const activityRequestedSchema: z.ZodObject<{
68
68
  followOnIndex: z.ZodOptional<z.ZodNumber>;
69
69
  sessionPolicy: z.ZodOptional<z.ZodLiteral<"fresh">>;
70
70
  supplemental: z.ZodOptional<z.ZodLiteral<true>>;
71
+ watchDriven: z.ZodOptional<z.ZodLiteral<true>>;
71
72
  }, z.core.$strict>;
72
73
  export declare const expectationSchema: z.ZodObject<{
73
74
  signalKind: z.ZodPipe<z.ZodString, z.ZodTransform<import("./identifiers.js").SignalName, string>>;
@@ -113,6 +114,8 @@ export declare const expectationSchema: z.ZodObject<{
113
114
  "pr.review-accepted": "pr.review-accepted";
114
115
  }>;
115
116
  where: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
117
+ mergeability: z.ZodLiteral<"conflicting">;
118
+ }, z.core.$strict>, z.ZodObject<{
116
119
  state: z.ZodLiteral<"merged">;
117
120
  }, z.core.$strict>, z.ZodObject<{
118
121
  checks: z.ZodLiteral<"failing">;
@@ -128,6 +131,9 @@ export declare const expectationSchema: z.ZodObject<{
128
131
  }, z.core.$strict>, z.ZodObject<{
129
132
  kind: z.ZodLiteral<"resource-transition-wait">;
130
133
  }, z.core.$strict>], "kind">;
134
+ retry: z.ZodOptional<z.ZodObject<{
135
+ max: z.ZodNumber;
136
+ }, z.core.$strict>>;
131
137
  }, z.core.$strict>>>;
132
138
  }, z.core.$strict>;
133
139
  export declare const signalSchema: z.ZodObject<{
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { eventDataSchema, eventEnvelopeSchema } from '@atolis-hq/eventing';
3
- import { activationId, ActivityEventType, activityName, ActivityOutcomeKind, PullRequestCheckState, PullRequestState, } from '../../activities/index.js';
3
+ import { activationId, ActivityEventType, activityName, ActivityOutcomeKind, PullRequestCheckState, PullRequestMergeability, PullRequestState, } from '../../activities/index.js';
4
4
  import { WorkspaceMode } from '../../execution/index.js';
5
5
  import { brandedStringSchema } from '../../kernel/index.js';
6
6
  import { workItemId } from '../../work/index.js';
@@ -80,6 +80,7 @@ export const activityRequestedSchema = z
80
80
  followOnIndex: z.number().int().nonnegative().optional(),
81
81
  sessionPolicy: z.literal('fresh').optional(),
82
82
  supplemental: z.literal(true).optional(),
83
+ watchDriven: z.literal(true).optional(),
83
84
  })
84
85
  .strict();
85
86
  const approvalAuthoritySchema = z.discriminatedUnion('kind', [
@@ -111,11 +112,16 @@ const resourceTransitionSchema = z
111
112
  ]),
112
113
  where: z
113
114
  .union([
115
+ z.object({ mergeability: z.literal(PullRequestMergeability.Conflicting) }).strict(),
114
116
  z.object({ state: z.literal(PullRequestState.Merged) }).strict(),
115
117
  z.object({ checks: z.literal(PullRequestCheckState.Failing) }).strict(),
116
118
  ])
117
119
  .optional(),
118
120
  target: transitionTargetSchema,
121
+ retry: z
122
+ .object({ max: z.number().int().min(1).max(2) })
123
+ .strict()
124
+ .optional(),
119
125
  })
120
126
  .strict();
121
127
  export const expectationSchema = z
@@ -184,6 +184,8 @@ export interface ActivityRequestedPayload {
184
184
  readonly sessionPolicy?: 'fresh' | undefined;
185
185
  readonly followOnIndex?: number | undefined;
186
186
  readonly supplemental?: boolean | undefined;
187
+ /** Requested as the resume of a watch- or provider-observed signal; absent means false. */
188
+ readonly watchDriven?: true | undefined;
187
189
  }
188
190
  export interface SignalExpectation {
189
191
  readonly signalKind: SignalName;
@@ -14,6 +14,7 @@ export interface ActivityActivationView {
14
14
  readonly status: ActivityActivationStatus;
15
15
  readonly followOnIndex?: number;
16
16
  readonly supplemental?: boolean;
17
+ readonly watchDriven?: true;
17
18
  }
18
19
  export interface SignalExpectationView {
19
20
  readonly signalKind: SignalName;
@@ -1,10 +1,11 @@
1
- import { ActivityEventType, activityName, ActivityOutcomeKind, } from '../../activities/index.js';
1
+ import { ActivityEventType, ActivityExecutionKind, activityName, ActivityOutcomeKind, } from '../../activities/index.js';
2
2
  import { workflowDefinitionConfigSchema, } from '../contracts/config.js';
3
3
  import { commandName, signalName, stageName, watchId, workflowName, } from '../contracts/identifiers.js';
4
4
  import { ApprovalAuthorityKind, TransitionTargetKind } from '../contracts/vocabulary.js';
5
5
  import { defaultApprovalAwait } from './approval-defaults.js';
6
6
  import { compileResourceTransitions } from './resource-transition-compiler.js';
7
- import { assertCyclesBounded, assertReachable } from './workflow-graph.js';
7
+ import { compileTarget, isReservedRouteTarget, isReservedTerminalTarget, } from './transition-target.js';
8
+ import { assertCyclesBounded, assertReachable, remainingAgentSteps } from './workflow-graph.js';
8
9
  export function compileWorkflow(name, input, activities, knownWorkflowNames = [name]) {
9
10
  const compiledName = workflowName(name);
10
11
  const config = workflowDefinitionConfigSchema.parse(input);
@@ -25,6 +26,7 @@ export function compileWorkflow(name, input, activities, knownWorkflowNames = [n
25
26
  assertReachable(compiledEntry, stages);
26
27
  assertCyclesBounded(stages);
27
28
  return Object.freeze({
29
+ remainingAgentSteps: Object.freeze(remainingAgentSteps(stages, (activity) => activities.describe(activity).executionKind === ActivityExecutionKind.Agent)),
28
30
  name: compiledName,
29
31
  entry: compiledEntry,
30
32
  commands: Object.freeze(commands),
@@ -181,14 +183,3 @@ function compileCommands(config, activities) {
181
183
  }),
182
184
  ]));
183
185
  }
184
- const isReservedRouteTarget = (target) => target === ActivityOutcomeKind.Done || target === 'await-human' || target === 'wait';
185
- const isReservedTerminalTarget = (target) => target === ActivityOutcomeKind.Done || target === 'await-human';
186
- function compileTarget(target, outcomeKind) {
187
- if (target === ActivityOutcomeKind.Done)
188
- return { kind: TransitionTargetKind.Complete };
189
- if (target === 'await-human')
190
- return { kind: TransitionTargetKind.AwaitSignal, signal: signalName(outcomeKind) };
191
- if (target === 'wait')
192
- return { kind: TransitionTargetKind.ResourceTransitionWait };
193
- return { kind: TransitionTargetKind.Stage, stage: stageName(target) };
194
- }
@@ -18,6 +18,7 @@ export declare function activation(id: WorkflowInstanceId, ordinal: number, acti
18
18
  readonly stage?: StageName;
19
19
  readonly followOnIndex?: number;
20
20
  readonly supplemental?: boolean;
21
+ readonly watchDriven?: boolean;
21
22
  }): ActivityRequestedPayload;
22
23
  type WorkflowDraftInput = {
23
24
  [Type in WorkflowOrchestrationEventName]: {
@@ -18,6 +18,7 @@ export function activation(id, ordinal, activity, input, options) {
18
18
  ...(options.sessionPolicy === undefined ? {} : { sessionPolicy: options.sessionPolicy }),
19
19
  ...(options.followOnIndex === undefined ? {} : { followOnIndex: options.followOnIndex }),
20
20
  ...(options.supplemental === true ? { supplemental: true } : {}),
21
+ ...(options.watchDriven === true ? { watchDriven: true } : {}),
21
22
  };
22
23
  }
23
24
  export function startDraft(input, event, ordinal) {
@@ -0,0 +1,9 @@
1
+ import type { CompiledStage, CompiledWorkflow } from '../contracts/config.js';
2
+ import type { ActivityActivationView, WorkflowInstanceView } from '../contracts/views.js';
3
+ export interface PendingActivationPriority {
4
+ /** Agent stages left on the cheapest path to completion, or UnreachableRemainingSteps. */
5
+ readonly remainingAgentSteps: number;
6
+ readonly watchDriven: boolean;
7
+ readonly retried: boolean;
8
+ }
9
+ export declare function pendingActivationPriority(definition: CompiledWorkflow | null, view: WorkflowInstanceView, activation: ActivityActivationView, isAgentActivity: (activity: CompiledStage['activity']) => boolean): PendingActivationPriority;
@@ -0,0 +1,16 @@
1
+ import { remainingAgentSteps, UnreachableRemainingSteps } from './workflow-graph.js';
2
+ // Retry keys are `<stage>:<outcomeKind>`; a stage is retried once any key for it has counted.
3
+ function isStageRetried(view, stage) {
4
+ return Object.entries(view.retryCounts).some(([key, count]) => count > 0 && key.startsWith(`${stage}:`));
5
+ }
6
+ export function pendingActivationPriority(definition, view, activation, isAgentActivity) {
7
+ const stage = activation.stage ?? view.currentStage;
8
+ const costs = definition === null
9
+ ? undefined
10
+ : (definition.remainingAgentSteps ?? remainingAgentSteps(definition.stages, isAgentActivity));
11
+ return {
12
+ remainingAgentSteps: costs?.[stage] ?? UnreachableRemainingSteps,
13
+ watchDriven: activation.watchDriven === true,
14
+ retried: isStageRetried(view, stage),
15
+ };
16
+ }
@@ -9,6 +9,7 @@ export function compileResourceTransitions(entries, context, allStages, isReserv
9
9
  throw new Error(`Unknown resourceTransitions target: ${then}`);
10
10
  return Object.freeze({
11
11
  event: entry.events[0],
12
+ ...(!('retry' in entry) ? {} : { retry: entry.retry }),
12
13
  ...(!('where' in entry) || entry.where === undefined ? {} : { where: entry.where }),
13
14
  target: compileTarget(then, context.outcomeKind),
14
15
  });
@@ -33,6 +33,7 @@ export function requestRunnerQuotaRetry(state, input) {
33
33
  eventType: OrchestrationEventType.ActivityRequested,
34
34
  payload: activation(state.workflowInstanceId, nextOrdinal(state), interrupted.activity, interrupted.input, {
35
35
  execution: interrupted.execution,
36
+ ...(interrupted.watchDriven === true ? { watchDriven: true } : {}),
36
37
  ...(interrupted.stage === undefined ? {} : { stage: interrupted.stage }),
37
38
  ...(interrupted.followOnIndex === undefined
38
39
  ? {}
@@ -6,6 +6,8 @@ import type { AcceptActivityOutcome, DecisionContext, OrchestrationDecision } fr
6
6
  export declare const AwaitTimeoutBlockReason = "await.timeout-exceeded";
7
7
  export interface AcceptSignal extends DecisionContext {
8
8
  readonly signal: OrchestrationSignal;
9
+ /** A confirmed resource transition can share the wait's watch-verdict channel. */
10
+ readonly resourceTransition?: true;
9
11
  readonly consent?: boolean;
10
12
  }
11
13
  export declare function waitForSignal(state: WorkflowInstanceView, expectation: SignalExpectation, input: DecisionContext): OrchestrationDecision;
@@ -1,5 +1,5 @@
1
1
  import { ActivityOutcomeKind } from '../../activities/index.js';
2
- import { OrchestrationEventType } from '../contracts/events.js';
2
+ import { OrchestrationEventType, ResourceTransitionSignal } from '../contracts/events.js';
3
3
  import { stageName } from '../contracts/identifiers.js';
4
4
  import { ActivityActivationStatus, ApprovalAuthorityKind, WorkflowStatus, } from '../contracts/vocabulary.js';
5
5
  import { activation, nextOrdinal, stateDraft } from './decision-events.js';
@@ -32,10 +32,15 @@ export function acceptSignal(definition, state, input) {
32
32
  }, 1),
33
33
  ];
34
34
  const target = signal.outcome === ActivityOutcomeKind.Rejected ? expected.onRejectResume : expected.resume;
35
+ // Human-only gate approvals are not "reacting to something"; watch verdicts and
36
+ // provider-observed resource transitions are.
37
+ const watchDriven = input.resourceTransition === true ||
38
+ authority.kind === ApprovalAuthorityKind.Watch ||
39
+ signal.kind === ResourceTransitionSignal;
35
40
  if (target !== undefined)
36
- resumeToTarget(events, definition, state, input, target);
41
+ resumeToTarget(events, definition, state, input, target, watchDriven);
37
42
  else
38
- requestLegacyReentry(events, definition, state, input);
43
+ requestLegacyReentry(events, definition, state, input, watchDriven);
39
44
  return { kind: 'append', events };
40
45
  }
41
46
  export function hasTimedOutAwait(state, occurredAt) {
@@ -61,13 +66,14 @@ export function expireTimedOutAwait(state, input) {
61
66
  ],
62
67
  };
63
68
  }
64
- function requestLegacyReentry(events, definition, state, input) {
69
+ function requestLegacyReentry(events, definition, state, input, watchDriven) {
65
70
  const stage = definition.stages[stageName(state.currentStage)];
66
71
  events.push(stateDraft(state, input, {
67
72
  eventType: OrchestrationEventType.ActivityRequested,
68
73
  payload: activation(state.workflowInstanceId, nextOrdinal(state), stage.activity, stage.with, {
69
74
  execution: stage.execution,
70
75
  stage: stageName(state.currentStage),
76
+ watchDriven,
71
77
  }),
72
78
  }, events.length + 1));
73
79
  }
@@ -0,0 +1,4 @@
1
+ import type { CompiledOutcomeRoute } from '../contracts/config.js';
2
+ export declare const isReservedRouteTarget: (target: string) => boolean;
3
+ export declare const isReservedTerminalTarget: (target: string) => boolean;
4
+ export declare function compileTarget(target: string, outcomeKind: string): CompiledOutcomeRoute['target'];
@@ -0,0 +1,14 @@
1
+ import { ActivityOutcomeKind } from '../../activities/index.js';
2
+ import { signalName, stageName } from '../contracts/identifiers.js';
3
+ import { TransitionTargetKind } from '../contracts/vocabulary.js';
4
+ export const isReservedRouteTarget = (target) => target === ActivityOutcomeKind.Done || target === 'await-human' || target === 'wait';
5
+ export const isReservedTerminalTarget = (target) => target === ActivityOutcomeKind.Done || target === 'await-human';
6
+ export function compileTarget(target, outcomeKind) {
7
+ if (target === ActivityOutcomeKind.Done)
8
+ return { kind: TransitionTargetKind.Complete };
9
+ if (target === 'await-human')
10
+ return { kind: TransitionTargetKind.AwaitSignal, signal: signalName(outcomeKind) };
11
+ if (target === 'wait')
12
+ return { kind: TransitionTargetKind.ResourceTransitionWait };
13
+ return { kind: TransitionTargetKind.Stage, stage: stageName(target) };
14
+ }