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

PullRequestSyncReactor.ts

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