@atolis-hq/wake 0.3.118 → 0.4.1

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 (46) hide show
  1. package/README.md +9 -2
  2. package/dist/src/bootstrap/composition-root.js +5 -1
  3. package/dist/src/bootstrap/index.js +3 -3
  4. package/dist/src/bootstrap/initialise.js +9 -14
  5. package/dist/src/bootstrap/integration-runtime.js +3 -1
  6. package/dist/src/bootstrap/projection-runtime.js +2 -0
  7. package/dist/src/bootstrap/surface-api-work-applications.js +70 -0
  8. package/dist/src/bootstrap/surface-cli-applications.js +16 -9
  9. package/dist/src/bootstrap/version.js +1 -1
  10. package/dist/src/conversations/application/conversation-projection.js +17 -0
  11. package/dist/src/conversations/application/conversation-repository.js +21 -0
  12. package/dist/src/conversations/application/conversation-service.js +105 -0
  13. package/dist/src/conversations/contracts/commands.js +1 -0
  14. package/dist/src/conversations/contracts/events.js +100 -0
  15. package/dist/src/conversations/contracts/identifiers.js +8 -0
  16. package/dist/src/conversations/contracts/streams.js +5 -0
  17. package/dist/src/conversations/contracts/views.js +1 -0
  18. package/dist/src/conversations/contracts/vocabulary.js +6 -0
  19. package/dist/src/conversations/domain/conversation.js +100 -0
  20. package/dist/src/conversations/index.js +8 -0
  21. package/dist/src/integrations/application/agent-run-publication-reactor.js +31 -0
  22. package/dist/src/integrations/application/work-admission.js +6 -0
  23. package/dist/src/integrations/delivery/application/delivery-outcome-reactor.js +48 -2
  24. package/dist/src/integrations/delivery/application/delivery-projector.js +2 -0
  25. package/dist/src/integrations/delivery/contracts/intents.js +2 -0
  26. package/dist/src/integrations/github/application/agent-context-reader.js +49 -3
  27. package/dist/src/integrations/github/application/comment-history-reader.js +27 -11
  28. package/dist/src/integrations/github/application/delivery-marker.js +7 -0
  29. package/dist/src/integrations/github/application/inbound-translator.js +126 -0
  30. package/dist/src/integrations/github/contracts/events.js +12 -0
  31. package/dist/src/integrations/github/provider.js +1 -0
  32. package/dist/src/orchestration/domain/operator-retry-policy.js +8 -5
  33. package/dist/src/persistence/filesystem/file-event-journal.js +31 -5
  34. package/dist/src/persistence/filesystem/file-projection-store.js +25 -6
  35. package/dist/src/surfaces/api/routes/commands.js +36 -6
  36. package/dist/src/surfaces/api/routes/work.js +1 -0
  37. package/dist/src/surfaces/contracts/config.js +17 -2
  38. package/dist/src/surfaces/web-assets/assets/index-B0ofn_L5.css +1 -0
  39. package/dist/src/surfaces/web-assets/assets/index-DFBhpSSX.js +1179 -0
  40. package/dist/src/surfaces/web-assets/index.html +2 -2
  41. package/docker/Dockerfile +1 -6
  42. package/docker/Dockerfile.packaged +1 -6
  43. package/package.json +1 -1
  44. package/dist/src/surfaces/web-assets/assets/index-CFfq35Jj.js +0 -1179
  45. package/dist/src/surfaces/web-assets/assets/index-Dj-RskGs.css +0 -1
  46. package/docker/entrypoint.sh +0 -90
