+36
![github-actions[bot]](/assets/img/avatar_default.png)








Julius Marminge
maria-rcks
Bilal Bakr
shivam
Vitalii Yehorov
Jake Leventhal
Claude Opus 5
Alex Southwell
github-actions[bot]
Nicholas Wasmiller
PB
Exotic
Yash Singh
Devin
Theo Browne
Gabriel De Andrade
Dara Adedeji
scratchyone
Dominic Roy
chukfinley
Primož Ajdišek
benthecarman
NaveDanan
aaditagrawal
Aditya Garud
Nick Anisimov
MacKinley Smith
Yordis Prieto
t3-code[bot]
AKolenda
Guillermo Casanova
Otavio Salvador
Shirish Pothi
Ishaan Kothari
Bob Fowler
Anton Bezdenezhnykh
ValeraZSD
Ephraim
Ryan Ilano
Alex
maco
Cursor
Tristan Knight
PR Batch Tester
oliver
kamkm
de34391427
Co-authored-by: maria-rcks <[email protected]> Co-authored-by: Bilal Bakr <[email protected]> Co-authored-by: shivam <[email protected]> Co-authored-by: Vitalii Yehorov <[email protected]> Co-authored-by: Jake Leventhal <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Alex Southwell <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Nicholas Wasmiller <[email protected]> Co-authored-by: PB <[email protected]> Co-authored-by: Exotic <[email protected]> Co-authored-by: Yash Singh <[email protected]> Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Theo Browne <[email protected]> Co-authored-by: Gabriel De Andrade <[email protected]> Co-authored-by: Dara Adedeji <[email protected]> Co-authored-by: scratchyone <[email protected]> Co-authored-by: Dominic Roy <[email protected]> Co-authored-by: chukfinley <[email protected]> Co-authored-by: Primož Ajdišek <[email protected]> Co-authored-by: benthecarman <[email protected]> Co-authored-by: NaveDanan <[email protected]> Co-authored-by: aaditagrawal <[email protected]> Co-authored-by: Aditya Garud <[email protected]> Co-authored-by: Nick Anisimov <[email protected]> Co-authored-by: MacKinley Smith <[email protected]> Co-authored-by: Yordis Prieto <[email protected]> Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com> Co-authored-by: AKolenda <[email protected]> Co-authored-by: Guillermo Casanova <[email protected]> Co-authored-by: Otavio Salvador <[email protected]> Co-authored-by: Shirish Pothi <[email protected]> Co-authored-by: Ishaan Kothari <[email protected]> Co-authored-by: Bob Fowler <[email protected]> Co-authored-by: Anton Bezdenezhnykh <[email protected]> Co-authored-by: ValeraZSD <[email protected]> Co-authored-by: Ephraim <[email protected]> Co-authored-by: Ryan Ilano <[email protected]> Co-authored-by: Alex <[email protected]> Co-authored-by: maco <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: Tristan Knight <[email protected]> Co-authored-by: PR Batch Tester <[email protected]> Co-authored-by: oliver <[email protected]> Co-authored-by: kamkm <[email protected]> Signed-off-by: Yordis Prieto <[email protected]>
409 lines
16 KiB
TypeScript
409 lines
16 KiB
TypeScript
import {
|
|
canonicalRepositoryKey,
|
|
sourceControlRepositorySelector,
|
|
} from "@t3tools/shared/sourceControl";
|
|
import {
|
|
CommandId,
|
|
type OrchestrationProjectShell,
|
|
type OrchestrationV2DomainEvent,
|
|
type OrchestrationV2ThreadShell,
|
|
type ThreadId,
|
|
type ThreadLinkedPullRequest,
|
|
} from "@t3tools/contracts";
|
|
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
|
import * as Cause from "effect/Cause";
|
|
import * as Context from "effect/Context";
|
|
import * as Crypto from "effect/Crypto";
|
|
import * as Effect from "effect/Effect";
|
|
import * as FileSystem from "effect/FileSystem";
|
|
import * as Layer from "effect/Layer";
|
|
import * as Option from "effect/Option";
|
|
import * as Schedule from "effect/Schedule";
|
|
import type * as Scope from "effect/Scope";
|
|
import * as Stream from "effect/Stream";
|
|
|
|
import * as GitManager from "../git/GitManager.ts";
|
|
import * as ProjectStore from "./ProjectStore.ts";
|
|
import * as PullRequestService from "../pullRequest/PullRequestService.ts";
|
|
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
|
|
import { forkParked } from "../serverActivation.ts";
|
|
import * as Orchestrator from "./Orchestrator.ts";
|
|
|
|
class ThreadPullRequestServiceV2 extends Context.Service<
|
|
ThreadPullRequestServiceV2,
|
|
{
|
|
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
|
readonly drain: Effect.Effect<void>;
|
|
}
|
|
>()("t3/orchestration-v2/ThreadPullRequestService/ThreadPullRequestServiceV2") {}
|
|
|
|
function samePullRequest(
|
|
left: ThreadLinkedPullRequest | null | undefined,
|
|
right: ThreadLinkedPullRequest | null,
|
|
): boolean {
|
|
if (left == null || right === null) return left == null && right === null;
|
|
return (
|
|
left.projectId === right.projectId &&
|
|
left.repository.toLowerCase() === right.repository.toLowerCase() &&
|
|
left.number === right.number &&
|
|
left.url === right.url
|
|
);
|
|
}
|
|
|
|
function pullRequestMatchesProject(
|
|
pullRequest: GitManager.GitBranchPullRequest,
|
|
project: OrchestrationProjectShell,
|
|
): boolean {
|
|
return (
|
|
pullRequest.repositoryKey !== null &&
|
|
project.repositoryIdentity != null &&
|
|
canonicalRepositoryKey(pullRequest.repositoryKey) ===
|
|
canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
|
|
);
|
|
}
|
|
|
|
export const resolveProjectForPullRequestDiscovery = Effect.fn(
|
|
"ThreadPullRequestServiceV2.resolveProject",
|
|
)(function* (
|
|
project: OrchestrationProjectShell,
|
|
repositoryIdentities: RepositoryIdentityResolver.RepositoryIdentityResolver["Service"],
|
|
options?: { readonly refresh?: boolean },
|
|
) {
|
|
// Identities stay cached for 15 minutes. A finished turn may have added the
|
|
// remote its pull request lives on, so post-turn discovery refreshes.
|
|
const repositoryIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
|
|
refresh: options?.refresh ?? false,
|
|
});
|
|
return {
|
|
project: { ...project, repositoryIdentity },
|
|
repository: sourceControlRepositorySelector(repositoryIdentity),
|
|
};
|
|
});
|
|
|
|
export function projectWorkspaceMatchesSnapshot(
|
|
currentProject: Option.Option<Pick<OrchestrationProjectShell, "workspaceRoot">>,
|
|
expectedWorkspaceRoot: string,
|
|
): boolean {
|
|
return (
|
|
Option.isSome(currentProject) && currentProject.value.workspaceRoot === expectedWorkspaceRoot
|
|
);
|
|
}
|
|
|
|
const BACKFILL_ATTEMPTS = 5;
|
|
|
|
interface RefreshRequest {
|
|
readonly threadId: ThreadId | null;
|
|
readonly refresh: boolean;
|
|
readonly backfill?: boolean;
|
|
}
|
|
|
|
export const make = Effect.gen(function* () {
|
|
const orchestrator = yield* Orchestrator.OrchestratorV2;
|
|
const projectStore = yield* ProjectStore.ProjectStoreV2;
|
|
const git = yield* GitManager.GitManager;
|
|
const pullRequests = yield* PullRequestService.PullRequestService;
|
|
const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
|
|
const crypto = yield* Crypto.Crypto;
|
|
const fileSystem = yield* FileSystem.FileSystem;
|
|
const pendingBackfill = new Map<ThreadId, number>();
|
|
|
|
const finishBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
|
|
for (const thread of threads) pendingBackfill.delete(thread.id);
|
|
};
|
|
const failBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
|
|
for (const thread of threads) {
|
|
const remaining = pendingBackfill.get(thread.id);
|
|
if (remaining === undefined) continue;
|
|
if (remaining <= 1) pendingBackfill.delete(thread.id);
|
|
else pendingBackfill.set(thread.id, remaining - 1);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* A sweep for one thread reads only that thread's shell, not every thread's.
|
|
* Finished runs and checkpoints queue one of these each. A sweep over all
|
|
* threads reads only active, unsettled ones, since discovery skips the rest;
|
|
* backfill looks up settled threads, so its passes read every active thread.
|
|
*/
|
|
const readThreadSnapshot = ({ threadId, backfill }: RefreshRequest) =>
|
|
threadId === null
|
|
? orchestrator.getShellSnapshot({
|
|
location: "active",
|
|
unsettledOnly: !(backfill || pendingBackfill.size > 0),
|
|
})
|
|
: Effect.gen(function* () {
|
|
// Read the sequence first. The thread is then at least this new, so a
|
|
// sync guarded by the sequence is rejected rather than missing a change.
|
|
const snapshotSequence = yield* orchestrator.getThreadEventSequence(threadId);
|
|
const thread = yield* orchestrator.getThreadShell(threadId);
|
|
return { snapshotSequence, threads: thread === null ? [] : [thread] };
|
|
});
|
|
|
|
const synchronize = Effect.fn("ThreadPullRequestServiceV2.synchronize")(function* (
|
|
request: RefreshRequest,
|
|
) {
|
|
const [threadSnapshot, projectShells] = yield* Effect.all([
|
|
readThreadSnapshot(request),
|
|
projectStore.listShells(),
|
|
]);
|
|
const projects = new Map(projectShells.map((project) => [project.id, project]));
|
|
if (request.backfill) {
|
|
for (const thread of threadSnapshot.threads) {
|
|
if (
|
|
(thread.settledOverride === "settled" || thread.settledAt !== null) &&
|
|
thread.branchPullRequest == null
|
|
) {
|
|
pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
|
|
}
|
|
}
|
|
}
|
|
// A single-thread read only shows whether its own thread is gone. A thread
|
|
// with no branch has nothing to look up, and its entry would keep every
|
|
// periodic pass on the full read.
|
|
const visibleThreadIds = new Set(
|
|
threadSnapshot.threads.filter((thread) => thread.branch !== null).map((thread) => thread.id),
|
|
);
|
|
const checkedIds = request.threadId === null ? [...pendingBackfill.keys()] : [request.threadId];
|
|
for (const threadId of checkedIds) {
|
|
if (!visibleThreadIds.has(threadId)) pendingBackfill.delete(threadId);
|
|
}
|
|
const threads = threadSnapshot.threads.filter(
|
|
(thread) =>
|
|
thread.archivedAt === null &&
|
|
((thread.settledOverride !== "settled" && thread.settledAt === null) ||
|
|
request.threadId !== null ||
|
|
pendingBackfill.has(thread.id)) &&
|
|
(thread.branch !== null || thread.branchPullRequest != null),
|
|
);
|
|
const groups = Map.groupBy(threads, (thread) =>
|
|
JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
|
|
);
|
|
|
|
yield* Effect.forEach(
|
|
groups.values(),
|
|
(group) =>
|
|
Effect.gen(function* () {
|
|
const first = group[0]!;
|
|
const project = projects.get(first.projectId);
|
|
if (project === undefined) return finishBackfill(group);
|
|
const { project: resolvedProject, repository } =
|
|
yield* resolveProjectForPullRequestDiscovery(project, repositoryIdentities, {
|
|
refresh: request.refresh,
|
|
});
|
|
if (first.branch !== null && repository === null) return finishBackfill(group);
|
|
const worktreeExists =
|
|
first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
|
|
const cwd =
|
|
worktreeExists && first.worktreePath !== null
|
|
? first.worktreePath
|
|
: project.workspaceRoot;
|
|
const detected =
|
|
first.branch === null
|
|
? null
|
|
: yield* git.branchPullRequest(
|
|
{ cwd, branch: first.branch },
|
|
{ refresh: request.refresh },
|
|
);
|
|
if (detected !== null && !pullRequestMatchesProject(detected, resolvedProject)) {
|
|
return finishBackfill(group);
|
|
}
|
|
const detectedReference =
|
|
detected !== null && repository !== null
|
|
? {
|
|
projectId: project.id,
|
|
repository,
|
|
number: detected.number,
|
|
url: detected.url,
|
|
}
|
|
: null;
|
|
|
|
const plans = yield* Effect.forEach(group, (thread) =>
|
|
Effect.gen(function* () {
|
|
let branchPullRequest = detectedReference;
|
|
if (
|
|
branchPullRequest === null &&
|
|
thread.branch !== null &&
|
|
thread.worktreePath === null &&
|
|
thread.branchPullRequest != null
|
|
) {
|
|
const previous = yield* pullRequests.summary(thread.branchPullRequest, {
|
|
recoverTransientFailure: false,
|
|
});
|
|
if (previous.state === "merged" || previous.state === "closed") {
|
|
branchPullRequest = thread.branchPullRequest;
|
|
}
|
|
}
|
|
|
|
let replacement: ThreadLinkedPullRequest | undefined;
|
|
if (
|
|
(thread.pullRequests ?? []).length === 0 &&
|
|
thread.linkedPullRequest != null &&
|
|
detected?.state === "open" &&
|
|
detectedReference !== null &&
|
|
!samePullRequest(thread.linkedPullRequest, detectedReference)
|
|
) {
|
|
const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
|
|
recoverTransientFailure: false,
|
|
});
|
|
if (linked.state === "merged" || linked.state === "closed") {
|
|
replacement = detectedReference;
|
|
}
|
|
}
|
|
if (
|
|
samePullRequest(thread.branchPullRequest, branchPullRequest) &&
|
|
replacement === undefined
|
|
) {
|
|
pendingBackfill.delete(thread.id);
|
|
return null;
|
|
}
|
|
return { thread, branchPullRequest, replacement };
|
|
}).pipe(
|
|
Effect.catchCauseIf(
|
|
(cause) => !Cause.hasInterruptsOnly(cause),
|
|
(cause) =>
|
|
Effect.logWarning("thread pull request discovery failed", {
|
|
threadId: thread.id,
|
|
cause: Cause.pretty(cause),
|
|
}).pipe(
|
|
Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
|
|
Effect.as(null),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
const updates = plans.filter((plan) => plan !== null);
|
|
if (updates.length === 0) return;
|
|
|
|
if (detected !== null && first.branch !== null) {
|
|
const current = yield* git.branchPullRequest({ cwd, branch: first.branch });
|
|
const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
|
|
refresh: true,
|
|
});
|
|
if (
|
|
current === null ||
|
|
current.number !== detected.number ||
|
|
current.url !== detected.url ||
|
|
current.state !== detected.state ||
|
|
current.repositoryKey !== detected.repositoryKey ||
|
|
!pullRequestMatchesProject(current, {
|
|
...project,
|
|
repositoryIdentity: currentIdentity,
|
|
})
|
|
) {
|
|
return failBackfill(updates.map((update) => update.thread));
|
|
}
|
|
}
|
|
|
|
yield* Effect.forEach(
|
|
updates,
|
|
({ thread, branchPullRequest, replacement }) =>
|
|
Effect.gen(function* () {
|
|
// Discovery can perform network I/O. Re-read the project at
|
|
// the transaction boundary so a deleted project or changed
|
|
// workspace root cannot apply a result from the old checkout.
|
|
const currentProject = yield* projectStore.getShell(project.id);
|
|
if (!projectWorkspaceMatchesSnapshot(currentProject, project.workspaceRoot)) {
|
|
return failBackfill([thread]);
|
|
}
|
|
const uuid = yield* crypto.randomUUIDv4;
|
|
yield* orchestrator.dispatch({
|
|
type: "thread.pull-request.sync",
|
|
commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
|
|
threadId: thread.id,
|
|
projectId: project.id,
|
|
snapshotSequence: threadSnapshot.snapshotSequence,
|
|
expected: {
|
|
workspaceRoot: project.workspaceRoot,
|
|
branch: thread.branch,
|
|
worktreePath: thread.worktreePath,
|
|
linkedPullRequest: thread.linkedPullRequest ?? null,
|
|
branchPullRequest: thread.branchPullRequest ?? null,
|
|
},
|
|
branchPullRequest,
|
|
...(replacement === undefined ? {} : { linkedPullRequest: replacement }),
|
|
});
|
|
pendingBackfill.delete(thread.id);
|
|
}).pipe(
|
|
Effect.catchCause((cause) =>
|
|
Cause.hasInterruptsOnly(cause)
|
|
? Effect.failCause(cause)
|
|
: Effect.logWarning("thread pull request update failed", {
|
|
threadId: thread.id,
|
|
cause: Cause.pretty(cause),
|
|
}).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
|
|
),
|
|
),
|
|
{ discard: true },
|
|
);
|
|
}).pipe(
|
|
Effect.catchCauseIf(
|
|
(cause) => !Cause.hasInterruptsOnly(cause),
|
|
(cause) =>
|
|
Effect.logWarning("thread branch pull request lookup failed", {
|
|
threadIds: group.map((thread) => thread.id),
|
|
cause: Cause.pretty(cause),
|
|
}).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
|
|
),
|
|
),
|
|
// Wide enough that a sweep's GitHub branch lookups reach GitHubCli together and share one
|
|
// GraphQL document, instead of one `gh pr list` per branch.
|
|
{ concurrency: 32, discard: true },
|
|
);
|
|
});
|
|
|
|
const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
|
|
synchronize(request).pipe(
|
|
Effect.catchCauseIf(
|
|
(cause) => !Cause.hasInterruptsOnly(cause),
|
|
(cause) =>
|
|
Effect.logWarning("thread pull request refresh failed", {
|
|
cause: Cause.pretty(cause),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
|
|
const processEvent = (event: OrchestrationV2DomainEvent) => {
|
|
switch (event.type) {
|
|
case "thread.created":
|
|
case "thread.unarchived":
|
|
case "thread.metadata-updated":
|
|
return worker.enqueue({ threadId: event.threadId, refresh: false });
|
|
case "thread.unsettled":
|
|
case "checkpoint.captured":
|
|
return worker.enqueue({ threadId: event.threadId, refresh: true });
|
|
case "run.updated":
|
|
if (
|
|
event.payload.status === "completed" ||
|
|
event.payload.status === "failed" ||
|
|
event.payload.status === "cancelled" ||
|
|
event.payload.status === "interrupted"
|
|
) {
|
|
return worker.enqueue({ threadId: event.threadId, refresh: true });
|
|
}
|
|
break;
|
|
}
|
|
return Effect.void;
|
|
};
|
|
|
|
const start: ThreadPullRequestServiceV2["Service"]["start"] = Effect.fn(
|
|
"ThreadPullRequestServiceV2.start",
|
|
)(function* () {
|
|
yield* forkParked(Stream.runForEach(orchestrator.streamDomainEvents, processEvent));
|
|
yield* forkParked(
|
|
Effect.gen(function* () {
|
|
yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
|
|
yield* worker.drain;
|
|
yield* Effect.gen(function* () {
|
|
yield* worker.enqueue({ threadId: null, refresh: false });
|
|
yield* worker.drain;
|
|
}).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
|
|
}).pipe(Effect.asVoid),
|
|
);
|
|
});
|
|
|
|
return { start, drain: worker.drain } satisfies ThreadPullRequestServiceV2["Service"];
|
|
});
|
|
|
|
const layer = Layer.effect(ThreadPullRequestServiceV2, make);
|