diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index 7105f3a0e2923..0d0c551252887 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -179,6 +179,7 @@ const make = Effect.gen(function* () { const project = yield* loadProject(scope, projection.thread.projectId); const projectCwd = project.workspaceRoot; + const projectCommands = TaskFolders.linkRunsProjectCommands(projection.thread.linkOrigin); // A project that tracks repositories moves into a task folder: its own folder, which need // not be a repository, and a worktree of each tracked one. @@ -284,6 +285,7 @@ const make = Effect.gen(function* () { projectStart: { refName: worktreeBaseRef, baseRefName }, baseBranch: input.baseRef, startFromOrigin, + projectCommands, }) .pipe( Effect.map((created) => { @@ -332,6 +334,7 @@ const make = Effect.gen(function* () { root: worktree.taskFolder, force: true, forget: true, + projectCommands, deleteBranch: worktree.refName, }), ).pipe(Effect.ignoreCause({ log: true })); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts index 529dea74dec91..eabaf6427c6ee 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts @@ -243,6 +243,7 @@ const taskFolderThread = Effect.fn(function* (state: State, options: Options) { branch, projectStart: { refName: "main", baseRefName: "main" }, startFromOrigin: false, + projectCommands: true, }); const worktreePath = taskFolder.projectPath; const folders = { @@ -728,6 +729,7 @@ it.live.each([{ projectIsRepository: true }, { projectIsRepository: false }])( root: taskFolder.root, force: true, forget: false, + projectCommands: true, }); assert.deepEqual(removal.kept, []); assert.isFalse(yield* fileSystem.exists(taskFolder.root)); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index e85175ef2ee33..b60a263aaa512 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -260,6 +260,7 @@ export const layer: Layer.Layer< yield* taskFolders.restore({ taskFolder, branch, + projectCommands: TaskFolders.linkRunsProjectCommands(context.thread.linkOrigin), recreate: (checkout) => gitWorkflow.pruneWorktrees({ cwd: checkout.repositoryPath }).pipe( Effect.andThen( diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 9bc617e48823b..ac834641f0f52 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -2999,6 +2999,102 @@ it.effect("cancels tracked setup before provider work is released", () => }), ); +it.live( + "a thread started through a link below full access gets no worktree from a project's layout command", + () => { + const state: TaskFoldersTestState = { + workspaceRoot: "/unset", + trackedFolders: [], + thread: null, + }; + const layerGit = GitVcsDriver.layer.pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-launch-layout-" })), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + const layerTaskFolders = layerTaskFoldersWithGit(state).pipe( + Layer.provide(layerGit), + Layer.orDie, + ); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const git = yield* GitVcsDriver.GitVcsDriver; + const tmp = yield* fileSystem.realPath( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-layout-" }), + ); + const shop = path.join(tmp, "shop"); + const ran = path.join(tmp, "ran"); + yield* fileSystem.makeDirectory(shop); + for (const args of [ + ["init", "-b", "main"], + ["config", "user.email", "launch@example.test"], + ["config", "user.name", "Launch"], + ["commit", "--allow-empty", "-m", "initial"], + ]) { + yield* git.execute({ operation: "launch-test", cwd: shop, args }); + } + yield* fileSystem.writeFileString( + path.join(shop, "t3.json"), + JSON.stringify({ + worktreeLayout: { + create: `echo create >> "${ran}" && git worktree add -q -b "$T3_WORKTREE_BRANCH" "$T3_WORKTREE_PROJECT_PATH"`, + }, + }), + ); + state.workspaceRoot = shop; + const harness = makeHarness({ taskFolders: layerTaskFolders }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const launch = Effect.fnUntraced(function* ( + name: string, + access: "full-access" | "auto-accept-edits", + ) { + const launched = yield* launches.launch({ + ...launchInput({ + command: `launch:${name}`, + thread: `thread:${name}`, + message: "Start", + workspace: { type: "worktree", baseRef: "main", branch: `feature/${name}` }, + }), + createdBy: "agent", + creationSource: "mcp", + linkOrigin: { sessionId: "mcp-session:linked", label: "Linked laptop", access }, + }); + return yield* preparationSettled(launched.threadId); + }); + + const limited = yield* launch("limited", "auto-accept-edits"); + assert.equal(limited.runs[0]?.status, "failed"); + assert.isNull(limited.thread.worktreePath); + assert.isFalse(yield* fileSystem.exists(ran)); + + // Preparing the same run again reads the link from the thread, not from a request. + const threads = yield* ThreadManagement.ThreadManagementService; + yield* launches.retryPreparation({ + commandId: CommandId.make("launch:limited:retry"), + threadId: limited.thread.id, + runId: limited.runs[0]!.id, + }); + yield* threads.streamStoredEventsFrom({ threadId: limited.thread.id }).pipe( + Stream.filter( + (stored) => + stored.event.type === "run.updated" && + (stored.commandId?.endsWith(":release") === true || + stored.event.payload.status === "failed"), + ), + Stream.take(2), + Stream.runDrain, + ); + assert.isFalse(yield* fileSystem.exists(ran)); + + const full = yield* launch("full", "full-access"); + assert.equal(full.runs[0]?.status, "starting"); + assert.equal(yield* fileSystem.readFileString(ran), "create\n"); + }).pipe(Effect.provide(harness.layer)); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, layerGit)), Effect.scoped); + }, +); + it.live("launches into a task folder and leaves nothing behind when its setup is cancelled", () => { const state: TaskFoldersTestState = { workspaceRoot: "/unset", trackedFolders: [], thread: null }; const layerGit = GitVcsDriver.layer.pipe( diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 9262695987cbf..8e2c94e6ca84b 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -131,7 +131,7 @@ export interface ThreadLaunchInput { type PreparationInput = Pick< ThreadLaunchInput, - "commandId" | "projectId" | "workspaceStrategy" | "initialMessage" + "commandId" | "projectId" | "workspaceStrategy" | "initialMessage" | "linkOrigin" > & { readonly reusedWorktree?: { readonly baseRef: string }; }; @@ -853,6 +853,7 @@ const make = Effect.gen(function* () { projectStart: { refName: startRef, baseRefName }, baseBranch: input.workspaceStrategy.baseRef, startFromOrigin: input.workspaceStrategy.startFromOrigin === true, + projectCommands: TaskFolders.linkRunsProjectCommands(input.linkOrigin), projectProgress: progress, onClaimed: (taskFolder, claimedBranch) => Effect.sync(() => { @@ -1177,6 +1178,7 @@ const make = Effect.gen(function* () { root: removedTaskFolder, force: true, forget: true, + projectCommands: TaskFolders.linkRunsProjectCommands(input.linkOrigin), deleteBranch: removedBranch ?? undefined, }) .pipe( @@ -1705,6 +1707,7 @@ const make = Effect.gen(function* () { commandId: input.commandId, projectId: thread.projectId, workspaceStrategy: reuse?.strategy ?? workspacePreparation, + ...(thread.linkOrigin === undefined ? {} : { linkOrigin: thread.linkOrigin }), ...(reuse === null ? {} : { reusedWorktree: reuse.reusedWorktree }), ...(message === undefined ? {} diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 0b374ea7c6514..c62d74f186553 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -1041,6 +1041,7 @@ it.live("removes a task folder's clean worktrees and keeps the one with uncommit branch: "task", projectStart: { refName: "main", baseRefName: "main" }, startFromOrigin: false, + projectCommands: true, }); const root = taskFolder.root; // A nested worktree's uncommitted work must survive its thread's cleanup. diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index a5bddbd7c9cba..451df614f8184 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -1663,6 +1663,7 @@ const make = Effect.gen(function* () { root: taskFolder.root, force: false, forget: deleted, + projectCommands: TaskFolders.linkRunsProjectCommands(thread.linkOrigin), inspect: (checkout) => worktreeAdminDir(checkout.worktreePath).pipe( Effect.map((adminDir) => adminDirs.set(checkout.worktreePath, adminDir)), diff --git a/apps/server/src/workspace/TaskFolders.test.ts b/apps/server/src/workspace/TaskFolders.test.ts index 9ae3de88b6143..302af55199966 100644 --- a/apps/server/src/workspace/TaskFolders.test.ts +++ b/apps/server/src/workspace/TaskFolders.test.ts @@ -82,6 +82,7 @@ const create = Effect.fnUntraced(function* ( projectStart: { refName: "main", baseRefName: "main" }, baseBranch, startFromOrigin: false, + projectCommands: true, }); }); @@ -161,7 +162,7 @@ it.live("lays a plain wrapper out as links around its repositories' worktrees", // A file of the thread's own keeps the folder, and a folder that stays keeps its links. yield* fileSystem.writeFileString(path.join(root, "draft.md"), "mine\n"); - yield* taskFolders.remove({ root, force: false, forget: true }); + yield* taskFolders.remove({ root, force: false, forget: true, projectCommands: true }); assert.equal( yield* fileSystem.readLink(path.join(root, "AGENTS.md")), path.join(shop, "AGENTS.md"), @@ -218,13 +219,23 @@ it.live("keeps a Git project and its sibling repository side by side", () => const taskFolders = yield* TaskFolders.TaskFolders; const { root } = taskFolder; yield* fileSystem.writeFileString(path.join(root, "notes.md"), "mine\n"); - const first = yield* taskFolders.remove({ root, force: false, forget: true }); + const first = yield* taskFolders.remove({ + root, + force: false, + forget: true, + projectCommands: true, + }); assert.deepEqual( first.kept.map((entry) => entry.path), [root], ); assert.isNotNull(yield* taskFolders.find(root)); - const second = yield* taskFolders.remove({ root, force: true, forget: true }); + const second = yield* taskFolders.remove({ + root, + force: true, + forget: true, + projectCommands: true, + }); assert.deepEqual(second.kept, []); assert.isFalse(yield* fileSystem.exists(root)); assert.isNull(yield* taskFolders.find(root)); @@ -293,7 +304,9 @@ it.live.each([{ projectIsRepository: true }, { projectIsRepository: false }])( const taskFolders = yield* TaskFolders.TaskFolders; const request = { cwd: shop, refName: "main", newRefName: "feature", path: null }; - const created = yield* taskFolders.createForProjectFolder(request); + const created = yield* taskFolders.createForProjectFolder(request, { + projectCommands: true, + }); const taskFolder = yield* taskFolders.find(created!.worktree.path); assert.deepEqual(created, { @@ -316,7 +329,9 @@ it.live.each([{ projectIsRepository: true }, { projectIsRepository: false }])( { cwd: shop, refName: "main", path: null }, { ...request, cwd: web }, ]) { - assert.isNull(yield* taskFolders.createForProjectFolder(single)); + assert.isNull( + yield* taskFolders.createForProjectFolder(single, { projectCommands: true }), + ); } }), ), @@ -481,6 +496,7 @@ it.live("adopts the checkouts a project's own layout command makes, and runs its root: taskFolder.root, force: true, forget: true, + projectCommands: true, inspect: () => Effect.succeed({ keep: null, force: true }), }); assert.isTrue(yield* fileSystem.exists(path.join(shop, "torn-down"))); @@ -491,6 +507,63 @@ it.live("adopts the checkouts a project's own layout command makes, and runs its ), ); +it.live("leaves a project's layout commands out for a request that may not run them", () => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, tmp, run, repository, worktreeCount } = yield* fixture; + const shop = path.join(tmp, "shop"); + const api = yield* repository("shop/api"); + const ran = path.join(tmp, "ran"); + yield* fileSystem.writeFileString( + path.join(shop, "t3.json"), + JSON.stringify({ + worktreeLayout: { + create: `echo create >> "${ran}" && mkdir -p "$T3_WORKTREE_PROJECT_PATH" && git -C "$T3_PROJECT_ROOT/api" worktree add -q -b "$T3_WORKTREE_BRANCH" "$T3_WORKTREE_PROJECT_PATH/api"`, + remove: `echo remove >> "${ran}"`, + }, + }), + ); + state.workspaceRoot = shop; + state.trackedFolders = tracked(api); + const taskFolders = yield* TaskFolders.TaskFolders; + + const refused = yield* taskFolders + .createForProjectFolder( + { cwd: shop, refName: "main", newRefName: "feature", path: null }, + { projectCommands: false }, + ) + .pipe(Effect.flip); + assert.include(refused.detail, "not permitted to run"); + assert.isFalse(yield* fileSystem.exists(ran)); + assert.equal(yield* worktreeCount(api), 1); + assert.equal(yield* run(api, "branch", "--list", "feature"), ""); + + const { taskFolder } = yield* create("feature"); + assert.equal(yield* fileSystem.readFileString(ran), "create\n"); + // A missing checkout comes back plain, and the folder goes without the project's teardown. + yield* fileSystem.remove(path.join(taskFolder.root, "api"), { recursive: true }); + yield* run(api, "worktree", "prune"); + yield* taskFolders.restore({ + taskFolder, + branch: "feature", + projectCommands: false, + recreate: (checkout) => + run(checkout.repositoryPath, "worktree", "add", "-q", checkout.worktreePath, "feature"), + }); + assert.equal(yield* worktreeCount(api), 2); + assert.isTrue( + yield* taskFolders.removeIfTaskFolder({ + path: taskFolder.root, + force: true, + projectCommands: false, + }), + ); + assert.equal(yield* fileSystem.readFileString(ran), "create\n"); + assert.isFalse(yield* fileSystem.exists(taskFolder.root)); + }), + ), +); + it.live( "removes what a failed layout command checked out, and refuses a checkout it cannot own", () => @@ -516,6 +589,7 @@ it.live( branch: "feature", projectStart: { refName: "main", baseRefName: "main" }, startFromOrigin: false, + projectCommands: true, }) .pipe(Effect.flip); }); @@ -591,11 +665,17 @@ it.live.each([{ linked: false }, { linked: true }])( yield* taskFolders.restore({ taskFolder, branch: "feature", + projectCommands: true, recreate: () => Effect.die("the layout command rebuilds the folder"), }); assert.isTrue(yield* fileSystem.exists(prepared)); - yield* taskFolders.remove({ root: taskFolder.root, force: true, forget: true }); + yield* taskFolders.remove({ + root: taskFolder.root, + force: true, + forget: true, + projectCommands: true, + }); assert.equal(yield* worktreeCount(mono), linked ? 2 : 1); }), ), @@ -625,12 +705,10 @@ it.live("starts each repository from the base branch where it has one", () => yield* head(web, "main"), ); // A worktree an existing thread asks for starts its repositories from the chosen base too. - const requested = yield* (yield* TaskFolders.TaskFolders).createForProjectFolder({ - cwd: state.workspaceRoot, - refName: "release", - newRefName: "later", - path: null, - }); + const requested = yield* (yield* TaskFolders.TaskFolders).createForProjectFolder( + { cwd: state.workspaceRoot, refName: "release", newRefName: "later", path: null }, + { projectCommands: true }, + ); assert.equal( yield* head(path.join(requested!.worktree.path, "api"), "HEAD"), yield* head(api, "release"), @@ -852,6 +930,7 @@ it.live("adds a repository to an existing task folder on the thread's branch", ( .restore({ taskFolder: (yield* taskFolders.find(root))!, branch: "feature", + projectCommands: true, recreate: () => Effect.die("an existing checkout is never recreated"), }) .pipe(Effect.flip); @@ -875,7 +954,12 @@ it.live("keeps a repository git will not remove and removes the rest", () => const root = taskFolder.root; yield* fileSystem.writeFileString(path.join(root, "api", "README.md"), "uncommitted\n"); - const first = yield* taskFolders.remove({ root, force: false, forget: true }); + const first = yield* taskFolders.remove({ + root, + force: false, + forget: true, + projectCommands: true, + }); assert.deepEqual(first.removed, [path.join(root, "web")]); assert.deepEqual( @@ -898,7 +982,12 @@ it.live("keeps a repository git will not remove and removes the rest", () => [api], ); - const second = yield* taskFolders.remove({ root, force: true, forget: true }); + const second = yield* taskFolders.remove({ + root, + force: true, + forget: true, + projectCommands: true, + }); assert.deepEqual(second.kept, []); assert.isFalse(yield* fileSystem.exists(root)); @@ -929,6 +1018,7 @@ it.live("restores a recorded repository the project stopped tracking as its work yield* (yield* TaskFolders.TaskFolders).restore({ taskFolder, branch: "feature", + projectCommands: true, recreate: ({ repositoryPath, worktreePath }) => run(repositoryPath, "worktree", "prune").pipe( Effect.andThen(run(repositoryPath, "worktree", "add", "-q", worktreePath, "feature")), @@ -965,6 +1055,7 @@ it.live("resumes once an excluded dependency's worktree is replaced by a clone", const restore = taskFolders.restore({ taskFolder, branch: "feature", + projectCommands: true, recreate: () => Effect.die("nothing is missing"), }); diff --git a/apps/server/src/workspace/TaskFolders.ts b/apps/server/src/workspace/TaskFolders.ts index fe6def1f9dc3a..78a21fdccc8df 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -1,5 +1,7 @@ import { GitCommandError, + linkOriginIsFenced, + type OrchestrationV2LinkOrigin, type ProjectId, type ProjectTrackedFolder, TASK_FOLDER_DEFAULT_REPOSITORIES_MAX, @@ -104,6 +106,11 @@ export class TaskFolders extends Context.Service< */ readonly baseBranch?: string | undefined; readonly startFromOrigin: boolean; + /** + * Whether the project's own layout command may run for whoever asks. A project that + * declares one gets no worktree without it: the default layout is not what it asked for. + */ + readonly projectCommands: boolean; readonly projectProgress?: GitVcsDriver.CreateWorktreeProgress; /** As soon as the folder is recorded, so a cancelled caller knows what to remove. */ readonly onClaimed?: (taskFolder: TaskFolder, branch: string) => Effect.Effect; @@ -130,6 +137,7 @@ export class TaskFolders extends Context.Service< */ readonly createForProjectFolder: ( input: VcsCreateWorktreeInput, + options: { readonly projectCommands: boolean }, ) => Effect.Effect; /** * Gives a tracked Git folder its worktree in a thread's task folder, on the thread's branch. @@ -152,6 +160,8 @@ export class TaskFolders extends Context.Service< readonly root: string; readonly force: boolean; readonly forget: boolean; + /** False leaves the project's teardown command out. */ + readonly projectCommands: boolean; readonly deleteBranch?: string | undefined; readonly inspect?: ( checkout: TaskFolderCheckout, @@ -164,6 +174,7 @@ export class TaskFolders extends Context.Service< readonly removeIfTaskFolder: (input: { readonly path: string; readonly force: boolean; + readonly projectCommands: boolean; }) => Effect.Effect; /** Renames the branch in every checkout to one name free in all of them. */ readonly renameBranch: (input: { @@ -172,9 +183,13 @@ export class TaskFolders extends Context.Service< readonly newBranch: string; readonly exactName?: boolean; }) => Effect.Effect<{ readonly branch: string }, TaskFolderError>; - /** Puts back whatever is missing; `recreate` checks a branch out again at a path. */ + /** + * Puts back whatever is missing; `recreate` checks a branch out again at a path. Without + * `projectCommands` every missing checkout comes back plain. + */ readonly restore: (input: { readonly taskFolder: TaskFolder; + readonly projectCommands: boolean; /** The thread's branch, for a project that lays its folder out with its own command. */ readonly branch: string; readonly recreate: (checkout: TaskFolderCheckout) => Effect.Effect; @@ -184,6 +199,13 @@ export class TaskFolders extends Context.Service< const isTaskFolderError = Schema.is(TaskFolderError); +/** + * A layout command is the project owner's own code. A link paired below full access grants T3's + * tools only (see `mcp/linkOrigin.ts`), so work it started never runs one. + */ +export const linkRunsProjectCommands = (origin: OrchestrationV2LinkOrigin | undefined) => + origin === undefined || !linkOriginIsFenced(origin); + const failureDetail = (cause: unknown) => typeof cause === "object" && cause !== null && @@ -730,7 +752,8 @@ const make = Effect.gen(function* () { }); // The project's own teardown goes first; what it leaves is removed below as usual. Only when // every checkout may go: the command cannot be told which ones to keep. - const layout = laidOut ? yield* worktreeLayout(taskFolder.projectRoot) : null; + const layout = + laidOut && input.projectCommands ? yield* worktreeLayout(taskFolder.projectRoot) : null; if (layout?.remove !== undefined) { const checkouts = [ ...taskFolder.repositories, @@ -975,6 +998,12 @@ const make = Effect.gen(function* () { yield* store.put(empty); if (input.onClaimed !== undefined) yield* input.onClaimed(empty, branch); const layout = yield* worktreeLayout(taskPlan.projectRoot); + if (layout !== null && !input.projectCommands) { + return yield* new TaskFolderError({ + operation: "create", + detail: `This project lays out its worktrees with its own command (worktreeLayout in ${T3_PROJECT_FILE_NAME}), which this request is not permitted to run.`, + }); + } if (layout !== null) { const before = yield* branchNames(checkedOutFrom).pipe(Effect.mapError(listFailed)); for (const [index, repositoryPath] of checkedOutFrom.entries()) { @@ -1117,7 +1146,12 @@ const make = Effect.gen(function* () { Effect.andThen( removeLocked( current(), - { force: true, forget: true, deleteBranch: branch }, + { + force: true, + forget: true, + deleteBranch: branch, + projectCommands: input.projectCommands, + }, hadBranch, layoutStarted, ), @@ -1168,7 +1202,7 @@ const make = Effect.gen(function* () { const createForProjectFolder: TaskFolders["Service"]["createForProjectFolder"] = Effect.fn( "TaskFolders.createForProjectFolder", - )(function* (input) { + )(function* (input, { projectCommands }) { if (input.path !== null || input.newRefName === undefined) return null; const project = yield* projects .findActiveByWorkspaceRoot(input.cwd) @@ -1183,6 +1217,7 @@ const make = Effect.gen(function* () { projectStart: { refName: input.refName, baseRefName: input.baseRefName ?? input.refName }, baseBranch: input.baseRefName ?? input.refName, startFromOrigin: yield* startsFromOrigin("create", projectId), + projectCommands, }); return { worktree: { path: taskFolder.projectPath, refName: branch } }; }); @@ -1321,7 +1356,11 @@ const make = Effect.gen(function* () { const target = path.resolve(input.path); if (taskFolder === null || (target !== taskFolder.root && target !== taskFolder.projectPath)) return false; - const { kept } = yield* removeLocked(taskFolder, { force: input.force, forget: true }); + const { kept } = yield* removeLocked(taskFolder, { + force: input.force, + forget: true, + projectCommands: input.projectCommands, + }); if (kept.length > 0) { return yield* new TaskFolderError({ operation: "remove", @@ -1380,6 +1419,7 @@ const make = Effect.gen(function* () { const restore: TaskFolders["Service"]["restore"] = Effect.fn("TaskFolders.restore")(function* ({ taskFolder, branch, + projectCommands, recreate, }) { const restoreFailed = fail("create", "Could not restore the worktrees"); @@ -1422,7 +1462,7 @@ const make = Effect.gen(function* () { [taskFolder.projectPath, ...repositories.map((entry) => entry.worktreePath)], exists, ); - if (layout !== null && present.includes(false)) { + if (layout !== null && projectCommands && present.includes(false)) { yield* fileSystem .makeDirectory(taskFolder.root, { recursive: true }) .pipe(Effect.mapError(restoreFailed)); diff --git a/apps/server/src/workspace/restoreMissingWorktree.ts b/apps/server/src/workspace/restoreMissingWorktree.ts index ea803cbdac680..9af24e001cf6b 100644 --- a/apps/server/src/workspace/restoreMissingWorktree.ts +++ b/apps/server/src/workspace/restoreMissingWorktree.ts @@ -1,5 +1,6 @@ import { ThreadId, + type OrchestrationV2LinkOrigin, type Project, type ProjectId, type TerminalCwdNotFoundError, @@ -57,6 +58,7 @@ interface WorktreeThread { readonly projectId: ProjectId; readonly worktreePath: string | null; readonly branch: string | null; + readonly linkOrigin?: OrchestrationV2LinkOrigin | undefined; } export const makeRestoreMissingWorktree = Effect.gen(function* () { @@ -202,6 +204,7 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { .restore({ taskFolder, branch, + projectCommands: TaskFolders.linkRunsProjectCommands(thread.linkOrigin), recreate: (checkout) => Effect.logWarning("recreating missing worktree", { threadId: thread.id, diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 2838be2a228a3..dc79f0166aa95 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -17,6 +17,7 @@ import { type WorkflowStep, AuthSessionId, AuthSourceControlWriteScope, + AuthTerminalOperateScope, ORCHESTRATION_PROTOCOL_VERSION, ORCHESTRATION_PROTOCOL_QUERY_PARAM, EnvironmentId, @@ -1936,6 +1937,96 @@ it.effect("a missing thread worktree gets its project's skills in the cwd snapsh ), ); +it.effect( + "worktree requests run a project's layout commands only for a session that may run commands", + () => + Effect.gen(function* () { + const browser = yield* ServerBrowser.ServerBrowser; + const requested = Effect.fnUntraced(function* (scopes: ReadonlyArray) { + const seen: boolean[] = []; + const exits = yield* Queue.unbounded(); + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(TaskFolders.TaskFolders)({ + createForProjectFolder: (_input, options) => + Effect.sync(() => seen.push(options.projectCommands)).pipe( + Effect.as({ worktree: { path: "/repo-worktrees/feature", refName: "feature" } }), + ), + removeIfTaskFolder: (input) => + Effect.sync(() => seen.push(input.projectCommands)).pipe(Effect.as(true)), + }), + Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({ + refreshStatus: () => Effect.die("unused"), + }), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + ); + const server = yield* RpcServer.makeNoSerialization(WsRpcGroup, { + ...WS_RPC_SERVER_OPTIONS, + onFromServer: (response) => + response._tag === "Exit" ? Queue.offer(exits, response.exit._tag) : Effect.void, + }).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("worktree-test"), + subject: "worktree-test", + method: "browser-session-cookie", + scopes: [...scopes], + }, + {}, + browser, + () => Effect.void, + { secretReferences: true }, + ).pipe(Layer.provide(services), Layer.merge(RpcAuthorization.layer(scopes))), + ), + ); + yield* server.write(0, { + _tag: "Request", + id: RpcMessage.RequestId("create"), + tag: WS_METHODS.vcsCreateWorktree, + payload: { cwd: "/repo", refName: "main", newRefName: "feature", path: null }, + headers: Headers.empty, + }); + assert.equal(yield* Queue.take(exits), "Success"); + yield* server.write(0, { + _tag: "Request", + id: RpcMessage.RequestId("remove"), + tag: WS_METHODS.vcsRemoveWorktree, + payload: { cwd: "/repo", path: "/repo-worktrees/feature" }, + headers: Headers.empty, + }); + assert.equal(yield* Queue.take(exits), "Success"); + return seen; + }, Effect.scoped); + + assert.deepEqual(yield* requested([AuthSourceControlWriteScope]), [false, false]); + assert.deepEqual( + yield* requested([AuthSourceControlWriteScope, AuthOrchestrationOperateScope]), + [true, true], + ); + assert.deepEqual(yield* requested([AuthSourceControlWriteScope, AuthTerminalOperateScope]), [ + true, + true, + ]); + }).pipe( + Effect.provide( + Layer.mergeAll( + Layer.fresh(layerConfigSources), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), + ), + ), + ), +); + it.effect("a git action that fails partway still refreshes the repository status", () => Effect.gen(function* () { const failure = new GitManagerError({ operation: "test", cwd: "/repo", detail: "push failed" }); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 583b1919aa5e0..7ffce48991ee8 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -34,6 +34,7 @@ import { AuthAccessStreamError, type AuthAccessStreamEvent, AuthOrchestrationOperateScope, + AuthTerminalOperateScope, AuthProvidersManageScope, type AuthEnvironmentScope, ProviderDriverKind, @@ -1637,6 +1638,11 @@ export const layerWsRpc = ( ...result, tasks: result.tasks.map(({ webhook: _webhook, ...task }) => task), }; + // A project's layout command is its owner's code: only a session that may already run + // commands on the host has it run from a worktree request. + const projectCommands = + currentSession.scopes.includes(AuthOrchestrationOperateScope) || + currentSession.scopes.includes(AuthTerminalOperateScope); const authorizeEffect = ( requiredScope: AuthEnvironmentScope, effect: Effect.Effect, @@ -3330,7 +3336,7 @@ export const layerWsRpc = ( [WS_METHODS.vcsListRefs]: (input) => gitWorkflow.listRefs(input), [WS_METHODS.vcsCreateWorktree]: (input) => // A project that tracks repositories gets a task folder, as its new worktree threads do. - taskFolders.createForProjectFolder(input).pipe( + taskFolders.createForProjectFolder(input, { projectCommands }).pipe( Effect.mapError( (cause) => new GitCommandError({ @@ -3348,28 +3354,30 @@ export const layerWsRpc = ( ), [WS_METHODS.vcsRemoveWorktree]: (input) => // A thread's worktree may be a task folder: its repositories' worktrees go with it. - taskFolders.removeIfTaskFolder({ path: input.path, force: input.force === true }).pipe( - Effect.mapError( - (cause) => - new GitCommandError({ - operation: "TaskFolders.remove", - command: "git worktree remove", - cwd: input.cwd, - detail: cause.detail, - }), - ), - Effect.flatMap((removed) => - removed ? Effect.void : gitWorkflow.removeWorktree(input), - ), - // No project-root refresh here: the client awaits vcs.refreshStatus right after, and a - // second refresh would queue behind this one and reread an unchanged repository. - // Subscribers of the removed checkout learn it is no longer a repository. - Effect.tap(() => - vcsStatusBroadcaster - .refreshLocalStatus(input.path) - .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid), + taskFolders + .removeIfTaskFolder({ path: input.path, force: input.force === true, projectCommands }) + .pipe( + Effect.mapError( + (cause) => + new GitCommandError({ + operation: "TaskFolders.remove", + command: "git worktree remove", + cwd: input.cwd, + detail: cause.detail, + }), + ), + Effect.flatMap((removed) => + removed ? Effect.void : gitWorkflow.removeWorktree(input), + ), + // No project-root refresh here: the client awaits vcs.refreshStatus right after, and a + // second refresh would queue behind this one and reread an unchanged repository. + // Subscribers of the removed checkout learn it is no longer a repository. + Effect.tap(() => + vcsStatusBroadcaster + .refreshLocalStatus(input.path) + .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid), + ), ), - ), [WS_METHODS.vcsCreateRef]: (input) => (input.switchRef ? assertCheckoutIdle("GitWorkflowService.createRef", input.cwd) diff --git a/docs/internals/05_remote.md b/docs/internals/05_remote.md index 13ef6dffb9374..2b12c6b99bef6 100644 --- a/docs/internals/05_remote.md +++ b/docs/internals/05_remote.md @@ -32,7 +32,8 @@ side lists and revokes it in Sharing & access like any other session, and owns i derived forks, subagents, and spawned threads) carry an immutable `linkOrigin` stamp enforced in shared access rules ([`mcp/linkOrigin.ts`](../../apps/server/src/mcp/linkOrigin.ts)). Below full access, linked work can mutate only threads with the same origin, cannot touch projects, settings, - scheduled tasks, or further links, and skips project setup scripts. Full-access links are not + scheduled tasks, or further links, and skips project setup scripts and worktree layout commands + (a project that declares a layout gives such a thread no worktree). Full-access links are not fenced because their agents already run as the receiving OS user. - **Namespace idempotency keys.** All callers on the linking side share one session on the receiving side, so idempotency keys must be hashed with the caller's namespace before forwarding. diff --git a/docs/user/multi-repo-projects.md b/docs/user/multi-repo-projects.md index 7962770417175..2f76ee613c25c 100644 --- a/docs/user/multi-repo-projects.md +++ b/docs/user/multi-repo-projects.md @@ -143,6 +143,10 @@ What the commands can rely on, and what they must do: - **One command runs at a time per project**, so a command can update a shared file in the project folder without its own locking. - **Each command has ten minutes.** +- **The commands run only for requests that may run commands on the host.** A client paired + without `orchestration:operate` and `terminal:operate`, and a thread started through a + [linked environment](remote-access.md#link-another-environment) paired below full access, get no worktree in a project + that declares a layout, and their cleanup leaves `remove` out. A project with no other repository can declare a layout too. This example gives each thread a worktree with its submodules checked out. The command runs in `sh`, and in `cmd.exe` on Windows, diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 3518382d2026e..3805ea12a2f86 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -605,7 +605,11 @@ checkout use that checkout's permissions. client: pushing, switching or creating branches, cloning, and removing worktrees. It does not restrict what a task does. Starting a task in a new worktree still creates that branch and worktree with `orchestration:operate`, -and the agent it runs can use Git however the environment allows. +and the agent it runs can use Git however the environment allows. A project +that [lays out its worktrees with its own command](multi-repo-projects.md#lay-the-folder-out-yourself) +runs that command on the host, so creating a worktree there from the client also +needs `orchestration:operate` or `terminal:operate`; without one of them, +removing a worktree skips the project's `remove` command. Settings changes, provider management, environment maintenance, access management, and T3 Connect preferences can each be granted separately. Setting