@@ -0,0 +1,100 @@
1
+ import { ConversationEventType } from '../contracts/events.js';
2
+ export function foldConversation(events) {
3
+ let view = null;
4
+ for (const event of events)
5
+ view = applyConversationEvent(view, event);
6
+ return view;
7
+ }
8
+ export function applyConversationEvent(view, event) {
9
+ switch (event.eventType) {
10
+ case ConversationEventType.Created:
11
+ return {
12
+ conversationId: event.stream.id,
13
+ workItemId: event.payload.workItemId,
14
+ entries: [],
15
+ resources: [],
16
+ };
17
+ case ConversationEventType.EntryRecorded:
18
+ return appendEntry(view, event);
19
+ case ConversationEventType.ResourceAssociated:
20
+ return appendResource(view, event);
21
+ case ConversationEventType.EntryRevised:
22
+ return reviseEntry(view, event);
23
+ case ConversationEventType.EntryTombstoned:
24
+ return tombstoneEntry(view, event);
25
+ case ConversationEventType.EntryRepresentationRecorded:
26
+ return recordRepresentation(view, event);
27
+ }
28
+ }
29
+ function appendEntry(view, event) {
30
+ if (view === null || view.entries.some((entry) => entry.entryId === event.payload.entryId))
31
+ return view;
32
+ return {
33
+ ...view,
34
+ entries: [
35
+ ...view.entries,
36
+ {
37
+ entryId: event.payload.entryId,
38
+ body: event.payload.body,
39
+ occurredAt: event.occurredAt,
40
+ origin: event.payload.origin,
41
+ deleted: false,
42
+ revisions: [{ body: event.payload.body, occurredAt: event.occurredAt }],
43
+ representations: [],
44
+ },
45
+ ],
46
+ };
47
+ }
48
+ function recordRepresentation(view, event) {
49
+ if (view === null)
50
+ return view;
51
+ return {
52
+ ...view,
53
+ entries: view.entries.map((entry) => entry.entryId !== event.payload.entryId ||
54
+ entry.representations.some((representation) => representation.resourceId === event.payload.resourceId &&
55
+ representation.externalId === event.payload.externalId)
56
+ ? entry
57
+ : {
58
+ ...entry,
59
+ representations: [
60
+ ...entry.representations,
61
+ { resourceId: event.payload.resourceId, externalId: event.payload.externalId },
62
+ ],
63
+ }),
64
+ };
65
+ }
66
+ function appendResource(view, event) {
67
+ if (view === null ||
68
+ view.resources.some((resource) => resource.resourceId === event.payload.resourceId &&
69
+ resource.threadId === event.payload.threadId))
70
+ return view;
71
+ return {
72
+ ...view,
73
+ resources: [...view.resources, event.payload],
74
+ };
75
+ }
76
+ function reviseEntry(view, event) {
77
+ if (view === null)
78
+ return view;
79
+ return {
80
+ ...view,
81
+ entries: view.entries.map((entry) => entry.entryId !== event.payload.entryId
82
+ ? entry
83
+ : {
84
+ ...entry,
85
+ body: event.payload.body,
86
+ revisions: [
87
+ ...entry.revisions,
88
+ { body: event.payload.body, occurredAt: event.occurredAt },
89
+ ],
90
+ }),
91
+ };
92
+ }
93
+ function tombstoneEntry(view, event) {
94
+ if (view === null)
95
+ return view;
96
+ return {
97
+ ...view,
98
+ entries: view.entries.map((entry) => entry.entryId === event.payload.entryId ? { ...entry, deleted: true } : entry),
99
+ };
100
+ }
@@ -0,0 +1,8 @@
1
+ export * from './application/conversation-projection.js';
2
+ export * from './application/conversation-service.js';
3
+ export * from './contracts/commands.js';
4
+ export * from './contracts/events.js';
5
+ export * from './contracts/identifiers.js';
6
+ export * from './contracts/streams.js';
7
+ export * from './contracts/views.js';
8
+ export * from './contracts/vocabulary.js';
@@ -1,4 +1,5 @@
1
1
  import { BuiltInActivityName } from '../../activities/index.js';
2
+ import { conversationIdForWorkItem, ConversationOriginKind, } from '../../conversations/index.js';
2
3
  import { RunStatus } from '../../execution/index.js';
3
4
  import { createEventDraft, EventActorKind, EventSourceKind, } from '../../kernel/index.js';
4
5
  import { ApprovalAuthorityKind, isApprovalAwaitingSignalKind, OrchestrationEventType, OrchestrationStreamKind, WatchGateVerdictSignal, } from '../../orchestration/index.js';
@@ -45,6 +46,7 @@ export class AgentRunPublicationReactor {
45
46
  const report = projectTerminalAgentRunReport(reportInput(run, stage, workflow, allWorkflows));
46
47
  if (report === null)
47
48
  return;
49
+ await this.recordConversationEntry(workflow.workItemId, run.runId, report.displayBody, stage, occurredAt, correlationId);
48
50
  const replies = this.dependencies.replies ?? defaultReplyPublication;
49
51
  const target = selectReplyTarget({ stage, outcome: report.outcome }, replies.rules, replies.default);
50
52
  if (target === ReplyTarget.None)
@@ -69,6 +71,12 @@ export class AgentRunPublicationReactor {
69
71
  workflowInstanceId: run.workflowInstanceId,
70
72
  activationId: run.activationId,
71
73
  resourceId: resource.resourceId,
74
+ ...(this.dependencies.conversations === undefined
75
+ ? {}
76
+ : {
77
+ conversationId: conversationIdForWorkItem(workflow.workItemId),
78
+ conversationEntryId: `agent-run:${run.runId}`,
79
+ }),
72
80
  report,
73
81
  },
74
82
  }),
