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

PullRequestSyncReactor.ts

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