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

PullRequestSyncReactor.ts

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