@@ -78,6 +86,29 @@ export class AgentRunPublicationReactor {
78
86
  /* idempotency is the deterministic run event id */
79
87
  }
80
88
  }
89
+ async recordConversationEntry(workItemId, runId, body, stage, occurredAt, correlationId) {
90
+ const conversations = this.dependencies.conversations;
91
+ if (conversations === undefined)
92
+ return;
93
+ const context = {
94
+ commandId: `conversation:${runId}`,
95
+ correlationId: correlationId,
96
+ occurredAt,
97
+ actor: { kind: EventActorKind.Agent, id: 'wake' },
98
+ };
99
+ await conversations.createForWorkItem(workItemId, context);
100
+ await conversations.record({
101
+ conversationId: conversationIdForWorkItem(workItemId),
102
+ entryId: `agent-run:${runId}`,
103
+ body,
104
+ origin: {
105
+ kind: ConversationOriginKind.Agent,
106
+ actorId: 'wake',
107
+ runId,
108
+ ...(stage === undefined ? {} : { stage }),
109
+ },
110
+ }, { ...context, commandId: `agent-run:${runId}` });
111
+ }
81
112
  async resourceForTarget(workItemId, target) {
82
113
  const correlations = await this.dependencies.resources.correlationsForWork(workItemId);
83
114
  const primary = () => correlations.find((value) => value.role === ResourceCorrelationRole.Primary);
@@ -15,6 +15,12 @@ beforeStart) {
15
15
  ...(input.title === undefined ? {} : { title: input.title }),
16
16
  }, context);
17
17
  await services.work.create({ workItemId: input.workItemId, objective: input.objective, tags: input.tags }, context);
18
+ try {
19
+ await services.conversations?.createForWorkItem(input.workItemId, context);
20
+ }
21
+ catch (error) {
22
+ console.error(`Conversation creation failed for admitted WorkItem ${input.workItemId}`, error);
23
+ }
18
24
  await services.resources.correlate(input.resourceId, input.workItemId, ResourceCorrelationRole.Primary, context);
19
25
  if (beforeStart !== undefined)
20
26
  await beforeStart();
@@ -1,8 +1,9 @@
1
1
  import { ActivityOutcomeKind, activationId } from '../../../activities/index.js';
2
2
  import { EventActorKind, } from '../../../kernel/index.js';
3
3
  import { ActivityActivationStatus, workflowInstanceId, } from '../../../orchestration/index.js';
4
+ import { IntegrationStreamKind } from '../../contracts/streams.js';
4
5
  import { DeliveryEventType, selectDeliveryEvent } from '../contracts/events.js';
5
- import { DeliveryResultKind } from '../contracts/vocabulary.js';
6
+ import { DeliveryIntentKind, DeliveryResultKind } from '../contracts/vocabulary.js';
6
7
  const deliveryResultSignalKind = 'delivery-result';
7
8
  const pendingNamespace = 'reactor:delivery-outcomes:pending';
8
9
  const pendingKey = 'pending-confirmations';
