feat(pull-requests): link multiple pull requests to threads (#10839)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-09 15:50:58 -07:00
1 parent 383cc40f4d
commit afb84898be
172 files changed
+12063 -914

No files matched your search

+2
View File
@@ -68,6 +68,8 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.pullRequestsList]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsListStats]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsSummary]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsStack]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsLinkedThreads]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsDetail]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsThreadComments]: AuthOrchestrationReadScope,
@@ -169,6 +169,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
expect(second.capabilities.usagePriceOverrides).toBe(true);
expect(second.capabilities.threadActiveReorder).toBe(true);
expect(second.capabilities.threadTitleRegeneration).toBe(true);
expect(second.capabilities.threadPullRequests).toBe(true);
expect(second.capabilities.threadPullRequestLinking).toBe(true);
expect(second.capabilities.agentActivityPublishing).toBe(false);
}),
@@ -230,6 +230,7 @@ export const make = Effect.gen(function* () {
threadPinReorder: true,
threadActiveReorder: true,
threadTitleRegeneration: true,
threadPullRequests: true,
threadPullRequestLinking: true,
environmentIcon: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
@@ -0,0 +1,230 @@
import {
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
type GitRunStackedActionResult,
type OrchestrationCommand,
type OrchestrationProjectShell,
type OrchestrationThreadShell,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { OrchestrationCommandInvariantError } from "../orchestration/Errors.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import { createdPullRequestKey, linkCreatedPullRequest } from "./linkCreatedPullRequest.ts";
const PROJECT_ID = ProjectId.make("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const commandId = Effect.succeed(CommandId.make("server:pr-created-link:test"));
const project: OrchestrationProjectShell = {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/workspace/project",
defaultModelSelection: null,
scripts: [],
repositoryIdentity: {
canonicalKey: "github.acme.test/platform/api",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "[email protected]:Platform/API.git",
},
provider: "github",
displayName: "Platform/API",
owner: "Platform",
name: "API",
},
createdAt: "2026-08-01T00:00:00.000Z",
updatedAt: "2026-08-01T00:00:00.000Z",
};
const thread: OrchestrationThreadShell = {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: null,
createdAt: "2026-08-01T00:00:00.000Z",
updatedAt: "2026-08-20T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: "2026-08-20T00:00:00.000Z",
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
};
function prResult(pr: GitRunStackedActionResult["pr"]): Pick<GitRunStackedActionResult, "pr"> {
return { pr };
}
const makeDependencies = (
dispatch: OrchestrationEngineShape["dispatch"],
threadShell: OrchestrationThreadShell | null = thread,
) =>
Layer.mergeAll(
Layer.mock(ProjectionSnapshotQuery)({
getThreadShellById: () => Effect.succeed(Option.fromNullishOr(threadShell)),
getProjectShellById: () => Effect.succeed(Option.some(project)),
}),
Layer.mock(OrchestrationEngineService)({
readEvents: () => Stream.empty,
dispatch,
streamDomainEvents: Stream.empty,
latestSequence: Effect.succeed(0),
}),
);
const recordingDispatch = Effect.fn("recordingDispatch")(function* () {
const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Ref.update(commands, (recorded) => [...recorded, command]).pipe(Effect.as({ sequence: 1 }));
return { commands, dispatch };
});
describe("createdPullRequestKey", () => {
it("reads host and repository from the URL when it is recognisable", () => {
expect(
createdPullRequestKey(
prResult({
status: "created",
number: 12,
url: "https://github.com/Other/Fork/pull/12",
}),
project,
),
).toEqual({
host: "github.com",
repository: "other/fork",
number: 12,
url: "https://github.com/Other/Fork/pull/12",
});
});
it("falls back to the project's host and repository for an unreadable URL", () => {
expect(
createdPullRequestKey(
prResult({ status: "opened_existing", number: 3, url: "https://ghe.internal/x/3" }),
project,
),
).toEqual({
host: "github.acme.test",
repository: "platform/api",
number: 3,
url: "https://ghe.internal/x/3",
});
expect(
createdPullRequestKey(
prResult({ status: "created", number: 3, url: "https://ghe.internal/x/3" }),
undefined,
),
).toBeNull();
});
it("yields nothing when no pull request came out of the action", () => {
expect(
createdPullRequestKey(prResult({ status: "skipped_not_requested" }), project),
).toBeNull();
expect(
createdPullRequestKey(
prResult({ status: "created", url: "https://github.com/a/b/pull/1" }),
project,
),
).toBeNull();
expect(createdPullRequestKey(prResult({ status: "created", number: 1 }), project)).toBeNull();
});
});
describe("linkCreatedPullRequest", () => {
it.effect("links a created pull request to the thread with source created", () =>
Effect.gen(function* () {
const { commands, dispatch } = yield* recordingDispatch();
yield* linkCreatedPullRequest({
threadId: THREAD_ID,
result: prResult({
status: "created",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
}),
commandId,
}).pipe(Effect.provide(makeDependencies(dispatch)));
expect(yield* Ref.get(commands)).toEqual([
{
type: "thread.pull-request.link",
commandId: "server:pr-created-link:test",
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
source: "created",
},
]);
}),
);
it.effect("dispatches nothing when the action produced no pull request", () =>
Effect.gen(function* () {
const { commands, dispatch } = yield* recordingDispatch();
const dependencies = makeDependencies(dispatch);
yield* linkCreatedPullRequest({
threadId: THREAD_ID,
result: prResult({ status: "skipped_not_requested" }),
commandId,
}).pipe(Effect.provide(dependencies));
yield* linkCreatedPullRequest({
threadId: THREAD_ID,
result: prResult({ status: "created", url: "https://github.com/t3tools/t3code/pull/42" }),
commandId,
}).pipe(Effect.provide(dependencies));
expect(yield* Ref.get(commands)).toEqual([]);
}),
);
it.effect("swallows an already-linked rejection and other dispatch failures", () =>
Effect.gen(function* () {
const rejecting: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: "already linked",
}),
);
const result = prResult({
status: "opened_existing",
number: 7,
url: "https://github.com/t3tools/t3code/pull/7",
});
yield* linkCreatedPullRequest({ threadId: THREAD_ID, result, commandId }).pipe(
Effect.provide(makeDependencies(rejecting)),
);
yield* linkCreatedPullRequest({ threadId: THREAD_ID, result, commandId }).pipe(
Effect.provide(makeDependencies(() => Effect.die(new Error("engine down")))),
);
// A thread that vanished between the action and the link is not an error either.
yield* linkCreatedPullRequest({ threadId: THREAD_ID, result, commandId }).pipe(
Effect.provide(makeDependencies(() => Effect.die(new Error("unreachable")), null)),
);
}),
);
});
@@ -0,0 +1,98 @@
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
import {
type CommandId,
pullRequestHostOf,
type GitRunStackedActionResult,
type OrchestrationProjectShell,
type SourceControlProviderKind,
type ThreadId,
} from "@t3tools/contracts";
import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
export interface CreatedPullRequestKey {
readonly host: string;
readonly repository: string;
readonly number: number;
readonly url: string;
}
/**
* The identity a stacked action's pull request should be linked under, or
* null when the action did not leave one behind. Reading the host and
* repository from the URL keeps the link host-level even when the checkout's
* remote differs from where the PR was opened (a fork, say); the project is
* only consulted when the URL is one this cannot read.
*/
export function createdPullRequestKey(
result: Pick<GitRunStackedActionResult, "pr">,
project: OrchestrationProjectShell | undefined,
): CreatedPullRequestKey | null {
const { status, number, url } = result.pr;
if ((status !== "created" && status !== "opened_existing") || number === undefined || !url) {
return null;
}
const parsed = parseChangeRequestUrl(url);
if (parsed !== null) return { ...parsed, url };
const identity = project?.repositoryIdentity;
const kind = identity?.provider as SourceControlProviderKind | undefined;
const repository = sourceControlRepositorySelector(identity);
if (!identity || kind === undefined || repository === null) return null;
return {
host: pullRequestHostOf(identity, kind),
repository: repository.toLowerCase(),
number,
url,
};
}
/**
* Links the pull request a `create_pr`-shaped action produced to the thread it
* ran beside. Never fails: the git action already succeeded and its result is
* on its way to the client, so a link that cannot be made is logged and
* dropped. A duplicate link is the decider saying the thread already knew.
*/
export const linkCreatedPullRequest = <E>(input: {
readonly threadId: ThreadId;
readonly result: Pick<GitRunStackedActionResult, "pr">;
readonly commandId: Effect.Effect<CommandId, E>;
}): Effect.Effect<
void,
never,
OrchestrationEngine.OrchestrationEngineService | ProjectionSnapshotQuery.ProjectionSnapshotQuery
> =>
Effect.gen(function* () {
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const thread = yield* snapshots.getThreadShellById(input.threadId);
if (Option.isNone(thread)) return;
const project = Option.getOrUndefined(
yield* snapshots.getProjectShellById(thread.value.projectId),
);
const key = createdPullRequestKey(input.result, project);
if (key === null) return;
const commandId = yield* input.commandId;
yield* engine
.dispatch({
type: "thread.pull-request.link",
commandId,
threadId: input.threadId,
...key,
source: "created",
})
.pipe(Effect.catchTags({ OrchestrationCommandInvariantError: () => Effect.void }));
}).pipe(
Effect.withSpan("linkCreatedPullRequest"),
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(cause as Cause.Cause<never>)
: Effect.logWarning("failed to link created pull request to thread", {
threadId: input.threadId,
}),
),
);
+47
View File
@@ -6,12 +6,15 @@ 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 Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { McpProtocol, McpSchema, McpServer } from "effect/unstable/ai";
import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as ServerConfig from "../config.ts";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
@@ -48,6 +51,18 @@ const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-server-test-" })),
Layer.provideMerge(NodeServices.layer),
);
const PullRequestsTestLayer = McpHttpServer.PullRequestsToolkitRegistrationLive.pipe(
Layer.provideMerge(McpServer.McpServer.layer),
Layer.provide(
Layer.mergeAll(
Layer.mock(ProjectionSnapshotQuery)({
getThreadShellById: () => Effect.succeed(Option.none()),
}),
Layer.mock(OrchestrationEngineService)({}),
NodeServices.layer,
),
),
);
const snapshotResult = {
url: "http://example.test/",
@@ -345,6 +360,38 @@ it.effect("reports a tagged error when the screenshot cannot be saved", () =>
).pipe(Effect.provide(TestLayer)),
);
it.effect(
"registers the pull request toolkit and surfaces a missing capability as a tool error",
() =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const names = server.tools.map(({ tool }) => tool.name);
expect(names).toEqual(
expect.arrayContaining([
"link_pull_request",
"unlink_pull_request",
"list_thread_pull_requests",
]),
);
const linkTool = server.tools.find(({ tool }) => tool.name === "link_pull_request");
expect(linkTool?.tool.annotations?.idempotentHint).toBe(true);
expect(linkTool?.tool.annotations?.openWorldHint).toBe(false);
expect(linkTool?.tool.description).toContain("Register every pull request you open");
const denied = yield* server
.callTool({ name: "list_thread_pull_requests", arguments: {} })
.pipe(
// A preview-only credential: the token predates the toolkit or was minted elsewhere.
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(denied.isError).toBe(true);
expect(denied.content).toEqual([
{ type: "text", text: "MCP credential does not grant the pull-requests capability." },
]);
}).pipe(Effect.provide(PullRequestsTestLayer)),
);
it.effect("keeps the snapshot text under the agent's output ceiling", () =>
Effect.scoped(
Effect.gen(function* () {
+10 -1
View File
@@ -28,6 +28,8 @@ import {
PreviewSnapshotToolkit,
PreviewStandardToolkit,
} from "./toolkits/preview/tools.ts";
import { PullRequestsToolkitHandlersLive } from "./toolkits/pullRequests/handlers.ts";
import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts";
const unauthorized = HttpServerResponse.jsonUnsafe(
{
@@ -437,6 +439,10 @@ export const PreviewToolkitRegistrationLive = Layer.mergeAll(
PreviewSnapshotRegistrationLive,
);
export const PullRequestsToolkitRegistrationLive = McpServer.toolkit(PullRequestsToolkit).pipe(
Layer.provide(PullRequestsToolkitHandlersLive),
);
const McpTransportLive = McpServer.layerHttp({
name: "T3 Code",
version: packageJson.version,
@@ -444,4 +450,7 @@ const McpTransportLive = McpServer.layerHttp({
protocols: [McpProtocol.v2025_06_18],
}).pipe(Layer.provide(McpAuthMiddlewareLive));
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
export const layer = Layer.mergeAll(
PreviewToolkitRegistrationLive,
PullRequestsToolkitRegistrationLive,
).pipe(Layer.provideMerge(McpTransportLive));
@@ -1,6 +1,7 @@
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
McpCapabilityUnavailableError,
PreviewAutomationUnavailableError,
ProviderInstanceId,
ThreadId,
@@ -36,3 +37,29 @@ it.effect("reports the scoped credential context when preview capability is unav
expect(error.message).toBe("MCP credential does not grant the preview capability.");
});
});
it.effect("reports other missing capabilities with the neutral error", () => {
const invocation: McpInvocationContext.McpInvocationScope = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
providerSessionId: "provider-session-1",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(["preview"]),
issuedAt: 1,
};
return Effect.gen(function* () {
const error = yield* McpInvocationContext.requireMcpCapability("pull-requests").pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.flip,
);
expect(error).toBeInstanceOf(McpCapabilityUnavailableError);
expect(error).toMatchObject({ capability: "pull-requests", threadId: invocation.threadId });
const scope = yield* McpInvocationContext.requireMcpCapability("preview").pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
);
expect(scope).toBe(invocation);
});
});
+30 -15
View File
@@ -1,5 +1,6 @@
import {
type EnvironmentId,
McpCapabilityUnavailableError,
PreviewAutomationUnavailableError,
type ProviderInstanceId,
type ThreadId,
@@ -7,7 +8,7 @@ import {
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
export type McpCapability = "preview";
export type McpCapability = "preview" | "pull-requests";
export interface McpInvocationScope {
readonly environmentId: EnvironmentId;
@@ -23,18 +24,32 @@ export class McpInvocationContext extends Context.Service<
McpInvocationScope
>()("t3/mcp/McpInvocationContext") {}
export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* (
/** The error a missing capability surfaces as; preview keeps its own so the broker can route it. */
export type McpCapabilityError<C extends McpCapability> = C extends "preview"
? PreviewAutomationUnavailableError
: McpCapabilityUnavailableError;
const missingCapability = (
invocation: McpInvocationScope,
capability: McpCapability,
) {
const invocation = yield* McpInvocationContext;
if (!invocation.capabilities.has(capability)) {
return yield* new PreviewAutomationUnavailableError({
capability,
environmentId: invocation.environmentId,
threadId: invocation.threadId,
providerSessionId: invocation.providerSessionId,
providerInstanceId: invocation.providerInstanceId,
});
}
return invocation;
});
): PreviewAutomationUnavailableError | McpCapabilityUnavailableError => {
const fields = {
environmentId: invocation.environmentId,
threadId: invocation.threadId,
providerSessionId: invocation.providerSessionId,
providerInstanceId: invocation.providerInstanceId,
};
return capability === "preview"
? new PreviewAutomationUnavailableError({ capability, ...fields })
: new McpCapabilityUnavailableError({ capability, ...fields });
};
export const requireMcpCapability = <const C extends McpCapability>(
capability: C,
): Effect.Effect<McpInvocationScope, McpCapabilityError<C>, McpInvocationContext> =>
Effect.flatMap(McpInvocationContext, (invocation) =>
invocation.capabilities.has(capability)
? Effect.succeed(invocation)
: // The conditional type narrows what the literal argument decided at runtime.
Effect.fail(missingCapability(invocation, capability) as McpCapabilityError<C>),
).pipe(Effect.withSpan("mcp.requireCapability"));
@@ -7,6 +7,8 @@ export interface McpProviderSessionConfig {
readonly providerInstanceId: ProviderInstanceId;
readonly endpoint: string;
readonly authorizationHeader: string;
/** Whether the credential grants the preview (browser) toolkit; the pull request toolkit always is. */
readonly preview: boolean;
}
const sessionsByThread = new Map<ThreadId, McpProviderSessionConfig>();
@@ -39,6 +39,7 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
const issued = yield* registry.issue({
threadId,
providerInstanceId: ProviderInstanceId.make("codex"),
preview: true,
});
expect(issued.config.endpoint).toBe("http://127.0.0.1:43123/mcp");
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
@@ -54,6 +55,29 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
}),
);
it.effect("always grants pull-requests and gates preview on the request", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry(() => 1_000);
const withPreview = yield* registry.issue({
threadId: ThreadId.make("thread-preview"),
providerInstanceId: ProviderInstanceId.make("codex"),
preview: true,
});
const withoutPreview = yield* registry.issue({
threadId: ThreadId.make("thread-no-preview"),
providerInstanceId: ProviderInstanceId.make("codex"),
preview: false,
});
const capabilitiesOf = (issued: typeof withPreview) =>
registry
.resolve(issued.config.authorizationHeader.replace(/^Bearer\s+/, ""))
.pipe(Effect.map((scope) => [...(scope?.capabilities ?? [])].sort()));
expect(yield* capabilitiesOf(withPreview)).toEqual(["preview", "pull-requests"]);
expect(yield* capabilitiesOf(withoutPreview)).toEqual(["pull-requests"]);
}),
);
it.effect("builds MCP endpoints from the bound server host", () =>
Effect.gen(function* () {
const cases = [
@@ -68,6 +92,7 @@ it.effect("builds MCP endpoints from the bound server host", () =>
const issued = yield* registry.issue({
threadId: ThreadId.make(`thread-${hostname}`),
providerInstanceId: ProviderInstanceId.make("codex"),
preview: true,
});
expect(issued.config.endpoint).toBe(expectedEndpoint);
}
@@ -81,6 +106,7 @@ it.effect("expires credentials once their session stops showing signs of life",
const issued = yield* registry.issue({
threadId: ThreadId.make("thread-2"),
providerInstanceId: ProviderInstanceId.make("claude"),
preview: true,
});
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
timestamp += 101;
@@ -96,6 +122,7 @@ it.effect("keeps a credential alive across turns that never touch an MCP tool",
const issued = yield* registry.issue({
threadId,
providerInstanceId: ProviderInstanceId.make("claude"),
preview: true,
});
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
@@ -117,6 +144,7 @@ it.effect("does not keep credentials of other threads alive", () =>
const issued = yield* registry.issue({
threadId: ThreadId.make("thread-4"),
providerInstanceId: ProviderInstanceId.make("codex"),
preview: true,
});
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
+10 -2
View File
@@ -14,6 +14,11 @@ import * as McpProviderSession from "./McpProviderSession.ts";
export interface McpCredentialRequest {
readonly threadId: ThreadId;
readonly providerInstanceId: ProviderInstanceId;
/**
* Whether the credential may drive the user's browser. The pull request
* toolkit is always granted: it only touches the thread's own links.
*/
readonly preview: boolean;
}
export interface McpIssuedCredential {
@@ -68,7 +73,7 @@ export interface McpSessionRegistryOptions {
*
* The bound matters because `/mcp` is mounted outside the environment auth
* stack and is reachable on whatever host the server binds to, so this token is
* the only thing guarding the preview toolkit on a remote-reachable server.
* the only thing guarding the `t3-code` toolkits on a remote-reachable server.
*/
const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000;
@@ -128,7 +133,9 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
threadId: ThreadId.make(request.threadId),
providerSessionId,
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
capabilities: new Set(["preview"]),
capabilities: new Set<McpInvocationContext.McpCapability>(
request.preview ? ["pull-requests", "preview"] : ["pull-requests"],
),
issuedAt,
};
yield* SynchronizedRef.update(state, ({ records }) => {
@@ -144,6 +151,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
providerInstanceId: scope.providerInstanceId,
endpoint,
authorizationHeader: `Bearer ${rawToken}`,
preview: request.preview,
},
};
},
@@ -0,0 +1,418 @@
import {
EnvironmentId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationCommand,
type OrchestrationProjectShell,
type OrchestrationThreadShell,
type ThreadPullRequestLink,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import type { Tool } from "effect/unstable/ai";
import { OrchestrationCommandInvariantError } from "../../../orchestration/Errors.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../../../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import { listThreadPullRequests, PullRequestsToolkitHandlersLive } from "./handlers.ts";
import { PullRequestLinkFailedError, PullRequestsToolkit } from "./tools.ts";
const PROJECT_ID = ProjectId.make("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const testCrypto = Crypto.make({
randomBytes: (size) => new Uint8Array(size).fill(7),
digest: (_algorithm, data) => Effect.succeed(data),
});
const invocation = (
capabilities: ReadonlyArray<McpInvocationContext.McpCapability>,
): McpInvocationContext.McpInvocationScope => ({
environmentId: EnvironmentId.make("environment-1"),
threadId: THREAD_ID,
providerSessionId: "provider-session-1",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(capabilities),
issuedAt: 1,
});
function makeProject(
repositoryIdentity: OrchestrationProjectShell["repositoryIdentity"] = {
canonicalKey: "github.com/t3tools/t3code",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "[email protected]:T3Tools/T3Code.git",
},
provider: "github",
displayName: "T3Tools/T3Code",
owner: "T3Tools",
name: "T3Code",
},
): OrchestrationProjectShell {
return {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/workspace/project",
defaultModelSelection: null,
scripts: [],
repositoryIdentity,
createdAt: "2026-08-01T00:00:00.000Z",
updatedAt: "2026-08-01T00:00:00.000Z",
};
}
function makeThread(pullRequests: ReadonlyArray<ThreadPullRequestLink>): OrchestrationThreadShell {
return {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests,
latestTurn: null,
createdAt: "2026-08-01T00:00:00.000Z",
updatedAt: "2026-08-20T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: "2026-08-20T00:00:00.000Z",
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
};
}
function makeLink(
number: number,
overrides: Partial<ThreadPullRequestLink> & {
readonly headBranch?: string;
readonly baseBranch?: string;
} = {},
): ThreadPullRequestLink {
const { headBranch, baseBranch, ...rest } = overrides;
return {
host: "github.com",
repository: "t3tools/t3code",
number,
url: `https://github.com/t3tools/t3code/pull/${number}`,
source: "manual",
linkedAt: "2026-08-10T00:00:00.000Z",
snapshot:
headBranch === undefined
? null
: {
state: "open",
title: `PR ${number}`,
headBranch,
baseBranch: baseBranch ?? "main",
isDraft: false,
updatedAt: null,
syncedAt: "2026-08-27T00:00:00.000Z",
},
stack: null,
...rest,
};
}
interface HarnessOptions {
readonly thread?: OrchestrationThreadShell | null;
readonly project?: OrchestrationProjectShell | null;
readonly reject?: (command: OrchestrationCommand) => OrchestrationCommandInvariantError | null;
}
const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* (
options: HarnessOptions = {},
) {
const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const thread = options.thread === undefined ? makeThread([]) : options.thread;
const project = options.project === undefined ? makeProject() : options.project;
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
const rejection = options.reject?.(command) ?? null;
if (rejection !== null) return yield* rejection;
yield* Ref.update(commands, (recorded) => [...recorded, command]);
return { sequence: 1 };
});
const dependencies = Layer.mergeAll(
Layer.mock(ProjectionSnapshotQuery)({
getThreadShellById: (threadId) =>
Effect.succeed(threadId === THREAD_ID ? Option.fromNullishOr(thread) : Option.none()),
getProjectShellById: () => Effect.succeed(Option.fromNullishOr(project)),
}),
Layer.mock(OrchestrationEngineService)({
readEvents: () => Stream.empty,
dispatch,
streamDomainEvents: Stream.empty,
latestSequence: Effect.succeed(0),
}),
Layer.succeed(Crypto.Crypto, testCrypto),
);
const toolkit = yield* PullRequestsToolkit.pipe(
Effect.provide(PullRequestsToolkitHandlersLive.pipe(Layer.provide(dependencies))),
);
const call = <Name extends keyof typeof PullRequestsToolkit.tools>(
name: Name,
params: Parameters<typeof toolkit.handle<Name>>[1],
capabilities: ReadonlyArray<McpInvocationContext.McpCapability> = ["pull-requests"],
) =>
toolkit.handle(name, params).pipe(
Stream.unwrap,
Stream.runCollect,
// Failure mode is "error", so a delivered result is always the success shape.
Effect.map(
(chunk) => chunk.at(-1)!.result as Tool.Success<(typeof PullRequestsToolkit.tools)[Name]>,
),
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities)),
Effect.provide(dependencies),
);
return { commands, call };
});
describe("pull request toolkit handlers", () => {
it.effect("refuses a credential without the pull-requests capability", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
const error = yield* harness
.call("list_thread_pull_requests", {}, ["preview"])
.pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "McpCapabilityUnavailableError",
capability: "pull-requests",
threadId: THREAD_ID,
});
expect(yield* Ref.get(harness.commands)).toEqual([]);
}),
);
it.effect("links by URL with source agent on the token's thread", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
const result = yield* harness.call("link_pull_request", {
url: "https://github.com/T3Tools/T3Code/pull/123/files",
});
expect(result).toEqual({
host: "github.com",
repository: "t3tools/t3code",
number: 123,
url: "https://github.com/T3Tools/T3Code/pull/123/files",
alreadyLinked: false,
});
expect(yield* Ref.get(harness.commands)).toMatchObject([
{
type: "thread.pull-request.link",
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 123,
source: "agent",
},
]);
}),
);
it.effect("links by repository and number, defaulting the host to the project's", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
const result = yield* harness.call("link_pull_request", {
repository: "T3Tools/Other",
number: 7,
});
expect(result).toEqual({
host: "github.com",
repository: "t3tools/other",
number: 7,
url: "https://github.com/t3tools/other/pull/7",
alreadyLinked: false,
});
}),
);
it.effect("builds the URL in the project host's own shape", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
project: makeProject({
canonicalKey: "gitlab.com/group/sub/project",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "[email protected]:group/sub/project.git",
},
provider: "gitlab",
displayName: "group/sub/project",
}),
});
const result = yield* harness.call("link_pull_request", {
repository: "group/sub/project",
number: 42,
});
expect(result.url).toBe("https://gitlab.com/group/sub/project/-/merge_requests/42");
expect(result.host).toBe("gitlab.com");
}),
);
it.effect("rejects a target that names neither a URL nor repository and number", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
const error = yield* harness
.call("link_pull_request", { repository: "x/y" })
.pipe(Effect.flip);
expect(error).toMatchObject({ _tag: "PullRequestTargetIncompleteError" });
const unknown = yield* harness
.call("link_pull_request", {
url: "https://github.com/t3tools/t3code/issues/1?token=private-value",
})
.pipe(Effect.flip);
expect(unknown).toMatchObject({ _tag: "PullRequestUrlInvalidError" });
expect(unknown.message).not.toContain("private-value");
expect(yield* Ref.get(harness.commands)).toEqual([]);
}),
);
it.effect("treats a duplicate link as alreadyLinked rather than an error", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
thread: makeThread([makeLink(123)]),
reject: (command) =>
command.type === "thread.pull-request.link"
? new OrchestrationCommandInvariantError({
commandType: command.type,
detail: "already linked",
})
: null,
});
const result = yield* harness.call("link_pull_request", {
url: "https://github.com/t3tools/t3code/pull/123",
});
expect(result.alreadyLinked).toBe(true);
}),
);
it.effect("unlinks a linked pull request and reports a missing one as wasLinked=false", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
thread: makeThread([makeLink(5)]),
reject: (command) =>
command.type === "thread.pull-request.unlink" && command.number !== 5
? new OrchestrationCommandInvariantError({
commandType: command.type,
detail: "not linked",
})
: null,
});
const linked = yield* harness.call("unlink_pull_request", {
repository: "t3tools/t3code",
number: 5,
});
expect(linked).toEqual({
host: "github.com",
repository: "t3tools/t3code",
number: 5,
wasLinked: true,
});
const missing = yield* harness.call("unlink_pull_request", {
url: "https://github.com/t3tools/t3code/pull/9",
});
expect(missing.wasLinked).toBe(false);
expect(yield* Ref.get(harness.commands)).toMatchObject([
{ type: "thread.pull-request.unlink", number: 5 },
]);
}),
);
it.effect("fails cleanly when the token's thread no longer exists", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ thread: null });
const error = yield* harness.call("list_thread_pull_requests", {}).pipe(Effect.flip);
expect(error).toMatchObject({ _tag: "PullRequestThreadNotFoundError", threadId: THREAD_ID });
}),
);
it.effect("lists visible links with host state and derived chain order", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
thread: makeThread([
makeLink(3, { headBranch: "feat-c", baseBranch: "feat-b", source: "agent" }),
makeLink(1, { headBranch: "feat-a", baseBranch: "main", source: "created" }),
makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a", source: "agent" }),
makeLink(9, { source: "stack-dismissed" }),
makeLink(10),
]),
});
const result = yield* harness.call("list_thread_pull_requests", {});
expect(result.pullRequests.map((entry) => entry.number)).toEqual([3, 1, 2, 10]);
expect(result.pullRequests[0]).toEqual({
host: "github.com",
repository: "t3tools/t3code",
number: 3,
url: "https://github.com/t3tools/t3code/pull/3",
source: "agent",
state: "open",
title: "PR 3",
headBranch: "feat-c",
baseBranch: "feat-b",
isDraft: false,
stack: { kind: "derived", position: 3, size: 3 },
});
expect(result.pullRequests[3]).toMatchObject({
number: 10,
state: null,
title: null,
headBranch: null,
stack: null,
});
expect(result.chains).toEqual([
{ kind: "derived", numbers: [1, 2, 3] },
{ kind: "derived", numbers: [10] },
]);
}),
);
});
describe("listThreadPullRequests", () => {
it("reports a native stack position for each member", () => {
const stack = {
kind: "native" as const,
id: "stack-1",
number: 1,
url: "https://github.com/t3tools/t3code/stack/1",
base: "main",
layers: [
{ number: 1, headBranch: "a", state: "open" as const },
{ number: 2, headBranch: "b", state: "open" as const },
],
};
const result = listThreadPullRequests({
pullRequests: [
makeLink(2, { stack, source: "stack" }),
makeLink(1, { stack, source: "created" }),
],
});
expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
[2, { kind: "native", position: 2, size: 2 }],
[1, { kind: "native", position: 1, size: 2 }],
]);
expect(result.chains).toEqual([{ kind: "native", numbers: [1, 2] }]);
});
});
it("keeps failure diagnostics as the cause rather than exposing them in the tool message", () => {
const cause = new Error("database internals");
const failure = new PullRequestLinkFailedError({ cause });
expect(failure.message).toBe("Could not link the pull request.");
expect(failure.cause).toBe(cause);
});
@@ -0,0 +1,243 @@
import {
CommandId,
pullRequestHostOf,
type OrchestrationProjectShell,
type OrchestrationThreadShell,
type SourceControlProviderKind,
type ThreadId,
type ThreadPullRequestLink,
} from "@t3tools/contracts";
import { changeRequestUrlFor, parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
import {
resolveThreadPullRequestChains,
threadPullRequestKeyOf,
visibleThreadPullRequests,
} from "@t3tools/shared/threadPullRequests";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as OrchestrationEngine from "../../../orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import {
type ListThreadPullRequestsResult,
PullRequestLinkFailedError,
PullRequestUrlInvalidError,
PullRequestTargetIncompleteError,
PullRequestHostRequiredError,
PullRequestUnlinkFailedError,
PullRequestListFailedError,
type PullRequestTargetInput,
PullRequestThreadNotFoundError,
PullRequestsToolkit,
type ThreadPullRequestEntry,
} from "./tools.ts";
interface ResolvedTarget {
readonly host: string;
readonly repository: string;
readonly number: number;
readonly url: string;
}
/** The project's host and provider supply defaults for a repository-and-number input. */
function projectHostAndProvider(project: OrchestrationProjectShell | undefined): {
readonly host: string | null;
readonly kind: SourceControlProviderKind | null;
} {
const identity = project?.repositoryIdentity;
const kind = (identity?.provider as SourceControlProviderKind | undefined) ?? null;
if (!identity || kind === null) return { host: null, kind: null };
return {
host: pullRequestHostOf(identity, kind),
kind,
};
}
/**
* Turns whichever shape the agent passed into one host-level identity. A URL
* wins outright; otherwise the repository and number are completed with the
* thread's project host, which is where an agent working in that checkout
* almost always opened the pull request.
*/
const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
input: PullRequestTargetInput,
project: OrchestrationProjectShell | undefined,
) {
if (input.url !== undefined) {
const parsed = parseChangeRequestUrl(input.url);
if (parsed === null) {
return yield* new PullRequestUrlInvalidError({});
}
return { ...parsed, url: input.url } satisfies ResolvedTarget;
}
if (input.repository === undefined || input.number === undefined) {
return yield* new PullRequestTargetIncompleteError({});
}
const projectHost = projectHostAndProvider(project);
const host = (input.host ?? projectHost.host)?.toLowerCase();
if (host === undefined) {
return yield* new PullRequestHostRequiredError({});
}
const repository = input.repository.toLowerCase();
const url =
changeRequestUrlFor(
// The project's kind only describes its own host; another host gets no URL guess.
host === projectHost.host ? projectHost.kind : null,
host,
repository,
input.number,
) ?? `https://${host}/${repository}/pull/${input.number}`;
return { host, repository, number: input.number, url } satisfies ResolvedTarget;
});
function entryOf(
link: ThreadPullRequestLink,
chains: ReturnType<typeof resolveThreadPullRequestChains>,
): ThreadPullRequestEntry {
const key = threadPullRequestKeyOf(link);
let stack: ThreadPullRequestEntry["stack"] = null;
for (const chain of chains) {
if (chain.layers.length < 2) continue;
const index = chain.layers.findIndex((layer) => threadPullRequestKeyOf(layer) === key);
if (index !== -1) {
stack = { kind: chain.kind, position: index + 1, size: chain.layers.length };
break;
}
}
return {
host: link.host,
repository: link.repository,
number: link.number,
url: link.url,
source: link.source,
state: link.snapshot?.state ?? null,
title: link.snapshot?.title ?? null,
headBranch: link.snapshot?.headBranch ?? null,
baseBranch: link.snapshot?.baseBranch ?? null,
isDraft: link.snapshot?.isDraft ?? null,
stack,
};
}
/** What the tools report from a thread shell; exported so the shape is testable without a layer. */
export function listThreadPullRequests(
thread: Pick<OrchestrationThreadShell, "pullRequests">,
): ListThreadPullRequestsResult {
const chains = resolveThreadPullRequestChains(thread.pullRequests);
return {
pullRequests: visibleThreadPullRequests(thread.pullRequests).map((link) =>
entryOf(link, chains),
),
chains: chains.map((chain) => ({
kind: chain.kind,
numbers: chain.layers.map((layer) => layer.number),
})),
};
}
const make = Effect.gen(function* () {
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const crypto = yield* Crypto.Crypto;
const commandId = (tag: string, threadId: ThreadId) =>
crypto.randomUUIDv4.pipe(
Effect.orDie,
Effect.map((uuid) => CommandId.make(`server:${tag}:${threadId}:${uuid}`)),
);
const requireThread = Effect.fn("PullRequestsToolkit.requireThread")(function* (
Failure:
| typeof PullRequestLinkFailedError
| typeof PullRequestUnlinkFailedError
| typeof PullRequestListFailedError,
) {
const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
const thread = yield* snapshots
.getThreadShellById(scope.threadId)
.pipe(Effect.mapError((cause) => new Failure({ cause })));
if (Option.isNone(thread)) {
return yield* new PullRequestThreadNotFoundError({ threadId: scope.threadId });
}
return thread.value;
});
const projectOf = (
thread: OrchestrationThreadShell,
Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError,
) =>
snapshots.getProjectShellById(thread.projectId).pipe(
Effect.map(Option.getOrUndefined),
Effect.mapError((cause) => new Failure({ cause })),
);
const dispatchFailure =
(Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError) =>
<E>(
cause: Cause.Cause<E>,
): Effect.Effect<never, PullRequestLinkFailedError | PullRequestUnlinkFailedError> =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(cause as Cause.Cause<never>)
: Effect.fail(new Failure({ cause }));
return PullRequestsToolkit.of({
link_pull_request: (input) =>
Effect.gen(function* () {
const thread = yield* requireThread(PullRequestLinkFailedError);
const project = yield* projectOf(thread, PullRequestLinkFailedError);
const target = yield* resolveTarget(input, project);
const alreadyLinked = yield* engine
.dispatch({
type: "thread.pull-request.link",
commandId: yield* commandId("mcp-pr-link", thread.id),
threadId: thread.id,
host: target.host,
repository: target.repository,
number: target.number,
url: target.url,
source: "agent",
})
.pipe(
Effect.as(false),
// The decider rejects a second link of the same PR; for the agent that is
// the outcome it asked for, not an error.
Effect.catchTags({ OrchestrationCommandInvariantError: () => Effect.succeed(true) }),
Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)),
);
return { ...target, alreadyLinked };
}),
unlink_pull_request: (input) =>
Effect.gen(function* () {
const thread = yield* requireThread(PullRequestUnlinkFailedError);
const project = yield* projectOf(thread, PullRequestUnlinkFailedError);
const target = yield* resolveTarget(input, project);
const wasLinked = yield* engine
.dispatch({
type: "thread.pull-request.unlink",
commandId: yield* commandId("mcp-pr-unlink", thread.id),
threadId: thread.id,
host: target.host,
repository: target.repository,
number: target.number,
})
.pipe(
Effect.as(true),
Effect.catchTags({ OrchestrationCommandInvariantError: () => Effect.succeed(false) }),
Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError)),
);
return {
host: target.host,
repository: target.repository,
number: target.number,
wasLinked,
};
}),
list_thread_pull_requests: () =>
requireThread(PullRequestListFailedError).pipe(Effect.map(listThreadPullRequests)),
});
});
export const PullRequestsToolkitHandlersLive = PullRequestsToolkit.toLayer(make);
@@ -0,0 +1,231 @@
import {
McpCapabilityUnavailableError,
PositiveInt,
PullRequestState,
ThreadPullRequestLinkSource,
TrimmedNonEmptyString,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import * as Tool from "effect/unstable/ai/Tool";
import * as Toolkit from "effect/unstable/ai/Toolkit";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as OrchestrationEngine from "../../../orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
const dependencies = [
McpInvocationContext.McpInvocationContext,
OrchestrationEngine.OrchestrationEngineService,
ProjectionSnapshotQuery.ProjectionSnapshotQuery,
];
const REGISTER_EVERY_PR =
"Register every pull request you open for this thread, including each layer of a stack, right after creating it.";
/**
* Either the pull request's URL or its repository and number. Both forms
* resolve to the same host-level identity, so the agent can pass whichever
* the host CLI handed back.
*/
export const PullRequestTargetInput = Schema.Struct({
url: Schema.optional(
TrimmedNonEmptyString.annotate({
description:
"The pull request's web URL, for example https://github.com/owner/repo/pull/123. Preferred when you have it; host, repository and number are read from it.",
}),
),
repository: Schema.optional(
TrimmedNonEmptyString.annotate({
description:
"Repository path below the host, for example owner/repo. Required with number when url is omitted.",
}),
),
number: Schema.optional(
PositiveInt.annotate({
description: "Pull request number. Required with repository when url is omitted.",
}),
),
host: Schema.optional(
TrimmedNonEmptyString.annotate({
description:
"Host the repository lives on, for example github.com. Defaults to the host of this thread's project.",
}),
),
});
export type PullRequestTargetInput = typeof PullRequestTargetInput.Type;
export class PullRequestUrlInvalidError extends Schema.TaggedError<PullRequestUrlInvalidError>()(
"PullRequestUrlInvalidError",
{},
) {
override get message(): string {
return "This is not a recognised pull request URL. Pass repository and number instead.";
}
}
export class PullRequestTargetIncompleteError extends Schema.TaggedError<PullRequestTargetIncompleteError>()(
"PullRequestTargetIncompleteError",
{},
) {
override get message(): string {
return "Pass either url, or both repository and number.";
}
}
export class PullRequestHostRequiredError extends Schema.TaggedError<PullRequestHostRequiredError>()(
"PullRequestHostRequiredError",
{},
) {
override get message(): string {
return "This thread's project has no recognised remote. Pass host or url.";
}
}
export class PullRequestThreadNotFoundError extends Schema.TaggedError<PullRequestThreadNotFoundError>()(
"PullRequestThreadNotFoundError",
{ threadId: Schema.String },
) {
override get message(): string {
return `Thread ${this.threadId} was not found.`;
}
}
export class PullRequestLinkFailedError extends Schema.TaggedError<PullRequestLinkFailedError>()(
"PullRequestLinkFailedError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Could not link the pull request.";
}
}
export class PullRequestUnlinkFailedError extends Schema.TaggedError<PullRequestUnlinkFailedError>()(
"PullRequestUnlinkFailedError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Could not unlink the pull request.";
}
}
export class PullRequestListFailedError extends Schema.TaggedError<PullRequestListFailedError>()(
"PullRequestListFailedError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Could not list the pull request.";
}
}
export const PullRequestToolError = Schema.Union([
McpCapabilityUnavailableError,
PullRequestUrlInvalidError,
PullRequestTargetIncompleteError,
PullRequestHostRequiredError,
PullRequestThreadNotFoundError,
PullRequestLinkFailedError,
PullRequestUnlinkFailedError,
PullRequestListFailedError,
]);
export type PullRequestToolError = typeof PullRequestToolError.Type;
const PullRequestIdentity = {
host: Schema.String,
repository: Schema.String,
number: Schema.Int,
url: Schema.String,
};
export const LinkPullRequestResult = Schema.Struct({
...PullRequestIdentity,
alreadyLinked: Schema.Boolean.annotate({
description: "True when the pull request was linked to this thread before the call.",
}),
});
export type LinkPullRequestResult = typeof LinkPullRequestResult.Type;
export const UnlinkPullRequestResult = Schema.Struct({
host: Schema.String,
repository: Schema.String,
number: Schema.Int,
wasLinked: Schema.Boolean.annotate({
description: "False when the pull request was not linked to this thread to begin with.",
}),
});
export type UnlinkPullRequestResult = typeof UnlinkPullRequestResult.Type;
export const ThreadPullRequestEntry = Schema.Struct({
...PullRequestIdentity,
source: ThreadPullRequestLinkSource,
state: Schema.NullOr(PullRequestState),
title: Schema.NullOr(Schema.String),
headBranch: Schema.NullOr(Schema.String),
baseBranch: Schema.NullOr(Schema.String),
isDraft: Schema.NullOr(Schema.Boolean),
stack: Schema.NullOr(
Schema.Struct({
kind: Schema.Literals(["native", "derived"]),
/** 1-based, bottom of the stack first. */
position: Schema.Int,
size: Schema.Int,
}),
),
});
export type ThreadPullRequestEntry = typeof ThreadPullRequestEntry.Type;
export const ListThreadPullRequestsResult = Schema.Struct({
pullRequests: Schema.Array(ThreadPullRequestEntry),
chains: Schema.Array(
Schema.Struct({
kind: Schema.Literals(["native", "derived"]),
/** Bottom to top. */
numbers: Schema.Array(Schema.Int),
}),
),
});
export type ListThreadPullRequestsResult = typeof ListThreadPullRequestsResult.Type;
const LinkPullRequestTool = Tool.make("link_pull_request", {
description: `${REGISTER_EVERY_PR} Links a pull request to this thread so T3 Code tracks it, shows its status beside the thread, and settles the thread when it merges. Pass the URL, or repository plus number. Linking an already-linked pull request succeeds with alreadyLinked=true.`,
parameters: PullRequestTargetInput,
success: LinkPullRequestResult,
failure: PullRequestToolError,
dependencies,
})
.annotate(Tool.Title, "Link pull request to thread")
.annotate(Tool.Readonly, false)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true)
.annotate(Tool.OpenWorld, false);
const UnlinkPullRequestTool = Tool.make("unlink_pull_request", {
description:
"Remove a pull request link from this thread, for example after closing a pull request you opened by mistake. Pass the URL, or repository plus number. Unlinking a pull request that is not linked succeeds with wasLinked=false.",
parameters: PullRequestTargetInput,
success: UnlinkPullRequestResult,
failure: PullRequestToolError,
dependencies,
})
.annotate(Tool.Title, "Unlink pull request from thread")
.annotate(Tool.Readonly, false)
.annotate(Tool.Destructive, true)
.annotate(Tool.Idempotent, true)
.annotate(Tool.OpenWorld, false);
const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {
description: `List the pull requests linked to this thread with their last known host state, and how they chain into stacks (bottom to top). ${REGISTER_EVERY_PR}`,
success: ListThreadPullRequestsResult,
failure: PullRequestToolError,
dependencies,
})
.annotate(Tool.Title, "List thread pull requests")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true)
.annotate(Tool.OpenWorld, false);
export const PullRequestsToolkit = Toolkit.make(
LinkPullRequestTool,
UnlinkPullRequestTool,
ListThreadPullRequestsTool,
);
@@ -60,7 +60,10 @@ const asMessageId = (value: string): MessageId => MessageId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
function makeOrchestrationLayer(databasePath?: string) {
function makeOrchestrationLayer(
databasePath?: string,
repositoryIdentityResolver?: RepositoryIdentityResolver.RepositoryIdentityResolver["Service"],
) {
const persistence = databasePath
? makeSqlitePersistenceLive(databasePath)
: SqlitePersistenceMemory;
@@ -78,15 +81,27 @@ function makeOrchestrationLayer(databasePath?: string) {
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationEventStoreLive),
Layer.provideMerge(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(
repositoryIdentityResolver
? Layer.succeed(
RepositoryIdentityResolver.RepositoryIdentityResolver,
repositoryIdentityResolver,
)
: RepositoryIdentityResolver.layer,
),
Layer.provide(persistence),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
}
async function createOrchestrationSystem(databasePath?: string) {
const runtime = ManagedRuntime.make(makeOrchestrationLayer(databasePath));
async function createOrchestrationSystem(
databasePath?: string,
repositoryIdentityResolver?: RepositoryIdentityResolver.RepositoryIdentityResolver["Service"],
) {
const runtime = ManagedRuntime.make(
makeOrchestrationLayer(databasePath, repositoryIdentityResolver),
);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
return {
@@ -373,6 +388,7 @@ describe("OrchestrationEngine", () => {
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: null,
createdAt: "2026-03-03T00:00:02.000Z",
updatedAt: "2026-03-03T00:00:03.000Z",
@@ -1009,7 +1025,20 @@ describe("OrchestrationEngine", () => {
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();
const system = await createOrchestrationSystem(undefined, {
resolve: (workspaceRoot) =>
Effect.succeed({
canonicalKey: "example.test/owner/repository",
provider: "github",
displayName: "owner/repository",
rootPath: workspaceRoot,
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://example.test/owner/repository.git",
},
}),
});
try {
const projectId = ProjectId.make("pr-race-project");
const threadId = ThreadId.make("pr-race-thread");
@@ -1058,6 +1087,7 @@ describe("OrchestrationEngine", () => {
linkedPullRequest: previous,
}),
);
expect((await system.readModel()).threads[0]?.linkedPullRequest).toEqual(previous);
const metadataChanges = {
unlink: { linkedPullRequest: null },
relink: {
@@ -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 PullRequestSyncReactor from "../PullRequestSyncReactor.ts";
import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
@@ -84,6 +85,16 @@ describe("OrchestrationReactor", () => {
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(PullRequestSyncReactor.PullRequestSyncReactor, {
start: () => {
started.push("pull-request-sync-reactor");
return Effect.void;
},
drain: Effect.void,
requestSync: () => Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, {
publishThread: () => Effect.void,
@@ -107,6 +118,7 @@ describe("OrchestrationReactor", () => {
"thread-deletion-reactor",
"thread-pull-request-reactor",
"thread-settlement-reactor",
"pull-request-sync-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 PullRequestSyncReactor from "../PullRequestSyncReactor.ts";
import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
@@ -19,6 +20,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
const checkpointReactor = yield* CheckpointReactor;
const threadDeletionReactor = yield* ThreadDeletionReactor;
const threadSettlementReactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
const pullRequestSyncReactor = yield* PullRequestSyncReactor.PullRequestSyncReactor;
const threadPullRequestReactor = yield* ThreadPullRequestReactor.ThreadPullRequestReactor;
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
@@ -29,6 +31,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
yield* threadDeletionReactor.start();
yield* threadPullRequestReactor.start();
yield* threadSettlementReactor.start();
yield* pullRequestSyncReactor.start();
yield* agentAwarenessRelay.start();
});
@@ -8,6 +8,7 @@ import {
MessageId,
ProjectId,
ThreadId,
type ThreadPullRequestSnapshot,
ThreadLinkedPullRequest,
TurnId,
ProviderInstanceId,
@@ -686,6 +687,242 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-base-")))(
},
);
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-pull-requests-")))(
"OrchestrationProjectionPipeline pull request links",
(it) => {
it.effect("projects link, sync, unlink, legacy replay and delete into the link table", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const threadId = ThreadId.make("thread-pr");
const projectId = ProjectId.make("project-pr");
const t0 = "2026-01-01T00:00:00.000Z";
let counter = 0;
const base = (occurredAt: string) => {
counter += 1;
return {
eventId: EventId.make(`evt-pr-${counter}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt,
commandId: CommandId.make(`cmd-pr-${counter}`),
causationEventId: null,
correlationId: CommandId.make(`cmd-pr-${counter}`),
metadata: {},
} as const;
};
const readLinks = () =>
sql<{
readonly host: string;
readonly repository: string;
readonly number: number;
readonly source: string;
readonly linkedAt: string;
readonly snapshotJson: string | null;
readonly stackJson: string | null;
}>`
SELECT
host,
repository,
number,
source,
linked_at AS "linkedAt",
snapshot_json AS "snapshotJson",
stack_json AS "stackJson"
FROM projection_thread_pull_requests
WHERE thread_id = ${threadId}
ORDER BY number ASC
`;
const readThreadUpdatedAt = () =>
sql<{ readonly updatedAt: string }>`
SELECT updated_at AS "updatedAt" FROM projection_threads WHERE thread_id = ${threadId}
`;
yield* eventStore.append({
...base(t0),
type: "thread.created",
payload: {
threadId,
projectId,
title: "Thread PR",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: t0,
updatedAt: t0,
},
});
// Legacy single-link event replays into a manual row with the URL host.
yield* eventStore.append({
...base("2026-01-01T00:00:01.000Z"),
type: "thread.meta-updated",
payload: {
threadId,
linkedPullRequest: {
projectId,
repository: "web",
number: 41,
url: "https://org-a.visualstudio.com/DefaultCollection/project/_git/web/pullrequest/41",
},
updatedAt: "2026-01-01T00:00:01.000Z",
},
});
yield* eventStore.append({
...base("2026-01-01T00:00:02.000Z"),
type: "thread.pull-request-linked",
payload: {
threadId,
link: {
host: "github.com",
repository: "pingdotgg/t3code",
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
source: "created",
linkedAt: "2026-01-01T00:00:02.000Z",
snapshot: null,
stack: null,
},
updatedAt: "2026-01-01T00:00:02.000Z",
},
});
yield* projectionPipeline.bootstrap;
assert.deepEqual(yield* readLinks(), [
{
host: "dev.azure.com",
repository: "org-a/project/_git/web",
number: 41,
source: "manual",
linkedAt: "2026-01-01T00:00:01.000Z",
snapshotJson: null,
stackJson: null,
},
{
host: "github.com",
repository: "pingdotgg/t3code",
number: 42,
source: "created",
linkedAt: "2026-01-01T00:00:02.000Z",
snapshotJson: null,
stackJson: null,
},
]);
assert.deepEqual(yield* readThreadUpdatedAt(), [{ updatedAt: "2026-01-01T00:00:02.000Z" }]);
// Sync fills snapshot/stack on the matching row; a sync for an unknown
// link is ignored.
const snapshot: ThreadPullRequestSnapshot = {
state: "open",
title: "Add links",
headBranch: "feat/links",
baseBranch: "main",
isDraft: false,
updatedAt: "2026-01-01T00:00:02.500Z",
syncedAt: "2026-01-01T00:00:03.000Z",
};
yield* eventStore.append({
...base("2026-01-01T00:00:03.000Z"),
type: "thread.pull-request-synced",
payload: {
threadId,
host: "github.com",
repository: "pingdotgg/t3code",
number: 42,
snapshot,
stack: null,
updatedAt: "2026-01-01T00:00:03.000Z",
},
});
yield* eventStore.append({
...base("2026-01-01T00:00:03.500Z"),
type: "thread.pull-request-synced",
payload: {
threadId,
host: "github.com",
repository: "pingdotgg/t3code",
number: 99,
snapshot,
stack: null,
updatedAt: "2026-01-01T00:00:03.500Z",
},
});
yield* projectionPipeline.bootstrap;
const synced = yield* readLinks();
assert.equal(synced.length, 2);
assert.equal(synced[0]?.snapshotJson, null);
// @effect-diagnostics-next-line preferSchemaOverJson:off
assert.deepEqual(JSON.parse(synced[1]?.snapshotJson ?? "null"), snapshot);
assert.deepEqual(yield* readThreadUpdatedAt(), [{ updatedAt: "2026-01-01T00:00:03.000Z" }]);
// A legacy null clears only the manual row; created/agent/stack rows stay.
yield* eventStore.append({
...base("2026-01-01T00:00:04.000Z"),
type: "thread.meta-updated",
payload: {
threadId,
linkedPullRequest: null,
updatedAt: "2026-01-01T00:00:04.000Z",
},
});
yield* projectionPipeline.bootstrap;
assert.deepEqual(
(yield* readLinks()).map((row) => row.number),
[42],
);
yield* eventStore.append({
...base("2026-01-01T00:00:05.000Z"),
type: "thread.pull-request-unlinked",
payload: {
threadId,
host: "GitHub.COM",
repository: "PingDotGG/T3Code",
number: 42,
updatedAt: "2026-01-01T00:00:05.000Z",
},
});
yield* projectionPipeline.bootstrap;
assert.deepEqual(yield* readLinks(), []);
assert.deepEqual(yield* readThreadUpdatedAt(), [{ updatedAt: "2026-01-01T00:00:05.000Z" }]);
// Deleting the thread clears whatever links it still had.
yield* eventStore.append({
...base("2026-01-01T00:00:06.000Z"),
type: "thread.pull-request-linked",
payload: {
threadId,
link: {
host: "github.com",
repository: "pingdotgg/t3code",
number: 43,
url: "https://github.com/pingdotgg/t3code/pull/43",
source: "agent",
linkedAt: "2026-01-01T00:00:06.000Z",
snapshot: null,
stack: null,
},
updatedAt: "2026-01-01T00:00:06.000Z",
},
});
yield* eventStore.append({
...base("2026-01-01T00:00:07.000Z"),
type: "thread.deleted",
payload: {
threadId,
deletedAt: "2026-01-01T00:00:07.000Z",
},
});
yield* projectionPipeline.bootstrap;
assert.deepEqual(yield* readLinks(), []);
}),
);
},
);
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-safe-")))(
"OrchestrationProjectionPipeline",
(it) => {
@@ -16,6 +16,10 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
legacyThreadPullRequestKey,
threadPullRequestKeysEqual,
} from "@t3tools/shared/threadPullRequests";
import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
@@ -32,6 +36,7 @@ import {
type ProjectionThreadProposedPlan,
ProjectionThreadProposedPlanRepository,
} from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import * as ProjectionThreadPullRequests from "../../persistence/ProjectionThreadPullRequests.ts";
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
import {
type ProjectionTurn,
@@ -480,6 +485,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
const projectionThreadRepository = yield* ProjectionThreadRepository;
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
const projectionThreadPullRequestRepository =
yield* ProjectionThreadPullRequests.ProjectionThreadPullRequestRepository;
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
const projectionTurnRepository = yield* ProjectionTurnRepository;
@@ -599,6 +606,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.created":
// A draft retry can re-create this id; links belong to the old incarnation.
yield* projectionThreadPullRequestRepository.deleteByThreadId({
threadId: event.payload.threadId,
});
yield* projectionThreadRepository.upsert({
threadId: event.payload.threadId,
projectId: event.payload.projectId,
@@ -820,6 +831,94 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
: {}),
updatedAt: event.payload.updatedAt,
});
// Legacy single-link events replay into the link table. The old
// field held one user-chosen link, so it only ever owns the manual
// rows; created/agent/stack links are left alone.
if (event.payload.linkedPullRequest !== undefined) {
yield* projectionThreadPullRequestRepository.deleteByThreadIdAndSource({
threadId: event.payload.threadId,
source: "manual",
});
if (event.payload.linkedPullRequest !== null) {
const linked = event.payload.linkedPullRequest;
yield* projectionThreadPullRequestRepository.upsert({
threadId: event.payload.threadId,
...legacyThreadPullRequestKey(linked),
url: linked.url,
source: "manual",
linkedAt: event.payload.updatedAt,
snapshot: null,
stack: null,
});
}
}
return;
}
case "thread.pull-request-linked": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadPullRequestRepository.upsert({
threadId: event.payload.threadId,
...event.payload.link,
});
yield* projectionThreadRepository.upsert({
...existingRow.value,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.pull-request-unlinked": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadPullRequestRepository.delete({
threadId: event.payload.threadId,
host: event.payload.host.toLowerCase(),
repository: event.payload.repository.toLowerCase(),
number: event.payload.number,
});
yield* projectionThreadRepository.upsert({
...existingRow.value,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.pull-request-synced": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
// A sync for a link the user removed in the meantime is stale; drop it.
const links = yield* projectionThreadPullRequestRepository.listByThreadId({
threadId: event.payload.threadId,
});
const link = links.find((candidate) =>
threadPullRequestKeysEqual(candidate, event.payload),
);
if (link === undefined) {
return;
}
yield* projectionThreadPullRequestRepository.upsert({
...link,
snapshot: event.payload.snapshot,
stack: event.payload.stack,
});
yield* projectionThreadRepository.upsert({
...existingRow.value,
updatedAt: event.payload.updatedAt,
});
return;
}
@@ -866,6 +965,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
if (!recreatedLater) {
attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);
}
// A tombstoned thread must not show up as linked to a pull request.
yield* projectionThreadPullRequestRepository.deleteByThreadId({
threadId: event.payload.threadId,
});
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
@@ -2068,6 +2171,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
Layer.provideMerge(ProjectionThreadRepositoryLive),
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
Layer.provideMerge(ProjectionThreadPullRequests.layer),
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
Layer.provideMerge(ProjectionTurnRepositoryLive),
@@ -6,6 +6,7 @@ import {
MessageId,
ProjectId,
ThreadId,
type ThreadPullRequestLink,
ThreadLinkedPullRequest,
TurnId,
ProviderInstanceId,
@@ -66,6 +67,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_state`;
yield* sql`DELETE FROM projection_thread_proposed_plans`;
yield* sql`DELETE FROM projection_thread_pull_requests`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
@@ -91,6 +93,45 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
)
`;
// A merged link plus a newer open one: the multi-link projection must
// resolve to the open pull request, not the stale JSON column below.
yield* sql`
INSERT INTO projection_thread_pull_requests (
thread_id,
host,
repository,
number,
url,
source,
linked_at,
snapshot_json,
stack_json
)
VALUES
(
'thread-1',
'github.com',
'pingdotgg/t3code',
41,
'https://github.com/pingdotgg/t3code/pull/41',
'created',
'2026-02-24T00:00:02.500Z',
'{"state":"merged","title":"Groundwork","headBranch":"feat/groundwork","baseBranch":"main","isDraft":false,"updatedAt":"2026-02-24T00:00:02.600Z","syncedAt":"2026-02-24T00:00:02.700Z"}',
NULL
),
(
'thread-1',
'github.com',
'pingdotgg/t3code',
42,
'https://github.com/pingdotgg/t3code/pull/42',
'manual',
'2026-02-24T00:00:03.000Z',
NULL,
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
@@ -124,7 +165,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'default',
NULL,
NULL,
'{"projectId":"project-1","repository":"pingdotgg/t3code","number":42,"url":"https://github.com/pingdotgg/t3code/pull/42"}',
'{"projectId":"project-1","repository":"pingdotgg/t3code","number":41,"url":"https://github.com/pingdotgg/t3code/pull/41"}',
${encodeThreadLinkedPullRequest(branchPullRequest)},
'turn-1',
'2026-02-24T00:00:04.000Z',
@@ -286,6 +327,37 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
sequence += 1;
}
const expectedPullRequests: ReadonlyArray<ThreadPullRequestLink> = [
{
host: "github.com",
repository: "pingdotgg/t3code",
number: 41,
url: "https://github.com/pingdotgg/t3code/pull/41",
source: "created",
linkedAt: "2026-02-24T00:00:02.500Z",
snapshot: {
state: "merged",
title: "Groundwork",
headBranch: "feat/groundwork",
baseBranch: "main",
isDraft: false,
updatedAt: "2026-02-24T00:00:02.600Z",
syncedAt: "2026-02-24T00:00:02.700Z",
},
stack: null,
},
{
host: "github.com",
repository: "pingdotgg/t3code",
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
source: "manual",
linkedAt: "2026-02-24T00:00:03.000Z",
snapshot: null,
stack: null,
},
];
const snapshot = yield* snapshotQuery.getSnapshot();
assert.equal(snapshot.snapshotSequence, 5);
@@ -331,12 +403,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
linkedPullRequest: {
projectId: asProjectId("project-1"),
repository: "pingdotgg/t3code",
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
},
pullRequests: expectedPullRequests,
branchPullRequest,
latestTurn: {
turnId: asTurnId("turn-1"),
@@ -461,12 +528,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
linkedPullRequest: {
projectId: asProjectId("project-1"),
repository: "pingdotgg/t3code",
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
},
pullRequests: expectedPullRequests,
branchPullRequest,
latestTurn: {
turnId: asTurnId("turn-1"),
@@ -516,13 +578,27 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
assert.deepEqual(threadDetail.value, snapshot.threads[0]);
}
const commandSnapshot = yield* snapshotQuery.getCommandReadModel();
assert.equal(commandSnapshot.threads[0]?.activeOrderKey, "hq");
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);
assert.deepEqual(threadShell.value, shellSnapshot.threads[0]);
}
const commandReadModel = yield* snapshotQuery.getCommandReadModel();
assert.deepEqual(commandReadModel.threads[0]?.pullRequests, expectedPullRequests);
assert.deepEqual(
commandReadModel.threads[0]?.linkedPullRequest,
snapshot.threads[0]?.linkedPullRequest,
);
// Without link rows the legacy field is omitted, whatever the old JSON
// column still holds.
yield* sql`DELETE FROM projection_thread_pull_requests`;
const unlinkedShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
assert.equal(unlinkedShell._tag, "Some");
if (unlinkedShell._tag === "Some") {
assert.deepEqual(unlinkedShell.value.pullRequests, []);
assert.equal("linkedPullRequest" in unlinkedShell.value, false);
}
yield* sql`
@@ -3259,3 +3335,56 @@ projectionSnapshotLayer("ProjectionSnapshotQuery imported sources", (it) => {
}),
);
});
it.effect("omits foreign-host PRs from legacy snapshots while preserving native links", () => {
const layer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(
Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
resolve: () =>
Effect.succeed({
canonicalKey: "github.com/acme/web",
provider: "github",
displayName: "acme/web",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "https://github.com/acme/web.git",
},
}),
}),
),
Layer.provideMerge(SqlitePersistenceMemory),
);
return Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const query = yield* ProjectionSnapshotQuery;
yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at)
VALUES ('project-1', 'Project', '/repo', '[]', '2026-09-09T00:00:00Z', '2026-09-09T00:00:00Z')`;
yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, created_at, updated_at)
VALUES ('thread-1', 'project-1', 'Thread', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', '2026-09-09T00:00:00Z', '2026-09-09T00:00:00Z')`;
yield* sql`INSERT INTO projection_thread_pull_requests (thread_id, host, repository, number, url, source, linked_at)
VALUES ('thread-1', 'github.enterprise.test', 'acme/web', 42, 'https://github.enterprise.test/acme/web/pull/42', 'manual', '2026-09-09T00:00:00Z')`;
const readThreads = Effect.gen(function* () {
const full = yield* query.getSnapshot();
const shell = yield* query.getShellSnapshot();
const detail = yield* query.getThreadDetailById(ThreadId.make("thread-1"));
const individual = yield* query.getThreadShellById(ThreadId.make("thread-1"));
return [
full.threads[0]!,
shell.threads[0]!,
Option.getOrThrow(detail),
Option.getOrThrow(individual),
];
});
for (const thread of yield* readThreads) {
assert.equal(thread.linkedPullRequest ?? null, null);
assert.equal(thread.pullRequests[0]?.host, "github.enterprise.test");
}
yield* sql`UPDATE projection_thread_pull_requests SET host = 'github.com', url = 'https://github.com/acme/web/pull/42'`;
for (const thread of yield* readThreads) {
assert.equal(thread.linkedPullRequest?.url, "https://github.com/acme/web/pull/42");
}
}).pipe(Effect.provide(layer));
});
@@ -29,7 +29,11 @@ import {
ProjectId,
ThreadLinkedPullRequest,
ThreadId,
ThreadPullRequestSnapshot,
ThreadPullRequestStack,
type ThreadPullRequestLink,
} from "@t3tools/contracts";
import { legacyLinkedPullRequestOf } from "@t3tools/shared/threadPullRequests";
import * as Arr from "effect/Array";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -54,6 +58,7 @@ import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadPullRequest } from "../../persistence/ProjectionThreadPullRequests.ts";
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
import {
@@ -112,6 +117,12 @@ const ProjectionTurnStartMessageDbRowSchema = ProjectionThreadMessageDbRowSchema
Struct.assign({ hasOtherUserMessages: Schema.Number }),
);
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
const ProjectionThreadPullRequestDbRowSchema = ProjectionThreadPullRequest.mapFields(
Struct.assign({
snapshot: Schema.NullOr(Schema.fromJsonString(ThreadPullRequestSnapshot)),
stack: Schema.NullOr(Schema.fromJsonString(ThreadPullRequestStack)),
}),
);
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
@@ -403,6 +414,49 @@ function mapProposedPlanRow(
};
}
function mapPullRequestRow(
row: Schema.Schema.Type<typeof ProjectionThreadPullRequestDbRowSchema>,
): ThreadPullRequestLink {
return {
host: row.host,
repository: row.repository,
number: row.number,
url: row.url,
source: row.source,
linkedAt: row.linkedAt,
snapshot: row.snapshot,
stack: row.stack,
};
}
function groupPullRequestRowsByThread(
rows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionThreadPullRequestDbRowSchema>>,
): Map<string, Array<ThreadPullRequestLink>> {
const byThread = new Map<string, Array<ThreadPullRequestLink>>();
for (const row of rows) {
const links = byThread.get(row.threadId) ?? [];
links.push(mapPullRequestRow(row));
byThread.set(row.threadId, links);
}
return byThread;
}
/**
* The link array plus the legacy single-link field derived from it, so clients
* from before `pullRequests` keep seeing the thread's current pull request.
*/
function mapThreadPullRequests(
pullRequests: ReadonlyArray<ThreadPullRequestLink>,
projectId: ProjectId,
identity?: OrchestrationProject["repositoryIdentity"],
): Pick<OrchestrationThread, "pullRequests" | "linkedPullRequest"> {
const linkedPullRequest = legacyLinkedPullRequestOf(pullRequests, projectId, identity);
return {
pullRequests,
...(linkedPullRequest === null ? {} : { linkedPullRequest }),
};
}
function mapThreadActivityRow(
row: Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>,
): OrchestrationThreadActivity {
@@ -649,6 +703,74 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listThreadPullRequestRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadPullRequestDbRowSchema,
execute: () =>
sql`
SELECT
thread_id AS "threadId",
host,
repository,
number,
url,
source,
linked_at AS "linkedAt",
snapshot_json AS "snapshot",
stack_json AS "stack"
FROM projection_thread_pull_requests
ORDER BY thread_id ASC, linked_at ASC, number ASC
`,
});
const listActiveThreadPullRequestRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadPullRequestDbRowSchema,
execute: () =>
sql`
SELECT
links.thread_id AS "threadId",
links.host,
links.repository,
links.number,
links.url,
links.source,
links.linked_at AS "linkedAt",
links.snapshot_json AS "snapshot",
links.stack_json AS "stack"
FROM projection_thread_pull_requests links
INNER JOIN projection_threads threads
ON threads.thread_id = links.thread_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
ORDER BY links.thread_id ASC, links.linked_at ASC, links.number ASC
`,
});
const listArchivedThreadPullRequestRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadPullRequestDbRowSchema,
execute: () =>
sql`
SELECT
links.thread_id AS "threadId",
links.host,
links.repository,
links.number,
links.url,
links.source,
links.linked_at AS "linkedAt",
links.snapshot_json AS "snapshot",
links.stack_json AS "stack"
FROM projection_thread_pull_requests links
INNER JOIN projection_threads threads
ON threads.thread_id = links.thread_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NOT NULL
ORDER BY links.thread_id ASC, links.linked_at ASC, links.number ASC
`,
});
const listThreadActivityRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadActivityDbRowSchema,
@@ -1208,6 +1330,27 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listThreadPullRequestRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionThreadPullRequestDbRowSchema,
execute: ({ threadId }) =>
sql`
SELECT
thread_id AS "threadId",
host,
repository,
number,
url,
source,
linked_at AS "linkedAt",
snapshot_json AS "snapshot",
stack_json AS "stack"
FROM projection_thread_pull_requests
WHERE thread_id = ${threadId}
ORDER BY linked_at ASC, number ASC
`,
});
const listThreadActivityRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionThreadActivityDbRowSchema,
@@ -1852,6 +1995,14 @@ pending_approval_requests AS (
),
),
),
listThreadPullRequestRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getSnapshot:listThreadPullRequests:query",
"ProjectionSnapshotQuery.getSnapshot:listThreadPullRequests:decodeRows",
),
),
),
listThreadActivityRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -1901,6 +2052,7 @@ pending_approval_requests AS (
threadRows,
messageRows,
proposedPlanRows,
pullRequestRows,
activityRows,
sessionRows,
checkpointRows,
@@ -1910,6 +2062,7 @@ pending_approval_requests AS (
Effect.gen(function* () {
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
const pullRequestsByThread = groupPullRequestRowsByThread(pullRequestRows);
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
const sessionsByThread = new Map<string, OrchestrationSession>();
@@ -2071,10 +2224,12 @@ pending_approval_requests AS (
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
...mapThreadPullRequests(
pullRequestsByThread.get(row.threadId) ?? [],
row.projectId,
repositoryIdentities.get(row.projectId),
),
branchPullRequest: row.branchPullRequest,
...(row.linkedPullRequest === null
? {}
: { linkedPullRequest: row.linkedPullRequest }),
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -2146,6 +2301,14 @@ pending_approval_requests AS (
),
),
),
listThreadPullRequestRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getCommandReadModel:listThreadPullRequests:query",
"ProjectionSnapshotQuery.getCommandReadModel:listThreadPullRequests:decodeRows",
),
),
),
listThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -2174,8 +2337,25 @@ pending_approval_requests AS (
)
.pipe(
Effect.flatMap(
([projectRows, threadRows, proposedPlanRows, sessionRows, latestTurnRows, stateRows]) =>
Effect.sync(() => {
([
projectRows,
threadRows,
proposedPlanRows,
pullRequestRows,
sessionRows,
latestTurnRows,
stateRows,
]) =>
Effect.gen(function* () {
const linkedThreadIds = new Set(pullRequestRows.map((row) => row.threadId));
const linkedProjectIds = new Set(
threadRows
.filter((row) => linkedThreadIds.has(row.threadId))
.map((row) => row.projectId),
);
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
projectRows.filter((row) => linkedProjectIds.has(row.projectId)),
);
let updatedAt: string | null = null;
const projects: OrchestrationProject[] = [];
const threads: OrchestrationThread[] = [];
@@ -2190,6 +2370,7 @@ pending_approval_requests AS (
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null,
defaultModelSelection: row.defaultModelSelection,
defaultThreadEnvMode: row.defaultThreadEnvMode,
autoPull: row.autoPull === 1,
@@ -2252,6 +2433,7 @@ pending_approval_requests AS (
latestTurnByThread.set(row.threadId, mapLatestTurn(row));
}
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
const pullRequestsByThread = groupPullRequestRowsByThread(pullRequestRows);
const sessionByThread = new Map<string, OrchestrationSession>();
for (let index = 0; index < sessionRows.length; index += 1) {
@@ -2286,10 +2468,12 @@ pending_approval_requests AS (
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
...mapThreadPullRequests(
pullRequestsByThread.get(row.threadId) ?? [],
row.projectId,
repositoryIdentities.get(row.projectId),
),
branchPullRequest: row.branchPullRequest,
...(row.linkedPullRequest === null
? {}
: { linkedPullRequest: row.linkedPullRequest }),
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -2356,6 +2540,14 @@ pending_approval_requests AS (
),
),
),
listActiveThreadPullRequestRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listThreadPullRequests:query",
"ProjectionSnapshotQuery.getShellSnapshot:listThreadPullRequests:decodeRows",
),
),
),
listActiveLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -2375,99 +2567,104 @@ pending_approval_requests AS (
]),
)
.pipe(
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
Effect.gen(function* () {
let updatedAt: string | null = null;
for (const row of projectRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of threadRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of latestTurnRows) {
updatedAt = maxIso(updatedAt, row.requestedAt);
if (row.startedAt !== null) {
updatedAt = maxIso(updatedAt, row.startedAt);
Effect.flatMap(
([projectRows, threadRows, sessionRows, pullRequestRows, latestTurnRows, stateRows]) =>
Effect.gen(function* () {
let updatedAt: string | null = null;
for (const row of projectRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
if (row.completedAt !== null) {
updatedAt = maxIso(updatedAt, row.completedAt);
for (const row of threadRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of latestTurnRows) {
updatedAt = maxIso(updatedAt, row.requestedAt);
if (row.startedAt !== null) {
updatedAt = maxIso(updatedAt, row.startedAt);
}
if (row.completedAt !== null) {
updatedAt = maxIso(updatedAt, row.completedAt);
}
}
for (const row of stateRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
}
for (const row of stateRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(projectRows);
const latestTurnByThread = new Map(
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
);
const sessionByThread = new Map(
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
);
const repositoryIdentities =
yield* resolveRepositoryIdentitiesForProjects(projectRows);
const latestTurnByThread = new Map(
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
);
const sessionByThread = new Map(
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
);
const pullRequestsByThread = groupPullRequestRowsByThread(pullRequestRows);
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects: Arr.filterMap(projectRows, (row) =>
row.deletedAt === null
? Result.succeed(
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
)
: Result.failVoid,
),
threads: Arr.filterMap(threadRows, (row) =>
row.deletedAt === null
? Result.succeed({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
branchPullRequest: row.branchPullRequest,
...(row.linkedPullRequest === null
? {}
: { linkedPullRequest: row.linkedPullRequest }),
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
unsettledAt: row.unsettledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
activeOrderKey: row.activeOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId),
} satisfies OrchestrationThreadShell)
: Result.failVoid,
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
};
return yield* decodeShellSnapshot(snapshot).pipe(
Effect.mapError(
toPersistenceDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:decodeShellSnapshot",
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects: Arr.filterMap(projectRows, (row) =>
row.deletedAt === null
? Result.succeed(
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
)
: Result.failVoid,
),
),
);
}),
threads: Arr.filterMap(threadRows, (row) =>
row.deletedAt === null
? Result.succeed({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
branchPullRequest: row.branchPullRequest,
...mapThreadPullRequests(
pullRequestsByThread.get(row.threadId) ?? [],
row.projectId,
repositoryIdentities.get(row.projectId),
),
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
unsettledAt: row.unsettledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
activeOrderKey: row.activeOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId),
} satisfies OrchestrationThreadShell)
: Result.failVoid,
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
};
return yield* decodeShellSnapshot(snapshot).pipe(
Effect.mapError(
toPersistenceDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:decodeShellSnapshot",
),
),
);
}),
),
Effect.mapError((error) => {
if (isPersistenceError(error)) {
@@ -2505,6 +2702,14 @@ pending_approval_requests AS (
),
),
),
listArchivedThreadPullRequestRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadPullRequests:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadPullRequests:decodeRows",
),
),
),
listArchivedLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -2524,98 +2729,102 @@ pending_approval_requests AS (
]),
)
.pipe(
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
Effect.gen(function* () {
let updatedAt: string | null = null;
for (const row of projectRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of threadRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of latestTurnRows) {
updatedAt = maxIso(updatedAt, row.requestedAt);
if (row.startedAt !== null) {
updatedAt = maxIso(updatedAt, row.startedAt);
Effect.flatMap(
([projectRows, threadRows, sessionRows, pullRequestRows, latestTurnRows, stateRows]) =>
Effect.gen(function* () {
let updatedAt: string | null = null;
for (const row of projectRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
if (row.completedAt !== null) {
updatedAt = maxIso(updatedAt, row.completedAt);
for (const row of threadRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of latestTurnRows) {
updatedAt = maxIso(updatedAt, row.requestedAt);
if (row.startedAt !== null) {
updatedAt = maxIso(updatedAt, row.startedAt);
}
if (row.completedAt !== null) {
updatedAt = maxIso(updatedAt, row.completedAt);
}
}
for (const row of stateRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
}
for (const row of stateRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
const activeProjectIds = new Set(threadRows.map((row) => row.projectId));
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
projectRows.filter((row) => activeProjectIds.has(row.projectId)),
);
const latestTurnByThread = new Map(
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
);
const sessionByThread = new Map(
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
);
const pullRequestsByThread = groupPullRequestRowsByThread(pullRequestRows);
const activeProjectIds = new Set(threadRows.map((row) => row.projectId));
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
projectRows.filter((row) => activeProjectIds.has(row.projectId)),
);
const latestTurnByThread = new Map(
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
);
const sessionByThread = new Map(
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
);
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects: Arr.filterMap(projectRows, (row) =>
row.deletedAt === null && activeProjectIds.has(row.projectId)
? Result.succeed(
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
)
: Result.failVoid,
),
threads: threadRows.map((row): OrchestrationThreadShell => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
branchPullRequest: row.branchPullRequest,
...(row.linkedPullRequest === null
? {}
: { linkedPullRequest: row.linkedPullRequest }),
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
unsettledAt: row.unsettledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
activeOrderKey: row.activeOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects: Arr.filterMap(projectRows, (row) =>
row.deletedAt === null && activeProjectIds.has(row.projectId)
? Result.succeed(
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
)
: Result.failVoid,
),
planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId),
})),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
};
threads: threadRows.map((row): OrchestrationThreadShell => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
branchPullRequest: row.branchPullRequest,
...mapThreadPullRequests(
pullRequestsByThread.get(row.threadId) ?? [],
row.projectId,
repositoryIdentities.get(row.projectId),
),
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
unsettledAt: row.unsettledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
activeOrderKey: row.activeOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId),
})),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
};
return yield* decodeShellSnapshot(snapshot).pipe(
Effect.mapError(
toPersistenceDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:decodeShellSnapshot",
return yield* decodeShellSnapshot(snapshot).pipe(
Effect.mapError(
toPersistenceDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:decodeShellSnapshot",
),
),
),
);
}),
);
}),
),
Effect.mapError((error) => {
if (isPersistenceError(error)) {
@@ -2861,7 +3070,7 @@ pending_approval_requests AS (
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
const [threadRow, latestTurnRow, sessionRow, pullRequestRows] = yield* Effect.all([
getActiveThreadRowById({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -2886,6 +3095,14 @@ pending_approval_requests AS (
),
),
),
listThreadPullRequestRowsByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:listPullRequests:query",
"ProjectionSnapshotQuery.getThreadShellById:listPullRequests:decodeRows",
),
),
),
]);
if (Option.isNone(threadRow)) {
@@ -2901,10 +3118,15 @@ pending_approval_requests AS (
interactionMode: threadRow.value.interactionMode,
branch: threadRow.value.branch,
worktreePath: threadRow.value.worktreePath,
...mapThreadPullRequests(
pullRequestRows.map(mapPullRequestRow),
threadRow.value.projectId,
pullRequestRows.length === 0
? null
: Option.getOrNull(yield* getProjectShellById(threadRow.value.projectId))
?.repositoryIdentity,
),
branchPullRequest: threadRow.value.branchPullRequest,
...(threadRow.value.linkedPullRequest === null
? {}
: { linkedPullRequest: threadRow.value.linkedPullRequest }),
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
createdAt: threadRow.value.createdAt,
updatedAt: threadRow.value.updatedAt,
@@ -3112,6 +3334,7 @@ pending_approval_requests AS (
threadRow,
messageRows,
proposedPlanRows,
pullRequestRows,
activities,
checkpointRows,
latestTurnRow,
@@ -3144,6 +3367,14 @@ pending_approval_requests AS (
),
),
),
listThreadPullRequestRowsByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listPullRequests:query",
"ProjectionSnapshotQuery.getThreadDetailById:listPullRequests:decodeRows",
),
),
),
activitiesEffect,
listCheckpointRowsByThread({ threadId }).pipe(
Effect.mapError(
@@ -3184,10 +3415,15 @@ pending_approval_requests AS (
interactionMode: threadRow.value.interactionMode,
branch: threadRow.value.branch,
worktreePath: threadRow.value.worktreePath,
...mapThreadPullRequests(
pullRequestRows.map(mapPullRequestRow),
threadRow.value.projectId,
pullRequestRows.length === 0
? null
: Option.getOrNull(yield* getProjectShellById(threadRow.value.projectId))
?.repositoryIdentity,
),
branchPullRequest: threadRow.value.branchPullRequest,
...(threadRow.value.linkedPullRequest === null
? {}
: { linkedPullRequest: threadRow.value.linkedPullRequest }),
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
createdAt: threadRow.value.createdAt,
updatedAt: threadRow.value.updatedAt,
@@ -0,0 +1,704 @@
import {
ProjectId,
ProviderInstanceId,
PullRequestOperationError,
ThreadId,
type OrchestrationCommand,
type OrchestrationProjectShell,
type OrchestrationShellSnapshot,
type OrchestrationThreadShell,
type PullRequestRef,
type PullRequestStack,
type PullRequestSummary,
type ThreadPullRequestLink,
type ThreadPullRequestSnapshot,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { PullRequestService } from "../pullRequest/PullRequestService.ts";
import { ServerActivation } from "../serverActivation.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
import * as PullRequestSyncReactor from "./PullRequestSyncReactor.ts";
const NOW = "2026-08-28T12:00:00.000Z";
const PROJECT_ID = ProjectId.make("sync-project");
type SyncCommand = Extract<
OrchestrationCommand,
{ readonly type: "thread.pull-request-link.sync" }
>;
type LinkCommand = Extract<OrchestrationCommand, { readonly type: "thread.pull-request.link" }>;
const testCrypto = Crypto.make({
randomBytes: (size) => new Uint8Array(size).fill(1),
digest: (_algorithm, data) => Effect.succeed(data),
});
function makeProject(id: ProjectId = PROJECT_ID): OrchestrationProjectShell {
return {
id,
title: `Project ${id}`,
workspaceRoot: "/workspace/project",
defaultModelSelection: null,
scripts: [],
createdAt: "2026-08-01T00:00:00.000Z",
updatedAt: NOW,
};
}
function makeThread(
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: null,
worktreePath: null,
pullRequests: [],
latestTurn: null,
createdAt: "2026-08-01T00:00:00.000Z",
updatedAt: "2026-08-20T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: "2026-08-20T00:00:00.000Z",
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...overrides,
};
}
function makeLink(
number: number,
snapshot: Partial<ThreadPullRequestSnapshot> | null = null,
overrides: Partial<ThreadPullRequestLink> = {},
): ThreadPullRequestLink {
return {
host: "github.com",
repository: "owner/repository",
number,
url: `https://github.com/owner/repository/pull/${number}`,
source: "manual",
linkedAt: "2026-08-10T00:00:00.000Z",
snapshot:
snapshot === null
? null
: {
state: "open",
title: "Pull request",
headBranch: "feature",
baseBranch: "main",
isDraft: false,
updatedAt: "2026-08-27T00:00:00.000Z",
syncedAt: "2026-08-27T00:00:00.000Z",
...snapshot,
},
stack: null,
...overrides,
};
}
function makeSnapshot(
threads: ReadonlyArray<OrchestrationThreadShell>,
snapshotSequence = 1,
): OrchestrationShellSnapshot {
return {
snapshotSequence,
projects: [makeProject()],
threads,
updatedAt: NOW,
};
}
function makeSummary(
input: PullRequestRef,
overrides: Partial<PullRequestSummary> = {},
): PullRequestSummary {
return {
provider: "github",
projectId: input.projectId,
repository: input.repository,
number: input.number,
title: "Pull request",
url: `https://github.com/${input.repository}/pull/${input.number}`,
state: "open",
headBranch: "feature",
baseBranch: "main",
updatedAt: "2026-08-27T00:00:00.000Z",
...overrides,
};
}
interface HarnessOptions {
readonly invalidate?: PullRequestService["Service"]["invalidate"];
readonly snapshot: OrchestrationShellSnapshot;
readonly summary?: (
input: PullRequestRef,
) => Effect.Effect<PullRequestSummary, PullRequestOperationError>;
readonly stack?: (
input: PullRequestRef,
) => Effect.Effect<PullRequestStack | null, PullRequestOperationError>;
}
const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options: HarnessOptions) {
const activation = yield* Deferred.make<void>();
const snapshots = yield* Ref.make(options.snapshot);
const snapshotReads = yield* Queue.unbounded<void>();
const syncCommands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
const linkCommands = yield* Ref.make<ReadonlyArray<LinkCommand>>([]);
const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
const stackCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
const summary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
Effect.gen(function* () {
assert.strictEqual(readOptions?.recoverTransientFailure, false);
yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
return yield* options.summary?.(input) ?? Effect.succeed(makeSummary(input));
});
const stack: PullRequestService["Service"]["stack"] = (input) =>
Effect.gen(function* () {
yield* Ref.update(stackCalls, (calls) => [...calls, input]);
return yield* options.stack?.(input) ?? Effect.succeed(null);
});
const dispatch: OrchestrationEngineShape["dispatch"] = (command) => {
if (command.type === "thread.pull-request-link.sync") {
return Ref.update(syncCommands, (recorded) => [...recorded, command]).pipe(
Effect.as({ sequence: 1 }),
);
}
if (command.type === "thread.pull-request.link") {
return Ref.update(linkCommands, (recorded) => [...recorded, command]).pipe(
Effect.as({ sequence: 1 }),
);
}
return Effect.die(new Error(`Unexpected command: ${command.type}`));
};
const dependencies = Layer.mergeAll(
Layer.mock(ProjectionSnapshotQuery)({
getShellSnapshot: () =>
Queue.offer(snapshotReads, undefined).pipe(Effect.andThen(Ref.get(snapshots))),
}),
Layer.mock(PullRequestService)({
summary,
stack,
invalidate: options.invalidate ?? (() => Effect.void),
}),
Layer.mock(OrchestrationEngineService)({
readEvents: () => Stream.empty,
dispatch,
streamDomainEvents: Stream.empty,
latestSequence: Effect.succeed(0),
}),
Layer.succeed(ServerActivation, Deferred.await(activation)),
Layer.succeed(Crypto.Crypto, testCrypto),
);
return {
activation,
snapshots,
snapshotReads,
syncCommands,
linkCommands,
summaryCalls,
stackCalls,
layer: PullRequestSyncReactor.layer.pipe(Layer.provide(dependencies)),
};
});
type Harness = Effect.Success<ReturnType<typeof makeHarness>>;
const startAndSweep = Effect.fn("startPullRequestSyncHarness")(function* (fixture: Harness) {
const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor;
yield* reactor.start();
yield* Deferred.succeed(fixture.activation, undefined);
yield* Queue.take(fixture.snapshotReads);
yield* reactor.drain;
return reactor;
});
const sweepAgain = Effect.fn("sweepPullRequestSyncHarness")(function* (
fixture: Harness,
reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"],
) {
yield* TestClock.adjust("1 minute");
yield* Queue.take(fixture.snapshotReads);
yield* reactor.drain;
});
/** What the reactor would have persisted, so the next sweep sees its own writes. */
function applySync(
snapshot: OrchestrationShellSnapshot,
commands: ReadonlyArray<SyncCommand>,
): OrchestrationShellSnapshot {
return {
...snapshot,
snapshotSequence: snapshot.snapshotSequence + 1,
threads: snapshot.threads.map((thread) => ({
...thread,
pullRequests: thread.pullRequests.map((link) => {
const command = commands.findLast(
(candidate) => candidate.threadId === thread.id && candidate.number === link.number,
);
return command === undefined
? link
: { ...link, snapshot: command.snapshot, stack: command.stack };
}),
})),
};
}
describe("PullRequestSyncReactor", () => {
it.effect("retries a failed stack read after the summary becomes terminal", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
let attempts = 0;
const nativeStack: PullRequestStack = {
id: "stack",
number: 7,
url: "https://github.com/owner/repository/stacks/7",
base: "main",
layers: [{ number: 7, headBranch: "feature", state: "merged" }],
};
const fixture = yield* makeHarness({
snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7)] })]),
summary: (input) =>
Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
stack: () =>
++attempts === 1
? Effect.fail(
new PullRequestOperationError({
operation: "stack",
detail: "temporary failure",
}),
)
: Effect.succeed(nativeStack),
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
const commands = yield* Ref.get(fixture.syncCommands);
yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
yield* sweepAgain(fixture, reactor);
assert.strictEqual(attempts, 2);
assert.deepStrictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.stack, {
kind: "native",
...nativeStack,
});
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("explicit refresh reads a changed stack even when its PR summary is unchanged", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fixture = yield* makeHarness({
snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, {})] })]),
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 0);
yield* reactor.requestSync({
host: "github.com",
repository: "owner/repository",
number: 7,
});
yield* Queue.take(fixture.snapshotReads);
yield* reactor.drain;
assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("snapshots an unsynced link once and writes it to the thread", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fixture = yield* makeHarness({
snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
summary: (input) =>
Effect.succeed(makeSummary(input, { title: "Ship it", isDraft: true })),
});
yield* Effect.gen(function* () {
yield* startAndSweep(fixture);
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
{
projectId: PROJECT_ID,
host: "github.com",
repository: "owner/repository",
number: 42,
},
]);
assert.deepStrictEqual(
(yield* Ref.get(fixture.syncCommands)).map(({ commandId: _, ...rest }) => rest),
[
{
type: "thread.pull-request-link.sync",
threadId: ThreadId.make("one"),
host: "github.com",
repository: "owner/repository",
number: 42,
snapshot: {
state: "open",
title: "Ship it",
headBranch: "feature",
baseBranch: "main",
isDraft: true,
updatedAt: "2026-08-27T00:00:00.000Z",
syncedAt: NOW,
closedAt: null,
mergedAt: null,
},
stack: null,
},
],
);
assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("asks the host once for a pull request shared by two threads", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("one", { pullRequests: [makeLink(42)] }),
makeThread("two", {
pullRequests: [makeLink(42, null, { repository: "Owner/Repository" })],
}),
]),
});
yield* Effect.gen(function* () {
yield* startAndSweep(fixture);
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
const commands = yield* Ref.get(fixture.syncCommands);
assert.deepStrictEqual(
commands
.map((command) => [command.threadId, command.repository] as const)
.sort((left, right) => left[0].localeCompare(right[0])),
[
[ThreadId.make("one"), "owner/repository"],
[ThreadId.make("two"), "Owner/Repository"],
],
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("dispatches nothing when the host snapshot is unchanged", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fixture = yield* makeHarness({
snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
const firstSweep = yield* Ref.get(fixture.syncCommands);
assert.strictEqual(firstSweep.length, 1);
yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
yield* sweepAgain(fixture, reactor);
// Still open on an active thread, so the host was asked again, but nothing changed.
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("refreshes closed links through the reactor's project after reopening elsewhere", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const stale = yield* Ref.make(true);
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("first", { pullRequests: [makeLink(42, { state: "closed" })] }),
makeThread("second", {
projectId: ProjectId.make("second-project"),
pullRequests: [makeLink(42, { state: "closed" })],
}),
]),
invalidate: ({ reference }) =>
reference?.projectId === makeProject().id && reference.host === "github.com"
? Ref.set(stale, false)
: Effect.void,
summary: (input) =>
Ref.get(stale).pipe(
Effect.map((cached) => makeSummary(input, { state: cached ? "closed" : "open" })),
),
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
yield* reactor.requestSync({
host: "github.com",
repository: "owner/repository",
number: 42,
});
yield* Queue.take(fixture.snapshotReads);
yield* reactor.drain;
const commands = yield* Ref.get(fixture.syncCommands);
yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
const snapshot = yield* Ref.get(fixture.snapshots);
assert.deepStrictEqual(
snapshot.threads.map((thread) => thread.pullRequests[0]?.snapshot?.state),
["open", "open"],
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("stops asking the host once a pull request is merged", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("merged", { pullRequests: [makeLink(1, { state: "merged" })] }),
]),
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
yield* sweepAgain(fixture, reactor);
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
yield* reactor.requestSync({
host: "github.com",
repository: "owner/repository",
number: 1,
});
yield* Queue.take(fixture.snapshotReads);
yield* reactor.drain;
assert.deepStrictEqual(
(yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
[1],
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("discovers externally reopened pull requests after fifteen minutes", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const state = yield* Ref.make<"closed" | "open">("closed");
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
]),
summary: (input) =>
Ref.get(state).pipe(Effect.map((state) => makeSummary(input, { state }))),
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
yield* Ref.set(state, "open");
for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
yield* sweepAgain(fixture, reactor);
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("preserves a refresh requested while an older host read is in flight", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const reading = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
let calls = 0;
const fixture = yield* makeHarness({
snapshot: makeSnapshot([]),
summary: (input) =>
Effect.gen(function* () {
calls += 1;
if (calls === 1) {
yield* Deferred.succeed(reading, undefined);
yield* Deferred.await(release);
}
return makeSummary(input, { state: calls === 1 ? "closed" : "open" });
}),
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
yield* Ref.set(
fixture.snapshots,
makeSnapshot([
makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
]),
);
const key = { host: "github.com", repository: "owner/repository", number: 2 };
yield* reactor.requestSync(key);
yield* Deferred.await(reading);
yield* reactor.requestSync(key);
yield* Deferred.succeed(release, undefined);
yield* reactor.drain;
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("polls open pull requests on settled threads every fifteen minutes", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("settled", {
settledOverride: "settled",
settledAt: "2026-08-21T00:00:00.000Z",
pullRequests: [makeLink(5, { state: "open" })],
}),
]),
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
yield* sweepAgain(fixture, reactor);
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
for (let index = 0; index < 13; index += 1) yield* sweepAgain(fixture, reactor);
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
yield* sweepAgain(fixture, reactor);
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("auto-links missing native stack layers and leaves dismissed ones alone", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const stack: PullRequestStack = {
id: "stack-1",
number: 42,
url: "https://github.com/owner/repository/stack/1",
base: "main",
layers: [
{ number: 41, headBranch: "layer-1", state: "merged" },
{ number: 42, headBranch: "layer-2", state: "open" },
{ number: 43, headBranch: "layer-3", state: "open" },
],
};
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("one", {
pullRequests: [
makeLink(42),
makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
],
}),
]),
stack: () => Effect.succeed(stack),
});
yield* Effect.gen(function* () {
yield* startAndSweep(fixture);
const syncCommands = yield* Ref.get(fixture.syncCommands);
assert.deepStrictEqual(
syncCommands.map((command) => [command.number, command.stack] as const),
[[42, { kind: "native", ...stack }]],
);
assert.deepStrictEqual(
(yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest),
[
{
type: "thread.pull-request.link",
threadId: ThreadId.make("one"),
host: "github.com",
repository: "owner/repository",
number: 43,
url: "https://github.com/owner/repository/pull/43",
source: "stack",
},
],
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("keeps existing snapshots and continues when the host fails", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }),
makeThread("fine", { pullRequests: [makeLink(8)] }),
]),
summary: (input) =>
input.number === 7
? Effect.fail(
new PullRequestOperationError({ operation: "summary", detail: "host down" }),
)
: Effect.succeed(makeSummary(input)),
});
yield* Effect.gen(function* () {
yield* startAndSweep(fixture);
assert.deepStrictEqual(
(yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
[8],
);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
});
@@ -0,0 +1,328 @@
import { siblingPullRequestUrl } from "@t3tools/shared/changeRequestUrl";
import {
CommandId,
type OrchestrationThreadShell,
type PullRequestSummary,
type ThreadPullRequestKey,
type ThreadPullRequestLink,
type ThreadPullRequestSnapshot,
type ThreadPullRequestStack,
} from "@t3tools/contracts";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import {
threadPullRequestKeyOf,
threadPullRequestKeysEqual,
visibleThreadPullRequests,
} from "@t3tools/shared/threadPullRequests";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schedule from "effect/Schedule";
import type * as Scope from "effect/Scope";
import * as PullRequestService from "../pullRequest/PullRequestService.ts";
import { forkParked } from "../serverActivation.ts";
import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
interface LinkEntry {
readonly thread: OrchestrationThreadShell;
readonly link: ThreadPullRequestLink;
}
function snapshotFieldsOf(summary: PullRequestSummary): SnapshotFields {
return {
state: summary.state,
title: summary.title,
headBranch: summary.headBranch,
baseBranch: summary.baseBranch,
isDraft: summary.isDraft ?? false,
updatedAt: summary.updatedAt,
closedAt: summary.closedAt ?? null,
mergedAt: summary.mergedAt ?? null,
...(summary.author === undefined ? {} : { author: summary.author }),
...(summary.additions === undefined ? {} : { additions: summary.additions }),
...(summary.deletions === undefined ? {} : { deletions: summary.deletions }),
...(summary.changedFiles === undefined ? {} : { changedFiles: summary.changedFiles }),
...(summary.reviewDecision === undefined ? {} : { reviewDecision: summary.reviewDecision }),
...(summary.checksState === undefined ? {} : { checksState: summary.checksState }),
...(summary.mergeability === undefined ? {} : { mergeability: summary.mergeability }),
};
}
function snapshotFieldsEqual(left: SnapshotFields, right: SnapshotFields): boolean {
return (
left.state === right.state &&
left.title === right.title &&
left.headBranch === right.headBranch &&
left.baseBranch === right.baseBranch &&
left.isDraft === right.isDraft &&
left.updatedAt === right.updatedAt &&
(left.closedAt ?? null) === (right.closedAt ?? null) &&
(left.mergedAt ?? null) === (right.mergedAt ?? null) &&
(left.author?.login ?? null) === (right.author?.login ?? null) &&
(left.author?.avatarUrl ?? null) === (right.author?.avatarUrl ?? null) &&
left.additions === right.additions &&
left.deletions === right.deletions &&
left.changedFiles === right.changedFiles &&
(left.reviewDecision ?? null) === (right.reviewDecision ?? null) &&
(left.checksState ?? null) === (right.checksState ?? null) &&
left.mergeability === right.mergeability
);
}
function stacksEqual(
left: ThreadPullRequestStack | null,
right: ThreadPullRequestStack | null,
): boolean {
if (left === null || right === null) return left === right;
return (
left.kind === right.kind &&
left.id === right.id &&
left.number === right.number &&
left.url === right.url &&
left.base === right.base &&
left.layers.length === right.layers.length &&
left.layers.every((layer, index) => {
const other = right.layers[index]!;
return (
layer.number === other.number &&
layer.headBranch === other.headBranch &&
layer.state === other.state
);
})
);
}
function isUnsettled(thread: OrchestrationThreadShell): boolean {
return thread.settledOverride !== "settled" && thread.settledAt === null;
}
/**
* Keeps every thread ↔ pull request link's host snapshot current. One sweep a minute reads
* the shell snapshot, groups visible links by pull request so the host is asked once per PR
* no matter how many threads share it, and writes back only what changed. Native stacks the
* host reports are auto-linked to the thread as `source: "stack"`.
*/
export class PullRequestSyncReactor extends Context.Service<
PullRequestSyncReactor,
{
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
readonly drain: Effect.Effect<void>;
/** Force the next sweep to re-read this pull request, even when its snapshot is terminal. */
readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
}
>()("t3/orchestration/PullRequestSyncReactor") {}
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const pullRequests = yield* PullRequestService.PullRequestService;
const crypto = yield* Crypto.Crypto;
const lastSyncedAt = new Map<string, number>();
const requested = new Map<string, number>();
let requestGeneration = 0;
const retryStacks = new Set<string>();
const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
if (requested.has(key) || retryStacks.has(key)) return true;
if (entries.some((entry) => entry.link.snapshot === null)) return true;
if (entries.every((entry) => entry.link.snapshot?.state === "merged")) return false;
if (entries.some((entry) => entry.link.snapshot?.state === "open" && isUnsettled(entry.thread)))
return true;
// Closed requests can reopen on the host, including after the thread settles.
const last = lastSyncedAt.get(key);
return last === undefined || nowMs - last >= SLOW_SYNC_INTERVAL_MS;
};
const logSkipped =
(message: string, fields: Record<string, unknown>) =>
<E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* () {
const snapshot = yield* snapshots.getShellSnapshot();
const now = yield* DateTime.now;
const nowMs = DateTime.toEpochMillis(now);
const nowIso = DateTime.formatIso(now);
const groups = new Map<string, Array<LinkEntry>>();
for (const thread of snapshot.threads) {
if (thread.archivedAt !== null) continue;
for (const link of visibleThreadPullRequests(thread.pullRequests)) {
const key = threadPullRequestKeyOf(link);
const entries = groups.get(key) ?? [];
entries.push({ thread, link });
groups.set(key, entries);
}
}
for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
// Layers auto-linked this sweep, so two links of one thread that share a
// stack do not both try to add the same sibling.
const linkedThisSweep = new Set<string>();
const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
entry: LinkEntry,
fields: SnapshotFields,
fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
) {
const { thread, link } = entry;
const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
const changed =
link.snapshot === null ||
!snapshotFieldsEqual(link.snapshot, fields) ||
!stacksEqual(link.stack, nextStack);
if (changed) {
const uuid = yield* crypto.randomUUIDv4;
yield* engine.dispatch({
type: "thread.pull-request-link.sync",
commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
threadId: thread.id,
host: link.host,
repository: link.repository,
number: link.number,
snapshot: { ...fields, syncedAt: nowIso },
stack: nextStack,
});
}
if (fetchedStack === null || fetchedStack.stack === null) return;
for (const layer of fetchedStack.stack.layers) {
const layerKey = { host: link.host, repository: link.repository, number: layer.number };
const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
if (linkedThisSweep.has(dedupeKey)) continue;
// Tombstones count as present: a dismissed layer is never re-added.
if (
thread.pullRequests.some((existing) => threadPullRequestKeysEqual(existing, layerKey))
) {
continue;
}
const url = siblingPullRequestUrl(link.url, layer.number);
if (url === null) continue;
linkedThisSweep.add(dedupeKey);
const uuid = yield* crypto.randomUUIDv4;
yield* engine
.dispatch({
type: "thread.pull-request.link",
commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
threadId: thread.id,
...layerKey,
url,
source: "stack",
})
.pipe(
Effect.catchCause(
logSkipped("pull request stack layer link skipped", {
threadId: thread.id,
number: layer.number,
}),
),
);
}
});
const syncGroup = Effect.fn("PullRequestSyncReactor.syncGroup")(function* (
key: string,
entries: ReadonlyArray<LinkEntry>,
) {
const first = entries[0]!;
const ref = {
projectId: first.thread.projectId,
host: first.link.host,
repository: first.link.repository,
number: first.link.number,
};
const generation = requested.get(key);
if (generation !== undefined) yield* pullRequests.invalidate({ reference: ref });
const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
const fields = snapshotFieldsOf(summary);
const needsStack =
generation !== undefined ||
retryStacks.has(key) ||
entries.some(
(entry) =>
entry.link.snapshot === null || !snapshotFieldsEqual(entry.link.snapshot, fields),
);
const fetchedStack = needsStack
? yield* pullRequests.stack(ref).pipe(
Effect.map((stack) => ({
stack: stack === null ? null : ({ kind: "native", ...stack } as const),
})),
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(cause)
: Effect.logWarning("pull request stack lookup failed", {
key,
}).pipe(Effect.as(null)),
),
)
: null;
if (needsStack) {
if (fetchedStack === null) retryStacks.add(key);
else retryStacks.delete(key);
}
// The host answered, so the cadence clock ticks even if a dispatch below is rejected.
lastSyncedAt.set(key, nowMs);
// A refresh requested while the host read was in flight belongs to the next sweep.
if (requested.get(key) === generation) requested.delete(key);
yield* Effect.forEach(
entries,
(entry) =>
syncEntry(entry, fields, fetchedStack).pipe(
Effect.catchCause(
logSkipped("pull request sync skipped", { threadId: entry.thread.id, key }),
),
),
{ discard: true },
);
});
yield* Effect.forEach(
groups,
([key, entries]) =>
isDue(key, entries, nowMs)
? syncGroup(key, entries).pipe(
Effect.catchCause(logSkipped("pull request sync skipped", { key })),
)
: Effect.void,
{ concurrency: 8, discard: true },
);
});
const worker = yield* makeDrainableWorker(() =>
sweep().pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
);
const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
"PullRequestSyncReactor.start",
)(function* () {
yield* forkParked(
Effect.gen(function* () {
yield* worker.enqueue(undefined);
yield* worker.drain;
}).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
);
});
const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
Effect.suspend(() => {
requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
return worker.enqueue(undefined);
});
return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
});
export const layer = Layer.effect(PullRequestSyncReactor, make);
+6
View File
@@ -16,6 +16,9 @@ import {
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
ThreadPinReorderedPayload as ContractsThreadPinReorderedPayloadSchema,
ThreadPullRequestLinkedPayload as ContractsThreadPullRequestLinkedPayloadSchema,
ThreadPullRequestUnlinkedPayload as ContractsThreadPullRequestUnlinkedPayloadSchema,
ThreadPullRequestSyncedPayload as ContractsThreadPullRequestSyncedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -48,6 +51,9 @@ export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
export const ThreadPinReorderedPayload = ContractsThreadPinReorderedPayloadSchema;
export const ThreadPullRequestLinkedPayload = ContractsThreadPullRequestLinkedPayloadSchema;
export const ThreadPullRequestUnlinkedPayload = ContractsThreadPullRequestUnlinkedPayloadSchema;
export const ThreadPullRequestSyncedPayload = ContractsThreadPullRequestSyncedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -87,6 +87,7 @@ function thread(
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
pullRequests: [],
branch: "feature",
worktreePath: null,
latestTurn: null,
@@ -1,3 +1,7 @@
import {
canonicalRepositoryKey,
sourceControlRepositorySelector,
} from "@t3tools/shared/sourceControl";
import {
CommandId,
type OrchestrationEvent,
@@ -53,18 +57,6 @@ interface RefreshRequest {
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,
@@ -138,7 +130,7 @@ export const make = Effect.gen(function* () {
const first = group[0]!;
const project = projects.get(first.projectId);
if (project === undefined) return finishBackfill(group);
const repository = PullRequestService.repositoryIdentityOf(project);
const repository = sourceControlRepositorySelector(project.repositoryIdentity);
if (first.branch !== null && repository === null) return finishBackfill(group);
const worktreeExists =
first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
@@ -189,6 +181,7 @@ export const make = Effect.gen(function* () {
let replacement: ThreadLinkedPullRequest | undefined;
if (
thread.pullRequests.length === 0 &&
thread.linkedPullRequest != null &&
detected?.state === "open" &&
detectedReference !== null &&
@@ -5,6 +5,7 @@ import {
ProjectId,
TurnId,
type OrchestrationThreadShell,
type ThreadPullRequestLink,
} from "@t3tools/contracts";
import { type SettlementPullRequest, resolveAutoSettlementAt } from "./ThreadSettlementPolicy.ts";
@@ -18,6 +19,7 @@ const makeThread = (
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
pullRequests: [],
branch: "feature",
worktreePath: "/repo",
latestTurn: null,
@@ -213,3 +215,75 @@ describe("resolveAutoSettlementAt", () => {
).toBe(true);
});
});
function linkedRequest(
number: number,
snapshot: ThreadPullRequestLink["snapshot"],
): ThreadPullRequestLink {
return {
host: "github.com",
repository: "org/repo",
number,
url: `https://github.com/org/repo/pull/${number}`,
source: "manual",
linkedAt: NOW,
stack: null,
snapshot,
};
}
const terminalSnapshot = (
state: "closed" | "merged",
terminalAt: string,
updatedAt = terminalAt,
) => ({
state,
title: "Change",
headBranch: "feature",
baseBranch: "main",
isDraft: false,
closedAt: terminalAt,
mergedAt: state === "merged" ? terminalAt : null,
updatedAt,
syncedAt: NOW,
});
describe("linked request settlement", () => {
it.each(["closed", "merged"] as const)(
"uses the latest actual %s transition despite later comments on another PR",
(state) => {
const old = linkedRequest(1, terminalSnapshot(state, "2026-08-19T00:00:00.000Z", NOW));
const recent = linkedRequest(2, terminalSnapshot(state, "2026-08-21T00:00:00.000Z"));
expect(decide(makeThread({ pullRequests: [old, recent] }), null, { days: null })).toBe(true);
expect(decide(makeThread({ pullRequests: [recent, old] }), null, { days: null })).toBe(true);
expect(decide(makeThread({ pullRequests: [old] }), null, { days: null })).toBe(false);
},
);
it("keeps unknown and open links active even after the inactivity window", () => {
const merged = linkedRequest(1, terminalSnapshot("merged", NOW));
const unknown = linkedRequest(2, null);
const open = linkedRequest(3, {
...terminalSnapshot("closed", NOW),
state: "open",
closedAt: null,
});
expect(decide(makeThread({ pullRequests: [merged, unknown] }))).toBe(false);
expect(decide(makeThread({ pullRequests: [merged, open] }))).toBe(false);
expect(
decide(makeThread({ pullRequests: [merged, { ...unknown, source: "stack-dismissed" }] })),
).toBe(true);
});
it("honors merge settings and ignores missing terminal timestamps", () => {
const merged = linkedRequest(1, terminalSnapshot("merged", NOW));
expect(decide(makeThread({ pullRequests: [merged] }), null, { days: null, merge: false })).toBe(
false,
);
const missing = linkedRequest(2, { ...terminalSnapshot("merged", NOW), mergedAt: null });
expect(decide(makeThread({ pullRequests: [missing] }), null, { days: null })).toBe(false);
expect(decide(makeThread({ pullRequests: [missing, merged] }), null, { days: null })).toBe(
true,
);
});
});
@@ -1,4 +1,5 @@
import type { OrchestrationThreadShell } from "@t3tools/contracts";
import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
export interface SettlementPullRequest {
readonly state: "open" | "closed" | "merged";
@@ -72,7 +73,29 @@ export function resolveAutoSettlementAt(input: {
readonly autoSettleAfterDays: number | null;
readonly autoSettleOnMerge: boolean;
}): string | null {
const { thread, pullRequest } = input;
const { thread } = input;
let pullRequest = input.pullRequest;
const links = visibleThreadPullRequests(thread.pullRequests);
if (links.some((link) => link.snapshot === null || link.snapshot.state === "open")) return null;
if (links.length > 0) {
const terminalTimestamp = (link: (typeof links)[number]) => {
const snapshot = link.snapshot;
const value = snapshot?.state === "merged" ? snapshot.mergedAt : snapshot?.closedAt;
const timestamp = Date.parse(value ?? "");
return Number.isNaN(timestamp) ? Number.NEGATIVE_INFINITY : timestamp;
};
const latest = links.reduce((current, candidate) =>
terminalTimestamp(candidate) > terminalTimestamp(current) ? candidate : current,
);
pullRequest =
latest.snapshot === null
? null
: {
state: latest.snapshot.state,
mergedAt: latest.snapshot.mergedAt ?? null,
closedAt: latest.snapshot.closedAt ?? null,
};
}
if (!isAutoSettlementCandidate(thread, input.now)) return null;
const activityAt = latestTimestamp([
thread.latestUserMessageAt,
@@ -80,6 +80,7 @@ function makeThread(
},
runtimeMode: "full-access",
interactionMode: "default",
pullRequests: [],
branch: null,
worktreePath: null,
latestTurn: null,
@@ -301,6 +302,57 @@ const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
});
describe("ThreadSettlementReactor", () => {
it.effect(
"settles all-terminal links from snapshots and keeps open or unsynced links active",
() =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const link = (number: number, state: "open" | "merged" | null) => ({
host: "example.test",
repository: "owner/repository",
number,
url: `https://example.test/owner/repository/pull/${number}`,
source: "manual" as const,
linkedAt: NOW,
stack: null,
snapshot:
state === null
? null
: {
state,
title: "Review",
headBranch: "feature",
baseBranch: "main",
isDraft: false,
updatedAt: NOW,
syncedAt: NOW,
mergedAt: state === "merged" ? NOW : null,
},
});
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("merged", { pullRequests: [link(1, "merged"), link(2, "merged")] }),
makeThread("open", { pullRequests: [link(1, "merged"), link(2, "open")] }),
makeThread("unsynced", { pullRequests: [link(1, "merged"), link(2, null)] }),
]),
settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleOnMerge: true },
branchPullRequest: () => Effect.die("linked threads must not query the branch"),
pullRequestSummary: () => Effect.die("linked threads must use their snapshots"),
});
yield* Effect.gen(function* () {
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
assert.deepStrictEqual(
(yield* Ref.get(fixture.commands)).map(({ threadId }) => threadId),
[ThreadId.make("merged")],
);
assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("uses saved PRs without settling resumed threads or branches with newer PRs", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -103,7 +103,9 @@ export const make = Effect.gen(function* () {
{
concurrency: 8,
},
)).filter((thread) => thread !== null);
))
.filter((thread) => thread !== null)
.filter((thread) => !thread.pullRequests.some((link) => link.source !== "stack-dismissed"));
// Use the same cwd as PR discovery so both paths share GitManager's cache.
const lookupCwdByThreadId = new Map<string, string>();
@@ -59,6 +59,7 @@ const readModel: OrchestrationReadModel = {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
pullRequests: [],
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -84,6 +85,7 @@ const readModel: OrchestrationReadModel = {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
pullRequests: [],
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -33,6 +33,7 @@ function makeReadModel(overrides: Partial<OrchestrationThread> = {}): Orchestrat
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
pullRequests: [],
branch: null,
worktreePath: null,
latestTurn: null,
@@ -36,6 +36,7 @@ function makeReadModel(input: {
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
@@ -0,0 +1,532 @@
import {
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
OrchestrationEvent,
OrchestrationCommand,
type OrchestrationReadModel,
type ThreadPullRequestLink,
type ThreadPullRequestSnapshot,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { decideOrchestrationCommand } from "./decider.ts";
import { projectEvent } from "./projector.ts";
import { isThreadDetailEvent } from "../ws.ts";
const decodeCommand = Schema.decodeUnknownEffect(OrchestrationCommand);
type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
function expectSingleEvent<Type extends OrchestrationEvent["type"]>(
decided: PlannedEvent | ReadonlyArray<PlannedEvent>,
type: Type,
): Omit<Extract<OrchestrationEvent, { type: Type }>, "sequence"> {
const event = Array.isArray(decided) ? decided[0] : (decided as PlannedEvent);
if (event === undefined || event.type !== type) {
throw new Error(`expected ${type}, got ${String(event?.type)}`);
}
return event as Omit<Extract<OrchestrationEvent, { type: Type }>, "sequence">;
}
const NOW = "2026-01-01T00:00:00.000Z";
const THREAD_ID = ThreadId.make("thread-1");
function makeLink(overrides: Partial<ThreadPullRequestLink> = {}): ThreadPullRequestLink {
return {
host: "github.com",
repository: "t3tools/t3code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
source: "manual",
linkedAt: NOW,
snapshot: null,
stack: null,
...overrides,
};
}
function makeReadModel(pullRequests: ReadonlyArray<ThreadPullRequestLink>): OrchestrationReadModel {
return {
snapshotSequence: 0,
projects: [
{
id: ProjectId.make("project-1"),
title: "Project",
workspaceRoot: "/repo",
defaultModelSelection: null,
scripts: [],
createdAt: NOW,
updatedAt: NOW,
deletedAt: null,
repositoryIdentity: {
canonicalKey: "github.com/t3tools/t3code",
provider: "github",
displayName: "t3tools/t3code",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/t3tools/t3code.git",
},
},
},
],
threads: [
{
id: THREAD_ID,
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests,
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: NOW,
};
}
const snapshot: ThreadPullRequestSnapshot = {
state: "open",
title: "Add links",
headBranch: "feat/links",
baseBranch: "main",
isDraft: false,
updatedAt: NOW,
syncedAt: NOW,
};
it.layer(NodeServices.layer)("pull request link decider", (it) => {
it.effect("legacy unlink cannot remove a newer cross-host link", () =>
Effect.gen(function* () {
const own = makeLink();
const foreign = makeLink({
host: "github.enterprise.test",
url: "https://github.enterprise.test/t3tools/t3code/pull/42",
linkedAt: "2026-01-02T00:00:00Z",
});
const command = yield* decodeCommand({
type: "thread.meta.update",
commandId: "unlink",
threadId: THREAD_ID,
linkedPullRequest: null,
});
const decided = yield* decideOrchestrationCommand({
readModel: makeReadModel([own, foreign]),
command,
});
const event = expectSingleEvent(decided, "thread.pull-request-unlinked");
expect(event.payload.host).toBe("github.com");
}),
);
it.effect("legacy replacement preserves unrelated manual links", () =>
Effect.gen(function* () {
const other = makeLink({ number: 7, snapshot: { ...snapshot, state: "merged" } });
const current = makeLink({ linkedAt: "2026-01-02T00:00:00Z" });
let model = makeReadModel([other, current]);
const command = yield* decodeCommand({
type: "thread.meta.update",
commandId: "replace",
threadId: THREAD_ID,
linkedPullRequest: {
projectId: "project-1",
repository: "t3tools/t3code",
number: 99,
url: "https://github.com/t3tools/t3code/pull/99",
},
});
const decided = yield* decideOrchestrationCommand({ readModel: model, command });
const events = Array.isArray(decided) ? decided : [decided];
expect(events.map((event) => event.type)).toEqual([
"thread.pull-request-unlinked",
"thread.pull-request-linked",
]);
for (const event of events)
model = yield* projectEvent(model, { ...event, sequence: model.snapshotSequence + 1 });
expect(model.threads[0]!.pullRequests.map((link) => link.number)).toEqual([7, 99]);
}),
);
it.effect("round-trips an Azure legacy link and unlinks only its organization", () =>
Effect.gen(function* () {
const foreign = makeLink({
host: "dev.azure.com",
repository: "org-b/project/_git/web",
number: 7,
url: "https://dev.azure.com/org-b/project/_git/web/pullrequest/7",
});
let model = makeReadModel([foreign]);
model = {
...model,
projects: model.projects.map((project) => ({
...project,
repositoryIdentity: {
...project.repositoryIdentity!,
provider: "azure-devops",
canonicalKey: "ssh.dev.azure.com/v3/org-a/project/web",
displayName: "v3/org-a/project/web",
name: "web",
},
})),
};
const legacy = {
projectId: "project-1",
repository: "web",
number: 7,
url: "https://dev.azure.com/org-a/project/_git/web/pullrequest/7",
};
for (const linkedPullRequest of [legacy, null]) {
const command = yield* decodeCommand({
type: "thread.meta.update",
commandId: linkedPullRequest === null ? "unlink-azure" : "link-azure",
threadId: THREAD_ID,
linkedPullRequest,
});
const decided = yield* decideOrchestrationCommand({ readModel: model, command });
for (const event of Array.isArray(decided) ? decided : [decided]) {
model = yield* projectEvent(model, { ...event, sequence: model.snapshotSequence + 1 });
}
if (linkedPullRequest !== null) {
expect(model.threads[0]!.linkedPullRequest).toEqual(legacy);
expect(model.threads[0]!.pullRequests.map((link) => link.repository)).toEqual([
"org-b/project/_git/web",
"org-a/project/_git/web",
]);
}
}
expect(model.threads[0]!.pullRequests).toEqual([foreign]);
expect(model.threads[0]!.linkedPullRequest).toBeNull();
}),
);
it.effect("legacy unlink alone does not emit an empty metadata event", () =>
Effect.gen(function* () {
const command = yield* decodeCommand({
type: "thread.meta.update",
commandId: "unlink",
threadId: THREAD_ID,
linkedPullRequest: null,
});
const decided = yield* decideOrchestrationCommand({
readModel: makeReadModel([makeLink()]),
command,
});
const events = Array.isArray(decided) ? decided : [decided];
expect(events.map((event) => event.type)).toEqual(["thread.pull-request-unlinked"]);
}),
);
for (const source of ["manual", "agent", "created", "stack"] as const) {
it.effect(`legacy unlink removes the visible ${source} link and preserves other requests`, () =>
Effect.gen(function* () {
const other = makeLink({ number: 7, snapshot: { ...snapshot, state: "merged" } });
const current = makeLink({ source, linkedAt: "2026-01-02T00:00:00.000Z" });
let model = makeReadModel([other, current]);
// This is the pre-array command shape sent by older clients.
const command = yield* decodeCommand({
type: "thread.meta.update",
commandId: "legacy-unlink",
threadId: THREAD_ID,
linkedPullRequest: null,
title: "Renamed by old client",
});
const decided = yield* decideOrchestrationCommand({ readModel: model, command });
const events = Array.isArray(decided) ? decided : [decided];
for (const planned of events) {
const event = { ...planned, sequence: model.snapshotSequence + 1 };
const encoded = yield* Schema.encodeEffect(OrchestrationEvent)(event);
const decoded = yield* Schema.decodeUnknownEffect(OrchestrationEvent)(encoded);
// Older detail-event unions must never receive the new PR discriminants.
expect(isThreadDetailEvent(decoded)).toBe(false);
model = yield* projectEvent(model, decoded);
}
const thread = model.threads[0]!;
expect(thread.title).toBe("Renamed by old client");
expect(thread.pullRequests).toEqual(
source === "stack" ? [other, { ...current, source: "stack-dismissed" }] : [other],
);
// The old single-link field continues to track the remaining visible request.
expect(thread.linkedPullRequest?.number).toBe(7);
}),
);
}
it.effect("links a pull request with a normalized key and empty host state", () =>
Effect.gen(function* () {
const decided = yield* decideOrchestrationCommand({
command: {
type: "thread.pull-request.link",
commandId: CommandId.make("cmd-link"),
threadId: THREAD_ID,
host: " GitHub.com ",
repository: "T3Tools/T3Code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
source: "manual",
},
readModel: makeReadModel([]),
});
expect(Array.isArray(decided)).toBe(false);
const event = expectSingleEvent(decided, "thread.pull-request-linked");
expect(event.payload.link).toEqual({
host: "github.com",
repository: "t3tools/t3code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
source: "manual",
linkedAt: event.payload.updatedAt,
snapshot: null,
stack: null,
});
expect(event.payload.updatedAt).not.toBe(NOW);
}),
);
it.effect("rejects linking a pull request that is already linked", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.pull-request.link",
commandId: CommandId.make("cmd-link-dup"),
threadId: THREAD_ID,
host: "GITHUB.COM",
repository: "t3tools/t3code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
source: "agent",
},
readModel: makeReadModel([makeLink()]),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("re-linking a dismissed stack member un-dismisses it", () =>
Effect.gen(function* () {
const dismissed = makeLink({
source: "stack-dismissed",
snapshot,
stack: {
kind: "native",
id: "stack-1",
number: 1,
url: "https://github.com/t3tools/t3code/stack/1",
base: "main",
layers: [{ number: 42, headBranch: "feat/links", state: "open" }],
},
});
const decided = yield* decideOrchestrationCommand({
command: {
type: "thread.pull-request.link",
commandId: CommandId.make("cmd-relink"),
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
source: "manual",
},
readModel: makeReadModel([dismissed]),
});
const event = expectSingleEvent(decided, "thread.pull-request-linked");
// Host state survives the flip; only the source changes.
expect(event.payload.link).toEqual({ ...dismissed, source: "manual" });
}),
);
it.effect("rejects a stack sync re-adding a dismissed stack member", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.pull-request.link",
commandId: CommandId.make("cmd-stack-readd"),
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
source: "stack",
},
readModel: makeReadModel([makeLink({ source: "stack-dismissed" })]),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("unlinks a manual pull request", () =>
Effect.gen(function* () {
const decided = yield* decideOrchestrationCommand({
command: {
type: "thread.pull-request.unlink",
commandId: CommandId.make("cmd-unlink"),
threadId: THREAD_ID,
host: "GitHub.com",
repository: "t3tools/t3code",
number: 42,
},
readModel: makeReadModel([makeLink()]),
});
const event = expectSingleEvent(decided, "thread.pull-request-unlinked");
expect(event.payload).toMatchObject({
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
});
}),
);
it.effect("unlinking a stack member leaves a stack-dismissed tombstone", () =>
Effect.gen(function* () {
const member = makeLink({ source: "stack", snapshot });
const decided = yield* decideOrchestrationCommand({
command: {
type: "thread.pull-request.unlink",
commandId: CommandId.make("cmd-unlink-stack"),
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
},
readModel: makeReadModel([member]),
});
const event = expectSingleEvent(decided, "thread.pull-request-linked");
expect(event.payload.link).toEqual({ ...member, source: "stack-dismissed" });
}),
);
for (const source of ["manual", "agent", "created"] as const) {
it.effect(`unlinking a ${source} member prevents its sibling rediscovering it`, () =>
Effect.gen(function* () {
const member = makeLink({ source });
const sibling = makeLink({
number: 43,
source: "stack",
stack: {
kind: "native",
id: "stack-1",
number: 1,
url: "https://github.com/t3tools/t3code/stack/1",
base: "main",
layers: [
{ number: 42, headBranch: "first", state: "open" },
{ number: 43, headBranch: "second", state: "open" },
],
},
});
let model = makeReadModel([member, sibling]);
const decided = yield* decideOrchestrationCommand({
readModel: model,
command: {
type: "thread.pull-request.unlink",
commandId: CommandId.make("remove"),
threadId: THREAD_ID,
host: member.host,
repository: member.repository,
number: member.number,
},
});
const event = expectSingleEvent(decided, "thread.pull-request-linked");
model = yield* projectEvent(model, { ...event, sequence: 1 });
expect(model.threads[0]!.pullRequests).toEqual([
{ ...member, source: "stack-dismissed" },
sibling,
]);
const rediscovered = yield* decideOrchestrationCommand({
readModel: model,
command: {
type: "thread.pull-request.link",
commandId: CommandId.make("rediscovered"),
threadId: THREAD_ID,
host: member.host,
repository: member.repository,
number: member.number,
url: member.url,
source: "stack",
},
}).pipe(Effect.result);
expect(rediscovered._tag).toBe("Failure");
}),
);
}
it.effect("rejects unlinking a pull request that is not linked", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.pull-request.unlink",
commandId: CommandId.make("cmd-unlink-missing"),
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 7,
},
readModel: makeReadModel([makeLink()]),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("rejects syncing a pull request that is not linked", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.pull-request-link.sync",
commandId: CommandId.make("cmd-sync-missing"),
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
snapshot,
stack: null,
},
readModel: makeReadModel([]),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("sync emits the host snapshot for a linked pull request", () =>
Effect.gen(function* () {
const decided = yield* decideOrchestrationCommand({
command: {
type: "thread.pull-request-link.sync",
commandId: CommandId.make("cmd-sync"),
threadId: THREAD_ID,
host: "GitHub.com",
repository: "t3tools/t3code",
number: 42,
snapshot,
stack: null,
},
readModel: makeReadModel([makeLink()]),
});
const event = expectSingleEvent(decided, "thread.pull-request-synced");
expect(event.payload).toMatchObject({
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
snapshot,
stack: null,
});
}),
);
});
@@ -26,6 +26,7 @@ const readModel: OrchestrationReadModel = {
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
pullRequests: [],
branch: null,
worktreePath: null,
latestTurn: null,
@@ -47,6 +47,7 @@ function makeReadModel(
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
@@ -41,6 +41,7 @@ function makeReadModel(input: {
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
@@ -26,6 +26,7 @@ const readModel: OrchestrationReadModel = {
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: null,
createdAt: UPDATED_AT,
updatedAt: UPDATED_AT,
+221
View File
@@ -10,8 +10,16 @@ import {
type OrchestrationEvent,
type OrchestrationReadModel,
type OrchestrationThread,
type ThreadPullRequestKey,
type ThreadPullRequestLink,
type OrchestrationThreadActivity,
} from "@t3tools/contracts";
import {
legacyLinkedPullRequestOf,
legacyThreadPullRequestKey,
normalizeThreadPullRequestKey,
threadPullRequestKeysEqual,
} from "@t3tools/shared/threadPullRequests";
import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
@@ -121,6 +129,13 @@ function hasQueuedTurnStartForThread(
);
}
function findPullRequestLink(
thread: Pick<OrchestrationThread, "pullRequests">,
key: ThreadPullRequestKey,
): ThreadPullRequestLink | undefined {
return thread.pullRequests.find((link) => threadPullRequestKeysEqual(link, key));
}
function withEventBase(
input: Pick<OrchestrationCommand, "commandId"> & {
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
@@ -876,6 +891,80 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
threadId: command.threadId,
});
// Old clients only see the derived single link. Unlink that request through
// the same command path as modern clients, including stack dismissal, while
// retaining other links they cannot see. Historical metadata events still replay unchanged.
const legacy = legacyLinkedPullRequestOf(
thread.pullRequests,
thread.projectId,
readModel.projects.find((project) => project.id === thread.projectId)?.repositoryIdentity,
);
const currentPullRequest =
legacy === null
? null
: (thread.pullRequests.find(
(link) => link.url === legacy.url && link.number === legacy.number,
) ?? null);
if (command.linkedPullRequest != null) {
const { linkedPullRequest: linked, ...metadata } = command;
const project = readModel.projects.find((project) => project.id === thread.projectId);
let host = project?.repositoryIdentity?.canonicalKey.split("/")[0] ?? "unknown";
try {
host = new URL(linked.url).hostname;
} catch {
// Historical clients can send links without a parseable URL.
}
const hasMetadata = Object.entries(metadata).some(
([key, value]) => !["type", "commandId", "threadId"].includes(key) && value !== undefined,
);
return yield* decideCommandSequence({
readModel,
commands: [
...(hasMetadata ? [metadata] : []),
...(currentPullRequest?.source === "manual"
? [
{
type: "thread.pull-request.unlink" as const,
commandId: command.commandId,
threadId: command.threadId,
host: currentPullRequest.host,
repository: currentPullRequest.repository,
number: currentPullRequest.number,
},
]
: []),
{
type: "thread.pull-request.link",
commandId: command.commandId,
threadId: command.threadId,
...legacyThreadPullRequestKey(linked, host),
url: linked.url,
source: "manual",
},
],
});
}
if (command.linkedPullRequest === null && currentPullRequest !== null) {
const { linkedPullRequest: _linkedPullRequest, ...metadata } = command;
const hasMetadata = Object.entries(metadata).some(
([key, value]) => !["type", "commandId", "threadId"].includes(key) && value !== undefined,
);
return yield* decideCommandSequence({
readModel,
commands: [
...(hasMetadata ? [metadata] : []),
{
type: "thread.pull-request.unlink",
commandId: command.commandId,
threadId: command.threadId,
host: currentPullRequest.host,
repository: currentPullRequest.repository,
number: currentPullRequest.number,
},
],
});
}
const branch =
command.branch !== undefined &&
command.expectedBranch !== undefined &&
@@ -920,6 +1009,138 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.pull-request.link": {
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const key = normalizeThreadPullRequestKey(command);
const existing = findPullRequestLink(thread, key);
// An explicit link on a dismissed stack member un-dismisses it; any
// other duplicate is a no-op the engine would reject as zero-event.
const undismisses =
existing?.source === "stack-dismissed" &&
(command.source === "manual" || command.source === "agent" || command.source === "created");
if (existing !== undefined && !undismisses) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `pull request ${key.host}/${key.repository}#${key.number} is already linked to thread ${command.threadId}`,
});
}
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.pull-request-linked",
payload: {
threadId: command.threadId,
link:
existing !== undefined
? { ...existing, url: command.url, source: command.source }
: {
...key,
url: command.url,
source: command.source,
linkedAt: occurredAt,
snapshot: null,
stack: null,
},
updatedAt: occurredAt,
},
};
}
case "thread.pull-request.unlink": {
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const key = normalizeThreadPullRequestKey(command);
const existing = findPullRequestLink(thread, key);
if (existing === undefined) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `pull request ${key.host}/${key.repository}#${key.number} is not linked to thread ${command.threadId}`,
});
}
const occurredAt = yield* nowIso;
const eventBase = yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
});
// Any known native-stack member needs a tombstone, regardless of who linked it.
// A sibling can rediscover it even before this link has its own stack snapshot.
const belongsToStack =
existing.source === "stack" ||
existing.stack !== null ||
thread.pullRequests.some(
(link) =>
link.host.toLowerCase() === key.host &&
link.repository.toLowerCase() === key.repository &&
link.stack?.layers.some((layer) => layer.number === key.number),
);
if (belongsToStack) {
return {
...eventBase,
type: "thread.pull-request-linked",
payload: {
threadId: command.threadId,
link: { ...existing, source: "stack-dismissed" },
updatedAt: occurredAt,
},
};
}
return {
...eventBase,
type: "thread.pull-request-unlinked",
payload: {
threadId: command.threadId,
...key,
updatedAt: occurredAt,
},
};
}
case "thread.pull-request-link.sync": {
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const key = normalizeThreadPullRequestKey(command);
if (findPullRequestLink(thread, key) === undefined) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `pull request ${key.host}/${key.repository}#${key.number} is not linked to thread ${command.threadId}`,
});
}
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.pull-request-synced",
payload: {
threadId: command.threadId,
...key,
snapshot: command.snapshot,
stack: command.stack,
updatedAt: occurredAt,
},
};
}
case "thread.pull-request.sync": {
const thread = yield* requireThreadNotArchived({
readModel,
@@ -49,6 +49,7 @@ function makeReadModel(
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
pullRequests: [],
branch: null,
worktreePath: null,
latestTurn: null,
@@ -0,0 +1,417 @@
import {
CommandId,
EventId,
ProjectId,
ThreadId,
type OrchestrationEvent,
type OrchestrationReadModel,
type RepositoryIdentity,
type ThreadPullRequestLink,
type ThreadPullRequestSnapshot,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const NOW = "2026-01-01T00:00:00.000Z";
const LATER = "2026-01-02T00:00:00.000Z";
const THREAD_ID = ThreadId.make("thread-1");
const PROJECT_ID = ProjectId.make("project-1");
function makeEvent(input: {
readonly sequence: number;
readonly type: OrchestrationEvent["type"];
readonly payload: unknown;
}): OrchestrationEvent {
return {
sequence: input.sequence,
eventId: EventId.make(`event-${input.sequence}`),
type: input.type,
aggregateKind: "thread",
aggregateId: THREAD_ID,
occurredAt: NOW,
commandId: CommandId.make(`command-${input.sequence}`),
causationEventId: null,
correlationId: null,
metadata: {},
payload: input.payload as never,
} as OrchestrationEvent;
}
function makeLink(overrides: Partial<ThreadPullRequestLink> = {}): ThreadPullRequestLink {
return {
host: "github.com",
repository: "t3tools/t3code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
source: "manual",
linkedAt: NOW,
snapshot: null,
stack: null,
...overrides,
};
}
const snapshot: ThreadPullRequestSnapshot = {
state: "merged",
title: "Add links",
headBranch: "feat/links",
baseBranch: "main",
isDraft: false,
updatedAt: LATER,
syncedAt: LATER,
};
const createThread = (model: OrchestrationReadModel) =>
projectEvent(
model,
makeEvent({
sequence: model.snapshotSequence + 1,
type: "thread.created",
payload: {
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: NOW,
updatedAt: NOW,
},
}),
);
const createProject = (model: OrchestrationReadModel, repositoryIdentity: RepositoryIdentity) =>
projectEvent(model, {
...makeEvent({
sequence: model.snapshotSequence + 1,
type: "project.created",
payload: {
projectId: PROJECT_ID,
title: "Project",
workspaceRoot: "/workspace/project",
defaultModelSelection: null,
scripts: [],
createdAt: NOW,
updatedAt: NOW,
},
}),
aggregateKind: "project",
aggregateId: PROJECT_ID,
}).pipe(
Effect.map((next) => ({
...next,
projects: next.projects.map((project) =>
project.id === PROJECT_ID ? { ...project, repositoryIdentity } : project,
),
})),
);
it.effect("seeds threads with no pull requests", () =>
Effect.gen(function* () {
const created = yield* createThread(createEmptyReadModel(NOW));
expect(created.threads[0]?.pullRequests).toEqual([]);
expect(created.threads[0]?.linkedPullRequest ?? null).toBeNull();
}),
);
it.effect("projects link, sync, and unlink onto the thread", () =>
Effect.gen(function* () {
const created = yield* createThread(
yield* createProject(createEmptyReadModel(NOW), {
canonicalKey: "github.com/t3tools/t3code",
provider: "github",
displayName: "t3tools/t3code",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/t3tools/t3code.git",
},
}),
);
const link = makeLink();
const linked = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.pull-request-linked",
payload: { threadId: THREAD_ID, link, updatedAt: LATER },
}),
);
expect(linked.threads[0]?.pullRequests).toEqual([link]);
expect(linked.threads[0]?.updatedAt).toBe(LATER);
// The legacy field is derived from the array so old clients keep working.
expect(linked.threads[0]?.linkedPullRequest).toEqual({
projectId: PROJECT_ID,
repository: "t3tools/t3code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
});
// A second link for the same key replaces in place (used for un-dismiss
// and stack tombstones), never duplicates.
const relinked = yield* projectEvent(
linked,
makeEvent({
sequence: 3,
type: "thread.pull-request-linked",
payload: {
threadId: THREAD_ID,
link: { ...link, host: "GITHUB.COM", source: "agent" },
updatedAt: LATER,
},
}),
);
expect(relinked.threads[0]?.pullRequests).toHaveLength(1);
expect(relinked.threads[0]?.pullRequests[0]?.source).toBe("agent");
const synced = yield* projectEvent(
relinked,
makeEvent({
sequence: 4,
type: "thread.pull-request-synced",
payload: {
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
snapshot,
stack: null,
updatedAt: LATER,
},
}),
);
expect(synced.threads[0]?.pullRequests[0]?.snapshot).toEqual(snapshot);
const unlinked = yield* projectEvent(
synced,
makeEvent({
sequence: 5,
type: "thread.pull-request-unlinked",
payload: {
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
updatedAt: LATER,
},
}),
);
expect(unlinked.threads[0]?.pullRequests).toEqual([]);
expect(unlinked.threads[0]?.linkedPullRequest).toBeNull();
}),
);
it.effect("ignores a sync for a pull request that is no longer linked", () =>
Effect.gen(function* () {
const created = yield* createThread(createEmptyReadModel(NOW));
const other = makeLink({ number: 7, url: "https://github.com/t3tools/t3code/pull/7" });
const linked = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.pull-request-linked",
payload: { threadId: THREAD_ID, link: other, updatedAt: NOW },
}),
);
const synced = yield* projectEvent(
linked,
makeEvent({
sequence: 3,
type: "thread.pull-request-synced",
payload: {
threadId: THREAD_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
snapshot,
stack: null,
updatedAt: LATER,
},
}),
);
expect(synced.threads[0]?.pullRequests).toEqual([other]);
expect(synced.threads[0]?.updatedAt).toBe(NOW);
}),
);
it.effect("mirrors legacy meta-updated links into pullRequests using the project host", () =>
Effect.gen(function* () {
const withProject = yield* createProject(createEmptyReadModel(NOW), {
canonicalKey: "GitHub.com/t3tools/t3code",
provider: "github",
displayName: "t3tools/t3code",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "[email protected]:t3tools/t3code.git",
},
});
const created = yield* createThread(withProject);
const agentLink = makeLink({
number: 7,
url: "https://github.com/t3tools/t3code/pull/7",
source: "agent",
});
const withAgentLink = yield* projectEvent(
created,
makeEvent({
sequence: 3,
type: "thread.pull-request-linked",
payload: { threadId: THREAD_ID, link: agentLink, updatedAt: NOW },
}),
);
const legacyLinked = yield* projectEvent(
withAgentLink,
makeEvent({
sequence: 4,
type: "thread.meta-updated",
payload: {
threadId: THREAD_ID,
linkedPullRequest: {
projectId: PROJECT_ID,
repository: "T3Tools/T3Code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
},
updatedAt: LATER,
},
}),
);
expect(legacyLinked.threads[0]?.pullRequests).toEqual([
agentLink,
{
host: "github.com",
repository: "t3tools/t3code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
source: "manual",
linkedAt: LATER,
snapshot: null,
stack: null,
},
]);
// Two open links read as a stack; the derived field points at the top.
expect(legacyLinked.threads[0]?.linkedPullRequest).toEqual({
projectId: PROJECT_ID,
repository: "t3tools/t3code",
number: 42,
url: "https://github.com/t3tools/t3code/pull/42",
});
// Null clears only the manual link; the agent's stays.
const legacyCleared = yield* projectEvent(
legacyLinked,
makeEvent({
sequence: 5,
type: "thread.meta-updated",
payload: { threadId: THREAD_ID, linkedPullRequest: null, updatedAt: LATER },
}),
);
expect(legacyCleared.threads[0]?.pullRequests).toEqual([agentLink]);
expect(legacyCleared.threads[0]?.linkedPullRequest).toEqual({
projectId: PROJECT_ID,
repository: "t3tools/t3code",
number: 7,
url: "https://github.com/t3tools/t3code/pull/7",
});
}),
);
it.effect("falls back to the link URL host when the project has no repository identity", () =>
Effect.gen(function* () {
const created = yield* createThread(createEmptyReadModel(NOW));
const legacyLinked = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.meta-updated",
payload: {
threadId: THREAD_ID,
linkedPullRequest: {
projectId: PROJECT_ID,
repository: "t3tools/t3code",
number: 42,
url: "https://GitLab.example.com/t3tools/t3code/-/merge_requests/42",
},
updatedAt: LATER,
},
}),
);
expect(legacyLinked.threads[0]?.pullRequests[0]?.host).toBe("gitlab.example.com");
}),
);
it.effect("leaves pullRequests alone when meta-updated carries no legacy link", () =>
Effect.gen(function* () {
const created = yield* createThread(createEmptyReadModel(NOW));
const link = makeLink();
const linked = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.pull-request-linked",
payload: { threadId: THREAD_ID, link, updatedAt: NOW },
}),
);
const retitled = yield* projectEvent(
linked,
makeEvent({
sequence: 3,
type: "thread.meta-updated",
payload: { threadId: THREAD_ID, title: "Renamed", updatedAt: LATER },
}),
);
expect(retitled.threads[0]?.title).toBe("Renamed");
expect(retitled.threads[0]?.pullRequests).toEqual([link]);
}),
);
it.effect("replays Azure legacy selectors as full repository keys", () =>
Effect.gen(function* () {
const withProject = yield* createProject(createEmptyReadModel(NOW), {
canonicalKey: "ssh.dev.azure.com/v3/org-a/project/web",
provider: "azure-devops",
displayName: "v3/org-a/project/web",
name: "web",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "[email protected]:v3/org-a/project/web",
},
});
const created = yield* createThread(withProject);
const legacy = {
projectId: PROJECT_ID,
repository: "web",
number: 7,
url: "https://dev.azure.com/org-a/project/_git/web/pullrequest/7",
};
const model = yield* projectEvent(
created,
makeEvent({
sequence: 3,
type: "thread.meta-updated",
payload: { threadId: THREAD_ID, linkedPullRequest: legacy, updatedAt: LATER },
}),
);
expect(model.threads[0]?.pullRequests).toEqual([
{
host: "dev.azure.com",
repository: "org-a/project/_git/web",
number: 7,
url: legacy.url,
source: "manual",
linkedAt: LATER,
snapshot: null,
stack: null,
},
]);
expect(model.threads[0]?.linkedPullRequest).toEqual(legacy);
}),
);
@@ -86,6 +86,7 @@ describe("orchestration projector", () => {
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
branchPullRequest: null,
latestTurn: null,
createdAt: now,
@@ -117,7 +118,31 @@ describe("orchestration projector", () => {
commandId: null,
};
let model = yield* projectEvent(
createEmptyReadModel(now),
{
...createEmptyReadModel(now),
projects: [
{
id: ProjectId.make("project-1"),
title: "T3 Code",
workspaceRoot: "/repo",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
deletedAt: null,
repositoryIdentity: {
canonicalKey: "github.com/pingdotgg/t3code",
provider: "github",
displayName: "pingdotgg/t3code",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/pingdotgg/t3code.git",
},
},
},
],
},
makeEvent({
...eventFields,
sequence: 1,
+212 -25
View File
@@ -1,4 +1,12 @@
import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
import type {
OrchestrationEvent,
OrchestrationProject,
OrchestrationReadModel,
ThreadId,
ThreadLinkedPullRequest,
ThreadPullRequestKey,
ThreadPullRequestLink,
} from "@t3tools/contracts";
import {
isImportedAgentSessionMessageId,
OrchestrationCheckpointSummary,
@@ -6,6 +14,11 @@ import {
OrchestrationSession,
OrchestrationThread,
} from "@t3tools/contracts";
import {
legacyLinkedPullRequestOf,
legacyThreadPullRequestKey,
threadPullRequestKeysEqual,
} from "@t3tools/shared/threadPullRequests";
import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
@@ -28,6 +41,9 @@ import {
ThreadSettledPayload,
ThreadPinnedPayload,
ThreadPinReorderedPayload,
ThreadPullRequestLinkedPayload,
ThreadPullRequestSyncedPayload,
ThreadPullRequestUnlinkedPayload,
ThreadSnoozedPayload,
ThreadUnpinnedPayload,
ThreadUnarchivedPayload,
@@ -101,6 +117,77 @@ function updateThread(
return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));
}
/** Patch that swaps a thread's links and re-derives the legacy single-PR field from them. */
function pullRequestsPatch(
thread: Pick<OrchestrationThread, "projectId">,
pullRequests: ReadonlyArray<ThreadPullRequestLink>,
projects: OrchestrationReadModel["projects"],
): Pick<OrchestrationThread, "pullRequests" | "linkedPullRequest"> {
return {
pullRequests,
linkedPullRequest: legacyLinkedPullRequestOf(
pullRequests,
thread.projectId,
projects.find((project) => project.id === thread.projectId)?.repositoryIdentity,
),
};
}
function upsertPullRequestLink(
pullRequests: ReadonlyArray<ThreadPullRequestLink>,
link: ThreadPullRequestLink,
): ReadonlyArray<ThreadPullRequestLink> {
const index = pullRequests.findIndex((entry) => threadPullRequestKeysEqual(entry, link));
return index === -1
? [...pullRequests, link]
: pullRequests.map((entry, entryIndex) => (entryIndex === index ? link : entry));
}
function removePullRequestLink(
pullRequests: ReadonlyArray<ThreadPullRequestLink>,
key: ThreadPullRequestKey,
): ReadonlyArray<ThreadPullRequestLink> {
return pullRequests.filter((entry) => !threadPullRequestKeysEqual(entry, key));
}
/**
* Host for a legacy `linkedPullRequest` being replayed into the link array.
* Legacy links never carried one; the project's canonical key
* (`<host>/<owner>/<name>`) is the best witness, then the link URL.
*/
function legacyPullRequestHost(
project: OrchestrationProject | undefined,
linked: ThreadLinkedPullRequest,
): string {
const canonicalHost = project?.repositoryIdentity?.canonicalKey.split("/")[0];
if (canonicalHost) return canonicalHost.toLowerCase();
try {
return new URL(linked.url).hostname.toLowerCase();
} catch {
return "unknown";
}
}
function legacyLinkToPullRequests(
thread: Pick<OrchestrationThread, "pullRequests">,
project: OrchestrationProject | undefined,
linked: ThreadLinkedPullRequest | null,
linkedAt: string,
): ReadonlyArray<ThreadPullRequestLink> {
// The legacy field held one user-chosen link, so null clears exactly the
// manual ones and leaves created/agent/stack links alone.
const withoutManual = thread.pullRequests.filter((entry) => entry.source !== "manual");
if (linked === null) return withoutManual;
return upsertPullRequestLink(withoutManual, {
...legacyThreadPullRequestKey(linked, legacyPullRequestHost(project, linked)),
url: linked.url,
source: "manual",
linkedAt,
snapshot: null,
stack: null,
});
}
function decodeForEvent<A>(
schema: Schema.Decoder<A, never>,
value: unknown,
@@ -336,6 +423,7 @@ export function projectEvent(
interactionMode: payload.interactionMode,
branch: payload.branch,
worktreePath: payload.worktreePath,
pullRequests: [],
branchPullRequest: null,
latestTurn: null,
createdAt: payload.createdAt,
@@ -498,30 +586,129 @@ export function projectEvent(
case "thread.meta-updated":
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...(payload.title !== undefined ? { title: payload.title } : {}),
...(payload.activeOrderKey !== undefined
? { activeOrderKey: payload.activeOrderKey }
: {}),
...(payload.titleRegeneration !== undefined
? { titleRegeneration: payload.titleRegeneration }
: {}),
...(payload.modelSelection !== undefined
? { modelSelection: payload.modelSelection }
: {}),
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
...(payload.linkedPullRequest !== undefined
? { linkedPullRequest: payload.linkedPullRequest }
: {}),
...(payload.branchPullRequest !== undefined
? { branchPullRequest: payload.branchPullRequest }
: {}),
updatedAt: payload.updatedAt,
}),
})),
Effect.map((payload) => {
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
// Legacy single-link events replay into the link array so the
// derived linkedPullRequest and pullRequests never disagree.
const legacyLinkPatch =
thread !== undefined && payload.linkedPullRequest !== undefined
? pullRequestsPatch(
thread,
legacyLinkToPullRequests(
thread,
nextBase.projects.find((project) => project.id === thread.projectId),
payload.linkedPullRequest,
payload.updatedAt,
),
nextBase.projects,
)
: {};
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...(payload.title !== undefined ? { title: payload.title } : {}),
...(payload.titleRegeneration !== undefined
? { titleRegeneration: payload.titleRegeneration }
: {}),
...(payload.modelSelection !== undefined
? { modelSelection: payload.modelSelection }
: {}),
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
...(payload.activeOrderKey !== undefined
? { activeOrderKey: payload.activeOrderKey }
: {}),
...(payload.branchPullRequest !== undefined
? { branchPullRequest: payload.branchPullRequest }
: {}),
...legacyLinkPatch,
updatedAt: payload.updatedAt,
}),
};
}),
);
case "thread.pull-request-linked":
return decodeForEvent(
ThreadPullRequestLinkedPayload,
event.payload,
event.type,
"payload",
).pipe(
Effect.map((payload) => {
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...pullRequestsPatch(
thread,
upsertPullRequestLink(thread.pullRequests, payload.link),
nextBase.projects,
),
updatedAt: payload.updatedAt,
}),
};
}),
);
case "thread.pull-request-unlinked":
return decodeForEvent(
ThreadPullRequestUnlinkedPayload,
event.payload,
event.type,
"payload",
).pipe(
Effect.map((payload) => {
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...pullRequestsPatch(
thread,
removePullRequestLink(thread.pullRequests, payload),
nextBase.projects,
),
updatedAt: payload.updatedAt,
}),
};
}),
);
case "thread.pull-request-synced":
return decodeForEvent(
ThreadPullRequestSyncedPayload,
event.payload,
event.type,
"payload",
).pipe(
Effect.map((payload) => {
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
// A sync for a link the user removed in the meantime is stale; drop it.
if (
!thread ||
!thread.pullRequests.some((link) => threadPullRequestKeysEqual(link, payload))
) {
return nextBase;
}
const pullRequests = thread.pullRequests.map((link) =>
threadPullRequestKeysEqual(link, payload)
? { ...link, snapshot: payload.snapshot, stack: payload.stack }
: link,
);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...pullRequestsPatch(thread, pullRequests, nextBase.projects),
updatedAt: payload.updatedAt,
}),
};
}),
);
case "thread.runtime-mode-set":
@@ -15,15 +15,21 @@ import * as Statement from "effect/unstable/sql/Statement";
import { SqlitePersistenceMemory } from "./Sqlite.ts";
import { ProjectionProjectRepositoryLive } from "./ProjectionProjects.ts";
import { ProjectionThreadRepositoryLive } from "./ProjectionThreads.ts";
import { ProjectionThreadProposedPlanRepositoryLive } from "./ProjectionThreadProposedPlans.ts";
import * as ProjectionThreadPullRequests from "../ProjectionThreadPullRequests.ts";
import { ProjectionProjectRepository } from "../Services/ProjectionProjects.ts";
import { ProjectionThreadRepository } from "../Services/ProjectionThreads.ts";
import {
ProjectionThreadPullRequestRepository,
type ProjectionThreadPullRequest,
} from "../ProjectionThreadPullRequests.ts";
import { ProjectionThreadProposedPlanRepositoryLive } from "./ProjectionThreadProposedPlans.ts";
import { ProjectionThreadProposedPlanRepository } from "../Services/ProjectionThreadProposedPlans.ts";
const projectionRepositoriesLayer = it.layer(
Layer.mergeAll(
ProjectionProjectRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
ProjectionThreadRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
ProjectionThreadPullRequests.layer.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
ProjectionThreadProposedPlanRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
SqlitePersistenceMemory,
),
@@ -529,4 +535,164 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.deepStrictEqual(Option.getOrNull(branchCleared)?.linkedPullRequest, linkedPullRequest);
}),
);
it.effect("uses one Azure identity for repository writes, lookups, and deletion", () =>
Effect.gen(function* () {
const pullRequests = yield* ProjectionThreadPullRequestRepository;
const threadId = ThreadId.make("azure-alias-link");
const row: ProjectionThreadPullRequest = {
threadId,
host: "org.visualstudio.com",
repository: "project/_git/web",
number: 7,
url: "https://org.visualstudio.com/project/_git/web/pullrequest/7",
source: "manual",
linkedAt: "2026-09-09T00:00:00.000Z",
snapshot: null,
stack: null,
};
yield* pullRequests.upsert(row);
yield* pullRequests.upsert({
...row,
host: "dev.azure.com",
repository: "org/project/_git/web",
});
const found = yield* pullRequests.listByPullRequest({
host: "ssh.dev.azure.com",
repository: "v3/org/project/web",
number: 7,
});
assert.deepStrictEqual(found, [
{ ...row, host: "dev.azure.com", repository: "org/project/_git/web" },
]);
assert.deepStrictEqual(
yield* pullRequests.listByPullRequest({
host: "dev.azure.com",
repository: "other/project/_git/web",
number: 7,
}),
[],
);
yield* pullRequests.delete({
threadId,
host: "vs-ssh.visualstudio.com",
repository: "v3/org/project/web",
number: 7,
});
assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId }), []);
}),
);
it.effect("round-trips pull request links with JSON snapshot and stack columns", () =>
Effect.gen(function* () {
const pullRequests = yield* ProjectionThreadPullRequestRepository;
const sql = yield* SqlClient.SqlClient;
const threadId = ThreadId.make("thread-pr-links");
const otherThreadId = ThreadId.make("thread-pr-links-other");
const unsynced: ProjectionThreadPullRequest = {
threadId,
host: "github.com",
repository: "pingdotgg/t3code",
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
source: "manual",
linkedAt: "2026-03-24T00:00:00.000Z",
snapshot: null,
stack: null,
};
const synced: ProjectionThreadPullRequest = {
threadId,
host: "github.com",
repository: "pingdotgg/t3code",
number: 7,
url: "https://github.com/pingdotgg/t3code/pull/7",
source: "stack",
linkedAt: "2026-03-23T00:00:00.000Z",
snapshot: {
state: "open",
title: "Add links",
headBranch: "feat/links",
baseBranch: "main",
isDraft: false,
updatedAt: "2026-03-23T01:00:00.000Z",
syncedAt: "2026-03-23T02:00:00.000Z",
},
stack: {
kind: "native",
id: "stack-1",
number: 1,
url: "https://github.com/pingdotgg/t3code/stack/1",
base: "main",
layers: [
{ number: 7, headBranch: "feat/links", state: "open" },
{ number: 42, headBranch: "feat/links-ui", state: "open" },
],
},
};
const sharedOnOtherThread: ProjectionThreadPullRequest = {
...unsynced,
threadId: otherThreadId,
source: "agent",
linkedAt: "2026-03-25T00:00:00.000Z",
};
yield* pullRequests.upsert(unsynced);
yield* pullRequests.upsert(synced);
yield* pullRequests.upsert(sharedOnOtherThread);
const rawRows = yield* sql<{
readonly number: number;
readonly snapshotJson: string | null;
readonly stackJson: string | null;
}>`
SELECT number, snapshot_json AS "snapshotJson", stack_json AS "stackJson"
FROM projection_thread_pull_requests
WHERE thread_id = ${threadId}
ORDER BY number ASC
`;
assert.strictEqual(rawRows[0]?.number, 7);
// @effect-diagnostics-next-line preferSchemaOverJson:off
assert.deepStrictEqual(JSON.parse(rawRows[0]?.snapshotJson ?? "null"), synced.snapshot);
// @effect-diagnostics-next-line preferSchemaOverJson:off
assert.deepStrictEqual(JSON.parse(rawRows[0]?.stackJson ?? "null"), synced.stack);
assert.strictEqual(rawRows[1]?.snapshotJson, null);
assert.strictEqual(rawRows[1]?.stackJson, null);
// Ordered by linked_at, then number.
assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId }), [synced, unsynced]);
// One pull request across threads, ordered by linked_at.
assert.deepStrictEqual(
yield* pullRequests.listByPullRequest({
host: "github.com",
repository: "pingdotgg/t3code",
number: 42,
}),
[unsynced, sharedOnOtherThread],
);
// Upsert on the composite key replaces snapshot and stack in place.
const resynced = { ...unsynced, snapshot: synced.snapshot, stack: null } as const;
yield* pullRequests.upsert(resynced);
assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId }), [synced, resynced]);
yield* pullRequests.delete({
threadId,
host: "github.com",
repository: "pingdotgg/t3code",
number: 7,
});
assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId }), [resynced]);
yield* pullRequests.deleteByThreadIdAndSource({ threadId, source: "manual" });
assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId }), []);
assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId: otherThreadId }), [
sharedOnOtherThread,
]);
yield* pullRequests.deleteByThreadId({ threadId: otherThreadId });
assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId: otherThreadId }), []);
}),
);
});
@@ -61,6 +61,7 @@ import Migration0046 from "./Migrations/046_RepairAutomaticSettlementTimestamps.
import Migration0047 from "./Migrations/047_ProjectionProjectIcon.ts";
import Migration0048 from "./Migrations/048_ProjectionThreadBranchPullRequest.ts";
import Migration0049 from "./Migrations/049_ProjectionThreadsActiveOrderKey.ts";
import Migration0050 from "./Migrations/050_ProjectionThreadPullRequests.ts";
/**
* Migration loader with all migrations defined inline.
@@ -122,6 +123,7 @@ const migrationEntries = [
[47, "ProjectionProjectIcon", Migration0047],
[48, "ProjectionThreadBranchPullRequest", Migration0048],
[49, "ProjectionThreadsActiveOrderKey", Migration0049],
[50, "ProjectionThreadPullRequests", Migration0050],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,181 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
interface PullRequestRow {
readonly threadId: string;
readonly host: string;
readonly repository: string;
readonly number: number;
readonly url: string;
readonly source: string;
readonly linkedAt: string;
readonly snapshotJson: string | null;
readonly stackJson: string | null;
}
layer("050_ProjectionThreadPullRequests", (it) => {
it.effect("creates the link table and backfills legacy single links", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 49 });
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-1',
'Project 1',
'/tmp/project-1',
'[]',
'2026-03-01T00:00:00.000Z',
'2026-03-01T00:00:00.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
linked_pull_request_json,
created_at,
updated_at
)
VALUES
(
'thread-github',
'project-1',
'GitHub link',
'{"instanceId":"codex","model":"gpt-5.4"}',
'{"projectId":"project-1","repository":"PingDotGG/T3Code","number":42,"url":"https://GitHub.com/pingdotgg/t3code/pull/42"}',
'2026-03-01T00:00:01.000Z',
'2026-03-02T00:00:00.000Z'
),
(
'thread-bad-url',
'project-1',
'Unparseable URL',
'{"instanceId":"codex","model":"gpt-5.4"}',
'{"projectId":"project-1","repository":"acme/widgets","number":7,"url":"not a url"}',
'2026-03-01T00:00:02.000Z',
'2026-03-03T00:00:00.000Z'
),
(
'thread-malformed',
'project-1',
'Malformed JSON',
'{"instanceId":"codex","model":"gpt-5.4"}',
'{"repository":"acme/widgets"}',
'2026-03-01T00:00:03.000Z',
'2026-03-04T00:00:00.000Z'
),
(
'thread-unlinked',
'project-1',
'No link',
'{"instanceId":"codex","model":"gpt-5.4"}',
NULL,
'2026-03-01T00:00:04.000Z',
'2026-03-05T00:00:00.000Z'
)
`;
yield* runMigrations({ toMigrationInclusive: 50 });
const rows = yield* sql<PullRequestRow>`
SELECT
thread_id AS "threadId",
host,
repository,
number,
url,
source,
linked_at AS "linkedAt",
snapshot_json AS "snapshotJson",
stack_json AS "stackJson"
FROM projection_thread_pull_requests
ORDER BY thread_id ASC
`;
assert.deepStrictEqual(rows, [
{
threadId: "thread-bad-url",
host: "unknown",
repository: "acme/widgets",
number: 7,
url: "not a url",
source: "manual",
linkedAt: "2026-03-03T00:00:00.000Z",
snapshotJson: null,
stackJson: null,
},
{
threadId: "thread-github",
host: "github.com",
repository: "pingdotgg/t3code",
number: 42,
url: "https://GitHub.com/pingdotgg/t3code/pull/42",
source: "manual",
linkedAt: "2026-03-02T00:00:00.000Z",
snapshotJson: null,
stackJson: null,
},
]);
// The legacy column stays so a rollback keeps its data.
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
assert.ok(columns.some((column) => column.name === "linked_pull_request_json"));
const indexes = yield* sql<{ readonly name: string }>`
PRAGMA index_list(projection_thread_pull_requests)
`;
assert.ok(indexes.some((index) => index.name === "idx_projection_thread_pull_requests_pr"));
}),
);
});
it.layer(Layer.fresh(NodeSqliteClient.layerMemory()))("050 Azure legacy links", (it) => {
it.effect("keeps legacy Azure repositories distinct across organizations", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 49 });
for (const organization of ["org-a", "org-b"]) {
yield* sql`
INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, linked_pull_request_json, created_at, updated_at)
VALUES (${organization}, ${organization}, 'Azure', '{"instanceId":"codex","model":"gpt-5.4"}',
${encodeJson({ projectId: organization, repository: "web", number: 7, url: `https://dev.azure.com/${organization}/project/_git/web/pullrequest/7` })},
'2026-03-01T00:00:00.000Z', '2026-03-01T00:00:00.000Z')
`;
}
yield* runMigrations({ toMigrationInclusive: 50 });
const rows =
yield* sql`SELECT host, repository, number FROM projection_thread_pull_requests ORDER BY repository`;
assert.deepStrictEqual(rows, [
{ host: "dev.azure.com", repository: "org-a/project/_git/web", number: 7 },
{ host: "dev.azure.com", repository: "org-b/project/_git/web", number: 7 },
]);
}),
);
});
@@ -0,0 +1,92 @@
import { legacyThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
interface LegacyLinkedThreadRow {
readonly threadId: string;
readonly updatedAt: string;
readonly linkedPullRequestJson: string;
}
interface LegacyLinkedPullRequest {
readonly repository: string;
readonly number: number;
readonly url: string;
}
function parseLegacyLinkedPullRequest(json: string): LegacyLinkedPullRequest | null {
try {
const value: unknown = JSON.parse(json);
if (typeof value !== "object" || value === null) return null;
const { repository, number, url } = value as Record<string, unknown>;
if (typeof repository !== "string" || repository.trim().length === 0) return null;
if (typeof number !== "number" || !Number.isInteger(number) || number < 1) return null;
if (typeof url !== "string" || url.trim().length === 0) return null;
return { repository, number, url };
} catch {
return null;
}
}
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE TABLE IF NOT EXISTS projection_thread_pull_requests (
thread_id TEXT NOT NULL,
host TEXT NOT NULL,
repository TEXT NOT NULL,
number INTEGER NOT NULL,
url TEXT NOT NULL,
source TEXT NOT NULL,
linked_at TEXT NOT NULL,
snapshot_json TEXT,
stack_json TEXT,
PRIMARY KEY (thread_id, host, repository, number)
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_pull_requests_pr
ON projection_thread_pull_requests(host, repository, number)
`;
const legacyRows = yield* sql<LegacyLinkedThreadRow>`
SELECT
thread_id AS "threadId",
updated_at AS "updatedAt",
linked_pull_request_json AS "linkedPullRequestJson"
FROM projection_threads
WHERE linked_pull_request_json IS NOT NULL
`;
for (const row of legacyRows) {
const linked = parseLegacyLinkedPullRequest(row.linkedPullRequestJson);
if (linked === null) continue;
const key = legacyThreadPullRequestKey(linked);
yield* sql`
INSERT OR IGNORE INTO projection_thread_pull_requests (
thread_id,
host,
repository,
number,
url,
source,
linked_at,
snapshot_json,
stack_json
)
VALUES (
${row.threadId},
${key.host},
${key.repository},
${linked.number},
${linked.url},
'manual',
${row.updatedAt},
NULL,
NULL
)
`;
}
});
@@ -0,0 +1,266 @@
import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
import {
IsoDateTime,
PositiveInt,
ThreadId,
ThreadPullRequestKey,
ThreadPullRequestLinkSource,
ThreadPullRequestSnapshot,
ThreadPullRequestStack,
TrimmedNonEmptyString,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import { toPersistenceSqlError, type ProjectionRepositoryError } from "./Errors.ts";
import * as Layer from "effect/Layer";
import * as Struct from "effect/Struct";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
export const ProjectionThreadPullRequest = Schema.Struct({
threadId: ThreadId,
host: TrimmedNonEmptyString,
repository: TrimmedNonEmptyString,
number: PositiveInt,
url: TrimmedNonEmptyString,
source: ThreadPullRequestLinkSource,
linkedAt: IsoDateTime,
snapshot: Schema.NullOr(ThreadPullRequestSnapshot),
stack: Schema.NullOr(ThreadPullRequestStack),
});
export type ProjectionThreadPullRequest = typeof ProjectionThreadPullRequest.Type;
export const ListProjectionThreadPullRequestsInput = Schema.Struct({
threadId: ThreadId,
});
export type ListProjectionThreadPullRequestsInput =
typeof ListProjectionThreadPullRequestsInput.Type;
export const ListProjectionThreadPullRequestsByPullRequestInput = ThreadPullRequestKey;
export type ListProjectionThreadPullRequestsByPullRequestInput =
typeof ListProjectionThreadPullRequestsByPullRequestInput.Type;
export const DeleteProjectionThreadPullRequestInput = Schema.Struct({
threadId: ThreadId,
...ThreadPullRequestKey.fields,
});
export type DeleteProjectionThreadPullRequestInput =
typeof DeleteProjectionThreadPullRequestInput.Type;
export const DeleteProjectionThreadPullRequestsInput = Schema.Struct({
threadId: ThreadId,
});
export type DeleteProjectionThreadPullRequestsInput =
typeof DeleteProjectionThreadPullRequestsInput.Type;
export const DeleteProjectionThreadPullRequestsBySourceInput = Schema.Struct({
threadId: ThreadId,
source: ThreadPullRequestLinkSource,
});
export type DeleteProjectionThreadPullRequestsBySourceInput =
typeof DeleteProjectionThreadPullRequestsBySourceInput.Type;
const ProjectionThreadPullRequestDbRow = ProjectionThreadPullRequest.mapFields(
Struct.assign({
snapshot: Schema.NullOr(Schema.fromJsonString(ThreadPullRequestSnapshot)),
stack: Schema.NullOr(Schema.fromJsonString(ThreadPullRequestStack)),
}),
);
export class ProjectionThreadPullRequestRepository extends Context.Service<
ProjectionThreadPullRequestRepository,
{
readonly upsert: (
row: ProjectionThreadPullRequest,
) => Effect.Effect<void, ProjectionRepositoryError>;
readonly listByThreadId: (
input: ListProjectionThreadPullRequestsInput,
) => Effect.Effect<ReadonlyArray<ProjectionThreadPullRequest>, ProjectionRepositoryError>;
readonly listByPullRequest: (
input: ListProjectionThreadPullRequestsByPullRequestInput,
) => Effect.Effect<ReadonlyArray<ProjectionThreadPullRequest>, ProjectionRepositoryError>;
readonly delete: (
input: DeleteProjectionThreadPullRequestInput,
) => Effect.Effect<void, ProjectionRepositoryError>;
readonly deleteByThreadId: (
input: DeleteProjectionThreadPullRequestsInput,
) => Effect.Effect<void, ProjectionRepositoryError>;
readonly deleteByThreadIdAndSource: (
input: DeleteProjectionThreadPullRequestsBySourceInput,
) => Effect.Effect<void, ProjectionRepositoryError>;
}
>()("t3/persistence/ProjectionThreadPullRequests/ProjectionThreadPullRequestRepository") {}
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertProjectionThreadPullRequestRow = SqlSchema.void({
Request: ProjectionThreadPullRequest,
execute: (row) => sql`
INSERT INTO projection_thread_pull_requests (
thread_id,
host,
repository,
number,
url,
source,
linked_at,
snapshot_json,
stack_json
)
VALUES (
${row.threadId},
${row.host},
${row.repository},
${row.number},
${row.url},
${row.source},
${row.linkedAt},
${row.snapshot === null ? null : JSON.stringify(row.snapshot)},
${row.stack === null ? null : JSON.stringify(row.stack)}
)
ON CONFLICT (thread_id, host, repository, number)
DO UPDATE SET
url = excluded.url,
source = excluded.source,
linked_at = excluded.linked_at,
snapshot_json = excluded.snapshot_json,
stack_json = excluded.stack_json
`,
});
const listProjectionThreadPullRequestRows = SqlSchema.findAll({
Request: ListProjectionThreadPullRequestsInput,
Result: ProjectionThreadPullRequestDbRow,
execute: ({ threadId }) => sql`
SELECT
thread_id AS "threadId",
host,
repository,
number,
url,
source,
linked_at AS "linkedAt",
snapshot_json AS "snapshot",
stack_json AS "stack"
FROM projection_thread_pull_requests
WHERE thread_id = ${threadId}
ORDER BY linked_at ASC, number ASC
`,
});
const listProjectionThreadPullRequestRowsByPullRequest = SqlSchema.findAll({
Request: ListProjectionThreadPullRequestsByPullRequestInput,
Result: ProjectionThreadPullRequestDbRow,
execute: ({ host, repository, number }) => sql`
SELECT
thread_id AS "threadId",
host,
repository,
number,
url,
source,
linked_at AS "linkedAt",
snapshot_json AS "snapshot",
stack_json AS "stack"
FROM projection_thread_pull_requests
WHERE host = ${host}
AND repository = ${repository}
AND number = ${number}
ORDER BY linked_at ASC, thread_id ASC
`,
});
const deleteProjectionThreadPullRequestRow = SqlSchema.void({
Request: DeleteProjectionThreadPullRequestInput,
execute: ({ threadId, host, repository, number }) => sql`
DELETE FROM projection_thread_pull_requests
WHERE thread_id = ${threadId}
AND host = ${host}
AND repository = ${repository}
AND number = ${number}
`,
});
const deleteProjectionThreadPullRequestRows = SqlSchema.void({
Request: DeleteProjectionThreadPullRequestsInput,
execute: ({ threadId }) => sql`
DELETE FROM projection_thread_pull_requests
WHERE thread_id = ${threadId}
`,
});
const deleteProjectionThreadPullRequestRowsBySource = SqlSchema.void({
Request: DeleteProjectionThreadPullRequestsBySourceInput,
execute: ({ threadId, source }) => sql`
DELETE FROM projection_thread_pull_requests
WHERE thread_id = ${threadId}
AND source = ${source}
`,
});
const upsert: ProjectionThreadPullRequestRepository["Service"]["upsert"] = (row) =>
upsertProjectionThreadPullRequestRow({ ...row, ...normalizeThreadPullRequestKey(row) }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionThreadPullRequestRepository.upsert:query")),
);
const listByThreadId: ProjectionThreadPullRequestRepository["Service"]["listByThreadId"] = (
input,
) =>
listProjectionThreadPullRequestRows(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadPullRequestRepository.listByThreadId:query"),
),
);
const listByPullRequest: ProjectionThreadPullRequestRepository["Service"]["listByPullRequest"] = (
input,
) =>
listProjectionThreadPullRequestRowsByPullRequest(normalizeThreadPullRequestKey(input)).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadPullRequestRepository.listByPullRequest:query"),
),
);
const deleteLink: ProjectionThreadPullRequestRepository["Service"]["delete"] = (input) =>
deleteProjectionThreadPullRequestRow({
...input,
...normalizeThreadPullRequestKey(input),
}).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionThreadPullRequestRepository.delete:query")),
);
const deleteByThreadId: ProjectionThreadPullRequestRepository["Service"]["deleteByThreadId"] = (
input,
) =>
deleteProjectionThreadPullRequestRows(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadPullRequestRepository.deleteByThreadId:query"),
),
);
const deleteByThreadIdAndSource: ProjectionThreadPullRequestRepository["Service"]["deleteByThreadIdAndSource"] =
(input) =>
deleteProjectionThreadPullRequestRowsBySource(input).pipe(
Effect.mapError(
toPersistenceSqlError(
"ProjectionThreadPullRequestRepository.deleteByThreadIdAndSource:query",
),
),
);
return {
upsert,
listByThreadId,
listByPullRequest,
delete: deleteLink,
deleteByThreadId,
deleteByThreadIdAndSource,
} satisfies ProjectionThreadPullRequestRepository["Service"];
});
export const layer = Layer.effect(ProjectionThreadPullRequestRepository, make);
@@ -124,6 +124,7 @@ const makeProjectedThread = (input: {
modelSelection: { instanceId: sourceThread.providerInstanceId, model: "default" },
runtimeMode: "full-access",
interactionMode: "default",
pullRequests: [],
branch: null,
worktreePath: null,
latestTurn: null,
@@ -1,3 +1,4 @@
import { buildRuntimeInstructions } from "../RuntimeInstructions.ts";
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
@@ -392,8 +393,7 @@ describe("ClaudeAdapterLive", () => {
assert.deepEqual(createInput?.options.systemPrompt, {
type: "preset",
preset: "claude_code",
append:
"<runtime_info>In case you're asked: you are running in T3 Code through the Claude Code harness. No need to mention this otherwise. You can embed images and videos in your response using Markdown with absolute file paths.</runtime_info>",
append: buildRuntimeInstructions({ harness: "Claude Code" }),
});
assert.equal(createInput?.options.permissionMode, "bypassPermissions");
assert.equal(createInput?.options.allowDangerouslySkipPermissions, true);
@@ -2283,6 +2283,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
"-c",
'mcp_servers.t3-code.bearer_token_env_var="T3_MCP_BEARER_TOKEN"',
],
browserToolsAvailable: mcpSession.preview,
}
: {}),
};
@@ -166,6 +166,13 @@ export interface CodexSessionRuntimeOptions {
readonly serviceTier?: CodexServiceTier | undefined;
readonly resumeCursor?: CodexResumeCursor;
readonly appServerArgs?: ReadonlyArray<string>;
/**
* Whether the attached `t3-code` MCP server exposes the preview tools. The
* server is attached for every session now (the pull request toolkit is
* always on), so its presence in `appServerArgs` no longer implies browser
* access; the credential's own capability decides the developer prompt.
*/
readonly browserToolsAvailable?: boolean;
}
export interface CodexSessionRuntimeSendTurnInput {
@@ -2349,10 +2356,12 @@ export const makeCodexSessionRuntime = (
...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
...(input.effort ? { effort: input.effort } : {}),
...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),
// Derived from the session's own MCP configuration rather than the
// Derived from the session's own credential rather than the
// setting, so the prompt describes the tools this turn actually
// has even if the setting changed after the session started.
browserToolsAvailable: hasConfiguredMcpServer(options.appServerArgs),
browserToolsAvailable:
hasConfiguredMcpServer(options.appServerArgs) &&
(options.browserToolsAvailable ?? true),
});
const rawResponse = yield* client.raw.request("turn/start", params);
const response = yield* decodeV2TurnStartResponse(rawResponse).pipe(
@@ -4797,7 +4797,6 @@ boundedListing.layer("ProviderServiceLive session listing", (it) => {
const decodeBrowserAccessThreadShell = Schema.decodeUnknownEffect(OrchestrationThreadShell);
describe("agent browser access", () => {
const revokedThreads: Array<ThreadId> = [];
const projectId = ProjectId.make("project-browser-access");
const startSessionWith = (
@@ -4806,7 +4805,7 @@ describe("agent browser access", () => {
projectOverride?: boolean,
) =>
Effect.gen(function* () {
const issued: Array<ThreadId> = [];
const issued: Array<{ readonly threadId: ThreadId; readonly preview: boolean }> = [];
const codex = makeFakeCodexAdapter();
const providerAdapterLayer = Layer.succeed(
ProviderAdapterRegistry.ProviderAdapterRegistry,
@@ -4865,10 +4864,9 @@ describe("agent browser access", () => {
const providerLayer = makeProviderServiceLive({
issueMcpCredential: (request) =>
Effect.sync(() => {
issued.push(request.threadId);
issued.push({ threadId: request.threadId, preview: request.preview });
return undefined;
}),
revokeMcpCredential: (revoked) => Effect.sync(() => void revokedThreads.push(revoked)),
}).pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
@@ -4903,48 +4901,34 @@ describe("agent browser access", () => {
return issued;
});
// Credential issuance is the observable that matters: it is the only place a
// credential is minted, and `/mcp` accepts nothing else, so withholding it is
// what actually denies every provider and external MCP client.
it.effect("requests no MCP credential when agent browser access is off", () =>
// The capability on the credential is the observable that matters: a session
// always gets a credential (the pull request toolkit is never withheld), and
// `preview` on it is what actually grants or denies the browser tools.
it.effect("issues a credential without preview when agent browser access is off", () =>
Effect.gen(function* () {
const issued = yield* startSessionWith(false, asThreadId("thread-browser-off"));
const threadId = asThreadId("thread-browser-off");
assert.deepEqual(issued, []);
const issued = yield* startSessionWith(false, threadId);
assert.deepEqual(issued, [{ threadId, preview: false }]);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("revokes an already-issued credential when access is off", () =>
Effect.gen(function* () {
const threadId = asThreadId("thread-browser-revoke");
revokedThreads.length = 0;
yield* startSessionWith(false, threadId);
// Clearing the in-memory map is not enough: a token issued before the
// toggle flipped stays valid against `/mcp` for its whole liveness
// window, and later turns refresh it.
assert.deepEqual(revokedThreads, [threadId]);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("requests an MCP credential when agent browser access is on", () =>
it.effect("issues a credential with preview when agent browser access is on", () =>
Effect.gen(function* () {
const threadId = asThreadId("thread-browser-on");
const issued = yield* startSessionWith(true, threadId);
assert.deepEqual(issued, [threadId]);
assert.deepEqual(issued, [{ threadId, preview: true }]);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("withholds and revokes MCP credentials when the project disables browser access", () =>
it.effect("issues a credential without preview when the project disables browser access", () =>
Effect.gen(function* () {
const threadId = asThreadId("thread-project-browser-off");
revokedThreads.length = 0;
const issued = yield* startSessionWith(true, threadId, false);
assert.deepEqual(issued, []);
assert.deepEqual(revokedThreads, [threadId]);
assert.deepEqual(issued, [{ threadId, preview: false }]);
}).pipe(Effect.provide(NodeServices.layer)),
);
@@ -4952,7 +4936,7 @@ describe("agent browser access", () => {
Effect.gen(function* () {
const threadId = asThreadId("thread-project-browser-on");
const issued = yield* startSessionWith(false, threadId, true);
assert.deepEqual(issued, [threadId]);
assert.deepEqual(issued, [{ threadId, preview: true }]);
}).pipe(Effect.provide(NodeServices.layer)),
);
});
@@ -249,8 +249,6 @@ export interface ProviderServiceLiveOptions {
* test see whether a credential was requested at all.
*/
readonly issueMcpCredential?: typeof McpSessionRegistry.issueActiveMcpCredential;
/** Same seam as `issueMcpCredential`, for observing the deny path's revoke. */
readonly revokeMcpCredential?: typeof McpSessionRegistry.revokeActiveMcpThread;
}
interface TurnAnalyticsMetadata {
@@ -479,8 +477,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
);
const issueMcpCredential =
options?.issueMcpCredential ?? McpSessionRegistry.issueActiveMcpCredential;
const revokeMcpCredential =
options?.revokeMcpCredential ?? McpSessionRegistry.revokeActiveMcpThread;
const fileSystem = yield* FileSystem.FileSystem;
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const pendingCompactions = new Map<ThreadId, PendingCompaction>();
@@ -853,14 +849,8 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
yield* recordCompletedTurnProperties(properties);
});
/**
* Attach the `t3-code` MCP server to the session that is about to start.
* Whether the credential minted below may drive the user's browser.
*
* This is the only place a credential is minted, so withholding one here is
* what disables agent browser access everywhere: every adapter already
* treats a missing session as "no MCP server", and the `/mcp` endpoint
* accepts nothing but tokens issued from this path.
*/
/**
* Deny on an unreadable settings file rather than letting the read failure
* escape: adding `ServerSettingsError` to `ProviderServiceError` would widen
* a union every caller handles, for a branch that only decides whether one
@@ -889,20 +879,20 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
),
);
/**
* Attach the `t3-code` MCP server to the session that is about to start.
*
* Every session gets a credential: the pull request toolkit is always on,
* since it only registers links on the session's own thread. Browser access
* is a capability on that credential, so turning the setting off withholds
* the preview tools without taking the server away. `issueActiveMcpCredential`
* revokes the thread's previous token first, which matters because a session
* restart (runtime mode, cwd, model) re-prepares without stopping.
*/
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
Effect.gen(function* () {
if (!(yield* agentBrowserAccessEnabled(threadId))) {
// Revoke as well as clear. Every other prepare path reaches
// `issueActiveMcpCredential`, which revokes the thread first, so
// skipping it here would leave a previously issued bearer token valid
// against `/mcp` for the rest of its liveness window — and later turns
// would keep refreshing it. A session restart (runtime mode, cwd,
// model) re-prepares without stopping, so it relies on this.
yield* revokeMcpCredential(threadId);
yield* Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId));
return undefined;
}
const credential = yield* issueMcpCredential({ threadId, providerInstanceId });
const preview = yield* agentBrowserAccessEnabled(threadId);
const credential = yield* issueMcpCredential({ threadId, providerInstanceId, preview });
if (credential) {
yield* Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config));
}
@@ -98,6 +98,7 @@ function makeReadModel(
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
pullRequests: [],
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -2,6 +2,14 @@ import { describe, expect, it } from "vite-plus/test";
import { buildRuntimeInstructions } from "./RuntimeInstructions.ts";
describe("buildRuntimeInstructions", () => {
it("requires explicit registration of every PR and stack layer", () => {
const instructions = buildRuntimeInstructions({ harness: "Codex" });
expect(instructions).toContain("When the t3-code MCP server exposes link_pull_request");
expect(instructions).toContain("with the full PR URL immediately after creating a PR");
expect(instructions).toContain("For a stack, call it for every layer");
expect(instructions).toContain("call list_thread_pull_requests and link any PR");
});
it("keeps known model and effort metadata on one line", () => {
expect(
buildRuntimeInstructions({
@@ -1,3 +1,7 @@
const PULL_REQUEST_LINKING_INSTRUCTIONS = `<pull_request_linking>
When the t3-code MCP server exposes link_pull_request, you must use it to register every pull request you create or work on for this thread. Call link_pull_request with the full PR URL immediately after creating a PR or starting work on an existing PR. For a stack, call it for every layer, not just the current branch or the top PR. This applies when creating or updating PRs through gh, gh stack, another CLI, or the host API: those operations do not register the PRs with this thread. Linking an already-linked PR is safe. Before finishing PR work, call list_thread_pull_requests and link any PR from your work that is missing. Do not link unrelated PRs mentioned only as background. If a linking call fails, report that failure instead of claiming the PR is linked.
</pull_request_linking>`;
/** Shared runtime context; omit model and effort when the harness manages them dynamically. */
export function buildRuntimeInstructions(runtime: {
readonly harness: string;
@@ -9,7 +13,7 @@ export function buildRuntimeInstructions(runtime: {
const effort = toSingleLine(runtime.reasoningEffort ?? "");
const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${model}` : "";
const effortInfo = effort ? ` with ${effort} reasoning effort` : "";
return `<runtime_info>In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images and videos in your response using Markdown with absolute file paths.</runtime_info>`;
return `<runtime_info>In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images and videos in your response using Markdown with absolute file paths.</runtime_info>\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`;
}
function toSingleLine(value: string): string {
@@ -183,20 +183,37 @@ afterEach(() => {
});
layer("GitHubPullRequestCli.layer", (it) => {
it.effect("reads linked pull request status through one narrow request", () =>
it.effect("reads linked pull request status with the overview fields in one request", () =>
Effect.gen(function* () {
mockedGetPullRequest.mockReturnValueOnce(
Effect.succeed({
number: 7,
title: "Reuse the summary",
url: "https://github.com/acme/web/pull/7",
baseRefName: "main",
headRefName: "feat/summary",
state: "merged",
closedAt: "2026-08-23T10:00:00Z",
mergedAt: "2026-08-23T10:00:00Z",
updatedAt: "2026-08-24T12:34:56.000Z",
}),
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
number: 7,
title: "Reuse the summary",
url: "https://github.com/acme/web/pull/7",
author: { login: "octocat", name: "Octo Cat" },
baseRefName: "main",
headRefName: "feat/summary",
state: "OPEN",
isDraft: false,
mergeable: "MERGEABLE",
reviewDecision: "APPROVED",
additions: 12,
deletions: 3,
changedFiles: 2,
createdAt: "2026-08-20T00:00:00.000Z",
updatedAt: "2026-08-24T12:34:56.000Z",
reviewRequests: [],
labels: [],
statusCheckRollup: [
{ __typename: "CheckRun", status: "COMPLETED", conclusion: "SUCCESS", name: "ci" },
],
body: "",
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
@@ -207,23 +224,207 @@ layer("GitHubPullRequestCli.layer", (it) => {
number: 7,
});
assert.deepStrictEqual(summary, {
number: 7,
title: "Reuse the summary",
url: "https://github.com/acme/web/pull/7",
headBranch: "feat/summary",
baseBranch: "main",
state: "merged",
closedAt: "2026-08-23T10:00:00Z",
mergedAt: "2026-08-23T10:00:00Z",
updatedAt: "2026-08-24T12:34:56.000Z",
});
expect(mockedGetPullRequest).toHaveBeenCalledOnce();
expect(mockedGetPullRequest).toHaveBeenCalledWith({
assert.deepStrictEqual(
{
number: summary.number,
state: summary.state,
headBranch: summary.headBranch,
isDraft: summary.isDraft,
author: summary.author?.login,
additions: summary.additions,
deletions: summary.deletions,
changedFiles: summary.changedFiles,
reviewDecision: summary.reviewDecision,
checksState: summary.checksState,
mergeability: summary.mergeability,
},
{
number: 7,
state: "open",
headBranch: "feat/summary",
isDraft: false,
author: "octocat",
additions: 12,
deletions: 3,
changedFiles: 2,
reviewDecision: "approved",
checksState: "passing",
mergeability: "mergeable",
},
);
expect(mockedExecute).toHaveBeenCalledOnce();
expect(mockedExecute.mock.calls[0]?.[0]?.args).toEqual([
"pr",
"view",
"7",
"--repo",
"github.com/acme/web",
"--json",
expect.stringContaining("statusCheckRollup"),
]);
expect(mockedGetPullRequest).not.toHaveBeenCalled();
}),
);
it.effect("reads the stack a pull request is in through the stacks preview, on its host", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
id: 42,
number: 3,
url: "https://api.github.com/repos/acme/web/stacks/3",
base: { ref: "main" },
pull_requests: [
{
number: 6,
head: { ref: "feat/one" },
state: "closed",
merged_at: "2026-09-02",
},
{ number: 7, head: { ref: "feat/two" }, state: "open", merged_at: null },
],
},
]),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const stack = yield* cli.getPullRequestStack({
cwd: "/w",
reference: "https://github.com/acme/web/pull/7",
repository: "acme/web",
host: "ghe.example.com",
number: 7,
});
expect(mockedExecute).not.toHaveBeenCalled();
assert.deepStrictEqual(stack, {
id: "42",
number: 3,
url: "https://api.github.com/repos/acme/web/stacks/3",
base: "main",
layers: [
{ number: 6, headBranch: "feat/one", state: "merged" },
{ number: 7, headBranch: "feat/two", state: "open" },
],
});
assert.deepStrictEqual(callAt(0).args, [
"api",
"--hostname",
"ghe.example.com",
"repos/acme/web/stacks?pull_request=7",
]);
}),
);
it.effect("reads an empty stacks listing as not stacked", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const stack = yield* cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
assert.isNull(stack);
}),
);
it.effect("reads a host that refuses the stacks preview as not stacked", () =>
Effect.gen(function* () {
// The CLI classifies a missing preview endpoint as not found.
mockedExecute.mockReturnValueOnce(
Effect.fail(
new GitHubCli.GitHubPullRequestNotFoundError({
command: "gh",
cwd: "/w",
cause: new Error("HTTP 404: Not Found (https://api.github.com/repos/acme/web/stacks)"),
}),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const stack = yield* cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
assert.isNull(stack);
}),
);
it.effect("does not read a signed-out gh as an unstacked pull request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.fail(
new GitHubCli.GitHubCliAuthenticationError({
command: "gh",
cwd: "/w",
cause: new Error("gh auth login"),
}),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
}),
);
assert.strictEqual(error._tag, "GitHubCliAuthenticationError");
}),
);
it.effect("preserves transient stack failures instead of reporting no stack", () =>
Effect.gen(function* () {
const failure = new GitHubCli.GitHubCliCommandError({
command: "gh",
cwd: "/w",
cause: new Error("HTTP 503"),
});
mockedExecute.mockReturnValueOnce(Effect.fail(failure));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
}),
);
assert.strictEqual(error, failure);
}),
);
it.effect("reports a stacks answer it cannot read against the stack read", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output('[{"id":42}]')));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
}),
);
assert.strictEqual(error._tag, "GitHubPullRequestReadError");
if (error._tag !== "GitHubPullRequestReadError") return;
assert.strictEqual(error.operation, "getPullRequestStack");
}),
);
@@ -39,6 +39,7 @@ import {
decodePullRequestListJson,
decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
decodePullRequestStacksJson,
decodePullRequestStatsJson,
decodeReactionSubjectScopeJson,
decodeRepositoryAccessJson,
@@ -84,6 +85,7 @@ import {
type GitHubPullRequestHead,
type GitHubPullRequestListItem,
type GitHubPullRequestSearchItem,
type GitHubPullRequestStack,
type GitHubReviewThreadComments,
type GitHubRepositoryAccess,
type GitHubWorkflowRunApproval,
@@ -91,7 +93,7 @@ import {
type GitHubReviewThreadPage,
type GitHubViewerAccess,
} from "./gitHubPullRequestJson.ts";
import type { ProviderListCursor } from "./PullRequestProvider.ts";
import type { ProviderChangeRequestSummary, ProviderListCursor } from "./PullRequestProvider.ts";
/**
* Names the read that produced unusable output, so a failure reports the call it came from
@@ -460,21 +462,7 @@ export class GitHubPullRequestCli extends Context.Service<
readonly repository: string;
readonly host: string;
readonly number: number;
}) => Effect.Effect<
{
readonly number: number;
readonly title: string;
readonly url: string;
readonly headBranch: string;
readonly baseBranch: string;
readonly state: "open" | "closed" | "merged";
readonly isDraft?: boolean;
readonly closedAt?: string | null;
readonly mergedAt?: string | null;
readonly updatedAt: string;
},
GitHubPullRequestCliError
>;
}) => Effect.Effect<ProviderChangeRequestSummary, GitHubPullRequestCliError>;
readonly getPullRequestDetail: (input: {
readonly cwd: string;
@@ -494,6 +482,17 @@ export class GitHubPullRequestCli extends Context.Service<
readonly isCrossRepository: true;
}) => Effect.Effect<ReadonlyArray<GitHubWorkflowRunApproval>, GitHubPullRequestCliError>;
/**
* The host-native stack this pull request is in, or null when it is in none — which is also
* the answer for a host that refuses the stacks preview altogether.
*/
readonly getPullRequestStack: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
}) => Effect.Effect<GitHubPullRequestStack | null, GitHubPullRequestCliError>;
/**
* How far the branch trails its base, and whether this viewer may update it. Its own read
* because the comparison needs the head ref the detail answers with — a fork's branch is not
@@ -807,8 +806,8 @@ function matchesFilters(
viewer: string,
): boolean {
if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
const holds = (label: string) => labels.has(label.trim().toLowerCase());
return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
(filters.review === undefined ||
@@ -1630,41 +1629,94 @@ export const make = Effect.gen(function* () {
).pipe(Effect.map((results) => results.flat()));
},
// One `gh pr view` either way; asking for the detail fields costs nothing extra and hands
// the thread overview its author, diff stat, review decision and checks in the same read.
getPullRequestSummary: (input) =>
github
.getPullRequest({
.execute({
cwd: input.cwd,
reference: `https://${input.host}/${input.repository}/pull/${input.number}`,
args: [
"pr",
"view",
String(input.number),
...repositoryArgs(input),
"--json",
PULL_REQUEST_DETAIL_JSON_FIELDS,
],
})
.pipe(
Effect.flatMap((summary) =>
summary.updatedAt === undefined
? Effect.fail(
new GitHubPullRequestUpdatedAtUnavailableError({
command: "gh",
cwd: input.cwd,
repository: input.repository,
number: input.number,
}),
)
: Effect.succeed({
number: summary.number,
title: summary.title,
url: summary.url,
headBranch: summary.headRefName,
baseBranch: summary.baseRefName,
state: summary.state ?? "open",
...(summary.isDraft === true ? { isDraft: true } : {}),
closedAt: summary.closedAt ?? null,
mergedAt: summary.mergedAt ?? null,
updatedAt: summary.updatedAt,
Effect.flatMap((result) => {
const decoded = decodePullRequestDetailJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestReadError({
command: "gh",
cwd: input.cwd,
operation: "getPullRequestSummary",
cause: decoded.failure,
}),
),
);
}
const detail = decoded.success;
return Effect.succeed({
number: detail.number,
title: detail.title,
url: detail.url,
headBranch: detail.headBranch,
baseBranch: detail.baseBranch,
state: detail.state,
updatedAt: detail.updatedAt,
closedAt: detail.closedAt ?? null,
mergedAt: detail.mergedAt ?? null,
isDraft: detail.isDraft,
author: detail.author,
additions: detail.additions,
deletions: detail.deletions,
changedFiles: detail.changedFiles,
reviewDecision: detail.reviewDecision,
checksState: detail.checksState,
mergeability: detail.mergeability,
});
}),
),
getPullRequestDetail,
listWorkflowRunsRequiringApproval,
getPullRequestStack: (input) => {
const { owner, name } = parseRepositorySelector(input.repository);
return github
.execute({
cwd: input.cwd,
args: [
"api",
"--hostname",
input.host,
`repos/${owner}/${name}/stacks?pull_request=${input.number}`,
],
})
.pipe(
Effect.flatMap((result) => {
const decoded = decodePullRequestStacksJson(result.stdout.trim());
return Result.isSuccess(decoded)
? Effect.succeed(decoded.success)
: Effect.fail(
new GitHubPullRequestReadError({
command: "gh",
cwd: input.cwd,
operation: "getPullRequestStack",
cause: decoded.failure,
}),
);
}),
// Hosts without the stacks preview return 404. Other failures must preserve the
// previously synced stack and let the caller retry.
Effect.catchTags({
GitHubPullRequestNotFoundError: () => Effect.succeed(null),
}),
);
},
getPullRequestBaseComparison: (input) => {
const { owner, name } = parseRepositorySelector(input.repository);
return graphqlRead({
@@ -25,6 +25,7 @@ it.effect("uses one narrow read for a linked pull request summary", () =>
baseBranch: "main",
state: "open" as const,
updatedAt: "2026-08-24T12:34:56.000Z",
author: { login: "octocat", name: null, avatarUrl: null },
};
}),
}),
@@ -42,6 +43,66 @@ it.effect("uses one narrow read for a linked pull request summary", () =>
expect(summary.state).toBe("open");
expect(summaryReads).toBe(1);
// The author's avatar comes from the login-shaped URL, not a second request.
expect(summary.author?.avatarUrl).toBe("https://github.com/octocat.png?size=80");
}),
);
it.effect("declares host-native stacks and passes the one the CLI reads through", () =>
Effect.gen(function* () {
const stack = {
id: "42",
number: 3,
url: "https://github.com/acme/web/stacks/3",
base: "main",
layers: [
{ number: 6, headBranch: "feat/one", state: "merged" as const },
{ number: 7, headBranch: "feat/two", state: "open" as const },
],
};
const provider = yield* make.pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestStack: (input) => Effect.succeed(input.number === 7 ? stack : null),
}),
),
);
expect(provider.capabilities.stacks).toBe(true);
const readStack = provider.getChangeRequestStack;
if (readStack === undefined) return yield* Effect.die("stack read was not implemented");
const ref = { cwd: "/w", repository: "acme/web", host: "github.com" };
expect(yield* readStack({ ...ref, number: 7 })).toEqual(stack);
expect(yield* readStack({ ...ref, number: 8 })).toBeNull();
}),
);
it.effect("reports a failed stack read against its own operation", () =>
Effect.gen(function* () {
const provider = yield* make.pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestStack: () =>
Effect.fail(
new GitHubPullRequestCli.GitHubPullRequestReadError({
command: "gh",
cwd: "/w",
operation: "getPullRequestStack",
cause: new Error("unreadable"),
}),
),
}),
),
);
const readStack = provider.getChangeRequestStack;
if (readStack === undefined) return yield* Effect.die("stack read was not implemented");
const error = yield* Effect.flip(
readStack({ cwd: "/w", repository: "acme/web", host: "github.com", number: 7 }),
);
expect(error.operation).toBe("getChangeRequestStack");
expect(error.reason).toBe("failed");
}),
);
@@ -47,6 +47,7 @@ const CAPABILITIES: PullRequestCapabilities = {
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
stacks: true,
labels: true,
};
@@ -292,7 +293,20 @@ export const make = Effect.gen(function* () {
.pipe(Effect.mapError(fail("listChangeRequestStats"))),
getChangeRequestSummary: (input) =>
cli.getPullRequestSummary(input).pipe(Effect.mapError(fail("getChangeRequestSummary"))),
cli.getPullRequestSummary(input).pipe(
// `gh pr view` names the author without an avatar; the login-shaped URL every user
// has stands in, without the second request the listing spends on it.
Effect.map((summary) => ({
...summary,
...(summary.author === undefined
? {}
: { author: withAvatar(summary.author, new Map(), input.host) }),
})),
Effect.mapError(fail("getChangeRequestSummary")),
),
getChangeRequestStack: (input) =>
cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
getChangeRequest: (input) =>
Effect.all(
@@ -103,6 +103,34 @@ export interface ProviderChangeRequestSummary {
readonly closedAt?: string | null;
readonly mergedAt?: string | null;
readonly updatedAt: string;
/** Overview fields, present where the host's single read returns them at no extra cost. */
readonly author?: PullRequestActor | null | undefined;
readonly additions?: number | undefined;
readonly deletions?: number | undefined;
readonly changedFiles?: number | undefined;
readonly reviewDecision?: PullRequestReviewDecision | null | undefined;
readonly checksState?: PullRequestChecksState | null | undefined;
readonly mergeability?: PullRequestMergeability | undefined;
}
/** One layer of a host-native stack, bottom to top order is the array's. */
export interface ProviderChangeRequestStackLayer {
readonly number: number;
readonly headBranch: string;
readonly state: PullRequestState;
}
/**
* A host-native stack: an ordered set of change requests the host itself merges and retargets as
* a unit. Only GitHub offers one today; the neutral shape lets the sync reactor and the UI stay
* ignorant of which host said so.
*/
export interface ProviderChangeRequestStack {
readonly id: string;
readonly number: number;
readonly url: string;
readonly base: string;
readonly layers: ReadonlyArray<ProviderChangeRequestStackLayer>;
}
export interface ProviderChangeRequestPage {
@@ -331,6 +359,14 @@ export interface PullRequestProviderApi {
input: ProviderRepositoryRef & { readonly number: number },
) => Effect.Effect<ProviderChangeRequestSummary, PullRequestProviderError>;
/**
* The host-native stack a change request belongs to, or null when it is not stacked. Optional
* because most hosts have no such object; the service derives chains from base branches there.
*/
readonly getChangeRequestStack?: (
input: ProviderRepositoryRef & { readonly number: number },
) => Effect.Effect<ProviderChangeRequestStack | null, PullRequestProviderError>;
/** Comments, line threads, and commits, kept off the critical path for the core detail. */
readonly getChangeRequestActivity: (
input: ProviderRepositoryRef & { readonly number: number },
@@ -32,6 +32,7 @@ function project(input: {
readonly repository?: string;
readonly provider?: string;
readonly host?: string;
readonly remoteUrl?: string;
}): OrchestrationProjectShell {
// The host defaults from the provider, so a fixture only names one when the point of the
// test is two hosts of the same kind.
@@ -47,7 +48,7 @@ function project(input: {
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: `https://${host}/${input.repository}.git`,
remoteUrl: input.remoteUrl ?? `https://${host}/${input.repository}.git`,
},
provider: input.provider ?? "github",
displayName: input.repository,
@@ -470,7 +471,7 @@ it.effect("uses a provider's raw cursor advance when it consumed malformed rows"
// Keyed by the selector Azure is actually asked with, which is the repository's own name.
assert.deepStrictEqual(result.nextCursors, {
"dev.azure.com web": "2026-07-02T00:00:00Z|4|7",
"dev.azure.com dev.azure.com/acme/web": "2026-07-02T00:00:00Z|4|7",
});
}),
);
@@ -1563,6 +1564,247 @@ it.effect("refuses a repository that does not belong to the requested project",
}),
);
it.effect("reads a host-native stack through the provider and null where it has none", () =>
Effect.gen(function* () {
const service = yield* makeService({
projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
providers: [
fakeProvider("github", {
getChangeRequestStack: () =>
Effect.succeed({
id: "9",
number: 3,
url: "https://github.com/acme/web/stacks/3",
base: "main",
layers: [
{ number: 7, headBranch: "a", state: "open" as const },
{ number: 8, headBranch: "b", state: "open" as const },
],
}),
}),
],
});
const stack = yield* service.stack({
projectId: "p1" as ProjectId,
repository: "acme/web",
number: 7,
});
assert.deepStrictEqual(
stack?.layers.map((layer) => layer.number),
[7, 8],
);
const withoutStacks = yield* makeService({
projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
providers: [fakeProvider("github")],
});
assert.isNull(
yield* withoutStacks.stack({
projectId: "p1" as ProjectId,
repository: "acme/web",
number: 7,
}),
);
}),
);
it.effect("routes a hosted reference to another repository through a project on that host", () =>
Effect.gen(function* () {
const seen: Array<{ cwd: string; repository: string; host: string }> = [];
const service = yield* makeService({
projects: [
project({ id: "frontend", title: "web", workspaceRoot: "/web", repository: "acme/web" }),
],
providers: [
fakeProvider("github", {
getChangeRequestSummary: (input) =>
Effect.sync(() => {
seen.push({ cwd: input.cwd, repository: input.repository, host: input.host });
return changeRequest(7, "2026-07-02T00:00:00Z");
}),
}),
],
});
const summary = yield* service.summary(
{ projectId: "frontend" as ProjectId, host: "github.com", repository: "acme/api", number: 7 },
{ recoverTransientFailure: false },
);
assert.strictEqual(summary.number, 7);
assert.deepStrictEqual(seen, [{ cwd: "/web", repository: "acme/api", host: "github.com" }]);
}),
);
it.effect("routes Azure reads and writes through the requested organization's checkout", () =>
Effect.gen(function* () {
const seen: string[] = [];
const service = yield* makeService({
projects: ["org-a", "org-b"].map((organization) =>
project({
id: organization,
title: organization,
workspaceRoot: `/${organization}`,
repository: `${organization}/project/_git/web`,
provider: "azure-devops",
host: "dev.azure.com",
}),
),
providers: [
fakeProvider("azure-devops", {
getChangeRequestSummary: (input) =>
Effect.sync(() => {
seen.push(`read ${input.cwd} ${input.repository}`);
return changeRequest(7, "2026-07-02T00:00:00Z");
}),
runAction: (input) =>
Effect.sync(() => {
seen.push(`write ${input.cwd} ${input.repository}`);
}),
}),
],
});
const reference = {
projectId: "org-a" as ProjectId,
host: "dev.azure.com",
repository: "org-b/project/_git/web",
number: 7,
};
yield* service.summary(reference, { recoverTransientFailure: false });
yield* service.runAction({ ...reference, action: "merge" });
assert.deepStrictEqual(seen, ["read /org-b web", "write /org-b web", "read /org-b web"]);
}),
);
for (const checkout of [
{
host: "ssh.dev.azure.com",
repository: "v3/org-b/project/web",
remoteUrl: "[email protected]:v3/org-b/project/web",
},
{
host: "vs-ssh.visualstudio.com",
repository: "v3/org-b/project/web",
remoteUrl: "[email protected]:v3/org-b/project/web",
},
{
host: "org-b.visualstudio.com",
repository: "DefaultCollection/project/_git/web",
remoteUrl: "https://org-b.visualstudio.com/DefaultCollection/project/_git/web",
},
]) {
it.effect(`routes Azure URL reads and writes through a ${checkout.host} checkout`, () =>
Effect.gen(function* () {
const seen: string[] = [];
const target = project({
id: "target",
title: "target",
workspaceRoot: "/target",
provider: "azure-devops",
...checkout,
});
const service = yield* makeService({
projects: [
...["org-a/project/_git/web", "org-b/other-project/_git/web"].map((repository) =>
project({
id: repository,
title: repository,
workspaceRoot: `/${repository}`,
provider: "azure-devops",
host: "dev.azure.com",
repository,
}),
),
target,
],
providers: [
fakeProvider("azure-devops", {
getChangeRequestSummary: (input) =>
Effect.sync(() => {
seen.push(`read ${input.cwd} ${input.repository}`);
return changeRequest(7, "2026-07-02T00:00:00Z");
}),
runAction: (input) =>
Effect.sync(() => {
seen.push(`write ${input.cwd} ${input.repository}`);
}),
}),
],
});
const reference = {
projectId: "org-a/project/_git/web" as ProjectId,
host: "dev.azure.com",
repository: "org-b/project/_git/web",
number: 7,
};
yield* service.summary(reference, { recoverTransientFailure: false });
yield* service.runAction({ ...reference, action: "merge" });
assert.deepStrictEqual(seen, ["read /target web", "write /target web", "read /target web"]);
}),
);
}
it.effect("refuses Azure cross-organization reads and writes without its checkout", () =>
Effect.gen(function* () {
const service = yield* makeService({
projects: [
project({
id: "org-a",
title: "org-a",
workspaceRoot: "/org-a",
repository: "org-a/project/_git/web",
provider: "azure-devops",
host: "dev.azure.com",
}),
],
providers: [
fakeProvider("azure-devops", {
getChangeRequestSummary: () => Effect.die("must not read the wrong organization"),
runAction: () => Effect.die("must not modify the wrong organization"),
}),
],
});
const reference = {
projectId: "org-a" as ProjectId,
host: "dev.azure.com",
repository: "org-b/project/_git/web",
number: 7,
};
const readError = yield* Effect.flip(
service.summary(reference, { recoverTransientFailure: false }),
);
const writeError = yield* Effect.flip(service.runAction({ ...reference, action: "close" }));
assert.strictEqual(readError._tag, "PullRequestUnavailableError");
assert.strictEqual(writeError._tag, "PullRequestUnavailableError");
}),
);
it.effect("refuses a hosted reference when nothing is checked out from that host", () =>
Effect.gen(function* () {
const service = yield* makeService({
projects: [
project({ id: "frontend", title: "web", workspaceRoot: "/web", repository: "acme/web" }),
],
providers: [fakeProvider("github")],
});
const error = yield* service
.summary(
{
projectId: "frontend" as ProjectId,
host: "gitlab.com",
repository: "acme/api",
number: 7,
},
{ recoverTransientFailure: false },
)
.pipe(Effect.flip);
assert.strictEqual(error._tag, "PullRequestUnavailableError");
}),
);
it.effect("refuses a diff on a host that cannot produce one", () =>
Effect.gen(function* () {
const service = yield* makeService({
@@ -3377,6 +3619,48 @@ it.effect("does not ask the host again for a linked summary it already holds", (
}),
);
it.effect(
"opening detail preserves enriched linked summaries and updates draft and diff fields",
() =>
Effect.gen(function* () {
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
const service = yield* makeService({
projects: [
project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
],
providers: [
fakeProvider("github", {
getChangeRequestSummary: () =>
Effect.succeed({
...changeRequest(1, "2026-07-02T00:00:00Z"),
isDraft: true,
reviewDecision: "approved",
checksState: "passing",
}),
getChangeRequest: () =>
Effect.succeed({
...hostedChangeRequest("body", 14),
deletions: 3,
changedFiles: 5,
mergeability: "conflicting",
}),
}),
],
});
yield* service.summary(reference);
const detail = yield* service.detail(reference);
const summary = yield* service.summary(reference);
assert.strictEqual(summary.isDraft, false);
assert.deepStrictEqual(summary.author, detail.author);
assert.strictEqual(summary.additions, 14);
assert.strictEqual(summary.deletions, 3);
assert.strictEqual(summary.changedFiles, 5);
assert.strictEqual(summary.mergeability, "conflicting");
assert.strictEqual(summary.reviewDecision, "approved");
assert.strictEqual(summary.checksState, "passing");
}),
);
it.effect("reuses an observed merged state for strict settlement reads", () =>
Effect.gen(function* () {
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
@@ -3587,43 +3871,6 @@ it.effect("carries an armed auto-merge through to the detail, and silence as sil
}),
);
it("names an Azure DevOps repository by its own name, not its project path", () => {
// `az repos pr list --repository` takes a name and detects the organisation and project from
// the checkout; the recorded `org/project/_git/repo` path is refused, and the repository then
// reads as unavailable on the page.
const selector = PullRequestService.repositoryIdentityOf({
repositoryIdentity: {
provider: "azure-devops",
displayName: "contoso/payments/_git/checkout",
owner: "contoso",
name: "checkout",
},
} as never);
assert.strictEqual(selector, "checkout");
});
it("falls back to the path's last segment where an Azure identity has no name", () => {
const selector = PullRequestService.repositoryIdentityOf({
repositoryIdentity: {
provider: "azure-devops",
displayName: "contoso/payments/_git/checkout",
},
} as never);
assert.strictEqual(selector, "checkout");
});
it("keeps a GitLab identity's whole path, because a nested group is part of the name", () => {
const selector = PullRequestService.repositoryIdentityOf({
repositoryIdentity: {
provider: "gitlab",
displayName: "group/subgroup/service",
owner: "group",
name: "service",
},
} as never);
assert.strictEqual(selector, "group/subgroup/service");
});
it.effect("narrows the rows of a host that ignored the filters it was handed", () =>
Effect.gen(function* () {
const service = yield* makeService({
@@ -4137,3 +4384,40 @@ it.effect("names the signed-in account in the detail, and says nothing where the
assert.strictEqual(unnamed.viewer, undefined);
}),
);
it.effect("keeps Azure continuation cursors separate for repositories with the same name", () =>
Effect.gen(function* () {
const seen: string[] = [];
const service = yield* makeService({
projects: ["org-a", "org-b"].map((organization) =>
project({
id: organization,
title: organization,
workspaceRoot: `/${organization}`,
repository: `${organization}/project/_git/web`,
provider: "azure-devops",
host: "dev.azure.com",
}),
),
providers: [
fakeProvider("azure-devops", {
listChangeRequests: (input) =>
Effect.sync(() => {
seen.push(input.cwd);
return {
items: [changeRequest(7, "2026-07-02T00:00:00Z")],
truncated: true,
continues: true,
};
}),
}),
],
});
const first = yield* service.list({ state: "open" });
assert.lengthOf(Object.keys(first.nextCursors), 2);
const key = Object.keys(first.nextCursors).find((key) => key.includes("org-b"))!;
seen.length = 0;
yield* service.list({ state: "open", cursors: { [key]: first.nextCursors[key]! } });
assert.deepStrictEqual(seen, ["/org-b"]);
}),
);
+202 -59
View File
@@ -1,3 +1,7 @@
import {
canonicalRepositoryKey,
sourceControlRepositorySelector,
} from "@t3tools/shared/sourceControl";
import * as Cache from "effect/Cache";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
@@ -46,6 +50,7 @@ import {
type PullRequestLabelCandidateList,
type PullRequestLabelChangeInput,
type PullRequestSubmitReviewInput,
type PullRequestStack,
type PullRequestSummary,
type PullRequestThreadReplyInput,
type PullRequestThreadResolutionInput,
@@ -144,6 +149,13 @@ export class PullRequestService extends Context.Service<
input: PullRequestRef,
options?: { readonly recoverTransientFailure?: boolean },
) => Effect.Effect<PullRequestSummary, PullRequestError>;
/**
* The host-native stack the pull request belongs to, or null when it is not in one or the
* host keeps no such object. Cached like a summary; a stack changes about as often.
*/
readonly stack: (
input: PullRequestRef,
) => Effect.Effect<PullRequestStack | null, PullRequestError>;
readonly subscribeMerges: Effect.Effect<
Stream.Stream<PullRequestMergeEvent>,
never,
@@ -241,6 +253,7 @@ const LABEL_CHANGE_REFUSAL = "You need triage access on this repository to chang
/** A project this page can read: its remote is on a host with an implementation. */
interface SupportedProject {
readonly cursorKey: string;
readonly project: OrchestrationProjectShell;
readonly api: PullRequestProviderApi;
readonly repository: string;
@@ -453,7 +466,7 @@ function withRateLimitBackoff(
call: (...args: Args) => Effect.Effect<A, PullRequestProviderError>,
) => wrap(operation, call, true);
return {
const wrapped = {
kind: api.kind,
capabilities: api.capabilities,
getViewer: wrap("getViewer", api.getViewer),
@@ -474,6 +487,9 @@ function withRateLimitBackoff(
: {
getChangeRequestSummary: wrap("getChangeRequestSummary", api.getChangeRequestSummary),
}),
...(api.getChangeRequestStack === undefined
? {}
: { getChangeRequestStack: wrap("getChangeRequestStack", api.getChangeRequestStack) }),
getChangeRequestActivity: wrap("getChangeRequestActivity", api.getChangeRequestActivity),
...(api.getReviewThreadComments === undefined
? {}
@@ -506,30 +522,9 @@ function withRateLimitBackoff(
setReaction: interactive("setReaction", api.setReaction),
setThreadResolution: interactive("setThreadResolution", api.setThreadResolution),
};
}
/**
* The provider-native repository selector. `displayName` is the full path below the host, which
* is what nested GitLab groups need; owner/name is the two-segment fallback for identities
* recorded before that field existed.
*
* Azure DevOps is the exception: `az repos pr list --repository` takes a repository name, and
* takes the organisation and project from the checkout it detects — so the recorded
* `org/project/_git/repo` path is refused outright and the whole repository reads as
* unavailable. Its name is the last segment, which is what this hands over.
*
* One function because everything downstream is keyed by what it answers: the rows' own
* `repository`, the per-repository cursors, and the detail and diff reads a row leads to.
*/
export function repositoryIdentityOf(project: OrchestrationProjectShell): string | null {
const identity = project.repositoryIdentity;
if (!identity) return null;
if (identity.provider === "azure-devops") {
const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "_git");
return identity.name || segments.at(-1) || null;
}
if (identity.displayName) return identity.displayName;
return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;
// Optional provider methods must be forwarded too; returning the interface alone permits omissions.
return wrapped satisfies PullRequestProviderApi &
Record<Exclude<keyof PullRequestProviderApi, keyof typeof wrapped>, never>;
}
export const make = Effect.gen(function* () {
@@ -554,7 +549,11 @@ export const make = Effect.gen(function* () {
for (const project of projects) {
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
const identity = project.repositoryIdentity;
if (identity?.provider !== "unknown" || repositoryIdentityOf(project) === null) continue;
if (
identity?.provider !== "unknown" ||
sourceControlRepositorySelector(project.repositoryIdentity) === null
)
continue;
const host = pullRequestHostOf(identity, "unknown");
// A legacy identity has no canonical host until its provider is refined, so it must reach
// the refinement before a host filter can decide whether it belongs in the result.
@@ -628,7 +627,7 @@ export const make = Effect.gen(function* () {
if (filter.projectIds !== undefined && !filter.projectIds.includes(project.id)) continue;
const identity = project.repositoryIdentity;
let kind = identity?.provider as SourceControlProviderKind | undefined;
const repository = repositoryIdentityOf(project);
const repository = sourceControlRepositorySelector(project.repositoryIdentity);
if (!identity || kind === undefined || repository === null) continue;
// Worktrees of one repository are separate projects; reading the remote once keeps
// the page from repeating every change request per local checkout. The host is part
@@ -647,7 +646,10 @@ export const make = Effect.gen(function* () {
if (roots === undefined) viewerRoots.set(host, [project.workspaceRoot]);
else if (!roots.includes(project.workspaceRoot)) roots.push(project.workspaceRoot);
}
const key = listCursorKey(host, repository);
const key = listCursorKey(
host,
kind === "azure-devops" ? identity.canonicalKey : repository,
);
if (seen.has(key)) continue;
seen.add(key);
if (api === null) {
@@ -657,6 +659,7 @@ export const make = Effect.gen(function* () {
continue;
}
supported.push({
cursorKey: key,
project,
api: withRateLimitBackoff(api, host, rateLimits),
repository,
@@ -667,16 +670,30 @@ export const make = Effect.gen(function* () {
}),
);
/**
* The project whose checkout and credentials serve a reference. The project's own
* repository is the default; a reference that names a `host` may instead point at any
* repository on that host. Prefer its own checkout; providers with explicit repository
* targeting can fall back to another checkout on the host. Azure derives its organization
* from the checkout, so it requires a matching repository.
*/
const requireProject = (ref: PullRequestRef): Effect.Effect<SupportedProject, PullRequestError> =>
listWorkspaceProjects({ projectId: ref.projectId }).pipe(
Effect.flatMap(({ supported }): Effect.Effect<SupportedProject, PullRequestError> => {
const match = supported[0];
if (!match) {
return Effect.fail(new PullRequestUnavailableError({ reason: "provider-unsupported" }));
const own = supported[0];
const repository = ref.repository.trim();
const host = ref.host?.trim().toLowerCase();
if (own !== undefined && own.repository.toLowerCase() === repository.toLowerCase()) {
// Hostless references only ever meant the project's own repository, and a hosted one
// naming it still is; either way the project serves itself.
if (host === undefined || host === own.host) return Effect.succeed(own);
}
// The repository travels through the client, so it is checked against the project's
// own remote rather than being handed to a provider verbatim.
if (match.repository.toLowerCase() !== ref.repository.trim().toLowerCase()) {
if (host === undefined) {
if (own === undefined) {
return Effect.fail(new PullRequestUnavailableError({ reason: "provider-unsupported" }));
}
// The repository travels through the client, so it is checked against the project's
// own remote rather than being handed to a provider verbatim.
return Effect.fail(
new PullRequestOperationError({
operation: "resolveRepository",
@@ -684,7 +701,39 @@ export const make = Effect.gen(function* () {
}),
);
}
return Effect.succeed(match);
const repositoryKey = canonicalRepositoryKey(`${host}/${repository}`.toLowerCase());
// Azure SSH and legacy clone hosts differ from the browser URL's host. Compare
// the complete repository identity before narrowing those checkouts by host.
return listWorkspaceProjects(
repositoryKey.startsWith("dev.azure.com/") ? {} : { host },
).pipe(
Effect.flatMap(({ supported }) => {
const onHost = supported.filter((candidate) => candidate.host === host);
const route =
supported.find(
(candidate) =>
candidate.api.kind === "azure-devops" &&
candidate.project.repositoryIdentity != null &&
canonicalRepositoryKey(
candidate.project.repositoryIdentity.canonicalKey.toLowerCase(),
) === repositoryKey,
) ??
onHost.find(
(candidate) =>
candidate.api.kind !== "azure-devops" &&
candidate.repository.toLowerCase() === repository.toLowerCase(),
) ??
onHost.find((candidate) => candidate.api.kind !== "azure-devops");
if (route === undefined) {
return Effect.fail(
new PullRequestUnavailableError({ reason: "provider-unsupported" }),
);
}
return Effect.succeed(
route.api.kind === "azure-devops" ? route : { ...route, repository },
);
}),
);
}),
);
@@ -829,8 +878,8 @@ export const make = Effect.gen(function* () {
viewer: string,
): boolean => {
if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
const holds = (label: string) => labels.has(label.trim().toLowerCase());
return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
// Judged on the provider row rather than the entry, because the two absences mean
@@ -949,9 +998,7 @@ export const make = Effect.gen(function* () {
const selected =
continuation === null
? projects
: projects.filter(({ host, repository }) =>
continuation.has(listCursorKey(host, repository)),
);
: projects.filter(({ cursorKey }) => continuation.has(cursorKey));
const readable = selected.filter(({ host }) => viewers[host] !== undefined);
// A host that could not be read still has projects, and they are absent from the list.
// Reporting them keeps "N repositories were unavailable" honest instead of dropping them.
@@ -993,7 +1040,7 @@ export const make = Effect.gen(function* () {
const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT;
const cursorOf = (project: SupportedProject): ListCursor | undefined =>
continuation?.get(listCursorKey(project.host, project.repository));
continuation?.get(project.cursorKey);
/**
* One repository asked on its own. What every host without a search across repositories
@@ -1002,7 +1049,7 @@ export const make = Effect.gen(function* () {
const readRepository = (project: SupportedProject): Effect.Effect<RepositoryBatch> => {
{
const viewer = viewers[project.host]!;
const key = listCursorKey(project.host, project.repository);
const key = project.cursorKey;
const cursor = cursorOf(project);
return project.api
.listChangeRequests({
@@ -1161,7 +1208,7 @@ export const make = Effect.gen(function* () {
!cursorHere.seenAt.includes(item.number),
);
return Effect.succeed({
key: listCursorKey(project.host, project.repository),
key: project.cursorKey,
entries: items
.filter((item) => matchesRowFilters(item, input.filters, viewer))
.map((item) => toEntry({ project, item, viewer })),
@@ -1254,17 +1301,67 @@ export const make = Effect.gen(function* () {
title: changeRequest.title,
url: changeRequest.url,
state: changeRequest.state,
...(changeRequest.isDraft === true ? { isDraft: true } : {}),
headBranch: changeRequest.headBranch,
baseBranch: changeRequest.baseBranch,
closedAt: changeRequest.closedAt ?? null,
mergedAt: changeRequest.mergedAt ?? null,
updatedAt: changeRequest.updatedAt,
...(changeRequest.isDraft === undefined ? {} : { isDraft: changeRequest.isDraft }),
...(changeRequest.author === undefined ? {} : { author: changeRequest.author }),
...(changeRequest.additions === undefined
? {}
: { additions: changeRequest.additions }),
...(changeRequest.deletions === undefined
? {}
: { deletions: changeRequest.deletions }),
...(changeRequest.changedFiles === undefined
? {}
: { changedFiles: changeRequest.changedFiles }),
...(changeRequest.reviewDecision === undefined
? {}
: { reviewDecision: changeRequest.reviewDecision }),
...(changeRequest.checksState === undefined
? {}
: { checksState: changeRequest.checksState }),
...(changeRequest.mergeability === undefined
? {}
: { mergeability: changeRequest.mergeability }),
})),
);
}),
);
const stackUncached: PullRequestService["Service"]["stack"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project) => {
const read = project.api.getChangeRequestStack;
if (read === undefined) return Effect.succeed(null);
return read({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
}).pipe(
Effect.mapError(toPullRequestError("stack")),
Effect.map((stack): PullRequestStack | null =>
stack === null
? null
: {
id: stack.id,
number: stack.number,
url: stack.url,
base: stack.base,
layers: stack.layers.map((layer) => ({
number: layer.number,
headBranch: layer.headBranch,
state: layer.state,
})),
},
),
);
}),
);
const detailUncached: PullRequestService["Service"]["detail"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project) =>
@@ -1507,7 +1604,11 @@ export const make = Effect.gen(function* () {
})
.pipe(
Effect.mapError(toPullRequestError("runAction")),
Effect.as(project.repository),
Effect.as(
project.api.kind === "azure-devops"
? input.repository.trim()
: project.repository,
),
);
}),
);
@@ -2133,11 +2234,35 @@ export const make = Effect.gen(function* () {
let turnRefreshEpoch = 0;
const refEpochs = new Map<string, number>();
const REF_EPOCH_CAPACITY = 2_048;
const refScope = (ref: PullRequestRef) => `${ref.projectId} ${ref.repository} ${ref.number}`;
const refScope = (ref: PullRequestRef) =>
`${ref.projectId} ${ref.host?.toLowerCase() ?? ""} ${ref.repository.toLowerCase()} ${ref.number}`;
const refEpoch = (ref: PullRequestRef) =>
Math.max(turnRefreshEpoch, refEpochs.get(refScope(ref)) ?? 0);
// Keys carry the reference back out of the cache loader, so the slot layout is shared with
// `refOfCacheKey` rather than read positionally at every loader.
const refCacheKey = (ref: PullRequestRef) =>
JSON.stringify([refEpoch(ref), ref.projectId, ref.repository, ref.number]);
JSON.stringify([
refEpoch(ref),
ref.projectId,
ref.host?.toLowerCase() ?? null,
ref.repository.toLowerCase(),
ref.number,
]);
const refOfCacheKey = (key: string): PullRequestRef => {
const [, projectId, host, repository, number] = JSON.parse(key) as [
number,
string,
string | null,
string,
number,
];
return {
projectId,
...(host === null ? {} : { host }),
repository,
number,
} as PullRequestRef;
};
// Counts belong to a PR, not a filtered page. Background reads and filter changes reuse
// them; explicit refreshes, mutations, and turns strand old and in-flight results.
const statsCacheKey = (key: string) => JSON.stringify([listingsEpoch, key]);
@@ -2181,8 +2306,7 @@ export const make = Effect.gen(function* () {
const summaryCache = yield* Cache.makeWith(
(key: string) => {
const [, projectId, repository, number] = JSON.parse(key) as [number, string, string, number];
return summaryUncached({ projectId, repository, number } as PullRequestRef);
return summaryUncached(refOfCacheKey(key));
},
{
capacity: DETAIL_CACHE_CAPACITY,
@@ -2203,6 +2327,13 @@ export const make = Effect.gen(function* () {
);
};
const stackCache = yield* Cache.makeWith((key: string) => stackUncached(refOfCacheKey(key)), {
capacity: DETAIL_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? SUMMARY_CACHE_TTL : Duration.zero),
});
const stack: PullRequestService["Service"]["stack"] = (input) =>
Cache.get(stackCache, refCacheKey(input));
// Keys serialize positionally and parse back in the lookup, so the cache is the only holder
// of in-flight state: concurrent identical reads coalesce on the key into one host request.
// The continuation cursors are part of the key, entries sorted so one continuation is one
@@ -2283,8 +2414,7 @@ export const make = Effect.gen(function* () {
const detailCache = yield* Cache.makeWith(
(key: string) => {
const statsKey = statsCacheKey(key);
const [, projectId, repository, number] = JSON.parse(key) as [number, string, string, number];
return detailUncached({ projectId, repository, number } as PullRequestRef).pipe(
return detailUncached(refOfCacheKey(key)).pipe(
Effect.tap(
Effect.fn("PullRequestService.recordDetailStats")(function* (value: PullRequestDetail) {
recordStats(
@@ -2307,7 +2437,12 @@ export const make = Effect.gen(function* () {
timeToLive: (exit) => (Exit.isSuccess(exit) ? DETAIL_CACHE_TTL : Duration.zero),
},
);
const summaryFromDetail = (detail: PullRequestDetail): PullRequestSummary => ({
const summaryFromDetail = (
detail: PullRequestDetail,
previous: PullRequestSummary | undefined,
): PullRequestSummary => ({
// Detail does not carry review/check summaries. Keep the last summary observation.
...previous,
provider: detail.provider,
projectId: detail.projectId,
repository: detail.repository,
@@ -2315,7 +2450,12 @@ export const make = Effect.gen(function* () {
title: detail.title,
url: detail.url,
state: detail.state,
...(detail.isDraft === true ? { isDraft: true } : {}),
isDraft: detail.isDraft,
author: detail.author,
additions: detail.additions,
deletions: detail.deletions,
changedFiles: detail.changedFiles,
mergeability: detail.mergeability,
headBranch: detail.headBranch,
baseBranch: detail.baseBranch,
closedAt: detail.closedAt,
@@ -2338,7 +2478,7 @@ export const make = Effect.gen(function* () {
key,
Cache.get(detailCache, key).pipe(
Effect.tap((value) => {
const summary = summaryFromDetail(value);
const summary = summaryFromDetail(value, lastGoodSummary.peek(key));
return shouldReplaceHeldSummary(key, summary)
? lastGoodSummary.record(key, summary)
: Effect.void;
@@ -2350,8 +2490,7 @@ export const make = Effect.gen(function* () {
const activityCache = yield* Cache.makeWith(
(key: string) => {
const [, projectId, repository, number] = JSON.parse(key) as [number, string, string, number];
return activityUncached({ projectId, repository, number } as PullRequestRef);
return activityUncached(refOfCacheKey(key));
},
{
capacity: DETAIL_CACHE_CAPACITY,
@@ -2365,9 +2504,10 @@ export const make = Effect.gen(function* () {
const diffCache = yield* Cache.makeWith(
(key: string) => {
const [, projectId, repository, number, cursor, commit] = JSON.parse(key) as [
const [, projectId, host, repository, number, cursor, commit] = JSON.parse(key) as [
number,
string,
string | null,
string,
number,
string | null,
@@ -2375,6 +2515,7 @@ export const make = Effect.gen(function* () {
];
return diffUncached({
projectId,
...(host === null ? {} : { host }),
repository,
number,
...(cursor === null ? {} : { cursor }),
@@ -2385,7 +2526,7 @@ export const make = Effect.gen(function* () {
capacity: DIFF_CACHE_CAPACITY,
timeToLive: (exit, key) => {
if (!Exit.isSuccess(exit)) return Duration.zero;
const commit = (JSON.parse(key) as ReadonlyArray<unknown>)[5];
const commit = (JSON.parse(key) as ReadonlyArray<unknown>)[6];
return commit === null ? DIFF_CACHE_TTL : COMMIT_DIFF_CACHE_TTL;
},
},
@@ -2394,7 +2535,8 @@ export const make = Effect.gen(function* () {
const key = JSON.stringify([
refEpoch(input),
input.projectId,
input.repository,
input.host?.toLowerCase() ?? null,
input.repository.toLowerCase(),
input.number,
input.cursor ?? null,
input.commit ?? null,
@@ -2523,6 +2665,7 @@ export const make = Effect.gen(function* () {
list,
listStats,
summary,
stack,
subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
Effect.map((subscription) => Stream.fromSubscription(subscription)),
),
@@ -11,6 +11,7 @@ import {
decodePullRequestListJson,
decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
decodePullRequestStacksJson,
decodeLabelCandidatesJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
@@ -1500,3 +1501,81 @@ describe("how far a branch trails its base", () => {
expect(Result.isSuccess(decodeBaseComparisonJson("{"))).toBe(false);
});
});
describe("host-native stack decoding", () => {
/** A stack as the preview lists it, bottom to top, with the fields it answers today. */
function stack(overrides: Record<string, unknown> = {}) {
return {
id: 42,
number: 3,
node_id: "STK_kwDO",
url: "https://api.github.com/repos/acme/web/stacks/3",
base: { ref: "main", sha: "abc" },
open: true,
created_at: "2026-09-01T00:00:00Z",
pull_requests: [
{
number: 10,
head: { ref: "feat/one" },
state: "closed",
merged_at: "2026-09-02T00:00:00Z",
},
{ number: 11, head: { ref: "feat/two" }, state: "open", merged_at: null },
{ number: 12, head: { ref: "feat/three" }, state: "closed", merged_at: null },
],
...overrides,
};
}
/** The one stack a listing answered with, which these reads all expect to find. */
function expectStack(overrides: Record<string, unknown> = {}) {
const decoded = expectSuccess(decodePullRequestStacksJson(JSON.stringify([stack(overrides)])));
if (decoded === null) throw new Error("expected a stack");
return decoded;
}
it("reads the first stack, bottom to top, with merged_at outranking state", () => {
expect(expectStack()).toEqual({
id: "42",
number: 3,
url: "https://api.github.com/repos/acme/web/stacks/3",
base: "main",
layers: [
{ number: 10, headBranch: "feat/one", state: "merged" },
{ number: 11, headBranch: "feat/two", state: "open" },
{ number: 12, headBranch: "feat/three", state: "closed" },
],
});
});
it("accepts a base named as a bare branch, which is what the preview started out sending", () => {
expect(expectStack({ base: "develop" }).base).toBe("develop");
});
it("prefers the page a person opens over the API URL, where the host reports one", () => {
expect(expectStack({ html_url: "https://github.com/acme/web/stacks/3" }).url).toBe(
"https://github.com/acme/web/stacks/3",
);
});
it("falls back to the node id, then the number, for a stack without an id", () => {
expect(expectStack({ id: undefined }).id).toBe("STK_kwDO");
expect(expectStack({ id: null, node_id: null }).id).toBe("3");
});
it("reads an empty listing as not stacked", () => {
expect(expectSuccess(decodePullRequestStacksJson("[]"))).toBeNull();
});
it("refuses a stack without a number or without its pull requests", () => {
expect(
Result.isSuccess(decodePullRequestStacksJson(JSON.stringify([stack({ number: undefined })]))),
).toBe(false);
expect(
Result.isSuccess(
decodePullRequestStacksJson(JSON.stringify([stack({ pull_requests: undefined })])),
),
).toBe(false);
expect(Result.isSuccess(decodePullRequestStacksJson("{"))).toBe(false);
});
});
@@ -2445,3 +2445,69 @@ export function decodePullRequestFilesJson(
omittedFileStats,
});
}
/** One pull request as the stacks API lists it: a number, a head, and whether it is done. */
const RawStackPullRequestSchema = Schema.Struct({
number: Schema.Int,
head: Schema.Struct({ ref: Schema.String }),
state: Schema.optional(Schema.NullOr(Schema.String)),
merged_at: Schema.optional(Schema.NullOr(Schema.String)),
});
/**
* A stack as `GET /repos/{owner}/{repo}/stacks` answers it, in a public preview whose shape may
* still move. Only what a stack is made of is required — where it lives, what it stands on, and
* its pull requests — and `base` is accepted both as the ref object the preview sends today and
* as the bare branch name it started out as.
*/
const RawStackSchema = Schema.Struct({
id: Schema.optional(Schema.NullOr(Schema.Union([Schema.Int, Schema.String]))),
number: Schema.Int,
node_id: Schema.optional(Schema.NullOr(Schema.String)),
url: Schema.String,
html_url: Schema.optional(Schema.NullOr(Schema.String)),
base: Schema.Union([Schema.String, Schema.Struct({ ref: Schema.String })]),
pull_requests: Schema.Array(RawStackPullRequestSchema),
});
const decodeStacks = decodeJsonResult(Schema.Array(RawStackSchema));
export interface GitHubPullRequestStackLayer {
readonly number: number;
readonly headBranch: string;
readonly state: PullRequestState;
}
export interface GitHubPullRequestStack {
readonly id: string;
readonly number: number;
readonly url: string;
readonly base: string;
/** Bottom to top, which is the order GitHub lists them in. */
readonly layers: ReadonlyArray<GitHubPullRequestStackLayer>;
}
/**
* The first stack of a `?pull_request=` listing, or null for an empty one: a pull request is in
* at most one stack, so the array is GitHub's way of saying "none" rather than a page.
*/
export function decodePullRequestStacksJson(
raw: string,
): Result.Result<GitHubPullRequestStack | null, DecodeFailure> {
const decoded = decodeStacks(raw);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
const stack = decoded.success[0];
if (stack === undefined) return Result.succeed(null);
return Result.succeed({
id: stack.id == null ? (trimmed(stack.node_id) ?? String(stack.number)) : String(stack.id),
number: stack.number,
// The page a person opens where the preview reports one; the API URL is what it always has.
url: trimmed(stack.html_url) ?? stack.url,
base: typeof stack.base === "string" ? stack.base : stack.base.ref,
layers: stack.pull_requests.map((pullRequest) => ({
number: pullRequest.number,
headBranch: pullRequest.head.ref,
state: toState({ state: pullRequest.state, mergedAt: pullRequest.merged_at }),
})),
});
}
@@ -0,0 +1,117 @@
import { assert, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { listLinkedPullRequestThreads } from "./linkedThreads.ts";
it.effect(
"finds active and archived threads for exactly one pull request, excluding deleted and dismissed links",
() =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const createdAt = "2026-09-01T00:00:00.000Z";
const archivedAt = "2026-09-03T00:00:00.000Z";
yield* sql`
INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at)
VALUES ('project-1', 'Project', '/tmp/project', '[]', ${createdAt}, ${createdAt})
`;
const fixtures = [
{
id: "azure",
host: "dev.azure.com",
repository: "org/project/_git/web",
number: 7,
source: "manual",
},
{
id: "other-org",
host: "dev.azure.com",
repository: "other/project/_git/web",
number: 7,
source: "manual",
},
{ id: "active", host: "github.com", repository: "acme/web", number: 7, source: "manual" },
{
id: "archived",
host: "github.com",
repository: "acme/web",
number: 7,
source: "created",
},
{ id: "deleted", host: "github.com", repository: "acme/web", number: 7, source: "manual" },
{
id: "dismissed",
host: "github.com",
repository: "acme/web",
number: 7,
source: "stack-dismissed",
},
{
id: "other-host",
host: "github.example.com",
repository: "acme/web",
number: 7,
source: "manual",
},
{
id: "other-repository",
host: "github.com",
repository: "acme/api",
number: 7,
source: "manual",
},
{
id: "other-number",
host: "github.com",
repository: "acme/web",
number: 8,
source: "manual",
},
];
for (const fixture of fixtures) {
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, created_at, updated_at, archived_at, deleted_at
) VALUES (
${fixture.id}, 'project-1', ${fixture.id}, '{"instanceId":"codex","model":"gpt-5.4"}',
${createdAt}, ${fixture.id === "archived" ? archivedAt : createdAt},
${fixture.id === "archived" ? archivedAt : null},
${fixture.id === "deleted" ? archivedAt : null}
)
`;
yield* sql`
INSERT INTO projection_thread_pull_requests (thread_id, host, repository, number, url, source, linked_at)
VALUES (${fixture.id}, ${fixture.host}, ${fixture.repository}, ${fixture.number},
'https://github.com/acme/web/pull/7', ${fixture.source}, ${createdAt})
`;
}
expect(
(yield* listLinkedPullRequestThreads({
host: "org.visualstudio.com",
repository: "project/_git/web",
number: 7,
})).threads.map((thread) => thread.id),
).toEqual(["azure"]);
const result = yield* listLinkedPullRequestThreads({
host: "GitHub.Com",
repository: "ACME/WEB",
number: 7,
});
expect(result).toEqual({
threads: [
{ id: "archived", projectId: "project-1", title: "archived", archivedAt },
{ id: "active", projectId: "project-1", title: "active", archivedAt: null },
],
});
assert.deepStrictEqual(
yield* listLinkedPullRequestThreads({
host: "github.com",
repository: "acme/web",
number: 99,
}),
{ threads: [] },
);
}).pipe(Effect.provide(SqlitePersistenceMemory)),
);
@@ -0,0 +1,39 @@
import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
import {
PullRequestLinkedThreadsResult,
PullRequestOperationError,
type ThreadPullRequestKey,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
const decodeLinkedThreads = Schema.decodeUnknownEffect(PullRequestLinkedThreadsResult);
export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThreads")(
function* (input: ThreadPullRequestKey) {
const key = normalizeThreadPullRequestKey(input);
const sql = yield* SqlClient.SqlClient;
const threads = yield* sql`
SELECT t.thread_id AS id, t.project_id AS "projectId", t.title,
t.archived_at AS "archivedAt"
FROM projection_thread_pull_requests AS link
JOIN projection_threads AS t ON t.thread_id = link.thread_id
WHERE link.host = ${key.host.toLowerCase()}
AND link.repository = ${key.repository.toLowerCase()}
AND link.number = ${key.number}
AND link.source != 'stack-dismissed'
AND t.deleted_at IS NULL
ORDER BY t.updated_at DESC, t.thread_id ASC
`;
return yield* decodeLinkedThreads({ threads });
},
Effect.mapError(
(cause) =>
new PullRequestOperationError({
operation: "linkedThreads",
detail: "Could not load linked threads.",
cause,
}),
),
);
@@ -0,0 +1,46 @@
import { ProjectId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { pullRequestSyncKey } from "./pullRequestSyncKey.ts";
describe("pullRequestSyncKey", () => {
const reference = { projectId: ProjectId.make("project"), repository: "web", number: 7 };
it.each([
"dev.azure.com/org/project/_git/web",
"ssh.dev.azure.com/v3/org/project/web",
"vs-ssh.visualstudio.com/v3/org/project/web",
"org.visualstudio.com/defaultcollection/project/_git/web",
])("resolves hostless and checkout-host Azure references for %s", (canonicalKey) => {
const identity = {
canonicalKey,
provider: "azure-devops",
name: "web",
displayName: canonicalKey.split("/").slice(1).join("/"),
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: `https://${canonicalKey}`,
},
};
const expected = { host: "dev.azure.com", repository: "org/project/_git/web", number: 7 };
expect(pullRequestSyncKey(reference, identity)).toEqual(expected);
expect(
pullRequestSyncKey({ ...reference, host: canonicalKey.split("/")[0]! }, identity),
).toEqual(expected);
expect(pullRequestSyncKey({ ...reference, repository: "other" }, identity)).toBeNull();
expect(pullRequestSyncKey({ ...reference, host: "unrelated.test" }, identity)).toBeNull();
});
it("normalizes complete hosted aliases without requiring a checkout", () => {
expect(
pullRequestSyncKey({
...reference,
host: "org.visualstudio.com",
repository: "project/_git/web",
}),
).toEqual({ host: "dev.azure.com", repository: "org/project/_git/web", number: 7 });
expect(
pullRequestSyncKey({ ...reference, host: "github.com", repository: "acme/web" }),
).toEqual({ host: "github.com", repository: "acme/web", number: 7 });
expect(pullRequestSyncKey(reference)).toBeNull();
});
});
@@ -0,0 +1,44 @@
import {
pullRequestHostOf,
type PullRequestRef,
type RepositoryIdentity,
type SourceControlProviderKind,
type ThreadPullRequestKey,
} from "@t3tools/contracts";
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
/** Convert checkout-scoped references to the host-level identity used by linked threads. */
export function pullRequestSyncKey(
reference: PullRequestRef,
identity?: RepositoryIdentity | null,
): ThreadPullRequestKey | null {
if (identity?.provider === "azure-devops" && !reference.repository.includes("/")) {
if (
reference.repository.toLowerCase() !==
sourceControlRepositorySelector(identity)?.toLowerCase() ||
(reference.host !== undefined &&
reference.host.toLowerCase() !== pullRequestHostOf(identity, "azure-devops"))
)
return null;
const [host, ...repository] = identity.canonicalKey.split("/");
if (!host || repository.length === 0) return null;
return normalizeThreadPullRequestKey({
host,
repository: repository.join("/"),
number: reference.number,
});
}
const host =
reference.host ??
(identity
? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind)
: undefined);
return host === undefined
? null
: normalizeThreadPullRequestKey({
host,
repository: reference.repository,
number: reference.number,
});
}
@@ -334,6 +334,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: null,
createdAt: now,
updatedAt: now,
@@ -477,6 +478,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: {
turnId: "turn-1" as TurnId,
state: "running",
@@ -668,6 +670,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: {
turnId: "turn-1" as TurnId,
state: "running",
+10 -1
View File
@@ -117,6 +117,7 @@ import {
} from "./orchestration/Errors.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { ThreadDeletionReactor } from "./orchestration/Services/ThreadDeletionReactor.ts";
import * as PullRequestSyncReactor from "./orchestration/PullRequestSyncReactor.ts";
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationEventStore } from "./persistence/Services/OrchestrationEventStore.ts";
@@ -331,6 +332,7 @@ const makeDefaultOrchestrationReadModel = () => {
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
pullRequests: [],
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -361,6 +363,7 @@ const makeDefaultOrchestrationThreadShell = (
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: null,
createdAt: now,
updatedAt: now,
@@ -384,7 +387,7 @@ const browserOtlpTracingLayer = Layer.mergeAll(
const makeAuthTestLayer = () =>
EnvironmentAuth.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provide(ServerSecretStore.layer),
Layer.provide(
Layer.mock(ServerEnvironment.ServerEnvironmentIdentity)({
@@ -956,6 +959,11 @@ const buildAppUnderTest = (options?: {
drainThrough: () => Effect.void,
...options?.layers?.threadDeletionReactor,
}),
Layer.mock(PullRequestSyncReactor.PullRequestSyncReactor)({
start: () => Effect.void,
drain: Effect.void,
requestSync: () => Effect.void,
}),
),
),
Layer.provide(
@@ -8104,6 +8112,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
pullRequests: [],
createdAt: now,
updatedAt: now,
archivedAt: null,
+2
View File
@@ -71,6 +71,7 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma
import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
import * as ThreadSettlementReactor from "./orchestration/ThreadSettlementReactor.ts";
import * as PullRequestSyncReactor from "./orchestration/PullRequestSyncReactor.ts";
import * as ThreadPullRequestReactor from "./orchestration/ThreadPullRequestReactor.ts";
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
@@ -280,6 +281,7 @@ const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(CheckpointReactorLive),
Layer.provideMerge(ThreadDeletionReactorLive),
Layer.provideMerge(ThreadSettlementReactor.layer),
Layer.provideMerge(PullRequestSyncReactor.layer),
Layer.provideMerge(ThreadPullRequestReactor.layer),
Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),
Layer.provideMerge(RuntimeReceiptBusLive),
+89 -8
View File
@@ -70,6 +70,7 @@ import {
type TerminalError,
type TerminalEvent,
type TerminalMetadataStreamEvent,
type PullRequestRef,
WS_METHODS,
WsRpcGroup,
} from "@t3tools/contracts";
@@ -124,6 +125,7 @@ import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts";
import * as ReviewService from "./review/ReviewService.ts";
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
import * as AgentSessionScanner from "./project/AgentSessionScanner.ts";
@@ -142,6 +144,10 @@ import * as UsageLimitSources from "./usage/UsageLimitSources.ts";
import * as UsageService from "./usage/UsageService.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
import * as PullRequestService from "./pullRequest/PullRequestService.ts";
import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts";
import { pullRequestSyncKey } from "./pullRequest/pullRequestSyncKey.ts";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as PullRequestSyncReactor from "./orchestration/PullRequestSyncReactor.ts";
import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
@@ -476,7 +482,18 @@ const makeWsRpcLayer = (
Effect.gen(function* () {
const currentSessionId = currentSession.sessionId;
const crypto = yield* Crypto.Crypto;
const sql = yield* SqlClient.SqlClient;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
/** A reference's host-level link key; the project's own host where the ref names none. */
const resolvePullRequestSyncKey = (reference: PullRequestRef) =>
reference.host !== undefined && reference.repository.includes("/")
? Effect.succeed(pullRequestSyncKey(reference))
: projectionSnapshotQuery.getProjectShellById(reference.projectId).pipe(
Effect.map((project) =>
pullRequestSyncKey(reference, Option.getOrUndefined(project)?.repositoryIdentity),
),
Effect.orElseSucceed(() => null),
);
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
const threadDeletionReactor = yield* ThreadDeletionReactor;
const analytics = yield* AnalyticsService.AnalyticsService;
@@ -604,6 +621,7 @@ const makeWsRpcLayer = (
const sourceControlRepositories =
yield* SourceControlRepositoryService.SourceControlRepositoryService;
const pullRequests = yield* PullRequestService.PullRequestService;
const pullRequestSync = yield* PullRequestSyncReactor.PullRequestSyncReactor;
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
const sessions = yield* SessionStore.SessionStore;
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
@@ -2133,6 +2151,24 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.pullRequestsSummary, pullRequests.summary(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsStack]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsStack, pullRequests.stack(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsLinkedThreads]: (input) =>
observeRpcEffect(
WS_METHODS.pullRequestsLinkedThreads,
resolvePullRequestSyncKey(input).pipe(
Effect.flatMap((key) =>
key === null
? Effect.succeed({ threads: [] })
: listLinkedPullRequestThreads(key).pipe(
Effect.provideService(SqlClient.SqlClient, sql),
),
),
),
{ "rpc.aggregate": "pull-requests" },
),
[WS_METHODS.pullRequestsDetail]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsDetail, pullRequests.detail(input), {
"rpc.aggregate": "pull-requests",
@@ -2156,9 +2192,21 @@ const makeWsRpcLayer = (
{ "rpc.aggregate": "pull-requests" },
),
[WS_METHODS.pullRequestsRunAction]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsRunAction, pullRequests.runAction(input), {
"rpc.aggregate": "pull-requests",
}),
observeRpcEffect(
WS_METHODS.pullRequestsRunAction,
pullRequests
.runAction(input)
.pipe(
Effect.tap(() =>
resolvePullRequestSyncKey(input).pipe(
Effect.flatMap((key) =>
key === null ? Effect.void : pullRequestSync.requestSync(key),
),
),
),
),
{ "rpc.aggregate": "pull-requests" },
),
[WS_METHODS.pullRequestsUpdate]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsUpdate, pullRequests.update(input), {
"rpc.aggregate": "pull-requests",
@@ -2196,9 +2244,23 @@ const makeWsRpcLayer = (
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsInvalidate]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsInvalidate, pullRequests.invalidate(input), {
"rpc.aggregate": "pull-requests",
}),
observeRpcEffect(
WS_METHODS.pullRequestsInvalidate,
pullRequests.invalidate(input).pipe(
// A reader asking for fresh host state also wants the thread badges it feeds to
// catch up, including a merged link the sweep would otherwise never revisit.
Effect.andThen(
input.reference === undefined
? Effect.void
: resolvePullRequestSyncKey(input.reference).pipe(
Effect.flatMap((key) =>
key === null ? Effect.void : pullRequestSync.requestSync(key),
),
),
),
),
{ "rpc.aggregate": "pull-requests" },
),
[WS_METHODS.pullRequestsSubscribeRefreshes]: () =>
observeRpcStream(
WS_METHODS.pullRequestsSubscribeRefreshes,
@@ -2507,8 +2569,25 @@ const makeWsRpcLayer = (
.pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Queue.failCause(queue, cause),
onSuccess: () =>
refreshGitStatus(input.cwd).pipe(
onSuccess: (result) =>
(input.threadId === undefined
? Effect.void
: linkCreatedPullRequest({
threadId: input.threadId,
result,
commandId: serverCommandId("pr-created-link"),
}).pipe(
Effect.provideService(
OrchestrationEngine.OrchestrationEngineService,
orchestrationEngine,
),
Effect.provideService(
ProjectionSnapshotQuery.ProjectionSnapshotQuery,
projectionSnapshotQuery,
),
)
).pipe(
Effect.andThen(refreshGitStatus(input.cwd)),
Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
),
}),
@@ -2932,6 +3011,7 @@ export const websocketRpcRouteLayer = Layer.unwrap(
),
});
const pullRequests = yield* PullRequestService.PullRequestService;
const sql = yield* SqlClient.SqlClient;
return HttpRouter.add(
"GET",
"/ws",
@@ -2966,6 +3046,7 @@ export const websocketRpcRouteLayer = Layer.unwrap(
previewAutomationBroker,
).pipe(
Layer.provideMerge(RpcSerialization.layerJson),
Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)),
Layer.provide(AgentSessionScanner.layer),
Layer.provide(ProviderMaintenanceRunner.layer),
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),