Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestSyncReactor.ts

1,000 lines42.6 KB

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