Files
PaperClipAI/server/src/__tests__/agent-project-access.test.ts
T
Dotta e7ed0c2f93 fix(workspaces): reconcile project-derived workspace bindings when a task moves projects (#23293)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a task is created in a project without explicit workspace
overrides, Paperclip derives `projectWorkspaceId`,
`executionWorkspaceSettings`, and a project-derived `workspaceSelection`
(`source: "project"`).
> - Moving that unbound task to a different project via `issues.update`
left the old project's `projectWorkspaceId` and `workspaceSelection`
behind.
> - Subsequent runs kept resolving back to the old project's workspace
and storage owner, causing repeated workspace validation or
storage-incompatibility failures even after the user moved the task to a
compatible project.
> - This pull request re-derives project-derived workspace bindings when
an unbound task moves projects, and reconciles already-moved unbound
tasks with stale `source: "project"` bindings at run admission while
preserving explicit workspace selections and bound execution workspaces.
> - The benefit is that moving an unbound task to a compatible project
immediately lets it run on the new project's workspace without hidden
stale-workspace failures.

## Linked Issues or Issue Description

Related: #17552, #22849.

**What happened?**

When a task was created in a project, `issues.create` automatically set
`projectWorkspaceId` and `workspaceSelection` with `source: "project"`.
If the task failed before binding an execution workspace
(`executionWorkspaceId === null`) and the user moved the task to a
different project (for example from a Core-storage project to a
plugin-storage project), `issues.update` updated `projectId` but left
`projectWorkspaceId` and `workspaceSelection` pointing to the old
project's workspace. Every subsequent run still resolved the old
project's workspace and storage policy and failed.

**Expected behavior**

- Moving an unbound task whose workspace binding is project-derived
(`source: "project"`, or a legacy `projectWorkspaceId` belonging to the
previous project with no `workspaceSelection`) re-derives
`projectWorkspaceId`, `workspaceSelection`, and
`executionWorkspaceSettings` from the new project (or clears them when
moving to no project or a sourceless project).
- Explicit workspace selections (`source !== "project"`), bound
execution workspaces (`executionWorkspaceId != null`), pending workspace
selections, and tasks with an active running run or pending workspace
recovery keep their current workspace binding.
- Tasks already moved on an older release with a stale `source:
"project"` binding pointing to a different project are reconciled at run
admission before workspace preparation.

**Steps to reproduce**

1. Create a Core-storage project A with a Git workspace and a
plugin-storage project B with a Git workspace.
2. Create an isolated task in project A (so `issues.create` sets
`workspaceSelection.source = "project"`).
3. Move the task to project B via `issueService.update(id, { projectId:
projectB.id })`.
4. Before this fix, `projectWorkspaceId` and
`workspaceSelection.selection.projectWorkspaceId` still point to project
A's workspace.

**Paperclip version or commit**

Reproduced against `origin/master` at `2d764bebc6ed`.

**Deployment mode**

Self-hosted / Cloud server. Verified locally on macOS arm64 with
embedded PostgreSQL.

## What Changed

- `server/src/services/project-move-workspace-reconciliation.ts`: add
focused helpers (`isProjectDerivedWorkspaceBindingStale`,
`deriveProjectDefaultWorkspaceBinding`,
`hasActiveTaskWorkspaceRunHolder`) shared between issue updates and run
admission.
- `server/src/services/execution-workspaces.ts`: add
`reconcileProjectWorkspaceForProjectMove` (used by `issues.update`) and
`reconcileStaleProjectWorkspaceAtAdmission` (used at run admission for
already-moved tasks with stale `source: "project"` bindings). Keeping
the shared reconciliation helpers in a sibling module avoids growing
`execution-workspaces.ts` and `issues.ts` unnecessarily.
- `server/src/services/issues.ts`: invoke
`reconcileProjectWorkspaceForProjectMove` inside `issues.update` after
`changesPrivacy` when `projectId` changes and no explicit workspace
fields were supplied.
- `server/src/services/heartbeat.ts`: invoke
`reconcileStaleProjectWorkspaceAtAdmission` alongside
`releaseAncestorWorkspaceBindingAtAdmission` at run admission, marking
`workspaceSelectionChanged = true` when reconciled.
- `server/src/__tests__/issue-project-move-workspace.test.ts`: add
red-green database regressions for moving to another project, moving to
a sourceless/null project, preserving explicit selections, preserving
bound `executionWorkspaceId`, deferring mid-run moves, and reconciling
already-moved tasks at admission.
- `server/src/__tests__/agent-project-access.test.ts`: use `source:
"explicit"` for the explicitly-retained-source denial test and add a
companion test verifying `source: "project"` re-derives on project move.

## Verification

- **Red (before production edits)**:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-project-move-workspace.test.ts` failed on
`re-derives a project-derived workspace when moving an unbound task to
another project` and `clears a project-derived workspace when moving to
no project or a sourceless project` because `projectWorkspaceId` and
`workspaceSelection` stayed pinned to the old project.
- **Green (after production edits)**:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-project-move-workspace.test.ts
src/__tests__/agent-project-access.test.ts` — 20/20 passed.
  - `pnpm --filter @paperclipai/server typecheck` — passed.
  - `pnpm --filter @paperclipai/server build` — passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/heartbeat/workspace-preparation.test.ts -t "names
incompatible Core project storage|rejects Core Git worktree
preparation"` — 2/2 passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/task-interruption-presentation.test.ts` — 82/82 passed.
- `pnpm verify --explain` selected 1978/2333 files due to touching
central server services; required GitHub Actions CI supplies the broad
suite coverage.
- Live deployment and recovery of previously affected tasks on hosted
instances are outside this PR's scope.

## Risks

- Low risk. Reconciliation is gated to unbound tasks
(`executionWorkspaceId == null`, `workspacePendingSelection == null`)
with no active run holder or pending workspace recovery, and never
alters explicit (`source !== "project"`) workspace selections or bound
files.
- Moving a task to a project whose trust boundary currently denies the
assigned agent will not fail the move; execution access remains enforced
at run admission.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use,
shell execution, and local test verification. Exact deployment model ID
and context window are not exposed to the session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-11-30 15:44:28 +00:00

250 lines
21 KiB
TypeScript

import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agents, agentWakeupRequests, activityLog, authUsers, companies, companyMemberships, createDb,
executionWorkspaces, heartbeatRuns, issues, projects, projectWorkspaces, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
import { registerAgentProjectAccessRoutes } from "../routes/agent-project-access.js";
import { errorHandler } from "../middleware/error-handler.js";
import { assertTaskWorkspaceExecutionAccess, assertTaskWorkspaceSourceProjectAccess } from "../services/task-workspace-access.js";
import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js";
import { ProjectAccessDeniedError } from "../services/project-access-denial.js";
import { issueService } from "../services/issues.js";
import { executionWorkspaceService } from "../services/execution-workspaces.js";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
describe("additive project access", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
let db: ReturnType<typeof createDb>;
beforeAll(async () => {
const external = process.env.PAPERCLIP_TEST_DATABASE_URL;
if (external) db = createDb(external);
else { database = await startEmbeddedPostgresTestDatabase("agent-project-access-"); db = createDb(database.connectionString); }
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
async function seed() {
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Project access", issuePrefix: `A${companyId.slice(0, 6)}` });
const selected = await db.insert(projects).values(["Existing", "Needed", "Third"].map(name => ({ companyId, name }))).returning();
const permissions = { canCreateAgents: false, canCreateSkills: false, trustPreset: "low_trust_review",
authorizationPolicy: { reviewPreset: { id: "low_trust_review", version: 1, rawOutputDisposition: "quarantine" },
customPolicy: { preserve: true }, trustBoundary: { mode: "low_trust_review", companyId,
projectIds: [selected[0]!.id], issueIds: [issueId], allowedToolClasses: ["git.read"], allowedSecretBindingIds: [] } } };
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process", status: "idle", permissions });
await db.insert(companyMemberships).values({ companyId, principalType: "agent", principalId: agentId, membershipRole: "member", status: "active" });
const [issue] = await db.insert(issues).values({ id: issueId, companyId, title: "Saved message", status: "blocked", assigneeAgentId: agentId, projectId: selected[1]!.id }).returning();
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, issueId, status: "failed", errorCode: "setup_failed",
error: "Project is outside this low-trust boundary.", contextSnapshot: { issueId } });
return { companyId, agentId, issue: issue!, runId, selected, permissions };
}
function app(actor: express.Request["actor"]) {
const app = express(); app.use(express.json()); app.use((req, _res, next) => { req.actor = actor; next(); });
registerAgentProjectAccessRoutes(app, db); app.use(errorHandler); return app;
}
const board = { type: "board" as const, source: "local_implicit" as const };
it("keeps a historical denial blocked after the task moves to an allowed project but explicitly retains its source", async () => {
const f = await seed();
const [source] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.selected[1]!.id,
name: "Original repository", cwd: "/tmp/project-access-original" }).returning();
await db.update(issues).set({ projectWorkspaceId: source!.id,
workspaceSelection: { version: 1, source: "explicit", selection: {
kind: "configured_source", projectWorkspaceId: source!.id, mode: "managed_isolated",
} } }).where(eq(issues.id, f.issue.id));
const moved = await issueService(db).update(f.issue.id, { projectId: f.selected[0]!.id });
expect(moved).toMatchObject({ projectId: f.selected[0]!.id, projectWorkspaceId: source!.id });
const actor = { type: "agent" as const, source: "agent_key" as const, agentId: f.agentId, companyId: f.companyId };
await expect(assertTaskWorkspaceExecutionAccess(db, actor, f.companyId, { issueId: f.issue.id }))
.rejects.toBeInstanceOf(ProjectAccessDeniedError);
expect(await taskInterruptionPresentation(db, moved!)).toMatchObject({
canRetry: false, userAction: "project_access", projectAccess: { ready: false, projectId: null },
});
expect((await request(app(board)).post(`/agents/${f.agentId}/project-access`)
.send({ projectIds: [f.selected[1]!.id] })).status).toBe(200);
expect(await taskInterruptionPresentation(db, moved!)).toMatchObject({ canRetry: true, projectAccess: { ready: true } });
await expect(assertTaskWorkspaceExecutionAccess(db, actor, f.companyId, { issueId: f.issue.id })).resolves.toBeDefined();
});
it("re-derives a project-derived workspace source when moving an unbound task to an allowed project", async () => {
const f = await seed();
const [deniedSource] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.selected[1]!.id,
name: "Original repository", cwd: "/tmp/project-access-original" }).returning();
const [allowedSource] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.selected[0]!.id,
name: "Allowed repository", cwd: "/tmp/project-access-allowed" }).returning();
await db.update(issues).set({ projectWorkspaceId: deniedSource!.id,
workspaceSelection: { version: 1, source: "project", selection: {
kind: "configured_source", projectWorkspaceId: deniedSource!.id, mode: "managed_isolated",
} } }).where(eq(issues.id, f.issue.id));
const moved = await issueService(db).update(f.issue.id, { projectId: f.selected[0]!.id });
expect(moved).toMatchObject({ projectId: f.selected[0]!.id, projectWorkspaceId: allowedSource!.id });
const actor = { type: "agent" as const, source: "agent_key" as const, agentId: f.agentId, companyId: f.companyId };
await expect(assertTaskWorkspaceExecutionAccess(db, actor, f.companyId, { issueId: f.issue.id })).resolves.toBeDefined();
expect(await taskInterruptionPresentation(db, moved!)).toMatchObject({ canRetry: true, projectAccess: { ready: true } });
});
it.each(["applied", "pending"] as const)("rechecks the selected source after an %s repair instead of the old denied project", async repair => {
const f = await seed();
const [source] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.selected[0]!.id,
name: "Allowed repository", cwd: "/tmp/project-access-allowed" }).returning();
await db.update(heartbeatRuns).set({ errorCode: "project_access_denied", error: null,
resultJson: { projectAccessDenied: { projectId: f.selected[1]!.id } } }).where(eq(heartbeatRuns.id, f.runId));
const moved = await issueService(db).update(f.issue.id, { projectId: f.selected[0]!.id });
if (repair === "applied") {
await issueService(db).update(f.issue.id, { projectWorkspaceId: source!.id, workspaceSelectionActor: board });
} else {
await executionWorkspaceService(db).selectTaskWorkspace({ companyId: f.companyId, issueId: f.issue.id, actor: board,
selection: { kind: "configured_source", projectWorkspaceId: source!.id, mode: "managed_isolated" },
expectedBindingRevision: 0, requestKey: randomUUID() });
}
expect(await taskInterruptionPresentation(db, moved!)).toMatchObject({ canRetry: true, projectAccess: { ready: true } });
// The original denied source was not granted, and presentation creates no execution.
expect((await db.select().from(agents).where(eq(agents.id, f.agentId)))[0]!.permissions).toEqual(f.permissions);
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toHaveLength(0);
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(1);
if (repair === "pending") {
await db.update(issues).set({ workspaceBindingRevision: 2 }).where(eq(issues.id, f.issue.id));
const stale = await taskInterruptionPresentation(db, moved!);
expect(stale).toMatchObject({ state: "failed", canRetry: false, userAction: null });
expect(stale).not.toHaveProperty("projectAccess");
}
});
it("keeps a pending existing selection blocked if its workspace is archived before retry", async () => {
const f = await seed();
const task = await issueService(db).update(f.issue.id, { projectId: f.selected[0]!.id });
const [workspace] = await db.insert(executionWorkspaces).values({ companyId: f.companyId,
projectId: f.selected[0]!.id, name: "Selected files", cwd: "/tmp/project-access-selected",
mode: "isolated_workspace", strategyType: "git_worktree" }).returning();
const service = executionWorkspaceService(db);
await service.selectTaskWorkspace({ companyId: f.companyId, issueId: f.issue.id, actor: board,
selection: { kind: "existing", workspaceId: workspace!.id }, expectedBindingRevision: 0, requestKey: randomUUID() });
expect(await taskInterruptionPresentation(db, task!)).toMatchObject({ canRetry: true, projectAccess: { ready: true } });
expect(await service.archiveWorkspaceUnderLifecycleLock({ id: workspace!.id, patch: {}, closedAt: new Date() }))
.toMatchObject({ outcome: "archived" });
await expect(service.applyPendingTaskWorkspaceSelection({ companyId: f.companyId, issueId: f.issue.id,
runId: f.runId, actor: { type: "agent", source: "agent_key", agentId: f.agentId, companyId: f.companyId } }))
.rejects.toThrow("Workspace is unavailable or inaccessible");
const archived = await taskInterruptionPresentation(db, task!);
expect(archived).toMatchObject({ state: "failed", canRetry: false, userAction: null });
expect(archived).not.toHaveProperty("projectAccess");
});
it.each(["denied_project", "foreign_company"] as const)("retains the %s gate on a bound workspace even when its source is allowed", async boundary => {
const f = await seed(), foreign = boundary === "foreign_company" ? await seed() : null;
const [source] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.selected[0]!.id,
name: "Allowed source", cwd: "/tmp/project-access-source" }).returning();
const [workspace] = await db.insert(executionWorkspaces).values({ companyId: foreign?.companyId ?? f.companyId,
projectId: foreign?.selected[0]!.id ?? f.selected[1]!.id, projectWorkspaceId: foreign ? null : source!.id,
name: "Retained files", cwd: "/tmp/project-access-bound", mode: "isolated_workspace", strategyType: "git_worktree" }).returning();
const [task] = await db.update(issues).set({ projectId: f.selected[0]!.id, projectWorkspaceId: source!.id,
executionWorkspaceId: workspace!.id }).where(eq(issues.id, f.issue.id)).returning();
const blocked = await taskInterruptionPresentation(db, task!);
if (boundary === "denied_project") {
expect(blocked).toMatchObject({ canRetry: false,
userAction: "project_access", projectAccess: { ready: false, projectId: null } });
} else {
expect(blocked).toMatchObject({ state: "failed", canRetry: false, userAction: null });
expect(blocked).not.toHaveProperty("projectAccess");
}
});
it("preserves containment, audits concurrent additions, and changes the persisted denial into an explicit retry", async () => {
const f = await seed();
const actor = { type: "agent" as const, source: "agent_key" as const, agentId: f.agentId, companyId: f.companyId };
await expect(assertTaskWorkspaceSourceProjectAccess(db, actor, f.companyId, f.selected[1]!.id)).rejects.toBeInstanceOf(ProjectAccessDeniedError);
expect(await taskInterruptionPresentation(db, f.issue)).toMatchObject({ userAction: "project_access", canRetry: false });
const api = app(board);
const results = await Promise.all(f.selected.slice(1).map(project => request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [project.id] })));
expect(results.map(result => result.status)).toEqual([200, 200]);
const [saved] = await db.select().from(agents).where(eq(agents.id, f.agentId));
expect(saved!.permissions).toEqual({ ...f.permissions, authorizationPolicy: { ...f.permissions.authorizationPolicy,
trustBoundary: { ...f.permissions.authorizationPolicy.trustBoundary, projectIds: expect.arrayContaining(f.selected.map(project => project.id)) } } });
expect((saved!.permissions as typeof f.permissions).authorizationPolicy.trustBoundary.projectIds).toHaveLength(3);
await expect(assertTaskWorkspaceSourceProjectAccess(db, actor, f.companyId, f.selected[1]!.id)).resolves.toBeUndefined();
expect(await taskInterruptionPresentation(db, f.issue)).toMatchObject({ canRetry: true, projectAccess: { ready: true } });
const again = await request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [f.selected[1]!.id] });
expect(again.status).toBe(200);
expect(await db.select().from(activityLog).where(and(eq(activityLog.companyId, f.companyId), eq(activityLog.action, "agent.project_access_added")))).toHaveLength(2);
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toHaveLength(0);
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(1);
});
it("rejects foreign projects, agent self-grants, unknown policy fields, and pending-approval agents", async () => {
const f = await seed(), other = await seed(), api = app(board);
expect((await request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [other.selected[1]!.id] })).status).toBe(404);
expect((await request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [f.selected[1]!.id], trustPreset: "standard" })).status).toBe(400);
expect((await request(app({ type: "agent", agentId: f.agentId, companyId: f.companyId, source: "agent_key" }))
.post(`/agents/${f.agentId}/project-access`).send({ projectIds: [f.selected[1]!.id] })).status).toBe(403);
await db.update(agents).set({ status: "pending_approval" }).where(eq(agents.id, f.agentId));
expect((await request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [f.selected[1]!.id] })).status).toBe(409);
const [saved] = await db.select().from(agents).where(eq(agents.id, f.agentId)); expect(saved!.permissions).toEqual(f.permissions);
});
it.each(["standard", "root_issue"])("rechecks actual project authority after a %s repair and acknowledges an accepted retry", async repair => {
const f = await seed();
const permissions = repair === "standard" ? { canCreateAgents: false, trustPreset: "standard", authorizationPolicy: {} }
: { ...f.permissions, authorizationPolicy: { ...f.permissions.authorizationPolicy,
trustBoundary: { ...f.permissions.authorizationPolicy.trustBoundary, rootIssueId: f.issue.id } } };
await db.update(agents).set({ permissions }).where(eq(agents.id, f.agentId));
expect(await taskInterruptionPresentation(db, f.issue)).toMatchObject({ canRetry: true, projectAccess: { ready: true } });
await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId,
source: "on_demand", status: "deferred_issue_execution", requestedByActorType: "user", payload: { issueId: f.issue.id } });
const accepted = await taskInterruptionPresentation(db, f.issue);
expect(accepted).toMatchObject({ state: "working", canRetry: false });
expect(accepted).not.toHaveProperty("projectAccess");
// Current project policy remains authoritative even after agent access changes.
await db.update(projects).set({ executionWorkspacePolicy: { trustPreset: "low_trust_review", authorizationPolicy: {
trustBoundary: { mode: "low_trust_review", companyId: f.companyId, projectIds: [f.selected[0]!.id] },
} } }).where(eq(projects.id, f.selected[1]!.id));
if (repair === "standard") expect(await taskInterruptionPresentation(db, f.issue))
.toMatchObject({ canRetry: false, userAction: "project_access" });
});
it("shows read-only access to viewers and denies their saves and cross-company reads", async () => {
const f = await seed(), other = await seed(), userId = randomUUID();
await db.insert(authUsers).values({ id: userId, name: "Viewer", email: `${userId}@example.test`, emailVerified: true, createdAt: new Date(), updatedAt: new Date() });
await db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: userId, membershipRole: "viewer", status: "active" });
const api = app({ type: "board", source: "session", userId, companyIds: [f.companyId], memberships: [{ companyId: f.companyId, membershipRole: "viewer", status: "active" }] });
expect((await request(api).get(`/agents/${f.agentId}/project-access`)).body).toMatchObject({ canManage: false });
expect((await request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [f.selected[1]!.id] })).status).toBe(403);
expect((await request(api).get(`/agents/${other.agentId}/project-access`)).status).toBe(404);
});
it("runs a private task in its owner's personal project without granting that project", async () => {
const companyId = randomUUID(), agentId = randomUUID(), ownerId = `owner-${randomUUID()}`;
await db.insert(companies).values({ id: companyId, name: "Personal private tasks", issuePrefix: `P${companyId.slice(0, 6)}` });
await db.insert(agents).values({ id: agentId, companyId, name: "CEO", adapterType: "process", status: "idle" });
await db.insert(companyMemberships).values({ companyId, principalType: "agent", principalId: agentId, membershipRole: "member", status: "active" });
const [personal, shared] = await db.insert(projects).values([
{ companyId, name: "My private tasks", visibility: "private", personalOwnerUserId: ownerId, privacyOwnerUserId: ownerId },
{ companyId, name: "Private team project", visibility: "private", privacyOwnerUserId: ownerId },
]).returning();
const task = async (projectId: string) => (await db.insert(issues).values({ companyId, title: "Private chat", status: "todo",
assigneeAgentId: agentId, projectId, visibility: "private", responsibleUserId: ownerId }).returning())[0]!;
const actor = { type: "agent" as const, source: "agent_key" as const, agentId, companyId };
const personalTask = await task(personal!.id);
await db.update(issues).set({ privacyRootIssueId: personalTask.id }).where(eq(issues.id, personalTask.id));
// The agent can work the task it was given; the personal project stays unreadable.
await expect(assertTaskWorkspaceExecutionAccess(db, actor, companyId, { issueId: personalTask.id })).resolves.toMatchObject({ task: { id: personalTask.id } });
await expect(assertTaskWorkspaceSourceProjectAccess(db, actor, companyId, personal!.id)).rejects.toThrow(/not an access member/);
// An execution workspace from the personal project is not a bare container.
const [ownerFiles] = await db.insert(executionWorkspaces).values({ companyId, projectId: personal!.id, name: "Owner workspace",
cwd: "/tmp/personal-owner-workspace", mode: "isolated_workspace", strategyType: "git_worktree" }).returning();
await db.update(issues).set({ executionWorkspaceId: ownerFiles!.id }).where(eq(issues.id, personalTask.id));
await expect(assertTaskWorkspaceExecutionAccess(db, actor, companyId, { issueId: personalTask.id, workspaceId: ownerFiles!.id }))
.rejects.toThrow(/not an access member/);
await db.update(issues).set({ executionWorkspaceId: null }).where(eq(issues.id, personalTask.id));
// A shared private project, or a personal project that provides files, still needs membership.
const sharedTask = await task(shared!.id);
await db.update(issues).set({ privacyRootIssueId: sharedTask.id }).where(eq(issues.id, sharedTask.id));
await expect(assertTaskWorkspaceExecutionAccess(db, actor, companyId, { issueId: sharedTask.id })).rejects.toThrow(/not an access member/);
await db.insert(projectWorkspaces).values({ companyId, projectId: personal!.id, name: "Owner files", cwd: "/tmp/personal-owner-files" });
await expect(assertTaskWorkspaceExecutionAccess(db, actor, companyId, { issueId: personalTask.id })).rejects.toThrow(/not an access member/);
});
});