@atolis-hq/wake 0.3.97 → 0.3.99

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 (28) hide show
  1. package/dist/src/activities/agent/agent-activity.js +4 -2
  2. package/dist/src/bootstrap/initialise.js +6 -6
  3. package/dist/src/bootstrap/integration-runtime.js +3 -1
  4. package/dist/src/bootstrap/runner-registry.js +1 -1
  5. package/dist/src/bootstrap/version.js +1 -1
  6. package/dist/src/execution/application/execution-activity.js +11 -0
  7. package/dist/src/execution/contracts/config.js +8 -1
  8. package/dist/src/execution/contracts/vocabulary.js +1 -0
  9. package/dist/src/execution/infrastructure/process-execution.js +113 -30
  10. package/dist/src/execution/infrastructure/runners/claude.js +20 -4
  11. package/dist/src/execution/infrastructure/runners/codex.js +1 -1
  12. package/dist/src/execution/infrastructure/runners/command.js +2 -2
  13. package/dist/src/execution/infrastructure/runners/cursor.js +1 -1
  14. package/dist/src/execution/infrastructure/workspace/prepare-workspace.js +1 -1
  15. package/dist/src/integrations/application/poll-service.js +20 -11
  16. package/dist/src/integrations/fake/inbound-translator.js +13 -2
  17. package/dist/src/integrations/github/application/inbound-translator.js +252 -33
  18. package/dist/src/integrations/github/contracts/events.js +37 -0
  19. package/dist/src/resources/application/resource-correlation-retry.js +110 -0
  20. package/dist/src/resources/application/resource-projections.js +58 -6
  21. package/dist/src/resources/application/resource-repository.js +15 -1
  22. package/dist/src/resources/application/resource-service.js +16 -0
  23. package/dist/src/resources/contracts/events.js +45 -1
  24. package/dist/src/resources/contracts/vocabulary.js +4 -0
  25. package/dist/src/resources/domain/resource.js +50 -1
  26. package/dist/src/surfaces/web-assets/assets/{index-0vTT3Aar.js → index-YyzRROrS.js} +12 -12
  27. package/dist/src/surfaces/web-assets/index.html +1 -1
  28. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable max-lines */
2
2
  import { ActivityEventType, createPullRequestService, } from '../../../activities/index.js';
3
- import { createEventDraft, EventActorKind, EventSourceKind, UlidIdGenerator, WrongExpectedSequenceError, } from '../../../kernel/index.js';
3
+ import { correlationId, createEventDraft, EventActorKind, EventSourceKind, UlidIdGenerator, WrongExpectedSequenceError, } from '../../../kernel/index.js';
4
4
  import { BuiltInResourceCapability, BuiltInResourceKind, ResourceCorrelationRole, ResourceEventType, resourceId, resourceStream, } from '../../../resources/index.js';
5
5
  import { workItemId } from '../../../work/index.js';
6
6
  import { admitObservedWork } from '../../application/work-admission.js';
