,
+ ) {
+ const apiKey = yield* scopeToCurrentKey;
+ return yield* backoff.guard(apiKey, effect);
+ }, Effect.mapError(toLinearError));
+
+ const bodyHash = (body: string) => String(Hash.string(body));
+
+ /** Posts or edits the one comment of a pipeline link. Serialized per link, so never duplicated. */
+ const syncPipelineComment: LinearService["Service"]["syncPipelineComment"] = (stored) =>
+ linkLock.withLock(
+ stored.link.linkId,
+ Effect.gen(function* () {
+ const run = yield* pipelines
+ .getRun(stored.link.targetId as PipelineRunId)
+ .pipe(
+ Effect.mapError(
+ () => new LinearError({ reason: "not_found", message: "Pipeline run not found." }),
+ ),
+ );
+ const body = renderPipelineCommentBody({
+ pipelineName: run.definition.name,
+ threadUrl: stored.threadUrl,
+ runStatus: run.status,
+ steps: run.steps.map((step) => ({
+ name:
+ run.definition.steps.find((candidate) => candidate.id === step.stepId)?.name ??
+ step.stepId,
+ status: step.status,
+ })),
+ });
+ // Re-read inside the lock: another caller may have posted since `stored` was loaded.
+ const current = yield* store
+ .get(stored.link.linkId)
+ .pipe(Effect.mapError(unavailableStorage));
+ if (current === null) return;
+ const hash = bodyHash(body);
+ if (current.link.commentId === null) {
+ const created = yield* trackerCall(tracker.createComment(stored.link.issueId, body));
+ yield* store
+ .recordComment(stored.link.linkId, created.id, hash)
+ .pipe(Effect.mapError(unavailableStorage));
+ } else if (current.commentBodyHash !== hash) {
+ yield* trackerCall(tracker.updateComment(current.link.commentId, body));
+ yield* store
+ .recordBodyHash(stored.link.linkId, hash)
+ .pipe(Effect.mapError(unavailableStorage));
+ }
+ }),
+ );
+
+ const recordLaunch: LinearService["Service"]["recordLaunch"] = Effect.fn(
+ "LinearService.recordLaunch",
+ )(function* (input) {
+ // Linear unreachable: link from what the client knew and skip the immediate write-backs.
+ const unreadable: { error: LinearError | null } = { error: null };
+ const loaded = yield* cached(
+ issueCache,
+ input.issueId,
+ ISSUE_TTL_MS,
+ tracker.issue(input.issueId),
+ ).pipe(
+ Effect.map((entry) => Option.some(entry.value)),
+ Effect.catchIf(
+ (error) => input.issue !== undefined && error.reason !== "not_found",
+ (error) =>
+ Effect.sync(() => {
+ unreadable.error = error;
+ return Option.none();
+ }),
+ ),
+ );
+ const issue = Option.getOrNull(loaded);
+ const { target } = input;
+ // A pipeline comment is the reactor's job, so it still lands once Linear is readable again.
+ // A run on another machine cannot be read here, so its comment is a static one-off post and
+ // its link never reaches the reactor, which only lists "pipeline" links.
+ const commentMode = !input.writeBack.comment
+ ? "none"
+ : target.kind === "pipeline_run" && input.remote === undefined
+ ? "pipeline"
+ : issue === null
+ ? "none"
+ : "thread";
+ const identity =
+ issue !== null
+ ? {
+ identifier: issue.identifier,
+ teamId: issue.team.id,
+ projectId: issue.project?.id ?? null,
+ }
+ : {
+ identifier: input.issue!.identifier,
+ teamId: input.issue!.teamId,
+ projectId: input.issue!.projectId ?? null,
+ };
+ const stored = yield* store
+ .upsert({
+ linkId: yield* crypto.randomUUIDv4().pipe(Effect.orDie),
+ issueId: input.issueId,
+ issueIdentifier: identity.identifier,
+ teamId: identity.teamId,
+ projectId: identity.projectId,
+ targetKind: target.kind,
+ targetId: target.targetId,
+ threadId: target.threadId,
+ createdAt: DateTime.formatIso(yield* DateTime.now),
+ commentMode,
+ threadUrl: input.threadUrl,
+ environmentId: input.remote?.environmentId ?? null,
+ })
+ .pipe(Effect.mapError(unavailableStorage));
+
+ const warnings: Array<{ step: "move_state" | "comment"; message: string }> = [];
+ // A missing or rejected key is a setup state; an outage or rate limit deserves a heads-up.
+ if (
+ unreadable.error !== null &&
+ (unreadable.error.reason === "unavailable" || unreadable.error.reason === "rate_limited")
+ ) {
+ const message = writeBackFailure(unreadable.error);
+ if (input.writeBack.moveToStateId !== undefined) {
+ warnings.push({ step: "move_state", message });
+ }
+ if (commentMode === "none" && input.writeBack.comment) {
+ warnings.push({ step: "comment", message });
+ }
+ }
+
+ const recordWarning = (step: "move_state" | "comment") => (error: LinearError) =>
+ Effect.logWarning(`Linear ${step} write-back failed`, { reason: error.reason }).pipe(
+ Effect.andThen(
+ Effect.sync(() => warnings.push({ step, message: writeBackFailure(error) })),
+ ),
+ );
+
+ // Write-backs are best effort and run once per link, so repeating the call is harmless. The
+ // link is re-read under its lock so concurrent launches cannot both move or comment.
+ if (issue !== null) {
+ const moveToStateId = input.writeBack.moveToStateId;
+ yield* linkLock.withLock(
+ stored.link.linkId,
+ Effect.gen(function* () {
+ const current =
+ (yield* store.get(stored.link.linkId).pipe(Effect.mapError(unavailableStorage)))
+ ?.link ?? stored.link;
+ if (
+ moveToStateId !== undefined &&
+ current.stateMovedTo === null &&
+ isStateMoveEligible(issue.state.type)
+ ) {
+ yield* trackerCall(tracker.moveIssueToState(issue.id, moveToStateId)).pipe(
+ Effect.andThen(
+ store
+ .recordStateMove(stored.link.linkId, moveToStateId)
+ .pipe(Effect.mapError(unavailableStorage)),
+ ),
+ Effect.andThen(expireIssueCaches),
+ Effect.catch(recordWarning("move_state")),
+ );
+ }
+ if (
+ input.writeBack.comment &&
+ current.commentMode === "thread" &&
+ current.commentId === null
+ ) {
+ yield* Effect.gen(function* () {
+ const { viewer } = yield* viewerInfo;
+ const body =
+ input.remote === undefined
+ ? renderChatCommentBody({
+ viewerName: viewer.name,
+ threadTitle: target.title,
+ threadUrl: input.threadUrl,
+ })
+ : renderRemotePipelineCommentBody({
+ pipelineName: input.remote.pipelineName,
+ machineName: input.remote.machineName,
+ threadUrl: input.threadUrl,
+ });
+ const created = yield* trackerCall(tracker.createComment(issue.id, body));
+ yield* store
+ .recordComment(stored.link.linkId, created.id, bodyHash(body))
+ .pipe(Effect.mapError(unavailableStorage));
+ }).pipe(Effect.catch(recordWarning("comment")));
+ }
+ }),
+ );
+ if (input.writeBack.comment && stored.link.commentMode === "pipeline") {
+ yield* syncPipelineComment(stored).pipe(Effect.catch(recordWarning("comment")));
+ }
+ }
+
+ const link =
+ (yield* store.get(stored.link.linkId).pipe(Effect.mapError(unavailableStorage)))?.link ??
+ stored.link;
+ yield* bumpRefresh;
+ return { link, warnings } satisfies LinearRecordLaunchResult;
+ });
+
+ return LinearService.of({
+ status,
+ connect,
+ disconnect,
+ resync,
+ refresh,
+ teams,
+ teamMetadata: Effect.fn("LinearService.teamMetadata")(function* (teamId) {
+ return yield* cachedValue(
+ teamMetadataCache,
+ teamId,
+ REFERENCE_TTL_MS,
+ tracker.teamMetadata(teamId),
+ );
+ }),
+ projects: Effect.fn("LinearService.projects")(function* (teamId) {
+ return yield* cachedValue(
+ projectsCache,
+ teamId ?? "*",
+ REFERENCE_TTL_MS,
+ tracker.projects(teamId),
+ );
+ }),
+ milestones: Effect.fn("LinearService.milestones")(function* (projectId) {
+ return yield* cachedValue(
+ milestonesCache,
+ projectId,
+ MILESTONE_TTL_MS,
+ tracker.milestones(projectId),
+ );
+ }),
+ issues,
+ issueDetail: Effect.fn("LinearService.issueDetail")(function* (issueId) {
+ return yield* cachedValue(
+ issueDetailCache,
+ issueId,
+ ISSUE_TTL_MS,
+ tracker.issueDetail(issueId),
+ );
+ }),
+ subIssues: Effect.fn("LinearService.subIssues")(function* (issueId) {
+ return yield* cachedValue(
+ subIssuesCache,
+ issueId,
+ ISSUE_TTL_MS,
+ tracker.subIssues(issueId),
+ );
+ }),
+ views: cachedValue(viewsCache, "views", REFERENCE_TTL_MS, tracker.views),
+ search: Effect.fn("LinearService.search")(function* (term) {
+ return yield* cachedValue(
+ searchCache,
+ term.toLowerCase(),
+ SEARCH_TTL_MS,
+ tracker.search(term),
+ );
+ }),
+ activity: computeLinearActivity(store, pipelines, projection).pipe(
+ Effect.mapError(unavailableStorage),
+ ),
+ recordLaunch,
+ subscribeRefreshes: SubscriptionRef.changes(refreshes).pipe(
+ Stream.filter((revision) => revision > 0),
+ ),
+ syncPipelineComment,
+ });
+ }),
+);
+
+/** Cutoff for pipeline links the comment reactor still maintains. */
+export const pipelineCommentCutoff = Effect.map(Clock.currentTimeMillis, (nowMs) =>
+ DateTime.formatIso(DateTime.makeUnsafe(nowMs - PIPELINE_COMMENT_WINDOW_MS)),
+);
diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts
index b82d9bb5ae59c..b032b381255dd 100644
--- a/apps/server/src/mcp/McpToolAccess.ts
+++ b/apps/server/src/mcp/McpToolAccess.ts
@@ -147,6 +147,8 @@ export const writes = (
options?: {
/** Whether a linked caller may make it, as for uploads its own sends need. */
readonly linkedCallers?: "allowed";
+ /** What a refused linked caller cannot do, in the refusal. Default: scheduled tasks. */
+ readonly refusedWhenLinked?: string;
},
) =>
declare(
@@ -155,7 +157,10 @@ export const writes =
(
Effect.tap((caller) =>
options?.linkedCallers === "allowed"
? Effect.void
- : assertNotLinked(caller, "change this environment's scheduled tasks"),
+ : assertNotLinked(
+ caller,
+ options?.refusedWhenLinked ?? "change this environment's scheduled tasks",
+ ),
),
Effect.flatMap(() => handle(params)),
),
diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
index f260093f3f161..6ce8dd91847ea 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
@@ -3,6 +3,8 @@ import {
NodeId,
type OrchestrationV2ThreadProjection,
type OrchestrationV2ThreadShell,
+ PipelineRunId,
+ PipelineStepId,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
@@ -20,6 +22,7 @@ import { expect, it } from "vite-plus/test";
import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import * as ProjectService from "../project/ProjectService.ts";
+import * as PipelineService from "../pipelines/PipelineService.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
@@ -175,6 +178,7 @@ it("readThread preserves caller access errors and prefers activity-run status ov
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
list: () => Effect.succeed({ tasks: [] }),
} satisfies Partial),
@@ -261,6 +265,7 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
list: () => Effect.succeed({ tasks: [] }),
} satisfies Partial),
@@ -298,6 +303,79 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn
}).pipe(Effect.provide(layer), Effect.runPromise);
});
+it("readThread names the pipeline run on a pipeline's parent and step threads", async () => {
+ const pipeline = { runId: PipelineRunId.make("pipeline-run:mcp-detail"), stepId: null };
+ const stepPipeline = { ...pipeline, stepId: PipelineStepId.make("review") };
+ const projectionFor = (
+ threadId: ThreadId,
+ link: { runId: PipelineRunId; stepId: PipelineStepId | null } | undefined,
+ ) =>
+ ({
+ thread: {
+ ...baseThread({
+ threadId,
+ title: "Pipeline thread",
+ instanceId: parentInstanceId,
+ model: "gpt-5.4",
+ }),
+ ...(link === undefined ? {} : { pipeline: link }),
+ },
+ runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
+ visibleTurnItems: [],
+ runtimeRequests: [],
+ messages: [],
+ contextTransfers: [],
+ subagents: [],
+ updatedAt: now,
+ }) as unknown as OrchestrationV2ThreadProjection;
+ const projections = new Map([
+ [parentThreadId, projectionFor(parentThreadId, pipeline)],
+ [childThreadId, projectionFor(childThreadId, stepPipeline)],
+ [
+ ThreadId.make("thread-mcp-plain"),
+ projectionFor(ThreadId.make("thread-mcp-plain"), undefined),
+ ],
+ ]);
+
+ const layer = layerOrchestratorService.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
+ getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
+ getThreadRecords: (threadId) => Effect.succeed(projections.get(threadId)!),
+ getThreadShell: (threadId) =>
+ Effect.succeed(
+ projections.get(threadId)!.thread as unknown as OrchestrationV2ThreadShell,
+ ),
+ getProjectThreadRecords: (input) => Effect.succeed(projections.get(input.threadId)!),
+ } satisfies Partial),
+ ServerSettings.layerTest(),
+ Layer.mock(ProviderRegistry.ProviderRegistry)({
+ getProviders: Effect.succeed([]),
+ } satisfies Partial),
+ Layer.mock(ProjectService.ProjectService)({}),
+ Layer.mock(SecretRequests.SecretRequests)({}),
+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
+ Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
+ Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
+ list: () => Effect.succeed([]),
+ } satisfies Partial),
+ NodeCrypto.layer,
+ ),
+ ),
+ );
+
+ await Effect.gen(function* () {
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
+ const read = (threadId: ThreadId) =>
+ service.readThread(makeScope(), { threadId }).pipe(Effect.map((result) => result.thread));
+ expect((yield* read(parentThreadId)).pipeline).toEqual(pipeline);
+ expect((yield* read(childThreadId)).pipeline).toEqual(stepPipeline);
+ expect("pipeline" in (yield* read(ThreadId.make("thread-mcp-plain")))).toBe(false);
+ }).pipe(Effect.provide(layer), Effect.runPromise);
+});
+
it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => {
const parentProjection = {
thread: baseThread({
@@ -394,6 +472,7 @@ it("taskStatus returns task.providerInstanceId rather than the driver kind", asy
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
list: () => Effect.succeed({ tasks: [] }),
} satisfies Partial),
@@ -522,6 +601,7 @@ it("readThread and sendToThread reach threads in other projects", async () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
list: () =>
Effect.succeed({
diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts
index d463b066b7e40..a29272be43cda 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts
@@ -7,6 +7,12 @@ import {
MessageId,
NodeId,
ORCHESTRATOR_MCP_RUNNING_TASK_NEXT,
+ PipelineError,
+ PipelineId,
+ PipelineRunId,
+ PipelineStepId,
+ type PipelineDefinition,
+ type PipelineRun,
type OrchestratorMcpCapabilitiesResult,
OrchestratorMcpTarget,
type OrchestrationV2ThreadShell,
@@ -57,6 +63,7 @@ import * as ThreadManagementService from "../orchestration-v2/ThreadManagementSe
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import { buildUnavailableProviderSnapshot } from "../provider/unavailableProviderSnapshot.ts";
import * as ProjectService from "../project/ProjectService.ts";
+import * as PipelineService from "../pipelines/PipelineService.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
@@ -172,6 +179,7 @@ describe("OrchestratorMcpService", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
@@ -273,6 +281,7 @@ describe("OrchestratorMcpService", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
@@ -374,6 +383,7 @@ describe("OrchestratorMcpService", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
@@ -468,6 +478,7 @@ describe("OrchestratorMcpService", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
@@ -566,6 +577,7 @@ describe("OrchestratorMcpService", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
@@ -659,6 +671,7 @@ describe("OrchestratorMcpService", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
@@ -746,6 +759,7 @@ describe("OrchestratorMcpService", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
@@ -834,6 +848,7 @@ describe("OrchestratorMcpService", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
@@ -1017,6 +1032,7 @@ describe("OrchestratorMcpService", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
@@ -1294,6 +1310,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
yield* Effect.gen(function* () {
@@ -1414,6 +1431,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
@@ -1592,6 +1610,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
),
),
@@ -1719,6 +1738,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
@@ -1832,6 +1852,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
ServerSettings.layerTest(),
);
@@ -1941,6 +1962,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
ServerSettings.layerTest(),
);
@@ -2037,6 +2059,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
),
),
@@ -2294,6 +2317,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
@@ -2459,6 +2483,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
list: () => Effect.succeed({ tasks }),
upsert: () =>
@@ -2530,6 +2555,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
list: () => Effect.succeed({ tasks: [task({})] }),
}),
@@ -2619,6 +2645,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
list: () => Effect.succeed({ tasks: [bound] }),
upsert: () =>
@@ -2703,6 +2730,7 @@ describe("OrchestratorMcpService provider resolution", () => {
}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
list: () => Effect.succeed({ tasks: [existing] }),
upsert: (input) =>
@@ -2908,6 +2936,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
yield* Effect.gen(function* () {
@@ -3018,6 +3047,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
yield* Effect.gen(function* () {
@@ -3112,6 +3142,7 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
yield* Effect.gen(function* () {
@@ -3190,6 +3221,7 @@ describe("OrchestratorMcpService thread lookup", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
),
),
@@ -3335,6 +3367,7 @@ describe("OrchestratorMcpService thread list", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
),
),
@@ -3476,6 +3509,7 @@ describe("OrchestratorMcpService thread stop", () => {
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
),
),
@@ -3542,3 +3576,662 @@ describe("OrchestratorMcpService thread stop", () => {
),
);
});
+
+describe("OrchestratorMcpService pipelines", () => {
+ const projectId = ProjectId.make("project:mcp-test");
+ const callerThreadId = ThreadId.make("thread:mcp-pipeline-caller");
+ const at = "2026-10-28T10:00:00.000Z";
+ const step = (id: string, name: string, runtimeMode: "approval-required" | "full-access") => ({
+ id: PipelineStepId.make(id),
+ name,
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
+ runtimeMode,
+ skills: [],
+ promptTemplate: "{{input}}",
+ pauseBefore: false,
+ });
+ const definition: PipelineDefinition = {
+ id: PipelineId.make("pipeline:feature-delivery"),
+ name: "Feature delivery",
+ steps: [step("plan", "Plan", "approval-required"), step("build", "Build", "full-access")],
+ createdAt: at,
+ updatedAt: at,
+ };
+ const run = (overrides: Partial = {}): PipelineRun => ({
+ id: PipelineRunId.make("pipeline-run:one"),
+ pipelineId: definition.id,
+ definition: { name: definition.name, steps: definition.steps },
+ projectId,
+ parentThreadId: ThreadId.make("thread:pipeline-parent"),
+ input: "Add dark mode",
+ workspaceStrategy: { type: "root" },
+ status: "paused",
+ pauseReason: "awaiting_continue",
+ error: null,
+ currentStepIndex: 1,
+ steps: [
+ {
+ index: 0,
+ stepId: definition.steps[0]!.id,
+ status: "completed",
+ attempt: 1,
+ childThreadId: ThreadId.make("thread:pipeline-step-0"),
+ pauseBefore: false,
+ canRestoreWorkspace: false,
+ handedOff: false,
+ outputPreview: "Plan: add a theme toggle.",
+ error: null,
+ startedAt: at,
+ completedAt: at,
+ },
+ {
+ index: 1,
+ stepId: definition.steps[1]!.id,
+ status: "pending",
+ attempt: 0,
+ childThreadId: null,
+ pauseBefore: true,
+ canRestoreWorkspace: false,
+ handedOff: false,
+ outputPreview: null,
+ error: null,
+ startedAt: null,
+ completedAt: null,
+ },
+ ],
+ revisions: [],
+ createdBy: "agent",
+ creationSource: "mcp",
+ createdAt: at,
+ updatedAt: at,
+ completedAt: null,
+ ...overrides,
+ });
+
+ const harness = (
+ modes: {
+ readonly runtimeMode: "approval-required" | "full-access";
+ readonly interactionMode: "default" | "plan";
+ },
+ extra: {
+ readonly run?: Partial;
+ readonly getRunError?: PipelineError;
+ readonly checkout?: { readonly worktreePath: string; readonly branch: string };
+ /** The commit sha a checkout resolves to, or undefined when git cannot resolve it. */
+ readonly resolveCommit?: (cwd: string, revision: string) => string | undefined;
+ /** Makes the caller a pipeline thread: a step when `stepId` is set, else the run's parent. */
+ readonly pipelineThread?: { readonly runId: PipelineRunId; readonly stepId: string | null };
+ /** The thread that launched the caller, as for a task a step delegated. */
+ readonly callerParentThreadId?: ThreadId;
+ /** Other threads the service reads; any other id reads as the caller. */
+ readonly shells?: ReadonlyArray;
+ } = {},
+ ) => {
+ const started: Array<{ input: unknown; options: unknown }> = [];
+ const continued: Array = [];
+ const handedOff: Array = [];
+ const revised: Array = [];
+ const caller = liveThreadShell(callerThreadId, modes);
+ const shell = {
+ ...caller,
+ ...extra.checkout,
+ ...(extra.pipelineThread === undefined ? {} : { pipeline: extra.pipelineThread }),
+ ...(extra.callerParentThreadId === undefined
+ ? {}
+ : { lineage: { ...caller.lineage, parentThreadId: extra.callerParentThreadId } }),
+ };
+ const pipelines = Layer.mock(PipelineService.PipelineService)({
+ list: () => Effect.succeed({ pipelines: [definition] }),
+ start: (input, options) =>
+ Effect.sync(() => {
+ started.push({ input, options });
+ return { run: run({ status: "running", pauseReason: null, currentStepIndex: 0 }) };
+ }),
+ getRun: () =>
+ extra.getRunError === undefined
+ ? Effect.succeed(run(extra.run))
+ : Effect.fail(extra.getRunError),
+ continueRun: (input) =>
+ Effect.sync(() => {
+ continued.push(input);
+ return { run: run({ status: "running", pauseReason: null }) };
+ }),
+ reviseStep: (input) =>
+ Effect.sync(() => {
+ revised.push(input);
+ return { run: run({ status: "running", pauseReason: null, currentStepIndex: 0 }) };
+ }),
+ handoffStep: (input) =>
+ Effect.sync(() => {
+ handedOff.push(input);
+ return { run: run({ status: "running", pauseReason: null }) };
+ }),
+ });
+ const dependencies = Layer.mergeAll(
+ NodeServices.layer,
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
+ getThreadRecords: () => Effect.succeed(idleThreadProjection(shell)),
+ getThreadShell: (threadId) =>
+ Effect.succeed(extra.shells?.find((candidate) => candidate.id === threadId) ?? shell),
+ }),
+ ServerSettings.layerTest(),
+ Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
+ Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
+ list: () => Effect.succeed([]),
+ }),
+ Layer.mock(ProjectService.ProjectService)({
+ getById: () =>
+ Effect.succeedSome({
+ id: projectId,
+ title: "Acme",
+ workspaceRoot: "/home/user/acme",
+ } as never),
+ }),
+ Layer.mock(SecretRequests.SecretRequests)({}),
+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
+ pipelines,
+ );
+ const scope: McpInvocationScope = {
+ environmentId: EnvironmentId.make("environment:mcp-pipeline"),
+ requestNamespace: "provider-session:mcp-pipeline",
+ thread: {
+ threadId: callerThreadId,
+ providerSessionId: "provider-session:mcp-pipeline",
+ providerInstanceId: ProviderInstanceId.make("codex"),
+ },
+ client: undefined,
+ capabilities: new Set(["orchestration"]),
+ issuedAt: 1,
+ };
+ return {
+ started,
+ continued,
+ handedOff,
+ revised,
+ scope,
+ layer: OrchestratorMcpService.layer.pipe(
+ Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
+ Layer.provide(
+ Layer.mock(GitVcsDriver.GitVcsDriver)({
+ resolveCommit: (input) => {
+ const commitSha = extra.resolveCommit?.(input.cwd, input.revision);
+ return commitSha === undefined
+ ? Effect.fail(new Error("git cannot resolve this") as never)
+ : Effect.succeed({ commitSha } as never);
+ },
+ }),
+ ),
+ Layer.provide(dependencies),
+ ),
+ };
+ };
+
+ const withService = (
+ h: ReturnType,
+ use: (service: OrchestratorMcpService.OrchestratorMcpServiceShape) => Effect.Effect,
+ ) =>
+ Effect.gen(function* () {
+ return yield* use(yield* OrchestratorMcpService.OrchestratorMcpService);
+ }).pipe(Effect.provide(h.layer));
+
+ it.effect(
+ "starts a pipeline by exact name with the caller's mode limits and agent provenance",
+ () =>
+ Effect.gen(function* () {
+ const h = harness({ runtimeMode: "approval-required", interactionMode: "default" });
+ const result = yield* withService(h, (service) =>
+ service.startPipeline(h.scope, {
+ pipeline: "feature delivery",
+ prompt: "Add dark mode",
+ clientRequestId: "start-1",
+ }),
+ );
+ assert.equal(h.started.length, 1);
+ const call = h.started[0] as {
+ input: Record;
+ options: Record;
+ };
+ assert.equal(call.input.pipelineId, definition.id);
+ assert.equal(call.input.projectId, projectId);
+ assert.equal(call.input.input, "Add dark mode");
+ assert.deepEqual(call.input.workspaceStrategy, { type: "root" });
+ assert.equal(call.input.creationSource, "mcp");
+ assert.equal(
+ call.input.commandId,
+ "command:mcp:provider-session%3Amcp-pipeline:start-pipeline:start-1",
+ );
+ // The runner clamps each step's runtime mode to this limit.
+ assert.deepEqual(call.options, {
+ createdBy: "agent",
+ modeLimit: { runtimeMode: "approval-required", interactionMode: "default" },
+ });
+ assert.equal(result.runId, "pipeline-run:one");
+ assert.equal(result.status, "running");
+ }),
+ );
+
+ it.effect("starts a pipeline by id", () =>
+ Effect.gen(function* () {
+ const h = harness({ runtimeMode: "full-access", interactionMode: "default" });
+ yield* withService(h, (service) =>
+ service.startPipeline(h.scope, { pipeline: definition.id, prompt: "Go" }),
+ );
+ const call = h.started[0] as { input: Record };
+ assert.equal(call.input.pipelineId, definition.id);
+ assert.isUndefined(call.input.commandId);
+ }),
+ );
+
+ it.effect("refuses to start a pipeline from a plan-mode thread", () =>
+ Effect.gen(function* () {
+ const h = harness({ runtimeMode: "full-access", interactionMode: "plan" });
+ const error = yield* withService(h, (service) =>
+ service
+ .startPipeline(h.scope, { pipeline: "Feature delivery", prompt: "Add dark mode" })
+ .pipe(Effect.flip),
+ );
+ assert.equal(error.code, "interaction_mode_escalation_denied");
+ assert.include(error.message, "plan mode");
+ assert.equal(h.started.length, 0);
+ }),
+ );
+
+ it.effect("names the available pipelines when the requested one does not exist", () =>
+ Effect.gen(function* () {
+ const h = harness({ runtimeMode: "full-access", interactionMode: "default" });
+ const error = yield* withService(h, (service) =>
+ service.startPipeline(h.scope, { pipeline: "Nightly", prompt: "x" }).pipe(Effect.flip),
+ );
+ assert.equal(error.code, "invalid_request");
+ assert.include(error.message, 'Pipeline "Nightly" was not found');
+ assert.include(error.message, "list_pipelines");
+ assert.equal(h.started.length, 0);
+ }),
+ );
+
+ it.effect("lists pipelines with their steps", () =>
+ Effect.gen(function* () {
+ const h = harness({ runtimeMode: "full-access", interactionMode: "default" });
+ const result = yield* withService(h, (service) => service.listPipelines(h.scope));
+ assert.deepEqual(result as unknown, {
+ pipelines: [
+ {
+ pipelineId: definition.id,
+ name: "Feature delivery",
+ steps: [
+ {
+ stepId: "plan",
+ name: "Plan",
+ providerInstanceId: "codex",
+ model: "gpt-5",
+ runtimeMode: "approval-required",
+ pauseBefore: false,
+ },
+ {
+ stepId: "build",
+ name: "Build",
+ providerInstanceId: "codex",
+ model: "gpt-5",
+ runtimeMode: "full-access",
+ pauseBefore: false,
+ },
+ ],
+ },
+ ],
+ });
+ }),
+ );
+
+ it.effect("reports a run's status with each step's thread link and output preview", () =>
+ Effect.gen(function* () {
+ const h = harness({ runtimeMode: "full-access", interactionMode: "default" });
+ const status = yield* withService(h, (service) =>
+ service.pipelineStatus(h.scope, { runId: PipelineRunId.make("pipeline-run:one") }),
+ );
+ assert.equal(status.name, "Feature delivery");
+ assert.equal(status.status, "paused");
+ assert.equal(status.pauseReason, "awaiting_continue");
+ assert.equal(status.currentStepIndex, 1);
+ assert.equal(status.threadId, "thread:pipeline-parent");
+ assert.isString(status.link);
+ assert.deepEqual(
+ status.steps.map((entry) => ({
+ index: entry.index,
+ name: entry.name,
+ status: entry.status,
+ threadId: entry.threadId,
+ hasLink: entry.link !== undefined,
+ outputPreview: entry.outputPreview,
+ })),
+ [
+ {
+ index: 0,
+ name: "Plan",
+ status: "completed",
+ threadId: "thread:pipeline-step-0",
+ hasLink: true,
+ outputPreview: "Plan: add a theme toggle.",
+ },
+ {
+ index: 1,
+ name: "Build",
+ status: "pending",
+ threadId: null,
+ hasLink: false,
+ outputPreview: null,
+ },
+ ],
+ );
+ }),
+ );
+
+ it.effect("continues a run only when the remaining steps fit the caller's modes", () =>
+ Effect.gen(function* () {
+ // Step 1 runs at full-access, which an approval-required caller could not have started.
+ const narrow = harness({ runtimeMode: "approval-required", interactionMode: "default" });
+ const denied = yield* withService(narrow, (service) =>
+ service
+ .continuePipeline(narrow.scope, {
+ runId: PipelineRunId.make("pipeline-run:one"),
+ stepIndex: 1,
+ })
+ .pipe(Effect.flip),
+ );
+ assert.equal(denied.code, "runtime_mode_escalation_denied");
+ assert.equal(narrow.continued.length, 0);
+
+ const plan = harness({ runtimeMode: "full-access", interactionMode: "plan" });
+ const planDenied = yield* withService(plan, (service) =>
+ service
+ .continuePipeline(plan.scope, {
+ runId: PipelineRunId.make("pipeline-run:one"),
+ stepIndex: 1,
+ })
+ .pipe(Effect.flip),
+ );
+ assert.equal(planDenied.code, "interaction_mode_escalation_denied");
+ assert.equal(plan.continued.length, 0);
+
+ const wide = harness({ runtimeMode: "full-access", interactionMode: "default" });
+ const resumed = yield* withService(wide, (service) =>
+ service.continuePipeline(wide.scope, {
+ runId: PipelineRunId.make("pipeline-run:one"),
+ stepIndex: 1,
+ }),
+ );
+ assert.equal(resumed.status, "running");
+ assert.deepEqual(wide.continued, [
+ { runId: PipelineRunId.make("pipeline-run:one"), stepIndex: 1 },
+ ]);
+ }),
+ );
+
+ it.effect("refuses to continue a user's awaiting_continue pause but not a failed step", () =>
+ Effect.gen(function* () {
+ const gated = harness(
+ { runtimeMode: "full-access", interactionMode: "default" },
+ { run: { createdBy: "user" } },
+ );
+ const refused = yield* withService(gated, (service) =>
+ service
+ .continuePipeline(gated.scope, {
+ runId: PipelineRunId.make("pipeline-run:one"),
+ stepIndex: 1,
+ })
+ .pipe(Effect.flip),
+ );
+ assert.equal(refused.code, "invalid_request");
+ assert.include(refused.message, "only they can continue it");
+ assert.equal(gated.continued.length, 0);
+
+ const failed = harness(
+ { runtimeMode: "full-access", interactionMode: "default" },
+ { run: { createdBy: "user", pauseReason: "step_failed" } },
+ );
+ yield* withService(failed, (service) =>
+ service.continuePipeline(failed.scope, {
+ runId: PipelineRunId.make("pipeline-run:one"),
+ stepIndex: 1,
+ }),
+ );
+ assert.equal(failed.continued.length, 1);
+ }),
+ );
+
+ it.effect("lets the run's coordinator chat continue a user's awaiting_continue pause", () =>
+ Effect.gen(function* () {
+ const coordinator = harness(
+ { runtimeMode: "full-access", interactionMode: "default" },
+ {
+ run: { createdBy: "user", parentThreadId: callerThreadId },
+ pipelineThread: { runId: PipelineRunId.make("pipeline-run:one"), stepId: null },
+ },
+ );
+ yield* withService(coordinator, (service) =>
+ service.continuePipeline(coordinator.scope, {
+ runId: PipelineRunId.make("pipeline-run:one"),
+ stepIndex: 1,
+ }),
+ );
+ assert.equal(coordinator.continued.length, 1);
+ }),
+ );
+
+ it.effect("sends feedback as the coordinator, as another agent, and never from a step", () =>
+ Effect.gen(function* () {
+ const runId = PipelineRunId.make("pipeline-run:one");
+ const input = { runId, stepIndex: 0, feedback: "Plan misses dark mode" };
+ const modes = { runtimeMode: "full-access", interactionMode: "default" } as const;
+ const coordinator = harness(modes, {
+ run: { parentThreadId: callerThreadId },
+ pipelineThread: { runId, stepId: null },
+ });
+ yield* withService(coordinator, (service) =>
+ service.revisePipelineStep(coordinator.scope, input),
+ );
+ assert.deepEqual(coordinator.revised, [{ ...input, author: "coordinator" }]);
+
+ const other = harness(modes);
+ yield* withService(other, (service) => service.revisePipelineStep(other.scope, input));
+ assert.deepEqual(other.revised, [{ ...input, author: "agent" }]);
+
+ const step = harness(modes, { pipelineThread: { runId, stepId: "plan" } });
+ const refused = yield* withService(step, (service) =>
+ service.revisePipelineStep(step.scope, input).pipe(Effect.flip),
+ );
+ assert.equal(refused.code, "invalid_request");
+ assert.equal(step.revised.length, 0);
+
+ // A task a step delegated is part of that step too.
+ const stepThreadId = ThreadId.make("thread:pipeline-step-0");
+ const delegated = harness(modes, {
+ callerParentThreadId: stepThreadId,
+ shells: [{ ...liveThreadShell(stepThreadId), pipeline: { runId, stepId: "plan" } }],
+ });
+ const delegatedRefused = yield* withService(delegated, (service) =>
+ service.revisePipelineStep(delegated.scope, input).pipe(Effect.flip),
+ );
+ assert.equal(delegatedRefused.code, "invalid_request");
+ assert.equal(delegated.revised.length, 0);
+ }),
+ );
+
+ it.effect(
+ "the coordinator runs its run's steps at their modes; another agent only within its own",
+ () =>
+ Effect.gen(function* () {
+ const runId = PipelineRunId.make("pipeline-run:one");
+ const narrow = { runtimeMode: "approval-required", interactionMode: "default" } as const;
+ // The coordinator has the first step's approval-required mode; step 2 runs at full-access.
+ const coordinator = harness(narrow, {
+ run: { createdBy: "user", parentThreadId: callerThreadId },
+ pipelineThread: { runId, stepId: null },
+ });
+ yield* withService(coordinator, (service) =>
+ Effect.all([
+ service.continuePipeline(coordinator.scope, { runId, stepIndex: 1 }),
+ service.revisePipelineStep(coordinator.scope, { runId, stepIndex: 0, feedback: "x" }),
+ ]),
+ );
+ assert.equal(coordinator.continued.length, 1);
+ assert.deepEqual(coordinator.revised, [
+ { runId, stepIndex: 0, feedback: "x", author: "coordinator" },
+ ]);
+
+ const planning = harness(
+ { runtimeMode: "full-access", interactionMode: "plan" },
+ { run: { parentThreadId: callerThreadId }, pipelineThread: { runId, stepId: null } },
+ );
+ const planRefused = yield* withService(planning, (service) =>
+ service
+ .revisePipelineStep(planning.scope, { runId, stepIndex: 0, feedback: "x" })
+ .pipe(Effect.flip),
+ );
+ assert.equal(planRefused.code, "interaction_mode_escalation_denied");
+
+ const other = harness(narrow);
+ const otherRefused = yield* withService(other, (service) =>
+ service
+ .revisePipelineStep(other.scope, { runId, stepIndex: 0, feedback: "x" })
+ .pipe(Effect.flip),
+ );
+ assert.equal(otherRefused.code, "runtime_mode_escalation_denied");
+ assert.equal(other.revised.length, 0);
+
+ // Every step fits, but the user raised step 1's thread to full-access since it ran.
+ const stepThreadId = ThreadId.make("thread:pipeline-step-0");
+ const raised = harness(narrow, {
+ run: {
+ definition: {
+ name: definition.name,
+ steps: definition.steps.map((entry) => ({
+ ...entry,
+ runtimeMode: "approval-required",
+ })),
+ },
+ },
+ shells: [liveThreadShell(stepThreadId, { runtimeMode: "full-access" })],
+ });
+ const raisedRefused = yield* withService(raised, (service) =>
+ service
+ .revisePipelineStep(raised.scope, { runId, stepIndex: 0, feedback: "x" })
+ .pipe(Effect.flip),
+ );
+ assert.equal(raisedRefused.code, "runtime_mode_escalation_denied");
+ assert.equal(raised.revised.length, 0);
+ }),
+ );
+
+ it.effect("starts a pipeline in the caller's worktree, or its own worktree on request", () =>
+ Effect.gen(function* () {
+ const modes = { runtimeMode: "full-access", interactionMode: "default" } as const;
+ const checkout = { worktreePath: "/home/user/acme-wt", branch: "feat/dark" };
+ const shared = harness(modes, { checkout });
+ yield* withService(shared, (service) =>
+ service.startPipeline(shared.scope, { pipeline: definition.id, prompt: "Go" }),
+ );
+ assert.deepEqual(
+ (shared.started[0] as { input: { workspaceStrategy: unknown } }).input.workspaceStrategy,
+ { type: "existing_worktree", worktreePath: "/home/user/acme-wt", branch: "feat/dark" },
+ );
+
+ const isolated = harness(modes, {
+ checkout,
+ resolveCommit: () => "abc123",
+ });
+ yield* withService(isolated, (service) =>
+ service.startPipeline(isolated.scope, {
+ pipeline: definition.id,
+ prompt: "Go",
+ worktree: true,
+ }),
+ );
+ assert.deepEqual(
+ (isolated.started[0] as { input: { workspaceStrategy: unknown } }).input.workspaceStrategy,
+ { type: "worktree", baseRef: "abc123", startFromOrigin: false },
+ );
+
+ // A checkout whose commit the project root lacks cannot seed the worktree.
+ const foreign = harness(modes, {
+ checkout,
+ resolveCommit: (cwd) => (cwd === "/home/user/acme-wt" ? "abc123" : undefined),
+ });
+ const error = yield* withService(foreign, (service) =>
+ service
+ .startPipeline(foreign.scope, { pipeline: definition.id, prompt: "Go", worktree: true })
+ .pipe(Effect.flip),
+ );
+ assert.equal(error.code, "invalid_request");
+ assert.include(error.message, 'project "Acme" (/home/user/acme)');
+ assert.include(error.message, "Omit worktree");
+ assert.equal(foreign.started.length, 0);
+ }),
+ );
+
+ it.effect("maps fixable pipeline errors to invalid_request and hides internal causes", () =>
+ Effect.gen(function* () {
+ const modes = { runtimeMode: "full-access", interactionMode: "default" } as const;
+ const runId = PipelineRunId.make("pipeline-run:one");
+ const stale = harness(modes, {
+ getRunError: new PipelineError({ message: "Pipeline run not found.", runId }),
+ });
+ const notFound = yield* withService(stale, (service) =>
+ service.pipelineStatus(stale.scope, { runId }).pipe(Effect.flip),
+ );
+ assert.equal(notFound.code, "invalid_request");
+ assert.equal(notFound.message, "Pipeline run not found.");
+
+ const broken = harness(modes, {
+ getRunError: new PipelineError({
+ message: "Could not read pipeline run.",
+ runId,
+ cause: new Error("SQLITE_BUSY at /home/user/.t3/statev2.sqlite"),
+ }),
+ });
+ const internal = yield* withService(broken, (service) =>
+ service.pipelineStatus(broken.scope, { runId }).pipe(Effect.flip),
+ );
+ assert.equal(internal.code, "orchestration_error");
+ assert.notInclude(internal.message, "SQLITE");
+ }),
+ );
+
+ it.effect("hands off a pipeline step's output from its own thread", () =>
+ Effect.gen(function* () {
+ const h = harness(
+ { runtimeMode: "full-access", interactionMode: "default" },
+ {
+ pipelineThread: { runId: PipelineRunId.make("pipeline-run:one"), stepId: "plan" },
+ },
+ );
+ const result = yield* withService(h, (service) =>
+ service.handoffPipelineStep(h.scope, { output: "The plan" }),
+ );
+ assert.deepEqual(h.handedOff, [
+ { runId: "pipeline-run:one", threadId: callerThreadId, output: "The plan" },
+ ]);
+ assert.equal(result.runId, "pipeline-run:one");
+ assert.include(result.next, "End your turn now");
+ }),
+ );
+
+ it.effect("refuses a handoff from a thread that is not a pipeline step", () =>
+ Effect.gen(function* () {
+ for (const pipelineThread of [
+ undefined,
+ { runId: PipelineRunId.make("pipeline-run:one"), stepId: null },
+ ]) {
+ const h = harness(
+ { runtimeMode: "full-access", interactionMode: "default" },
+ pipelineThread === undefined ? {} : { pipelineThread },
+ );
+ const refused = yield* Effect.flip(
+ withService(h, (service) => service.handoffPipelineStep(h.scope, { output: "x" })),
+ );
+ assert.include(refused.message, "not a pipeline step");
+ assert.deepEqual(h.handedOff, []);
+ }
+ }),
+ );
+});
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 0d59dfd4940ca..6f881ce1ff11d 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -10,9 +10,12 @@ import {
type OrchestrationV2Run,
type OrchestrationV2Subagent,
type OrchestrationV2ThreadProjection,
+ type EnvironmentId,
type OrchestrationV2ThreadShell,
type OrchestrationV2ThreadLaunchWorkspaceStrategy,
type OrchestrationV2TurnItem,
+ type PipelineError,
+ type PipelineRun,
OrchestratorMcpFailure,
type OrchestratorMcpCapabilitiesInput,
type OrchestratorMcpCapabilitiesResult,
@@ -26,7 +29,16 @@ import {
type OrchestratorMcpRequestSecretInput,
type OrchestratorMcpRequestSecretResult,
type OrchestratorMcpDeleteScheduledTaskResult,
+ type OrchestratorMcpContinuePipelineInput,
+ type OrchestratorMcpHandoffPipelineStepInput,
+ type OrchestratorMcpHandoffPipelineStepResult,
+ type OrchestratorMcpRerunPipelineInput,
+ type OrchestratorMcpRevisePipelineStepInput,
+ type OrchestratorMcpListPipelinesResult,
type OrchestratorMcpListScheduledTasksResult,
+ type OrchestratorMcpPipelineRun,
+ type OrchestratorMcpPipelineRunInput,
+ type OrchestratorMcpStartPipelineInput,
type OrchestratorMcpScheduledTask,
type OrchestratorMcpScheduleTaskInput,
type OrchestratorMcpScheduleTaskResult,
@@ -99,9 +111,11 @@ import type {
import { runOutcome } from "../orchestration-v2/RestartBackgroundNote.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
+import * as TaskFolderService from "../workspace/TaskFolderService.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts";
import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts";
+import * as PipelineService from "../pipelines/PipelineService.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
@@ -188,6 +202,40 @@ export interface OrchestratorMcpServiceShape {
scope: McpInvocationScope,
input: OrchestratorMcpDeleteScheduledTaskInput,
) => Effect.Effect;
+ readonly listPipelines: (
+ scope: McpInvocationScope,
+ ) => Effect.Effect;
+ /** Steps run at the caller's runtime mode or narrower. A plan-mode caller is refused. */
+ readonly startPipeline: (
+ scope: McpInvocationScope,
+ input: OrchestratorMcpStartPipelineInput,
+ ) => Effect.Effect;
+ readonly pipelineStatus: (
+ scope: McpInvocationScope,
+ input: OrchestratorMcpPipelineRunInput,
+ ) => Effect.Effect;
+ readonly continuePipeline: (
+ scope: McpInvocationScope,
+ input: OrchestratorMcpContinuePipelineInput,
+ ) => Effect.Effect;
+ readonly cancelPipeline: (
+ scope: McpInvocationScope,
+ input: OrchestratorMcpPipelineRunInput,
+ ) => Effect.Effect;
+ readonly rerunPipelineStep: (
+ scope: McpInvocationScope,
+ input: OrchestratorMcpRerunPipelineInput,
+ ) => Effect.Effect;
+ /** Refused from the run's own step threads, so steps cannot route feedback upstream. */
+ readonly revisePipelineStep: (
+ scope: McpInvocationScope,
+ input: OrchestratorMcpRevisePipelineStepInput,
+ ) => Effect.Effect;
+ /** Only from a pipeline step's own thread. */
+ readonly handoffPipelineStep: (
+ scope: McpInvocationScope,
+ input: OrchestratorMcpHandoffPipelineStepInput,
+ ) => Effect.Effect;
/** Only status reaches the agent, never this value. */
readonly requestSecret: (
scope: McpInvocationScope,
@@ -256,6 +304,69 @@ function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+// PipelineService sets `cause` only on storage, launch, and id-allocation failures. Its other
+// errors are a request the caller can fix, and their messages are written for the agent.
+function pipelineFailure(error: PipelineError): OrchestratorMcpFailure {
+ return error.cause === undefined
+ ? failure("invalid_request", error.message)
+ : failure("orchestration_error", "The pipeline service failed. Try again, or tell the user.");
+}
+
+const REVISION_FEEDBACK_PREVIEW_CHARS = 500;
+/** How far up a caller's thread lineage the step-of-this-run check looks. */
+const PIPELINE_LINEAGE_MAX_HOPS = 8;
+
+/** The run's own coordinator chat acts for the user; the server can only check who is asking. */
+const isRunCoordinator = (
+ parent: Pick | undefined,
+ run: Pick,
+) => parent?.thread.id === run.parentThreadId;
+
+function pipelineRunSummary(
+ environmentId: EnvironmentId,
+ run: PipelineRun,
+): OrchestratorMcpPipelineRun {
+ return {
+ runId: run.id,
+ pipelineId: run.pipelineId,
+ name: run.definition.name,
+ projectId: run.projectId,
+ threadId: run.parentThreadId,
+ link: formatThreadLink({ environmentId, threadId: run.parentThreadId }),
+ status: run.status,
+ pauseReason: run.pauseReason,
+ error: run.error,
+ currentStepIndex: run.currentStepIndex,
+ revisions: run.revisions.map((revision) => ({
+ stepIndex: revision.stepIndex,
+ stepId: revision.stepId,
+ feedback:
+ revision.feedback.length > REVISION_FEEDBACK_PREVIEW_CHARS
+ ? `${revision.feedback.slice(0, REVISION_FEEDBACK_PREVIEW_CHARS)}…`
+ : revision.feedback,
+ author: revision.author,
+ createdAt: revision.createdAt,
+ })),
+ steps: run.steps.map((step) => ({
+ index: step.index,
+ stepId: step.stepId,
+ name: run.definition.steps[step.index]?.name ?? step.stepId,
+ status: step.status,
+ attempt: step.attempt,
+ threadId: step.childThreadId,
+ ...(step.childThreadId === null
+ ? {}
+ : { link: formatThreadLink({ environmentId, threadId: step.childThreadId }) }),
+ outputPreview: step.outputPreview,
+ handedOff: step.handedOff,
+ error: step.error,
+ })),
+ createdAt: run.createdAt,
+ updatedAt: run.updatedAt,
+ completedAt: run.completedAt,
+ };
+}
+
function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): OrchestratorMcpScheduledTask {
return {
scheduledTaskId: task.id,
@@ -851,6 +962,7 @@ function threadDetail(
worktreePath: projection.thread.worktreePath,
parentThreadId: projection.thread.lineage.parentThreadId,
relationshipToParent: projection.thread.lineage.relationshipToParent,
+ ...(projection.thread.pipeline === undefined ? {} : { pipeline: projection.thread.pipeline }),
runCount: projection.runs.length,
itemCount,
pendingRequestCount: projection.runtimeRequests.filter(
@@ -1008,11 +1120,14 @@ const make = Effect.gen(function* () {
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const providerAdapters = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
+ const pipelines = yield* PipelineService.PipelineService;
const projects = yield* ProjectService.ProjectService;
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
const gitDriver = yield* GitVcsDriver.GitVcsDriver;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const remoteDelegation = yield* RemoteDelegation.RemoteDelegation;
+ // Optional so hosts and tests without task folders keep single-repo delegates.
+ const taskFolders = yield* Effect.serviceOption(TaskFolderService.TaskFolderService);
const requireProject = (projectId: ProjectId) =>
projects.getById(projectId).pipe(
@@ -1975,6 +2090,106 @@ const make = Effect.gen(function* () {
return task;
});
+ /** Whether the caller is one of the run's step threads, or a thread a step launched. */
+ const isWithinRunStep = Effect.fn("OrchestratorMcpService.isWithinRunStep")(function* (
+ parent: Pick,
+ runId: PipelineRun["id"],
+ ): Effect.fn.Return {
+ let thread: Pick | null = parent.thread;
+ for (let hop = 0; thread !== null && hop <= PIPELINE_LINEAGE_MAX_HOPS; hop += 1) {
+ if (thread.pipeline?.runId === runId && thread.pipeline.stepId !== null) return true;
+ const parentThreadId: ThreadId | null = thread.lineage.parentThreadId;
+ if (parentThreadId === null) return false;
+ thread = yield* threadManagement
+ .getThreadShell(parentThreadId)
+ .pipe(Effect.mapError(threadManagementFailure));
+ }
+ return false;
+ });
+
+ /** Pipelines have no plan mode, and a step never runs broader than the caller's runtime mode. */
+ const assertPipelineWithinLimits = Effect.fn("OrchestratorMcpService.assertPipelineWithinLimits")(
+ function* (
+ limits: {
+ readonly runtimeMode: RuntimeMode;
+ readonly interactionMode: ProviderInteractionMode;
+ },
+ steps: ReadonlyArray>,
+ ) {
+ if (limits.interactionMode === "plan") {
+ return yield* failure(
+ "interaction_mode_escalation_denied",
+ "Pipelines cannot run in plan mode, and this thread is in plan mode. Leave plan mode first, or ask the user to run the pipeline.",
+ );
+ }
+ for (const step of steps) yield* resolveRuntimeMode(limits.runtimeMode, step.runtimeMode);
+ },
+ );
+
+ /** A worktree strategy based on a checkout's current commit, which the project root must also contain. */
+ const worktreeStrategyFromCheckout = Effect.fn(
+ "OrchestratorMcpService.worktreeStrategyFromCheckout",
+ )(function* (input: {
+ readonly project: TaskFolderService.TaskFolderProject & { readonly title: string };
+ readonly checkoutPath: string | null;
+ readonly unresolvedMessage: string;
+ readonly outsideProjectMessage: (where: string) => string;
+ }) {
+ const { project, checkoutPath } = input;
+ const base = yield* gitDriver
+ .resolveCommit({ cwd: checkoutPath ?? project.workspaceRoot, revision: "HEAD" })
+ .pipe(Effect.mapError(() => failure("invalid_request", input.unresolvedMessage)));
+ // Launch preparation creates the worktree from the project root, so a
+ // checkout in another repository (such as a Git folder inside Scratch)
+ // would hand it a commit it cannot find.
+ if (checkoutPath !== null) {
+ yield* gitDriver
+ .resolveCommit({ cwd: project.workspaceRoot, revision: base.commitSha })
+ .pipe(
+ Effect.mapError(() =>
+ failure(
+ "invalid_request",
+ input.outsideProjectMessage(`project "${project.title}" (${project.workspaceRoot})`),
+ ),
+ ),
+ );
+ }
+ // A multi-repo checkout gets its own task folder, each repo at the checkout's HEAD there.
+ const repositories = Option.isNone(taskFolders)
+ ? null
+ : yield* taskFolders.value
+ .repositoryHeads({ project, worktreePath: checkoutPath })
+ .pipe(Effect.mapError((error) => failure("invalid_request", error.detail)));
+ return {
+ type: "worktree",
+ baseRef: base.commitSha,
+ startFromOrigin: false,
+ ...(repositories === null ? {} : { repositories }),
+ } satisfies OrchestrationV2ThreadLaunchWorkspaceStrategy;
+ });
+
+ /** The id when it matches, else the one pipeline with this name, ignoring case. */
+ const resolvePipeline = Effect.fn("OrchestratorMcpService.resolvePipeline")(function* (
+ key: string,
+ ) {
+ const { pipelines: all } = yield* pipelines.list().pipe(Effect.mapError(pipelineFailure));
+ const byId = all.find((pipeline) => pipeline.id === key);
+ if (byId !== undefined) return byId;
+ const wanted = key.trim().toLowerCase();
+ const byName = all.filter((pipeline) => pipeline.name.trim().toLowerCase() === wanted);
+ if (byName.length === 1 && byName[0] !== undefined) return byName[0];
+ if (byName.length > 1) {
+ return yield* failure(
+ "invalid_request",
+ `More than one pipeline is named "${key}". Pass one of these ids: ${byName.map((pipeline) => pipeline.id).join(", ")}.`,
+ );
+ }
+ return yield* failure(
+ "invalid_request",
+ `Pipeline "${key}" was not found. Call list_pipelines for the available ids and names.`,
+ );
+ });
+
return OrchestratorMcpService.of({
scheduleTask: Effect.fn("OrchestratorMcpService.scheduleTask")(function* (scope, input) {
const { parent, limits } = yield* loadCaller(scope);
@@ -2117,6 +2332,205 @@ const make = Effect.gen(function* () {
return { scheduledTaskId: existing.id, deleted: true };
},
),
+ listPipelines: Effect.fn("OrchestratorMcpService.listPipelines")(function* (scope) {
+ yield* loadCaller(scope);
+ const { pipelines: all } = yield* pipelines.list().pipe(Effect.mapError(pipelineFailure));
+ return {
+ pipelines: all.map((pipeline) => ({
+ pipelineId: pipeline.id,
+ name: pipeline.name,
+ steps: pipeline.steps.map((step) => ({
+ stepId: step.id,
+ name: step.name,
+ providerInstanceId: step.modelSelection.instanceId,
+ model: step.modelSelection.model,
+ runtimeMode: step.runtimeMode,
+ pauseBefore: step.pauseBefore,
+ })),
+ })),
+ };
+ }),
+ startPipeline: Effect.fn("OrchestratorMcpService.startPipeline")(function* (scope, input) {
+ const { parent, limits } = yield* loadCaller(scope);
+ yield* assertPipelineWithinLimits(limits, []);
+ const projectId = yield* resolveProjectTarget(parent, input.projectId);
+ yield* assertLiveCallerForOtherProject(scope, parent, projectId);
+ const project = yield* requireProject(projectId);
+ const pipeline = yield* resolvePipeline(input.pipeline);
+ const callerWorktree =
+ parent !== undefined && parent.thread.projectId === projectId
+ ? parent.thread.worktreePath
+ : null;
+ const workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy =
+ input.worktree === true
+ ? yield* worktreeStrategyFromCheckout({
+ project,
+ checkoutPath: callerWorktree,
+ unresolvedMessage: "Unable to resolve the checkout commit for the worktree.",
+ outsideProjectMessage: (where) =>
+ `The worktree is created in ${where}, which does not contain this checkout's commit. Omit worktree to run in this checkout.`,
+ })
+ : callerWorktree === null
+ ? { type: "root" }
+ : {
+ type: "existing_worktree",
+ worktreePath: callerWorktree,
+ ...(parent?.thread.branch ? { branch: parent.thread.branch } : {}),
+ };
+ const { run } = yield* pipelines
+ .start(
+ {
+ ...(input.clientRequestId === undefined
+ ? {}
+ : {
+ commandId: stableCommandId({
+ scope,
+ requestKey: input.clientRequestId,
+ operation: "start-pipeline",
+ }),
+ }),
+ pipelineId: pipeline.id,
+ projectId,
+ input: input.prompt,
+ workspaceStrategy,
+ creationSource: "mcp",
+ },
+ { createdBy: "agent", modeLimit: limits },
+ )
+ .pipe(Effect.mapError(pipelineFailure));
+ return pipelineRunSummary(scope.environmentId, run);
+ }),
+ pipelineStatus: Effect.fn("OrchestratorMcpService.pipelineStatus")(function* (scope, input) {
+ yield* loadCaller(scope);
+ const run = yield* pipelines.getRun(input.runId).pipe(Effect.mapError(pipelineFailure));
+ return pipelineRunSummary(scope.environmentId, run);
+ }),
+ continuePipeline: Effect.fn("OrchestratorMcpService.continuePipeline")(
+ function* (scope, input) {
+ const { parent, limits } = yield* loadCaller(scope);
+ const existing = yield* pipelines
+ .getRun(input.runId)
+ .pipe(Effect.mapError(pipelineFailure));
+ yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId);
+ const isCoordinator = isRunCoordinator(parent, existing);
+ if (
+ existing.pauseReason === "awaiting_continue" &&
+ existing.createdBy === "user" &&
+ !isCoordinator
+ ) {
+ return yield* failure(
+ "invalid_request",
+ "The user started this run and set this pause, so only they can continue it. Tell the user it is waiting for them.",
+ );
+ }
+ // The run's steps were clamped to whoever started it, so its coordinator may run them all.
+ // Another caller launches them for itself.
+ yield* assertPipelineWithinLimits(
+ limits,
+ isCoordinator ? [] : existing.definition.steps.slice(input.stepIndex),
+ );
+ const { run } = yield* pipelines
+ .continueRun({ runId: input.runId, stepIndex: input.stepIndex })
+ .pipe(Effect.mapError(pipelineFailure));
+ return pipelineRunSummary(scope.environmentId, run);
+ },
+ ),
+ cancelPipeline: Effect.fn("OrchestratorMcpService.cancelPipeline")(function* (scope, input) {
+ const { parent } = yield* loadCaller(scope);
+ const existing = yield* pipelines.getRun(input.runId).pipe(Effect.mapError(pipelineFailure));
+ yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId);
+ const { run } = yield* pipelines
+ .cancel({ runId: input.runId })
+ .pipe(Effect.mapError(pipelineFailure));
+ return pipelineRunSummary(scope.environmentId, run);
+ }),
+ rerunPipelineStep: Effect.fn("OrchestratorMcpService.rerunPipelineStep")(
+ function* (scope, input) {
+ const { parent, limits } = yield* loadCaller(scope);
+ const existing = yield* pipelines
+ .getRun(input.runId)
+ .pipe(Effect.mapError(pipelineFailure));
+ yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId);
+ // The run's steps were clamped to whoever started it. Rerunning launches them for this caller.
+ yield* assertPipelineWithinLimits(limits, existing.definition.steps.slice(input.stepIndex));
+ const { run } = yield* pipelines
+ .rerunFromStep({ runId: input.runId, stepIndex: input.stepIndex })
+ .pipe(Effect.mapError(pipelineFailure));
+ return pipelineRunSummary(scope.environmentId, run);
+ },
+ ),
+ revisePipelineStep: Effect.fn("OrchestratorMcpService.revisePipelineStep")(
+ function* (scope, input) {
+ const { parent, limits } = yield* loadCaller(scope);
+ const existing = yield* pipelines
+ .getRun(input.runId)
+ .pipe(Effect.mapError(pipelineFailure));
+ yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId);
+ if (parent !== undefined && (yield* isWithinRunStep(parent, existing.id))) {
+ return yield* failure(
+ "invalid_request",
+ "A step of a run cannot send feedback to its own run. Say what you found in your reply or hand off; the user or the run's coordinator decides.",
+ );
+ }
+ const isCoordinator = isRunCoordinator(parent, existing);
+ // The run's steps were clamped to whoever started it, so its coordinator may redo them all.
+ // Another caller redoes them for itself, including in step threads the user raised since.
+ yield* assertPipelineWithinLimits(
+ limits,
+ isCoordinator ? [] : existing.definition.steps.slice(input.stepIndex),
+ );
+ if (!isCoordinator) {
+ for (const step of existing.steps.slice(input.stepIndex)) {
+ if (step.childThreadId === null) continue;
+ const shell = yield* threadManagement
+ .getThreadShell(step.childThreadId)
+ .pipe(Effect.mapError(threadManagementFailure));
+ if (shell !== null && shell.deletedAt === null) {
+ yield* resolveRuntimeMode(limits.runtimeMode, shell.runtimeMode);
+ }
+ }
+ }
+ const { run } = yield* pipelines
+ .reviseStep({
+ runId: input.runId,
+ stepIndex: input.stepIndex,
+ feedback: input.feedback,
+ author: isCoordinator ? "coordinator" : "agent",
+ })
+ .pipe(Effect.mapError(pipelineFailure));
+ return pipelineRunSummary(scope.environmentId, run);
+ },
+ ),
+ handoffPipelineStep: Effect.fn("OrchestratorMcpService.handoffPipelineStep")(
+ function* (scope, input) {
+ yield* requireCapability(scope);
+ const threadScope = yield* requireThreadScope(scope, "handoff_pipeline_step");
+ const threadId = threadScope.thread.threadId;
+ const shell = yield* threadManagement
+ .getThreadShell(threadId)
+ .pipe(Effect.mapError(threadManagementFailure));
+ const pipeline = shell?.pipeline;
+ if (pipeline === undefined || pipeline.stepId === null) {
+ return yield* failure(
+ "invalid_request",
+ "This thread is not a pipeline step, so there is nothing to hand off. Report your result in your reply instead.",
+ );
+ }
+ const { run } = yield* pipelines
+ .handoffStep({ runId: pipeline.runId, threadId, output: input.output })
+ .pipe(Effect.mapError(pipelineFailure));
+ const step = run.steps.find((candidate) => candidate.childThreadId === threadId);
+ const stepIndex = step?.index ?? run.currentStepIndex;
+ const last = stepIndex + 1 >= run.steps.length;
+ return {
+ runId: run.id,
+ stepIndex,
+ next: last
+ ? "Handed off. End your turn now with a short summary; the run finishes when your turn ends."
+ : "Handed off. End your turn now with a short summary; the next step starts when your turn ends. Calling this again replaces the output.",
+ };
+ },
+ ),
requestSecret: Effect.fn("OrchestratorMcpService.requestSecret")(function* (scope, input) {
const { scope: threadScope, parent } = yield* loadThreadCaller(scope, "request_secret");
const threadId = threadScope.thread.threadId;
@@ -2390,32 +2804,13 @@ const make = Effect.gen(function* () {
let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined;
if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) {
const project = yield* requireProject(parent.thread.projectId);
- const base = yield* gitDriver
- .resolveCommit({
- cwd: parent.thread.worktreePath ?? project.workspaceRoot,
- revision: "HEAD",
- })
- .pipe(
- Effect.mapError(() =>
- failure("invalid_request", "Unable to resolve the parent checkout commit."),
- ),
- );
- // Launch preparation creates the worktree from the project root, so a
- // parent checkout in another repository (such as a Git folder inside
- // Scratch) would hand it a commit it cannot find.
- if (parent.thread.worktreePath !== null) {
- yield* gitDriver
- .resolveCommit({ cwd: project.workspaceRoot, revision: base.commitSha })
- .pipe(
- Effect.mapError(() =>
- failure(
- "invalid_request",
- `Isolation "worktree" creates the child checkout in project "${project.title}" (${project.workspaceRoot}), which does not contain the parent checkout's commit. Use isolation "shared" to work in the parent's checkout.`,
- ),
- ),
- );
- }
- workspaceStrategy = { type: "worktree", baseRef: base.commitSha, startFromOrigin: false };
+ workspaceStrategy = yield* worktreeStrategyFromCheckout({
+ project,
+ checkoutPath: parent.thread.worktreePath,
+ unresolvedMessage: "Unable to resolve the parent checkout commit.",
+ outsideProjectMessage: (where) =>
+ `Isolation "worktree" creates the child checkout in ${where}, which does not contain the parent checkout's commit. Use isolation "shared" to work in the parent's checkout.`,
+ });
}
// ThreadManagementService.dispatch is the chokepoint for this command
// type's own enablement check, using the same command id and its
@@ -3272,6 +3667,7 @@ export const layer: Layer.Layer<
| ProviderRegistry.ProviderRegistry
| ProviderAdapterRegistry.ProviderAdapterRegistryV2
| ScheduledTaskService.ScheduledTaskService
+ | PipelineService.PipelineService
| ProjectService.ProjectService
| SecretRequests.SecretRequests
| ServerSettings.ServerSettingsService
diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
index 1861c3264d89a..7c3594f4be9c1 100644
--- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
@@ -43,6 +43,7 @@ import {
} from "@t3tools/provider-testing/replayTranscript";
import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMock.ts";
import * as ProjectService from "../project/ProjectService.ts";
+import * as PipelineService from "../pipelines/PipelineService.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
@@ -241,6 +242,7 @@ describe("orchestrator MCP toolkit", () => {
Layer.provide(layerProviderRegistry),
Layer.provide(ServerSettings.layerTest()),
Layer.provide(layerUnusedScheduledTaskStub),
+ Layer.provide(Layer.mock(PipelineService.PipelineService)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
diff --git a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts
index 5e6cc151fc297..34c14df5d0b74 100644
--- a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts
+++ b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts
@@ -36,6 +36,7 @@ import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
+import * as PipelineService from "../pipelines/PipelineService.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import type { McpInvocationScope } from "./McpInvocationContext.ts";
@@ -158,6 +159,7 @@ it.effect("task_cancel ends a delegated child's background native subagent", ()
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
ServerSettings.layerTest(),
+ Layer.mock(PipelineService.PipelineService)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
NodeServices.layer,
),
diff --git a/apps/server/src/mcp/TaskCancelUsageLimit.integration.test.ts b/apps/server/src/mcp/TaskCancelUsageLimit.integration.test.ts
index e4176219244cf..ea4742386734c 100644
--- a/apps/server/src/mcp/TaskCancelUsageLimit.integration.test.ts
+++ b/apps/server/src/mcp/TaskCancelUsageLimit.integration.test.ts
@@ -38,6 +38,7 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
+import * as PipelineService from "../pipelines/PipelineService.ts";
import * as Scheduler from "../scheduling/Scheduler.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
@@ -188,6 +189,7 @@ it.effect.each([
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
ServerSettings.layerTest(),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
+ Layer.mock(PipelineService.PipelineService)({}),
NodeServices.layer,
),
),
diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts
index 3be8705cc0bb0..3d634dae33042 100644
--- a/apps/server/src/mcp/WorktreeMcpService.test.ts
+++ b/apps/server/src/mcp/WorktreeMcpService.test.ts
@@ -32,6 +32,7 @@ import * as ProjectService from "../project/ProjectService.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
+import * as TaskFolderService from "../workspace/TaskFolderService.ts";
import type * as McpInvocationContext from "./McpInvocationContext.ts";
import * as WorktreeMcpService from "./WorktreeMcpService.ts";
@@ -82,6 +83,7 @@ const project: Project = {
workspaceRoot,
defaultModelSelection: null,
scripts: [],
+ trackedFolders: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
@@ -113,6 +115,7 @@ interface HarnessOptions {
readonly removeWorktreeFails?: boolean;
readonly deleteLocalBranchFails?: boolean;
readonly createWorktreeGate?: Effect.Effect;
+ readonly taskFolders?: Partial;
}
const makeHarness = (options: HarnessOptions = {}) => {
@@ -318,6 +321,10 @@ const makeHarness = (options: HarnessOptions = {}) => {
Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
refreshStatus,
} satisfies Partial),
+ Layer.mock(TaskFolderService.TaskFolderService)({
+ plan: () => Effect.succeed(null),
+ ...options.taskFolders,
+ }),
NodeServices.layer,
),
),
@@ -668,6 +675,59 @@ describe("t3_worktree_handoff", () => {
expect(harness.dispatch).toHaveBeenCalled();
});
});
+
+ it.effect("hands a multi-repo thread a task folder and names the repos it left out", () => {
+ const home = "/worktrees/project/feature-multi";
+ const record = {
+ root: home,
+ projectId,
+ homeWorktreePath: home,
+ repositories: [
+ {
+ kind: "home" as const,
+ name: "project",
+ originalPath: workspaceRoot,
+ worktreePath: home,
+ relativePath: "",
+ baseRef: "dev",
+ branch: "feature/multi",
+ },
+ ],
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ };
+ const create = vi.fn((_input: TaskFolderService.TaskFolderCreateInput) =>
+ Effect.succeed({
+ record,
+ failed: [{ name: "api", originalPath: "/repo/api", detail: "invalid reference: nope" }],
+ startedFromOrigin: false,
+ }),
+ );
+ const harness = makeHarness({
+ taskFolders: {
+ plan: () =>
+ Effect.succeed({
+ projectId,
+ homeName: "project",
+ homePath: workspaceRoot,
+ repositories: [{ name: "api", originalPath: "/repo/api", baseRef: undefined }],
+ }),
+ create,
+ },
+ });
+ return Effect.gen(function* () {
+ const result = yield* runHandoff(harness, { branch: "feature/multi" });
+ expect(result.worktreePath).toBe(home);
+ expect(result.branch).toBe("feature/multi");
+ expect(result.note).toContain("api (invalid reference: nope)");
+ expect(create.mock.calls[0]?.[0]).toMatchObject({ branch: "feature/multi", baseRef: "dev" });
+ expect(harness.createWorktree).not.toHaveBeenCalled();
+ expect(harness.fetchWorktreeBaseCommit).not.toHaveBeenCalled();
+ expect(harness.dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ worktreePath: home, branch: "feature/multi" }),
+ );
+ });
+ });
});
describe("t3_worktree_status", () => {
diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts
index 267df07f2432f..b3c17c55182bd 100644
--- a/apps/server/src/mcp/WorktreeMcpService.ts
+++ b/apps/server/src/mcp/WorktreeMcpService.ts
@@ -22,6 +22,7 @@ import * as ProjectService from "../project/ProjectService.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
+import * as TaskFolderService from "../workspace/TaskFolderService.ts";
import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts";
export class WorktreeMcpService extends Context.Service<
@@ -62,6 +63,8 @@ const make = Effect.gen(function* () {
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
+ // Optional so hosts and tests without task folders keep single-repo handoffs.
+ const taskFolders = yield* Effect.serviceOption(TaskFolderService.TaskFolderService);
// Serialize handoffs per thread to avoid creating two worktrees and orphaning one.
const handoffThreadsInFlight = new Set();
@@ -206,11 +209,19 @@ const make = Effect.gen(function* () {
}
const startFromOrigin = input.startFromOrigin ?? (yield* readDefaultStartFromOrigin);
+ const folders = Option.getOrUndefined(taskFolders);
+ const folderPlan =
+ folders === undefined
+ ? null
+ : yield* folders
+ .plan({ project })
+ .pipe(asOperationFailed("Unable to read the project's repositories"));
let worktreeBaseRef = baseRef;
let baseRefName = baseRef;
let startedFromOrigin = false;
- if (startFromOrigin) {
+ // A task folder fetches each repo's own base while it creates the worktrees.
+ if (startFromOrigin && folderPlan === null) {
const resolvedRemoteBase = yield* gitWorkflow
.fetchWorktreeBaseCommit({ cwd: projectCwd, refName: baseRef })
.pipe(asOperationFailed(`Unable to fetch the remote base of '${baseRef}'`));
@@ -226,17 +237,34 @@ const make = Effect.gen(function* () {
// Mask interruption after worktree creation through setup; binding can detach and interrupt the caller.
return yield* Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
- const worktree = yield* restore(
- gitWorkflow
- .createWorktree({
- cwd: projectCwd,
- refName: worktreeBaseRef,
- newRefName: input.branch,
- baseRefName,
- path: null,
- })
- .pipe(asOperationFailed("Unable to create the worktree")),
- );
+ const folder =
+ folders === undefined || folderPlan === null
+ ? null
+ : yield* restore(
+ folders
+ .create({ plan: folderPlan, branch: input.branch, baseRef, startFromOrigin })
+ .pipe(asOperationFailed("Unable to create the worktrees")),
+ );
+ const worktree =
+ folder === null
+ ? yield* restore(
+ gitWorkflow
+ .createWorktree({
+ cwd: projectCwd,
+ refName: worktreeBaseRef,
+ newRefName: input.branch,
+ baseRefName,
+ path: null,
+ })
+ .pipe(asOperationFailed("Unable to create the worktree")),
+ )
+ : {
+ worktree: {
+ path: folder.record.homeWorktreePath,
+ refName: folder.record.repositories[0]?.branch ?? input.branch,
+ },
+ };
+ if (folder !== null) startedFromOrigin = folder.startedFromOrigin;
const worktreePath = worktree.worktree.path;
const reportFailed = (logMessage: string) =>
@@ -250,17 +278,36 @@ const make = Effect.gen(function* () {
});
const removeCreatedWorktree = Effect.suspend(() =>
- gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }).pipe(
- Effect.andThen(
- Effect.suspend(() =>
- gitWorkflow.deleteLocalBranch({
- cwd: projectCwd,
- refName: worktree.worktree.refName,
- force: true,
- }),
+ folder === null
+ ? gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }).pipe(
+ Effect.andThen(
+ Effect.suspend(() =>
+ gitWorkflow.deleteLocalBranch({
+ cwd: projectCwd,
+ refName: worktree.worktree.refName,
+ force: true,
+ }),
+ ),
+ ),
+ )
+ : folders!.remove({ path: worktreePath, force: true }).pipe(
+ Effect.flatMap((removal) =>
+ Option.isSome(removal) && removal.value.removed
+ ? Effect.forEach(
+ folder.record.repositories,
+ (row) =>
+ row.branch === null
+ ? Effect.void
+ : gitWorkflow.deleteLocalBranch({
+ cwd: row.originalPath,
+ refName: row.branch,
+ force: true,
+ }),
+ { discard: true },
+ )
+ : Effect.void,
+ ),
),
- ),
- ),
).pipe(Effect.ignoreCause({ log: true }));
const recheckAndBind = Effect.gen(function* () {
@@ -365,6 +412,12 @@ const make = Effect.gen(function* () {
);
}
+ const missing =
+ folder === null || folder.failed.length === 0
+ ? ""
+ : ` These repositories have no worktree: ${folder.failed
+ .map((failure) => `${failure.name} (${failure.detail})`)
+ .join("; ")}.`;
const result: WorktreeMcpHandoffResult = {
worktreePath,
branch: worktree.worktree.refName,
@@ -373,9 +426,10 @@ const make = Effect.gen(function* () {
setupScript,
continuation,
note:
- continuation.status === "scheduled"
+ (continuation.status === "scheduled"
? "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the queued continuation prompt then starts the next turn inside the worktree with the conversation preserved. The worktree is not removed automatically when the thread is deleted."
- : "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the conversation continues inside the worktree when the thread receives its next message. Pass continuationPrompt to resume automatically. The worktree is not removed automatically when the thread is deleted.",
+ : "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the conversation continues inside the worktree when the thread receives its next message. Pass continuationPrompt to resume automatically. The worktree is not removed automatically when the thread is deleted.") +
+ missing,
};
return result;
}),
diff --git a/apps/server/src/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.ts
index 253905e1d6373..9c9f17a6f89de 100644
--- a/apps/server/src/mcp/linkOrigin.test.ts
+++ b/apps/server/src/mcp/linkOrigin.test.ts
@@ -34,6 +34,7 @@ import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
+import * as PipelineService from "../pipelines/PipelineService.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
@@ -117,75 +118,79 @@ const layerTools = Layer.mergeAll(
McpHttpServer.layerOrchestratorToolkit,
McpHttpServer.layerThreadToolkit,
McpHttpServer.layerProjectRegistration,
-).pipe(
- Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
- Layer.provideMerge(McpServer.McpServer.layer),
- Layer.provide(layerLaunches),
- Layer.provide(NodeCrypto.layer),
- Layer.provide(
- Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
- ),
- Layer.provide(
- Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
- list: () => Effect.succeed([]),
- }),
- ),
- Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
- Layer.provide(
- Layer.mock(ProjectService.ProjectService)({
- getById: () => Effect.succeedNone,
- create: (input) =>
- Effect.succeed({
- id: input.projectId,
- title: input.title,
- workspaceRoot: input.workspaceRoot,
- defaultModelSelection: null,
- scripts: [],
- createdAt: "2026-10-18T00:00:00.000Z",
- updatedAt: "2026-10-18T00:00:00.000Z",
- deletedAt: null,
- }),
- update: (input) =>
- Effect.succeed({
- id: input.projectId,
- title: input.title ?? "Untitled",
- workspaceRoot: "/p/t3code",
- defaultModelSelection: null,
- scripts: [],
- createdAt: "2026-10-18T00:00:00.000Z",
- updatedAt: "2026-10-18T00:00:00.000Z",
- deletedAt: null,
- }),
- }),
- ),
- Layer.provide(Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({})),
- Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
- Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
- Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
- Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
- Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
- Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
- Layer.provide(
- Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }),
- ),
- Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
- Layer.provide(
- Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
- cloneRepository: (input) =>
- Effect.succeed({
- cwd: input.destinationPath,
- remoteUrl: "https://github.com/pingdotgg/t3code.git",
- repository: null,
- }),
- }),
- ),
- Layer.provide(
- ServerConfig.layerTest(process.cwd(), { prefix: "t3-link-origin-" }).pipe(
- Layer.provide(NodeServices.layer),
+)
+ .pipe(
+ Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
+ Layer.provideMerge(McpServer.McpServer.layer),
+ Layer.provide(layerLaunches),
+ Layer.provide(NodeCrypto.layer),
+ Layer.provide(
+ Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
),
- ),
- Layer.provide(NodeServices.layer),
-);
+ Layer.provide(
+ Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
+ list: () => Effect.succeed([]),
+ }),
+ ),
+ Layer.provide(Layer.mock(PipelineService.PipelineService)({})),
+ Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
+ Layer.provide(
+ Layer.mock(ProjectService.ProjectService)({
+ getById: () => Effect.succeedNone,
+ create: (input) =>
+ Effect.succeed({
+ id: input.projectId,
+ title: input.title,
+ workspaceRoot: input.workspaceRoot,
+ defaultModelSelection: null,
+ scripts: [],
+ trackedFolders: [],
+ createdAt: "2026-10-18T00:00:00.000Z",
+ updatedAt: "2026-10-18T00:00:00.000Z",
+ deletedAt: null,
+ }),
+ update: (input) =>
+ Effect.succeed({
+ id: input.projectId,
+ title: input.title ?? "Untitled",
+ workspaceRoot: "/p/t3code",
+ defaultModelSelection: null,
+ scripts: [],
+ trackedFolders: [],
+ createdAt: "2026-10-18T00:00:00.000Z",
+ updatedAt: "2026-10-18T00:00:00.000Z",
+ deletedAt: null,
+ }),
+ }),
+ ),
+ Layer.provide(Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({})),
+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
+ Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
+ Layer.provide(
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }),
+ ),
+ Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
+ Layer.provide(
+ Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
+ cloneRepository: (input) =>
+ Effect.succeed({
+ cwd: input.destinationPath,
+ remoteUrl: "https://github.com/pingdotgg/t3code.git",
+ repository: null,
+ }),
+ }),
+ ),
+ Layer.provide(
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-link-origin-" }).pipe(
+ Layer.provide(NodeServices.layer),
+ ),
+ ),
+ )
+ .pipe(Layer.provide(NodeServices.layer));
const mcpClient = McpSchema.McpServerClient.of({
clientId: 1,
diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts
index 5774f0e4c4f65..9581fee13f26b 100644
--- a/apps/server/src/mcp/toolkits/core.test.ts
+++ b/apps/server/src/mcp/toolkits/core.test.ts
@@ -48,6 +48,7 @@ import * as ProjectService from "../../project/ProjectService.ts";
import * as ProviderRegistry from "../../provider/ProviderRegistry.ts";
import * as SecretRequests from "../../secrets/SecretRequests.ts";
import * as RemoteDelegation from "../../peer/RemoteDelegation.ts";
+import * as PipelineService from "../../pipelines/PipelineService.ts";
import * as ScheduledTaskService from "../../scheduledTasks/ScheduledTaskService.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as McpHttpServer from "../McpHttpServer.ts";
@@ -77,6 +78,7 @@ const decodeThreadReadResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadR
const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe(
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
+ Layer.provide(Layer.mock(PipelineService.PipelineService)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
@@ -648,6 +650,7 @@ it.effect("refuses act-as-caller tools to a client caller", () =>
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
+ Layer.provide(Layer.mock(PipelineService.PipelineService)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
@@ -693,6 +696,7 @@ it.effect("a caller cannot rewrite a scheduled task that runs above its own mode
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
+ Layer.provide(Layer.mock(PipelineService.PipelineService)({})),
Layer.provide(
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
list: () =>
@@ -779,6 +783,114 @@ it.effect.each([
),
);
+it.effect(
+ "pipeline tools: a read-only client lists and checks runs but cannot start, continue, revise or cancel",
+ () =>
+ Effect.gen(function* () {
+ const server = yield* McpServer.McpServer;
+ const call = (
+ access: McpInvocationContext.McpClientCaller["access"],
+ name: string,
+ args: Record,
+ ) =>
+ server
+ .callTool({ name, arguments: args })
+ .pipe(
+ Effect.provideService(McpInvocationContext.McpInvocationContext, clientScope(access)),
+ Effect.provideService(McpSchema.McpServerClient, client),
+ );
+ const runId = "pipeline-run:core";
+
+ expect((yield* call("read-only", "list_pipelines", {})).isError).toBe(false);
+ expect((yield* call("read-only", "pipeline_status", { runId })).isError).toBe(false);
+ for (const [name, args] of [
+ [
+ "start_pipeline",
+ { pipeline: "Feature delivery", prompt: "Add dark mode", projectId: "project-a" },
+ ],
+ ["continue_pipeline", { runId, stepIndex: 0 }],
+ ["revise_pipeline_step", { runId, stepIndex: 0, feedback: "Cover dark mode" }],
+ ["cancel_pipeline", { runId }],
+ ] as const) {
+ expect(declaredFailure(yield* call("read-only", name, args)), name).toMatchObject({
+ code: "capability_denied",
+ });
+ }
+ expect(started).toEqual([]);
+
+ // A client's approval is the step limit: the service passes it to the runner as `modeLimit`.
+ const result = yield* call("auto", "start_pipeline", {
+ pipeline: "pipeline:feature-delivery",
+ prompt: "Add dark mode",
+ projectId: "project-a",
+ });
+ expect(result.isError).toBe(false);
+ expect(started).toEqual([
+ { createdBy: "agent", modeLimit: { runtimeMode: "auto", interactionMode: "default" } },
+ ]);
+ }).pipe(
+ Effect.provide(
+ layerOrchestratorToolkit.pipe(
+ Layer.provideMerge(McpServer.McpServer.layer),
+ Layer.provide(NodeCrypto.layer),
+ Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})),
+ Layer.provide(ServerSettings.layerTest()),
+ Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
+ Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
+ Layer.provide(
+ Layer.mock(PipelineService.PipelineService)({
+ list: () =>
+ Effect.succeed({
+ pipelines: [
+ { id: "pipeline:feature-delivery", name: "Feature delivery", steps: [] },
+ ],
+ } as never),
+ getRun: () => Effect.succeed(pipelineRun as never),
+ start: (_input, options) =>
+ Effect.sync(() => {
+ started.push(options);
+ return { run: pipelineRun } as never;
+ }),
+ }),
+ ),
+ Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
+ Layer.provide(
+ Layer.mock(ProjectService.ProjectService)({
+ getById: () =>
+ Effect.succeedSome({
+ id: "project-a",
+ title: "Acme",
+ workspaceRoot: "/home/user/acme",
+ } as never),
+ }),
+ ),
+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
+ ),
+ ),
+ ),
+);
+const started: Array = [];
+const pipelineRun = {
+ id: "pipeline-run:core",
+ pipelineId: "pipeline:feature-delivery",
+ definition: { name: "Feature delivery", steps: [] },
+ projectId: "project-a",
+ parentThreadId: "thread-pipeline-parent",
+ status: "running",
+ pauseReason: null,
+ error: null,
+ currentStepIndex: 0,
+ revisions: [],
+ steps: [],
+ createdAt: "2026-10-28T10:00:00.000Z",
+ updatedAt: "2026-10-28T10:00:00.000Z",
+ completedAt: null,
+};
+
function scheduledTask(id: string, runtimeMode: "auto" | "full-access"): never {
return {
id,
@@ -855,6 +967,7 @@ it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])(
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
+ Layer.provide(Layer.mock(PipelineService.PipelineService)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
@@ -951,6 +1064,7 @@ it.effect("discovers workflow stop targets and requires orchestration capability
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
+ Layer.provide(Layer.mock(PipelineService.PipelineService)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
@@ -1058,6 +1172,7 @@ it.effect(
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
+ Layer.provide(Layer.mock(PipelineService.PipelineService)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
index 3db297bc0d303..a1d1a14baa251 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
@@ -131,6 +131,74 @@ const handlers = {
return yield* service.deleteScheduledTask(scope, input);
}),
),
+ list_pipelines: McpToolAccess.reads(() =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
+ return yield* service.listPipelines(scope);
+ }),
+ ),
+ start_pipeline: McpToolAccess.startsThreads(
+ () => ({}),
+ (input) =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
+ return yield* service.startPipeline(scope, input);
+ }),
+ // A run's threads carry no link origin, so a linked caller could not be fenced to its own runs.
+ { refused: "start pipelines in this environment" },
+ ),
+ pipeline_status: McpToolAccess.reads((input) =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
+ return yield* service.pipelineStatus(scope, input);
+ }),
+ ),
+ continue_pipeline: McpToolAccess.writes(
+ (input) =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
+ return yield* service.continuePipeline(scope, input);
+ }),
+ { refusedWhenLinked: "continue this environment's pipelines" },
+ ),
+ cancel_pipeline: McpToolAccess.writes(
+ (input) =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
+ return yield* service.cancelPipeline(scope, input);
+ }),
+ { refusedWhenLinked: "cancel this environment's pipelines" },
+ ),
+ rerun_pipeline_step: McpToolAccess.writes(
+ (input) =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
+ return yield* service.rerunPipelineStep(scope, input);
+ }),
+ { refusedWhenLinked: "rerun this environment's pipelines" },
+ ),
+ revise_pipeline_step: McpToolAccess.writes(
+ (input) =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
+ return yield* service.revisePipelineStep(scope, input);
+ }),
+ { refusedWhenLinked: "send feedback to this environment's pipelines" },
+ ),
+ handoff_pipeline_step: McpToolAccess.actsAsCaller((input) =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
+ return yield* service.handoffPipelineStep(scope, input);
+ }),
+ ),
request_secret: McpToolAccess.actsAsCaller((input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext.McpInvocationContext;
diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts
index ea0caa4ce166a..86de5387441f0 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts
@@ -1,4 +1,5 @@
import { expect, it } from "@effect/vitest";
+import * as Context from "effect/Context";
import * as Exit from "effect/Exit";
import * as Schema from "effect/Schema";
import { Tool } from "effect/ai";
@@ -27,3 +28,43 @@ it("refuses a t3_thread_update whose fields do not fit its action", () => {
true,
);
});
+
+it("decodes pipeline tool inputs and refuses empty or stale-shaped ones", () => {
+ const decodeStart = Schema.decodeUnknownExit(
+ OrchestratorToolkit.tools.start_pipeline.parametersSchema,
+ );
+ expect(
+ Exit.isSuccess(decodeStart({ pipeline: "Feature delivery", prompt: "Add dark mode" })),
+ ).toBe(true);
+ expect(
+ Exit.isSuccess(
+ decodeStart({
+ pipeline: "pipeline:starter:feature-delivery",
+ prompt: "Add dark mode",
+ worktree: true,
+ clientRequestId: "start-1",
+ }),
+ ),
+ ).toBe(true);
+ expect(Exit.isFailure(decodeStart({ pipeline: "Feature delivery", prompt: " " }))).toBe(true);
+ expect(Exit.isFailure(decodeStart({ prompt: "Add dark mode" }))).toBe(true);
+
+ const decodeContinue = Schema.decodeUnknownExit(
+ OrchestratorToolkit.tools.continue_pipeline.parametersSchema,
+ );
+ expect(Exit.isSuccess(decodeContinue({ runId: "pipeline-run:one", stepIndex: 1 }))).toBe(true);
+ expect(Exit.isFailure(decodeContinue({ runId: "pipeline-run:one" }))).toBe(true);
+ expect(Exit.isFailure(decodeContinue({ runId: "pipeline-run:one", stepIndex: -1 }))).toBe(true);
+});
+
+// The Claude read-only allowlist is derived from these annotations (ClaudeAdapterV2.test.ts checks it).
+it("marks only the pipeline reads as read-only", () => {
+ const readonly = (name: keyof typeof OrchestratorToolkit.tools) =>
+ Context.get(OrchestratorToolkit.tools[name].annotations, Tool.Readonly);
+ expect(readonly("list_pipelines")).toBe(true);
+ expect(readonly("pipeline_status")).toBe(true);
+ expect(readonly("start_pipeline")).toBe(false);
+ expect(readonly("continue_pipeline")).toBe(false);
+ expect(readonly("revise_pipeline_step")).toBe(false);
+ expect(readonly("cancel_pipeline")).toBe(false);
+});
diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
index 7c05f5c8d8e25..6d55e6ef69310 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
@@ -13,14 +13,23 @@ import {
OrchestratorMcpDelegateTaskResult,
OrchestratorMcpDeleteScheduledTaskInput,
OrchestratorMcpDeleteScheduledTaskResult,
+ OrchestratorMcpContinuePipelineInput,
+ OrchestratorMcpHandoffPipelineStepInput,
+ OrchestratorMcpHandoffPipelineStepResult,
+ OrchestratorMcpRerunPipelineInput,
+ OrchestratorMcpRevisePipelineStepInput,
OrchestratorMcpEnvironmentTarget,
OrchestratorMcpRequestSecretInput,
OrchestratorMcpRequestSecretResult,
OrchestratorMcpFailure,
+ OrchestratorMcpListPipelinesResult,
OrchestratorMcpListScheduledTasksInput,
OrchestratorMcpListScheduledTasksResult,
+ OrchestratorMcpPipelineRun,
+ OrchestratorMcpPipelineRunInput,
OrchestratorMcpSaveScheduledTaskInput,
OrchestratorMcpScheduleTaskResult,
+ OrchestratorMcpStartPipelineInput,
OrchestratorMcpTaskCancelInput,
OrchestratorMcpTaskCancelResult,
OrchestratorMcpTaskStatusInput,
@@ -195,6 +204,109 @@ const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", {
.annotate(Tool.Title, "Delete a scheduled task")
.annotate(Tool.Destructive, true);
+const ListPipelinesTool = Tool.make("list_pipelines", {
+ description:
+ "List the user's pipelines: saved chains of agent steps, each step in its own thread, each step's output feeding the next. Pass an id or exact name to `start_pipeline`.",
+ success: OrchestratorMcpListPipelinesResult,
+ failure: OrchestratorMcpFailure,
+ failureMode: "return",
+ dependencies,
+})
+ .annotate(Tool.Title, "List pipelines")
+ .annotate(Tool.Readonly, true)
+ .annotate(Tool.Destructive, false)
+ .annotate(Tool.Idempotent, true);
+
+const StartPipelineTool = Tool.make("start_pipeline", {
+ description:
+ "Run a saved pipeline on `prompt` when the user asks for one by name or purpose. Not for ordinary delegation. Steps share your checkout (another project's root), or one new worktree with `worktree=true`. They run at your runtime mode or narrower. Plan mode cannot start one. Returns `runId`: poll `pipeline_status`. In your reply, name the run as its `link` verbatim.",
+ parameters: OrchestratorMcpStartPipelineInput,
+ success: OrchestratorMcpPipelineRun,
+ failure: OrchestratorMcpFailure,
+ failureMode: "return",
+ dependencies,
+})
+ .annotate(Tool.Title, "Start a pipeline")
+ .annotate(Tool.Destructive, true)
+ .annotate(Tool.OpenWorld, true);
+
+const PipelineStatusTool = Tool.make("pipeline_status", {
+ description:
+ "Status of a pipeline run: each step's status, thread `link`, output preview, and the feedback sent to steps so far (`revisions`). `paused` with `awaiting_continue`: `continue_pipeline` if you started the run, or if you are the run's own coordinator chat and the user's latest message asks you to; else wait for the user. The user's feedback on an earlier step: `revise_pipeline_step`. `awaiting_handoff`: the step's agent ended its turn without handing off, usually with a question; tell the user. No tool retries or skips a failed or stopped step: tell the user.",
+ parameters: OrchestratorMcpPipelineRunInput,
+ success: OrchestratorMcpPipelineRun,
+ failure: OrchestratorMcpFailure,
+ failureMode: "return",
+ dependencies,
+})
+ .annotate(Tool.Title, "Pipeline run status")
+ .annotate(Tool.Readonly, true)
+ .annotate(Tool.Destructive, false)
+ .annotate(Tool.Idempotent, true);
+
+const ContinuePipelineTool = Tool.make("continue_pipeline", {
+ description:
+ "Resume a paused pipeline run at `stepIndex`, its `currentStepIndex`. Starts the next step. Refused for a user-started run's `awaiting_continue` pause, unless you are that run's own coordinator chat: then only when the user's latest message asks you to continue. For a failed, stopped or `awaiting_handoff` step, takes its thread's latest message as its result: only if the user asks.",
+ parameters: OrchestratorMcpContinuePipelineInput,
+ success: OrchestratorMcpPipelineRun,
+ failure: OrchestratorMcpFailure,
+ failureMode: "return",
+ dependencies,
+})
+ .annotate(Tool.Title, "Continue a pipeline")
+ .annotate(Tool.Destructive, true)
+ .annotate(Tool.OpenWorld, true);
+
+const CancelPipelineTool = Tool.make("cancel_pipeline", {
+ description:
+ "Cancel a pipeline run: stops its running step and starts no more. Finished steps and their threads stay.",
+ parameters: OrchestratorMcpPipelineRunInput,
+ success: OrchestratorMcpPipelineRun,
+ failure: OrchestratorMcpFailure,
+ failureMode: "return",
+ dependencies,
+})
+ .annotate(Tool.Title, "Cancel a pipeline")
+ .annotate(Tool.Destructive, true);
+
+const RerunPipelineTool = Tool.make("rerun_pipeline_step", {
+ description:
+ "Start over: run a paused, cancelled or completed pipeline run again from `stepIndex` in fresh threads with the original prompts; earlier steps keep their results. Only if the user asks to start over. For feedback on a step's work use `revise_pipeline_step` instead.",
+ parameters: OrchestratorMcpRerunPipelineInput,
+ success: OrchestratorMcpPipelineRun,
+ failure: OrchestratorMcpFailure,
+ failureMode: "return",
+ dependencies,
+})
+ .annotate(Tool.Title, "Rerun a pipeline step")
+ .annotate(Tool.Destructive, true)
+ .annotate(Tool.OpenWorld, true);
+
+const RevisePipelineStepTool = Tool.make("revise_pipeline_step", {
+ description:
+ "Send the user's feedback to an earlier step of a pipeline run. That step fixes it in its own thread, then every later step redoes its work in its thread. Stops a later step that is running. Only when the user gives feedback; refused from the run's own step threads.",
+ parameters: OrchestratorMcpRevisePipelineStepInput,
+ success: OrchestratorMcpPipelineRun,
+ failure: OrchestratorMcpFailure,
+ failureMode: "return",
+ dependencies,
+})
+ .annotate(Tool.Title, "Revise a pipeline step")
+ .annotate(Tool.Destructive, true)
+ .annotate(Tool.OpenWorld, true);
+
+const HandoffPipelineStepTool = Tool.make("handoff_pipeline_step", {
+ description:
+ "Only in a pipeline step's thread: hand this step's finished result to the next step. The run moves on when your turn ends. Call it only when the step's work is done; if you are blocked or need a decision, ask the user and wait instead.",
+ parameters: OrchestratorMcpHandoffPipelineStepInput,
+ success: OrchestratorMcpHandoffPipelineStepResult,
+ failure: OrchestratorMcpFailure,
+ failureMode: "return",
+ dependencies,
+})
+ .annotate(Tool.Title, "Hand off a pipeline step")
+ .annotate(Tool.Destructive, false);
+
const RequestSecretTool = Tool.make("request_secret", {
description:
'Ask the user to enter a secret in a private card and wait. You never see the value. Returns a one-use `secretRef` for a tool that accepts it, or with `delivery: "file"` a private file path to read inside a shell command. Asked how to provide a secret: call this now, do not explain instead.',
@@ -357,6 +469,14 @@ export const OrchestratorToolkit = Toolkit.make(
ScheduleTaskTool,
ListScheduledTasksTool,
DeleteScheduledTaskTool,
+ ListPipelinesTool,
+ StartPipelineTool,
+ PipelineStatusTool,
+ ContinuePipelineTool,
+ CancelPipelineTool,
+ RerunPipelineTool,
+ RevisePipelineStepTool,
+ HandoffPipelineStepTool,
RequestSecretTool,
CreateThreadsTool,
ThreadListTool,
diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts
index 4dd7a995a921b..c470a5b015fd9 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.test.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts
@@ -642,6 +642,7 @@ it.effect("deleting a project through MCP also discards its clone record", () =>
autoPull: false,
projectIcon: null,
scripts: [],
+ trackedFolders: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: "2026-01-01T00:00:00.000Z",
diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts
index 59399c7febdea..fde068d499995 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.ts
@@ -41,7 +41,9 @@ function projectFailure(error: Project.ProjectServiceError) {
? "The project was not found."
: error._tag === "ProjectConflictError"
? "The workspace is already registered to a project."
- : "The project is not empty; force=true is required to delete it.";
+ : error._tag === "ProjectTrackedFoldersInvalidError"
+ ? error.message
+ : "The project is not empty; force=true is required to delete it.";
return new OrchestratorMcpFailure({ code: "invalid_request", message });
}
@@ -315,7 +317,8 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
if (
input.scripts !== undefined ||
input.createWorkspaceRootIfMissing !== undefined ||
- input.defaultModelSelection !== undefined
+ input.defaultModelSelection !== undefined ||
+ input.trackedFolders !== undefined
)
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
index 714af0312b45f..c404c214c0b18 100644
--- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
+++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
@@ -1,5 +1,7 @@
import {
EnvironmentId,
+ PipelineRunId,
+ PipelineStepId,
ProjectId,
ProviderInstanceId,
ThreadId,
@@ -77,6 +79,7 @@ function makeProject(
workspaceRoot: "/workspace/project",
defaultModelSelection: null,
scripts: [],
+ trackedFolders: [],
repositoryIdentity,
createdAt: "2026-08-01T00:00:00.000Z",
updatedAt: "2026-08-01T00:00:00.000Z",
@@ -353,6 +356,41 @@ describe("pull request toolkit handlers", () => {
}),
);
+ it.effect("refuses a watch from a pipeline step, which hands back when its turn ends", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness({
+ thread: {
+ ...makeThread([makeLink(1, { headBranch: "feature" })]),
+ pipeline: { runId: PipelineRunId.make("run-1"), stepId: PipelineStepId.make("review") },
+ },
+ });
+ const error = yield* harness
+ .call("watch_pull_request", { repository: "t3tools/t3code", number: 1 })
+ .pipe(Effect.flip);
+ expect(error).toMatchObject({ _tag: "PullRequestWatchFromPipelineStepError" });
+ expect(yield* Ref.get(harness.commands)).toEqual([]);
+ const result = yield* harness.call("link_pull_request", {
+ url: "https://github.com/t3tools/t3code/pull/124",
+ });
+ expect(result).toMatchObject({ number: 124, next: CHILD_PULL_REQUEST_REPORT_NEXT });
+ }),
+ );
+
+ it.effect("lets a pipeline's parent thread watch its pull request", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness({
+ thread: {
+ ...makeThread([makeLink(1, { headBranch: "feature" })]),
+ pipeline: { runId: PipelineRunId.make("run-1"), stepId: null },
+ },
+ });
+ yield* harness.call("watch_pull_request", { repository: "t3tools/t3code", number: 1 });
+ expect(yield* Ref.get(harness.commands)).toMatchObject([
+ { type: "thread.pull-request.watch", number: 1, watching: true },
+ ]);
+ }),
+ );
+
it.effect("asks a subagent thread to end with its PR report after it links", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts
index 7798ec11bff05..58a5bdd772bc0 100644
--- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts
+++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts
@@ -40,6 +40,7 @@ import {
type PullRequestTargetInput,
PullRequestWatchFailedError,
PullRequestWatchFromSubagentError,
+ PullRequestWatchFromPipelineStepError,
PullRequestThreadNotFoundError,
PullRequestThreadRequiredError,
PullRequestGuideFailedError,
@@ -56,6 +57,11 @@ interface ResolvedTarget {
readonly url: string;
}
+/** A pipeline step hands its result back when its turn ends, like a subagent reporting to its parent. */
+function isPipelineStep(thread: OrchestrationV2ThreadShell): boolean {
+ return thread.pipeline != null && thread.pipeline.stepId !== null;
+}
+
function projectHostAndProvider(project: OrchestrationProjectShell | undefined): {
readonly host: string | null;
readonly kind: SourceControlProviderKind | null;
@@ -274,6 +280,10 @@ const make = Effect.gen(function* () {
if (watching && thread.lineage.relationshipToParent === "subagent") {
return yield* new PullRequestWatchFromSubagentError();
}
+ // A step's watch would hold its finished pipeline on the Working shelf and wake it later.
+ if (watching && isPipelineStep(thread)) {
+ return yield* new PullRequestWatchFromPipelineStepError();
+ }
const before = watchedLink(thread);
if (watching && before?.snapshot?.state === "merged") {
return yield* new PullRequestNotOpenError({ state: "merged" });
@@ -363,7 +373,7 @@ const make = Effect.gen(function* () {
Effect.gen(function* () {
const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId);
const next =
- thread.lineage.relationshipToParent === "subagent"
+ thread.lineage.relationshipToParent === "subagent" || isPipelineStep(thread)
? { next: CHILD_PULL_REQUEST_REPORT_NEXT }
: {};
const project = yield* projectOf(thread, PullRequestLinkFailedError);
diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts
index 789e9fe125235..9f1b1fe825130 100644
--- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts
+++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts
@@ -158,6 +158,15 @@ export class PullRequestWatchFromSubagentError extends Schema.TaggedError()(
+ "PullRequestWatchFromPipelineStepError",
+ {},
+) {
+ override get message(): string {
+ return "This thread is a pipeline step, so it cannot watch pull requests. Finish your step, then hand off with `handoff_pipeline_step`, including the pull request's state in its output.";
+ }
+}
+
export class PullRequestListFailedError extends Schema.TaggedError()(
"PullRequestListFailedError",
{ cause: Schema.Defect() },
@@ -200,6 +209,7 @@ export const PullRequestToolError = Schema.Union([
PullRequestWatchFailedError,
PullRequestNotOpenError,
PullRequestWatchFromSubagentError,
+ PullRequestWatchFromPipelineStepError,
PullRequestProjectNotFoundError,
PullRequestGuideFailedError,
]);
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index 7bb8bf8a34c18..e98314fe5d6bc 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -96,10 +96,40 @@ const RPC_AGGREGATES = {
[WS_METHODS.scheduledTasksRotateWebhookToken]: "scheduledTasks",
[WS_METHODS.scheduledTasksListWebhookDeliveries]: "scheduledTasks",
[WS_METHODS.scheduledTasksGetWebhookDelivery]: "scheduledTasks",
+ [WS_METHODS.pipelinesSubscribe]: "pipelines",
+ [WS_METHODS.pipelinesUpsert]: "pipelines",
+ [WS_METHODS.pipelinesDelete]: "pipelines",
+ [WS_METHODS.pipelineRunsSubscribe]: "pipelines",
+ [WS_METHODS.pipelineRunsSubscribeLive]: "pipelines",
+ [WS_METHODS.pipelineRunsStart]: "pipelines",
+ [WS_METHODS.pipelineRunsContinue]: "pipelines",
+ [WS_METHODS.pipelineRunsRetryStep]: "pipelines",
+ [WS_METHODS.pipelineRunsSkipStep]: "pipelines",
+ [WS_METHODS.pipelineRunsRerunFromStep]: "pipelines",
+ [WS_METHODS.pipelineRunsRevise]: "pipelines",
+ [WS_METHODS.pipelineRunsCancel]: "pipelines",
+ [WS_METHODS.pipelineRunsSetPauseBefore]: "pipelines",
[WS_METHODS.secretsAnswerRequest]: "secrets",
[WS_METHODS.guestShareCreate]: "guest-share",
[WS_METHODS.cloudGetRelayClientStatus]: "cloud",
[WS_METHODS.cloudInstallRelayClient]: "cloud",
+ [WS_METHODS.linearStatus]: "linear",
+ [WS_METHODS.linearConnect]: "linear",
+ [WS_METHODS.linearDisconnect]: "linear",
+ [WS_METHODS.linearResync]: "linear",
+ [WS_METHODS.linearRefresh]: "linear",
+ [WS_METHODS.linearTeams]: "linear",
+ [WS_METHODS.linearTeamMetadata]: "linear",
+ [WS_METHODS.linearProjects]: "linear",
+ [WS_METHODS.linearMilestones]: "linear",
+ [WS_METHODS.linearIssues]: "linear",
+ [WS_METHODS.linearIssueDetail]: "linear",
+ [WS_METHODS.linearSubIssues]: "linear",
+ [WS_METHODS.linearViews]: "linear",
+ [WS_METHODS.linearSearch]: "linear",
+ [WS_METHODS.linearActivity]: "linear",
+ [WS_METHODS.linearRecordLaunch]: "linear",
+ [WS_METHODS.linearSubscribeRefreshes]: "linear",
[WS_METHODS.pullRequestsList]: "pull-requests",
[WS_METHODS.pullRequestsListStats]: "pull-requests",
[WS_METHODS.pullRequestsFilterOptions]: "pull-requests",
@@ -185,6 +215,10 @@ const RPC_AGGREGATES = {
[WS_METHODS.vcsSwitchRef]: "vcs",
[WS_METHODS.vcsInit]: "vcs",
[WS_METHODS.reviewGetBranchCommits]: "review",
+ [WS_METHODS.workspaceListRepositories]: "workspace",
+ [WS_METHODS.workspaceScanFolders]: "workspace",
+ [WS_METHODS.workspacePreviewHomeGitInit]: "workspace",
+ [WS_METHODS.workspaceInitializeHomeGit]: "vcs",
[WS_METHODS.reviewGetDiffPreview]: "review",
[WS_METHODS.reviewGetDiffFileContents]: "review",
[WS_METHODS.terminalOpen]: "terminal",
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index 07c3bd731633f..91cbf8a5383ca 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -8,7 +8,11 @@ import {
} from "@t3tools/provider-acp-registry/testing";
import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings";
import { AcpRegistryCatalog } from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
-import { decodeAcpReplayTranscript, makeAcpReplayRuntime } from "./AcpAdapterV2.testkit.ts";
+import {
+ decodeAcpReplayTranscript,
+ makeAcpReplayCompletenessAssertion,
+ makeAcpReplayRuntime,
+} from "./AcpAdapterV2.testkit.ts";
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
@@ -1782,6 +1786,111 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
+ it.live.each([true, false])(
+ "sends the thread's other repos to an ACP agent only when it advertises them: %s",
+ (advertised) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-roots-" });
+ const statusPath = path.join(directory, "status.json");
+ const driver = ProviderDriverKind.make("acpRegistry");
+ const transcript = yield* decodeAcpReplayTranscript(
+ {
+ provider: driver,
+ protocol: "acp.ndjson-jsonrpc",
+ version: "1",
+ scenario: "multi-repo-roots",
+ entries: [
+ {
+ type: "expect_outbound",
+ frame: { kind: "request", method: "initialize", params: "" },
+ },
+ {
+ type: "emit_inbound",
+ frame: {
+ kind: "response",
+ method: "initialize",
+ result: {
+ protocolVersion: 1,
+ agentCapabilities: advertised
+ ? { sessionCapabilities: { additionalDirectories: {} } }
+ : {},
+ authMethods: [],
+ },
+ },
+ },
+ {
+ type: "expect_outbound",
+ frame: {
+ kind: "request",
+ method: "session/new",
+ params: {
+ cwd: "",
+ mcpServers: "",
+ ...(advertised ? { additionalDirectories: ["/work/api"] } : {}),
+ },
+ },
+ },
+ {
+ type: "emit_inbound",
+ frame: {
+ kind: "response",
+ method: "session/new",
+ result: { sessionId: "multi-repo-session" },
+ },
+ },
+ ],
+ },
+ driver,
+ );
+ const instanceId = ProviderInstanceId.make("acp-roots-test");
+ const adapter = yield* makeAcpRegistryAdapterV2({
+ instanceId,
+ selfInvocation: yield* resolveSelfInvocation(),
+ settings: DROID_SETTINGS,
+ environment: {},
+ makeRuntime: makeAcpReplayRuntime({
+ transcript,
+ statusPath,
+ fileSystem,
+ scriptPath: yield* path.fromFileUrl(
+ new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
+ ),
+ childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
+ }),
+ }).pipe(
+ Effect.provide(
+ Layer.mock(AcpRegistryCatalog)({ resolve: () => Effect.die("runtime is injected") }),
+ ),
+ );
+ const threadId = ThreadId.make("acp-roots-thread");
+ const modelSelection = { instanceId, model: "default" } as const;
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "auto-accept-edits",
+ interactionMode: "default",
+ cwd: directory,
+ workspace: {
+ repositories: [
+ { name: "web", path: directory },
+ { name: "api", path: "/work/api" },
+ ],
+ referenceFolders: [{ name: "design", path: "/notes/design" }],
+ extraRoots: ["/work/api"],
+ relativePathsDiffer: false,
+ },
+ });
+ const runtime = yield* adapter.openSession({
+ threadId,
+ modelSelection,
+ runtimePolicy,
+ providerSessionId: ProviderSessionId.make("acp-roots-session"),
+ });
+ yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
+ yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript);
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
+
it.live.each(["failed", "recovered", "cancelled"] as const)(
"projects Mistral retry notices and their %s outcome",
(outcome) =>
diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
index 63286a4bcea79..5c52b6e060a28 100644
--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
@@ -389,6 +389,63 @@ describe("AntigravityAdapterV2 client file system", () => {
);
});
+describe("AntigravityAdapterV2 multi-repo files", () => {
+ it.effect(
+ "reads the thread's other repos and reference folders and never advertises writes",
+ () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const web = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-web-" });
+ const api = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-api-" });
+ const design = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-ref-" });
+ const spec = path.join(design, "spec.md");
+ yield* fileSystem.writeFileString(spec, "spec");
+ const files = makeAntigravityAcpAdapterFlavor({
+ instanceId: ProviderInstanceId.make("antigravity-multi-repo-test"),
+ crypto: yield* Crypto.Crypto,
+ fileSystem,
+ path,
+ host: yield* ProviderHost.ProviderHost,
+ selfInvocation: undefined as never,
+ makeRuntime: () => Effect.die("not spawned in this test"),
+ withProcess: (_stop, task) => task,
+ // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
+ defaultModel: Effect.succeed(undefined),
+ }).clientFileSystem;
+ if (files === undefined) return yield* Effect.die("Antigravity serves client files");
+ const policy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd: web,
+ workspace: {
+ repositories: [
+ { name: "web", path: web },
+ { name: "api", path: api },
+ ],
+ referenceFolders: [{ name: "design", path: design }],
+ extraRoots: [api],
+ relativePathsDiffer: false,
+ },
+ });
+
+ yield* fileSystem.writeFileString(path.join(api, "index.ts"), "api");
+ const readApi = yield* files.readTextFile(
+ { sessionId: "mock-session-1", path: path.join(api, "index.ts") },
+ policy,
+ );
+ assert.equal(readApi.content, "api");
+ const readSpec = yield* files.readTextFile(
+ { sessionId: "mock-session-1", path: spec },
+ policy,
+ );
+ assert.equal(readSpec.content, "spec");
+ // Antigravity is read-only by design, even for the thread's own repos.
+ assert.isUndefined(files.writeTextFile);
+ }).pipe(Effect.provide(layerSession), Effect.scoped),
+ );
+});
+
describe("AntigravityAdapterV2 workspace changes", () => {
it.effect("confines file requests to the workspace of the turn in progress", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
index 8c5ccb48b149d..d1f51a8ec08dd 100644
--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
@@ -15,6 +15,7 @@ import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as EffectAcpErrors from "effect-acp/errors";
+import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import { PULL_REQUEST_LINKING_INSTRUCTIONS } from "@t3tools/provider-core/server/runtimeInstructions";
import type { AntigravityAuth } from "../../provider/AntigravityAuth.ts";
@@ -134,10 +135,15 @@ export function makeAntigravityAcpAdapterFlavor(
options: AntigravityAdapterV2Options & AntigravityFlavorServices,
): AcpAdapterV2Flavor {
const { profileDirectory } = options;
- const antigravityClientFileRoots = (cwd: string | null) =>
- cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir];
+ // Reads reach the thread's other repos and reference folders; writes are never advertised.
+ const readableClientFileRoots = (policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy) => [
+ ...(policy.cwd === null ? [] : [policy.cwd]),
+ ...(policy.workspace?.extraRoots ?? []),
+ options.host.paths.attachmentsDir,
+ ...(policy.workspace?.referenceFolders.map((folder) => folder.path) ?? []),
+ ];
const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")(
- function* (input: AcpAdapterV2RuntimeInput) {
+ function* ({ extraRoots, ...input }: AcpAdapterV2RuntimeInput) {
const scope = yield* Scope.fork(yield* Effect.scope);
const runtime = yield* options
.withProcess(
@@ -146,7 +152,8 @@ export function makeAntigravityAcpAdapterFlavor(
...input,
clientFileReads: true,
sessionSystemPromptAppend: PULL_REQUEST_LINKING_INSTRUCTIONS,
- additionalDirectories: [options.host.paths.attachmentsDir],
+ // Antigravity accepts additional directories without advertising them.
+ additionalDirectories: [options.host.paths.attachmentsDir, ...(extraRoots ?? [])],
}),
)
.pipe(Effect.provideService(Scope.Scope, scope));
@@ -250,11 +257,11 @@ export function makeAntigravityAcpAdapterFlavor(
sessionModeForPolicy: (policy) => antigravityPermissionMode(policy.runtimeMode),
runtimeModeForSessionMode: antigravityRuntimeModeForSessionMode,
clientFileSystem: {
- readTextFile: (request, cwd) =>
+ readTextFile: (request, policy) =>
readAntigravityClientTextFile({
fileSystem: options.fileSystem,
path: options.path,
- allowedRoots: antigravityClientFileRoots(cwd),
+ allowedRoots: readableClientFileRoots(policy),
request,
}),
},
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 42d24d0076d6e..5b307bc34858c 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -567,6 +567,52 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
assert.notEqual(rotatedKey, initialKey);
});
+ it("opens a new query with the thread's other repos when they change", () => {
+ const workspace = (extraRoots: ReadonlyArray) => ({
+ repositories: [
+ { name: "web", path: "/work/web" },
+ ...extraRoots.map((root) => ({ name: NodePath.basename(root), path: root })),
+ ],
+ referenceFolders: [{ name: "design", path: "/notes/design" }],
+ extraRoots,
+ relativePathsDiffer: false,
+ });
+ const queryPolicy = (extraRoots?: ReadonlyArray) =>
+ ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
+ ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd: "/work/web",
+ ...(extraRoots === undefined ? {} : { workspace: workspace(extraRoots) }),
+ }),
+ );
+ const key = (extraRoots?: ReadonlyArray) =>
+ ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(queryPolicy(extraRoots), {});
+ assert.equal(key(["/work/api"]), key(["/work/api"]));
+ assert.notEqual(key(["/work/api"]), key(["/work/api", "/work/docs"]));
+ assert.notEqual(key(), key(["/work/api"]));
+
+ const options = ClaudeAdapterV2.makeClaudeQueryOptions({
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
+ nativeThreadId: "native-multi-repo",
+ resume: true,
+ cwd: "/work/web",
+ attachmentsDir: "/attachments",
+ workspace: workspace(["/work/api"]),
+ });
+ // Reference folders are listed in the prompt but never granted.
+ assert.deepEqual(options.additionalDirectories, ["/work/web", "/work/api", "/attachments"]);
+ const systemPrompt = options.systemPrompt;
+ const append =
+ typeof systemPrompt === "object" &&
+ !Array.isArray(systemPrompt) &&
+ systemPrompt.type === "preset"
+ ? systemPrompt.append
+ : undefined;
+ assert.include(append, "- api (Git repository): /work/api");
+ assert.include(append, "- design (read-only reference): /notes/design");
+ });
+
it("matches the read-only allowlist to the orchestrator toolkit annotations", () => {
const readOnlyToolNames = [
...Object.values(OrchestratorToolkit.tools),
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 4d5238b74b709..da27e85aa2cec 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -1472,6 +1472,7 @@ export function makeClaudeQueryOptions(input: {
readonly resume: boolean;
readonly resumeSessionAt?: string;
readonly cwd: string | null;
+ readonly workspace?: ProviderAdapter.ProviderAdapterV2RuntimeWorkspace;
readonly attachmentsDir?: string;
readonly settings?: ClaudeSettings;
readonly sdkSettings?: string | ClaudeSdkSettings;
@@ -1599,7 +1600,10 @@ export function makeClaudeQueryOptions(input: {
type: "preset" as const,
preset: "claude_code" as const,
append: [
- buildRuntimeInstructions({ harness: "Claude Code" }) +
+ buildRuntimeInstructions({
+ harness: "Claude Code",
+ runtimePolicy: { cwd: input.cwd, workspace: input.workspace },
+ }) +
(input.mcpServers === undefined
? ""
: T3_CODE_ORCHESTRATION_INSTRUCTIONS +
@@ -1617,6 +1621,7 @@ export function makeClaudeQueryOptions(input: {
};
const additionalDirectories = [
...(input.cwd === null ? [] : [input.cwd]),
+ ...(input.workspace?.extraRoots ?? []),
...(input.attachmentsDir === undefined ? [] : [input.attachmentsDir]),
...claudeLaunchArgDirectories(input.settings?.launchArgs),
];
@@ -1704,6 +1709,8 @@ export const CLAUDE_T3_MCP_TOOL_WILDCARD = "mcp__t3-code__*";
export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray = [
"mcp__t3-code__orchestrator_capabilities",
"mcp__t3-code__list_scheduled_tasks",
+ "mcp__t3-code__list_pipelines",
+ "mcp__t3-code__pipeline_status",
"mcp__t3-code__t3_thread_list",
"mcp__t3-code__t3_thread_wait",
"mcp__t3-code__t3_worktree_status",
@@ -2567,6 +2574,8 @@ export interface ClaudeRuntimeQueryPolicy {
readonly allowedTools?: ReadonlyArray;
readonly allowDangerouslySkipPermissions?: true;
readonly installPermissionCallback: boolean;
+ /** A live query keeps the directories and prompt it opened with, so this is part of its key. */
+ readonly workspace?: ProviderAdapter.ProviderAdapterV2RuntimeWorkspace;
}
interface ClaudeBypassAvailability {
@@ -2606,6 +2615,9 @@ export function claudeRuntimeQueryPolicyForRuntimePolicy(
runtimePolicy.runtimeMode === "auto-accept-edits"
: runtimePolicy.approvalPolicy !== "never");
+ const workspace =
+ runtimePolicy.workspace === undefined ? {} : { workspace: runtimePolicy.workspace };
+
if (permissionMode === "plan") {
return {
permissionMode,
@@ -2613,6 +2625,7 @@ export function claudeRuntimeQueryPolicyForRuntimePolicy(
...(allowedTools === undefined ? {} : { allowedTools }),
// Claude routes Plan-mode writes to the callback even in Auto or Full access.
installPermissionCallback: true,
+ ...workspace,
};
}
@@ -2622,6 +2635,7 @@ export function claudeRuntimeQueryPolicyForRuntimePolicy(
...(allowedTools === undefined ? {} : { allowedTools }),
...(permissionMode === "bypassPermissions" ? { allowDangerouslySkipPermissions: true } : {}),
installPermissionCallback,
+ ...workspace,
};
}
@@ -2721,6 +2735,7 @@ function claudeRuntimeQueryPolicyKey(policy: ClaudeRuntimeQueryPolicy): string {
allowedTools: policy.allowedTools,
allowDangerouslySkipPermissions: policy.allowDangerouslySkipPermissions,
installPermissionCallback: policy.installPermissionCallback,
+ workspace: policy.workspace,
});
}
@@ -10356,6 +10371,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
resume: shouldResume,
...(resumeSessionAt === undefined ? {} : { resumeSessionAt }),
cwd: turnInput.runtimePolicy.cwd,
+ ...(queryPolicy.workspace === undefined ? {} : { workspace: queryPolicy.workspace }),
attachmentsDir,
settings: adapterOptions.settings,
...(launchArgSettings === undefined
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
index 2d14fa9518de6..459c250335313 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
@@ -252,6 +252,59 @@ describe("CodexAdapterV2 runtime policy", () => {
assert.isDefined(withT3.additionalContext?.["t3_code_runtime"]);
}),
);
+
+ it.effect("lets a multi-repo turn write to the thread's other repos, never references", () =>
+ Effect.gen(function* () {
+ const workspace = {
+ repositories: [
+ { name: "web", path: "/work/web" },
+ { name: "api", path: "/work/api" },
+ ],
+ referenceFolders: [{ name: "design", path: "/notes/design" }],
+ extraRoots: ["/work/api"],
+ relativePathsDiffer: false,
+ };
+ const build = (
+ runtimeMode: "approval-required" | "auto-accept-edits" | "full-access",
+ sandboxPolicy?: unknown,
+ ) =>
+ CodexAdapterV2.buildCodexTurnStartParams({
+ nativeThreadId: "native-multi-repo",
+ codexInput: [{ type: "text", text: "test" }],
+ runtimePolicy: {
+ runtimeMode,
+ interactionMode: "default",
+ cwd: "/work/web",
+ workspace,
+ ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }),
+ },
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ });
+
+ const edits = yield* build("auto-accept-edits");
+ assert.deepEqual(edits.sandboxPolicy, {
+ type: "workspaceWrite",
+ writableRoots: ["/work/api"],
+ });
+ // The repo list reaches the model even without T3's MCP tools.
+ assert.include(
+ edits.additionalContext?.["t3_code_workspace"]?.value,
+ "- design (read-only reference): /notes/design",
+ );
+ const explicit = yield* build("auto-accept-edits", {
+ type: "workspaceWrite",
+ writableRoots: ["/tmp/scratch", "/work/api"],
+ networkAccess: true,
+ });
+ assert.deepEqual(explicit.sandboxPolicy, {
+ type: "workspaceWrite",
+ writableRoots: ["/tmp/scratch", "/work/api"],
+ networkAccess: true,
+ });
+ assert.deepEqual((yield* build("approval-required")).sandboxPolicy, { type: "readOnly" });
+ assert.deepEqual((yield* build("full-access")).sandboxPolicy, { type: "dangerFullAccess" });
+ }),
+ );
});
describe("CodexAdapterV2 native protocol logging", () => {
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
index f81a3809b35fe..936a62c75a959 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
@@ -105,6 +105,7 @@ import * as PortScanner from "../../preview/PortScanner.ts";
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
import { ServerConfig } from "../../config.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
+import { buildWorkspaceInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import { buildCodexAdditionalContext } from "../../provider/CodexDeveloperInstructions.ts";
import {
describeMcpElicitation,
@@ -755,10 +756,20 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur
input.runtimePolicy.approvalPolicy === undefined
? runtimeModeDefaults.approvalPolicy
: yield* decodeTurnApprovalPolicy(input.runtimePolicy.approvalPolicy);
- const sandboxPolicy =
+ const requestedSandboxPolicy =
input.runtimePolicy.sandboxPolicy === undefined
? runtimeModeDefaults.sandboxPolicy
: yield* decodeTurnSandboxPolicy(input.runtimePolicy.sandboxPolicy);
+ const extraRoots = input.runtimePolicy.workspace?.extraRoots ?? [];
+ const sandboxPolicy =
+ requestedSandboxPolicy?.type === "workspaceWrite" && extraRoots.length > 0
+ ? {
+ ...requestedSandboxPolicy,
+ writableRoots: [
+ ...new Set([...(requestedSandboxPolicy.writableRoots ?? []), ...extraRoots]),
+ ],
+ }
+ : requestedSandboxPolicy;
const selectedEffort =
getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort") ??
codexDefaultReasoningEffortOverride(input.modelSelection.model);
@@ -785,10 +796,17 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur
},
)
: undefined;
+ // Its own entry: Codex truncates entries over 4,000 bytes, and repo paths matter without MCP too.
+ const workspaceInstructions = buildWorkspaceInstructions(input.runtimePolicy);
+ const workspaceContext = workspaceInstructions
+ ? { t3_code_workspace: { kind: "application" as const, value: workspaceInstructions } }
+ : {};
const additionalContext =
- t3Context === undefined && Object.keys(appContext).length === 0
+ t3Context === undefined &&
+ Object.keys(appContext).length === 0 &&
+ workspaceInstructions === ""
? undefined
- : { ...t3Context, ...appContext };
+ : { ...t3Context, ...workspaceContext, ...appContext };
return yield* decodeCodexTurnStartParamsWithCollaborationMode({
threadId: input.nativeThreadId,
input: input.codexInput,
diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
index a6038be86cfa2..d3edae74b4536 100644
--- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
@@ -40,6 +40,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as RuntimePolicy from "../RuntimePolicy.ts";
import * as ServerSettings from "../../serverSettings.ts";
+import { WorkspaceRepositories } from "../../workspace/WorkspaceRepositories.ts";
import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
import { acpCompletedTurnShouldTerminalizeTool } from "@t3tools/provider-acp/server/adapter";
import {
@@ -339,10 +340,11 @@ describe("Grok launch permission mode", () => {
RuntimePolicy.layerFromProjectStore.pipe(
Layer.provide(ServerSettings.layerTest()),
Layer.provide(
- Layer.mock(ProjectStore.ProjectStoreV2)({
- get: () => Effect.die("the thread has a worktree"),
- }),
+ Layer.mock(ProjectStore.ProjectStoreV2)({ get: () => Effect.succeedNone }),
),
+ // A project without tracked folders never looks up repositories.
+ Layer.provide(Layer.mock(WorkspaceRepositories)({})),
+ Layer.provide(Path.layer),
Layer.provide(
Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
getInstance: () =>
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
index bb52bb92daea3..9c56ce36ce1c8 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
@@ -2079,6 +2079,46 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
assert.equal((yield* Fiber.join(created)).nativeThreadRef?.nativeId, SESSION);
}).pipe(Effect.scoped),
);
+ it.effect("opens the thread's other repos like the workspace, never its references", () =>
+ Effect.gen(function* () {
+ const workspaceRules = [
+ { action: "shell", resource: "*", effect: "ask" },
+ { action: "edit", resource: "*", effect: "ask" },
+ { action: "external_directory", resource: "*", effect: "ask" },
+ { action: "external_directory", resource: "/work/api/*", effect: "allow" },
+ ...buildPaths,
+ ...mcpRules,
+ ];
+ const runtime = yield* openCode2ReplayRuntime([
+ ...opening,
+ out("agent.list", ""),
+ reply("agent.list", agentList),
+ out("session.create", {
+ location: { directory: WORK },
+ model: { providerID: "opencode", id: "big-pickle" },
+ permissions: workspaceRules,
+ }),
+ replyData("session.create", sessionInfo({ permissions: workspaceRules })),
+ ]);
+ const created = yield* runtime.ensureThread({
+ threadId,
+ modelSelection: bigPickle,
+ runtimePolicy: {
+ ...policy("approval-required"),
+ workspace: {
+ repositories: [
+ { name: "opencode2", path: WORK },
+ { name: "api", path: "/work/api" },
+ ],
+ referenceFolders: [{ name: "design", path: "/notes/design" }],
+ extraRoots: ["/work/api"],
+ relativePathsDiffer: false,
+ },
+ },
+ });
+ assert.equal(created.nativeThreadRef?.nativeId, SESSION);
+ }).pipe(Effect.scoped),
+ );
const reconnected = (
active: Record,
ended?: "succeeded",
diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts
index 17fe7224773d5..f35440582a499 100644
--- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts
+++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts
@@ -1,4 +1,5 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
+import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import {
CheckpointId,
@@ -15,21 +16,29 @@ import {
ProviderThreadId,
RunId,
ThreadId,
+ TurnItemId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as SqlClient from "effect/sql/SqlClient";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
+import * as CheckpointDiffQuery from "../checkpointing/CheckpointDiffQuery.ts";
import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
+import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
+import * as VcsProcess from "../vcs/VcsProcess.ts";
+import * as ThreadManagement from "./ThreadManagementService.ts";
import { VcsProcessTimeoutError } from "@t3tools/contracts";
import * as CheckpointService from "./CheckpointService.ts";
import * as CheckpointCaptureService from "./CheckpointCaptureService.ts";
import * as EventSink from "./EventSink.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProjectionStore from "./ProjectionStore.ts";
+import * as ProjectStore from "./ProjectStore.ts";
const layerProjectionStoreTest = Layer.mergeAll(
ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
@@ -269,12 +278,15 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
Layer.provide(
Layer.mergeAll(
IdAllocator.layer,
+ NodeServices.layer,
+ Layer.mock(ProjectStore.ProjectStoreV2)({}),
refLookupFails
? CheckpointService.layer.pipe(
Layer.provide(
Layer.mergeAll(
IdAllocator.layer,
NodeCrypto.layer,
+ NodeServices.layer,
Layer.mock(CheckpointStore.CheckpointStore)({
listAuthoredPaths: () => Effect.succeed(null),
isGitRepository: () => Effect.succeed(true),
@@ -448,6 +460,8 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
Layer.provide(
Layer.mergeAll(
IdAllocator.layer,
+ NodeServices.layer,
+ Layer.mock(ProjectStore.ProjectStoreV2)({}),
Layer.mock(CheckpointService.CheckpointServiceV2)({
materializeBaselineCheckpoint: () => Effect.die("a discarded run has no baseline"),
capture: () => Effect.die("a discarded run must not be captured"),
@@ -672,6 +686,8 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
Layer.provide(
Layer.mergeAll(
IdAllocator.layer,
+ NodeServices.layer,
+ Layer.mock(ProjectStore.ProjectStoreV2)({}),
Layer.mock(CheckpointService.CheckpointServiceV2)({
materializeBaselineCheckpoint: () =>
Effect.die("baseline materialization must be skipped when ordinal 0 is ready"),
@@ -864,11 +880,14 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
Layer.provide(
Layer.mergeAll(
IdAllocator.layer,
+ NodeServices.layer,
+ Layer.mock(ProjectStore.ProjectStoreV2)({}),
CheckpointService.layer.pipe(
Layer.provide(
Layer.mergeAll(
IdAllocator.layer,
NodeCrypto.layer,
+ NodeServices.layer,
Layer.mock(CheckpointStore.CheckpointStore)({
isGitRepository: gitUnavailable,
captureCheckpoint: gitUnavailable,
@@ -906,3 +925,505 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
}),
);
});
+
+const layerVcsProcessTest = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
+const layerCheckpointServiceTest = CheckpointService.layer.pipe(
+ Layer.provideMerge(
+ Layer.mergeAll(
+ CheckpointStore.layer.pipe(
+ Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcessTest))),
+ Layer.provide(NodeServices.layer),
+ ),
+ IdAllocator.layer,
+ NodeCrypto.layer,
+ NodeServices.layer,
+ ),
+ ),
+);
+const layerMultiRepoTest = Layer.mergeAll(
+ layerProjectionStoreTest,
+ layerCheckpointServiceTest,
+ layerVcsProcessTest,
+ IdAllocator.layer,
+ NodeCrypto.layer,
+ NodeServices.layer,
+);
+
+/**
+ * A run in a plain home folder that tracks two child repos (`api`, `web`), with an untracked
+ * sibling repo beside home. Baselines are taken the way run start takes them.
+ */
+const seedPlainHomeRun = Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const vcsProcess = yield* VcsProcess.VcsProcess;
+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
+ const checkpoints = yield* CheckpointService.CheckpointServiceV2;
+ const ids = yield* IdAllocator.IdAllocatorV2;
+ const now = yield* DateTime.now;
+ const parent = yield* fileSystem.realPath(
+ yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-capture-multi-repo-" }),
+ );
+ const home = path.join(parent, "home");
+ const git = (cwd: string, args: ReadonlyArray) =>
+ vcsProcess
+ .run({ operation: "CheckpointCaptureService.test.git", command: "git", cwd, args })
+ .pipe(Effect.map((result) => result.stdout.trim()));
+ for (const repository of [
+ path.join(home, "api"),
+ path.join(home, "web"),
+ path.join(parent, "other"),
+ ]) {
+ yield* fileSystem.makeDirectory(repository, { recursive: true });
+ yield* git(repository, ["init", "--quiet"]);
+ yield* git(repository, ["config", "user.email", "test@test.com"]);
+ yield* git(repository, ["config", "user.name", "Test"]);
+ yield* fileSystem.writeFileString(path.join(repository, "README.md"), "# initial\n");
+ yield* git(repository, ["add", "."]);
+ yield* git(repository, ["commit", "--quiet", "-m", "initial"]);
+ }
+ yield* fileSystem.writeFileString(path.join(home, "notes.md"), "plain home\n");
+
+ const threadId = ThreadId.make("thread:capture-multi-repo");
+ const multiRepoProjectId = ProjectId.make("project:capture-multi-repo");
+ const multiRepoRunId = RunId.make("run:capture-multi-repo");
+ const nodeId = NodeId.make("node:capture-multi-repo");
+ const multiRepoProviderThreadId = ProviderThreadId.make("provider-thread:capture-multi-repo");
+ const run: OrchestrationV2Run = {
+ id: multiRepoRunId,
+ threadId,
+ ordinal: 1,
+ providerInstanceId,
+ modelSelection,
+ providerThreadId: multiRepoProviderThreadId,
+ userMessageId: MessageId.make("message:capture-multi-repo"),
+ rootNodeId: nodeId,
+ activeAttemptId: null,
+ status: "waiting",
+ requestedAt: now,
+ startedAt: now,
+ completedAt: null,
+ checkpointId: null,
+ contextHandoffId: null,
+ };
+ const rootScope = yield* checkpoints.prepareRootRunScope({
+ threadId,
+ runId: multiRepoRunId,
+ rootNodeId: nodeId,
+ providerThreadId: multiRepoProviderThreadId,
+ cwd: home,
+ createdAt: now,
+ });
+ const repositoryScopes = yield* checkpoints.prepareRepositoryScopes({
+ rootScope,
+ repositories: ["api", "web"].map((name) => ({
+ name,
+ cwd: path.join(home, name),
+ originalPath: path.join(home, name),
+ })),
+ });
+ let sequence = 0;
+ const apply = (event: Omit) =>
+ projectionStore.apply({
+ ...event,
+ id: EventId.make(`event:capture-multi-repo:${sequence++}`),
+ threadId,
+ occurredAt: now,
+ } as OrchestrationV2DomainEvent);
+ yield* apply({
+ type: "thread.created",
+ payload: {
+ createdBy: "user",
+ creationSource: "web",
+ id: threadId,
+ projectId: multiRepoProjectId,
+ title: "Multi-repo capture",
+ providerInstanceId,
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ activeProviderThreadId: null,
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ },
+ });
+ yield* apply({ type: "run.updated", runId: multiRepoRunId, payload: run });
+ const rootNode = {
+ id: nodeId,
+ threadId,
+ runId: multiRepoRunId,
+ parentNodeId: null,
+ rootNodeId: nodeId,
+ kind: "root_turn" as const,
+ status: "waiting" as const,
+ countsForRun: true,
+ providerThreadId: multiRepoProviderThreadId,
+ providerTurnId: null,
+ nativeItemRef: null,
+ runtimeRequestId: null,
+ checkpointScopeId: rootScope.id,
+ startedAt: now,
+ completedAt: null,
+ };
+ yield* apply({ type: "node.updated", runId: multiRepoRunId, payload: rootNode });
+ yield* apply({
+ type: "provider-thread.updated",
+ driver,
+ payload: {
+ id: multiRepoProviderThreadId,
+ driver,
+ providerInstanceId,
+ providerSessionId: null,
+ appThreadId: threadId,
+ ownerNodeId: nodeId,
+ nativeThreadRef: null,
+ nativeConversationHeadRef: null,
+ status: "idle",
+ firstRunOrdinal: 1,
+ lastRunOrdinal: 1,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ },
+ });
+ for (const scope of [rootScope, ...repositoryScopes]) {
+ yield* apply({ type: "checkpoint-scope.created", runId: multiRepoRunId, payload: scope });
+ yield* checkpoints.captureBaseline({
+ scope,
+ ordinalWithinScope: 0,
+ ...(scope === rootScope ? { repositoryScopes } : {}),
+ });
+ }
+
+ // The turn edits both repos, an untracked sibling repo and a plain file in home.
+ yield* fileSystem.writeFileString(path.join(home, "api", "README.md"), "# api edit\n");
+ yield* fileSystem.makeDirectory(path.join(home, "web", "src"));
+ yield* fileSystem.writeFileString(path.join(home, "web", "src", "app.ts"), "export {};\n");
+ yield* fileSystem.writeFileString(path.join(parent, "other", "x.ts"), "export {};\n");
+ yield* fileSystem.writeFileString(path.join(home, "notes.md"), "plain home edit\n");
+ for (const [ordinal, fileName] of [
+ path.join(home, "api", "README.md"),
+ "web/src/app.ts",
+ path.join(parent, "other", "x.ts"),
+ "notes.md",
+ ].entries()) {
+ yield* apply({
+ type: "turn-item.updated",
+ runId: multiRepoRunId,
+ payload: {
+ id: TurnItemId.make(`turn-item:capture-multi-repo:${ordinal}`),
+ threadId,
+ runId: multiRepoRunId,
+ nodeId,
+ providerThreadId: multiRepoProviderThreadId,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: 100 + ordinal,
+ status: "completed",
+ title: null,
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "file_change",
+ fileName,
+ },
+ });
+ }
+
+ const committed: Array> = [];
+ const failNextCommit = yield* Ref.make(false);
+ const captureLayer = CheckpointCaptureService.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.succeed(CheckpointService.CheckpointServiceV2, checkpoints),
+ Layer.succeed(IdAllocator.IdAllocatorV2, ids),
+ Layer.succeed(ProjectionStore.ProjectionStoreV2, projectionStore),
+ NodeServices.layer,
+ Layer.mock(ProjectStore.ProjectStoreV2)({
+ get: () =>
+ Effect.succeedSome({
+ workspaceRoot: home,
+ trackedFolders: ["api", "web"].map((name) => ({ name, path: path.join(home, name) })),
+ } as never),
+ }),
+ Layer.mock(EventSink.EventSinkV2)({
+ commitCommand: (input) =>
+ Effect.gen(function* () {
+ if (yield* Ref.getAndSet(failNextCommit, false)) {
+ return yield* Effect.die("commit failed");
+ }
+ for (const event of input.events)
+ yield* projectionStore.apply(event).pipe(Effect.orDie);
+ committed.push(input.events);
+ return { committed: true } as never;
+ }),
+ }),
+ ),
+ ),
+ );
+ const capture = CheckpointCaptureService.CheckpointCaptureServiceV2.pipe(
+ Effect.flatMap((service) =>
+ service.execute({ threadId, runId: multiRepoRunId, scopeId: rootScope.id }),
+ ),
+ Effect.provide(captureLayer),
+ );
+ /** Starts run 2 the way run start does, and returns its capture. */
+ const startNextRun = Effect.gen(function* () {
+ const nextRunId = RunId.make("run:capture-multi-repo:2");
+ const nextNodeId = NodeId.make("node:capture-multi-repo:2");
+ yield* apply({
+ type: "run.updated",
+ runId: nextRunId,
+ payload: {
+ ...run,
+ id: nextRunId,
+ ordinal: 2,
+ userMessageId: MessageId.make("message:capture-multi-repo:2"),
+ rootNodeId: nextNodeId,
+ },
+ });
+ yield* apply({
+ type: "node.updated",
+ runId: nextRunId,
+ payload: { ...rootNode, id: nextNodeId, runId: nextRunId, rootNodeId: nextNodeId },
+ });
+ for (const scope of repositoryScopes) {
+ yield* apply({
+ type: "checkpoint-scope.created",
+ runId: nextRunId,
+ payload: { ...scope, runId: nextRunId },
+ });
+ }
+ for (const scope of [rootScope, ...repositoryScopes]) {
+ yield* checkpoints.captureBaseline({
+ scope,
+ ordinalWithinScope: 1,
+ ...(scope === rootScope ? { repositoryScopes } : {}),
+ });
+ }
+ yield* fileSystem.writeFileString(path.join(home, "api", "README.md"), "# api second edit\n");
+ return yield* CheckpointCaptureService.CheckpointCaptureServiceV2.pipe(
+ Effect.flatMap((service) =>
+ service.execute({ threadId, runId: nextRunId, scopeId: rootScope.id }),
+ ),
+ Effect.provide(captureLayer),
+ );
+ });
+ return {
+ parent,
+ home,
+ threadId,
+ rootScope,
+ repositoryScopes,
+ committed,
+ failNextCommit,
+ capture,
+ startNextRun,
+ git,
+ };
+});
+
+it.layer(layerMultiRepoTest)("CheckpointCaptureServiceV2 multi-repo", (it) => {
+ it.effect("keeps each turn's record in a plain home folder when the next run captures", () =>
+ Effect.gen(function* () {
+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
+ const run = yield* seedPlainHomeRun;
+ yield* run.capture;
+ yield* run.startNextRun;
+
+ // A plain home has no Git, so no baseline record may replace turn 1's root checkpoint.
+ const { checkpoints } = yield* projectionStore.getCheckpointContext(run.threadId);
+ const firstTurn = checkpoints.find(
+ (checkpoint) =>
+ checkpoint.scopeId === run.rootScope.id && checkpoint.ordinalWithinScope === 1,
+ );
+ assert.deepEqual(
+ { runId: firstTurn?.runId, appRunOrdinal: firstTurn?.appRunOrdinal },
+ { runId: RunId.make("run:capture-multi-repo"), appRunOrdinal: 1 },
+ );
+ const secondRun = (run.committed.at(-1) ?? []).flatMap((event) =>
+ event.type === "checkpoint.captured" ? [event.payload] : [],
+ );
+ assert.deepEqual(
+ secondRun
+ .filter((checkpoint) => checkpoint.scopeId === run.rootScope.id)
+ .map((checkpoint) => checkpoint.ordinalWithinScope),
+ [2],
+ );
+ assert.deepEqual(
+ secondRun
+ .find(
+ (checkpoint) =>
+ checkpoint.scopeId === run.repositoryScopes[0]?.id &&
+ checkpoint.ordinalWithinScope === 2,
+ )
+ ?.files.map((file) => file.path),
+ ["README.md"],
+ );
+ }),
+ );
+
+ it.effect("captures each tracked repo of a plain home folder and diffs them per repo", () =>
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
+ const run = yield* seedPlainHomeRun;
+ yield* run.capture;
+
+ const checkpoints = run.committed
+ .flat()
+ .flatMap((event) => (event.type === "checkpoint.captured" ? [event.payload] : []));
+ const root = checkpoints.find(
+ (checkpoint) => checkpoint.scopeId === run.rootScope.id && checkpoint.runId !== null,
+ );
+ assert.equal(root?.status, "missing");
+ assert.equal(root?.appRunOrdinal, 1);
+ assert.deepEqual(root?.outsideEdits, [
+ {
+ root: path.join(run.parent, "other"),
+ name: "other",
+ tracked: false,
+ files: ["x.ts"],
+ fileCount: 1,
+ },
+ ]);
+ assert.deepEqual(
+ run.repositoryScopes.map((scope) => {
+ const captured = checkpoints.filter((checkpoint) => checkpoint.scopeId === scope.id);
+ return {
+ label: scope.label,
+ records: captured.map(
+ ({ ordinalWithinScope, appRunOrdinal, status, runId, files }) => ({
+ ordinalWithinScope,
+ appRunOrdinal,
+ status,
+ hasRun: runId !== null,
+ files: files.map((file) => file.path),
+ }),
+ ),
+ };
+ }),
+ [
+ {
+ label: "api",
+ records: [
+ {
+ ordinalWithinScope: 0,
+ appRunOrdinal: null,
+ status: "ready",
+ hasRun: false,
+ files: [],
+ },
+ {
+ ordinalWithinScope: 1,
+ appRunOrdinal: null,
+ status: "ready",
+ hasRun: true,
+ files: ["README.md"],
+ },
+ ],
+ },
+ {
+ label: "web",
+ records: [
+ {
+ ordinalWithinScope: 0,
+ appRunOrdinal: null,
+ status: "ready",
+ hasRun: false,
+ files: [],
+ },
+ {
+ ordinalWithinScope: 1,
+ appRunOrdinal: null,
+ status: "ready",
+ hasRun: true,
+ files: ["src/app.ts"],
+ },
+ ],
+ },
+ ],
+ );
+
+ const query = yield* CheckpointDiffQuery.make.pipe(
+ Effect.provide(
+ Layer.mock(ThreadManagement.ThreadManagementService)({
+ getCheckpointContext: (threadId) =>
+ projectionStore.getCheckpointContext(threadId).pipe(Effect.orDie),
+ }),
+ ),
+ );
+ const turn = yield* query.getTurnDiff({
+ threadId: run.threadId,
+ fromTurnCount: 0,
+ toTurnCount: 1,
+ });
+ assert.equal(turn.diff, "");
+ assert.deepEqual(
+ turn.repositories?.map(({ name, repositoryPath, relativePath, diff }) => ({
+ name,
+ repositoryPath,
+ relativePath,
+ files: [...diff.matchAll(/^\+\+\+ b\/(.+)$/gm)].map((match) => match[1]),
+ })),
+ [
+ {
+ name: "api",
+ repositoryPath: path.join(run.home, "api"),
+ relativePath: "api",
+ files: ["README.md"],
+ },
+ {
+ name: "web",
+ repositoryPath: path.join(run.home, "web"),
+ relativePath: "web",
+ files: ["src/app.ts"],
+ },
+ ],
+ );
+ const fullThread = yield* query.getFullThreadDiff({ threadId: run.threadId, toTurnCount: 1 });
+ assert.deepEqual(fullThread.repositories, turn.repositories);
+ }).pipe(Effect.scoped),
+ );
+
+ it.effect("keeps refs a failed capture already wrote and fills only the missing ones", () =>
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const run = yield* seedPlainHomeRun;
+ const [api, web] = run.repositoryScopes;
+ if (api === undefined || web === undefined) return yield* Effect.die("missing scopes");
+ const ref = (scopeId: CheckpointScopeId) =>
+ CheckpointService.checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 1 });
+
+ yield* Ref.set(run.failNextCommit, true);
+ yield* run.capture.pipe(Effect.exit);
+ assert.deepEqual(run.committed, []);
+ const apiCommit = yield* run.git(api.cwd, ["rev-parse", yield* ref(api.id)]);
+ // The retry finds api captured and web not, and the workspace has moved on since.
+ yield* run.git(web.cwd, ["update-ref", "-d", yield* ref(web.id)]);
+ yield* fileSystem.writeFileString(path.join(api.cwd, "README.md"), "# after the run\n");
+ yield* fileSystem.writeFileString(path.join(web.cwd, "later.ts"), "export {};\n");
+
+ yield* run.capture;
+ assert.equal(yield* run.git(api.cwd, ["rev-parse", yield* ref(api.id)]), apiCommit);
+ assert.equal(yield* run.git(api.cwd, ["show", `${apiCommit}:README.md`]), "# api edit");
+ assert.deepEqual(
+ (yield* run.git(web.cwd, ["ls-tree", "-r", "--name-only", yield* ref(web.id)])).split("\n"),
+ ["README.md", "later.ts", "src/app.ts"],
+ );
+ assert.lengthOf(run.committed, 1);
+ }).pipe(Effect.scoped),
+ );
+});
diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts
index 9d7d3cfd4ae2a..8c36487ebad4a 100644
--- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts
+++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts
@@ -2,23 +2,33 @@ import {
CheckpointScopeId,
CommandId,
type OrchestrationV2Checkpoint,
+ type OrchestrationV2CheckpointScope,
type OrchestrationV2ExecutionNode,
type OrchestrationV2ProviderThread,
type OrchestrationV2Run,
type OrchestrationV2TurnItem,
+ type ProjectId,
RunId,
ThreadId,
} from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
+import { collectOutsideEdits } from "../checkpointing/OutsideEdits.ts";
import * as CheckpointService from "./CheckpointService.ts";
import * as EventSink from "./EventSink.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProjectionStore from "./ProjectionStore.ts";
+import * as ProjectStore from "./ProjectStore.ts";
+
+const CAPTURE_CONCURRENCY = 4;
export class CheckpointCaptureExecutionError extends Schema.TaggedError()(
"CheckpointCaptureExecutionError",
@@ -52,6 +62,9 @@ export const layer: Layer.Layer<
| EventSink.EventSinkV2
| IdAllocator.IdAllocatorV2
| ProjectionStore.ProjectionStoreV2
+ | ProjectStore.ProjectStoreV2
+ | FileSystem.FileSystem
+ | Path.Path
> = Layer.effect(
CheckpointCaptureServiceV2,
Effect.gen(function* () {
@@ -59,14 +72,35 @@ export const layer: Layer.Layer<
const eventSink = yield* EventSink.EventSinkV2;
const ids = yield* IdAllocator.IdAllocatorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const projects = yield* ProjectStore.ProjectStoreV2;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+
+ // The home checkout counts too: a worktree thread can still edit it, and it cannot be tracked.
+ const projectFolderPaths = (projectId: ProjectId | undefined) =>
+ (projectId === undefined
+ ? Effect.succeedNone
+ : projects.get(projectId, { includeDeleted: true })
+ ).pipe(
+ Effect.map(
+ Option.match({
+ onNone: () => [],
+ onSome: (project) => [
+ project.workspaceRoot,
+ ...project.trackedFolders.map((folder) => folder.path),
+ ],
+ }),
+ ),
+ Effect.orElseSucceed((): ReadonlyArray => []),
+ );
const execute = Effect.fn("orchestrationV2.checkpointCapture.execute")(function* (input: {
readonly threadId: ThreadId;
readonly runId: RunId;
readonly scopeId: CheckpointScopeId;
}) {
- const { run, rootNode, scope, providerThread, readyCheckpointOrdinals, sideChat } =
- yield* projections.getCheckpointCaptureContext(input.threadId, input);
+ const context = yield* projections.getCheckpointCaptureContext(input.threadId, input);
+ const { run, rootNode, scope, providerThread, readyCheckpointOrdinals, sideChat } = context;
// Stopped runs remain terminal; their checkpoint is the next message's rollback point.
const stopped = run?.status === "interrupted" || run?.status === "cancelled";
@@ -101,35 +135,118 @@ export const layer: Layer.Layer<
const capturedAt = yield* DateTime.now;
const baselineOrdinalWithinScope = Math.max(0, run.ordinal - 1);
- const hasReadyCheckpoint = (ordinalWithinScope: number) =>
- readyCheckpointOrdinals.includes(ordinalWithinScope);
- const threadStartCheckpoint =
- baselineOrdinalWithinScope === 0 || hasReadyCheckpoint(0)
+ const repositoryScopes = context.repositoryScopes;
+ // Each scope is checked on its own, so a retry fills only the refs still missing.
+ const captureScope = Effect.fnUntraced(function* (target: {
+ readonly scope: OrchestrationV2CheckpointScope;
+ readonly readyOrdinals: ReadonlySet;
+ readonly appRunOrdinal: number | null;
+ }) {
+ const isRoot = target.scope.id === scope.id;
+ const threadStartCheckpoint =
+ !isRoot || baselineOrdinalWithinScope === 0 || target.readyOrdinals.has(0)
+ ? null
+ : yield* checkpoints.materializeBaselineCheckpoint({
+ scope: target.scope,
+ ordinalWithinScope: 0,
+ forceMissing: sideChat,
+ });
+ const baselineCheckpoint = target.readyOrdinals.has(baselineOrdinalWithinScope)
? null
: yield* checkpoints.materializeBaselineCheckpoint({
- scope,
- ordinalWithinScope: 0,
+ scope: target.scope,
+ ordinalWithinScope: baselineOrdinalWithinScope,
forceMissing: sideChat,
});
- const baselineCheckpoint = hasReadyCheckpoint(baselineOrdinalWithinScope)
- ? null
- : yield* checkpoints.materializeBaselineCheckpoint({
- scope,
- ordinalWithinScope: baselineOrdinalWithinScope,
- forceMissing: sideChat,
- });
- const checkpoint = yield* checkpoints.capture({
- scope,
- runId: run.id,
- nodeId: rootNode.id,
- ordinalWithinScope: run.ordinal,
- appRunOrdinal: run.ordinal,
- capturedAt,
- forceMissing: sideChat,
+ const checkpoint = yield* checkpoints.capture({
+ scope: target.scope,
+ runId: run.id,
+ nodeId: rootNode.id,
+ ordinalWithinScope: run.ordinal,
+ appRunOrdinal: target.appRunOrdinal,
+ capturedAt,
+ forceMissing: sideChat,
+ ...(isRoot && repositoryScopes.length > 0 ? { repositoryScopes } : {}),
+ });
+ return {
+ baselines: [threadStartCheckpoint, baselineCheckpoint].filter(
+ (baseline): baseline is OrchestrationV2Checkpoint => baseline !== null,
+ ),
+ checkpoint,
+ };
});
+ const [rootCapture, repositoryCaptures] = yield* Effect.all(
+ [
+ captureScope({
+ scope,
+ readyOrdinals: new Set(readyCheckpointOrdinals),
+ appRunOrdinal: run.ordinal,
+ }),
+ Effect.forEach(
+ repositoryScopes,
+ (repositoryScope) =>
+ captureScope({
+ scope: repositoryScope,
+ readyOrdinals: new Set(
+ context.repositoryReadyOrdinals
+ .filter((ready) => ready.scopeId === repositoryScope.id)
+ .map((ready) => ready.ordinal),
+ ),
+ appRunOrdinal: null,
+ }),
+ { concurrency: CAPTURE_CONCURRENCY - 1 },
+ ),
+ ],
+ { concurrency: 2 },
+ );
+ const outsideEdits =
+ context.fileChanges.length === 0
+ ? []
+ : yield* collectOutsideEdits({
+ paths: context.fileChanges.flatMap((change) => [
+ change.fileName,
+ ...change.changes.flatMap((detail) =>
+ detail.oldPath === undefined ? [detail.path] : [detail.path, detail.oldPath],
+ ),
+ ]),
+ cwd: context.providerSessionCwd ?? scope.cwd,
+ homeCwd: scope.cwd,
+ coveredCwds: [
+ ...(rootCapture.checkpoint.status === "missing" ? [] : [scope.cwd]),
+ ...repositoryScopes.map((repositoryScope) => repositoryScope.cwd),
+ ],
+ projectFolderPaths: projectFolderPaths(context.projectId),
+ }).pipe(
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
+ Effect.provideService(Path.Path, path),
+ Effect.catchCauseIf(
+ (cause) => !Cause.hasInterruptsOnly(cause),
+ (cause) =>
+ Effect.logWarning("orchestration V2 outside edit scan failed", {
+ runId: run.id,
+ cause,
+ }).pipe(Effect.as([])),
+ ),
+ );
+ const checkpoint =
+ outsideEdits.length === 0
+ ? rootCapture.checkpoint
+ : { ...rootCapture.checkpoint, outsideEdits };
+ const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
+ const checkpointEvent = (payload: OrchestrationV2Checkpoint) =>
+ Effect.map(ids.allocate.event({ threadId: input.threadId, commandId }), (id) => ({
+ id,
+ type: "checkpoint.captured" as const,
+ threadId: input.threadId,
+ ...(payload.runId === null ? {} : { runId: payload.runId }),
+ nodeId: payload.nodeId,
+ driver: providerThread.driver,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: capturedAt,
+ payload,
+ }));
// Omit delegatedCompletion to preserve cohort writes made after capture loaded the run.
const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;
- const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
yield* eventSink.commitCommand({
commandId,
threadId: input.threadId,
@@ -137,45 +254,18 @@ export const layer: Layer.Layer<
acceptedAt: capturedAt,
effects: [],
events: [
- ...(threadStartCheckpoint === null
- ? []
- : [
- {
- id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
- type: "checkpoint.captured" as const,
- threadId: input.threadId,
- nodeId: threadStartCheckpoint.nodeId,
- driver: providerThread.driver,
- providerInstanceId: run.providerInstanceId,
- occurredAt: capturedAt,
- payload: threadStartCheckpoint,
- },
+ ...(yield* Effect.forEach(
+ [
+ // Root records last: clients that pick the latest ordinal-0 baseline get the thread's.
+ ...repositoryCaptures.flatMap((capture) => [
+ ...capture.baselines,
+ capture.checkpoint,
]),
- ...(baselineCheckpoint === null
- ? []
- : [
- {
- id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
- type: "checkpoint.captured" as const,
- threadId: input.threadId,
- nodeId: baselineCheckpoint.nodeId,
- driver: providerThread.driver,
- providerInstanceId: run.providerInstanceId,
- occurredAt: capturedAt,
- payload: baselineCheckpoint,
- },
- ]),
- {
- id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
- type: "checkpoint.captured",
- threadId: input.threadId,
- runId: run.id,
- nodeId: rootNode.id,
- driver: providerThread.driver,
- providerInstanceId: run.providerInstanceId,
- occurredAt: capturedAt,
- payload: checkpoint,
- },
+ ...rootCapture.baselines,
+ checkpoint,
+ ],
+ checkpointEvent,
+ )),
{
id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
type: "turn-item.updated",
diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
index 145de122f387a..5c770f82f4d12 100644
--- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
@@ -90,6 +90,8 @@ it.effect.each([
checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: null },
scope: { id: scopeId, cwd },
runsToRollback: [{ id: "later-run", ordinal: 1, status: "completed", rootNodeId: null }],
+ repositoryScopes: [],
+ repositoryCheckpoints: [],
} as unknown as ProjectionCheckpointRollbackContext;
const layerTest = CheckpointRollbackService.layer.pipe(
Layer.provide(
@@ -195,6 +197,8 @@ it.effect("lets rollback recreate a worktree storage cleanup removed", () =>
fileSystem,
path,
projections: {
+ getCheckpointContext: () =>
+ Effect.succeed({ runs: [], checkpointScopes: [], checkpoints: [] }),
getShellSnapshot: () => Effect.succeed({ threads: [], archivedThreads: [] }),
} as never,
projects: {} as never,
@@ -252,3 +256,106 @@ it.effect.each([
assert.equal(result, isolated);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
+
+it.effect.each([
+ { case: "isolated", isolated: true },
+ // The worktrees directory is reached through a symlink; task folder roots are stored unresolved.
+ { case: "symlinked-worktrees", isolated: true },
+ { case: "original-checkout", isolated: false },
+ { case: "outside-task-folder", isolated: false },
+ { case: "no-task-folder", isolated: false },
+ { case: "tracked-by-local-thread", isolated: false },
+] as const)("checks each repo of a task folder thread, case=$case", (scenario) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const parent = yield* fs.realPath(
+ yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-restore-repos-" }),
+ );
+ for (const created of ["task/home/api", "task/web", "elsewhere/web", "originals/web"]) {
+ yield* fs.makeDirectory(path.join(parent, "real", created), { recursive: true });
+ }
+ yield* fs.symlink(path.join(parent, "real"), path.join(parent, "linked"));
+ const base = path.join(parent, scenario.case === "symlinked-worktrees" ? "linked" : "real");
+ const folder = (...segments: ReadonlyArray) => path.join(base, ...segments);
+ const threadId = ThreadId.make("restore-repos-current");
+ const otherThreadId = ThreadId.make("restore-repos-local");
+ const otherProjectId = ProjectId.make("restore-repos-other-project");
+ const webCwd =
+ scenario.case === "original-checkout"
+ ? folder("originals", "web")
+ : scenario.case === "outside-task-folder"
+ ? folder("elsewhere", "web")
+ : folder("task", "web");
+ const repositoryScope = (name: string, cwd: string, repositoryPath: string) => ({
+ id: CheckpointScopeId.make(`restore-repos-${name}`),
+ runId: null,
+ kind: "repository" as const,
+ cwd,
+ label: name,
+ repositoryPath,
+ });
+ const isolated = yield* isCheckpointRestoreIsolated(
+ { id: threadId, worktreePath: folder("task", "home") },
+ { cwd: folder("task", "home") },
+ {
+ fileSystem: fs,
+ path,
+ projections: {
+ getCheckpointContext: (id: ThreadId) =>
+ Effect.succeed({
+ runs: [],
+ checkpoints: [],
+ checkpointScopes:
+ id === threadId
+ ? [
+ repositoryScope(
+ "api",
+ folder("task", "home", "api"),
+ folder("originals", "api"),
+ ),
+ repositoryScope("web", webCwd, folder("originals", "web")),
+ ]
+ : [],
+ }),
+ getShellSnapshot: () =>
+ Effect.succeed({
+ threads: [
+ {
+ id: otherThreadId,
+ projectId: otherProjectId,
+ worktreePath: null,
+ activeRunId: null,
+ lineage: {
+ parentThreadId: null,
+ relationshipToParent: null,
+ rootThreadId: otherThreadId,
+ },
+ deletedAt: null,
+ },
+ ],
+ archivedThreads: [],
+ }),
+ getThreadProviderContext: () => Effect.succeed({ providerSessions: [] }),
+ } as never,
+ projects: {
+ get: () =>
+ Effect.succeedSome({
+ workspaceRoot: folder("originals", "home"),
+ trackedFolders:
+ scenario.case === "tracked-by-local-thread"
+ ? [{ name: "web", path: folder("task", "web") }]
+ : [{ name: "api", path: folder("originals", "api") }],
+ }),
+ } as never,
+ taskFolders: {
+ findContaining: (candidate: string) =>
+ scenario.case === "no-task-folder" || !candidate.startsWith(folder("task"))
+ ? Effect.succeedNone
+ : Effect.succeedSome({ root: folder("task") } as never),
+ },
+ },
+ );
+ assert.equal(isolated, scenario.isolated);
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+);
diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts
index b7dc08018a896..52c15bf175def 100644
--- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
import type * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import type * as Path from "effect/Path";
+import type { TaskFolderStore } from "../workspace/TaskFolders.ts";
import type { ProjectionStoreV2 } from "./ProjectionStore.ts";
import type * as ProjectStore from "./ProjectStore.ts";
@@ -19,6 +20,8 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi
readonly projections: ProjectionStoreV2["Service"];
readonly projects: ProjectStore.ProjectStoreV2["Service"];
readonly path: Path.Path;
+ /** Without it, a repository scope only has to be a checkout other than its tracked folder. */
+ readonly taskFolders?: Pick;
},
) {
const { fileSystem, projections, projects, path } = dependencies;
@@ -30,77 +33,103 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi
);
};
const worktreePath = thread.worktreePath;
- let shared = worktreePath == null;
- if (!shared && worktreePath !== null) {
- // Storage cleanup may have removed the worktree; rollback recreates it.
- const resolve = (target: string) =>
- fileSystem.realPath(target).pipe(
+ if (worktreePath == null) return false;
+ // Storage cleanup may have removed the worktree; rollback recreates it.
+ const resolve = (target: string) =>
+ fileSystem.realPath(target).pipe(
+ Effect.catchIf(
+ (error) => error.reason._tag === "NotFound",
+ (_error) => Effect.succeed(path.resolve(target)),
+ ),
+ );
+ const cwd = yield* resolve(scope.cwd);
+ if (cwd !== (yield* resolve(worktreePath))) return false;
+
+ // Every repo of a multi-repo thread must be a checkout this thread's task folder owns.
+ const repositoryScopes = (yield* projections.getCheckpointContext(
+ thread.id,
+ )).checkpointScopes.filter((candidate) => candidate.kind === "repository");
+ const ownCwds = [cwd];
+ if (repositoryScopes.length > 0) {
+ const taskFolderRoot =
+ dependencies.taskFolders === undefined
+ ? undefined
+ : // Task folder roots are stored unresolved, so match the scope's path as recorded.
+ yield* dependencies.taskFolders.findContaining(path.resolve(scope.cwd)).pipe(
+ Effect.flatMap(
+ Option.match({
+ onNone: () => Effect.succeed(null),
+ onSome: (record) => resolve(record.root),
+ }),
+ ),
+ );
+ if (taskFolderRoot === null) return false;
+ for (const repositoryScope of repositoryScopes) {
+ const repositoryCwd = yield* resolve(repositoryScope.cwd);
+ if (
+ repositoryScope.repositoryPath != null &&
+ repositoryCwd === (yield* resolve(repositoryScope.repositoryPath))
+ ) {
+ return false;
+ }
+ if (taskFolderRoot !== undefined && !contains(taskFolderRoot, repositoryCwd)) return false;
+ ownCwds.push(repositoryCwd);
+ }
+ }
+
+ const overlaps = (otherCwd: string) =>
+ ownCwds.some((ownCwd) => contains(ownCwd, otherCwd) || contains(otherCwd, ownCwd));
+ const shell = yield* projections.getShellSnapshot();
+ const checkedPaths = new Set();
+ for (const otherThread of [...shell.threads, ...shell.archivedThreads]) {
+ if (otherThread.id === thread.id || otherThread.deletedAt !== null) continue;
+ // An idle side chat that only answered questions never touched the shared worktree.
+ if (
+ otherThread.lineage.sideChat === true &&
+ otherThread.activeRunId === null &&
+ otherThread.worktreePath === worktreePath
+ ) {
+ const { turnItems } = yield* projections.getThreadRecords(otherThread.id, ["turnItems"], {
+ turnItemTypes: ["command_execution", "file_change", "dynamic_tool"],
+ });
+ if (turnItems.length === 0) continue;
+ }
+ const other = yield* projections.getCheckpointContext(otherThread.id);
+ const providerContext = yield* projections.getThreadProviderContext(otherThread.id);
+ const paths = [
+ otherThread.worktreePath,
+ ...other.checkpointScopes.map((candidate) => candidate.cwd),
+ // Errored sessions can still stream. Shared sessions retain another thread's opening cwd;
+ // turn worktrees and project roots are already covered here.
+ ...providerContext.providerSessions
+ .filter(
+ (session) =>
+ session.status !== "stopped" &&
+ !session.capabilities.sessions.supportsMultipleProviderThreadsPerSession,
+ )
+ .map((session) => session.cwd),
+ ].filter((value): value is string => value !== null);
+ if (otherThread.worktreePath === null) {
+ const project = yield* projects.get(otherThread.projectId, { includeDeleted: true });
+ if (Option.isNone(project)) return false;
+ // A local thread reaches its tracked folders before its first turn records their scopes.
+ paths.push(
+ project.value.workspaceRoot,
+ ...project.value.trackedFolders.map((folder) => folder.path),
+ );
+ }
+ for (const candidate of paths) {
+ if (checkedPaths.has(candidate)) continue;
+ checkedPaths.add(candidate);
+ const otherCwd = yield* fileSystem.realPath(candidate).pipe(
Effect.catchIf(
(error) => error.reason._tag === "NotFound",
- (_error) => Effect.succeed(path.resolve(target)),
+ (_error) => Effect.succeed(null),
),
);
- const cwd = yield* resolve(scope.cwd);
- const worktreeCwd = yield* resolve(worktreePath);
- shared = cwd !== worktreeCwd;
- if (!shared) {
- const shell = yield* projections.getShellSnapshot();
- const checkedPaths = new Set();
- for (const otherThread of [...shell.threads, ...shell.archivedThreads]) {
- if (otherThread.id === thread.id || otherThread.deletedAt !== null) continue;
- // An idle side chat that only answered questions never touched the shared worktree.
- if (
- otherThread.lineage.sideChat === true &&
- otherThread.activeRunId === null &&
- otherThread.worktreePath === worktreePath
- ) {
- const { turnItems } = yield* projections.getThreadRecords(
- otherThread.id,
- ["turnItems"],
- {
- turnItemTypes: ["command_execution", "file_change", "dynamic_tool"],
- },
- );
- if (turnItems.length === 0) continue;
- }
- const other = yield* projections.getCheckpointContext(otherThread.id);
- const providerContext = yield* projections.getThreadProviderContext(otherThread.id);
- const paths = [
- otherThread.worktreePath,
- ...other.checkpointScopes.map((candidate) => candidate.cwd),
- // Errored sessions can still stream. Shared sessions retain another thread's opening cwd;
- // turn worktrees and project roots are already covered here.
- ...providerContext.providerSessions
- .filter(
- (session) =>
- session.status !== "stopped" &&
- !session.capabilities.sessions.supportsMultipleProviderThreadsPerSession,
- )
- .map((session) => session.cwd),
- ].filter((value): value is string => value !== null);
- if (otherThread.worktreePath === null) {
- const project = yield* projects.get(otherThread.projectId, { includeDeleted: true });
- if (Option.isNone(project)) return false;
- paths.push(project.value.workspaceRoot);
- }
- for (const candidate of paths) {
- if (checkedPaths.has(candidate)) continue;
- checkedPaths.add(candidate);
- const otherCwd = yield* fileSystem.realPath(candidate).pipe(
- Effect.catchIf(
- (error) => error.reason._tag === "NotFound",
- (_error) => Effect.succeed(null),
- ),
- );
- if (otherCwd !== null && (contains(cwd, otherCwd) || contains(otherCwd, cwd))) {
- shared = true;
- break;
- }
- }
- if (shared) break;
- }
+ if (otherCwd !== null && overlaps(otherCwd)) return false;
}
}
- return !shared;
+ return true;
},
);
diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
index c61f9bc175edc..effa92bf4a0e0 100644
--- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
@@ -1,3 +1,4 @@
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, vi } from "@effect/vitest";
import {
@@ -6,6 +7,8 @@ import {
EventId,
MessageId,
NodeId,
+ type OrchestrationV2Checkpoint,
+ type OrchestrationV2CheckpointScope,
type OrchestrationV2DomainEvent,
ProviderDriverKind,
ProviderTurnId,
@@ -28,7 +31,11 @@ import * as Path from "effect/Path";
import * as Option from "effect/Option";
import * as Layer from "effect/Layer";
+import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
+import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
+import * as VcsProcess from "../vcs/VcsProcess.ts";
+import { TaskFolderStore } from "../workspace/TaskFolders.ts";
import * as ServerConfig from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as GitWorkflow from "../git/GitWorkflowService.ts";
@@ -55,7 +62,14 @@ const layerCheckpointRollbackService = CheckpointRollbackService.layer.pipe(
NodeServices.layer,
Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
ServerSettings.layerTest(),
- Layer.mock(GitWorkflow.GitWorkflowService)({}),
+ Layer.mock(GitWorkflow.GitWorkflowService)({
+ isRepository: (cwd) =>
+ FileSystem.FileSystem.pipe(
+ Effect.flatMap((fileSystem) => fileSystem.exists(`${cwd}/.git`)),
+ Effect.provide(NodeServices.layer),
+ Effect.orDie,
+ ),
+ }),
Layer.mock(ProjectStore.ProjectStoreV2)({ get: () => Effect.succeed(unrelatedProject) }),
),
),
@@ -218,6 +232,8 @@ it.effect.each([
staleCheckpoints: [],
rootNodes: [],
providerTurns: [],
+ repositoryScopes: [],
+ repositoryCheckpoints: [],
} as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
const testLayer = CheckpointRollbackService.layer.pipe(
Layer.provide(
@@ -268,6 +284,8 @@ it.effect.each([
Layer.mock(ProjectionStore.ProjectionStoreV2)({
getThread: () => Effect.succeed(projection.thread),
getCheckpointRollbackContext: () => Effect.succeed(projection),
+ getCheckpointContext: () =>
+ Effect.succeed({ runs: [], checkpointScopes: [], checkpoints: [] }),
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 1,
@@ -731,3 +749,330 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe
);
},
);
+
+const layerVcsProcessTest = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
+const layerRealCheckpoints = CheckpointService.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ CheckpointStore.layer.pipe(
+ Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcessTest))),
+ Layer.provide(NodeServices.layer),
+ ),
+ IdAllocator.layer,
+ NodeCrypto.layer,
+ NodeServices.layer,
+ ),
+ ),
+);
+
+it.effect.each(["restores", "undo", "missing-ref", "plain-home", "git-home-missing"] as const)(
+ "rewinds every repo of a task folder, scenario=%s",
+ (scenario) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const vcsProcess = yield* VcsProcess.VcsProcess;
+ const checkpoints = yield* CheckpointService.CheckpointServiceV2;
+ const now = yield* DateTime.now;
+ const task = yield* fileSystem.realPath(
+ yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rollback-task-folder-" }),
+ );
+ const home = path.join(task, "home");
+ const git = (cwd: string, args: ReadonlyArray) =>
+ vcsProcess
+ .run({ operation: "CheckpointRollbackService.test.git", command: "git", cwd, args })
+ .pipe(Effect.map((result) => result.stdout.trim()));
+ const write = (cwd: string, text: string) =>
+ fileSystem.writeFileString(path.join(cwd, "a.txt"), `${text}\n`);
+ const read = (cwd: string) =>
+ fileSystem.readFileString(path.join(cwd, "a.txt")).pipe(Effect.map((text) => text.trim()));
+ for (const repository of [home, path.join(home, "api"), path.join(task, "web")]) {
+ yield* fileSystem.makeDirectory(repository, { recursive: true });
+ if (scenario === "plain-home" && repository === home) {
+ yield* write(repository, "initial");
+ continue;
+ }
+ yield* git(repository, ["init", "--quiet"]);
+ yield* git(repository, ["config", "user.email", "test@test.com"]);
+ yield* git(repository, ["config", "user.name", "Test"]);
+ yield* write(repository, "initial");
+ yield* git(repository, ["add", "a.txt"]);
+ yield* git(repository, ["commit", "--quiet", "-m", "initial"]);
+ }
+
+ const threadId = ThreadId.make("rollback-task-folder");
+ const providerThreadId = ProviderThreadId.make("rollback-task-folder-provider");
+ const providerInstanceId = ProviderInstanceId.make("codex");
+ const runId = (ordinal: number) => RunId.make(`rollback-task-folder-run-${ordinal}`);
+ const nodeId = NodeId.make("rollback-task-folder-node");
+ const rootScope = yield* checkpoints.prepareRootRunScope({
+ threadId,
+ runId: runId(2),
+ rootNodeId: nodeId,
+ providerThreadId,
+ cwd: home,
+ createdAt: now,
+ });
+ const [apiScope, webScope] = yield* checkpoints.prepareRepositoryScopes({
+ rootScope,
+ repositories: [
+ { name: "api", cwd: path.join(home, "api"), originalPath: "/tracked/api" },
+ { name: "web", cwd: path.join(task, "web"), originalPath: "/tracked/web" },
+ ],
+ });
+ if (apiScope === undefined || webScope === undefined) return yield* Effect.die("no scopes");
+ const repositoryScopes = [apiScope, webScope];
+ const records: Array = [];
+ const baseline = (scope: OrchestrationV2CheckpointScope, ordinalWithinScope: number) =>
+ Effect.gen(function* () {
+ yield* checkpoints.captureBaseline({
+ scope,
+ ordinalWithinScope,
+ ...(scope === rootScope ? { repositoryScopes } : {}),
+ });
+ const record = yield* checkpoints.materializeBaselineCheckpoint({
+ scope,
+ ordinalWithinScope,
+ });
+ if (record !== null) records.push(record);
+ });
+ const capture = (scope: OrchestrationV2CheckpointScope, ordinal: number) =>
+ checkpoints
+ .capture({
+ scope,
+ runId: runId(ordinal),
+ nodeId,
+ ordinalWithinScope: ordinal,
+ appRunOrdinal: scope === rootScope ? ordinal : null,
+ capturedAt: now,
+ ...(scope === rootScope ? { repositoryScopes } : {}),
+ })
+ .pipe(Effect.tap((checkpoint) => Effect.sync(() => records.push(checkpoint))));
+
+ // Run 1 edits home and api; web joins at run 2 after the user edited it.
+ yield* baseline(rootScope, 0);
+ yield* baseline(apiScope, 0);
+ yield* write(home, "turn 1");
+ yield* write(apiScope.cwd, "turn 1");
+ yield* capture(rootScope, 1);
+ yield* capture(apiScope, 1);
+ yield* write(webScope.cwd, "before run 2");
+ yield* baseline(webScope, 1);
+ for (const scope of [rootScope, apiScope, webScope]) yield* write(scope.cwd, "turn 2");
+ for (const scope of [rootScope, apiScope, webScope]) yield* capture(scope, 2);
+ const refOf = (scope: OrchestrationV2CheckpointScope, ordinal: number) =>
+ records.find(
+ (record) => record.scopeId === scope.id && record.ordinalWithinScope === ordinal,
+ )!.ref;
+ if (scenario === "missing-ref") {
+ yield* git(webScope.cwd, ["update-ref", "-d", refOf(webScope, 1)]);
+ }
+
+ // A plain home has no thread-start snapshot, so its earliest rewind target is turn 1.
+ const targetOrdinal = scenario === "plain-home" ? 1 : 0;
+ const recorded = records.find(
+ (record) => record.scopeId === rootScope.id && record.ordinalWithinScope === targetOrdinal,
+ )!;
+ // A Git home whose baseline capture failed records it as missing.
+ const target =
+ scenario === "git-home-missing" ? { ...recorded, status: "missing" as const } : recorded;
+ const thread = {
+ id: threadId,
+ projectId: ProjectId.make("rollback-task-folder-project"),
+ worktreePath: home,
+ branch: null,
+ activeProviderThreadId: providerThreadId,
+ modelSelection: { instanceId: providerInstanceId, model: "test" },
+ };
+ const providerThread = {
+ id: providerThreadId,
+ driver: ProviderDriverKind.make("codex"),
+ providerSessionId: ProviderSessionId.make("rollback-task-folder-session"),
+ providerInstanceId,
+ nativeThreadRef: null,
+ };
+ const context = {
+ thread,
+ providerThread,
+ providerSession: undefined,
+ checkpoint: target,
+ scope: rootScope,
+ targetAttempt: targetOrdinal === 0 ? undefined : { id: "target-attempt" },
+ providerTurns:
+ targetOrdinal === 0
+ ? []
+ : [{ id: "target-turn", providerThreadId, runAttemptId: "target-attempt", ordinal: 1 }],
+ rolledBackAttemptIds: [],
+ runsToRollback: [1, 2]
+ .filter((ordinal) => ordinal > targetOrdinal)
+ .map((ordinal) => ({
+ id: runId(ordinal),
+ ordinal,
+ status: "completed",
+ rootNodeId: NodeId.make(`rollback-task-folder-node-${ordinal}`),
+ providerInstanceId,
+ })),
+ rootNodes: [],
+ staleCheckpoints: records.filter(
+ (record) => record.scopeId === rootScope.id && record.ordinalWithinScope > targetOrdinal,
+ ),
+ repositoryScopes,
+ repositoryCheckpoints: records.filter((record) => record.scopeId !== rootScope.id),
+ } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
+ const calls: Array = [];
+ const written: Array = [];
+ let failWebRestore = scenario === "undo";
+ const layerTest = layerCheckpointRollbackService.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ ThreadCommandExecutor.layer,
+ IdAllocator.layer,
+ Layer.succeed(CheckpointService.CheckpointServiceV2, {
+ ...checkpoints,
+ restore: (input) => {
+ calls.push(`restore:${input.scope.label ?? "home"}`);
+ if (input.scope.id === webScope.id && failWebRestore) {
+ failWebRestore = false;
+ return Effect.fail(
+ new CheckpointService.CheckpointRestoreError({
+ scopeId: input.scope.id,
+ checkpointId: input.checkpoint.id,
+ cause: "disk full",
+ }),
+ );
+ }
+ return checkpoints.restore(input);
+ },
+ }),
+ Layer.mock(EventSink.EventSinkV2)({
+ write: ({ events }) => Effect.sync(() => (written.push(...events), [])),
+ }),
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
+ getThread: () => Effect.succeed(thread as never),
+ getCheckpointRollbackContext: () => Effect.succeed(context),
+ getProviderControlContext: () => Effect.succeed({ attempt: undefined } as never),
+ getCheckpointContext: () =>
+ Effect.succeed({
+ runs: [],
+ checkpoints: [],
+ checkpointScopes: [rootScope, ...repositoryScopes],
+ }),
+ getShellSnapshot: () =>
+ Effect.succeed({
+ schemaVersion: 1,
+ snapshotSequence: 0,
+ threads: [],
+ archivedThreads: [],
+ }),
+ }),
+ Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
+ open: () =>
+ Effect.succeed({
+ rollbackThread: () =>
+ Effect.sync(() => {
+ calls.push("provider");
+ return { providerThread };
+ }),
+ } as never),
+ }),
+ Layer.mock(RuntimePolicy.RuntimePolicyV2)({
+ resolve: () => Effect.succeed({} as never),
+ }),
+ Layer.mock(TaskFolderStore)({
+ findContaining: () => Effect.succeedSome({ root: task } as never),
+ }),
+ ),
+ ),
+ );
+ const result = yield* CheckpointRollbackService.CheckpointRollbackServiceV2.pipe(
+ Effect.flatMap((service) =>
+ service
+ .execute({
+ threadId,
+ providerThreadId,
+ checkpointId: target.id,
+ scopeId: rootScope.id,
+ })
+ .pipe(Effect.flip, Effect.option),
+ ),
+ Effect.provide(layerTest),
+ );
+
+ const contents = yield* Effect.forEach([home, apiScope.cwd, webScope.cwd], read);
+ const hasRef = (scope: OrchestrationV2CheckpointScope, ordinal: number) =>
+ git(scope.cwd, ["rev-parse", "--verify", "--quiet", refOf(scope, ordinal)]).pipe(
+ Effect.as(true),
+ Effect.orElseSucceed(() => false),
+ );
+ if (scenario === "plain-home") {
+ assert.deepEqual(Option.getOrUndefined(result), undefined);
+ assert.equal(target.status, "missing");
+ // The plain home keeps its files; each repo goes back to its own turn 1 snapshot.
+ assert.deepEqual(contents, ["turn 2", "turn 1", "before run 2"]);
+ assert.deepEqual(calls, ["provider", "restore:api", "restore:web"]);
+ return;
+ }
+ if (scenario === "restores") {
+ assert.isTrue(Option.isNone(result));
+ // web goes back to its first baseline, taken when it joined at run 2.
+ assert.deepEqual(contents, ["initial", "initial", "before run 2"]);
+ assert.deepEqual(calls, ["provider", "restore:home", "restore:api", "restore:web"]);
+ assert.deepEqual(
+ yield* Effect.forEach(
+ [
+ [apiScope, 1],
+ [apiScope, 2],
+ [webScope, 1],
+ [webScope, 2],
+ ] as const,
+ ([scope, ordinal]) => hasRef(scope, ordinal),
+ ),
+ [false, false, true, false],
+ );
+ assert.sameMembers(
+ written.flatMap((event) =>
+ event.type === "checkpoint.captured" && event.payload.status === "stale"
+ ? [
+ `${event.payload.scopeId === rootScope.id ? "home" : event.payload.scopeId === apiScope.id ? "api" : "web"}:${event.payload.ordinalWithinScope}`,
+ ]
+ : [],
+ ),
+ ["home:1", "home:2", "api:1", "api:2", "web:2"],
+ );
+ return;
+ }
+ const error = Option.getOrThrow(result);
+ assert.isEmpty(written);
+ assert.deepEqual(contents, ["turn 2", "turn 2", "turn 2"]);
+ if (scenario === "undo") {
+ assert.equal(error.reason, "repository-restore-failed");
+ assert.deepEqual(calls, [
+ "provider",
+ "restore:home",
+ "restore:api",
+ "restore:web",
+ "restore:home",
+ "restore:api",
+ "restore:web",
+ ]);
+ assert.equal(
+ CheckpointRollbackService.rollbackFailureClientMessage(error),
+ "Could not restore files in web. Every repo is back to how it was before the rewind.",
+ );
+ return;
+ }
+ assert.equal(error.reason, "repository-checkpoint-unavailable");
+ assert.deepEqual(calls, []);
+ if (scenario === "git-home-missing") {
+ assert.equal(error.repository, home);
+ return;
+ }
+ assert.equal(
+ CheckpointRollbackService.rollbackFailureClientMessage(error),
+ "Cannot restore files: web has no checkpoint for that turn. Rewind the conversation without restoring files instead.",
+ );
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(Layer.mergeAll(layerRealCheckpoints, layerVcsProcessTest, NodeServices.layer)),
+ ),
+);
diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
index 2c9a4070db9aa..d1abb67914e46 100644
--- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
@@ -2,14 +2,18 @@ import {
CheckpointId,
CheckpointScopeId,
latestProviderTurnForAttempt,
+ type OrchestrationV2Checkpoint,
+ type OrchestrationV2CheckpointScope,
type OrchestrationV2DomainEvent,
ProviderThreadId,
ThreadId,
VcsProcessExitError,
} from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -20,12 +24,18 @@ import * as GitWorkflowService from "../git/GitWorkflowService.ts";
import type * as ServerConfig from "../config.ts";
import type * as ServerSettings from "../serverSettings.ts";
import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
+import { TaskFolderStore } from "../workspace/TaskFolders.ts";
+import * as TaskFolderService from "../workspace/TaskFolderService.ts";
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
import {
isCheckpointRestoreIsolated,
SHARED_WORKSPACE_RESTORE_MESSAGE,
} from "./CheckpointRestoreSafety.ts";
-import { CheckpointRestoreError, CheckpointServiceV2 } from "./CheckpointService.ts";
+import {
+ CheckpointRestoreError,
+ CheckpointServiceV2,
+ type RestorableCheckpoint,
+} from "./CheckpointService.ts";
import { EventSinkV2 } from "./EventSink.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
@@ -48,15 +58,27 @@ export class CheckpointRollbackExecutionError extends Schema.TaggedError