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

PullRequestSyncReactor.ts

745 lines31.8 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 // Pause per project and host because credentials are project-specific; leave paused PRs due until reset.
350 const pausedUntil = new Map<string, number>();
351​
352 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
353 if (requested.has(key) || retryStacks.has(key)) return true;
354 if (entries.some((entry) => entry.link.snapshot === null)) return true;
355 const active = entries.filter((entry) => isUnsettled(entry.thread));
356 // Merged snapshots without mergedAt cannot settle threads; reread slowly until supplied.
357 const isFinal = ({ link: { snapshot } }: LinkEntry) =>
358 snapshot?.state === "merged"
359 ? snapshot.mergedAt != null
360 : snapshot?.state === "closed" &&
361 nowMs - Date.parse(snapshot.closedAt ?? "") >= CLOSED_FINAL_AFTER_MS;
362 if (active.every(isFinal)) return false;
363 const last = lastSyncedAt.get(key);
364 const sinceLastMs = last === undefined ? Number.POSITIVE_INFINITY : nowMs - last;
365 const open = active.filter((entry) => entry.link.snapshot?.state === "open");
366 if (open.length > 0) {
367 const quiet = open.every((entry) => {
368 const updatedAt = entry.link.snapshot?.updatedAt;
369 return updatedAt != null && nowMs - Date.parse(updatedAt) >= QUIET_AFTER_MS;
370 });
371 return !quiet || sinceLastMs >= QUIET_SYNC_INTERVAL_MS;
372 }
373 return sinceLastMs >= SLOW_SYNC_INTERVAL_MS;
374 };
375​
376 const logSkipped =
377 (message: string, fields: Record<string, unknown>) =>
378 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
379 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
380​
381 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
382 const threads = yield* projections.getThreadsWithPullRequests();
383 const now = yield* DateTime.now;
384 const nowMs = DateTime.toEpochMillis(now);
385 const nowIso = DateTime.formatIso(now);
386​
387 const groups = new Map<string, Array<LinkEntry>>();
388 for (const thread of threads) {
389 for (const link of visibleThreadPullRequests(thread.pullRequests ?? [])) {
390 // Reads depend on the project's checkout and credentials, including their failures.
391 const key = `${thread.projectId}\0${threadPullRequestKeyOf(link)}`;
392 const entries = groups.get(key) ?? [];
393 entries.push({ thread, link });
394 groups.set(key, entries);
395 }
396 }
397​
398 // A host-level refresh reaches every project, each retaining its own pending retry.
399 for (const [key, entries] of groups) {
400 if (pendingRequests.has(threadPullRequestKeyOf(entries[0]!.link))) requested.add(key);
401 }
402 pendingRequests.clear();
403​
404 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
405 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
406 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
407​
408 const linkedThisSweep = new Set<string>();
409 // Fresh stack reads by group, so a member flagged by a sibling is compared against what the
410 // host answered this sweep, not the saved layers that sibling is about to replace.
411 const stacksReadThisSweep = new Map<string, ThreadPullRequestStack | null>();
412 const persistence = yield* Semaphore.make(1);
413​
414 // Effect.fn's stack frames close over these sweep-scoped bodies and their arguments, and a
415 // cache lookup forked inside keeps those frames, so a plain span leaves the sweep collectable.
416 const syncEntry = Effect.fnUntraced(function* (
417 entry: LinkEntry,
418 hostFields: SnapshotFields,
419 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
420 provider: PullRequestSummary["provider"],
421 ) {
422 const { thread, link } = entry;
423 const fields = withKnownMergeability(link.snapshot, hostFields, provider);
424 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
425 const changed =
426 link.snapshot === null ||
427 !snapshotFieldsEqual(link.snapshot, fields) ||
428 !stacksEqual(link.stack, nextStack);
429 // Persist siblings before terminal snapshots trigger settlement; settled threads get snapshots without new links.
430 for (const layer of isUnsettled(thread) ? (fetchedStack?.stack?.layers ?? []) : []) {
431 const layerKey = {
432 host: normalizeThreadPullRequestKey(link).host,
433 repository: link.repository,
434 number: layer.number,
435 };
436 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
437 if (linkedThisSweep.has(dedupeKey)) continue;
438 // Tombstones count as present: a dismissed layer is never re-added.
439 if (
440 (thread.pullRequests ?? []).some((existing) =>
441 threadPullRequestKeysEqual(existing, layerKey),
442 )
443 ) {
444 continue;
445 }
446 const url = siblingChangeRequestUrl(link.url, layer.number);
447 if (url === null) continue;
448 const uuid = yield* random.uuidV4();
449 yield* engine.dispatch({
450 type: "thread.pull-request.link",
451 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
452 threadId: thread.id,
453 ...layerKey,
454 url,
455 source: "stack",
456 });
457 linkedThisSweep.add(dedupeKey);
458 }
459 if (changed) {
460 const uuid = yield* random.uuidV4();
461 yield* engine.dispatch({
462 type: "thread.pull-request-link.sync",
463 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
464 threadId: thread.id,
465 host: normalizeThreadPullRequestKey(link).host,
466 repository: link.repository,
467 number: link.number,
468 snapshot: { ...fields, syncedAt: nowIso },
469 stack: nextStack,
470 });
471 }
472 }, Effect.withSpan("PullRequestSyncReactor.syncEntry"));
473​
474 const syncGroup = Effect.fnUntraced(function* (key: string, entries: ReadonlyArray<LinkEntry>) {
475 const first = entries[0]!;
476 const ref = {
477 projectId: first.thread.projectId,
478 host: normalizeThreadPullRequestKey(first.link).host,
479 repository: first.link.repository,
480 number: first.link.number,
481 };
482 const refreshRequested = requested.has(key);
483 // A held merged summary is served without asking the host, so a snapshot still missing its
484 // merge time has to drop it or the slow-cadence re-read would hand back the same gap.
485 const missingMergedAt = entries.some(
486 (entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt == null,
487 );
488 // A stack retry reads past the cache, or it could get back the layer list it is retrying.
489 const invalidated = refreshRequested || missingMergedAt || retryStacks.has(key);
490 if (invalidated) yield* pullRequests.invalidate({ reference: ref });
491 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
492 const fields = snapshotFieldsOf(summary);
493 const needsStack =
494 refreshRequested ||
495 retryStacks.has(key) ||
496 entries.some(
497 (entry) =>
498 entry.link.snapshot === null ||
499 !snapshotFieldsEqual(
500 entry.link.snapshot,
501 withKnownMergeability(entry.link.snapshot, fields, summary.provider),
502 ) ||
503 (summary.stack !== undefined &&
504 (entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
505 );
506 const knownUnstacked =
507 summary.stack === null && entries.every((entry) => entry.link.stack === null);
508 // A sibling can flag this group while its summary read is in flight.
509 if (!invalidated && retryStacks.has(key) && !knownUnstacked) {
510 yield* pullRequests.invalidate({ reference: ref });
511 }
512 // The retry this read answers is consumed before the read, not after it: a sibling may
513 // flag this group again while the read is in flight, and that flag must survive to the
514 // next sweep because the answer below may predate the sibling's layers.
515 if (needsStack) retryStacks.delete(key);
516 const fetchedStack = !needsStack
517 ? null
518 : knownUnstacked
519 ? { stack: null }
520 : yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
521 Effect.map((stack) => ({
522 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
523 })),
524 Effect.catchCauseIf(
525 (cause) => !Cause.hasInterruptsOnly(cause),
526 (cause) =>
527 rateLimitRetryAt(cause) !== undefined
528 ? Effect.sync(() => retryStacks.add(key)).pipe(
529 Effect.andThen(Effect.failCause(cause)),
530 )
531 : Effect.logWarning("pull request stack lookup failed", {
532 key,
533 }).pipe(Effect.as(null)),
534 ),
535 );
536 if (needsStack) {
537 if (fetchedStack === null) {
538 retryStacks.add(key);
539 return;
540 }
541 const fetched = fetchedStack.stack;
542 stacksReadThisSweep.set(key, fetched);
543 // New upper layers leave older members' fields unchanged; differing layer lists need a stack read.
544 // Only flag siblings in the same project: different credentials can yield lists that never agree.
545 if (fetched !== null) {
546 const fetchedKey = nativeStackKeyOf(first.link, fetched);
547 for (const [siblingKey, siblingEntries] of groups) {
548 if (siblingKey === key) continue;
549 if (siblingEntries[0]!.thread.projectId !== first.thread.projectId) continue;
550 const readThisSweep = stacksReadThisSweep.get(siblingKey);
551 const stale = siblingEntries.some(({ link }) => {
552 const stack = readThisSweep === undefined ? link.stack : readThisSweep;
553 return (
554 stack !== null &&
555 nativeStackKeyOf(link, stack) === fetchedKey &&
556 !sameLayerNumbers(stack, fetched)
557 );
558 });
559 if (stale) retryStacks.add(siblingKey);
560 }
561 }
562 }
563 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
564 lastSyncedAt.set(key, nowMs);
565 requested.delete(key);
566 yield* Effect.forEach(
567 entries,
568 (entry) =>
569 syncEntry(entry, fields, fetchedStack, summary.provider).pipe(
570 persistence.withPermits(1),
571 Effect.catchCause((cause) => {
572 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
573 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
574 cause,
575 );
576 }),
577 ),
578 { discard: true },
579 );
580 }, Effect.withSpan("PullRequestSyncReactor.syncGroup"));
581​
582 const skips = new Map<string, { count: number; readonly key: string }>();
583 const readGroup = (key: string, entries: ReadonlyArray<LinkEntry>, pauseKey: string) =>
584 syncGroup(key, entries).pipe(
585 Effect.catchCause((cause) => {
586 if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
587 const retryAt = rateLimitRetryAt(cause);
588 if (retryAt !== undefined) {
589 pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0));
590 }
591 const reason = skipReason(cause);
592 const skip = skips.get(reason);
593 if (skip === undefined) skips.set(reason, { count: 1, key });
594 else skip.count += 1;
595 return Effect.void;
596 }),
597 );
598 yield* Effect.forEach(
599 groups,
600 ([key, entries]) => {
601 if (!((scope === "all" || requested.has(key)) && isDue(key, entries, nowMs))) {
602 return Effect.void;
603 }
604 const first = entries[0]!;
605 const pauseKey = `${first.thread.projectId}\0${normalizeThreadPullRequestKey(first.link).host}`;
606 // Check pauses at each read so changes during the sweep apply immediately.
607 return Clock.currentTimeMillis.pipe(
608 Effect.flatMap((startedAtMs) =>
609 (pausedUntil.get(pauseKey) ?? 0) > startedAtMs
610 ? Effect.void
611 : readGroup(key, entries, pauseKey),
612 ),
613 );
614 },
615 // Match summary batch width so GitHub reads coalesce into one request.
616 { concurrency: 25, discard: true },
617 );
618 for (const [reason, { count, key }] of skips) {
619 yield* Effect.logWarning("pull request sync skipped", { count, key, reason });
620 }
621 });
622​
623 const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
624 Effect.suspend(() => {
625 if (scope === "requested") requestedSweepQueued = false;
626 return pullRequests.withSharedProjectReads(sweep(scope));
627 }).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
628 );
629​
630 // Threads that ran a close command this run, with the commands already read for.
631 const closeCommands = new Map<ThreadId, Set<string>>();
632 const refreshUnmergedLinks = (threadId: ThreadId) =>
633 projections.getThreadsWithPullRequests(threadId).pipe(
634 Effect.flatMap((threads) =>
635 Effect.forEach(
636 threads.flatMap((thread) =>
637 visibleThreadPullRequests(thread.pullRequests ?? []).filter(
638 (link) => link.snapshot?.state === "open" || link.snapshot?.state === "closed",
639 ),
640 ),
641 requestSync,
642 { discard: true },
643 ),
644 ),
645 Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
646 );
647​
648 // An agent that opens a pull request from a shell gets it linked as link_pull_request would.
649 const linkCreatedChangeRequests = Effect.fn("PullRequestSyncReactor.linkCreatedChangeRequests")(
650 function* (threadId: ThreadId, item: CommandExecution) {
651 if (isOrchestrationV2WorkActive(item.status)) return;
652 yield* Effect.forEach(
653 changeRequestsCreatedBy(item.input, item.output ?? ""),
654 (created) =>
655 engine
656 .dispatch({
657 type: "thread.pull-request.link",
658 // Stable per command, so a repeated settlement cannot relink one the user unlinked.
659 commandId: CommandId.make(
660 `server:pr-created-link:${threadId}:${item.id}:${threadPullRequestKeyOf(created)}`,
661 ),
662 threadId,
663 ...created,
664 source: "created",
665 })
666 .pipe(
667 Effect.catchCause(
668 logSkipped("linking a pull request a command created failed", { threadId }),
669 ),
670 ),
671 { discard: true },
672 );
673 },
674 );
675​
676 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
677 "PullRequestSyncReactor.start",
678 )(function* () {
679 const events = engine.streamDomainEvents;
680 const stateChanges = Stream.merge(
681 yield* pullRequests.subscribeStateChanges,
682 yield* git.subscribePullRequestStateChanges,
683 );
684 yield* forkParked(
685 Stream.runForEach(stateChanges, requestSync).pipe(
686 Effect.catchCause(logSkipped("pull request state change stream failed", {})),
687 ),
688 );
689 yield* forkParked(
690 Stream.runForEach(events, (event) => {
691 switch (event.type) {
692 case "thread.pull-request-link-updated":
693 return event.payload.snapshot === null ? requestSync(event.payload) : Effect.void;
694 case "thread.pull-request-synced":
695 return Effect.forEach(
696 visibleThreadPullRequests(event.payload.pullRequests ?? []).filter(
697 (link) => link.snapshot === null,
698 ),
699 requestSync,
700 { discard: true },
701 );
702 // An agent can merge or close its pull request from a shell with its host's CLI, which
703 // sends no merge notification. Read the thread's unmerged links fresh once that command
704 // ends, while the agent usually still replies, so settlement can land before the run
705 // ends. Read again when the run ends, since `merge --auto` returns before it merges.
706 case "turn-item.updated": {
707 const item = event.payload;
708 if (item.type !== "command_execution") return Effect.void;
709 const linked = linkCreatedChangeRequests(event.threadId, item);
710 if (!isChangeRequestCloseCommand(item.input)) return linked;
711 const ended = closeCommands.get(event.threadId) ?? new Set<string>();
712 closeCommands.set(event.threadId, ended);
713 if (isOrchestrationV2WorkActive(item.status) || ended.has(item.id)) return linked;
714 ended.add(item.id);
715 return Effect.andThen(linked, refreshUnmergedLinks(event.threadId));
716 }
717 case "run.updated":
718 return isTerminalRunStatus(event.payload.status) && closeCommands.delete(event.threadId)
719 ? refreshUnmergedLinks(event.threadId)
720 : Effect.void;
721 default:
722 return Effect.void;
723 }
724 }).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
725 );
726 yield* forkParked(
727 Effect.gen(function* () {
728 yield* worker.enqueue("all");
729 yield* worker.drain;
730 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
731 );
732 });
733​
734 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
735 Effect.suspend(() => {
736 pendingRequests.add(threadPullRequestKeyOf(key));
737 if (requestedSweepQueued) return Effect.void;
738 requestedSweepQueued = true;
739 return worker.enqueue("requested");
740 });
741​
742 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
743});
744​
745export const layer = Layer.effect(PullRequestSyncReactor, make);