@atolis-hq/wake 0.4.76 → 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 (67) 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 +1 -0
  11. package/dist/src/bootstrap/config/root-schema.d.ts +19 -0
  12. package/dist/src/bootstrap/initialise.js +1 -0
  13. package/dist/src/bootstrap/integration-runtime.js +8 -1
  14. package/dist/src/bootstrap/resource-transition-evidence.js +20 -14
  15. package/dist/src/bootstrap/version.js +1 -1
  16. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +1 -0
  17. package/dist/src/control-plane/application/activation-scheduler.js +4 -0
  18. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +5 -0
  19. package/dist/src/control-plane/application/advance-once-dispatch.js +11 -1
  20. package/dist/src/control-plane/contracts/config.d.ts +2 -0
  21. package/dist/src/control-plane/contracts/config.js +2 -0
  22. package/dist/src/control-plane/domain/open-work-policy.d.ts +12 -0
  23. package/dist/src/control-plane/domain/open-work-policy.js +35 -0
  24. package/dist/src/control-plane/index.d.ts +1 -0
  25. package/dist/src/control-plane/index.js +1 -0
  26. package/dist/src/integrations/application/agent-run-publication-reactor.d.ts +1 -0
  27. package/dist/src/integrations/application/agent-run-publication-reactor.js +49 -25
  28. package/dist/src/integrations/application/agent-run-publication-report.d.ts +10 -0
  29. package/dist/src/integrations/application/agent-run-publication-report.js +53 -0
  30. package/dist/src/integrations/application/terminal-agent-run-report.d.ts +4 -0
  31. package/dist/src/integrations/application/terminal-agent-run-report.js +4 -0
  32. package/dist/src/integrations/delivery/contracts/intents.d.ts +2 -0
  33. package/dist/src/integrations/delivery/contracts/intents.js +2 -0
  34. package/dist/src/integrations/github/application/agent-run-comment.d.ts +2 -0
  35. package/dist/src/integrations/github/application/agent-run-comment.js +26 -5
  36. package/dist/src/integrations/github/application/pull-request-translation.js +1 -0
  37. package/dist/src/integrations/github/contracts/events.d.ts +2 -1
  38. package/dist/src/integrations/github/contracts/events.js +8 -1
  39. package/dist/src/integrations/github/contracts/payloads.d.ts +1 -0
  40. package/dist/src/integrations/github/infrastructure/client-reads.d.ts +18 -6
  41. package/dist/src/integrations/github/infrastructure/client-reads.js +6 -1
  42. package/dist/src/integrations/github/infrastructure/client.d.ts +18 -6
  43. package/dist/src/integrations/github/infrastructure/consecutive-pr-observations.d.ts +4 -0
  44. package/dist/src/integrations/github/infrastructure/consecutive-pr-observations.js +33 -0
  45. package/dist/src/integrations/github/infrastructure/pr-source.js +6 -1
  46. package/dist/src/integrations/github/infrastructure/source.d.ts +6 -2
  47. package/dist/src/integrations/github/infrastructure/source.js +9 -9
  48. package/dist/src/integrations/github/provider.js +1 -0
  49. package/dist/src/orchestration/application/advance-workflow.js +1 -0
  50. package/dist/src/orchestration/application/policy-blocked-merge-recovery.d.ts +5 -0
  51. package/dist/src/orchestration/application/policy-blocked-merge-recovery.js +108 -21
  52. package/dist/src/orchestration/application/pull-request-transition-evidence.js +22 -1
  53. package/dist/src/orchestration/application/resource-transition-evidence.d.ts +6 -1
  54. package/dist/src/orchestration/application/resource-transition-matching.d.ts +5 -0
  55. package/dist/src/orchestration/application/resource-transition-matching.js +23 -1
  56. package/dist/src/orchestration/contracts/config.d.ts +42 -1
  57. package/dist/src/orchestration/contracts/config.js +9 -1
  58. package/dist/src/orchestration/contracts/event-decoder.d.ts +5 -0
  59. package/dist/src/orchestration/contracts/event-decoder.js +6 -1
  60. package/dist/src/orchestration/contracts/views.d.ts +2 -0
  61. package/dist/src/orchestration/domain/resource-transition-compiler.js +1 -0
  62. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +1 -0
  63. package/dist/src/orchestration/domain/workflow-instance-events.js +2 -0
  64. package/dist/src/orchestration/domain/workflow-instance.js +9 -1
  65. package/dist/src/orchestration/index.d.ts +1 -0
  66. package/dist/src/orchestration/index.js +1 -0
  67. package/package.json +1 -1
