@atolis-hq/wake 0.4.77 → 0.4.78

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 (49) 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/config/root-schema.d.ts +18 -0
  11. package/dist/src/bootstrap/resource-transition-evidence.js +20 -14
  12. package/dist/src/bootstrap/version.js +1 -1
  13. package/dist/src/integrations/application/agent-run-publication-reactor.d.ts +1 -0
  14. package/dist/src/integrations/application/agent-run-publication-reactor.js +49 -25
  15. package/dist/src/integrations/application/agent-run-publication-report.d.ts +10 -0
  16. package/dist/src/integrations/application/agent-run-publication-report.js +53 -0
  17. package/dist/src/integrations/application/terminal-agent-run-report.d.ts +4 -0
  18. package/dist/src/integrations/application/terminal-agent-run-report.js +4 -0
  19. package/dist/src/integrations/delivery/contracts/intents.d.ts +2 -0
  20. package/dist/src/integrations/delivery/contracts/intents.js +2 -0
  21. package/dist/src/integrations/github/application/agent-run-comment.d.ts +2 -0
  22. package/dist/src/integrations/github/application/agent-run-comment.js +26 -5
  23. package/dist/src/integrations/github/application/pull-request-translation.js +1 -0
  24. package/dist/src/integrations/github/contracts/events.d.ts +2 -1
  25. package/dist/src/integrations/github/contracts/events.js +8 -1
  26. package/dist/src/integrations/github/contracts/payloads.d.ts +1 -0
  27. package/dist/src/integrations/github/infrastructure/client-reads.d.ts +18 -6
  28. package/dist/src/integrations/github/infrastructure/client-reads.js +6 -1
  29. package/dist/src/integrations/github/infrastructure/client.d.ts +18 -6
  30. package/dist/src/integrations/github/infrastructure/consecutive-pr-observations.d.ts +4 -0
  31. package/dist/src/integrations/github/infrastructure/consecutive-pr-observations.js +33 -0
  32. package/dist/src/integrations/github/infrastructure/pr-source.js +6 -1
  33. package/dist/src/integrations/github/infrastructure/source.d.ts +6 -2
  34. package/dist/src/integrations/github/infrastructure/source.js +9 -9
  35. package/dist/src/integrations/github/provider.js +1 -0
  36. package/dist/src/orchestration/application/policy-blocked-merge-recovery.d.ts +5 -0
  37. package/dist/src/orchestration/application/policy-blocked-merge-recovery.js +108 -21
  38. package/dist/src/orchestration/application/pull-request-transition-evidence.js +22 -1
  39. package/dist/src/orchestration/application/resource-transition-evidence.d.ts +6 -1
  40. package/dist/src/orchestration/application/resource-transition-matching.d.ts +5 -0
  41. package/dist/src/orchestration/application/resource-transition-matching.js +23 -1
  42. package/dist/src/orchestration/contracts/config.d.ts +42 -1
  43. package/dist/src/orchestration/contracts/config.js +9 -1
  44. package/dist/src/orchestration/contracts/event-decoder.d.ts +5 -0
  45. package/dist/src/orchestration/contracts/event-decoder.js +6 -1
  46. package/dist/src/orchestration/domain/resource-transition-compiler.js +1 -0
  47. package/dist/src/orchestration/index.d.ts +1 -0
  48. package/dist/src/orchestration/index.js +1 -0
  49. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import { type EventDataUnion, type EventEnvelope, type EventUnion } from '@atolis-hq/eventing';
2
- import { ProviderPermission, PullRequestCheckState, PullRequestState, ReviewActorKind, ReviewerAuthorizationSource, type ReviewerAuthorizationEvidence } from '../../../activities/index.js';
2
+ import { ProviderPermission, PullRequestCheckState, PullRequestMergeability, PullRequestState, ReviewActorKind, ReviewerAuthorizationSource, type ReviewerAuthorizationEvidence } from '../../../activities/index.js';
3
3
  import { type ResourceId } from '../../../resources/index.js';
4
4
  import { type WorkItemId } from '../../../work/index.js';
