Files
PaperClipAI/server/src/services/heartbeat/environment-selection.test.ts
T
Nicky LeachandClaude Opus 5.5 369e238295 fix(projects): make workspace storage the project's only placement choice (#20835)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A repository project gets its working files from core staging or
from a workspace storage plugin
> - #20459 reported that an installed storage plugin attached every new
repository project, so sandbox agents could not use those projects
> - #20587 fixed creation with an **Available in** choice that selects
storage
> - #20651 then saved an environment on every new project and used it
before the agent default to place runs. That solved a problem that did
not exist: the project needs storage, not a run environment
> - Creation saves the first environment of the chosen group, so a
project silently sends every agent's runs to that environment. Project
Configuration also shows two controls (Environment and Workspace
storage) for one decision
> - This pull request removes the project run environment and makes
storage the only placement choice a project owns. Storage is fixed at
creation
> - The benefit is that runs follow the agent again, and project
settings show one clear, read-only fact about storage

## Linked Issues or Issue Description

Refs #20459. Follow-up to #20587 and #20651.

Refs #11644. That issue asks for a project-level run environment
override. This pull request removes the override that #20651 added for
it, because the override is not necessary to fix #20459. #11644 stays a
separate feature request.

Related: #18176 (open) repairs placement through the legacy
workspace-policy field. This pull request does not restore project
placement, so it conflicts with the direction of #18176.

## What Changed

- **Remove the project run environment.** Migration `0466` drops
`projects.environment_id`. Run placement no longer reads the project.
Runs use the agent default, then the instance default, then local
execution. The low-trust task sandbox and the enforced sandbox policies
keep their precedence.
- **Keep the #20651 recovery and binding guards.** A recovered run still
uses its admitted environment lease (source `run`). Company-binding
checks before admission and during lease creation stay.
- **Keep the creation choice.** **Available in** in New Project still
selects storage. It still shows only when the environments need more
than one storage owner. That can only occur when a storage plugin is
installed. `POST /projects` with `environmentId` selects the storage of
that environment and does not save the environment.
- **Fix storage at creation.** `PATCH /projects/:id` rejects any storage
change with `409 project_storage_locked`, from core to a plugin and from
a plugin to core. Before, a core project could move to a plugin.
- **Drop legacy writes.** Older clients can still send
`executionWorkspacePolicy.environmentId`. The service removes it on
create and update.
- **Simplify Project Configuration.** Remove the Environment and
Workspace storage selectors. Show an advisory **Available in** list of
the environments that can use the project's storage. Show it when a
storage plugin is installed or when the project uses one. When the
project's plugin is not installed, show **Storage plugin unavailable**.
Without a storage plugin, show nothing.
- **Issue workspace card.** Remove the "project default" environment
label.
- **Shared contract.** Remove `Project.environmentId`, the
`environmentId` project field, and `expectedStorageProviderPluginId`
from the update schema. The create schema keeps `environmentId` and
`expectedStorageProviderPluginId` from #20587.
- **Docs and maps.** Update `doc/project-environment-compatibility.md`,
`docs/api/goals-and-projects.md`, and the project feature and
agent-access maps.
- **SDK source pins.** Refresh
`tests/runner-e2e/source-sdk-public-inputs.json` for the two shared
files. The shared file blobs return to their values before #20651. The
refresh also corrects the `pnpm-lock.yaml` pin and `lockSha256`:
`master` pins an older lockfile blob than the one it contains.

## Verification

- Targeted server suites pass (227 tests): `project-environments`,
`project-workspace-provider.integration`,
`heartbeat/environment-selection`, `execution-workspace-policy`,
`environment-selection-route-guards`, `environment-run-orchestrator`,
`openapi-routes`.
- Related server suites pass (349 tests): `environment-service`,
`environment-routes`, `plugin-workspaces.integration`, `issues-service`.
- Targeted UI suites pass: `ProjectProperties.concurrency`,
`IssueWorkspaceCard`, `NewProjectDialog`,
`NewProjectDialog.managed-sandbox`, `ProjectDetail`.
- New tests:
- Creation saves storage, not an environment. Core and plugin projects
both reject a storage change with `project_storage_locked`.
  - A legacy policy `environmentId` is dropped on create and update.
