Open History to see the last commit
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
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("");
97}
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;
128}
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()];
172}
173
174const isPullRequestProviderError = Schema.is(PullRequestProviderError);
175
176type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
177
178interface LinkEntry {
179 readonly thread: ProjectionStore.ProjectionThreadPullRequests;
180 readonly link: ThreadPullRequestLink;
181}
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 });
195}
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 };
215}
216
217// GitHub briefly returns unknown after base pushes; other hosts may mean a lasting condition.
218function withKnownMergeability(
219 previous: ThreadPullRequestSnapshot | null,
220 fields: SnapshotFields,
221 provider: PullRequestSummary["provider"],
222): SnapshotFields {
223 if (
224 provider !== "github" ||
225 fields.state !== "open" ||
226 fields.mergeability !== "unknown" ||
227 previous?.updatedAt !== fields.updatedAt
228 )
229 return fields;
230 const known = previous?.state === "open" ? previous.mergeability : undefined;
231 return known === undefined || known === "unknown" ? fields : { ...fields, mergeability: known };
232}
233
234// Rotating ghe.com avatar tokens should not make otherwise identical snapshots differ.
235function avatarIdentity(avatarUrl: string | null | undefined): string | null {
236 if (avatarUrl === null || avatarUrl === undefined) return null;
237 const url = URL.parse(avatarUrl);
238 if (url === null || (url.hostname !== "ghe.com" && !url.hostname.endsWith(".ghe.com"))) {
239 return avatarUrl;
240 }
241 url.searchParams.delete("token");
242 return url.href;
243}
244
245function snapshotFieldsEqual(left: SnapshotFields, right: SnapshotFields): boolean {
246 return (
247 left.state === right.state &&
248 left.title === right.title &&
249 left.headBranch === right.headBranch &&
250 left.baseBranch === right.baseBranch &&
251 left.isDraft === right.isDraft &&
252 left.updatedAt === right.updatedAt &&
253 (left.closedAt ?? null) === (right.closedAt ?? null) &&
254 (left.mergedAt ?? null) === (right.mergedAt ?? null) &&
255 (left.author?.login ?? null) === (right.author?.login ?? null) &&
256 avatarIdentity(left.author?.avatarUrl) === avatarIdentity(right.author?.avatarUrl) &&
257 left.additions === right.additions &&
258 left.deletions === right.deletions &&
259 left.changedFiles === right.changedFiles &&
260 (left.reviewDecision ?? null) === (right.reviewDecision ?? null) &&
261 (left.checksState ?? null) === (right.checksState ?? null) &&
262 left.mergeability === right.mergeability
263 );
264}
265
266function stacksEqual(
267 left: ThreadPullRequestStack | null,
268 right: ThreadPullRequestStack | null,
269): boolean {
270 if (left === null || right === null) return left === right;
271 return (
272 left.kind === right.kind &&
273 left.id === right.id &&
274 left.number === right.number &&
275 left.url === right.url &&
276 left.base === right.base &&
277 left.layers.length === right.layers.length &&
278 left.layers.every((layer, index) => {
279 const other = right.layers[index]!;
280 return (
281 layer.number === other.number &&
282 layer.headBranch === other.headBranch &&
283 layer.state === other.state
284 );
285 })
286 );
287}
288
289/** Stack ids are unique only within a repository, e.g. GitHub's fallback to the stack number. */
290function nativeStackKeyOf(link: ThreadPullRequestLink, stack: ThreadPullRequestStack): string {
291 const key = normalizeThreadPullRequestKey(link);
292 return `${key.host}/${key.repository}#stack:${stack.id}`;
293}
294
295function sameLayerNumbers(left: ThreadPullRequestStack, right: ThreadPullRequestStack): boolean {
296 return (
297 left.layers.length === right.layers.length &&
298 left.layers.every((layer, index) => layer.number === right.layers[index]!.number)
299 );
300}
301
302function skipReason(cause: Cause.Cause<unknown>): string {
303 const error = Cause.squash(cause);
304 return error instanceof Error ? error.message : String(error);
305}
306
307function rateLimitRetryAt(cause: Cause.Cause<unknown>): number | undefined {
308 let error: unknown = Cause.squash(cause);
309 while (error instanceof Error) {
310 if (isPullRequestProviderError(error) && error.reason === "rate-limited") return error.retryAt;
311 error = error.cause;
312 }
313 return undefined;
314}
315
316function isUnsettled(thread: ProjectionStore.ProjectionThreadPullRequests): boolean {
317 return thread.settledOverride !== "settled" && thread.settledAt === null;
318}
319
320export class PullRequestSyncReactor extends Context.Service<
321 PullRequestSyncReactor,
322 {
323 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
324 readonly drain: Effect.Effect<void>;
325 /** Forces reread on the next sweep, including terminal snapshots; rate-limited hosts wait until the pause ends. */
326 readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
327 }
328>()("t3/orchestration-v2/PullRequestSyncReactor") {}
329
330/** @public */
331export const make = Effect.gen(function* () {
332 const engine = yield* Orchestrator.OrchestratorV2;
333 const projections = yield* ProjectionStore.ProjectionStoreV2;
334 const pullRequests = yield* PullRequestService.PullRequestService;
335 const git = yield* GitManager.GitManager;
336 const random = yield* SecureRandom.SecureRandom;
337
338 const lastSyncedAt = new Map<string, number>();
339 const requested = new Set<string>();
340 // Requests arriving during a host read wait for the next sweep.
341 const pendingRequests = new Set<string>();
342 // PR keys wait in `pendingRequests` for one queued sweep, so a burst of links (an agent
343 // linking dozens of pull requests) is read together and shares the summary batches.
344 let requestedSweepQueued = false;
345 const retryStacks = new Set<string>();
346 // Pause per project and host because credentials are project-specific; leave paused PRs due until reset.
347 const pausedUntil = new Map<string, number>();
348
349 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
350 if (requested.has(key) || retryStacks.has(key)) return true;
351 if (entries.some((entry) => entry.link.snapshot === null)) return true;
352 const active = entries.filter((entry) => isUnsettled(entry.thread));
353 // Merged snapshots without mergedAt cannot settle threads; reread slowly until supplied.
354 if (
355 active.every(
356 (entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt != null,
357 )
358 ) {
359 return false;
360 }
361 const last = lastSyncedAt.get(key);
362 const sinceLastMs = last === undefined ? Number.POSITIVE_INFINITY : nowMs - last;
363 const open = active.filter((entry) => entry.link.snapshot?.state === "open");
364 if (open.length > 0) {
365 const quiet = open.every((entry) => {
366 const updatedAt = entry.link.snapshot?.updatedAt;
367 return updatedAt != null && nowMs - Date.parse(updatedAt) >= QUIET_AFTER_MS;
368 });
369 return !quiet || sinceLastMs >= QUIET_SYNC_INTERVAL_MS;
370 }
371 return sinceLastMs >= SLOW_SYNC_INTERVAL_MS;
372 };
373
374 const logSkipped =
375 (message: string, fields: Record<string, unknown>) =>
376 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
377 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
378
379 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
380 const threads = yield* projections.getThreadsWithPullRequests();
381 const now = yield* DateTime.now;
382 const nowMs = DateTime.toEpochMillis(now);
383 const nowIso = DateTime.formatIso(now);
384
385 const groups = new Map<string, Array<LinkEntry>>();
386 for (const thread of threads) {
387 for (const link of visibleThreadPullRequests(thread.pullRequests ?? [])) {
388 // Reads depend on the project's checkout and credentials, including their failures.
389 const key = `${thread.projectId}\0${threadPullRequestKeyOf(link)}`;
390 const entries = groups.get(key) ?? [];
391 entries.push({ thread, link });
392 groups.set(key, entries);
393 }
394 }
395
396 // A host-level refresh reaches every project, each retaining its own pending retry.
397 for (const [key, entries] of groups) {
398 if (pendingRequests.has(threadPullRequestKeyOf(entries[0]!.link))) requested.add(key);
399 }
400 pendingRequests.clear();
401
402 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
403 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
404 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
405
406 const linkedThisSweep = new Set<string>();
407 // Fresh stack reads by group, so a member flagged by a sibling is compared against what the
408 // host answered this sweep, not the saved layers that sibling is about to replace.
409 const stacksReadThisSweep = new Map<string, ThreadPullRequestStack | null>();
410 const persistence = yield* Semaphore.make(1);
411
412 // Effect.fn's stack frames close over these sweep-scoped bodies and their arguments, and a
413 // cache lookup forked inside keeps those frames, so a plain span leaves the sweep collectable.
414 const syncEntry = Effect.fnUntraced(function* (
415 entry: LinkEntry,
416 hostFields: SnapshotFields,
417 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
418 provider: PullRequestSummary["provider"],
419 ) {
420 const { thread, link } = entry;
421 const fields = withKnownMergeability(link.snapshot, hostFields, provider);
422 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
423 const changed =
424 link.snapshot === null ||
425 !snapshotFieldsEqual(link.snapshot, fields) ||
426 !stacksEqual(link.stack, nextStack);
427 // Persist siblings before terminal snapshots trigger settlement; settled threads get snapshots without new links.
428 for (const layer of isUnsettled(thread) ? (fetchedStack?.stack?.layers ?? []) : []) {
429 const layerKey = {
430 host: normalizeThreadPullRequestKey(link).host,
431 repository: link.repository,
432 number: layer.number,
433 };
434 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
435 if (linkedThisSweep.has(dedupeKey)) continue;
436 // Tombstones count as present: a dismissed layer is never re-added.
437 if (
438 (thread.pullRequests ?? []).some((existing) =>
439 threadPullRequestKeysEqual(existing, layerKey),
440 )
441 ) {
442 continue;
443 }
444 const url = siblingChangeRequestUrl(link.url, layer.number);
445 if (url === null) continue;
446 const uuid = yield* random.uuidV4();
447 yield* engine.dispatch({
448 type: "thread.pull-request.link",
449 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
450 threadId: thread.id,
451 ...layerKey,
452 url,
453 source: "stack",
454 });
455 linkedThisSweep.add(dedupeKey);
456 }
457 if (changed) {
458 const uuid = yield* random.uuidV4();
459 yield* engine.dispatch({
460 type: "thread.pull-request-link.sync",
461 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
462 threadId: thread.id,
463 host: normalizeThreadPullRequestKey(link).host,
464 repository: link.repository,
465 number: link.number,
466 snapshot: { ...fields, syncedAt: nowIso },
467 stack: nextStack,
468 });
469 }
470 }, Effect.withSpan("PullRequestSyncReactor.syncEntry"));
471
472 const syncGroup = Effect.fnUntraced(function* (key: string, entries: ReadonlyArray<LinkEntry>) {
473 const first = entries[0]!;
474 const ref = {
475 projectId: first.thread.projectId,
476 host: normalizeThreadPullRequestKey(first.link).host,
477 repository: first.link.repository,
478 number: first.link.number,
479 };
480 const refreshRequested = requested.has(key);
481 // A held merged summary is served without asking the host, so a snapshot still missing its
482 // merge time has to drop it or the slow-cadence re-read would hand back the same gap.
483 const missingMergedAt = entries.some(
484 (entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt == null,
485 );
486 // A stack retry reads past the cache, or it could get back the layer list it is retrying.
487 const invalidated = refreshRequested || missingMergedAt || retryStacks.has(key);
488 if (invalidated) yield* pullRequests.invalidate({ reference: ref });
489 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
490 const fields = snapshotFieldsOf(summary);
491 const needsStack =
492 refreshRequested ||
493 retryStacks.has(key) ||
494 entries.some(
495 (entry) =>
496 entry.link.snapshot === null ||
497 !snapshotFieldsEqual(
498 entry.link.snapshot,
499 withKnownMergeability(entry.link.snapshot, fields, summary.provider),
500 ) ||
501 (summary.stack !== undefined &&
502 (entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
503 );
504 const knownUnstacked =
505 summary.stack === null && entries.every((entry) => entry.link.stack === null);
506 // A sibling can flag this group while its summary read is in flight.
507 if (!invalidated && retryStacks.has(key) && !knownUnstacked) {
508 yield* pullRequests.invalidate({ reference: ref });
509 }
510 // The retry this read answers is consumed before the read, not after it: a sibling may
511 // flag this group again while the read is in flight, and that flag must survive to the
512 // next sweep because the answer below may predate the sibling's layers.
513 if (needsStack) retryStacks.delete(key);
514 const fetchedStack = !needsStack
515 ? null
516 : knownUnstacked
517 ? { stack: null }
518 : yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
519 Effect.map((stack) => ({
520 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
521 })),
522 Effect.catchCauseIf(
523 (cause) => !Cause.hasInterruptsOnly(cause),
524 (cause) =>
525 rateLimitRetryAt(cause) !== undefined
526 ? Effect.sync(() => retryStacks.add(key)).pipe(
527 Effect.andThen(Effect.failCause(cause)),
528 )
529 : Effect.logWarning("pull request stack lookup failed", {
530 key,
531 }).pipe(Effect.as(null)),
532 ),
533 );
534 if (needsStack) {
535 if (fetchedStack === null) {
536 retryStacks.add(key);
537 return;
538 }
539 const fetched = fetchedStack.stack;
540 stacksReadThisSweep.set(key, fetched);
541 // New upper layers leave older members' fields unchanged; differing layer lists need a stack read.
542 // Only flag siblings in the same project: different credentials can yield lists that never agree.
543 if (fetched !== null) {
544 const fetchedKey = nativeStackKeyOf(first.link, fetched);
545 for (const [siblingKey, siblingEntries] of groups) {
546 if (siblingKey === key) continue;
547 if (siblingEntries[0]!.thread.projectId !== first.thread.projectId) continue;
548 const readThisSweep = stacksReadThisSweep.get(siblingKey);
549 const stale = siblingEntries.some(({ link }) => {
550 const stack = readThisSweep === undefined ? link.stack : readThisSweep;
551 return (
552 stack !== null &&
553 nativeStackKeyOf(link, stack) === fetchedKey &&
554 !sameLayerNumbers(stack, fetched)
555 );
556 });
557 if (stale) retryStacks.add(siblingKey);
558 }
559 }
560 }
561 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
562 lastSyncedAt.set(key, nowMs);
563 requested.delete(key);
564 yield* Effect.forEach(
565 entries,
566 (entry) =>
567 syncEntry(entry, fields, fetchedStack, summary.provider).pipe(
568 persistence.withPermits(1),
569 Effect.catchCause((cause) => {
570 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
571 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
572 cause,
573 );
574 }),
575 ),
576 { discard: true },
577 );
578 }, Effect.withSpan("PullRequestSyncReactor.syncGroup"));
579
580 const skips = new Map<string, { count: number; readonly key: string }>();
581 const readGroup = (key: string, entries: ReadonlyArray<LinkEntry>, pauseKey: string) =>
582 syncGroup(key, entries).pipe(
583 Effect.catchCause((cause) => {
584 if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
585 const retryAt = rateLimitRetryAt(cause);
586 if (retryAt !== undefined) {
587 pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0));
588 }
589 const reason = skipReason(cause);
590 const skip = skips.get(reason);
591 if (skip === undefined) skips.set(reason, { count: 1, key });
592 else skip.count += 1;
593 return Effect.void;
594 }),
595 );
596 yield* Effect.forEach(
597 groups,
598 ([key, entries]) => {
599 if (!((scope === "all" || requested.has(key)) && isDue(key, entries, nowMs))) {
600 return Effect.void;
601 }
602 const first = entries[0]!;
603 const pauseKey = `${first.thread.projectId}\0${normalizeThreadPullRequestKey(first.link).host}`;
604 // Check pauses at each read so changes during the sweep apply immediately.
605 return Clock.currentTimeMillis.pipe(
606 Effect.flatMap((startedAtMs) =>
607 (pausedUntil.get(pauseKey) ?? 0) > startedAtMs
608 ? Effect.void
609 : readGroup(key, entries, pauseKey),
610 ),
611 );
612 },
613 // Match summary batch width so GitHub reads coalesce into one request.
614 { concurrency: 25, discard: true },
615 );
616 for (const [reason, { count, key }] of skips) {
617 yield* Effect.logWarning("pull request sync skipped", { count, key, reason });
618 }
619 });
620
621 const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
622 Effect.suspend(() => {
623 if (scope === "requested") requestedSweepQueued = false;
624 return pullRequests.withSharedProjectReads(sweep(scope));
625 }).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
626 );
627
628 // Threads that ran a close command this run, with the commands already read for.
629 const closeCommands = new Map<ThreadId, Set<string>>();
630 const refreshOpenLinks = (threadId: ThreadId) =>
631 projections.getThreadsWithPullRequests(threadId).pipe(
632 Effect.flatMap((threads) =>
633 Effect.forEach(
634 threads.flatMap((thread) =>
635 visibleThreadPullRequests(thread.pullRequests ?? []).filter(
636 (link) => link.snapshot?.state === "open",
637 ),
638 ),
639 requestSync,
640 { discard: true },
641 ),
642 ),
643 Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
644 );
645
646 // An agent that opens a pull request from a shell gets it linked as link_pull_request would.
647 const linkCreatedChangeRequests = Effect.fn("PullRequestSyncReactor.linkCreatedChangeRequests")(
648 function* (threadId: ThreadId, item: CommandExecution) {
649 if (isOrchestrationV2WorkActive(item.status)) return;
650 yield* Effect.forEach(
651 changeRequestsCreatedBy(item.input, item.output ?? ""),
652 (created) =>
653 engine
654 .dispatch({
655 type: "thread.pull-request.link",
656 // Stable per command, so a repeated settlement cannot relink one the user unlinked.
657 commandId: CommandId.make(
658 `server:pr-created-link:${threadId}:${item.id}:${threadPullRequestKeyOf(created)}`,
659 ),
660 threadId,
661 ...created,
662 source: "created",
663 })
664 .pipe(
665 Effect.catchCause(
666 logSkipped("linking a pull request a command created failed", { threadId }),
667 ),
668 ),
669 { discard: true },
670 );
671 },
672 );
673
674 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
675 "PullRequestSyncReactor.start",
676 )(function* () {
677 const events = engine.streamDomainEvents;
678 const stateChanges = Stream.merge(
679 yield* pullRequests.subscribeStateChanges,
680 yield* git.subscribePullRequestStateChanges,
681 );
682 yield* forkParked(
683 Stream.runForEach(stateChanges, requestSync).pipe(
684 Effect.catchCause(logSkipped("pull request state change stream failed", {})),
685 ),
686 );
687 yield* forkParked(
688 Stream.runForEach(events, (event) => {
689 switch (event.type) {
690 case "thread.pull-request-link-updated":
691 return event.payload.snapshot === null ? requestSync(event.payload) : Effect.void;
692 case "thread.pull-request-synced":
693 return Effect.forEach(
694 visibleThreadPullRequests(event.payload.pullRequests ?? []).filter(
695 (link) => link.snapshot === null,
696 ),
697 requestSync,
698 { discard: true },
699 );
700 // An agent can merge or close its pull request from a shell with its host's CLI, which
701 // sends no merge notification. Read the thread's open links fresh once that command
702 // ends, while the agent usually still replies, so settlement can land before the run
703 // ends. Read again when the run ends, since `merge --auto` returns before it merges.
704 case "turn-item.updated": {
705 const item = event.payload;
706 if (item.type !== "command_execution") return Effect.void;
707 const linked = linkCreatedChangeRequests(event.threadId, item);
708 if (!isChangeRequestCloseCommand(item.input)) return linked;
709 const ended = closeCommands.get(event.threadId) ?? new Set<string>();
710 closeCommands.set(event.threadId, ended);
711 if (isOrchestrationV2WorkActive(item.status) || ended.has(item.id)) return linked;
712 ended.add(item.id);
713 return Effect.andThen(linked, refreshOpenLinks(event.threadId));
714 }
715 case "run.updated":
716 return isTerminalRunStatus(event.payload.status) && closeCommands.delete(event.threadId)
717 ? refreshOpenLinks(event.threadId)
718 : Effect.void;
719 default:
720 return Effect.void;
721 }
722 }).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
723 );
724 yield* forkParked(
725 Effect.gen(function* () {
726 yield* worker.enqueue("all");
727 yield* worker.drain;
728 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
729 );
730 });
731
732 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
733 Effect.suspend(() => {
734 pendingRequests.add(threadPullRequestKeyOf(key));
735 if (requestedSweepQueued) return Effect.void;
736 requestedSweepQueued = true;
737 return worker.enqueue("requested");
738 });
739
740 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
741});
742
743export const layer = Layer.effect(PullRequestSyncReactor, make);