5
5
  import { ExternalWorkOutcome } from '../../contracts/outcome-vocabulary.js';
@@ -17,6 +17,7 @@ export declare const GitHubEventType: {
17
17
  readonly ConversationRecordRecovered: "integration.github.conversation-record-recovered";
18
18
  };
19
19
  export interface ExternalWorkObservedPayload {
20
+ readonly mergeability?: PullRequestMergeability | undefined;
20
21
  readonly externalKey: string;
21
22
  readonly kind: 'issue' | 'pull-request';
22
23
  readonly title: string;
@@ -1,6 +1,6 @@
1
1
  import { eventDataSchema, eventEnvelopeSchema, } from '@atolis-hq/eventing';
2
2
  import { z } from 'zod';
3
- import { ProviderPermission, PullRequestCheckState, PullRequestState, ReviewActorKind, ReviewerAuthorizationSource, } from '../../../activities/index.js';
3
+ import { ProviderPermission, PullRequestCheckState, PullRequestMergeability, PullRequestState, ReviewActorKind, ReviewerAuthorizationSource, } from '../../../activities/index.js';
4
4
  import { brandedStringSchema } from '../../../kernel/index.js';
5
5
  import { resourceId } from '../../../resources/index.js';
6
6
  import { workItemId } from '../../../work/index.js';
@@ -63,6 +63,13 @@ const githubEventSchemas = {
63
63
  state: z.enum([PullRequestState.Open, PullRequestState.Closed, PullRequestState.Merged]),
64
64
  outcome: z.enum([ExternalWorkOutcome.Completed, ExternalWorkOutcome.Cancelled]).optional(),
65
65
  revision: z.string(),
66
+ mergeability: z
67
+ .enum([
68
+ PullRequestMergeability.Unknown,
69
+ PullRequestMergeability.Mergeable,
70
+ PullRequestMergeability.Conflicting,
71
+ ])
72
+ .optional(),
66
73
  headRevision: z.string().optional(),
67
74
  baseRevision: z.string().optional(),
68
75
  checks: z
@@ -34,6 +34,7 @@ export interface GitHubIssueCommentPayload {
34
34
  readonly side?: 'LEFT' | 'RIGHT';
35
35
  }
36
36
  export interface GitHubPullRequestPayload extends GitHubIssuePayload {
37
+ readonly mergeable?: boolean | null;
37
38
  readonly pull_request?: Record<string, unknown>;
38
39
  readonly head?: {
39
40
  readonly sha?: string;
@@ -22,17 +22,17 @@ export declare function listPullRequests(octokit: Octokit, cache: ReturnType<typ
22
22
  comments_url: string;
23
23
  statuses_url: string;
24
24
  number: number;
25
- state: string;
25
+ state: "open" | "closed";
26
26
  locked: boolean;
27
27
  title: string;
28
- user: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
28
+ user: import("@octokit/openapi-types").components["schemas"]["simple-user"];
29
29
  body: string | null;
30
30
  labels: {
31
31
  id: number;
32
32
  node_id: string;
33
33
  url: string;
34
34
  name: string;
35
- description: string;
35
+ description: string | null;
36
36
  color: string;
37
37
  default: boolean;
38
38
  }[];
@@ -46,20 +46,20 @@ export declare function listPullRequests(octokit: Octokit, cache: ReturnType<typ
46
46
  assignee: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
47
47
  assignees?: import("@octokit/openapi-types").components["schemas"]["simple-user"][] | null;
48
48
  requested_reviewers?: import("@octokit/openapi-types").components["schemas"]["simple-user"][] | null;
49
- requested_teams?: import("@octokit/openapi-types").components["schemas"]["team"][] | null;
49
+ requested_teams?: import("@octokit/openapi-types").components["schemas"]["team-simple"][] | null;
50
50
  head: {
51
51
  label: string;
52
52
  ref: string;
53
53
  repo: import("@octokit/openapi-types").components["schemas"]["repository"];
54
54
  sha: string;
55
- user: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
55
+ user: import("@octokit/openapi-types").components["schemas"]["simple-user"];
56
56
  };
57
57
  base: {
58
58
  label: string;
59
59
  ref: string;
60
60
  repo: import("@octokit/openapi-types").components["schemas"]["repository"];
61
61
  sha: string;
62
- user: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
62
+ user: import("@octokit/openapi-types").components["schemas"]["simple-user"];
63
63
  };
64
64
  _links: {
65
65
  comments: import("@octokit/openapi-types").components["schemas"]["link"];
@@ -74,6 +74,18 @@ export declare function listPullRequests(octokit: Octokit, cache: ReturnType<typ
74
74
  author_association: import("@octokit/openapi-types").components["schemas"]["author-association"];
75
75
  auto_merge: import("@octokit/openapi-types").components["schemas"]["auto-merge"];
76
76
  draft?: boolean;
77
+ merged: boolean;
78
+ mergeable: boolean | null;
79
+ rebaseable?: boolean | null;
80
+ mergeable_state: string;
81
+ merged_by: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
82
+ comments: number;
83
+ review_comments: number;
84
+ maintainer_can_modify: boolean;
85
+ commits: number;
86
+ additions: number;
87
+ deletions: number;
88
+ changed_files: number;
77
89
  }, "state"> & {
78
90
  readonly state: typeof PullRequestState.Open | typeof PullRequestState.Closed;
79
91
  })[]>;
@@ -67,7 +67,12 @@ export async function listPullRequests(octokit, cache, owner, repo, maxResults)
67
67
  ...(headers === undefined ? {} : { headers }),
68
68
  }),
69
69
  });
70
- return pullRequests.map(normalizePullRequestState);
70
+ // List responses omit mergeability. Detail responses are needed even when the list ETag is unchanged.
71
+ const detailed = [];
72
+ for (const pullRequest of pullRequests) {
73
+ detailed.push(normalizePullRequestState(await getPullRequest(octokit, cache, owner, repo, pullRequest.number)));
74
+ }
75
+ return detailed;
71
76
  }
72
77
  export async function listReviews(octokit, cache, owner, repo, pullNumber, options) {
73
78
  const reviews = await fetchPaginatedWithEtag({
@@ -43,17 +43,17 @@ export declare function createGitHubClient(token: string): {
43
43
  comments_url: string;
44
44
  statuses_url: string;
45
45
  number: number;
46
- state: string;
46
+ state: "open" | "closed";
47
47
  locked: boolean;
48
48
  title: string;
49
- user: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
49
+ user: import("@octokit/openapi-types").components["schemas"]["simple-user"];
50
50
  body: string | null;
51
51
  labels: {
52
52
  id: number;
53
53
  node_id: string;
54
54
  url: string;
55
55
  name: string;
56
- description: string;
56
+ description: string | null;
57
57
  color: string;
58
58
  default: boolean;
59
59
  }[];
@@ -67,20 +67,20 @@ export declare function createGitHubClient(token: string): {
67
67
  assignee: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
68
68
  assignees?: import("@octokit/openapi-types").components["schemas"]["simple-user"][] | null;
69
69
  requested_reviewers?: import("@octokit/openapi-types").components["schemas"]["simple-user"][] | null;
70
- requested_teams?: import("@octokit/openapi-types").components["schemas"]["team"][] | null;
70
+ requested_teams?: import("@octokit/openapi-types").components["schemas"]["team-simple"][] | null;
71
71
  head: {
72
72
  label: string;
73
73
  ref: string;
74
74
  repo: import("@octokit/openapi-types").components["schemas"]["repository"];
75
75
  sha: string;
76
- user: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
76
+ user: import("@octokit/openapi-types").components["schemas"]["simple-user"];
77
77
  };
78
78
  base: {
79
79
  label: string;
80
80
  ref: string;
81
81
  repo: import("@octokit/openapi-types").components["schemas"]["repository"];
82
82
  sha: string;
83
- user: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
83
+ user: import("@octokit/openapi-types").components["schemas"]["simple-user"];
84
84
  };
85
85
  _links: {
86
86
  comments: import("@octokit/openapi-types").components["schemas"]["link"];
@@ -95,6 +95,18 @@ export declare function createGitHubClient(token: string): {
95
95
  author_association: import("@octokit/openapi-types").components["schemas"]["author-association"];
96
96
  auto_merge: import("@octokit/openapi-types").components["schemas"]["auto-merge"];
97
97
  draft?: boolean;
98
+ merged: boolean;
99
+ mergeable: boolean | null;
100
+ rebaseable?: boolean | null;
101
+ mergeable_state: string;
102
+ merged_by: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
103
+ comments: number;
104
+ review_comments: number;
105
+ maintainer_can_modify: boolean;
106
+ commits: number;
107
+ additions: number;
108
+ deletions: number;
109
+ changed_files: number;
98
110
  }, "state"> & {
99
111
  readonly state: typeof PullRequestState.Open | typeof PullRequestState.Closed;
100
112
  })[]>;
@@ -0,0 +1,4 @@
1
+ import type { EventJournal } from '@atolis-hq/eventing';
2
+ import type { AdapterId } from '../../contracts/identifiers.js';
3
+ import { type GitHubAdapterEventData } from '../contracts/events.js';
4
+ export declare function consecutivePullRequestObservations(drafts: readonly GitHubAdapterEventData[], journal: EventJournal | undefined, adapter: AdapterId | undefined): Promise<GitHubAdapterEventData[]>;
@@ -0,0 +1,33 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { integrationStream } from '../../contracts/streams.js';
3
+ import { createGitHubEventData } from '../contracts/event-factory.js';
4
+ import { GitHubEventType, selectGitHubAdapterEvent, } from '../contracts/events.js';
5
+ import { GitHubAdapter } from '../contracts/vocabulary.js';
6
+ export async function consecutivePullRequestObservations(drafts, journal, adapter) {
7
+ if (journal === undefined)
8
+ return [...drafts];
9
+ const latest = new Map();
10
+ for (const envelope of await journal.readStream(integrationStream(adapter ?? GitHubAdapter))) {
11
+ const event = selectGitHubAdapterEvent(envelope)?.event;
12
+ if (event?.eventType === GitHubEventType.WorkObserved && event.payload.kind === 'pull-request')
13
+ latest.set(event.payload.externalKey, event);
14
+ }
15
+ return drafts.flatMap((draft) => {
16
+ if (draft.eventType !== GitHubEventType.WorkObserved || draft.payload.kind !== 'pull-request')
17
+ return [draft];
18
+ const prior = latest.get(draft.payload.externalKey);
19
+ if (prior?.causationId === draft.causationId)
20
+ return [];
21
+ // Chain to durable evidence: replay stays stable, but recurring states get new identities.
22
+ const event = createGitHubEventData({
23
+ ...draft,
24
+ eventId: draft.eventId +
25
+ ':' +
26
+ createHash('sha256')
27
+ .update(prior?.eventId ?? '')
28
+ .digest('hex'),
29
+ });
30
+ latest.set(draft.payload.externalKey, event);
31
+ return [event];
32
+ });
33
+ }
@@ -1,6 +1,6 @@
1
1
  import { EventActorKind, EventSourceKind } from '@atolis-hq/eventing';
2
2
  import { createHash } from 'node:crypto';
3
- import { PullRequestCheckState, PullRequestState, ReviewActorKind, } from '../../../activities/index.js';
3
+ import { PullRequestCheckState, PullRequestMergeability, PullRequestState, ReviewActorKind, } from '../../../activities/index.js';
4
4
  import { boundedDiagnosticEvidence } from '../contracts/check-evidence.js';
5
5
  import { createGitHubEventData } from '../contracts/event-factory.js';
6
6
  import { GitHubEventType } from '../contracts/events.js';
@@ -57,6 +57,11 @@ function pullRequestObservation(input) {
57
57
  title: pullRequest.title,
58
58
  body: fallback(pullRequest.body, ''),
59
59
  state: pullRequestState(pullRequest),
60
+ mergeability: pullRequest.mergeable === false
61
+ ? PullRequestMergeability.Conflicting
62
+ : pullRequest.mergeable === true
63
+ ? PullRequestMergeability.Mergeable
64
+ : PullRequestMergeability.Unknown,
60
65
  revision,
61
66
  headRevision: revision,
62
67
  baseRevision: fallback(pullRequest.base?.sha, UnknownGitHubRevision),
@@ -1,12 +1,16 @@
1
- import type { CheckpointStore } from '@atolis-hq/eventing';
1
+ import type { CheckpointStore, EventJournal } from '@atolis-hq/eventing';
2
2
  import type { AdapterId } from '../../contracts/identifiers.js';
3
3
  import type { ExternalEventSource } from '../../contracts/intake.js';
4
4
  import type { GitHubConfig } from '../contracts/config.js';
5
+ import { type GitHubAdapterEventData } from '../contracts/events.js';
5
6
  import { type GitHubAdapterHealthRegistry } from './adapter-health-registry.js';
6
7
  import { type GitHubRequestCoordinator } from './request-coordinator.js';
7
8
  import type { GitHubSourceClient } from './source-contracts.js';
8
9
  export declare function createGitHubSource(config: GitHubConfig, client: GitHubSourceClient, adapter?: AdapterId, requests?: GitHubRequestCoordinator, state?: {
9
10
  readonly checkpoints?: CheckpointStore;
11
+ readonly journal?: EventJournal;
10
12
  readonly now?: () => number;
11
13
  readonly health?: GitHubAdapterHealthRegistry;
12
- }): ExternalEventSource;
14
+ }): Omit<ExternalEventSource, 'poll'> & {
15
+ poll(...args: Parameters<ExternalEventSource['poll']>): Promise<readonly GitHubAdapterEventData[]>;
16
+ };
@@ -2,6 +2,7 @@ import { gitHubIssueQueryFilters } from '../application/intake-policy.js';
2
2
  import { GitHubEventType } from '../contracts/events.js';
3
3
  import { createGitHubAdapterHealthRegistry, } from './adapter-health-registry.js';
4
4
  import { issueCommentEventsFor, reviewCommentEventsFor, reviewEventsFor, } from './comment-source.js';
5
+ import { consecutivePullRequestObservations } from './consecutive-pr-observations.js';
5
6
  import { issueObservation } from './issue-source.js';
6
7
  import { batchesComplete, batchesSucceeded, completedProviderWatermark, hasProviderTimestamp, loadWatermark, overlapSince, reportPartialPollFailure, timestampsValid, watermarkCheckpoint, } from './poll-watermark.js';
7
8
  import { pullRequestEventsFor } from './pr-source.js';
@@ -10,9 +11,8 @@ export function createGitHubSource(config, client, adapter, requests = createGit
10
11
  maxConcurrent: config.polling.maxConcurrent,
11
12
  }), state) {
12
13
  const health = state?.health ?? createGitHubAdapterHealthRegistry(config.repositories);
13
- // Event ids are content fingerprints (see issue-source.ts/pr-source.ts), and the polling
14
- // persistence boundary deduplicates them durably. This cache avoids returning unchanged
15
- // work observations within one process lifetime, so it is only a performance optimization.
14
+ // PR observations use the journal to deduplicate consecutive evidence durably.
15
+ // This cache avoids returning unchanged issue observations within one process.
16
16
  const lastEventIds = new Map();
17
17
  const pendingWatermarks = new Map();
18
18
  const now = state?.now ?? Date.now;
@@ -41,11 +41,12 @@ export function createGitHubSource(config, client, adapter, requests = createGit
41
41
  for (const result of perRepository)
42
42
  if (result.watermark !== undefined)
43
43
  pendingWatermarks.set(result.repository, result.watermark);
44
- return perRepository
45
- .flatMap((result) => result.drafts)
46
- .filter((draft) => {
44
+ const drafts = await consecutivePullRequestObservations(perRepository.flatMap((result) => result.drafts), state?.journal, adapter);
45
+ return drafts.filter((draft) => {
47
46
  if (draft.eventType !== GitHubEventType.WorkObserved)
48
47
  return true;
48
+ if (draft.payload.kind === 'pull-request' && state?.journal !== undefined)
49
+ return true;
49
50
  const prior = lastEventIds.get(draft.payload.externalKey);
50
51
  lastEventIds.set(draft.payload.externalKey, draft.eventId);
51
52
  return prior !== draft.eventId;
@@ -102,9 +103,8 @@ async function pollRepository(input) {
102
103
  ? pullRequestsResult.value
103
104
  : [];
104
105
  const topLevelTimestampsValid = timestampsValid(returnedIssues, returnedPullRequestPayloads);
105
- const pullRequestPayloads = returnedPullRequestPayloads
106
- .filter(hasProviderTimestamp)
107
- .filter((pullRequest) => since === undefined || pullRequest.updated_at >= since);
106
+ // Mergeability and checks can change without updating the PR timestamp.
107
+ const pullRequestPayloads = returnedPullRequestPayloads.filter(hasProviderTimestamp);
108
108
  const [pullRequests, reviews, reviewComments, issueComments] = await Promise.all([
109
109
  pullRequestEventsFor({
110
110
  client: { ...client, listPullRequests: async () => pullRequestPayloads },
@@ -49,6 +49,7 @@ export const gitHubProviderDefinition = {
49
49
  eventTypes: Object.values(GitHubEventType),
50
50
  source: createGitHubSource(config, client, adapter, requests, {
51
51
  checkpoints: services.checkpoints,
52
+ journal: services.journal,
52
53
  now: () => services.clock.now().getTime(),
53
54
  health,
54
55
  }),
@@ -5,3 +5,8 @@ import type { ResourceTransitionEvidence } from './resource-transition-evidence.
5
5
  import type { StartWorkflow } from './start-workflow.js';
6
6
  export declare function recoverPolicyBlockedMerges(repository: OrchestrationRepository, workflows: StartWorkflow, evidence: ResourceTransitionEvidence, context: CommandContext): Promise<void>;
7
7
  export declare function isPolicyBlockedMergeWait(view: WorkflowInstanceView): boolean;
8
+ export declare const MergeWaitBlockReason: {
9
+ readonly Closed: "merge.pr-closed-unmerged: primary PR was closed without merging; restore the PR and resolve the workflow explicitly";
10
+ readonly Conflict: "merge.pr-conflicting: primary PR conflicts with its base; no safe bounded repair route in the pinned workflow";
11
+ readonly Exhausted: "merge.conflict-retry-exhausted: bounded conflict repair exhausted; resolve the PR and workflow explicitly";
12
+ };
@@ -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,
@@ -75,7 +82,10 @@ export async function acceptResourceTransition(repository, workflows, id, target
75
82
  if (decision.kind === 'append') {
76
83
  const recovered = await appendWithIntentRecovery({
77
84
  append: async () => {
78
- await repository.append(id, loaded.sequence, decision.events);
85
+ await repository.append(id, loaded.sequence, [
86
+ ...(retry === undefined ? [] : [retry]),
87
+ ...decision.events,
88
+ ]);
79
89
  },
80
90
  load: () => repository.load(id),
81
91
  alreadyApplied: (reloaded) => reloaded.view !== null &&
@@ -87,3 +97,15 @@ export async function acceptResourceTransition(repository, workflows, id, target
87
97
  }
88
98
  return (await repository.load(id)).view;
89
99
  }
100
+ function retryDraft(view, evidenceId, context) {
101
+ if (context.retry === undefined)
102
+ return undefined;
103
+ const retry = context.retry;
104
+ const count = (view.retryCounts[retry.key] ?? 0) + 1;
105
+ return stateDraft(view, { occurredAt: context.occurredAt, causationId: `${context.commandId}:${evidenceId}` }, count > retry.max
106
+ ? {
107
+ eventType: OrchestrationEventType.InstanceBlocked,
108
+ payload: { reason: retry.exhaustedReason },
109
+ }
110
+ : { eventType: OrchestrationEventType.RetryCounted, payload: { retryKey: retry.key, count } }, 100);
111
+ }