- A new run follows the agent default for any project. A recovered run
keeps its admitted lease after the agent default changes.
- Project Configuration has no storage or environment selector. The note
is hidden without a plugin. It lists the core or plugin environments for
the project's storage. It shows **Storage plugin unavailable** for a
removed plugin.
- `pnpm --filter @paperclipai/server typecheck`, `pnpm --filter
@paperclipai/ui typecheck`, and `pnpm --filter @paperclipai/shared
typecheck` pass.
- `pnpm --filter @paperclipai/db check:migrations`, `pnpm
check:token-gates`, `node scripts/check-maps.mjs`, and `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check` pass.
- Not run locally: the full `pnpm test:run`, `pnpm build`, and browser
suites. CI supplies that coverage.
- Manual check: open Project Configuration on an instance with a storage
plugin. Confirm that there is no Environment or Workspace storage
selector, and that **Available in** lists the environments.

## Risks

- **Migration.** `0466` drops `projects.environment_id` and its foreign
key. The migration deletes the saved project environments. Apply it
before you serve the new revision. An old server revision that reads
`projects` fails until it stops. This is the same pattern as earlier
drop-column migrations (`0229`, `0289`).
- **Behavior change for existing projects.** Projects created after
#20651 shipped have a saved environment that overrides the agent. After
this change, their runs follow the agent default again. This is the
intended fix. Before #20651, a project environment selection was not
applied to runs (#11644), so no older behavior is lost.
- **No path from core to a plugin.** A core project, including one
created before a plugin was installed, cannot move to the plugin. To use
plugin storage, create a new project.
- **API.** A `PATCH` that sends `environmentId` or
`expectedStorageProviderPluginId` no longer has an effect. The schema
strips these fields.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) by Anthropic, in Claude Code, with
tool use (shell, file edits, test runs). Extended thinking was
available.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:00:21 -08:00