@@ -69,7 +69,6 @@ export class InboundTranslator {
69
69
  intake;
70
70
  conclusion;
71
71
  // Adapter filtering, checkpointing, and typed event dispatch must stay together.
72
- // eslint-disable-next-line complexity
73
72
  async runOnce(limit = 100) {
74
73
  if (this.journal === undefined ||
75
74
  this.checkpoints === undefined ||
@@ -77,35 +76,190 @@ export class InboundTranslator {
77
76
  this.resources === undefined) {
78
77
  throw new Error('InboundTranslator services are required to run evidence translation');
79
78
  }
79
+ // Retry state is resource-scoped, so it progresses even when the provider
80
+ // has no further observations for the broken resource.
81
+ await this.resources.retryPendingWorkCorrelations();
82
+ await this.applyDeferredExternalOutcomes();
80
83
  const checkpoint = `reactor:integration.${this.adapter}.inbound`;
84
+ await this.retryPendingTranslations();
81
85
  const position = await this.checkpoints.load(checkpoint);
82
86
  const events = await this.journal.readAll(position, limit);
83
87
  for (const event of events) {
84
- const owned = selectGitHubAdapterEvent(event);
85
- if (owned?.stream.id === this.adapter && owned.eventType === GitHubEventType.WorkObserved)
88
+ await this.translateEvent(event);
89
+ await this.checkpoints.save(checkpoint, event.globalPosition);
90
+ }
91
+ return events.length;
92
+ }
93
+ async retryPendingTranslations() {
94
+ const events = await this.journal.readStream(integrationStream(this.adapter));
95
+ const owned = events
96
+ .map(selectGitHubAdapterEvent)
97
+ .filter((event) => event !== null);
98
+ const failures = new Set(owned
99
+ .filter((event) => event.eventType === GitHubEventType.InboundTranslationFailed)
100
+ .map((event) => event.payload.sourceEventId));
101
+ const pending = new Set(owned
102
+ .filter((event) => event.eventType === GitHubEventType.InboundTranslationRetried)
103
+ .map((event) => event.payload.sourceEventId));
104
+ const recovered = new Set(owned
105
+ .filter((event) => event.eventType === GitHubEventType.InboundTranslationRecovered)
106
+ .map((event) => event.payload.sourceEventId));
107
+ for (const event of owned) {
108
+ if (pending.has(event.eventId) &&
109
+ !failures.has(event.eventId) &&
110
+ !recovered.has(event.eventId) &&
111
+ this.isTranslatable(event))
112
+ await this.translateEvent(event);
113
+ }
114
+ }
115
+ isTranslatable(event) {
116
+ return (event.stream.id === this.adapter &&
117
+ (event.eventType === GitHubEventType.WorkObserved ||
118
+ event.eventType === GitHubEventType.CommentObserved));
119
+ }
120
+ async translateEvent(event) {
121
+ const owned = selectGitHubAdapterEvent(event);
122
+ if (owned === null || !this.isTranslatable(owned))
123
+ return;
124
+ if (await this.failureRecorded(owned.eventId))
125
+ return;
126
+ try {
127
+ if (owned.eventType === GitHubEventType.WorkObserved)
86
128
  await this.apply(owned);
87
- if (owned?.stream.id === this.adapter &&
88
- owned.eventType === GitHubEventType.CommentObserved) {
89
- await applyReviewSignal({
90
- event: owned,
91
- journal: this.journal,
92
- resources: this.resources,
93
- work: this.work,
94
- lookup: this.lookup,
95
- pullRequests: this.pullRequests,
96
- ids: this.ids,
97
- adapter: this.adapter,
98
- orchestration: this.orchestration,
99
- });
129
+ if (owned.eventType === GitHubEventType.CommentObserved) {
130
+ if (!(await this.suppressWorkItemEffects(owned)))
131
+ await applyReviewSignal({
132
+ event: owned,
133
+ journal: this.journal,
134
+ resources: this.resources,
135
+ work: this.work,
136
+ lookup: this.lookup,
137
+ pullRequests: this.pullRequests,
138
+ ids: this.ids,
139
+ adapter: this.adapter,
140
+ orchestration: this.orchestration,
141
+ });
100
142
  await applyWatchGateVerdictSignal({
101
143
  event: owned,
102
144
  runs: this.runs,
103
145
  orchestration: this.orchestration,
104
146
  });
105
147
  }
106
- await this.checkpoints.save(checkpoint, event.globalPosition);
148
+ if (await this.retryRecorded(owned.eventId))
149
+ await this.recordTranslationRecovery(owned);
107
150
  }
108
- return events.length;
151
+ catch (error) {
152
+ await this.recordTranslationFailure(owned, error);
153
+ }
154
+ }
155
+ async failureRecorded(sourceEventId) {
156
+ return (await this.journal.readStream(integrationStream(this.adapter))).some((event) => {
157
+ const owned = selectGitHubAdapterEvent(event);
158
+ return (owned?.eventType === GitHubEventType.InboundTranslationFailed &&
159
+ owned.payload.sourceEventId === sourceEventId);
160
+ });
161
+ }
162
+ async retryRecorded(sourceEventId) {
163
+ return (await this.journal.readStream(integrationStream(this.adapter))).some((event) => {
164
+ const owned = selectGitHubAdapterEvent(event);
165
+ return (owned?.eventType === GitHubEventType.InboundTranslationRetried &&
166
+ owned.payload.sourceEventId === sourceEventId);
167
+ });
168
+ }
169
+ async recordTranslationRecovery(event) {
170
+ const stream = integrationStream(this.adapter);
171
+ const eventId = `github:inbound-translation-recovered:${this.adapter}:${event.eventId}`;
172
+ const existing = await this.journal.readStream(stream);
173
+ if (existing.some((candidate) => candidate.eventId === eventId))
174
+ return;
175
+ await this.journal.append(stream, existing.length, [
176
+ createEventDraft({
177
+ eventId,
178
+ eventType: GitHubEventType.InboundTranslationRecovered,
179
+ occurredAt: event.occurredAt,
180
+ correlationId: event.correlationId,
181
+ causationId: event.eventId,
182
+ actor: { kind: EventActorKind.Integration, id: this.adapter },
183
+ source: { kind: EventSourceKind.Internal, id: 'github-inbound-translator' },
184
+ stream,
185
+ payload: { adapter: this.adapter, sourceEventId: event.eventId },
186
+ }),
187
+ ]);
188
+ }
189
+ async recordTranslationFailure(event, error) {
190
+ const stream = integrationStream(this.adapter);
191
+ const existing = await this.journal.readStream(stream);
192
+ const retries = existing.reduce((count, candidate) => {
193
+ const owned = selectGitHubAdapterEvent(candidate);
194
+ return (count +
195
+ Number(owned?.eventType === GitHubEventType.InboundTranslationRetried &&
196
+ owned.payload.sourceEventId === event.eventId));
197
+ }, 0);
198
+ const attempt = retries + 1;
199
+ const message = error instanceof Error ? error.message : String(error);
200
+ const terminal = retries >= 3;
201
+ const eventId = terminal
202
+ ? `github:inbound-translation-failed:${this.adapter}:${event.eventId}`
203
+ : `github:inbound-translation-retried:${this.adapter}:${event.eventId}:${attempt}`;
204
+ const payload = terminal
205
+ ? {
206
+ adapter: this.adapter,
207
+ sourceEventId: event.eventId,
208
+ attempt,
209
+ message,
210
+ globalPosition: event.globalPosition,
211
+ eventType: event.eventType,
212
+ correlationId: event.correlationId,
213
+ causationId: event.causationId,
214
+ failedAt: event.occurredAt,
215
+ }
216
+ : { adapter: this.adapter, sourceEventId: event.eventId, attempt, message };
217
+ await this.appendTranslationDiagnostic(eventId, terminal
218
+ ? GitHubEventType.InboundTranslationFailed
219
+ : GitHubEventType.InboundTranslationRetried, event, payload);
220
+ console.error(`Inbound translation failed for ${event.eventId} (attempt ${attempt})`, error);
221
+ }
222
+ async appendTranslationDiagnostic(eventId, eventType, source, payload) {
223
+ const stream = integrationStream(this.adapter);
224
+ for (let contentionAttempts = 0; contentionAttempts < 3; contentionAttempts += 1) {
225
+ const existing = await this.journal.readStream(stream);
226
+ if (existing.some((event) => event.eventId === eventId))
227
+ return;
228
+ try {
229
+ await this.journal.append(stream, existing.length, [
230
+ createEventDraft({
231
+ eventId,
232
+ eventType,
233
+ occurredAt: source.occurredAt,
234
+ correlationId: source.correlationId,
235
+ causationId: source.eventId,
236
+ actor: { kind: EventActorKind.Integration, id: this.adapter },
237
+ source: { kind: EventSourceKind.Internal, id: 'github-inbound-translator' },
238
+ stream,
239
+ payload,
240
+ }),
241
+ ]);
242
+ return;
243
+ }
244
+ catch (error) {
245
+ if (!(error instanceof WrongExpectedSequenceError))
246
+ throw error;
247
+ }
248
+ }
249
+ throw new Error(`Could not record inbound translation diagnostic ${eventId} after contention`);
250
+ }
251
+ async suppressWorkItemEffects(event) {
252
+ const resourceIdValue = await this.lookup?.resourceIdForExternalKey({
253
+ adapter: this.adapter,
254
+ key: event.payload.externalKey,
255
+ });
256
+ if (resourceIdValue === null || resourceIdValue === undefined)
257
+ return false;
258
+ const hasPrimary = (await this.resources.correlations(resourceIdValue)).some((correlation) => correlation.role === ResourceCorrelationRole.Primary);
259
+ if (hasPrimary)
260
+ return false;
261
+ await this.resources.noteMissingPrimaryCorrelation(resourceIdValue, 'Resource has no active primary WorkItem correlation', commandContext(event));
262
+ return true;
109
263
  }
110
264
  async apply(event) {
111
265
  if (this.work === undefined || this.resources === undefined)
@@ -119,21 +273,14 @@ export class InboundTranslator {
119
273
  const identity = await this.resolveIdentity({ adapter: this.adapter, key: payload.externalKey }, intake.admitted);
120
274
  if (identity === null)
121
275
  return;
122
- if (identity.deleted) {
123
- await this.recordDeletedWorkObservation(event, identity.workItemId);
124
- return;
125
- }
126
276
  if (!identity.created) {
127
- await this.applyReobservation({
128
- payload,
129
- context,
130
- pullRequests,
131
- resourceId: identity.resourceId,
132
- workItemId: identity.workItemId,
133
- });
277
+ await this.applyExistingObservation(event, payload, context, pullRequests, identity);
134
278
  return;
135
279
  }
136
- const { resourceId: resourceIdValue, workItemId: workItemIdValue } = identity;
280
+ const resourceIdValue = identity.resourceId;
281
+ const workItemIdValue = identity.workItemId;
282
+ if (workItemIdValue === null)
283
+ throw new Error('Created identity is missing a WorkItem');
137
284
  const isPullRequest = payload.kind === 'pull-request';
138
285
  await admitObservedWork(this.admissionServices(), {
139
286
  adapter: this.adapter,
@@ -159,6 +306,66 @@ export class InboundTranslator {
159
306
  }
160
307
  : undefined);
161
308
  }
309
+ async applyExistingObservation(event, payload, context, pullRequests, identity) {
310
+ if (identity.missingPrimary) {
311
+ await this.recordMissingPrimaryObservation(identity.resourceId, payload, context);
312
+ return;
313
+ }
314
+ const workItemIdValue = identity.workItemId;
315
+ if (workItemIdValue === null)
316
+ throw new Error('Resolved identity is missing a WorkItem');
317
+ if (identity.deleted) {
318
+ await this.recordDeletedWorkObservation(event, workItemIdValue);
319
+ return;
320
+ }
321
+ await this.applyReobservation({
322
+ payload,
323
+ context,
324
+ pullRequests,
325
+ resourceId: identity.resourceId,
326
+ workItemId: workItemIdValue,
327
+ });
328
+ }
329
+ async recordMissingPrimaryObservation(resourceIdValue, payload, context) {
330
+ const current = await this.resources.get(resourceIdValue);
331
+ if (current === null)
332
+ throw new Error(`Resource ${resourceIdValue} could not be loaded`);
333
+ if (current.revision !== payload.revision)
334
+ await this.resources.discover({
335
+ resourceId: current.resourceId,
336
+ kind: current.kind,
337
+ externalKey: current.externalKey,
338
+ capabilities: current.capabilities,
339
+ revision: payload.revision,
340
+ ...(current.title === undefined ? {} : { title: current.title }),
341
+ }, context);
342
+ await this.resources.noteMissingPrimaryCorrelation(resourceIdValue, 'Resource has no active primary WorkItem correlation', context);
343
+ await this.resources.observeExternalOutcome(resourceIdValue, {
344
+ sourceObservationId: context.commandId,
345
+ ...(payload.outcome === undefined ? {} : { outcome: payload.outcome }),
346
+ revision: payload.revision,
347
+ }, context);
348
+ }
349
+ async applyDeferredExternalOutcomes() {
350
+ if (this.conclusion === undefined)
351
+ return;
352
+ for (const pending of await this.resources.pendingExternalOutcomes()) {
353
+ const primary = (await this.resources.correlations(pending.resourceId)).find((correlation) => correlation.role === ResourceCorrelationRole.Primary);
354
+ if (primary === undefined)
355
+ continue;
356
+ await concludeObservedWork({ work: this.work, conclusion: this.conclusion }, {
357
+ workItemId: primary.workItemId,
358
+ outcome: pending.outcome,
359
+ reason: `${this.adapter} external outcome observed while correlation was unresolved`,
360
+ });
361
+ await this.resources.consumeExternalOutcome(pending.resourceId, pending.sourceObservationId, {
362
+ commandId: `github:consume-external-outcome:${pending.sourceObservationId}`,
363
+ correlationId: correlationId(`github:external-outcome:${pending.sourceObservationId}`),
364
+ occurredAt: new Date().toISOString(),
365
+ actor: { kind: EventActorKind.Integration, id: this.adapter },
366
+ });
367
+ }
368
+ }
162
369
  async applyReobservation(input) {
163
370
  const { payload, context, pullRequests, resourceId: resourceIdValue, workItemId: workItemIdValue, } = input;
164
371
  const current = await this.resources.get(resourceIdValue);
@@ -278,7 +485,13 @@ export class InboundTranslator {
278
485
  async historicalIdentity(resourceIdValue) {
279
486
  const historical = await this.resources.primaryCorrelation(resourceIdValue);
280
487
  if (historical === null)
281
- throw new Error(`Resource ${resourceIdValue} has no primary correlation`);
488
+ return {
489
+ resourceId: resourceIdValue,
490
+ workItemId: null,
491
+ created: false,
492
+ deleted: false,
493
+ missingPrimary: true,
494
+ };
282
495
  const historicalWork = await this.work?.get(historical.workItemId);
283
496
  if (historicalWork?.deleted)
284
497
  return {
@@ -287,7 +500,13 @@ export class InboundTranslator {
287
500
  created: false,
288
501
  deleted: true,
289
502
  };
290
- throw new Error(`Resource ${resourceIdValue} has no active primary correlation`);
503
+ return {
504
+ resourceId: resourceIdValue,
505
+ workItemId: historical.workItemId,
506
+ created: false,
507
+ deleted: false,
508
+ missingPrimary: true,
509
+ };
291
510
  }
292
511
  async recordDeletedWorkObservation(event, workItemId) {
293
512
  const stream = integrationStream(this.adapter);
@@ -10,6 +10,9 @@ export const GitHubEventType = {
10
10
  CommentObserved: 'integration.github.comment-observed',
11
11
  DeliveryObserved: 'integration.github.delivery-observed',
12
12
  DeletedWorkObservationSkipped: 'integration.github.deleted-work-observation-skipped',
13
+ InboundTranslationRetried: 'integration.github.inbound-translation-retried',
14
+ InboundTranslationRecovered: 'integration.github.inbound-translation-recovered',
15
+ InboundTranslationFailed: 'integration.github.inbound-translation-failed',
13
16
  };
14
17
  const streamSchema = z
15
18
  .object({
@@ -129,6 +132,40 @@ const eventSchema = z.discriminatedUnion('eventType', [
129
132
  })
130
133
  .strict(),
131
134
  }),
135
+ eventEnvelopeSchema.extend({
136
+ eventType: z.literal(GitHubEventType.InboundTranslationRetried),
137
+ stream: streamSchema,
138
+ payload: z
139
+ .object({
140
+ adapter: z.string(),
141
+ sourceEventId: z.string(),
142
+ attempt: z.number().int().positive(),
143
+ message: z.string(),
144
+ })
145
+ .strict(),
146
+ }),
147
+ eventEnvelopeSchema.extend({
148
+ eventType: z.literal(GitHubEventType.InboundTranslationRecovered),
149
+ stream: streamSchema,
150
+ payload: z.object({ adapter: z.string(), sourceEventId: z.string() }).strict(),
151
+ }),
152
+ eventEnvelopeSchema.extend({
153
+ eventType: z.literal(GitHubEventType.InboundTranslationFailed),
154
+ stream: streamSchema,
155
+ payload: z
156
+ .object({
157
+ adapter: z.string(),
158
+ sourceEventId: z.string(),
159
+ attempt: z.number().int().positive(),
160
+ message: z.string(),
161
+ globalPosition: z.number().int().positive(),
162
+ eventType: z.string(),
163
+ correlationId: z.string(),
164
+ causationId: z.string(),
165
+ failedAt: z.string(),
166
+ })
167
+ .strict(),
168
+ }),
132
169
  ]);
133
170
  export function decodeGitHubAdapterEvent(event) {
134
171
  const result = eventSchema.safeParse(event);
@@ -0,0 +1,110 @@
1
+ import { correlationId, createEventDraft, EventActorKind, EventSourceKind, } from '../../kernel/index.js';
2
+ import { ResourceEventType, } from '../contracts/events.js';
3
+ import { resourceStream } from '../contracts/streams.js';
4
+ import { ResourceCorrelationRole } from '../contracts/vocabulary.js';
5
+ export async function observeExternalOutcome(repository, resourceId, observation, context) {
6
+ if (observation.outcome === undefined) {
7
+ await appendResourceEvent(repository, resourceId, resourceDraft(resourceId, context, ResourceEventType.ExternalOutcomeReopened, {
8
+ revision: observation.revision,
9
+ }));
10
+ return;
11
+ }
12
+ await appendResourceEvent(repository, resourceId, resourceDraft(resourceId, context, ResourceEventType.ExternalOutcomeObserved, {
13
+ sourceObservationId: observation.sourceObservationId,
14
+ outcome: observation.outcome,
15
+ revision: observation.revision,
16
+ }));
17
+ }
18
+ export async function pendingExternalOutcomes(repository) {
19
+ const pending = [];
20
+ for (const resourceId of await repository.listResourceIds()) {
21
+ const resource = (await repository.load(resourceId)).resource;
22
+ if (resource?.view.pendingExternalOutcome !== undefined && hasPrimary(resource.correlations))
23
+ pending.push({ resourceId, ...resource.view.pendingExternalOutcome });
24
+ }
25
+ return pending;
26
+ }
27
+ export async function noteMissingPrimaryCorrelation(repository, resourceId, reason, context) {
28
+ const loaded = await repository.load(resourceId);
29
+ if (loaded.resource === null || hasPrimary(loaded.resource.correlations))
30
+ return;
31
+ if (loaded.resource.view.correlationStatus === 'unresolvable')
32
+ return;
33
+ if (retryAttempts(loaded.resource.events) > 0)
34
+ return;
35
+ await repository.append(resourceId, loaded.sequence, [
36
+ resourceDraft(resourceId, context, ResourceEventType.WorkCorrelationRetryPending, {
37
+ attemptCount: 1,
38
+ lastFailureReason: reason,
39
+ }),
40
+ ]);
41
+ }
42
+ export async function retryPendingWorkCorrelations(repository) {
43
+ let processed = 0;
44
+ for (const resourceId of await repository.listResourceIds()) {
45
+ const loaded = await repository.load(resourceId);
46
+ if (loaded.resource === null || hasPrimary(loaded.resource.correlations))
47
+ continue;
48
+ if (loaded.resource.view.correlationStatus === 'unresolvable')
49
+ continue;
50
+ const attempts = retryAttempts(loaded.resource.events);
51
+ if (attempts === 0)
52
+ continue;
53
+ const last = [...loaded.resource.events]
54
+ .reverse()
55
+ .find((event) => event.eventType === ResourceEventType.WorkCorrelationRetryPending);
56
+ const reason = last?.payload.lastFailureReason ?? 'Resource has no active primary WorkItem correlation';
57
+ const attemptCount = attempts + 1;
58
+ const context = {
59
+ commandId: `resource:${resourceId}:missing-primary:${attemptCount}`,
60
+ correlationId: correlationId(`resource:${resourceId}:missing-primary`),
61
+ occurredAt: new Date().toISOString(),
62
+ actor: { kind: EventActorKind.System, id: 'resource-service' },
63
+ };
64
+ const draft = attemptCount >= 4
65
+ ? resourceDraft(resourceId, context, ResourceEventType.WorkCorrelationUnresolvable, {
66
+ externalKey: loaded.resource.view.externalKey,
67
+ attemptCount,
68
+ lastFailureReason: reason,
69
+ })
70
+ : resourceDraft(resourceId, context, ResourceEventType.WorkCorrelationRetryPending, {
71
+ attemptCount,
72
+ lastFailureReason: reason,
73
+ });
74
+ await repository.append(resourceId, loaded.sequence, [draft]);
75
+ processed += 1;
76
+ }
77
+ return processed;
78
+ }
79
+ function hasPrimary(correlations) {
80
+ return correlations.some((value) => value.role === ResourceCorrelationRole.Primary);
81
+ }
82
+ function retryAttempts(events) {
83
+ let attempts = 0;
84
+ for (let index = events.length - 1; index >= 0; index -= 1) {
85
+ const event = events[index];
86
+ if (event.eventType === ResourceEventType.WorkCorrelationEstablished &&
87
+ event.payload.role === ResourceCorrelationRole.Primary)
88
+ break;
89
+ if (event.eventType === ResourceEventType.WorkCorrelationRetryPending)
90
+ attempts = Math.max(attempts, event.payload.attemptCount);
91
+ }
92
+ return attempts;
93
+ }
94
+ async function appendResourceEvent(repository, resourceId, draft) {
95
+ const loaded = await repository.load(resourceId);
96
+ await repository.append(resourceId, loaded.sequence, [draft]);
97
+ }
98
+ function resourceDraft(resourceId, context, eventType, payload) {
99
+ return createEventDraft({
100
+ eventId: `${context.commandId}:${eventType}`,
101
+ eventType,
102
+ occurredAt: context.occurredAt,
103
+ correlationId: context.correlationId,
104
+ causationId: context.commandId,
105
+ actor: context.actor,
106
+ source: { kind: EventSourceKind.Internal, id: 'resource-service' },
107
+ stream: resourceStream(resourceId),
108
+ payload,
109
+ });
110
+ }
@@ -1,4 +1,5 @@
1
1
  import { ResourceEventType, selectResourceEvent } from '../contracts/events.js';
2
+ import { ResourceCorrelationRole } from '../contracts/vocabulary.js';
2
3
  export const resourceProjection = {
3
4
  name: 'resources',
4
5
  select(event) {
@@ -11,6 +12,10 @@ export const resourceProjection = {
11
12
  const owned = selectResourceEvent(event);
12
13
  if (owned === null)
13
14
  return previous;
15
+ if (isExternalOutcome(owned))
16
+ return projectExternalOutcome(previous, owned);
17
+ if (isCorrelationRetry(owned))
18
+ return projectCorrelationRetry(previous, owned);
14
19
  switch (owned.eventType) {
15
20
  case ResourceEventType.ResourceDiscovered:
16
21
  return {
@@ -35,6 +40,11 @@ export const resourceProjection = {
35
40
  },
36
41
  };
37
42
  case ResourceEventType.WorkCorrelationEstablished:
43
+ return previous === null
44
+ ? previous
45
+ : owned.payload.role === ResourceCorrelationRole.Primary
46
+ ? withoutCorrelationStatus(previous)
47
+ : previous;
38
48
  case ResourceEventType.WorkCorrelationRetracted:
39
49
  case ResourceEventType.IssueCompletionObservationConsumed:
40
50
  case ResourceEventType.IssueCompletionObservationSuperseded:
@@ -44,6 +54,48 @@ export const resourceProjection = {
44
54
  }
45
55
  },
46
56
  };
57
+ function isCorrelationRetry(event) {
58
+ return (event.eventType === ResourceEventType.WorkCorrelationRetryPending ||
59
+ event.eventType === ResourceEventType.WorkCorrelationUnresolvable);
60
+ }
61
+ function isExternalOutcome(event) {
62
+ return (event.eventType === ResourceEventType.ExternalOutcomeObserved ||
63
+ event.eventType === ResourceEventType.ExternalOutcomeReopened ||
64
+ event.eventType === ResourceEventType.ExternalOutcomeConsumed);
65
+ }
66
+ function projectCorrelationRetry(previous, event) {
67
+ switch (event.eventType) {
68
+ case ResourceEventType.WorkCorrelationRetryPending:
69
+ return previous;
70
+ case ResourceEventType.WorkCorrelationUnresolvable:
71
+ return previous === null ? previous : { ...previous, correlationStatus: 'unresolvable' };
72
+ default:
73
+ return assertNever(event);
74
+ }
75
+ }
76
+ function projectExternalOutcome(previous, event) {
77
+ switch (event.eventType) {
78
+ case ResourceEventType.ExternalOutcomeObserved:
79
+ return previous === null ? previous : { ...previous, pendingExternalOutcome: event.payload };
80
+ case ResourceEventType.ExternalOutcomeReopened:
81
+ return previous === null ? previous : withoutPendingExternalOutcome(previous);
82
+ case ResourceEventType.ExternalOutcomeConsumed:
83
+ return previous?.pendingExternalOutcome?.sourceObservationId ===
84
+ event.payload.sourceObservationId
85
+ ? withoutPendingExternalOutcome(previous)
86
+ : previous;
87
+ default:
88
+ return assertNever(event);
89
+ }
90
+ }
91
+ function withoutCorrelationStatus(view) {
92
+ const { correlationStatus: _correlationStatus, ...withoutStatus } = view;
93
+ return withoutStatus;
94
+ }
95
+ function withoutPendingExternalOutcome(view) {
96
+ const { pendingExternalOutcome: _pendingExternalOutcome, ...withoutOutcome } = view;
97
+ return withoutOutcome;
98
+ }
47
99
  export const resourceCorrelationProjection = {
48
100
  name: 'resource-correlations',
49
101
  select(event) {
@@ -55,6 +107,8 @@ export const resourceCorrelationProjection = {
55
107
  const owned = selectResourceEvent(event);
56
108
  if (owned === null)
57
109
  return previous;
110
+ if (!changesCorrelation(owned))
111
+ return previous;
58
112
  switch (owned.eventType) {
59
113
  case ResourceEventType.WorkCorrelationEstablished: {
60
114
  const correlation = {
@@ -70,17 +124,15 @@ export const resourceCorrelationProjection = {
70
124
  }
71
125
  case ResourceEventType.WorkCorrelationRetracted:
72
126
  return previous.filter((value) => value.workItemId !== owned.payload.workItemId);
73
- case ResourceEventType.ResourceDiscovered:
74
- case ResourceEventType.ResourceRevisionObserved:
75
- case ResourceEventType.WorkCorrelationConflicted:
76
- case ResourceEventType.IssueCompletionObservationConsumed:
77
- case ResourceEventType.IssueCompletionObservationSuperseded:
78
- return previous;
79
127
  default:
80
128
  return assertNever(owned);
81
129
  }
82
130
  },
83
131
  };
132
+ function changesCorrelation(event) {
133
+ return (event.eventType === ResourceEventType.WorkCorrelationEstablished ||
134
+ event.eventType === ResourceEventType.WorkCorrelationRetracted);
135
+ }
84
136
  function assertNever(value) {
85
137
  throw new Error(`Unhandled Resource event: ${JSON.stringify(value)}`);
86
138
  }
@@ -1,10 +1,13 @@
1
- import { decodeResourceEvent, selectResourceEvent, } from '../contracts/events.js';
1
+ import { cachedJournalView, } from '../../kernel/index.js';
2
+ import { ResourceEventType, decodeResourceEvent, selectResourceEvent, } from '../contracts/events.js';
2
3
  import { resourceStream } from '../contracts/streams.js';
3
4
  import { foldResource } from '../domain/resource.js';
4
5
  export class ResourceRepository {
5
6
  journal;
7
+ resourceIds;
6
8
  constructor(journal) {
7
9
  this.journal = journal;
10
+ this.resourceIds = cachedJournalView(journal, deriveResourceIds);
8
11
  }
9
12
  async load(resourceId) {
10
13
  const events = await this.journal.readStream(resourceStream(resourceId));
@@ -15,4 +18,15 @@ export class ResourceRepository {
15
18
  const events = await this.journal.append(resourceStream(resourceId), expectedSequence, drafts);
16
19
  return events.map(decodeResourceEvent);
17
20
  }
21
+ async listResourceIds() {
22
+ return this.resourceIds.get();
23
+ }
24
+ }
25
+ function deriveResourceIds(events) {
26
+ return [
27
+ ...new Set(events
28
+ .map(selectResourceEvent)
29
+ .filter((event) => event?.eventType === ResourceEventType.ResourceDiscovered)
30
+ .map((event) => event.stream.id)),
31
+ ];
18
32
  }