@@ -11,11 +12,13 @@ export class DeliveryOutcomeReactor {
11
12
  checkpoints;
12
13
  orchestration;
13
14
  projections;
14
- constructor(journal, checkpoints, orchestration, projections) {
15
+ conversations;
16
+ constructor(journal, checkpoints, orchestration, projections, conversations) {
15
17
  this.journal = journal;
16
18
  this.checkpoints = checkpoints;
17
19
  this.orchestration = orchestration;
18
20
  this.projections = projections;
21
+ this.conversations = conversations;
19
22
  }
20
23
  async runOnce() {
21
24
  const consumer = 'reactor:delivery-outcomes';
@@ -67,6 +70,13 @@ export class DeliveryOutcomeReactor {
67
70
  : null;
68
71
  if (outcome === null)
69
72
  return null;
73
+ try {
74
+ await this.recordConversationRepresentation(event, delivery);
75
+ }
76
+ catch (error) {
77
+ // Delivery reconciliation must continue if optional conversation provenance is unavailable.
78
+ console.error(`Conversation provenance recording failed for ${delivery.eventId}`, error);
79
+ }
70
80
  const command = {
71
81
  workflowInstanceId: workflowInstanceId(delivery.payload.workflowInstanceId),
72
82
  activationId: activationId(delivery.payload.activationId),
@@ -82,6 +92,28 @@ export class DeliveryOutcomeReactor {
82
92
  });
83
93
  return true;
84
94
  }
95
+ async recordConversationRepresentation(event, delivery) {
96
+ if (this.conversations === undefined || !isConfirmedDelivery(delivery))
97
+ return;
98
+ const intent = await conversationDeliveryIntent(this.projections, delivery.payload.intentEventId);
99
+ if (intent === undefined)
100
+ return;
101
+ const externalId = delivery.payload.externalId;
102
+ if (externalId === undefined)
103
+ return;
104
+ const payload = intent.payload;
105
+ await this.conversations.recordRepresentation({
106
+ conversationId: payload.conversationId,
107
+ entryId: payload.conversationEntryId,
108
+ resourceId: intent.resourceId,
109
+ externalId,
110
+ }, {
111
+ commandId: delivery.eventId,
112
+ correlationId: event.correlationId,
113
+ actor: { kind: EventActorKind.System, id: 'delivery-outcome-reactor' },
114
+ occurredAt: event.recordedAt,
115
+ });
116
+ }
85
117
  /**
86
118
  * A delivery's own completion may only resolve the activation that
87
119
  * actually asked to wait on it (an activity outcome of `waiting` with
@@ -109,3 +141,17 @@ export class DeliveryOutcomeReactor {
109
141
  });
110
142
  }
111
143
  }
144
+ function isConfirmedDelivery(delivery) {
145
+ return (delivery.eventType === DeliveryEventType.Confirmed ||
146
+ (delivery.eventType === DeliveryEventType.Reconciled &&
147
+ delivery.payload.result === DeliveryResultKind.Confirmed));
148
+ }
149
+ async function conversationDeliveryIntent(projections, intentEventId) {
150
+ const intent = (await projections.list(IntegrationStreamKind.Delivery)).find((candidate) => candidate.value.intentEventId === intentEventId)?.value;
151
+ if (intent?.payload.kind !== DeliveryIntentKind.AgentRunPublish ||
152
+ !('conversationId' in intent.payload) ||
153
+ intent.payload.conversationId === undefined ||
154
+ intent.payload.conversationEntryId === undefined)
155
+ return undefined;
156
+ return intent;
157
+ }
@@ -121,6 +121,8 @@ function integrationIntentView(integrationIntent) {
121
121
  payload: {
122
122
  kind: DeliveryIntentKind.AgentRunPublish,
123
123
  report: integrationIntent.payload.report,
124
+ conversationId: integrationIntent.payload.conversationId,
125
+ conversationEntryId: integrationIntent.payload.conversationEntryId,
124
126
  },
125
127
  state: DeliveryState.Pending,
126
128
  attempts: 0,
@@ -45,6 +45,8 @@ const agentSchema = z
45
45
  workflowInstanceId: z.string().min(1),
46
46
  activationId: z.string().min(1),
47
47
  resourceId: brandedStringSchema(resourceId),
48
+ conversationId: z.string().min(1).optional(),
49
+ conversationEntryId: z.string().min(1).optional(),
48
50
  report: reportSchema,
49
51
  })
50
52
  .strict();
@@ -1,15 +1,16 @@
1
1
  import { PullRequestCheckState, } from '../../../activities/index.js';
2
+ import { ConversationOriginKind, } from '../../../conversations/index.js';
2
3
  import { BuiltInResourceKind, ResourceCorrelationRole, } from '../../../resources/index.js';
3
4
  import { adapterId } from '../../contracts/identifiers.js';
4
5
  import { integrationStream } from '../../contracts/streams.js';
5
6
  import { boundedDiagnosticEvidence } from '../contracts/check-evidence.js';
6
7
  import { GitHubEventType, selectGitHubAdapterEvent } from '../contracts/events.js';
7
- import { createCommentHistoryReader, } from './comment-history-reader.js';
8
- export function createGitHubAgentContextReader(journal, resources, options = {}) {
8
+ import { createCommentHistoryReader, deliveryIntentIdForComment, sourceMessageIdForComment, } from './comment-history-reader.js';
9
+ export function createGitHubAgentContextReader(journal, resources, options = {}, conversations) {
9
10
  const commentHistory = createCommentHistoryReader(journal, resources, options);
10
11
  return {
11
12
  async forWorkItem(workItemId, options) {
12
- const { comments, omittedComments } = boundedAgentContextComments(await commentHistory.forWorkItem(workItemId, options));
13
+ const { comments, omittedComments } = boundedAgentContextComments(await commentsForWorkItem(commentHistory, conversations, workItemId, options));
13
14
  return {
14
15
  ...(await currentWorkItemContent(journal, resources, workItemId)),
15
16
  comments,
@@ -19,6 +20,51 @@ export function createGitHubAgentContextReader(journal, resources, options = {})
19
20
  },
20
21
  };
21
22
  }
23
+ async function commentsForWorkItem(commentHistory, conversations, workItemId, options) {
24
+ const conversation = await conversations?.forWorkItem(workItemId);
25
+ if (conversation === null || conversation === undefined)
26
+ return commentHistory.forWorkItem(workItemId, options);
27
+ const canonical = conversation.entries
28
+ .filter((entry) => !entry.deleted &&
29
+ (options?.observedSince === undefined ||
30
+ latestEntryRevision(entry).occurredAt > options.observedSince))
31
+ .map((entry) => ({
32
+ author: entry.origin.actorId,
33
+ occurredAt: latestEntryRevision(entry).occurredAt,
34
+ body: entry.body,
35
+ ...(entry.origin.kind !== ConversationOriginKind.External ||
36
+ entry.origin.location === undefined
37
+ ? {}
38
+ : { location: entry.origin.location }),
39
+ ...(entry.origin.kind !== ConversationOriginKind.External
40
+ ? {}
41
+ : { sourceMessageId: entry.origin.messageId }),
42
+ deliveryIntentId: undefined,
43
+ }));
44
+ const representedMessageIds = new Set(conversation.entries.flatMap((entry) => [
45
+ ...(entry.origin.kind !== ConversationOriginKind.External ? [] : [entry.origin.messageId]),
46
+ ...entry.representations.map((representation) => representation.externalId),
47
+ ]));
48
+ const representedAgentEntryIds = new Set(conversation.entries.flatMap((entry) => entry.origin.kind === ConversationOriginKind.Agent && entry.representations.length > 0
49
+ ? [entry.entryId]
50
+ : []));
51
+ const historic = (await commentHistory.forWorkItem(workItemId, options))
52
+ .map((entry) => ({
53
+ ...entry,
54
+ sourceMessageId: sourceMessageIdForComment(entry),
55
+ deliveryIntentId: deliveryIntentIdForComment(entry),
56
+ }))
57
+ .filter((entry) => (entry.sourceMessageId === undefined ||
58
+ !representedMessageIds.has(entry.sourceMessageId)) &&
59
+ (entry.deliveryIntentId === undefined ||
60
+ !representedAgentEntryIds.has(entry.deliveryIntentId)));
61
+ return [...historic, ...canonical]
62
+ .sort((left, right) => left.occurredAt.localeCompare(right.occurredAt))
63
+ .map(({ sourceMessageId: _sourceMessageId, deliveryIntentId: _deliveryIntentId, ...entry }) => entry);
64
+ }
65
+ function latestEntryRevision(entry) {
66
+ return entry.revisions.at(-1) ?? entry;
67
+ }
22
68
  const maximumAgentContextCommentCharacters = 8_000;
23
69
  const maximumAgentContextCharacters = 200_000;
24
70
  const truncationNotice = '\n[Wake truncated this historical comment for context bounds.]';
@@ -6,6 +6,15 @@ import { DeliveryResultKind } from '../../delivery/contracts/vocabulary.js';
6
6
  import { GitHubEventType, selectGitHubAdapterEvent } from '../contracts/events.js';
7
7
  import { GitHubAdapter, UnknownGitHubIdentity } from '../contracts/vocabulary.js';
8
8
  import { formatAgentRunComment } from './agent-run-comment.js';
9
+ import { appendDeliveryMarker, deliveryMarker } from './delivery-marker.js';
10
+ const sourceMessageIds = new WeakMap();
11
+ const deliveryIntentIds = new WeakMap();
12
+ export function sourceMessageIdForComment(entry) {
13
+ return sourceMessageIds.get(entry);
14
+ }
15
+ export function deliveryIntentIdForComment(entry) {
16
+ return deliveryIntentIds.get(entry);
17
+ }
9
18
  export function createCommentHistoryReader(journal, resources, readerOptions = {}) {
10
19
  return {
11
20
  async forWorkItem(workItemId, options) {
@@ -47,7 +56,7 @@ function providerComments(events, keys) {
47
56
  for (const event of events) {
48
57
  const comment = providerComment(event, keys);
49
58
  if (comment !== null)
50
- observed.set(event.eventId, comment);
59
+ observed.set(comment.messageId, comment);
51
60
  }
52
61
  return observed;
53
62
  }
@@ -70,7 +79,7 @@ function confirmations(events, intents) {
70
79
  function reconcileCommentHistory(observed, confirmed, resourcesById, observedSince, publicUiUrl) {
71
80
  const history = new Map();
72
81
  for (const entry of observed.values())
73
- history.set(entry.event.eventId, {
82
+ history.set(entry.messageId, {
74
83
  entry: entry.value,
75
84
  occurredAt: entry.event.occurredAt,
76
85
  globalPosition: entry.event.globalPosition,
@@ -88,7 +97,7 @@ function reconcileCommentHistory(observed, confirmed, resourcesById, observedSin
88
97
  globalPosition: confirmation.event.globalPosition,
89
98
  });
90
99
  if (matchingProvider !== undefined)
91
- history.delete(matchingProvider.event.eventId);
100
+ history.delete(matchingProvider.messageId);
92
101
  }
93
102
  return [...history.values()]
94
103
  .filter((entry) => observedSince === undefined || entry.occurredAt > observedSince)
@@ -112,26 +121,36 @@ function providerComment(event, keys) {
112
121
  return null;
113
122
  return {
114
123
  event,
124
+ messageId: observedCommentExternalId(observed),
115
125
  resourceKey: `${observed.stream.id}:${observed.payload.externalKey}`,
116
- value: {
126
+ value: commentWithSourceMessageId({
117
127
  author: observed.payload.actor.id,
118
128
  occurredAt: observed.occurredAt,
119
129
  body: observed.payload.body,
120
130
  ...(observed.payload.reviewKind !== 'issue' || observed.payload.location === undefined
121
131
  ? {}
122
132
  : { location: observed.payload.location }),
123
- },
133
+ }, observedCommentExternalId(observed)),
124
134
  };
125
135
  }
136
+ function commentWithSourceMessageId(entry, messageId) {
137
+ sourceMessageIds.set(entry, messageId);
138
+ return entry;
139
+ }
140
+ function observedCommentExternalId(event) {
141
+ const id = event.payload.raw.id;
142
+ return typeof id === 'string' || typeof id === 'number' ? String(id) : event.eventId;
143
+ }
126
144
  function syntheticComment(intent, occurredAt, publicUiUrl) {
127
- return {
145
+ const entry = {
128
146
  author: UnknownGitHubIdentity,
129
147
  occurredAt,
130
148
  body: deliveredCommentBody(intent, publicUiUrl),
131
149
  };
150
+ deliveryIntentIds.set(entry, intent.eventId);
151
+ return entry;
132
152
  }
133
153
  function deliveredCommentBody(intent, publicUiUrl) {
134
- const marker = `<!-- wake:delivery:${intent.eventId} -->`;
135
154
  const body = intent.eventType === DeliveryIntentEventType.AgentRunPublishRequested
136
155
  ? formatAgentRunComment({
137
156
  idempotencyKey: intent.eventId,
@@ -139,10 +158,7 @@ function deliveredCommentBody(intent, publicUiUrl) {
139
158
  publicUiUrl,
140
159
  })
141
160
  : intent.payload.body;
142
- return `${body}\n${marker}`.trim();
143
- }
144
- function deliveryMarker(body) {
145
- return /<!--\s*wake:delivery:([^\s>]+)\s*-->/.exec(body)?.[1];
161
+ return appendDeliveryMarker(body, intent.eventId);
146
162
  }
147
163
  function parseAdapterId(value) {
148
164
  try {
@@ -0,0 +1,7 @@
1
+ const wakeDeliveryMarkerPattern = /<!--\s*wake:delivery:([^\s>]+)\s*-->/;
2
+ export function deliveryMarker(body) {
3
+ return wakeDeliveryMarkerPattern.exec(body)?.[1];
4
+ }
5
+ export function appendDeliveryMarker(body, intentEventId) {
6
+ return `${body}\n<!-- wake:delivery:${intentEventId} -->`.trim();
7
+ }
@@ -1,5 +1,6 @@
1
1
  /* eslint-disable max-lines */
2
2
  import { ActivityEventType, createPullRequestService, } from '../../../activities/index.js';
3
+ import { conversationIdForWorkItem, ConversationOriginKind, } from '../../../conversations/index.js';
3
4
  import { correlationId, createEventDraft, EventActorKind, EventSourceKind, UlidIdGenerator, WrongExpectedSequenceError, } from '../../../kernel/index.js';
4
5
  import { BuiltInResourceCapability, BuiltInResourceKind, ResourceCorrelationRole, ResourceEventType, resourceId, resourceStream, } from '../../../resources/index.js';
5
6
  import { workItemId } from '../../../work/index.js';
@@ -58,6 +59,7 @@ export class InboundTranslator {
58
59
  this.routing = dependencies.routing;
59
60
  this.intake = gitHubIntakeRules(dependencies.intake ?? []);
60
61
  this.conclusion = dependencies.conclusion;
62
+ this.conversations = dependencies.conversations;
61
63
  }
62
64
  pullRequests;
63
65
  ids;
@@ -68,6 +70,8 @@ export class InboundTranslator {
68
70
  routing;
69
71
  intake;
70
72
  conclusion;
73
+ conversations;
74
+ conversationRecordRecoveryPending;
71
75
  // Adapter filtering, checkpointing, and typed event dispatch must stay together.
72
76
  async runOnce(limit = 100) {
73
77
  if (this.journal === undefined ||
@@ -81,6 +85,7 @@ export class InboundTranslator {
81
85
  await this.resources.retryPendingWorkCorrelations();
82
86
  await this.applyDeferredExternalOutcomes();
83
87
  const checkpoint = `reactor:integration.${this.adapter}.inbound`;
88
+ await this.retryPendingConversationRecords();
84
89
  await this.retryPendingTranslations();
85
90
  const position = await this.checkpoints.load(checkpoint);
86
91
  const events = await this.journal.readAll(position, limit);
@@ -144,6 +149,12 @@ export class InboundTranslator {
144
149
  runs: this.runs,
145
150
  orchestration: this.orchestration,
146
151
  });
152
+ try {
153
+ await this.recordConversationEntry(owned);
154
+ }
155
+ catch {
156
+ await this.recordConversationDeferred(owned);
157
+ }
147
158
  }
148
159
  if (await this.retryRecorded(owned.eventId))
149
160
  await this.recordTranslationRecovery(owned);
@@ -152,6 +163,116 @@ export class InboundTranslator {
152
163
  await this.recordTranslationFailure(owned, error);
153
164
  }
154
165
  }
166
+ async retryPendingConversationRecords() {
167
+ if (this.conversationRecordRecoveryPending === false)
168
+ return;
169
+ const stream = integrationStream(this.adapter);
170
+ const events = (await this.journal.readStream(stream))
171
+ .map(selectGitHubAdapterEvent)
172
+ .filter((event) => event !== null);
173
+ const recovered = new Set(events
174
+ .filter((event) => event.eventType === GitHubEventType.ConversationRecordRecovered)
175
+ .map((event) => event.payload.sourceEventId));
176
+ const pending = events
177
+ .filter((event) => event.eventType === GitHubEventType.ConversationRecordDeferred)
178
+ .filter((event) => !recovered.has(event.payload.sourceEventId));
179
+ this.conversationRecordRecoveryPending = pending.length > 0;
180
+ let stillPending = false;
181
+ for (const deferred of pending) {
182
+ const source = events.find((event) => event.eventId === deferred.payload.sourceEventId);
183
+ if (source?.eventType !== GitHubEventType.CommentObserved) {
184
+ stillPending = true;
185
+ continue;
186
+ }
187
+ try {
188
+ await this.recordConversationEntry(source);
189
+ }
190
+ catch {
191
+ stillPending = true;
192
+ continue;
193
+ }
194
+ await this.appendConversationRecordFact(GitHubEventType.ConversationRecordRecovered, source);
195
+ }
196
+ this.conversationRecordRecoveryPending = stillPending;
197
+ }
198
+ async recordConversationDeferred(event) {
199
+ await this.appendConversationRecordFact(GitHubEventType.ConversationRecordDeferred, event);
200
+ this.conversationRecordRecoveryPending = true;
201
+ }
202
+ async appendConversationRecordFact(eventType, source) {
203
+ const stream = integrationStream(this.adapter);
204
+ const eventId = `github:${eventType}:${this.adapter}:${source.eventId}`;
205
+ const existing = await this.journal.readStream(stream);
206
+ if (existing.some((event) => event.eventId === eventId))
207
+ return;
208
+ await this.journal.append(stream, existing.length, [
209
+ createEventDraft({
210
+ eventId,
211
+ eventType,
212
+ occurredAt: source.occurredAt,
213
+ correlationId: source.correlationId,
214
+ causationId: source.eventId,
215
+ actor: { kind: EventActorKind.Integration, id: this.adapter },
216
+ source: { kind: EventSourceKind.Internal, id: 'github-inbound-translator' },
217
+ stream,
218
+ payload: { adapter: this.adapter, sourceEventId: source.eventId },
219
+ }),
220
+ ]);
221
+ }
222
+ // Conversation reconciliation keeps all entry identity decisions in one ordered command path.
223
+ async recordConversationEntry(event) {
224
+ if (this.conversations === undefined || this.resources === undefined)
225
+ return;
226
+ const resource = await this.resources.findByExternalKey({
227
+ adapter: this.adapter,
228
+ key: event.payload.externalKey,
229
+ });
230
+ if (resource === null)
231
+ return;
232
+ const correlation = await this.resources.primaryCorrelation(resource.resourceId);
233
+ if (correlation === null)
234
+ return;
235
+ const conversationId = conversationIdForWorkItem(correlation.workItemId);
236
+ await this.conversations.createForWorkItem(correlation.workItemId, commandContext(event));
237
+ await this.conversations.associateResource({
238
+ conversationId,
239
+ resourceId: resource.resourceId,
240
+ threadId: resource.externalKey.key,
241
+ }, commandContext(event));
242
+ const externalId = observedCommentExternalId(event);
243
+ const existing = await this.conversations.forWorkItem(correlation.workItemId);
244
+ const priorEntry = existing?.entries.find((entry) => entry.origin.kind === ConversationOriginKind.External &&
245
+ entry.origin.resourceId === resource.resourceId &&
246
+ entry.origin.messageId === externalId);
247
+ if (existing?.entries.some((entry) => entry.representations.some((representation) => representation.resourceId === resource.resourceId &&
248
+ representation.externalId === externalId)))
249
+ return;
250
+ if (priorEntry !== undefined) {
251
+ if (priorEntry.body !== event.payload.body)
252
+ await this.conversations.revise({
253
+ conversationId,
254
+ entryId: priorEntry.entryId,
255
+ body: event.payload.body,
256
+ }, commandContext(event));
257
+ return;
258
+ }
259
+ await this.conversations.record({
260
+ conversationId,
261
+ entryId: event.eventId,
262
+ body: event.payload.body,
263
+ origin: {
264
+ kind: ConversationOriginKind.External,
265
+ adapter: this.adapter,
266
+ actorId: event.payload.actor.id,
267
+ resourceId: resource.resourceId,
268
+ threadId: resource.externalKey.key,
269
+ messageId: externalId,
270
+ ...(event.payload.reviewKind !== 'issue' || event.payload.location === undefined
271
+ ? {}
272
+ : { location: event.payload.location }),
273
+ },
274
+ }, commandContext(event));
275
+ }
155
276
  async failureRecorded(sourceEventId) {
156
277
  return (await this.journal.readStream(integrationStream(this.adapter))).some((event) => {
157
278
  const owned = selectGitHubAdapterEvent(event);
@@ -449,6 +570,7 @@ export class InboundTranslator {
449
570
  throw new Error('InboundTranslator requires work, resources, orchestration, and routing');
450
571
  return {
451
572
  work: this.work,
573
+ ...(this.conversations === undefined ? {} : { conversations: this.conversations }),
452
574
  resources: this.resources,
453
575
  orchestration: this.orchestration,
454
576
  routing: this.routing,
@@ -600,3 +722,7 @@ export class InboundTranslator {
600
722
  }
601
723
  }
602
724
  }
725
+ function observedCommentExternalId(event) {
726
+ const id = event.payload.raw.id;
727
+ return typeof id === 'string' || typeof id === 'number' ? String(id) : event.eventId;
728
+ }
@@ -15,6 +15,8 @@ export const GitHubEventType = {
15
15
  InboundTranslationRetried: 'integration.github.inbound-translation-retried',
16
16
  InboundTranslationRecovered: 'integration.github.inbound-translation-recovered',
17
17
  InboundTranslationFailed: 'integration.github.inbound-translation-failed',
18
+ ConversationRecordDeferred: 'integration.github.conversation-record-deferred',
19
+ ConversationRecordRecovered: 'integration.github.conversation-record-recovered',
18
20
  };
19
21
  const streamSchema = z
20
22
  .object({
@@ -49,6 +51,16 @@ const authorizationSchema = z.discriminatedUnion('source', [
49
51
  z.object({ source: z.literal(ReviewerAuthorizationSource.None) }).strict(),
50
52
  ]);
51
53
  const eventSchema = z.discriminatedUnion('eventType', [
54
+ eventEnvelopeSchema.extend({
55
+ eventType: z.literal(GitHubEventType.ConversationRecordDeferred),
56
+ stream: streamSchema,
57
+ payload: z.object({ adapter: z.string(), sourceEventId: z.string() }).strict(),
58
+ }),
59
+ eventEnvelopeSchema.extend({
60
+ eventType: z.literal(GitHubEventType.ConversationRecordRecovered),
61
+ stream: streamSchema,
62
+ payload: z.object({ adapter: z.string(), sourceEventId: z.string() }).strict(),
63
+ }),
52
64
  eventEnvelopeSchema.extend({
53
65
  eventType: z.literal(GitHubEventType.WorkObserved),
54
66
  stream: streamSchema,
@@ -158,6 +158,7 @@ export const gitHubProviderDefinition = {
158
158
  routing: services.routing,
159
159
  intake: config.intake,
160
160
  conclusion: services.conclusion,
161
+ conversations: services.conversations,
161
162
  }),
162
163
  checkConnectivity: async () => {
163
164
  await client.authenticatedLogin();