diff --git a/packages/paperclip-runner/src/protocol-actions/list-workspaces.ts b/packages/paperclip-runner/src/protocol-actions/list-workspaces.ts index b1bfd4f1f17..6ac54b7415b 100644 --- a/packages/paperclip-runner/src/protocol-actions/list-workspaces.ts +++ b/packages/paperclip-runner/src/protocol-actions/list-workspaces.ts @@ -37,7 +37,7 @@ export const listWorkspacesAction = { "success": { "ok": true, "operationId": "list_workspaces", - "result": {} + "result": [] } }, "live": { diff --git a/server/src/__tests__/execution-workspaces-routes.test.ts b/server/src/__tests__/execution-workspaces-routes.test.ts index 650b3351a31..1090222bd9d 100644 --- a/server/src/__tests__/execution-workspaces-routes.test.ts +++ b/server/src/__tests__/execution-workspaces-routes.test.ts @@ -146,6 +146,7 @@ describe("execution workspace routes", () => { issueId: undefined, status: undefined, reuseEligible: true, + selectableForTask: false, }); expect(mockExecutionWorkspaceService.list).not.toHaveBeenCalled(); }); diff --git a/server/src/__tests__/heartbeat-project-repositories.test.ts b/server/src/__tests__/heartbeat-project-repositories.test.ts index a04ea036543..5260c070638 100644 --- a/server/src/__tests__/heartbeat-project-repositories.test.ts +++ b/server/src/__tests__/heartbeat-project-repositories.test.ts @@ -15,6 +15,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro import { heartbeatService } from "../services/heartbeat.ts"; import { instanceSettingsService } from "../services/instance-settings.ts"; import { environmentRuntimeService } from "../services/environment-runtime.js"; +import { findNativeChatWorkspaceScope } from "../services/native-runtime/native-chat-workspace.js"; import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js"; const execute = vi.hoisted(() => vi.fn(async (_input: any) => ({ exitCode: 0, signal: null, timedOut: false }))); @@ -111,7 +112,7 @@ suite("task project repository provisioning", () => { }, { timeout: 15_000 }); await drainHeartbeatRunsToQuiescence(db, sandboxHeartbeat); const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.sourceIssueId, issueId)); - expect(workspace).toMatchObject({ companyId, projectId, mode: "isolated_workspace", strategyType: "project_primary" }); + expect(workspace).toMatchObject({ companyId, projectId: null, mode: "isolated_workspace", strategyType: "project_primary" }); expect(workspace.cwd).toContain(`/isolated-workspaces/${companyId}/${issueId}`); expect(execute.mock.calls.filter(([input]) => input.runId === run!.id)).toHaveLength(1); const call = execute.mock.calls.find(([input]) => input.runId === run!.id)![0]; @@ -194,6 +195,32 @@ suite("task project repository provisioning", () => { } }, 25_000); + it("keeps a task directory source projectless across chat admissions with an organizational project", async () => { + const companyId = randomUUID(), projectId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Chat files", issuePrefix: `C${companyId.slice(0, 6)}`, defaultResponsibleUserId: "responsible-user" }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "owner" }); + await db.insert(projects).values({ id: projectId, companyId, name: "Organization only" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Chat agent", status: "idle", adapterType: "codex_local", adapterConfig: {}, permissions: {} }); + await db.insert(issues).values({ id: issueId, companyId, projectId, title: "Keep chat files", originKind: "chat_channel", status: "todo", assigneeAgentId: agentId, + workspaceSelection: { version: 1, source: "explicit", selection: { kind: "task_directory" } } }); + let bindingId: string | undefined; + for (let admission = 0; admission < 2; admission++) { + await db.update(issues).set({ status: "todo" }).where(eq(issues.id, issueId)); + const run = await heartbeat.wakeup(agentId, { source: "on_demand", triggerDetail: "manual", contextSnapshot: { issueId, projectId } }); + await vi.waitFor(async () => { expect(await heartbeat.getRun(run!.id)).toMatchObject({ status: "succeeded", error: null }); }, { timeout: 15_000 }); + await drainHeartbeatRunsToQuiescence(db, heartbeat); + const [task] = await db.select().from(issues).where(eq(issues.id, issueId)); + const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, task.executionWorkspaceId!)); + expect(workspace.projectId).toBeNull(); + expect(task.projectId).toBe(projectId); + if (bindingId) expect(workspace.id).toBe(bindingId); + bindingId = workspace.id; + const scope = await findNativeChatWorkspaceScope(db, { companyId, agentId, issueId, instanceRoot: root, + adapterType: "paperclip_runner", environmentDriver: "local" }); + expect(scope?.projectId).toBeNull(); + } + }, 40_000); + it.each([ { code: "workspace_git_scan_timeout", scenario: "temporary", retryable: true }, { code: "workspace_git_scan_saturated", scenario: "temporary", retryable: true }, diff --git a/server/src/__tests__/issues-service.test.ts b/server/src/__tests__/issues-service.test.ts index c40bc18031d..d5246010337 100644 --- a/server/src/__tests__/issues-service.test.ts +++ b/server/src/__tests__/issues-service.test.ts @@ -5633,7 +5633,7 @@ describeEmbeddedPostgres("issueService.create workspace inheritance", () => { }); }); - it("derives project identity when an update adds workspace linkage to a projectless issue", async () => { + it("preserves projectless organization when an update adds workspace linkage", async () => { const companyId = randomUUID(); const projectId = randomUUID(); const projectWorkspaceId = randomUUID(); @@ -5674,7 +5674,7 @@ describeEmbeddedPostgres("issueService.create workspace inheritance", () => { projectWorkspaceId, }); - expect(updated?.projectId).toBe(projectId); + expect(updated?.projectId).toBeNull(); expect(updated?.projectWorkspaceId).toBe(projectWorkspaceId); }); diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index ee3618fc44c..cadbcf5a01e 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -49,6 +49,7 @@ const apiPrefixes: Record = { "decision-training.ts": "/api", "environments.ts": "/api", "execution-workspaces.ts": "/api", + "task-workspaces.ts": "/api", "file-resources.ts": "/api", "folders.ts": "/api", "goals.ts": "/api", diff --git a/server/src/__tests__/pipelines-routes.test.ts b/server/src/__tests__/pipelines-routes.test.ts index 3cb7bb7243d..4e5a7e36a15 100644 --- a/server/src/__tests__/pipelines-routes.test.ts +++ b/server/src/__tests__/pipelines-routes.test.ts @@ -598,7 +598,7 @@ describeEmbeddedPostgres("pipeline routes", () => { }); }); - it("fails automation execution when the selected project workspace belongs to a different project", async () => { + it("keeps automation project organization independent of the selected workspace source", async () => { const company = await seedCompany(); const http = request(app(boardActor)); const agent = await seedAutomationAgent(company.id); @@ -621,7 +621,7 @@ describeEmbeddedPostgres("pipeline routes", () => { config: { automation: { assigneeAgentId: agent.id, - instructionsBody: "This should fail before issue creation.", + instructionsBody: "Work in the selected source while retaining the task's project.", projectId: source.projectId, projectWorkspaceId: mismatched.projectWorkspaceId, }, @@ -638,14 +638,21 @@ describeEmbeddedPostgres("pipeline routes", () => { .send({ toStageKey: "in_progress", expectedVersion: 1 }) .expect(200); - expect(moved.body.automationExecution.status).toBe("failed"); + expect(moved.body.automationExecution.status).toBe("succeeded"); const executionId = moved.body.automationExecution.execution.id as string; const [execution] = await db .select() .from(pipelineAutomationExecutions) .where(eq(pipelineAutomationExecutions.id, executionId)); - expect(execution!.executionIssueId).toBeNull(); - expect(execution!.error).toContain("Project workspace must belong to the selected project"); + expect(execution!.executionIssueId).not.toBeNull(); + expect(execution!.error).toBeNull(); + const [issue] = await db.select().from(issues) + .where(eq(issues.id, execution!.executionIssueId!)); + expect(issue).toMatchObject({ + companyId: company.id, + projectId: source.projectId, + projectWorkspaceId: mismatched.projectWorkspaceId, + }); }); it("keeps legacy stage automation with only assignee and instructions compatible", async () => { diff --git a/server/src/__tests__/task-workspace-api.test.ts b/server/src/__tests__/task-workspace-api.test.ts index 7af818612ca..7abe2d4646c 100644 --- a/server/src/__tests__/task-workspace-api.test.ts +++ b/server/src/__tests__/task-workspace-api.test.ts @@ -36,4 +36,29 @@ const support = await getEmbeddedPostgresTestSupport(); await expect(f.authority.execute({ tool: "prepare_repository", callId: randomUUID(), arguments: { repository: { kind: "url", url: "https://github.com/public/example" }, requestKey: "denied" } })).rejects.toThrow(); await expect(f.authority.execute({ tool: "select_workspace", callId: randomUUID(), arguments: { selection: { kind: "task_directory" }, expectedBindingRevision: 0, requestKey: "denied" } })).rejects.toThrow(); }); + it("lists shared and isolated task selections and excludes unavailable lifecycle states", async () => { + const f = await server.fixture({ conversation: true, disableWakeOnDemand: true }); + const definitions = [ + { name: "Shared active", mode: "shared_workspace", status: "active", closedAt: null }, + { name: "Shared idle", mode: "shared_workspace", status: "idle", closedAt: null }, + { name: "Isolated idle", mode: "isolated_workspace", status: "idle", closedAt: null }, + { name: "In review", mode: "isolated_workspace", status: "in_review", closedAt: null }, + { name: "Archived", mode: "shared_workspace", status: "archived", closedAt: null }, + { name: "Closed", mode: "shared_workspace", status: "active", closedAt: new Date() }, + ]; + const rows = await server.db.insert(executionWorkspaces).values(definitions.map(definition => ({ + ...definition, companyId: f.companyId, projectId: null, strategyType: "task_directory", cwd: f.workspace, + }))).returning(); + const call = (tool: string, args: Record) => f.authority.execute({ tool, arguments: args, callId: randomUUID() }); + const listed = await call("list_workspaces", {}) as Array<{ id: string }>; + const candidates = new Set(rows.slice(0, 3).map(row => row.id)); + expect(listed.filter(row => rows.some(candidate => candidate.id === row.id)).map(row => row.id).sort()).toEqual([...candidates].sort()); + const view = await call("get_workspace", {}) as { bindingRevision: number }; + for (const row of rows) { + const selection = call("select_workspace", { selection: { kind: "existing", workspaceId: row.id }, + expectedBindingRevision: view.bindingRevision, requestKey: `select-${row.id}` }); + if (candidates.has(row.id)) await expect(selection).resolves.toMatchObject({ kind: "scheduled" }); + else await expect(selection).rejects.toThrow("Workspace is unavailable or inaccessible"); + } + }); }); diff --git a/server/src/__tests__/task-workspace-binding.test.ts b/server/src/__tests__/task-workspace-binding.test.ts index 4acb55fb7e1..368e37b236d 100644 --- a/server/src/__tests__/task-workspace-binding.test.ts +++ b/server/src/__tests__/task-workspace-binding.test.ts @@ -10,6 +10,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { eq } from "drizzle-orm"; import { agents, companies, createDb, executionWorkspaces, issues, projects } from "@paperclipai/db"; import { executionWorkspaceService } from "../services/execution-workspaces.js"; +import { canActorReadExecutionWorkspace } from "../services/authorization.js"; import { deleteCompany } from "../services/company-deletion.js"; import { issueService } from "../services/issues.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; @@ -112,6 +113,36 @@ const support = await getEmbeddedPostgresTestSupport(); expect(workspace?.metadata).toMatchObject({ _issuePrivacySources: { [f.issueId]: true, [secondIssueId]: true } }); }); + it.each(["creation", "selection"] as const)("retains private writers after an existing workspace is installed by %s and then detached", async (installation) => { + vi.stubEnv("PAPERCLIP_ISSUE_PRIVACY_MODE", "enforce"); + try { + const f = await fixture(), svc = executionWorkspaceService(db); + const [project] = await db.insert(projects).values({ companyId: f.companyId, name: "Organization" }).returning(); + const [reader] = await db.insert(agents).values({ companyId: f.companyId, name: "Unrelated reader", adapterType: "process" }).returning(); + const writer = await issueService(db).create(f.companyId, { + title: "Private writer", projectId: project.id, visibility: "private", responsibleUserId: "private-owner", + workspaceSelectionActor: f.actor, + ...(installation === "creation" ? { workspaceSelection: { kind: "existing" as const, workspaceId: f.workspaceId } } : {}), + }); + if (installation === "selection") { + await svc.selectTaskWorkspace({ ...f, issueId: writer.id, selection: { kind: "existing", workspaceId: f.workspaceId }, + expectedBindingRevision: 0, requestKey: "install-existing" }); + await svc.applyPendingTaskWorkspaceSelection({ ...f, issueId: writer.id, runId: randomUUID() }); + } + const installed = await svc.inspectTaskWorkspace(f.companyId, writer.id, f.actor); + expect(installed.workspace?.id).toBe(f.workspaceId); + // No bindTaskWorkspace call or heartbeat is needed: the migration's issue + // binding trigger retains provenance in the same installation transaction. + expect(installed.workspace?.metadata?._issuePrivacySources).toMatchObject({ [writer.id]: true }); + await svc.selectTaskWorkspace({ ...f, issueId: writer.id, selection: { kind: "task_directory" }, + expectedBindingRevision: installed.bindingRevision, requestKey: "detach-private-writer" }); + await svc.applyPendingTaskWorkspaceSelection({ ...f, issueId: writer.id, runId: randomUUID() }); + const [retained] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)); + expect(retained.metadata?._issuePrivacySources).toMatchObject({ [writer.id]: true }); + expect(await canActorReadExecutionWorkspace(db, { type: "agent", agentId: reader.id, companyId: f.companyId }, retained.id)).toBe(false); + } finally { vi.unstubAllEnvs(); } + }); + it("deletes a whole company in source-workspace dependency order", async () => { const f = await fixture(), sourceProjectId = randomUUID(); await db.insert(projects).values({ id: sourceProjectId, companyId: f.companyId, name: "Source policy" }); diff --git a/server/src/__tests__/task-workspace-tools.test.ts b/server/src/__tests__/task-workspace-tools.test.ts index e1fc96868b1..40123b8df48 100644 --- a/server/src/__tests__/task-workspace-tools.test.ts +++ b/server/src/__tests__/task-workspace-tools.test.ts @@ -4,6 +4,12 @@ import { callTaskWorkspaceTool } from "../services/task-workspace-tools.js"; afterEach(() => vi.unstubAllGlobals()); const base = { apiUrl: "https://paperclip.example/api", token: "run-token", companyId: "company", issueId: "task" }; describe("task workspace semantic transport", () => { + it("discovers task-selectable workspaces instead of legacy isolated reuse candidates", async () => { + const fetcher = vi.fn(async () => Response.json([{ id: "shared", mode: "shared_workspace" }])); + vi.stubGlobal("fetch", fetcher); + await expect(callTaskWorkspaceTool({ ...base, name: "list_workspaces", arguments: {} })).resolves.toEqual([{ id: "shared", mode: "shared_workspace" }]); + expect(fetcher.mock.calls[0]).toEqual(["https://paperclip.example/api/companies/company/execution-workspaces?summary=true&selectableForTask=true", expect.objectContaining({ method: "GET" })]); + }); it("uses the normal bound task routes without passing caller identities or interrupt requests", async () => { const fetcher = vi.fn(async () => Response.json({ kind: "scheduled", applies: "next_normal_admission" })); vi.stubGlobal("fetch", fetcher); diff --git a/server/src/routes/execution-workspaces.ts b/server/src/routes/execution-workspaces.ts index 6765d670d94..71a14a7f485 100644 --- a/server/src/routes/execution-workspaces.ts +++ b/server/src/routes/execution-workspaces.ts @@ -137,6 +137,7 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P issueId: req.query.issueId as string | undefined, status: req.query.status as string | undefined, reuseEligible: req.query.reuseEligible === "true", + selectableForTask: req.query.selectableForTask === "true", }; const workspaces = req.query.summary === "true" ? await svc.listSummaries(companyId, filters) diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 42ffdfd2c22..792cc5b9913 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -74,6 +74,8 @@ import { upsertIssueFeedbackVoteSchema, upsertIssueWatchdogSchema, runnerGoalActionRequestSchema, + selectTaskWorkspaceSchema, + prepareWorkspaceRepositorySchema, // Project createProjectSchema, updateProjectSchema, @@ -4247,6 +4249,35 @@ registry.registerPath({ }, }); +registry.registerPath({ + method: "get", + path: "/api/issues/{id}/workspace", + tags: ["issues"], + summary: "Inspect the task workspace and repository preparation state", + request: { params: z.object({ id: z.string().uuid() }) }, + responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound }, +}); + +registry.registerPath({ + method: "put", + path: "/api/issues/{id}/workspace", + tags: ["issues"], + summary: "Select a task workspace for the next normal admission", + description: "Records workspace intent without restarting active work or changing the task's organizational project. Agents may select only for their bound task.", + request: { params: z.object({ id: z.string().uuid() }), body: jsonBody(selectTaskWorkspaceSchema) }, + responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict }, +}); + +registry.registerPath({ + method: "post", + path: "/api/issues/{id}/workspace/repositories", + tags: ["issues"], + summary: "Request repository preparation in the task workspace", + description: "Queues an authorized repository for the next normal admission. The response does not claim the repository is available in an already-running provider session.", + request: { params: z.object({ id: z.string().uuid() }), body: jsonBody(prepareWorkspaceRepositorySchema) }, + responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict }, +}); + registry.registerPath({ method: "get", path: "/api/issues/{id}/watchdog", diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts index 6f215b982f7..e931767e65e 100644 --- a/server/src/services/execution-workspaces.ts +++ b/server/src/services/execution-workspaces.ts @@ -1,3 +1,4 @@ +import { taskWorkspaceSelectableCondition } from "./task-workspace-selection.js"; import { executionWorkspaceRepositoryService } from "./execution-workspace-repositories.js"; import { accessService } from "./access.js"; import { forbidden } from "../errors.js"; @@ -1292,9 +1293,10 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic if (selection.kind === "existing") { const [workspace] = await reader.select().from(executionWorkspaces).where(and( eq(executionWorkspaces.id, selection.workspaceId), eq(executionWorkspaces.companyId, input.companyId), + taskWorkspaceSelectableCondition(), await executionWorkspaceReadSqlCondition(reader, input.actor), )); - if (!workspace || !["active", "idle"].includes(workspace.status)) throw notFound("Workspace is unavailable or inaccessible"); + if (!workspace) throw notFound("Workspace is unavailable or inaccessible"); return { executionWorkspaceId: workspace.id, projectWorkspaceId: workspace.projectWorkspaceId, executionWorkspacePreference: "reuse_existing", executionWorkspaceSettings: { mode: workspace.mode } }; } @@ -1952,6 +1954,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic issueId?: string; status?: string; reuseEligible?: boolean; + selectableForTask?: boolean; readCondition?: SQL; }, ) { @@ -1967,6 +1970,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic if (statuses.length === 1) conditions.push(eq(executionWorkspaces.status, statuses[0]!)); else if (statuses.length > 1) conditions.push(inArray(executionWorkspaces.status, statuses)); } + if (filters?.selectableForTask) conditions.push(taskWorkspaceSelectableCondition()); if (filters?.reuseEligible) { conditions.push(inArray(executionWorkspaces.status, ["active", "idle", "in_review"])); conditions.push(isNull(executionWorkspaces.closedAt)); @@ -2209,6 +2213,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic issueId?: string; status?: string; reuseEligible?: boolean; + selectableForTask?: boolean; readCondition?: SQL; }) => { const conditions = buildListConditions(companyId, filters); @@ -2236,6 +2241,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic issueId?: string; status?: string; reuseEligible?: boolean; + selectableForTask?: boolean; readCondition?: SQL; }) => { const conditions = buildListConditions(companyId, filters); diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 0dec28b9d4f..2f088c14c14 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -4314,10 +4314,9 @@ export function heartbeatService( }, ); const resolvedProjectId = - reusableExistingExecutionWorkspace ? reusableExistingExecutionWorkspace.projectId : executionWorkspace.projectId ?? - issueRef?.projectId ?? - executionProjectId ?? - null; + reusableExistingExecutionWorkspace + ? reusableExistingExecutionWorkspace.projectId + : executionWorkspace.projectId; const resolvedProjectWorkspaceId = resolvedWorkspaceReusePolicy.shouldRestoreExistingWorkspace && reusableExistingExecutionWorkspace?.strategyType === "git_worktree" ? reusableExistingExecutionWorkspace.projectWorkspaceId diff --git a/server/src/services/heartbeat/workspaces.test.ts b/server/src/services/heartbeat/workspaces.test.ts index 7dc7f09f827..f06a1ba1160 100644 --- a/server/src/services/heartbeat/workspaces.test.ts +++ b/server/src/services/heartbeat/workspaces.test.ts @@ -106,6 +106,7 @@ describe("heartbeat workspace module", () => { await fs.mkdir(selectedCwd); const database = databaseWithResults( [{ projectId: "current-project", projectWorkspaceId: "selected-workspace" }], + [{ projectId: "current-project" }], [workspace("default-workspace", "current-project", path.join(testRoot, "missing")), workspace("selected-workspace", "current-project", selectedCwd)], ); const result = await createHeartbeatWorkspaceResolver(database.db).resolveWorkspaceForRun( @@ -114,7 +115,37 @@ describe("heartbeat workspace module", () => { null, ); expect(result).toMatchObject({ cwd: selectedCwd, projectId: "current-project", workspaceId: "selected-workspace", warnings: [], baseCwdFallback: false }); - expect(database.select).toHaveBeenCalledTimes(2); + expect(database.select).toHaveBeenCalledTimes(3); + }); + + it("fails closed with workspace diagnostics when a configured directory is unavailable", async () => { + const missingCwd = path.join(testRoot, "missing-configured-workspace"); + const database = databaseWithResults([workspace("selected", "project-one", missingCwd)]); + await expect(createHeartbeatWorkspaceResolver(database.db).resolveWorkspaceForRun( + agent(), { projectId: "project-one" }, null, + )).rejects.toMatchObject({ + code: "workspace_validation_failed", + resultJson: { workspaceValidation: { + reason: "configured_workspace_unavailable", resolvedProjectId: "project-one", baseCwdFallback: false, + } }, + }); + expect(await fs.stat(missingCwd).catch(() => null)).toBeNull(); + }); + + it("retains materialization diagnostics when a configured repository cannot be cloned", async () => { + const missingRepo = path.join(testRoot, "missing-repository.git"); + const database = databaseWithResults([{ + ...workspace("selected", "project-one", ""), repoUrl: missingRepo, sourceType: "git_remote", + }]); + await expect(createHeartbeatWorkspaceResolver(database.db).resolveWorkspaceForRun( + agent(), { projectId: "project-one" }, null, + )).rejects.toMatchObject({ + code: "workspace_validation_failed", + resultJson: { workspaceValidation: { + reason: "git_worktree_base_materialization_failed", + materializationFailures: [expect.objectContaining({ projectWorkspaceId: "selected", repoUrl: missingRepo, error: expect.any(String) })], + } }, + }); }); it("retains a valid prior session workspace and falls back when it disappears", async () => { diff --git a/server/src/services/heartbeat/workspaces.ts b/server/src/services/heartbeat/workspaces.ts index 10047bd1440..6214663fcaf 100644 --- a/server/src/services/heartbeat/workspaces.ts +++ b/server/src/services/heartbeat/workspaces.ts @@ -2769,6 +2769,13 @@ function buildSessionConfigCategoryValues(input: { // boundary; the reusable row and its evolving generation are state. delete workspaceConfig.existingExecutionWorkspace; delete workspaceConfig.reusableExecutionWorkspaceConfig; + // Binding the first realized workspace persists its already-effective mode + // on the issue. That receipt must not rotate the session on the next turn. + // requestedMode/effectiveMode still fingerprint mode changes, and all other + // issue settings remain part of the compatibility boundary. + const issueSettings = { ...parseObject(workspaceConfig.issueSettings) }; + if (issueSettings.mode === workspaceConfig.requestedMode) delete issueSettings.mode; + workspaceConfig.issueSettings = Object.keys(issueSettings).length ? issueSettings : null; return { adapter: { adapterType: input.adapterType, @@ -3455,7 +3462,26 @@ export function createHeartbeatWorkspaceResolver(db: Db) { missingProjectCwds.push(projectCwd); } - throw new Error(`Configured project workspace is unavailable: ${preferredWorkspaceWarning ?? materializationFailures[0]?.error ?? missingProjectCwds[0] ?? "source could not be prepared"}`); + const connections = materializationFailures.map((failure) => readConnectionFailure(failure.connectionFailure)); + const connectionFailure = connections.length > 0 && connections.every((failure) => failure?.provider === "git") + ? connections[0] as GitConnectionFailure : undefined; + throw new WorkspaceValidationFailure( + `Configured project workspace is unavailable: ${preferredWorkspaceWarning ?? materializationFailures[0]?.error ?? missingProjectCwds[0] ?? "source could not be prepared"}. Repair the configured path or repository access, then retry.`, + { + ...(connectionFailure ? { connectionFailure } : {}), + workspaceValidation: { + reason: materializationFailures.length > 0 ? "git_worktree_base_materialization_failed" : "configured_workspace_unavailable", + issueId, + issueProjectId, + issueProjectWorkspaceId: preferredProjectWorkspaceId, + resolvedWorkspaceSource: "project_primary", + resolvedProjectId, + resolvedProjectWorkspaceId: preferredWorkspace?.id ?? null, + baseCwdFallback: false, + materializationFailures, + }, + }, + ); } const sessionCwd = readNonEmptyString(previousSessionParams?.cwd); diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index 018c93dafaa..39471e2da24 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -103,7 +103,10 @@ describe("PaperclipRunnerToolAuthority", () => { issueId, runId, }); - expect(authority.definitions()).toHaveLength(44); + expect(authority.definitions()).toHaveLength(48); + expect(authority.definitions().map(tool => tool.name)).toEqual(expect.arrayContaining([ + "get_workspace", "list_workspaces", "select_workspace", "prepare_repository", + ])); expect(authority.definitions().map(tool => tool.name)).not.toContain("read_chat_attachment"); expect(authority.definitions().map(tool => tool.name)).not.toContain("read_current_wake_comments"); const questions = authority.definitions().find(tool => tool.name === "request_human_input")!; diff --git a/server/src/services/task-workspace-selection.ts b/server/src/services/task-workspace-selection.ts new file mode 100644 index 00000000000..1a2c235a9de --- /dev/null +++ b/server/src/services/task-workspace-selection.ts @@ -0,0 +1,10 @@ +import { and, inArray, isNull } from "drizzle-orm"; +import { executionWorkspaces } from "@paperclipai/db"; + +/** Lifecycle eligibility shared by discovery and selection; callers add scope and privacy. */ +export function taskWorkspaceSelectableCondition() { + return and( + inArray(executionWorkspaces.status, ["active", "idle"]), + isNull(executionWorkspaces.closedAt), + )!; +} diff --git a/server/src/services/task-workspace-tools.ts b/server/src/services/task-workspace-tools.ts index 06b6658fd0c..5a97a0991d4 100644 --- a/server/src/services/task-workspace-tools.ts +++ b/server/src/services/task-workspace-tools.ts @@ -13,7 +13,7 @@ export async function callTaskWorkspaceTool(input: { name: string; arguments: Re let body: unknown; switch (input.name) { case "get_workspace": break; - case "list_workspaces": route = `/companies/${input.companyId}/execution-workspaces?summary=true&reuseEligible=true`; break; + case "list_workspaces": route = `/companies/${input.companyId}/execution-workspaces?summary=true&selectableForTask=true`; break; case "select_workspace": method = "PUT"; body = selectTaskWorkspaceSchema.parse(input.arguments); break; case "prepare_repository": method = "POST"; route += "/repositories"; body = prepareWorkspaceRepositorySchema.parse(input.arguments); break; default: throw badRequest("Unknown workspace tool");