362 lines
24 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { mkdtemp, mkdir, rm, writeFile, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { agents, companies, createDb, environments, environmentLeases, heartbeatRuns, issues, projects, projectWorkspaces, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, type Db } from "@paperclipai/db";
import { eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { resolvePaperclipInstanceRoot } from "../../home-paths.js";
import { environmentService } from "../environments.js";
import { executionWorkspaceService } from "../execution-workspaces.js";
import { instanceSettingsService } from "../instance-settings.js";
import { buildNativeExecutionInput } from "../native-runtime/native-execution-input.js";
import { nativeRuntimeContextFixture } from "../native-runtime/runtime-context.test-fixture.js";
import { selectHeartbeatEnvironment, type HeartbeatEnvironmentSelectionInput } from "./environment-selection.js";
import { materializeIsolatedTaskDirectory } from "../isolated-task-directory.js";
const restoration = vi.hoisted(() => ({ removed: false }));
vi.mock("../git-workspace-restoration.js", async importOriginal => {
const actual = await importOriginal<typeof import("../git-workspace-restoration.js")>();
return { ...actual, readGitCacheExpiration: (workspace: Parameters<typeof actual.readGitCacheExpiration>[0]) =>
restoration.removed ? { workspaceRemoved: true } as ReturnType<typeof actual.readGitCacheExpiration> : actual.readGitCacheExpiration(workspace) };
});
const support = await getEmbeddedPostgresTestSupport();
describe.skipIf(!support.supported)("heartbeat environment selection boundary", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
let home: string;
beforeAll(async () => {
home = await mkdtemp(join(tmpdir(), "heartbeat-environment-selection-"));
vi.stubEnv("PAPERCLIP_HOME", home);
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "environment-selection");
await mkdir(resolvePaperclipInstanceRoot(), { recursive: true });
database = await startEmbeddedPostgresTestDatabase("heartbeat-environment-selection-");
db = createDb(database.connectionString);
await db.execute(sql`set client_min_messages = warning`);
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
afterAll(async () => {
await db?.$client.end();
await database?.cleanup();
vi.unstubAllEnvs();
if (home) await rm(home, { recursive: true, force: true });
});
beforeEach(async () => {
await db.execute(sql`truncate table companies restart identity cascade`);
});
async function fixture() {
const [company] = await db.insert(companies).values({ name: "Environment selection", issuePrefix: "ENV" }).returning();
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Selecting agent", status: "running", adapterType: "process" }).returning();
const [project] = await db.insert(projects).values({ companyId: company.id, name: "Project" }).returning();
const [issue] = await db.insert(issues).values({ companyId: company.id, projectId: project.id, title: "Select this environment", assigneeAgentId: agent.id }).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, issueId: issue.id, scopeKind: "issue", status: "running", runtimeMode: "legacy" }).returning();
const input: HeartbeatEnvironmentSelectionInput = {
run, agent,
task: { issueRef: issue, issueContext: issue, issueId: issue.id, executionProjectId: project.id, workspaceProjectContext: { hasWorkspace: false }, boundSourceWorkspace: null, hasSelectedWorkspaceSource: false, taskWorkspaceIntent: null, responsibleUserId: null, context: { issueId: issue.id } },
policy: {
trustPreset: { kind: "standard", preset: "standard", boundary: null, sourcePresets: {} },
requestedExecutionWorkspaceMode: "shared_workspace", isolatedWorkspacesEnabled: true,
projectExecutionWorkspacePolicy: null, issueExecutionWorkspaceSettings: null,
},
config: { config: {}, sourceWorkspaceConfig: {}, issueAssigneeOverrides: null },
services: { environmentsSvc: environmentService(db), executionWorkspacesSvc: executionWorkspaceService(db), instanceSettings: instanceSettingsService(db), findSharedWorkspaceHolder: vi.fn(async () => null), findExecutionWorkspaceHolder: vi.fn(async () => null) },
};
const workspace = async () => {
const created = await executionWorkspaceService(db).create({ companyId: company.id, projectId: project.id, sourceIssueId: issue.id, name: "Saved workspace", mode: "isolated_workspace", strategyType: "git_worktree", cwd: home, providerRef: home });
if (!created) throw new Error("Workspace fixture was not created");
return created;
};
const recover = (workspaceId: string) => {
input.run.runtimeMode = "native";
input.run.runnerProfileJson = { nativeExecutionInput: buildNativeExecutionInput({
companyId: company.id, runId: run.id, agentId: agent.id,
issue: { id: issue.id, identifier: "ENV-1", title: issue.title, description: null, workMode: "standard" },
taskPrompt: "Continue the same task", normalizedSessionId: randomUUID(), provider: "codex",
workspace: { id: workspaceId, cwd: home, repoUrl: null, repoRef: null, branchName: null },
completionContract: { id: randomUUID(), sha256: `sha256:${"a".repeat(64)}`, schemaVersion: "paperclip.run-result.v1", contract: { revision: "1", objective: "Select the environment", criteria: [{ id: "objective", requirement: "Preserve the workspace" }] } },
runtimeContext: nativeRuntimeContextFixture(),
}) };
};
return { input, issue, project, workspace, recover };
}
it("places a new run by the agent default, not by its project", async () => {
const f = await fixture();
const local = await environmentService(db).ensureLocalEnvironment(f.input.agent.companyId);
const [other] = await db.insert(projects).values({ companyId: f.input.agent.companyId, name: "Other project" }).returning();
f.input.agent.defaultEnvironmentId = local.id;
f.input.policy.isolatedWorkspacesEnabled = false;
expect((await selectHeartbeatEnvironment(db, f.input)).environmentResolution).toEqual({ environmentId: local.id, source: "agent" });
f.input.task.executionProjectId = other.id;
expect((await selectHeartbeatEnvironment(db, f.input)).environmentResolution).toEqual({ environmentId: local.id, source: "agent" });
});
it("restores the admitted environment after a default change and rejects a foreign lease", async () => {
const f = await fixture();
const local = await environmentService(db).ensureLocalEnvironment(f.input.agent.companyId);
const [next] = await db.insert(environments).values({ name: `Next target ${randomUUID()}`, driver: "ssh", config: { host: "next.example.test" } }).returning();
const saved = await f.workspace();
f.recover(saved.id);
f.input.agent.defaultEnvironmentId = next.id;
const [lease] = await db.insert(environmentLeases).values({ companyId: f.project.companyId, environmentId: local.id,
heartbeatRunId: f.input.run.id, issueId: f.issue.id, executionWorkspaceId: saved.id, metadata: { agentId: f.input.agent.id } }).returning();
f.input.run.contextSnapshot = { paperclipEnvironment: { id: local.id, leaseId: lease.id } };
expect((await selectHeartbeatEnvironment(db, f.input)).environmentResolution).toEqual({ environmentId: local.id, source: "run" });
await db.update(environmentLeases).set({ metadata: { agentId: randomUUID() } }).where(eq(environmentLeases.id, lease.id));
await expect(selectHeartbeatEnvironment(db, f.input)).rejects.toThrow("Cannot restore the admitted execution environment");
});
it("keeps the admitted workspace binding when the issue points at a newer workspace", async () => {
const { input, workspace, recover } = await fixture();
const original = await workspace();
const newer = await workspace();
input.task.issueRef!.executionWorkspaceId = newer.id;
input.task.issueRef!.executionWorkspacePreference = null;
recover(original.id);
const result = await selectHeartbeatEnvironment(db, input);
expect(result.nativeRecoveryExecutionWorkspaceId).toBe(original.id);
expect(result.reusableExistingExecutionWorkspace?.id).toBe(original.id);
expect(result.requestedShouldReuseExisting).toBe(true);
expect(input.task.issueRef!.executionWorkspaceId).toBe(newer.id);
expect(result.persistedNativeExecutionInput?.binding.executionWorkspaceId).toBe(original.id);
});
it.each(["bound", "issue_moved"] as const)(
"re-prepares a restarted fresh Retry attempt as its task directory, never as a git worktree base (RC-58, %s)", async binding => {
const { input, issue, workspace, recover } = await fixture();
// A project-less task's fresh Retry attempt directory, created and bound by the first preparation.
await db.update(issues).set({ projectId: null }).where(eq(issues.id, issue.id));
const attemptCwd = await materializeIsolatedTaskDirectory({ companyId: input.agent.companyId, issueId: issue.id, attemptId: input.run.id });
const created = await executionWorkspaceService(db).create({ companyId: input.agent.companyId, projectId: null,
sourceIssueId: issue.id, name: "Fresh attempt", mode: "isolated_workspace", strategyType: "project_primary",
providerType: "local_fs", cwd: attemptCwd });
if (!created) throw new Error("Attempt workspace fixture was not created");
await db.update(issues).set({ executionWorkspaceId: created.id, executionWorkspacePreference: "reuse_existing",
executionWorkspaceSettings: { mode: "isolated_workspace" } }).where(eq(issues.id, issue.id));
const issueRef = { ...input.task.issueRef!, projectId: null, executionWorkspaceId: created.id,
executionWorkspacePreference: "reuse_existing" };
input.task.issueRef = issueRef;
input.task.executionProjectId = null;
input.policy.requestedExecutionWorkspaceMode = "isolated_workspace";
input.policy.issueExecutionWorkspaceSettings = { mode: "isolated_workspace" };
if (binding === "issue_moved") issueRef.executionWorkspaceId = (await workspace()).id;
// The restart re-prepares from the admitted native input; readiness is no longer "fresh".
recover(created.id);
input.task.freshWorkspace = null;
const result = await selectHeartbeatEnvironment(db, input);
expect(result.nativeRecoveryExecutionWorkspaceId).toBe(created.id);
expect(result.reusableExistingExecutionWorkspace?.id).toBe(created.id);
// Only the task's current binding may resume as a task directory.
expect(result.useIsolatedTaskDirectory).toBe(binding === "bound");
});
it("selects the saved execution workspace without inspecting live Git delivery state", async () => {
const { input, workspace, recover } = await fixture();
const saved = await workspace();
recover(saved.id);
input.services.executionWorkspacesSvc = executionWorkspaceService(db, {
inspectGitCloseReadiness: async () => {
throw new Error("Live Git inspection is unavailable");
},
});
const result = await selectHeartbeatEnvironment(db, input);
expect(result.reusableExistingExecutionWorkspace).toMatchObject({
id: saved.id,
companyId: input.agent.companyId,
cwd: home,
strategyType: "git_worktree",
});
expect(result.nativeRecoveryExecutionWorkspaceId).toBe(saved.id);
});
it("does not treat a synthetic run-id recovery binding as a persisted workspace", async () => {
const { input, recover } = await fixture();
recover(input.run.id);
const result = await selectHeartbeatEnvironment(db, input);
expect(result).toMatchObject({ existingExecutionWorkspace: null, nativeRecoveryExecutionWorkspaceId: null, requestedShouldReuseExisting: false, reusableExistingExecutionWorkspace: null });
expect(result.persistedNativeExecutionInput?.binding.executionWorkspaceId).toBe(input.run.id);
});
it.each((["resume_stopped_native_workspace", "reuse_issue_workspace"] as const).flatMap(retainedMode =>
["preserved", "changed_binding", "changed_cwd"].map(mode => [retainedMode, mode] as const)))(
"pins the verified Retry workspace during environment selection (%s, %s)", async (retainedMode, mode) => {
const { input, issue, workspace } = await fixture();
const saved = await workspace();
await db.update(issues).set({ executionWorkspaceId: saved.id }).where(eq(issues.id, issue.id));
input.task.issueRef!.executionWorkspaceId = saved.id;
input.task.issueRef!.executionWorkspacePreference = null;
input.task.freshWorkspace = { mode: retainedMode, retryIntentId: randomUUID(),
sourceRunId: randomUUID(), workspaceId: saved.id, cwd: home };
if (mode === "changed_binding") input.task.issueRef!.executionWorkspaceId = (await workspace()).id;
if (mode === "changed_cwd") await executionWorkspaceService(db).update(saved.id, { cwd: join(home, "changed") });
if (mode !== "preserved") {
await expect(selectHeartbeatEnvironment(db, input)).rejects.toThrow("The saved Retry workspace binding changed.");
return;
}
const result = await selectHeartbeatEnvironment(db, input);
expect(result.requestedShouldReuseExisting).toBe(true);
expect(result.reusableExistingExecutionWorkspace).toMatchObject({ id: saved.id, cwd: home });
expect(result.nativeRecoveryExecutionWorkspaceId).toBeNull();
});
it("does not make an archived issue workspace available for reuse", async () => {
const { input, workspace } = await fixture();
const saved = await workspace();
await executionWorkspaceService(db).update(saved.id, { status: "archived" });
input.task.issueRef!.executionWorkspaceId = saved.id;
input.task.issueRef!.executionWorkspacePreference = "reuse_existing";
const result = await selectHeartbeatEnvironment(db, input);
expect(result.requestedShouldReuseExisting).toBe(true);
expect(result.reusableExistingExecutionWorkspace).toBeNull();
expect(result.requestedReusableExecutionWorkspaceConfig).toBeNull();
});
it("restores a reopened task's terminal workspace under its own admitted run", async () => {
const { input, issue, workspace } = await fixture();
const saved = await workspace();
await writeFile(join(home, "saved-work.txt"), "Retain the completed investigation\n");
await executionWorkspaceService(db).update(saved.id, { status: "archived", strategyType: "project_primary",
cleanupReason: "issue_terminal", closedAt: new Date("2020-01-01T00:00:00Z") });
await db.update(issues).set({ executionWorkspaceId: saved.id, executionWorkspacePreference: "reuse_existing" })
.where(eq(issues.id, issue.id));
input.task.issueRef!.executionWorkspaceId = saved.id;
input.task.issueRef!.executionWorkspacePreference = "reuse_existing";
const result = await selectHeartbeatEnvironment(db, input);
expect(result.reusableExistingExecutionWorkspace).toMatchObject({ id: saved.id, status: "active" });
expect(await readFile(join(home, "saved-work.txt"), "utf8")).toBe("Retain the completed investigation\n");
expect(await executionWorkspaceService(db).getStoredById(input.agent.companyId, saved.id))
.toMatchObject({ status: "active", closedAt: null, sourceIssueId: issue.id });
});
describe("workspaces removed by git cache expiration", () => {
async function expired() {
const f = await fixture();
const saved = await f.workspace();
await executionWorkspaceService(db).update(saved.id, { status: "archived" });
f.input.task.issueRef!.executionWorkspaceId = saved.id;
f.input.task.issueRef!.executionWorkspacePreference = "reuse_existing";
await db.update(issues).set({ executionWorkspaceId: saved.id, executionWorkspacePreference: "reuse_existing" }).where(eq(issues.id, f.issue.id));
restoration.removed = true;
const svc = executionWorkspaceService(db);
f.input.services.executionWorkspacesSvc = svc;
return { ...f, saved, svc };
}
it("reopens the issue's expired workspace before the run binds it", async () => {
const { input, issue, saved, svc } = await expired();
const reopen = vi.spyOn(svc, "reopenClosedIsolatedExecutionWorkspaceForIssue").mockImplementation(async () => {
await executionWorkspaceService(db).update(saved.id, { status: "active" });
return { ok: true, reopened: true, workspace: (await svc.getStoredById(issue.companyId, saved.id))!, generation: 4 };
});
const clear = vi.spyOn(svc, "clearReopenPendingConsumptionForUnconsumedReopen").mockResolvedValue({ cleared: true });
try {
const result = await selectHeartbeatEnvironment(db, input);
expect(reopen).toHaveBeenCalledWith(expect.objectContaining({ workspaceId: saved.id,
issue: { id: issue.id, companyId: issue.companyId, projectId: issue.projectId },
authorizationActor: expect.objectContaining({ type: "agent", agentId: input.agent.id, runId: input.run.id }) }));
expect(clear).toHaveBeenCalledWith(expect.objectContaining({ workspaceId: saved.id, expectedGeneration: 4 }));
expect(result.reusableExistingExecutionWorkspace).toMatchObject({ id: saved.id, status: "active" });
} finally { restoration.removed = false; }
});
it("fails the run instead of binding a new workspace when the restore fails", async () => {
const { input, svc } = await expired();
vi.spyOn(svc, "reopenClosedIsolatedExecutionWorkspaceForIssue")
.mockResolvedValue({ ok: false, code: "rebuild_failed", message: "Workspace restore failed" });
try {
await expect(selectHeartbeatEnvironment(db, input)).rejects.toThrow("Workspace restore failed");
} finally { restoration.removed = false; }
});
it("leaves a workspace archived for other reasons alone", async () => {
const { input, svc } = await expired();
restoration.removed = false;
const reopen = vi.spyOn(svc, "reopenClosedIsolatedExecutionWorkspaceForIssue");
const result = await selectHeartbeatEnvironment(db, input);
expect(reopen).not.toHaveBeenCalled();
expect(result.reusableExistingExecutionWorkspace).toBeNull();
});
});
it.each(["muse", "openai_dot", "grok_bot"] as const)("keeps %s managed placement without adopting the task's selected workspace", async provider => {
const { input, issue, workspace } = await fixture();
const source = await workspace();
const [sandbox] = await db.insert(environments).values({ name: `External controller ${provider}`, driver: "sandbox", status: "active", config: { provider: "fake" } }).returning();
input.agent.adapterType = "paperclip_runner";
input.agent.adapterConfig = { provider };
input.agent.defaultEnvironmentId = sandbox.id;
input.task.issueRef!.executionWorkspaceId = source.id;
input.task.issueRef!.projectWorkspaceId = randomUUID();
input.task.boundSourceWorkspace = source;
input.task.workspaceProjectContext = { hasWorkspace: true };
input.task.hasSelectedWorkspaceSource = true;
input.task.taskWorkspaceIntent = { version: 1, source: "explicit", selection: { kind: "task_directory" } };
await db.update(issues).set({ originKind: "chat_channel" }).where(eq(issues.id, issue.id));
const read = vi.spyOn(input.services.executionWorkspacesSvc, "getStoredById").mockRejectedValue(new Error("Task source must remain inaccessible"));
const select = vi.spyOn(input.services.executionWorkspacesSvc, "validateStoredSelectionForRun").mockRejectedValue(new Error("Task selection must remain inaccessible"));
try {
const result = await selectHeartbeatEnvironment(db, input);
expect(result).toMatchObject({ isDotRun: true, selectedEnvironmentId: sandbox.id,
existingExecutionWorkspace: null, reusableExistingExecutionWorkspace: null,
nativeChatWorkspaceScope: null, useIsolatedTaskDirectory: false, explicitTaskDirectory: false });
expect(read).not.toHaveBeenCalled();
expect(select).not.toHaveBeenCalled();
expect(input.services.findSharedWorkspaceHolder).not.toHaveBeenCalled();
expect(input.task.issueRef!.executionWorkspaceId).toBe(source.id);
} finally { read.mockRestore(); select.mockRestore(); }
});
it("uses the low-trust task sandbox even when workspace feature gates hide issue settings", async () => {
const { input, issue } = await fixture();
const [sandbox] = await db.insert(environments).values({ name: "Task sandbox", driver: "sandbox", status: "active", config: { provider: "fake" } }).returning();
input.task.issueContext!.executionWorkspaceSettings = { mode: "isolated_workspace", environmentId: sandbox.id };
input.policy.trustPreset = { kind: "low_trust_review", preset: "low_trust_review", sourcePresets: {}, boundary: { mode: "low_trust_review", companyId: input.agent.companyId, rootIssueId: issue.id } };
input.policy.requestedExecutionWorkspaceMode = "isolated_workspace";
input.policy.isolatedWorkspacesEnabled = false;
const result = await selectHeartbeatEnvironment(db, input);
expect(result.selectedEnvironmentForConfig?.id).toBe(sandbox.id);
expect(result.useIsolatedTaskDirectory).toBe(true);
});
it("returns the task-owned local chat root before workspace realization", async () => {
const { input, issue } = await fixture();
await db.update(issues).set({ originKind: "chat_channel", projectId: null }).where(eq(issues.id, issue.id));
input.agent.adapterType = "paperclip_runner";
input.task.executionProjectId = null;
input.task.workspaceProjectContext = null;
const result = await selectHeartbeatEnvironment(db, input);
expect(result.nativeChatWorkspaceScope).toMatchObject({ companyId: input.agent.companyId, agentId: input.agent.id, issueId: issue.id, projectId: null });
expect(result.nativeChatExpectedCwd).toBe(result.nativeChatWorkspaceScope?.taskRoot);
expect(result.nativeChatExpectedCwd).toContain(`isolated-workspaces/${input.agent.companyId}/${issue.id}`);
});
it.each(["git_worktree", "project_primary"] as const)("only prepares fresh native chat isolation with a %s source strategy", async (strategy) => {
const { input, issue, project } = await fixture();
const [source] = await db.insert(projectWorkspaces).values({ companyId: input.agent.companyId, projectId: project.id,
name: "Chat source", cwd: home, sourceType: "local_path", isPrimary: true }).returning();
const intent = { version: 1 as const, source: "explicit" as const, selection: { kind: "configured_source" as const, projectWorkspaceId: source.id, mode: "managed_isolated" as const } };
await db.update(issues).set({ originKind: "chat_channel", projectWorkspaceId: source.id, workspaceSelection: intent }).where(eq(issues.id, issue.id));
input.task.issueRef!.projectWorkspaceId = source.id;
input.task.workspaceProjectContext = { hasWorkspace: true };
input.task.hasSelectedWorkspaceSource = true;
input.task.taskWorkspaceIntent = intent;
input.agent.adapterType = "paperclip_runner";
input.policy.requestedExecutionWorkspaceMode = "isolated_workspace";
input.config.sourceWorkspaceConfig = { workspaceStrategy: { type: strategy } };
if (strategy === "project_primary") {
await expect(selectHeartbeatEnvironment(db, input)).rejects.toThrow("External chat requires a task-owned isolated workspace");
} else {
const result = await selectHeartbeatEnvironment(db, input);
expect(result).toMatchObject({ materializeNativeChatWorktree: true, nativeChatExpectedCwd: null, existingExecutionWorkspace: null });
expect(result.nativeChatWorkspaceScope?.projectId).toBe(project.id);
expect((await db.select().from(issues).where(eq(issues.id, issue.id)))[0].executionWorkspaceId).toBeNull();
}
});
});