@@ -2,13 +2,14 @@ import { defineEventProcessor, EventActorKind, EventProcessorCategory, EventProc
2
2
  import { BuiltInActivityName } from '../../activities/index.js';
3
3
  import { conversationIdForWorkItem, ConversationOriginKind, } from '../../conversations/index.js';
4
4
  import { RunStatus } from '../../execution/index.js';
5
- import { ApprovalAuthorityKind, isApprovalAwaitingSignalKind, OrchestrationEventType, OrchestrationStreamKind, selectWorkflowOrchestrationEvent, WatchGateVerdictSignal, } from '../../orchestration/index.js';
5
+ import { OrchestrationEventType, OrchestrationStreamKind, selectWorkflowOrchestrationEvent, } from '../../orchestration/index.js';
6
6
  import { BuiltInResourceKind, ResourceCorrelationRole, resourceStream, } from '../../resources/index.js';
7
7
  import { ReplyTarget } from '../contracts/reply-routing.js';
8
8
  import { createDeliveryIntentEventData } from '../delivery/contracts/event-factory.js';
9
9
  import { DeliveryIntentEventType } from '../delivery/contracts/intents.js';
10
10
  import { defaultReplyPublication, selectReplyTarget, } from '../github/application/reply-target-selector.js';
11
11
  import { projectTerminalAgentRunReport } from './terminal-agent-run-report.js';
12
+ import { agentRunReportInput, mergeWaitComment } from './agent-run-publication-report.js';
12
13
  /** Projects terminal agent runs into one durable outbound intent per configured resource. */
13
14
  export class AgentRunPublicationReactor {
14
15
  dependencies;
@@ -24,7 +25,8 @@ export class AgentRunPublicationReactor {
24
25
  select(event) {
25
26
  const outcome = selectWorkflowOrchestrationEvent(event);
26
27
  return outcome?.event.eventType === OrchestrationEventType.ActivityOutcomeAccepted ||
27
- outcome?.event.eventType === OrchestrationEventType.ActivityExecutionFailed
28
+ outcome?.event.eventType === OrchestrationEventType.ActivityExecutionFailed ||
29
+ outcome?.event.eventType === OrchestrationEventType.SignalWaitStarted
28
30
  ? outcome
29
31
  : null;
30
32
  },
@@ -32,6 +34,10 @@ export class AgentRunPublicationReactor {
32
34
  });
33
35
  }
34
36
  async react(outcome) {
37
+ if (outcome.event.eventType === OrchestrationEventType.SignalWaitStarted) {
38
+ await this.publishMergeWait(outcome);
39
+ return;
40
+ }
35
41
  if (outcome.event.eventType === OrchestrationEventType.ActivityOutcomeAccepted) {
36
42
  await this.publishAcceptedOutcome(outcome.stream.id, outcome.event.payload.activationId, outcome.recordedAt, outcome.event.eventId, outcome.event.correlationId);
37
43
  return;
@@ -57,7 +63,7 @@ export class AgentRunPublicationReactor {
57
63
  if (workflow === undefined)
58
64
  return;
59
65
  const stage = await this.stageForActivation(workflow.workflowInstanceId, run.activationId);
60
- const report = projectTerminalAgentRunReport(reportInput(run, stage, workflow, allWorkflows));
66
+ const report = projectTerminalAgentRunReport(agentRunReportInput(run, stage, workflow, allWorkflows));
61
67
  if (report === null)
62
68
  return;
63
69
  await this.recordConversationEntry(workflow.workItemId, run.runId, report.displayBody, stage, occurredAt, correlationId);
@@ -99,6 +105,46 @@ export class AgentRunPublicationReactor {
99
105
  /* idempotency is the deterministic run event id */
100
106
  }
101
107
  }
108
+ async publishMergeWait(event) {
109
+ const workflow = (await this.dependencies.orchestration.listAll()).find((view) => view.workflowInstanceId === event.stream.id);
110
+ const body = mergeWaitComment(workflow);
111
+ if (workflow?.pendingActivation === undefined || body === undefined)
112
+ return;
113
+ // A replayed older wait event must not publish guidance for a newer wait.
114
+ if (event.event.eventType === OrchestrationEventType.SignalWaitStarted &&
115
+ event.event.payload.signalKind !== workflow.waitingFor?.signalKind)
116
+ return;
117
+ const replies = this.dependencies.replies ?? defaultReplyPublication;
118
+ const target = selectReplyTarget({ stage: workflow.currentStage, outcome: 'DONE' }, replies.rules, replies.default);
119
+ if (target === ReplyTarget.None)
120
+ return;
121
+ const resource = await this.resourceForTarget(workflow.workItemId, target);
122
+ if (resource === undefined)
123
+ return;
124
+ const stream = resourceStream(resource.resourceId);
125
+ const facts = await this.dependencies.journal.readStream(stream);
126
+ const eventId = `merge-wait:${event.event.eventId}`;
127
+ if (facts.some((fact) => fact.event.eventId === eventId))
128
+ return;
129
+ await this.dependencies.journal.appendToStream(stream, facts.length, [
130
+ createDeliveryIntentEventData({
131
+ eventId,
132
+ eventType: DeliveryIntentEventType.ReplyPublishRequested,
133
+ occurredAt: event.recordedAt,
134
+ correlationId: event.event.correlationId,
135
+ causationId: event.event.eventId,
136
+ actor: { kind: EventActorKind.Integration, id: 'agent-run-publication' },
137
+ source: { kind: EventSourceKind.Internal, id: 'agent-run-publication' },
138
+ payload: {
139
+ workflowInstanceId: workflow.workflowInstanceId,
140
+ activationId: workflow.pendingActivation.activationId,
141
+ resourceId: resource.resourceId,
142
+ body,
143
+ publicationOnly: true,
144
+ },
145
+ }),
146
+ ]);
147
+ }
102
148
  async recordConversationEntry(workItemId, runId, body, stage, occurredAt, correlationId) {
103
149
  const conversations = this.dependencies.conversations;
104
150
  if (conversations === undefined)
@@ -153,25 +199,3 @@ export class AgentRunPublicationReactor {
153
199
  return undefined;
154
200
  }
155
201
  }
156
- function reportInput(run, stage, workflow, allWorkflows) {
157
- const watchGateVerdict = watchGateVerdictFor(run, workflow, allWorkflows);
158
- const isWaiting = workflow.waitingFor !== undefined &&
159
- isApprovalAwaitingSignalKind(workflow.waitingFor.signalKind);
160
- return {
161
- run,
162
- ...(stage === undefined ? {} : { stage }),
163
- ...(isWaiting ? { awaitingApproval: true } : {}),
164
- ...(watchGateVerdict === undefined ? {} : { watchGateVerdict }),
165
- };
166
- }
167
- function watchGateVerdictFor(run, workflow, allWorkflows) {
168
- if (run.agent?.outcome !== 'DONE' && run.agent?.outcome !== 'REJECTED')
169
- return undefined;
170
- if (workflow.parentWorkflowInstanceId === undefined || workflow.watchId === undefined)
171
- return undefined;
172
- const parent = allWorkflows.find((value) => value.workflowInstanceId === workflow.parentWorkflowInstanceId);
173
- if (parent?.waitingFor?.signalKind !== WatchGateVerdictSignal)
174
- return undefined;
175
- const namesThisWatch = parent.waitingFor.from?.some((entry) => entry.kind === ApprovalAuthorityKind.Watch && entry.watch === workflow.watchId);
176
- return namesThisWatch === true ? { runId: run.runId } : undefined;
177
- }
@@ -0,0 +1,10 @@
1
+ import { type WorkflowInstanceView } from '../../orchestration/index.js';
2
+ import { type projectTerminalAgentRunReport, type TerminalRun } from './terminal-agent-run-report.js';
3
+ /** The comment to post when a merge stage starts waiting, or undefined when no hint applies. */
4
+ export declare function mergeWaitComment(workflow: WorkflowInstanceView | undefined): string | undefined;
5
+ export declare function agentRunReportInput(run: TerminalRun, stage: string | undefined, workflow: WorkflowInstanceView, allWorkflows: readonly WorkflowInstanceView[]): Parameters<typeof projectTerminalAgentRunReport>[0];
6
+ export declare function isMergePublicationWait(workflow: WorkflowInstanceView | undefined): workflow is WorkflowInstanceView & {
7
+ readonly pendingActivation: NonNullable<WorkflowInstanceView['pendingActivation']>;
8
+ };
9
+ /** An approved wait at the merge stage is resumed by /approved. */
10
+ export declare function isMergeStageApproval(workflow: WorkflowInstanceView): boolean;
@@ -0,0 +1,53 @@
1
+ import { BuiltInActivityName } from '../../activities/index.js';
2
+ import { ApprovalAuthorityKind, ApprovedSignal, isApprovalAwaitingSignalKind, isPolicyBlockedMergeWait, ResourceTransitionSignal, WatchGateVerdictSignal, WorkflowStatus, } from '../../orchestration/index.js';
3
+ import { MergeStageApprovalGuidance, MergeWaitGuidance, } from './terminal-agent-run-report.js';
4
+ /** The comment to post when a merge stage starts waiting, or undefined when no hint applies. */
5
+ export function mergeWaitComment(workflow) {
6
+ if (workflow === undefined)
7
+ return undefined;
8
+ if (isMergePublicationWait(workflow))
9
+ return `**Wake: Awaiting merge**\n\n${MergeWaitGuidance}`;
10
+ const waiting = workflow.status === WorkflowStatus.Waiting && workflow.parentWorkflowInstanceId === undefined;
11
+ return waiting && isMergeStageApproval(workflow)
12
+ ? `**Wake: Awaiting approval**\n\n${MergeStageApprovalGuidance}`
13
+ : undefined;
14
+ }
15
+ export function agentRunReportInput(run, stage, workflow, allWorkflows) {
16
+ const watchGateVerdict = watchGateVerdictFor(run, workflow, allWorkflows);
17
+ const isWaiting = workflow.waitingFor !== undefined &&
18
+ isApprovalAwaitingSignalKind(workflow.waitingFor.signalKind);
19
+ const isMergeWait = isMergePublicationWait(workflow);
20
+ return {
21
+ run,
22
+ ...(stage === undefined ? {} : { stage }),
23
+ ...(isWaiting ? { awaitingApproval: true } : {}),
24
+ ...(isMergeWait ? { awaitingMerge: true } : {}),
25
+ ...(isMergeStageApproval(workflow) ? { mergeStageApproval: true } : {}),
26
+ ...(watchGateVerdict === undefined ? {} : { watchGateVerdict }),
27
+ };
28
+ }
29
+ export function isMergePublicationWait(workflow) {
30
+ return (workflow?.status === WorkflowStatus.Waiting &&
31
+ workflow.parentWorkflowInstanceId === undefined &&
32
+ workflow.waitingFor !== undefined &&
33
+ workflow.waitingFor.intentEventId === undefined &&
34
+ workflow.pendingActivation?.activity === BuiltInActivityName.PullRequestMerge &&
35
+ (workflow.waitingFor.signalKind === ResourceTransitionSignal ||
36
+ isPolicyBlockedMergeWait(workflow)));
37
+ }
38
+ /** An approved wait at the merge stage is resumed by /approved. */
39
+ export function isMergeStageApproval(workflow) {
40
+ return (workflow.waitingFor?.signalKind === ApprovedSignal &&
41
+ workflow.pendingActivation?.activity === BuiltInActivityName.PullRequestMerge);
42
+ }
43
+ function watchGateVerdictFor(run, workflow, allWorkflows) {
44
+ if (run.agent?.outcome !== 'DONE' && run.agent?.outcome !== 'REJECTED')
45
+ return undefined;
46
+ if (workflow.parentWorkflowInstanceId === undefined || workflow.watchId === undefined)
47
+ return undefined;
48
+ const parent = allWorkflows.find((value) => value.workflowInstanceId === workflow.parentWorkflowInstanceId);
49
+ if (parent?.waitingFor?.signalKind !== WatchGateVerdictSignal)
50
+ return undefined;
51
+ const namesThisWatch = parent.waitingFor.from?.some((entry) => entry.kind === ApprovalAuthorityKind.Watch && entry.watch === workflow.watchId);
52
+ return namesThisWatch === true ? { runId: run.runId } : undefined;
53
+ }
@@ -1,4 +1,6 @@
1
1
  import type { AgentRunPublicationReport } from '../delivery/contracts/intents.js';
2
+ export declare const MergeWaitGuidance = "Wake is waiting for the primary pull request to merge. Resolve and merge it in the provider; explicit conflicts use the pinned workflow repair policy, and closed unmerged pull requests block the work.";
3
+ export declare const MergeStageApprovalGuidance = "An authorized independent reviewer can reply with /approved to continue. Approval of your own work is not permitted.";
2
4
  export interface TerminalRunAgentResult {
3
5
  readonly outcome: 'DONE' | 'REJECTED' | 'BLOCKED' | 'FAILED' | 'NEEDS_CLARIFICATION';
4
6
  readonly displayBody: string;
@@ -27,6 +29,8 @@ export declare function projectTerminalAgentRunReport(input: {
27
29
  readonly run: TerminalRun;
28
30
  readonly stage?: string;
29
31
  readonly awaitingApproval?: boolean;
32
+ readonly awaitingMerge?: boolean;
33
+ readonly mergeStageApproval?: boolean;
30
34
  readonly watchGateVerdict?: {
31
35
  readonly runId: string;
32
36
  };
@@ -1,3 +1,5 @@
1
+ export const MergeWaitGuidance = 'Wake is waiting for the primary pull request to merge. Resolve and merge it in the provider; explicit conflicts use the pinned workflow repair policy, and closed unmerged pull requests block the work.';
2
+ export const MergeStageApprovalGuidance = 'An authorized independent reviewer can reply with /approved to continue. Approval of your own work is not permitted.';
1
3
  export function projectTerminalAgentRunReport(input) {
2
4
  if (input.run.finishedAt === undefined)
3
5
  return null;
@@ -14,6 +16,8 @@ export function projectTerminalAgentRunReport(input) {
14
16
  ...(input.run.workspace === undefined ? {} : { workspacePath: input.run.workspace.path }),
15
17
  metadata: agent?.metadata ?? {},
16
18
  ...(input.awaitingApproval === true ? { awaitingApproval: true } : {}),
19
+ ...(input.awaitingMerge === true ? { awaitingMerge: true } : {}),
20
+ ...(input.mergeStageApproval === true ? { mergeStageApproval: true } : {}),
17
21
  ...(input.watchGateVerdict === undefined ? {} : { watchGateVerdict: input.watchGateVerdict }),
18
22
  };
19
23
  }
@@ -30,6 +30,8 @@ export interface AgentRunPublicationReport {
30
30
  readonly workspacePath?: string | undefined;
31
31
  readonly metadata: Readonly<Record<string, string | number | boolean | null>>;
32
32
  readonly awaitingApproval?: boolean | undefined;
33
+ readonly awaitingMerge?: boolean | undefined;
34
+ readonly mergeStageApproval?: boolean | undefined;
33
35
  readonly watchGateVerdict?: {
34
36
  readonly runId: string;
35
37
  } | undefined;
@@ -35,6 +35,8 @@ const reportSchema = z
35
35
  workspacePath: z.string().min(1).optional(),
36
36
  metadata: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()])),
37
37
  awaitingApproval: z.boolean().optional(),
38
+ awaitingMerge: z.boolean().optional(),
39
+ mergeStageApproval: z.boolean().optional(),
38
40
  watchGateVerdict: z
39
41
  .object({ runId: z.string().min(1) })
40
42
  .strict()
@@ -14,6 +14,8 @@ export interface AgentRunComment {
14
14
  readonly sessionId?: string | undefined;
15
15
  readonly workspacePath?: string | undefined;
16
16
  readonly awaitingApproval?: boolean | undefined;
17
+ readonly awaitingMerge?: boolean | undefined;
18
+ readonly mergeStageApproval?: boolean | undefined;
17
19
  readonly watchGateVerdict?: {
18
20
  readonly runId: string;
19
21
  } | undefined;
@@ -1,19 +1,31 @@
1
+ import { MergeStageApprovalGuidance, MergeWaitGuidance, } from '../../application/terminal-agent-run-report.js';
2
+ /** Names only the commands the current wait accepts. */
3
+ function waitHintFor(value) {
4
+ if (value.awaitingMerge === true)
5
+ return `_${MergeWaitGuidance}_`;
6
+ if (value.awaitingApproval !== true)
7
+ return undefined;
8
+ if (value.mergeStageApproval === true)
9
+ return `_${MergeStageApprovalGuidance}_`;
10
+ return '_An authorized independent reviewer can reply with /approved or /changes followed by feedback. Approval of your own work is not permitted. To ask a question, reply with /ask followed by your question._';
11
+ }
1
12
  export function formatAgentRunComment(value) {
2
13
  const details = detailsLine(value);
3
14
  const sections = [
4
15
  '<!-- wake:agent -->',
5
16
  `<!-- wake:delivery:${value.idempotencyKey} -->`,
6
17
  `**${wakeHeading(value.publicUiUrl)}** _(Wake${details ? ` - ${details}` : ''})_`,
7
- `**Outcome:** ${value.awaitingApproval === true ? '⏳ Awaiting approval' : outcome(value.outcome)}`,
18
+ `**Outcome:** ${commentOutcome(value)}`,
8
19
  value.displayBody.trim() || fallback(value.outcome),
9
20
  ];
10
- if (value.awaitingApproval === true)
11
- sections.push('_An authorized independent reviewer can reply with /approved or /changes followed by feedback. Approval of your own work is not permitted. To ask a question, reply with /ask followed by your question._');
12
- if (value.outcome === 'BLOCKED' || value.outcome === 'NEEDS_CLARIFICATION')
21
+ const waitHint = waitHintFor(value);
22
+ if (waitHint !== undefined)
23
+ sections.push(waitHint);
24
+ if (hasContinuationHint(value))
13
25
  sections.push(value.outcome === 'NEEDS_CLARIFICATION'
14
26
  ? '_Reply with the requested clarification. A maintainer with repository write, maintain, or admin permission can also use /changes followed by instructions to continue eligible blocked work._'
15
27
  : '_A maintainer with repository write, maintain, or admin permission can continue eligible blocked work with /changes followed by instructions, including on an issue they authored. The authenticated UI also offers Continue with instructions. /retry is for eligible failed stages._');
16
- if (value.outcome === 'FAILED')
28
+ if (value.outcome === 'FAILED' && value.awaitingMerge !== true)
17
29
  sections.push('_An authorized maintainer can use /retry for an eligible failed stage, or /restart for a fresh session. These commands do not continue a blocked outcome._');
18
30
  const session = sessionSection(value);
19
31
  if (session !== undefined)
@@ -95,3 +107,12 @@ function cost(metadata) {
95
107
  function formatDuration(value) {
96
108
  return `${Math.max(0, Math.round(value / 1000))}s`;
97
109
  }
110
+ function commentOutcome(value) {
111
+ if (value.awaitingMerge === true)
112
+ return '⏳ Awaiting merge';
113
+ return value.awaitingApproval === true ? '⏳ Awaiting approval' : outcome(value.outcome);
114
+ }
115
+ function hasContinuationHint(value) {
116
+ return (value.awaitingMerge !== true &&
117
+ (value.outcome === 'BLOCKED' || value.outcome === 'NEEDS_CLARIFICATION'));
118
+ }
@@ -3,6 +3,7 @@ export function observePullRequest(resourceId, workItemId, payload) {
3
3
  resourceId,
4
4
  workItemId,
5
5
  state: payload.state,
6
+ ...(payload.mergeability === undefined ? {} : { mergeability: payload.mergeability }),
6
7
  headRevision: payload.headRevision ?? payload.revision,
7
8
  baseRevision: payload.baseRevision ?? 'unknown',
8
9
  checks: payload.checks ?? 'unknown',
@@ -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
  }),