feat(pull-requests): link multiple pull requests to threads (#10839)
This commit is contained in:
1 parent
383cc40f4d
commit
afb84898be
172 files changed
+12063
-914
No files matched your search
@@ -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);
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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":
|
||||
|
||||
Reference in new issue
Block a user