Repository navigation
Expand file tree
/
Copy pathPullRequestSyncReactor.ts
More file actions
886 lines (841 loc) · 38 KB
/
Copy pathPullRequestSyncReactor.ts
File metadata and controls
886 lines (841 loc) · 38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
import {
CommandId,
isOrchestrationV2WorkActive,
type OrchestrationV2TurnItem,
type ProviderDriverKind,
type PullRequestSummary,
type ThreadId,
type ThreadPullRequestKey,
type ThreadPullRequestLink,
type ThreadPullRequestSnapshot,
type ThreadPullRequestStack,
} from "@t3tools/contracts";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
import {
threadPullRequestKeyOf,
normalizeThreadPullRequestKey,
threadPullRequestKeysEqual,
visibleThreadPullRequests,
} from "../sourceControl/threadPullRequests.ts";
import {
isChangeRequestCloseCommand,
sourceControlDefinitions,
} from "../sourceControl/sourceControlDefinitions.ts";
import {
classifyAgentShellCommands,
COMMAND_SEPARATOR,
COMMAND_START,
shellCode,
shellScript,
shellSegments,
} from "../sourceControl/agentShellCommands.ts";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Schedule from "effect/Schedule";
import type * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as GitManager from "../git/GitManager.ts";
import * as Metrics from "../observability/Metrics.ts";
import { PullRequestProviderError } from "@t3tools/source-control-core/server/PullRequestProvider";
import * as PullRequestService from "../pullRequest/PullRequestService.ts";
import { forkParked } from "../serverActivation.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as Orchestrator from "./Orchestrator.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import { isTerminalRunStatus } from "./ThreadManagementService.ts";
const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
// Every server polls every open linked pull request, and most of them sit untouched for days.
// One nobody has updated for QUIET_AFTER_MS is read on the quiet cadence instead of each sweep;
// requested refreshes, watches and a host CLI's merge command still read it at once.
export const QUIET_AFTER_MS = 30 * 60 * 1_000;
export const QUIET_SYNC_INTERVAL_MS = 5 * 60 * 1_000;
// A pull request closed this long ago is rarely reopened, so the sweep stops reading it, as it
// does merged ones. A reader that sees it open, or a requested refresh, still reads it at once.
const CLOSED_FINAL_AFTER_MS = 24 * 60 * 60 * 1_000;
// A link whose host read failed waits a sweep, then twice as long after each further failure.
const FAILED_READ_BACKOFF_MS = 60 * 1_000;
const CREATE_COMMANDS = sourceControlDefinitions.definitions.flatMap(
({ kind, changeRequestCreateCommand: command }) =>
command === undefined
? []
: // The subcommand must end its shell word: `gh pr create#x` runs another one.
[
{
kind,
command,
run: new RegExp(`${COMMAND_START}${command.source}(?=$|[\\s;&|)])`, "gu"),
},
],
);
const createCommandCount = (code: string) =>
CREATE_COMMANDS.reduce((count, { run }) => count + [...code.matchAll(run)].length, 0);
// A push, directly or through a stack tool, that can start checks on a linked pull request.
const PUSH_COMMAND = new RegExp(
`${COMMAND_START}(?:git(?:\\s+-[cC]\\s+\\S+)*\\s+push|gh\\s+stack\\s+(?:push|submit)|cafe\\s+stack\\s+submit|jj\\s+git\\s+push)(?=$|[\\s;&|)])`,
"u",
);
// Commands that print other change requests' URLs, so output beside them proves nothing.
const LISTS_CHANGE_REQUESTS =
/\b(?:gh\s+(?:pr\s+(?:list|status)|search\s+prs|api)|glab\s+(?:mr\s+list|api))\b/u;
const URL_LINE = /^[ \t]*(https?:\/\/\S+)[ \t]*$/gmu;
const isPushCommand = (input: string) => PUSH_COMMAND.test(shellCode(shellScript(input)));
type CommandExecution = Extract<OrchestrationV2TurnItem, { readonly type: "command_execution" }>;
/**
* The change requests a shell command opened: URLs on lines of their own in the output of a
* command that runs a host's create command. One the command also names, as `gh pr view 12`
* does, existed before it ran. More URLs than create commands means something else printed
* some, such as `gh pr list`, so none are taken.
*/
export function changeRequestsCreatedBy(input: string, output: string) {
if (!CREATE_COMMANDS.some(({ command }) => command.test(input))) return [];
const script = shellScript(input);
const code = shellCode(script);
const creates = createCommandCount(code);
if (creates === 0) return [];
const otherCommands = code
.split(COMMAND_SEPARATOR)
.filter((part) => createCommandCount(part) === 0)
.join("\n");
if (LISTS_CHANGE_REQUESTS.test(otherCommands)) return [];
const otherScript = shellSegments(script)
.filter((segment) => createCommandCount(shellCode(segment)) === 0)
.join("\n");
const creators = new Set(
CREATE_COMMANDS.filter(({ run }) => code.match(run) !== null).map(({ kind }) => kind),
);
const created = new Map<string, ThreadPullRequestKey & { readonly url: string }>();
for (const [, url = ""] of output.matchAll(URL_LINE)) {
const parsed = sourceControlDefinitions.parseChangeRequestUrl(url);
// Only the host whose create command ran can have printed a new change request.
if (parsed === null || !creators.has(parsed.definition.kind)) continue;
const { link } = parsed;
const named = new RegExp(`(?:^|(?<=[\\s#/=("']))${link.number}(?=$|[\\s);&|/"'])`, "u");
// Quoted text in the other commands counts, as in `printf '.../pull/12'`.
if (named.test(otherScript)) continue;
const key = normalizeThreadPullRequestKey(link);
created.set(threadPullRequestKeyOf(key), { ...key, url });
}
return created.size > creates ? [] : [...created.values()];
}
const isPullRequestProviderError = Schema.is(PullRequestProviderError);
type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
interface LinkEntry {
readonly thread: ProjectionStore.ProjectionThreadPullRequests;
readonly link: ThreadPullRequestLink;
}
const referenceOf = ({ thread, link }: LinkEntry) => ({
projectId: thread.projectId,
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
number: link.number,
});
/** Pauses and batching both belong to a project's host. */
const pauseKeyOf = (entry: LinkEntry) => {
const { projectId, host } = referenceOf(entry);
return `${projectId}\0${host}`;
};
/** Another layer of the stack `url` belongs to, in its host's canonical shape. */
function siblingChangeRequestUrl(url: string, number: number): string | null {
if (!Number.isSafeInteger(number) || number < 1) return null;
const parsed = sourceControlDefinitions.parseChangeRequestUrl(url);
if (parsed === null) return null;
const { definition, link } = parsed;
return definition.changeRequestUrl({
host: link.host,
repository: link.repository,
number,
webUrl: link.repositoryUrl,
});
}
function snapshotFieldsOf(summary: PullRequestSummary): SnapshotFields {
return {
state: summary.state,
title: summary.title,
headBranch: summary.headBranch,
baseBranch: summary.baseBranch,
isDraft: summary.isDraft ?? false,
updatedAt: summary.updatedAt,
closedAt: summary.closedAt ?? null,
mergedAt: summary.mergedAt ?? null,
...(summary.author === undefined ? {} : { author: summary.author }),
...(summary.additions === undefined ? {} : { additions: summary.additions }),
...(summary.deletions === undefined ? {} : { deletions: summary.deletions }),
...(summary.changedFiles === undefined ? {} : { changedFiles: summary.changedFiles }),
...(summary.reviewDecision === undefined ? {} : { reviewDecision: summary.reviewDecision }),
...(summary.checksState === undefined ? {} : { checksState: summary.checksState }),
...(summary.mergeability === undefined ? {} : { mergeability: summary.mergeability }),
...(summary.rebaseRequired === undefined ? {} : { rebaseRequired: summary.rebaseRequired }),
};
}
// GitHub briefly returns unknown after base pushes; other hosts may mean a lasting condition.
function withKnownMergeability(
previous: ThreadPullRequestSnapshot | null,
fields: SnapshotFields,
provider: PullRequestSummary["provider"],
): SnapshotFields {
if (
provider !== "github" ||
fields.state !== "open" ||
fields.mergeability !== "unknown" ||
previous?.updatedAt !== fields.updatedAt
)
return fields;
const known = previous?.state === "open" ? previous.mergeability : undefined;
return known === undefined || known === "unknown" ? fields : { ...fields, mergeability: known };
}
// Rotating ghe.com avatar tokens should not make otherwise identical snapshots differ.
function avatarIdentity(avatarUrl: string | null | undefined): string | null {
if (avatarUrl === null || avatarUrl === undefined) return null;
const url = URL.parse(avatarUrl);
if (url === null || (url.hostname !== "ghe.com" && !url.hostname.endsWith(".ghe.com"))) {
return avatarUrl;
}
url.searchParams.delete("token");
return url.href;
}
function snapshotFieldsEqual(left: SnapshotFields, right: SnapshotFields): boolean {
return (
left.state === right.state &&
left.title === right.title &&
left.headBranch === right.headBranch &&
left.baseBranch === right.baseBranch &&
left.isDraft === right.isDraft &&
left.updatedAt === right.updatedAt &&
(left.closedAt ?? null) === (right.closedAt ?? null) &&
(left.mergedAt ?? null) === (right.mergedAt ?? null) &&
(left.author?.login ?? null) === (right.author?.login ?? null) &&
avatarIdentity(left.author?.avatarUrl) === avatarIdentity(right.author?.avatarUrl) &&
left.additions === right.additions &&
left.deletions === right.deletions &&
left.changedFiles === right.changedFiles &&
(left.reviewDecision ?? null) === (right.reviewDecision ?? null) &&
(left.checksState ?? null) === (right.checksState ?? null) &&
left.mergeability === right.mergeability &&
left.rebaseRequired === right.rebaseRequired
);
}
function stacksEqual(
left: ThreadPullRequestStack | null,
right: ThreadPullRequestStack | null,
): boolean {
if (left === null || right === null) return left === right;
return (
left.kind === right.kind &&
left.id === right.id &&
left.number === right.number &&
left.url === right.url &&
left.base === right.base &&
left.layers.length === right.layers.length &&
left.layers.every((layer, index) => {
const other = right.layers[index]!;
return (
layer.number === other.number &&
layer.headBranch === other.headBranch &&
layer.state === other.state
);
})
);
}
/** Stack ids are unique only within a repository, e.g. GitHub's fallback to the stack number. */
function nativeStackKeyOf(link: ThreadPullRequestLink, stack: ThreadPullRequestStack): string {
const key = normalizeThreadPullRequestKey(link);
return `${key.host}/${key.repository}#stack:${stack.id}`;
}
function sameLayerNumbers(left: ThreadPullRequestStack, right: ThreadPullRequestStack): boolean {
return (
left.layers.length === right.layers.length &&
left.layers.every((layer, index) => layer.number === right.layers[index]!.number)
);
}
function skipReason(cause: Cause.Cause<unknown>): string {
const error = Cause.squash(cause);
return error instanceof Error ? error.message : String(error);
}
function rateLimitRetryAt(cause: Cause.Cause<unknown>): number | undefined {
let error: unknown = Cause.squash(cause);
while (error instanceof Error) {
if (isPullRequestProviderError(error) && error.reason === "rate-limited") return error.retryAt;
error = error.cause;
}
return undefined;
}
function isUnsettled(thread: ProjectionStore.ProjectionThreadPullRequests): boolean {
return thread.settledOverride !== "settled" && thread.settledAt === null;
}
export class PullRequestSyncReactor extends Context.Service<
PullRequestSyncReactor,
{
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
readonly drain: Effect.Effect<void>;
/** Forces reread on the next sweep, including terminal snapshots; rate-limited hosts wait until the pause ends. */
readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
}
>()("t3/orchestration-v2/PullRequestSyncReactor") {}
/** @public */
export const make = Effect.gen(function* () {
const engine = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const pullRequests = yield* PullRequestService.PullRequestService;
const git = yield* GitManager.GitManager;
const random = yield* SecureRandom.SecureRandom;
const lastSyncedAt = new Map<string, number>();
const requested = new Set<string>();
// Requests arriving during a host read wait for the next sweep.
const pendingRequests = new Set<string>();
// PR keys wait in `pendingRequests` for one queued sweep, so a burst of links (an agent
// linking dozens of pull requests) is read together and shares the summary batches.
let requestedSweepQueued = false;
const retryStacks = new Set<string>();
const failedReads = new Map<string, { readonly retryAtMs: number; readonly backoffMs: number }>();
// Group keys the host answered not-found for, or this server cannot read (no CLI, signed out,
// unsupported host); they are read on the slow cadence until a read succeeds.
const missing = new Set<string>();
// Pause per project and host because credentials are project-specific; leave paused PRs due until reset.
const pausedUntil = new Map<string, number>();
const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
if ((failedReads.get(key)?.retryAtMs ?? 0) > nowMs) return false;
if (requested.has(key)) return true;
const active = entries.filter((entry) => isUnsettled(entry.thread));
if (active.length === 0) return false;
const last = lastSyncedAt.get(key);
const sinceLastMs = last === undefined ? Number.POSITIVE_INFINITY : nowMs - last;
if (missing.has(key)) return sinceLastMs >= SLOW_SYNC_INTERVAL_MS;
if (retryStacks.has(key) || active.some((entry) => entry.link.snapshot === null)) return true;
// Merged snapshots without mergedAt cannot settle threads; reread slowly until supplied.
const isFinal = ({ link: { snapshot } }: LinkEntry) =>
snapshot?.state === "merged"
? snapshot.mergedAt != null
: snapshot?.state === "closed" &&
nowMs - Date.parse(snapshot.closedAt ?? "") >= CLOSED_FINAL_AFTER_MS;
if (active.every(isFinal)) return false;
const open = active.filter((entry) => entry.link.snapshot?.state === "open");
if (open.length > 0) {
const quiet = open.every((entry) => {
const updatedAt = entry.link.snapshot?.updatedAt;
return updatedAt != null && nowMs - Date.parse(updatedAt) >= QUIET_AFTER_MS;
});
return !quiet || sinceLastMs >= QUIET_SYNC_INTERVAL_MS;
}
return sinceLastMs >= SLOW_SYNC_INTERVAL_MS;
};
const logSkipped =
(message: string, fields: Record<string, unknown>) =>
<E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
const threads = yield* projections.getThreadsWithPullRequests();
const now = yield* DateTime.now;
const nowMs = DateTime.toEpochMillis(now);
const nowIso = DateTime.formatIso(now);
const groups = new Map<string, Array<LinkEntry>>();
for (const thread of threads) {
for (const link of visibleThreadPullRequests(thread.pullRequests ?? [])) {
// Reads depend on the project's checkout and credentials, including their failures.
const key = `${thread.projectId}\0${threadPullRequestKeyOf(link)}`;
const entries = groups.get(key) ?? [];
entries.push({ thread, link });
groups.set(key, entries);
}
}
// A host-level refresh reaches every project, each retaining its own pending retry.
for (const [key, entries] of groups) {
if (!pendingRequests.has(threadPullRequestKeyOf(entries[0]!.link))) continue;
requested.add(key);
// A new request reads at once; a failure after it backs off further, not from the start.
const failed = failedReads.get(key);
if (failed !== undefined) failedReads.set(key, { ...failed, retryAtMs: nowMs });
}
pendingRequests.clear();
for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
for (const key of failedReads.keys()) if (!groups.has(key)) failedReads.delete(key);
for (const key of missing) if (!groups.has(key)) missing.delete(key);
for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
const linkedThisSweep = new Set<string>();
// Fresh stack reads by group, so a member flagged by a sibling is compared against what the
// host answered this sweep, not the saved layers that sibling is about to replace.
const stacksReadThisSweep = new Map<string, ThreadPullRequestStack | null>();
const persistence = yield* Semaphore.make(1);
// Effect.fn's stack frames close over these sweep-scoped bodies and their arguments, and a
// cache lookup forked inside keeps those frames, so a plain span leaves the sweep collectable.
const syncEntry = Effect.fnUntraced(function* (
entry: LinkEntry,
hostFields: SnapshotFields,
fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
provider: PullRequestSummary["provider"],
) {
const { thread, link } = entry;
const fields = withKnownMergeability(link.snapshot, hostFields, provider);
const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
const changed =
link.snapshot === null ||
!snapshotFieldsEqual(link.snapshot, fields) ||
!stacksEqual(link.stack, nextStack);
// Persist siblings before terminal snapshots trigger settlement; settled threads get snapshots without new links.
for (const layer of isUnsettled(thread) ? (fetchedStack?.stack?.layers ?? []) : []) {
const layerKey = {
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
number: layer.number,
};
const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
if (linkedThisSweep.has(dedupeKey)) continue;
// Tombstones count as present: a dismissed layer is never re-added.
if (
(thread.pullRequests ?? []).some((existing) =>
threadPullRequestKeysEqual(existing, layerKey),
)
) {
continue;
}
const url = siblingChangeRequestUrl(link.url, layer.number);
if (url === null) continue;
const uuid = yield* random.uuidV4();
yield* engine.dispatch({
type: "thread.pull-request.link",
commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
threadId: thread.id,
...layerKey,
url,
source: "stack",
});
linkedThisSweep.add(dedupeKey);
}
if (changed) {
const uuid = yield* random.uuidV4();
yield* engine.dispatch({
type: "thread.pull-request-link.sync",
commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
threadId: thread.id,
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
number: link.number,
snapshot: { ...fields, syncedAt: nowIso },
stack: nextStack,
});
}
}, Effect.withSpan("PullRequestSyncReactor.syncEntry"));
const syncGroup = Effect.fnUntraced(function* (key: string, entries: ReadonlyArray<LinkEntry>) {
const first = entries[0]!;
const ref = referenceOf(first);
const refreshRequested = requested.has(key);
// A held merged summary is served without asking the host, so a snapshot still missing its
// merge time has to drop it or the slow-cadence re-read would hand back the same gap.
const missingMergedAt = entries.some(
(entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt == null,
);
// A stack retry reads past the cache, or it could get back the layer list it is retrying.
const invalidated = refreshRequested || missingMergedAt || retryStacks.has(key);
if (invalidated) yield* pullRequests.invalidate({ reference: ref });
const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false }).pipe(
Effect.tapError((error) =>
error.reason === "not-found" || error._tag === "PullRequestUnavailableError"
? Effect.sync(() => {
// Not-found, or a host this server cannot read, won't change by asking again
// next sweep: it consumes the refresh and starts the backoff.
missing.add(key);
lastSyncedAt.set(key, nowMs);
requested.delete(key);
})
: Effect.void,
),
);
missing.delete(key);
const fields = snapshotFieldsOf(summary);
const needsStack =
refreshRequested ||
retryStacks.has(key) ||
entries.some(
(entry) =>
entry.link.snapshot === null ||
!snapshotFieldsEqual(
entry.link.snapshot,
withKnownMergeability(entry.link.snapshot, fields, summary.provider),
) ||
(summary.stack !== undefined &&
(entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
);
const knownUnstacked =
summary.stack === null && entries.every((entry) => entry.link.stack === null);
// A sibling can flag this group while its summary read is in flight.
if (!invalidated && retryStacks.has(key) && !knownUnstacked) {
yield* pullRequests.invalidate({ reference: ref });
}
// The retry this read answers is consumed before the read, not after it: a sibling may
// flag this group again while the read is in flight, and that flag must survive to the
// next sweep because the answer below may predate the sibling's layers.
if (needsStack) retryStacks.delete(key);
const fetchedStack = !needsStack
? null
: knownUnstacked
? { stack: null }
: yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
Effect.map((stack) => ({
stack: stack === null ? null : ({ kind: "native", ...stack } as const),
})),
Effect.catchCauseIf(
(cause) => !Cause.hasInterruptsOnly(cause),
(cause) =>
rateLimitRetryAt(cause) !== undefined
? Effect.sync(() => retryStacks.add(key)).pipe(
Effect.andThen(Effect.failCause(cause)),
)
: Effect.logWarning("pull request stack lookup failed", {
key,
}).pipe(Effect.as(null)),
),
);
if (needsStack) {
if (fetchedStack === null) {
retryStacks.add(key);
return;
}
const fetched = fetchedStack.stack;
stacksReadThisSweep.set(key, fetched);
// New upper layers leave older members' fields unchanged; differing layer lists need a stack read.
// Only flag siblings in the same project: different credentials can yield lists that never agree.
if (fetched !== null) {
const fetchedKey = nativeStackKeyOf(first.link, fetched);
for (const [siblingKey, siblingEntries] of groups) {
if (siblingKey === key) continue;
if (siblingEntries[0]!.thread.projectId !== first.thread.projectId) continue;
const readThisSweep = stacksReadThisSweep.get(siblingKey);
const stale = siblingEntries.some(({ link }) => {
const stack = readThisSweep === undefined ? link.stack : readThisSweep;
return (
stack !== null &&
nativeStackKeyOf(link, stack) === fetchedKey &&
!sameLayerNumbers(stack, fetched)
);
});
if (stale) retryStacks.add(siblingKey);
}
}
}
// The host answered, so the cadence clock ticks even if a dispatch below is rejected.
lastSyncedAt.set(key, nowMs);
failedReads.delete(key);
requested.delete(key);
yield* Effect.forEach(
entries,
(entry) =>
syncEntry(entry, fields, fetchedStack, summary.provider).pipe(
persistence.withPermits(1),
Effect.catchCause((cause) => {
if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
cause,
);
}),
),
{ discard: true },
);
}, Effect.withSpan("PullRequestSyncReactor.syncGroup"));
const skips = new Map<string, { count: number; readonly key: string }>();
const readGroup = (key: string, entries: ReadonlyArray<LinkEntry>, pauseKey: string) =>
syncGroup(key, entries).pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
const retryAt = rateLimitRetryAt(cause);
if (retryAt !== undefined) {
pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0));
} else {
const previous = failedReads.get(key);
const backoffMs =
previous === undefined
? FAILED_READ_BACKOFF_MS
: Math.min(previous.backoffMs * 2, SLOW_SYNC_INTERVAL_MS);
failedReads.set(key, { retryAtMs: nowMs + backoffMs, backoffMs });
}
const reason = skipReason(cause);
const skip = skips.get(reason);
if (skip === undefined) skips.set(reason, { count: 1, key });
else skip.count += 1;
return Effect.void;
}),
);
const pools = {
// Wider than one summary batch, so reads that finish their cache checks at different
// times still share batches.
batched: { width: 100, reads: yield* Semaphore.make(100) },
// One read per pull request, often a CLI process, so these keep the narrower width.
unbatched: { width: 25, reads: yield* Semaphore.make(25) },
};
const isPaused = (pauseKey: string, atMs: number) => (pausedUntil.get(pauseKey) ?? 0) > atMs;
// Judged once a slot is free, so a stack retry a sibling flags meanwhile still counts, and
// pauses set during the sweep apply at once.
const readIfDue = (
key: string,
entries: ReadonlyArray<LinkEntry>,
pauseKey: string,
reads: Semaphore.Semaphore,
) =>
reads.withPermits(1)(
Effect.suspend(() =>
isDue(key, entries, nowMs)
? Clock.currentTimeMillis.pipe(
Effect.flatMap((startedAtMs) =>
isPaused(pauseKey, startedAtMs) ? Effect.void : readGroup(key, entries, pauseKey),
),
)
: Effect.void,
),
);
const groupsByHost = Map.groupBy(
Array.from(groups).filter(([key]) => scope === "all" || requested.has(key)),
([, entries]) => pauseKeyOf(entries[0]!),
);
yield* Effect.forEach(
groupsByHost,
([pauseKey, hostGroups]) => {
// A host paused or with nothing due skips the lookup. Stack retries only flag groups on
// the flagging group's own host, so nothing on it becomes due this sweep.
if (
isPaused(pauseKey, nowMs) ||
!hostGroups.some(([key, entries]) => isDue(key, entries, nowMs))
) {
return Effect.void;
}
return pullRequests.batchesReads(referenceOf(hostGroups[0]![1][0]!)).pipe(
Effect.flatMap((batches) => {
const { width, reads } = batches ? pools.batched : pools.unbatched;
return Effect.forEach(
hostGroups,
([key, entries]) => readIfDue(key, entries, pauseKey, reads),
{
concurrency: width,
discard: true,
},
);
}),
);
},
{ concurrency: "unbounded", discard: true },
);
for (const [reason, { count, key }] of skips) {
yield* Effect.logWarning("pull request sync skipped", { count, key, reason });
}
});
const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
Effect.suspend(() => {
if (scope === "requested") requestedSweepQueued = false;
return pullRequests.withSharedProjectReads(sweep(scope));
}).pipe(
Effect.provideService(VcsProcess.Background, true),
Effect.catchCause(logSkipped("pull request sync sweep failed", {})),
),
);
// Threads that ran a close command this run, with the commands already read for.
const closeCommands = new Map<ThreadId, Set<string>>();
// Forge commands already counted this run, so a command settles into the metric once.
const countedCommands = new Map<ThreadId, Set<string>>();
const countForgeCommands = (
event: { readonly threadId: ThreadId; readonly driver?: ProviderDriverKind | undefined },
item: CommandExecution,
) =>
Effect.suspend(() => {
const commands = classifyAgentShellCommands(item.input);
if (commands.length === 0) return Effect.void;
const counted = countedCommands.get(event.threadId) ?? new Set<string>();
countedCommands.set(event.threadId, counted);
if (counted.has(item.id)) return Effect.void;
counted.add(item.id);
return Effect.forEach(
commands,
({ forge, command, bypass }) =>
Metrics.increment(Metrics.agentForgeCommandsTotal, {
forge,
kind: command.kind,
intent: command.kind === "read" ? command.intent : undefined,
provider: event.driver ?? "unknown",
bypass,
}),
{ discard: true },
);
});
const refreshUnmergedLinks = (threadId: ThreadId) =>
projections.getThreadsWithPullRequests(threadId).pipe(
Effect.flatMap((threads) =>
Effect.forEach(
threads.flatMap((thread) =>
visibleThreadPullRequests(thread.pullRequests ?? []).filter(
(link) => link.snapshot?.state === "open" || link.snapshot?.state === "closed",
),
),
requestSync,
{ discard: true },
),
),
Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
);
// A thread's sibling syncs and relinks must not re-read a pull request its project's host
// could not find; the slow cadence and explicit refreshes still do.
const requestUnsyncedLinks = Effect.fnUntraced(
function* (threadId: ThreadId, links: ReadonlyArray<ThreadPullRequestLink>) {
const unsynced = links.filter((link) => link.snapshot === null);
if (unsynced.length === 0) return;
const [thread] =
missing.size === 0 ? [] : yield* projections.getThreadsWithPullRequests(threadId);
for (const link of unsynced) {
if (
thread !== undefined &&
missing.has(`${thread.projectId}\0${threadPullRequestKeyOf(link)}`)
) {
continue;
}
yield* requestSync(link);
}
},
Effect.catchCause(logSkipped("pull request refresh after link update skipped", {})),
);
// An agent that opens a pull request from a shell gets it linked as link_pull_request would.
const linkCreatedChangeRequests = Effect.fn("PullRequestSyncReactor.linkCreatedChangeRequests")(
function* (threadId: ThreadId, item: CommandExecution) {
yield* Effect.forEach(
changeRequestsCreatedBy(item.input, item.output ?? ""),
(created) =>
engine
.dispatch({
type: "thread.pull-request.link",
// Stable per command, so a repeated settlement cannot relink one the user unlinked.
commandId: CommandId.make(
`server:pr-created-link:${threadId}:${item.id}:${threadPullRequestKeyOf(created)}`,
),
threadId,
...created,
source: "created",
})
.pipe(
Effect.catchCause(
logSkipped("linking a pull request a command created failed", { threadId }),
),
),
{ discard: true },
);
},
);
// A push can start new checks, so the thread's watches forget whether checks were running and
// hold the thread until they read the pull request again. The run is still going, so the
// thread never shows as done in between.
const reopenWatchedChecks = Effect.fn("PullRequestSyncReactor.reopenWatchedChecks")(
function* (threadId: ThreadId, item: CommandExecution) {
if (!isPushCommand(item.input)) return;
const threads = yield* projections.getThreadsWithPullRequests(threadId);
const answered = threads.some((thread) =>
(thread.pullRequests ?? []).some((link) => link.watch?.checksPending !== undefined),
);
if (!answered) return;
yield* engine.dispatch({
type: "thread.pull-request-watch.checks-reopen",
// Stable per command, so a repeated settlement clears an answer read since only once.
commandId: CommandId.make(`server:pr-push-checks:${threadId}:${item.id}`),
threadId,
});
},
(effect, threadId) =>
effect.pipe(
Effect.catchCause(
logSkipped("reopening a watch's checks after a push failed", { threadId }),
),
),
);
const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
"PullRequestSyncReactor.start",
)(function* () {
const events = engine.streamDomainEvents;
// Linking and reopening dispatch under the thread's lock, so a busy thread delays only its
// own reactions. Refreshes queue with them, so each thread's reactions keep event order.
const threadReactions = yield* KeyedLock.makeRunner<ThreadId>();
const inThreadOrder = <E>(threadId: ThreadId, reaction: Effect.Effect<void, E>) =>
threadReactions.run(
threadId,
// The reactions log their own failures, so this sees only defects and shutdown.
Effect.catchCause(reaction, (cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.interrupt
: Effect.logWarning("pull request sync reaction failed", { threadId, cause }),
),
);
const stateChanges = Stream.merge(
yield* pullRequests.subscribeStateChanges,
yield* git.subscribePullRequestStateChanges,
);
yield* forkParked(
Stream.runForEach(stateChanges, requestSync).pipe(
Effect.catchCause(logSkipped("pull request state change stream failed", {})),
),
);
yield* forkParked(
Stream.runForEach(events, (event) => {
switch (event.type) {
case "thread.pull-request-link-updated":
return requestUnsyncedLinks(event.threadId, [event.payload]);
case "thread.pull-request-synced":
return requestUnsyncedLinks(
event.threadId,
visibleThreadPullRequests(event.payload.pullRequests ?? []),
);
// An agent can merge or close its pull request from a shell with its host's CLI, which
// sends no merge notification. Read the thread's unmerged links fresh once that command
// ends, while the agent usually still replies, so settlement can land before the run
// ends. Read again when the run ends, since `merge --auto` returns before it merges.
case "turn-item.updated": {
const item = event.payload;
if (item.type !== "command_execution") return Effect.void;
let reaction = Effect.andThen(
linkCreatedChangeRequests(event.threadId, item),
reopenWatchedChecks(event.threadId, item),
);
const active = isOrchestrationV2WorkActive(item.status);
if (isChangeRequestCloseCommand(item.input)) {
const ended = closeCommands.get(event.threadId) ?? new Set<string>();
closeCommands.set(event.threadId, ended);
if (!active && !ended.has(item.id)) {
ended.add(item.id);
reaction = Effect.andThen(reaction, refreshUnmergedLinks(event.threadId));
}
}
if (active) return Effect.void;
return countForgeCommands(event, item).pipe(
Effect.andThen(inThreadOrder(event.threadId, reaction)),
);
}
// Settled threads are not swept, so read their links once to settle with fresh status.
case "thread.settled":
return inThreadOrder(event.threadId, refreshUnmergedLinks(event.threadId));
case "run.updated":
if (!isTerminalRunStatus(event.payload.status)) return Effect.void;
countedCommands.delete(event.threadId);
return closeCommands.delete(event.threadId)
? inThreadOrder(event.threadId, refreshUnmergedLinks(event.threadId))
: Effect.void;
default:
return Effect.void;
}
}).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
);
yield* forkParked(
Effect.gen(function* () {
yield* worker.enqueue("all");
yield* worker.drain;
}).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
);
});
const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
Effect.suspend(() => {
pendingRequests.add(threadPullRequestKeyOf(key));
if (requestedSweepQueued) return Effect.void;
requestedSweepQueued = true;
return worker.enqueue("requested");
});
return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
});
export const layer = Layer.effect(PullRequestSyncReactor, make);