fix(server): link thread PRs without an open client (#10101)

Co-authored-by: Claude Fable 5.1 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5.1 authored and GitHub committed 2026-09-06 04:06:15 -07:00
1 parent 5fa35d2116
commit 223ff4490f
50 files changed
+2308 -1485

No files matched your search

@@ -13,6 +13,7 @@ import {
ProjectId,
ThreadId,
TurnId,
type OrchestrationCommand,
type OrchestrationEvent,
ProviderInstanceId,
} from "@t3tools/contracts";
@@ -993,6 +994,216 @@ describe("OrchestrationEngine", () => {
await system.dispose();
});
it.each(["unlink", "relink", "branch", "worktree", "project", "delete"] as const)(
"rejects PR discovery completed after a newer %s command",
async (change) => {
const system = await createOrchestrationSystem();
try {
const projectId = ProjectId.make("pr-race-project");
const threadId = ThreadId.make("pr-race-thread");
const previous = {
projectId,
repository: "owner/repository",
number: 1,
url: "https://example.test/owner/repository/pull/1",
};
const replacement = {
...previous,
number: 2,
url: "https://example.test/owner/repository/pull/2",
};
await system.run(
system.engine.dispatch({
type: "project.create",
commandId: CommandId.make("pr-race-project-create"),
projectId,
title: "PR race project",
workspaceRoot: "/tmp/pr-race-project",
defaultModelSelection: null,
createdAt: now(),
}),
);
await system.run(
system.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("pr-race-thread-create"),
threadId,
projectId,
title: "PR race thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature",
worktreePath: null,
createdAt: now(),
}),
);
const observed = await system.run(
system.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("pr-race-link"),
threadId,
linkedPullRequest: previous,
}),
);
const metadataChanges = {
unlink: { linkedPullRequest: null },
relink: {
linkedPullRequest: {
...previous,
number: 3,
url: "https://example.test/owner/repository/pull/3",
},
},
branch: { branch: "another-feature" },
worktree: { worktreePath: "/tmp/another-worktree" },
project: {},
};
await system.run(
system.engine.dispatch(
change === "project"
? {
type: "project.meta.update",
commandId: CommandId.make("pr-race-project-move"),
projectId,
workspaceRoot: "/tmp/another-project-root",
}
: change === "delete"
? { type: "thread.delete", commandId: CommandId.make("pr-race-delete"), threadId }
: {
type: "thread.meta.update",
commandId: CommandId.make(`pr-race-${change}`),
threadId,
...metadataChanges[change],
},
),
);
const command = {
type: "thread.pull-request.sync",
commandId: CommandId.make("pr-race-stale-sync"),
threadId,
projectId,
snapshotSequence: observed.sequence,
expected: {
workspaceRoot: "/tmp/pr-race-project",
branch: "feature",
worktreePath: null,
linkedPullRequest: previous,
branchPullRequest: null,
},
branchPullRequest: replacement,
linkedPullRequest: replacement,
} satisfies OrchestrationCommand;
const error = await system.run(system.engine.dispatch(command).pipe(Effect.flip));
expect(error._tag).toBe("OrchestrationCommandInvariantError");
if (change === "delete") return;
const current = (await system.readModel()).threads[0];
expect(current?.branchPullRequest ?? null).toBeNull();
expect(current?.linkedPullRequest ?? null).toEqual(
change === "unlink"
? null
: change === "relink"
? metadataChanges.relink.linkedPullRequest
: previous,
);
} finally {
await system.dispose();
}
},
);
it("saves PR associations through streaming and unrelated metadata edits", async () => {
const system = await createOrchestrationSystem();
try {
const projectId = ProjectId.make("pr-sync-project");
const threadId = ThreadId.make("pr-sync-thread");
await system.run(
system.engine.dispatch({
type: "project.create",
commandId: CommandId.make("pr-sync-project-create"),
projectId,
title: "PR sync project",
workspaceRoot: "/tmp/pr-sync-project",
defaultModelSelection: null,
createdAt: now(),
}),
);
const created = await system.run(
system.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("pr-sync-thread-create"),
threadId,
projectId,
title: "PR sync thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature",
worktreePath: null,
createdAt: now(),
}),
);
const reference = {
projectId,
repository: "owner/repository",
number: 42,
url: "https://example.test/owner/repository/pull/42",
};
const activityAt = "2026-01-01T01:00:00.000Z";
await system.run(
system.engine.dispatch({
type: "thread.message.assistant.delta",
commandId: CommandId.make("pr-sync-streaming-message"),
threadId,
messageId: MessageId.make("pr-sync-message"),
delta: "The PR is ready.",
createdAt: activityAt,
}),
);
await system.run(
system.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("pr-sync-title-and-model"),
threadId,
title: "Renamed thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
}),
);
await system.run(
system.engine.dispatch({
type: "project.meta.update",
commandId: CommandId.make("pr-sync-project-title"),
projectId,
title: "Renamed project",
}),
);
const beforeSync = (await system.readModel()).threads[0];
await system.run(
system.engine.dispatch({
type: "thread.pull-request.sync",
commandId: CommandId.make("pr-sync-discovery"),
projectId,
threadId,
snapshotSequence: created.sequence,
expected: {
workspaceRoot: "/tmp/pr-sync-project",
branch: "feature",
worktreePath: null,
linkedPullRequest: null,
branchPullRequest: null,
},
branchPullRequest: reference,
}),
);
const current = (await system.readModel()).threads[0];
expect(current?.branchPullRequest).toEqual(reference);
expect(current?.linkedPullRequest ?? null).toBeNull();
expect(current?.updatedAt).toBe(beforeSync?.updatedAt);
} finally {
await system.dispose();
}
});
it("allows authoritative worktree bootstrap to assign a temporary branch", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
@@ -185,6 +185,23 @@ const makeOrchestrationEngine = Effect.gen(function* () {
});
}
// The decider compares the lookup inputs. Only recreation needs an
// event check, since it can reset a thread to the same field values.
if (
envelope.command.type === "thread.pull-request.sync" &&
(yield* eventStore.hasEventAfter({
aggregateKind: "thread",
aggregateId: envelope.command.threadId,
sequenceExclusive: envelope.command.snapshotSequence,
type: "thread.created",
}))
) {
return yield* new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: `thread ${envelope.command.threadId} was recreated before pull request discovery`,
});
}
if (
envelope.command.type === "thread.auto-settle" &&
threadBackgroundLiveness.getThreadBackgroundLiveness(envelope.command.threadId) !== null
@@ -10,6 +10,7 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
import * as ThreadSettlementReactor from "../ThreadSettlementReactor.ts";
import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
@@ -65,6 +66,15 @@ describe("OrchestrationReactor", () => {
drainThrough: () => Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ThreadPullRequestReactor.ThreadPullRequestReactor, {
start: () => {
started.push("thread-pull-request-reactor");
return Effect.void;
},
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ThreadSettlementReactor.ThreadSettlementReactor, {
start: () => {
@@ -95,6 +105,7 @@ describe("OrchestrationReactor", () => {
"provider-command-reactor",
"checkpoint-reactor",
"thread-deletion-reactor",
"thread-pull-request-reactor",
"thread-settlement-reactor",
"agent-awareness-relay",
]);
@@ -10,6 +10,7 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
import * as ThreadSettlementReactor from "../ThreadSettlementReactor.ts";
import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
export const makeOrchestrationReactor = Effect.gen(function* () {
@@ -18,6 +19,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
const checkpointReactor = yield* CheckpointReactor;
const threadDeletionReactor = yield* ThreadDeletionReactor;
const threadSettlementReactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
const threadPullRequestReactor = yield* ThreadPullRequestReactor.ThreadPullRequestReactor;
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
@@ -25,6 +27,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
yield* providerCommandReactor.start();
yield* checkpointReactor.start();
yield* threadDeletionReactor.start();
yield* threadPullRequestReactor.start();
yield* threadSettlementReactor.start();
yield* agentAwarenessRelay.start();
});
@@ -8,6 +8,7 @@ import {
MessageId,
ProjectId,
ThreadId,
ThreadLinkedPullRequest,
TurnId,
ProviderInstanceId,
} from "@t3tools/contracts";
@@ -18,6 +19,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { makeSqlStatementCounter } from "../../../integration/SqlStatementCounter.integration.ts";
@@ -59,6 +61,9 @@ const exists = (filePath: string) =>
});
const BaseTestLayer = makeProjectionPipelinePrefixedTestLayer("t3-projection-pipeline-test-");
const encodeThreadLinkedPullRequest = Schema.encodeSync(
Schema.fromJsonString(ThreadLinkedPullRequest),
);
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-cursor-batch-")))(
"OrchestrationProjectionPipeline cursor batches",
@@ -204,6 +209,93 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-import-shell-")
},
);
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-branch-pr-projection-")))(
"branch pull request projection",
(it) => {
it.effect("persists branch pull request updates without changing manual links", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("thread-pull-request");
const projectId = ProjectId.make("project-pull-request");
const eventFields = {
aggregateKind: "thread" as const,
aggregateId: threadId,
occurredAt: now,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
};
const created = yield* eventStore.append({
...eventFields,
type: "thread.created",
eventId: EventId.make("evt-pull-request-created"),
payload: {
threadId,
projectId,
title: "Pull request thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature",
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* projectionPipeline.projectEvent(created);
const linkedPullRequest = {
projectId,
repository: "pingdotgg/t3code",
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
};
const branchPullRequest = {
...linkedPullRequest,
number: 43,
url: "https://github.com/pingdotgg/t3code/pull/43",
};
const updates = [
{ payload: { linkedPullRequest, branchPullRequest }, expected: branchPullRequest },
{ payload: { title: "Renamed thread" }, expected: branchPullRequest },
{ payload: { branchPullRequest: null }, expected: null },
];
for (const [index, update] of updates.entries()) {
const event = yield* eventStore.append({
...eventFields,
type: "thread.meta-updated",
eventId: EventId.make(`evt-pull-request-update-${index}`),
payload: { threadId, updatedAt: now, ...update.payload },
});
yield* projectionPipeline.projectEvent(event);
const rows = yield* sql<{
readonly linkedPullRequest: string | null;
readonly branchPullRequest: string | null;
}>`
SELECT
linked_pull_request_json AS "linkedPullRequest",
branch_pull_request_json AS "branchPullRequest"
FROM projection_threads
WHERE thread_id = ${threadId}
`;
assert.deepEqual(rows, [
{
linkedPullRequest: encodeThreadLinkedPullRequest(linkedPullRequest),
branchPullRequest:
update.expected === null ? null : encodeThreadLinkedPullRequest(update.expected),
},
]);
}
}),
);
},
);
it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
it.effect("bootstraps all projection states and writes projection rows", () =>
Effect.gen(function* () {
@@ -605,6 +605,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
branch: event.payload.branch,
worktreePath: event.payload.worktreePath,
linkedPullRequest: null,
branchPullRequest: null,
latestTurnId: null,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
@@ -805,6 +806,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
...(event.payload.linkedPullRequest !== undefined
? { linkedPullRequest: event.payload.linkedPullRequest }
: {}),
...(event.payload.branchPullRequest !== undefined
? { branchPullRequest: event.payload.branchPullRequest }
: {}),
updatedAt: event.payload.updatedAt,
});
return;
@@ -6,6 +6,7 @@ import {
MessageId,
ProjectId,
ThreadId,
ThreadLinkedPullRequest,
TurnId,
ProviderInstanceId,
} from "@t3tools/contracts";
@@ -36,6 +37,9 @@ const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(val
const encodeChatAttachments = Schema.encodeEffect(
Schema.fromJsonString(Schema.Array(ChatAttachment)),
);
const encodeThreadLinkedPullRequest = Schema.encodeSync(
Schema.fromJsonString(ThreadLinkedPullRequest),
);
const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(
@@ -52,6 +56,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
const branchPullRequest = {
projectId: asProjectId("project-1"),
repository: "pingdotgg/t3code",
number: 43,
url: "https://github.com/pingdotgg/t3code/pull/43",
};
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_state`;
@@ -92,6 +102,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
branch,
worktree_path,
linked_pull_request_json,
branch_pull_request_json,
latest_turn_id,
latest_user_message_at,
pending_approval_count,
@@ -113,6 +124,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
NULL,
NULL,
'{"projectId":"project-1","repository":"pingdotgg/t3code","number":42,"url":"https://github.com/pingdotgg/t3code/pull/42"}',
${encodeThreadLinkedPullRequest(branchPullRequest)},
'turn-1',
'2026-02-24T00:00:04.000Z',
1,
@@ -323,6 +335,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
},
branchPullRequest,
latestTurn: {
turnId: asTurnId("turn-1"),
state: "completed",
@@ -451,6 +464,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
},
branchPullRequest,
latestTurn: {
turnId: asTurnId("turn-1"),
state: "completed",
@@ -498,6 +512,14 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
assert.deepEqual(threadDetail.value, snapshot.threads[0]);
}
const commandSnapshot = yield* snapshotQuery.getCommandReadModel();
assert.deepEqual(commandSnapshot.threads[0]?.branchPullRequest, branchPullRequest);
const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
assert.equal(threadShell._tag, "Some");
if (threadShell._tag === "Some") {
assert.deepEqual(threadShell.value.branchPullRequest, branchPullRequest);
}
yield* sql`
INSERT INTO projection_thread_activities (
activity_id,
@@ -743,6 +765,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
const branchPullRequest = {
projectId: asProjectId("project-archive-test"),
repository: "pingdotgg/t3code",
number: 43,
url: "https://github.com/pingdotgg/t3code/pull/43",
};
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
@@ -849,6 +877,13 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
shellSnapshot.threads.map((thread) => thread.id),
[ThreadId.make("thread-active")],
);
assert.equal(shellSnapshot.threads[0]?.branchPullRequest, null);
yield* sql`
UPDATE projection_threads
SET branch_pull_request_json = ${encodeThreadLinkedPullRequest(branchPullRequest)}
WHERE thread_id = 'thread-archived'
`;
const archivedShellSnapshot = yield* snapshotQuery.getArchivedShellSnapshot();
assert.deepEqual(
@@ -856,6 +891,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
[ThreadId.make("thread-archived")],
);
assert.equal(archivedShellSnapshot.threads[0]?.archivedAt, "2026-04-06T00:00:06.000Z");
assert.deepEqual(archivedShellSnapshot.threads[0]?.branchPullRequest, branchPullRequest);
const activeContext = yield* snapshotQuery.getThreadRuntimeContext(
ThreadId.make("thread-active"),
);
@@ -116,6 +116,7 @@ const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
}),
);
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
@@ -500,6 +501,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
branch,
worktree_path AS "worktreePath",
linked_pull_request_json AS "linkedPullRequest",
branch_pull_request_json AS "branchPullRequest",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -538,6 +540,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
branch,
worktree_path AS "worktreePath",
linked_pull_request_json AS "linkedPullRequest",
branch_pull_request_json AS "branchPullRequest",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -578,6 +581,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
branch,
worktree_path AS "worktreePath",
linked_pull_request_json AS "linkedPullRequest",
branch_pull_request_json AS "branchPullRequest",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -1067,6 +1071,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
branch,
worktree_path AS "worktreePath",
linked_pull_request_json AS "linkedPullRequest",
branch_pull_request_json AS "branchPullRequest",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -2062,6 +2067,7 @@ pending_approval_requests AS (
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
branchPullRequest: row.branchPullRequest,
...(row.linkedPullRequest === null
? {}
: { linkedPullRequest: row.linkedPullRequest }),
@@ -2275,6 +2281,7 @@ pending_approval_requests AS (
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
branchPullRequest: row.branchPullRequest,
...(row.linkedPullRequest === null
? {}
: { linkedPullRequest: row.linkedPullRequest }),
@@ -2415,6 +2422,7 @@ pending_approval_requests AS (
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
branchPullRequest: row.branchPullRequest,
...(row.linkedPullRequest === null
? {}
: { linkedPullRequest: row.linkedPullRequest }),
@@ -2563,6 +2571,7 @@ pending_approval_requests AS (
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
branchPullRequest: row.branchPullRequest,
...(row.linkedPullRequest === null
? {}
: { linkedPullRequest: row.linkedPullRequest }),
@@ -2884,6 +2893,7 @@ pending_approval_requests AS (
interactionMode: threadRow.value.interactionMode,
branch: threadRow.value.branch,
worktreePath: threadRow.value.worktreePath,
branchPullRequest: threadRow.value.branchPullRequest,
...(threadRow.value.linkedPullRequest === null
? {}
: { linkedPullRequest: threadRow.value.linkedPullRequest }),
@@ -3165,6 +3175,7 @@ pending_approval_requests AS (
interactionMode: threadRow.value.interactionMode,
branch: threadRow.value.branch,
worktreePath: threadRow.value.worktreePath,
branchPullRequest: threadRow.value.branchPullRequest,
...(threadRow.value.linkedPullRequest === null
? {}
: { linkedPullRequest: threadRow.value.linkedPullRequest }),
@@ -0,0 +1,613 @@
import {
EventId,
GitManagerError,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationProjectShell,
type OrchestrationShellSnapshot,
type OrchestrationThreadShell,
type PullRequestRef,
type PullRequestSummary,
type ThreadLinkedPullRequest,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";
import { PullRequestService } from "../pullRequest/PullRequestService.ts";
import { RepositoryIdentityResolver } from "../project/RepositoryIdentityResolver.ts";
import { ServerActivation } from "../serverActivation.ts";
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
import * as ThreadPullRequestReactor from "./ThreadPullRequestReactor.ts";
const NOW = "2026-09-01T12:00:00.000Z";
const PROJECT_ID = ProjectId.make("project");
const REPOSITORY = "owner/repository";
const REPOSITORY_KEY = `github.com/${REPOSITORY}`;
type SyncCommand = Extract<OrchestrationCommand, { type: "thread.pull-request.sync" }>;
function reference(number: number): ThreadLinkedPullRequest {
return {
projectId: PROJECT_ID,
repository: REPOSITORY,
number,
url: `https://github.com/${REPOSITORY}/pull/${number}`,
};
}
function branchPullRequest(
number = 42,
state: GitBranchPullRequest["state"] = "open",
): GitBranchPullRequest {
return {
...reference(number),
title: "Branch pull request",
baseRef: "main",
headRef: "feature",
state,
updatedAt: NOW,
repositoryKey: REPOSITORY_KEY,
};
}
function summary(input: PullRequestRef, state: PullRequestSummary["state"]): PullRequestSummary {
return {
...input,
provider: "github",
title: "Pull request",
url: reference(input.number).url,
state,
headBranch: "feature",
baseBranch: "main",
updatedAt: NOW,
};
}
function thread(
id: string,
overrides: Partial<OrchestrationThreadShell> = {},
): OrchestrationThreadShell {
return {
id: ThreadId.make(id),
projectId: PROJECT_ID,
title: id,
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature",
worktreePath: null,
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: NOW,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...overrides,
};
}
const project = {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/workspace/project",
repositoryIdentity: {
canonicalKey: REPOSITORY_KEY,
displayName: REPOSITORY,
rootPath: "/workspace/project",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: `[email protected]:${REPOSITORY}.git`,
},
},
defaultModelSelection: null,
scripts: [],
createdAt: NOW,
updatedAt: NOW,
} satisfies OrchestrationProjectShell;
const makeHarness = Effect.fn("makeThreadPullRequestHarness")(function* (options: {
readonly threads: ReadonlyArray<OrchestrationThreadShell>;
readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];
readonly summary?: PullRequestService["Service"]["summary"];
readonly existingWorktrees?: ReadonlyArray<string>;
readonly project?: OrchestrationProjectShell;
readonly resolveRepositoryIdentity?: RepositoryIdentityResolver["Service"]["resolve"];
}) {
const activation = yield* Deferred.make<void>();
const snapshots = yield* Ref.make<OrchestrationShellSnapshot>({
snapshotSequence: 1,
projects: [options.project ?? project],
threads: options.threads,
updatedAt: NOW,
});
const reads = yield* Queue.unbounded<void>();
const events = yield* PubSub.unbounded<OrchestrationEvent>();
const commands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
const branchCalls = yield* Ref.make<
ReadonlyArray<{ readonly cwd: string; readonly branch: string; readonly refresh: boolean }>
>([]);
const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
let uuid = 0;
const dependencies = Layer.mergeAll(
Layer.mock(ProjectionSnapshotQuery)({
getShellSnapshot: () =>
Ref.get(snapshots).pipe(Effect.tap(() => Queue.offer(reads, undefined))),
}),
Layer.mock(GitManager)({
branchPullRequest: (input, readOptions) =>
Ref.update(branchCalls, (calls) => [
...calls,
{ ...input, refresh: readOptions?.refresh === true },
]).pipe(
Effect.andThen(options.branchPullRequest?.(input, readOptions) ?? Effect.succeed(null)),
),
}),
Layer.mock(PullRequestService)({
summary: (input, readOptions) =>
Ref.update(summaryCalls, (calls) => [...calls, input]).pipe(
Effect.andThen(
options.summary?.(input, readOptions) ?? Effect.succeed(summary(input, "open")),
),
),
}),
Layer.mock(RepositoryIdentityResolver)({
resolve:
options.resolveRepositoryIdentity ??
(() => Effect.succeed(options.project?.repositoryIdentity ?? project.repositoryIdentity)),
}),
Layer.mock(OrchestrationEngineService)({
subscribeDomainEvents: PubSub.subscribe(events).pipe(
Effect.map((subscription) => Stream.fromSubscription(subscription)),
),
dispatch: (command) => {
if (command.type !== "thread.pull-request.sync") {
return Effect.die(`Unexpected command: ${command.type}`);
}
return Ref.update(commands, (current) => [...current, command]).pipe(
Effect.andThen(
Ref.updateAndGet(snapshots, (snapshot) => ({
...snapshot,
snapshotSequence: snapshot.snapshotSequence + 1,
threads: snapshot.threads.map((current) =>
current.id === command.threadId
? {
...current,
branchPullRequest: command.branchPullRequest,
...(command.linkedPullRequest !== undefined
? { linkedPullRequest: command.linkedPullRequest }
: {}),
}
: current,
),
})),
),
Effect.map((snapshot) => ({ sequence: snapshot.snapshotSequence })),
);
},
}),
Layer.succeed(ServerActivation, Deferred.await(activation)),
Layer.succeed(
Crypto.Crypto,
Crypto.make({
randomBytes: (size) => new Uint8Array(size).fill(++uuid),
digest: (_algorithm, data) => Effect.succeed(data),
}),
),
FileSystem.layerNoop({
exists: (path) => Effect.succeed(options.existingWorktrees?.includes(path) ?? false),
}),
);
const start = Effect.fn("startThreadPullRequestHarness")(function* () {
const reactor = yield* ThreadPullRequestReactor.ThreadPullRequestReactor;
yield* reactor.start();
yield* Deferred.succeed(activation, undefined);
yield* Queue.take(reads);
yield* reactor.drain;
return reactor;
});
return {
start,
reads,
snapshots,
commands,
branchCalls,
summaryCalls,
publish: (event: OrchestrationEvent) => PubSub.publish(events, event),
layer: ThreadPullRequestReactor.layer.pipe(Layer.provide(dependencies)),
};
});
describe("ThreadPullRequestReactor", () => {
it.effect("discovers saved branch PRs without a client and shares branch lookups", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeHarness({
threads: [
thread("first"),
thread("second"),
thread("archived", { archivedAt: NOW }),
thread("no-branch", { branch: null }),
],
branchPullRequest: () => Effect.succeed(branchPullRequest()),
});
yield* Effect.gen(function* () {
const reactor = yield* fixture.start();
expect(yield* Ref.get(fixture.branchCalls)).toEqual([
{ cwd: project.workspaceRoot, branch: "feature", refresh: false },
{ cwd: project.workspaceRoot, branch: "feature", refresh: false },
]);
expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
"first",
"second",
]);
expect((yield* Ref.get(fixture.snapshots)).threads[0]?.branchPullRequest).toEqual(
reference(42),
);
yield* TestClock.adjust("1 minute");
yield* Queue.take(fixture.reads);
yield* reactor.drain;
expect(yield* Ref.get(fixture.commands)).toHaveLength(2);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("replaces terminal manual links but preserves open links and explicit unlink", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeHarness({
threads: [
thread("merged", { linkedPullRequest: reference(1) }),
thread("closed", { linkedPullRequest: reference(2) }),
thread("open", { linkedPullRequest: reference(3) }),
thread("unlinked", { linkedPullRequest: null }),
],
branchPullRequest: () => Effect.succeed(branchPullRequest()),
summary: (input) =>
Effect.succeed(
summary(
input,
input.number === 1 ? "merged" : input.number === 2 ? "closed" : "open",
),
),
});
yield* Effect.gen(function* () {
yield* fixture.start();
const snapshot = yield* Ref.get(fixture.snapshots);
expect(snapshot.threads.map((current) => current.linkedPullRequest)).toEqual([
reference(42),
reference(42),
reference(3),
null,
]);
expect(
snapshot.threads.every((current) => current.branchPullRequest?.number === 42),
).toBe(true);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("refreshes discovery after a turn ends without client demand", () =>
Effect.scoped(
Effect.gen(function* () {
const current = thread("turn-thread");
const detected = yield* Ref.make<GitBranchPullRequest | null>(null);
const fixture = yield* makeHarness({
threads: [current],
branchPullRequest: (_input, options) =>
options?.refresh
? Ref.set(detected, branchPullRequest()).pipe(Effect.andThen(Ref.get(detected)))
: Ref.get(detected),
});
yield* Effect.gen(function* () {
const reactor = yield* fixture.start();
expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
yield* fixture.publish({
type: "thread.session-set",
sequence: 2,
eventId: EventId.make("turn-finished"),
aggregateKind: "thread",
aggregateId: current.id,
occurredAt: NOW,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
payload: {
threadId: current.id,
session: {
threadId: current.id,
status: "ready",
providerName: "Codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: NOW,
},
},
});
yield* Queue.take(fixture.reads);
yield* reactor.drain;
expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual(reference(42));
expect((yield* Ref.get(fixture.branchCalls)).filter((call) => call.refresh)).toHaveLength(
1,
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("uses live worktrees and falls back to the project for removed worktrees", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeHarness({
threads: [
thread("live", { worktreePath: "/workspace/worktree" }),
thread("removed", { worktreePath: "/workspace/removed" }),
],
existingWorktrees: ["/workspace/worktree"],
branchPullRequest: () => Effect.succeed(branchPullRequest()),
});
yield* Effect.gen(function* () {
yield* fixture.start();
expect(new Set((yield* Ref.get(fixture.branchCalls)).map((call) => call.cwd))).toEqual(
new Set(["/workspace/project", "/workspace/worktree"]),
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("retains only terminal PRs on shared checkouts and clears a removed branch", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeHarness({
threads: [
thread("terminal", { branch: "main", branchPullRequest: reference(1) }),
thread("open", { branchPullRequest: reference(2) }),
thread("worktree", {
worktreePath: "/workspace/worktree",
branchPullRequest: reference(1),
}),
thread("cleared", {
branch: null,
branchPullRequest: reference(1),
linkedPullRequest: reference(3),
}),
],
summary: (input) =>
Effect.succeed(summary(input, input.number === 1 ? "merged" : "open")),
});
yield* Effect.gen(function* () {
yield* fixture.start();
const snapshot = yield* Ref.get(fixture.snapshots);
expect(snapshot.threads.map((current) => current.branchPullRequest)).toEqual([
reference(1),
null,
null,
null,
]);
expect(snapshot.threads[3]?.linkedPullRequest).toEqual(reference(3));
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("keeps saved links on lookup failures and rejects a different repository", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeHarness({
threads: [
thread("failed", { branch: "failed", branchPullRequest: reference(1) }),
thread("wrong-repository", {
branch: "wrong-repository",
branchPullRequest: reference(2),
}),
thread("healthy"),
],
branchPullRequest: ({ cwd, branch }) =>
branch === "failed"
? Effect.fail(
new GitManagerError({
operation: "branchPullRequest",
cwd,
detail: "Lookup failed",
}),
)
: Effect.succeed({
...branchPullRequest(),
repositoryKey:
branch === "wrong-repository" ? "github.com/other/repository" : REPOSITORY_KEY,
}),
});
yield* Effect.gen(function* () {
yield* fixture.start();
expect(
(yield* Ref.get(fixture.snapshots)).threads.map((current) => current.branchPullRequest),
).toEqual([reference(1), reference(2), reference(42)]);
expect(yield* Ref.get(fixture.commands)).toHaveLength(1);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("retries failed settled backfills and stops querying them after success", () =>
Effect.scoped(
Effect.gen(function* () {
const online = yield* Ref.make(false);
const fixture = yield* makeHarness({
threads: [
thread("backfill", { settledOverride: "settled", settledAt: NOW }),
thread("known", {
branch: "known",
settledOverride: "settled",
settledAt: NOW,
branchPullRequest: reference(1),
}),
],
branchPullRequest: ({ cwd }) =>
Ref.get(online).pipe(
Effect.flatMap((connected) =>
connected
? Effect.succeed(branchPullRequest(42, "merged"))
: Effect.fail(
new GitManagerError({
operation: "branchPullRequest",
cwd,
detail: "Offline",
}),
),
),
),
});
yield* Effect.gen(function* () {
const reactor = yield* fixture.start();
expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
yield* Ref.set(online, true);
yield* TestClock.adjust("1 minute");
yield* Queue.take(fixture.reads);
yield* reactor.drain;
expect((yield* Ref.get(fixture.commands))[0]?.threadId).toBe("backfill");
yield* TestClock.adjust("1 minute");
yield* Queue.take(fixture.reads);
yield* reactor.drain;
expect((yield* Ref.get(fixture.branchCalls)).map((call) => call.branch)).toEqual([
"feature",
"feature",
"feature",
]);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("stops retrying a settled backfill after repeated lookup failures", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeHarness({
threads: [thread("backfill", { settledOverride: "settled", settledAt: NOW })],
branchPullRequest: ({ cwd }) =>
Effect.fail(
new GitManagerError({ operation: "branchPullRequest", cwd, detail: "No gh" }),
),
});
yield* Effect.gen(function* () {
const reactor = yield* fixture.start();
for (
let attempt = 1;
attempt < ThreadPullRequestReactor.BACKFILL_ATTEMPTS + 2;
attempt++
) {
yield* TestClock.adjust("1 minute");
yield* Queue.take(fixture.reads);
yield* reactor.drain;
}
expect(yield* Ref.get(fixture.branchCalls)).toHaveLength(
ThreadPullRequestReactor.BACKFILL_ATTEMPTS,
);
expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("matches Azure SSH projects to HTTPS PRs with the provider repository selector", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeHarness({
threads: [thread("azure")],
project: {
...project,
repositoryIdentity: {
canonicalKey: "ssh.dev.azure.com/v3/org/project/repository",
displayName: "v3/org/project/repository",
name: "repository",
provider: "azure-devops",
rootPath: project.workspaceRoot,
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "[email protected]:v3/org/project/repository",
},
},
},
branchPullRequest: () =>
Effect.succeed({
...branchPullRequest(),
repositoryKey: "dev.azure.com/org/project/_git/repository",
url: "https://dev.azure.com/org/project/_git/repository/pullrequest/42",
}),
});
yield* Effect.gen(function* () {
yield* fixture.start();
expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual({
projectId: PROJECT_ID,
repository: "repository",
number: 42,
url: "https://dev.azure.com/org/project/_git/repository/pullrequest/42",
});
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect.each(["primary", "branch"] as const)(
"rejects the group's links if the %s remote changes during a summary read",
(changedRemote) =>
Effect.scoped(
Effect.gen(function* () {
const identity = yield* Ref.make(project.repositoryIdentity);
const detected = yield* Ref.make(branchPullRequest());
const fixture = yield* makeHarness({
threads: [thread("manual", { linkedPullRequest: reference(1) }), thread("automatic")],
branchPullRequest: () => Ref.get(detected),
resolveRepositoryIdentity: (_cwd, options) =>
options?.refresh ? Ref.get(identity) : Effect.succeed(project.repositoryIdentity),
summary: (input) =>
(changedRemote === "primary"
? Ref.set(identity, {
...project.repositoryIdentity,
canonicalKey: "github.com/other/repository",
displayName: "other/repository",
})
: Ref.set(detected, {
...branchPullRequest(99),
repositoryKey: "github.com/other/repository",
url: "https://github.com/other/repository/pull/99",
})
).pipe(Effect.as(summary(input, "merged"))),
});
yield* Effect.gen(function* () {
yield* fixture.start();
expect(yield* Ref.get(fixture.commands)).toEqual([]);
expect((yield* Ref.get(fixture.snapshots)).threads[0]?.linkedPullRequest).toEqual(
reference(1),
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
});
@@ -0,0 +1,371 @@
import {
CommandId,
type OrchestrationEvent,
type OrchestrationProjectShell,
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 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 PullRequestService from "../pullRequest/PullRequestService.ts";
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
import { forkParked } from "../serverActivation.ts";
import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
export class ThreadPullRequestReactor extends Context.Service<
ThreadPullRequestReactor,
{
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
readonly drain: Effect.Effect<void>;
}
>()("t3/orchestration/ThreadPullRequestReactor") {}
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
);
}
/** Startup lookups per settled thread before discovery gives up on it. */
export const BACKFILL_ATTEMPTS = 5;
interface RefreshRequest {
readonly threadId: ThreadId | null;
readonly refresh: boolean;
readonly backfill?: boolean;
}
function canonicalRepositoryKey(key: string): string {
return key
.replace(
/^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
"dev.azure.com/$1/$2/_git/$3",
)
.replace(
/^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
"dev.azure.com/$1/$2/_git/$3",
);
}
export function pullRequestMatchesProject(
pullRequest: GitManager.GitBranchPullRequest,
project: OrchestrationProjectShell,
): boolean {
return (
pullRequest.repositoryKey !== null &&
project.repositoryIdentity != null &&
canonicalRepositoryKey(pullRequest.repositoryKey) ===
canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
);
}
export const make = Effect.gen(function* () {
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
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;
// Settled threads get one link discovery at startup. Failed lookups retry on
// the periodic pass a few times, then stop until the thread changes or the
// server restarts, so a missing or logged-out CLI cannot loop forever.
const pendingBackfill = new Map<ThreadId, number>();
const finishBackfill = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => {
for (const thread of threads) pendingBackfill.delete(thread.id);
};
const failBackfill = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => {
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);
}
};
const synchronize = Effect.fn("ThreadPullRequestReactor.synchronize")(function* (
request: RefreshRequest,
) {
const snapshot = yield* snapshots.getShellSnapshot();
const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
if (request.backfill) {
for (const thread of snapshot.threads) {
if (thread.settledOverride === "settled" && thread.branchPullRequest == null) {
pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
}
}
}
const threadIds = new Set(snapshot.threads.map((thread) => thread.id));
for (const threadId of pendingBackfill.keys()) {
if (!threadIds.has(threadId)) pendingBackfill.delete(threadId);
}
const threads = snapshot.threads.filter(
(thread) =>
thread.archivedAt === null &&
(request.threadId === null || thread.id === request.threadId) &&
(thread.settledOverride !== "settled" ||
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 repository = PullRequestService.repositoryIdentityOf(project);
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 },
);
// A worktree can have different remotes, and the project identity
// can lag a remote edit. Do not attach its PR to the wrong repository.
if (detected !== null && !pullRequestMatchesProject(detected, project)) {
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;
// Shared checkouts often return to the default branch after
// a merge. Keep that thread's terminal PR across the change.
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.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.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(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) {
// Summary reads can outlast a remote edit. Recheck the branch and
// the project's primary remote before saving the group's links.
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* () {
const uuid = yield* crypto.randomUUIDv4;
yield* engine.dispatch({
type: "thread.pull-request.sync",
commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
threadId: thread.id,
projectId: project.id,
snapshotSequence: snapshot.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(
// The thread changed since the lookup. Its own events requeue it.
Effect.catchTags({
OrchestrationCommandInvariantError: () =>
Effect.sync(() => finishBackfill([thread])),
}),
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.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(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)))),
),
),
{ concurrency: 8, discard: true },
);
});
const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
synchronize(request).pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(cause)
: Effect.logWarning("thread pull request refresh failed", {
cause: Cause.pretty(cause),
}),
),
),
);
const processEvent = (event: OrchestrationEvent) => {
switch (event.type) {
case "thread.created":
case "thread.unarchived":
return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
case "thread.meta-updated":
if (
event.payload.branchPullRequest === undefined &&
(event.payload.branch !== undefined ||
event.payload.worktreePath !== undefined ||
event.payload.linkedPullRequest !== undefined)
) {
return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
}
break;
case "thread.session-set":
if (
event.payload.session.status !== "running" &&
event.payload.session.status !== "starting"
) {
return worker.enqueue({ threadId: event.payload.threadId, refresh: true });
}
break;
case "thread.turn-diff-completed":
case "thread.unsettled":
return worker.enqueue({ threadId: event.payload.threadId, refresh: true });
case "project.meta-updated":
if (event.payload.workspaceRoot !== undefined) {
return worker.enqueue({ threadId: null, refresh: false });
}
break;
}
return Effect.void;
};
const start = Effect.fn("ThreadPullRequestReactor.start")(function* () {
const events = yield* engine.subscribeDomainEvents;
yield* forkParked(Stream.runForEach(events, processEvent));
// Run without client demand. Saved branch lookups share GitManager's
// provider cache and retry backoff with status and automatic settlement.
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 ThreadPullRequestReactor["Service"];
});
export const layer = Layer.effect(ThreadPullRequestReactor, make);
@@ -25,7 +25,7 @@ import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { GitManager } from "../git/GitManager.ts";
import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";
import {
PullRequestService,
type PullRequestMergeEvent,
@@ -132,6 +132,24 @@ function makePullRequestSummary(input: {
};
}
function makeBranchPullRequest(
state: GitBranchPullRequest["state"],
updatedAt: string | null = NOW,
): GitBranchPullRequest {
return {
number: 42,
title: "Branch pull request",
url: "https://example.test/owner/repository/pull/42",
baseRef: "main",
headRef: "saved-feature",
repositoryKey: "example.test/owner/repository",
state,
updatedAt,
closedAt: state === "closed" ? updatedAt : null,
mergedAt: state === "merged" ? updatedAt : null,
};
}
interface HarnessOptions {
readonly snapshot: OrchestrationShellSnapshot;
readonly settings?: ServerSettings;
@@ -173,9 +191,9 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
return next;
});
const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input) =>
const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input, readOptions) =>
Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),
Effect.andThen(options.branchPullRequest?.(input, readOptions) ?? Effect.succeed(null)),
);
const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
Effect.gen(function* () {
@@ -281,6 +299,83 @@ const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
});
describe("ThreadSettlementReactor", () => {
it.effect("uses saved PRs without settling resumed threads or branches with newer PRs", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const previous = {
projectId: PROJECT_ID,
repository: "owner/repository",
number: 1,
url: "https://example.test/owner/repository/pull/1",
};
const project = {
...makeProject(),
repositoryIdentity: {
canonicalKey: "example.test/owner/repository",
rootPath: "/workspace/project",
displayName: "owner/repository",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "https://example.test/owner/repository.git",
},
},
};
const fixture = yield* makeHarness({
snapshot: makeSnapshot(
[
makeThread("retained-terminal", { branch: "main", branchPullRequest: previous }),
makeThread("reused-manual", { branch: "reused", linkedPullRequest: previous }),
makeThread("reused-detected", { branch: "reused", branchPullRequest: previous }),
makeThread("foreign-branch-pr", { branch: "foreign", linkedPullRequest: previous }),
makeThread("resumed-manual", {
branch: "main",
linkedPullRequest: previous,
latestUserMessageAt: "2026-08-28T00:00:00.000Z",
}),
makeThread("resumed-detected", {
branch: "main",
branchPullRequest: previous,
latestUserMessageAt: "2026-08-28T00:00:00.000Z",
}),
],
[project],
),
settings: {
...DEFAULT_SERVER_SETTINGS,
sidebarAutoSettleAfterDays: null,
sidebarAutoSettleOnMerge: true,
},
branchPullRequest: ({ branch }, options) =>
Effect.succeed(
branch === "reused"
? makeBranchPullRequest(options?.refresh ? "open" : "merged")
: branch === "foreign"
? {
...makeBranchPullRequest("open"),
repositoryKey: "example.test/another/repository",
}
: null,
),
pullRequestSummary: (input) =>
Effect.succeed({
...makePullRequestSummary({ ...input, state: "merged" }),
mergedAt: "2026-08-27T00:00:00.000Z",
}),
});
yield* Effect.gen(function* () {
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
assert.deepStrictEqual(
new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
new Set([ThreadId.make("retained-terminal"), ThreadId.make("foreign-branch-pr")]),
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("starts without clients and skips protected threads before pull request lookup", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -375,9 +470,7 @@ describe("ThreadSettlementReactor", () => {
}),
]),
branchPullRequest: () =>
Ref.get(pullRequest).pipe(
Effect.map((state) => ({ state, updatedAt: NOW, closedAt: NOW, mergedAt: NOW })),
),
Ref.get(pullRequest).pipe(Effect.map((state) => makeBranchPullRequest(state))),
});
yield* Effect.gen(function* () {
@@ -430,10 +523,10 @@ describe("ThreadSettlementReactor", () => {
Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
Effect.flatMap((count) =>
count === 1
? Effect.succeed({ state: "open" as const, updatedAt: NOW })
? Effect.succeed(makeBranchPullRequest("open"))
: Deferred.succeed(periodicLookupStarted, undefined).pipe(
Effect.andThen(Deferred.await(releasePeriodicLookup)),
Effect.as({ state: "open" as const, updatedAt: NOW }),
Effect.as(makeBranchPullRequest("open")),
),
),
),
@@ -477,12 +570,7 @@ describe("ThreadSettlementReactor", () => {
]),
branchPullRequest: () =>
Ref.get(state).pipe(
Effect.map((pullRequestState) => ({
state: pullRequestState,
updatedAt: NOW,
closedAt: NOW,
mergedAt: NOW,
})),
Effect.map((pullRequestState) => makeBranchPullRequest(pullRequestState)),
),
onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
});
@@ -618,12 +706,7 @@ describe("ThreadSettlementReactor", () => {
: Effect.void,
),
Effect.andThen(Ref.get(state)),
Effect.map((pullRequestState) => ({
state: pullRequestState,
updatedAt: NOW,
closedAt: NOW,
mergedAt: NOW,
})),
Effect.map((pullRequestState) => makeBranchPullRequest(pullRequestState)),
),
});
@@ -896,8 +979,7 @@ describe("ThreadSettlementReactor", () => {
makeProject(LINKED_PROJECT_ID, "/workspace/linked-root"),
],
),
branchPullRequest: () =>
Effect.succeed({ state: "closed", updatedAt: NOW, closedAt: NOW }),
branchPullRequest: () => Effect.succeed(makeBranchPullRequest("closed")),
pullRequestSummary: (input) =>
Effect.succeed(makePullRequestSummary({ ...input, state: "merged" })),
});
@@ -17,6 +17,7 @@ import * as ServerSettings from "../serverSettings.ts";
import { forkParked } from "../serverActivation.ts";
import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
import { pullRequestMatchesProject } from "./ThreadPullRequestReactor.ts";
import {
isAutoSettlementCandidate,
resolveAutoSettlementAt,
@@ -46,10 +47,8 @@ export const make = Effect.gen(function* () {
const snapshot = yield* snapshots.getShellSnapshot();
const now = DateTime.formatIso(yield* DateTime.now);
const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
// A merge event re-sweeps every candidate, not just the threads linked to
// the merged pull request: most threads carry no link and settle from
// their branch lookup, which would otherwise wait for the next minute's
// sweep on a possibly stale cached answer.
// A merge rechecks all candidates, including branches that discovery has
// not linked yet. Those lookups can still have cached the PR as open.
const candidates = snapshot.threads.filter((thread) => isAutoSettlementCandidate(thread, now));
// Return the thread when it still needs a pull request decision. A rejected
@@ -101,14 +100,14 @@ export const make = Effect.gen(function* () {
},
)).filter((thread) => thread !== null);
// Use the same cwd as the sidebar so both paths share GitManager's PR cache.
// Use the same cwd as PR discovery so both paths share GitManager's cache.
const lookupCwdByThreadId = new Map<string, string>();
yield* Effect.forEach(
lookupCandidates,
(thread) =>
Effect.gen(function* () {
const project = projects.get(thread.projectId);
if (project === undefined || thread.linkedPullRequest != null) return;
if (project === undefined || thread.branch === null) return;
const worktreeExists =
thread.worktreePath !== null &&
(yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
@@ -122,12 +121,8 @@ export const make = Effect.gen(function* () {
{ concurrency: 8, discard: true },
);
if (mergedPullRequest !== null) {
// The merge just confirmed a terminal state the lookup caches can still
// call open (branch answers live two minutes, the sweep runs every
// minute). Drop the swept checkouts' cached answers so the merge settles
// its branch threads now instead of on a later sweep. Threads linked to
// the merged pull request settle from the event itself below and need no
// lookup, so they are absent from this map by construction.
// The merge confirmed a state the branch cache can still call open.
// Recheck those branches now instead of waiting for cache expiry.
const cwds = [...new Set(lookupCwdByThreadId.values())];
yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
concurrency: 8,
@@ -135,12 +130,15 @@ export const make = Effect.gen(function* () {
});
}
const lookupKey = (thread: (typeof candidates)[number]) => {
if (thread.linkedPullRequest != null) {
const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
if (reference != null) {
return JSON.stringify([
"linked",
thread.linkedPullRequest.projectId,
thread.linkedPullRequest.repository,
thread.linkedPullRequest.number,
reference.projectId,
reference.repository,
reference.number,
lookupCwdByThreadId.get(thread.id),
thread.branch,
]);
}
if (thread.branch === null) return JSON.stringify(["none", thread.id]);
@@ -154,35 +152,47 @@ export const make = Effect.gen(function* () {
const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (
thread: (typeof candidates)[number],
) {
if (thread.linkedPullRequest != null) {
// The event carries the merged state, so only the threads linked to
// that exact pull request settle from it. Every other linked thread
// falls through to a fresh summary lookup below: the merge sweep
// covers all candidates, and an unrelated merge must never settle
// them.
if (
const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
if (reference != null) {
const matchesMerge =
mergedPullRequest !== null &&
thread.linkedPullRequest.projectId === mergedPullRequest.projectId &&
thread.linkedPullRequest.repository.toLowerCase() ===
mergedPullRequest.repository.toLowerCase() &&
thread.linkedPullRequest.number === mergedPullRequest.number
) {
return {
state: "merged",
mergedAt: mergedPullRequest.mergedAt,
} satisfies SettlementPullRequest;
}
if (!projects.has(thread.linkedPullRequest.projectId)) {
reference.projectId === mergedPullRequest.projectId &&
reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
reference.number === mergedPullRequest.number;
if (!matchesMerge && !projects.has(reference.projectId)) {
return yield* Effect.die(new Error("linked pull request project not found"));
}
const summary = yield* pullRequests.summary(
{
projectId: thread.linkedPullRequest.projectId,
repository: thread.linkedPullRequest.repository,
number: thread.linkedPullRequest.number,
},
{ recoverTransientFailure: false },
);
const summary = matchesMerge
? ({
state: "merged",
closedAt: null,
mergedAt: mergedPullRequest.mergedAt,
} satisfies SettlementPullRequest)
: yield* pullRequests.summary(
{
projectId: reference.projectId,
repository: reference.repository,
number: reference.number,
},
{ recoverTransientFailure: false },
);
const cwd = lookupCwdByThreadId.get(thread.id);
if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
// A reused branch can already have a new open PR while discovery
// is replacing its old link. Do not let settlement win that race.
const current = yield* git.branchPullRequest(
{ cwd, branch: thread.branch },
{ refresh: true },
);
const project = projects.get(thread.projectId);
if (
current?.state === "open" &&
project !== undefined &&
pullRequestMatchesProject(current, project)
) {
return current;
}
}
return {
state: summary.state,
closedAt: summary.closedAt ?? null,
+59
View File
@@ -1,6 +1,7 @@
import {
EventId,
MessageId,
ThreadLinkedPullRequest,
UserInputRequestedPayload,
isImportedAgentSessionMessageId,
type OrchestrationCommand,
@@ -38,6 +39,7 @@ import { threadHasQueuedTurnStart } from "./ThreadSettlementPolicy.ts";
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const decodeUserInputRequestedPayload = Schema.decodeUnknownOption(UserInputRequestedPayload);
const threadPullRequestLinksEqual = Schema.toEquivalence(Schema.NullOr(ThreadLinkedPullRequest));
/**
* Blocked-on-you work derived from the thread's retained activities: an
@@ -836,6 +838,63 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.pull-request.sync": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
if (thread.deletedAt !== null) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} was deleted before pull request discovery`,
});
}
if (
thread.projectId !== command.projectId ||
thread.branch !== command.expected.branch ||
thread.worktreePath !== command.expected.worktreePath ||
!threadPullRequestLinksEqual(
thread.linkedPullRequest ?? null,
command.expected.linkedPullRequest,
) ||
!threadPullRequestLinksEqual(
thread.branchPullRequest ?? null,
command.expected.branchPullRequest,
)
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} changed before pull request discovery`,
});
}
const project = yield* requireProject({ readModel, command, projectId: command.projectId });
if (project.deletedAt !== null || project.workspaceRoot !== command.expected.workspaceRoot) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `project ${command.projectId} changed before pull request discovery`,
});
}
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.meta-updated",
payload: {
threadId: command.threadId,
branchPullRequest: command.branchPullRequest,
...(command.linkedPullRequest !== undefined
? { linkedPullRequest: command.linkedPullRequest }
: {}),
updatedAt: thread.updatedAt,
},
};
}
case "thread.title.regeneration.complete": {
const thread = yield* requireThread({
readModel,
@@ -86,6 +86,7 @@ describe("orchestration projector", () => {
interactionMode: "default",
branch: null,
worktreePath: null,
branchPullRequest: null,
latestTurn: null,
createdAt: now,
updatedAt: now,
@@ -105,6 +106,67 @@ describe("orchestration projector", () => {
]);
});
effectIt.effect("sets and clears branch pull requests without changing manual links", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const eventFields = {
aggregateKind: "thread" as const,
aggregateId: "thread-1",
occurredAt: now,
commandId: null,
};
let model = yield* projectEvent(
createEmptyReadModel(now),
makeEvent({
...eventFields,
sequence: 1,
type: "thread.created",
payload: {
threadId: "thread-1",
projectId: "project-1",
title: "Pull request thread",
modelSelection: { provider: "codex", model: "gpt-5-codex" },
runtimeMode: "full-access",
branch: "feature",
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
const linkedPullRequest = {
projectId: "project-1",
repository: "pingdotgg/t3code",
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
};
const branchPullRequest = {
...linkedPullRequest,
number: 43,
url: "https://github.com/pingdotgg/t3code/pull/43",
};
const updates = [
{ payload: { linkedPullRequest, branchPullRequest }, expected: branchPullRequest },
{ payload: { title: "Renamed thread" }, expected: branchPullRequest },
{ payload: { branchPullRequest: null }, expected: null },
];
for (const [index, update] of updates.entries()) {
model = yield* projectEvent(
model,
makeEvent({
...eventFields,
sequence: index + 2,
type: "thread.meta-updated",
payload: { threadId: "thread-1", updatedAt: now, ...update.payload },
}),
);
expect(model.threads[0]?.branchPullRequest).toEqual(update.expected);
expect(model.threads[0]?.linkedPullRequest).toEqual(linkedPullRequest);
}
}),
);
it("fails when event payload cannot be decoded by runtime schema", async () => {
const now = "2026-01-01T00:00:00.000Z";
const model = createEmptyReadModel(now);
@@ -336,6 +336,7 @@ export function projectEvent(
interactionMode: payload.interactionMode,
branch: payload.branch,
worktreePath: payload.worktreePath,
branchPullRequest: null,
latestTurn: null,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
@@ -510,6 +511,9 @@ export function projectEvent(
...(payload.linkedPullRequest !== undefined
? { linkedPullRequest: payload.linkedPullRequest }
: {}),
...(payload.branchPullRequest !== undefined
? { branchPullRequest: payload.branchPullRequest }
: {}),
updatedAt: payload.updatedAt,
}),
})),