Files
PaperClipAI/server/src/services/isolated-task-directory.test.ts
T
DottaandPaperclip cc5136ca02 fix(workspaces): run projectless isolated tasks and chats without a repo (#22972)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Execution workspace isolation controls how each task and
conversation gets a working directory
> - When isolated workspaces are enabled (including with
`enableIsolatedWorkspacesByDefault`), a task or conversation without a
project or repository can resolve to `isolated_workspace` without an
explicit `workspaceStrategy`
> - Wakeup preflight synthesized the default `git_worktree` strategy and
blocked projectless tasks with `workspace_worktree_requires_project`,
while `shouldUseIsolatedTaskDirectory` only allowed `low_trust_review` +
`sandbox` and failed standard local, sandbox, and plugin runs with
`git_worktree_base_not_git_checkout` or
`plugin_workspace_strategy_unsupported`
> - This pull request admits repository-free isolated tasks and
conversations into private isolated task directories across local,
sandbox, and plugin environments while preserving explicit Git worktree
validation, SSH preflight blocking, cross-task archived-workspace
protection, and low-trust sandbox containment
> - The benefit is that projectless tasks, projectless agent chats, and
repository-free project tasks run cleanly with persistent isolated
directories across turns, without weakening Git worktree isolation for
repository-backed projects

## Linked Issues or Issue Description

Fixes: #20962

Refs #20963, #19860, #14766, #13636

Relationship to #20963: #20963 enables private task directories for
standard local repository-free tasks and guards
`hasSelectedExecutionWorkspace`. This pull request builds on that
direction by also:
- Allowing repository-free isolated tasks without an explicit
`workspaceStrategy` to pass wakeup preflight in
`server/src/services/heartbeat/queue.ts` via the canonical
`shouldUseIsolatedTaskDirectory` predicate with resolved trust preset
and environment driver (otherwise projectless tasks and chats with
`mode: "isolated_workspace"` are blocked with
`workspace_worktree_requires_project` before environment selection runs,
while SSH, explicit `git_worktree`, and cross-task/shared archived
bindings remain blocked pre-dispatch).
- Supporting standard `sandbox` (Paperclip Cloud) and `plugin`
environments in `shouldUseIsolatedTaskDirectory` (including multi-turn
ordinary plugin task directory reuse via `isBoundPluginTaskDirectory`),
not only `local` / `null`.
- Scoping `!hasSelectedExecutionWorkspace` strictly to `trustPreset ===
"standard"` so `low_trust_review` sandbox containment remains unchanged.
- Preserving `nativeChatWorkspaceScope` isolation (zero referenced
project roots) in `workspace-preparation.ts` when an external chat also
uses a private task directory.

## What Changed

- `server/src/services/isolated-task-directory.ts`: Extract
`hasExplicitWorkspaceStrategy`, add a `standard`-scoped
`hasSelectedExecutionWorkspace` guard, and allow
`shouldUseIsolatedTaskDirectory` for `standard` trust on `local`,
`sandbox`, `plugin`, and `null` drivers while keeping `low_trust_review`
sandbox containment unchanged and keeping `ssh`, `denied`, selected
standard workspaces, and explicit strategies excluded.
- `server/src/services/provider-fresh-workspace.ts`: Add
`isBoundPluginTaskDirectory` recognizing both fresh plugin attempt
directories and ordinary task-owned plugin directories
(`/workspaces/<issueId>` with matching `runnerTaskWorkspaceOwner`,
`projectWorkspaceId === null`, and no `runnerTaskFreshWorkspace`) so
multi-turn repository-free plugin tasks reuse their bound workspace
without hitting `plugin_workspace_strategy_unsupported`.
- `server/src/services/heartbeat/queue.ts`: Call the canonical
`shouldUseIsolatedTaskDirectory` during wakeup preflight with resolved
`trustPreset` (`resolveCoreTrustPreset`) and effective
`environmentDriver` (honoring `executionWorkspaceSettings.environmentId`
for `low_trust_review`, `executionMode === "kubernetes"`, and
`enableManagedSandboxOnly`, and allowing verified exclusively task-owned
archived/cleanup_failed task directories matching
`readTaskDirectoryRetention` or `issue_terminal` cleanup while blocking
cross-task/shared archived bindings) to resolve
`effectivePreflightStrategy` to `"project_primary"` instead of adding a
bypass flag on `isUnrunnableWorktreeCombo`.
- `server/src/services/heartbeat/environment-selection.ts`: Use
`isBoundPluginTaskDirectory` for bound plugin task directory reuse and
pass `hasSelectedExecutionWorkspace` into
`shouldUseIsolatedTaskDirectory` so existing or tampered standard
workspace bindings still go through binding validation.
- `server/src/services/heartbeat/workspace-preparation.ts`: Force
`project_primary` strategy for host and plugin preparation when
`useIsolatedTaskDirectory` is active (outside `remoteAuthority`), and
keep projectless `nativeChatWorkspaceScope` runs on the external-chat
directory branch so referenced projects are not attached.
- `doc/experimental/issue-worktree-support.md`: Document private
isolated task directory behavior for repository-free isolated tasks and
conversations.
- Tests: Extend `isolated-task-directory.test.ts`,
`provider-fresh-workspace.test.ts`, `workspace-preparation.test.ts`, and
`heartbeat-workspace-source-trust.test.ts` with unit and
embedded-Postgres E2E coverage across local, sandbox, plugin, and SSH
environments (projectless tasks, projectless chats, repo-free projects,
2-turn local/sandbox/plugin workspace reuse, git-backed project
`git_worktree` regression, explicit projectless `git_worktree` block,
SSH pre-dispatch block, low-trust projectless sandbox on SSH-default
agent, cross-task archived workspace blocking, and exclusively
task-owned archived directory reopening).

## Verification

- `pnpm exec vitest run
server/src/services/isolated-task-directory.test.ts
server/src/services/provider-fresh-workspace.test.ts
server/src/__tests__/execution-workspace-policy.test.ts` — 3 files, 101
passed (101).
- `pnpm exec vitest run
server/src/services/heartbeat/workspace-preparation.test.ts -t "prepares
a repository-free local task directory|reuses a bound ordinary
repository-free plugin task directory|names incompatible Core project
storage"` — 3 passed (including 2-turn ordinary plugin task directory
reuse + explicit `git_worktree` rejection).
- `pnpm exec vitest run
server/src/__tests__/heartbeat-workspace-source-trust.test.ts -t "in a
company with no repository|still uses git_worktree"` — 9 passed with
embedded Postgres (projectless tasks, projectless chats, repo-free
projects on local and sandbox, git-backed project `git_worktree`,
explicit projectless `git_worktree` block, SSH pre-dispatch block,
low-trust projectless sandbox on SSH-default agent, cross-task archived
workspace pre-dispatch block, and own archived isolated task directory
reopening).
- `pnpm exec vitest run
server/src/__tests__/heartbeat-workspace-branch-containment.test.ts -t
"blocks projectless isolated git-worktree issues before dispatch"` — 1
passed.
- `pnpm --filter @paperclipai/server typecheck` — passed (0 errors
across all 7 layers).
- `node scripts/check-test-budget.mjs --files
server/src/services/isolated-task-directory.test.ts
server/src/services/provider-fresh-workspace.test.ts
server/src/services/heartbeat/workspace-preparation.test.ts
server/src/__tests__/heartbeat-workspace-source-trust.test.ts` — PASS
(110 nightly suites validated, 4 test files checked).
- `git diff --check` — clean; no secrets, artifacts, or internal IDs.
- Sharded PR CI on `eb2b11ee9b`: **66/66** executed checks `SUCCESS` (0
failing, 0 pending, 7 skipped, 2 non-blocking neutral Paperclip Review),
including `ci / verify`, `ci / e2e` + all 16 E2E shards, all 20 General
server shards + chat + workspaces-b, all 9 Serialized server shards, all
Verify Paperclip Runner lanes, `Build`, `Typecheck + Release Registry`,
`policy`, `Superagent Security Scan`, `Socket Security`, `Contributor
trust`, `commitperclip`, `Snyk`, and `Greptile Review` (5/5).

## Risks

- Repository-free tasks and conversations with `mode:
"isolated_workspace"` and no explicit `workspaceStrategy` now run in
private task directories under
`<instanceRoot>/isolated-workspaces/<companyId>/<issueId>` (or
`/workspaces/<issueId>` on plugin environments / remote empty workspaces
under `remoteAuthority`) instead of failing preflight or Git checkout
validation.
- Explicit `workspaceStrategy` requirements (including `git_worktree`,
`existingBranch`, and `provisionCommand`), SSH pre-dispatch blocking,
cross-task archived workspace blocking, low-trust sandbox confinement,
tampered-binding checks (`hasSelectedExecutionWorkspace`), and
`git_worktree` isolation for git-backed projects remain unchanged.
- No database migrations, schema changes, or API contract changes.

## Model Used

- Claude Opus 4.6 (`claude-opus-4-6`) in Antigravity with tool use,
shell execution, and extended thinking.

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:32:12 -06:00

177 lines
8.8 KiB
TypeScript

import { cp, mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises";
import { execFile as execFileCallback } from "node:child_process";
import { promisify } from "node:util";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { materializeIsolatedTaskDirectory, shouldUseIsolatedTaskDirectory } from "./isolated-task-directory.js";
import { prepareSandboxManagedRuntime, type SandboxManagedRuntimeClient, type SandboxSyncOperation } from "@paperclipai/adapter-utils/sandbox-managed-runtime";
const execFile = promisify(execFileCallback);
const policy = {
trustPreset: "low_trust_review",
environmentDriver: "sandbox",
mode: "isolated_workspace",
hasProjectWorkspace: false,
projectWorkspaceId: null,
workspaceStrategies: [undefined, null, {}],
};
describe("repository-free workspace selection", () => {
it("selects a private directory for low-trust sandbox tasks without a repository", () => {
expect(shouldUseIsolatedTaskDirectory(policy)).toBe(true);
expect(shouldUseIsolatedTaskDirectory({ ...policy, hasSelectedExecutionWorkspace: true })).toBe(true);
});
it.each([
{ trustPreset: "standard", environmentDriver: "local" },
{ trustPreset: "standard", environmentDriver: null },
{ trustPreset: "standard", environmentDriver: "sandbox" },
{ trustPreset: "standard", environmentDriver: "plugin" },
])("selects a private directory for standard repository-free tasks: %j", (override) => {
expect(shouldUseIsolatedTaskDirectory({ ...policy, ...override })).toBe(true);
});
it.each([
{ trustPreset: "low_trust_review", environmentDriver: "local" },
{ trustPreset: "low_trust_review", environmentDriver: "plugin" },
{ trustPreset: "low_trust_review", environmentDriver: null },
{ trustPreset: "denied", environmentDriver: "sandbox" },
{ environmentDriver: "ssh" },
{ trustPreset: "standard", environmentDriver: "ssh" },
{ mode: "shared_workspace" },
{ hasProjectWorkspace: true },
{ projectWorkspaceId: "workspace-1" },
{ trustPreset: "standard", environmentDriver: "local", hasSelectedExecutionWorkspace: true },
{ trustPreset: "standard", environmentDriver: "sandbox", hasSelectedExecutionWorkspace: true },
{ trustPreset: "standard", environmentDriver: "plugin", hasSelectedExecutionWorkspace: true },
{ workspaceStrategies: [{ type: "git_worktree" }] },
{ workspaceStrategies: [{ existingBranch: "main" }] },
{ workspaceStrategies: [{ provisionCommand: "setup" }] },
])("preserves configured workspace requirements: %j", (override) => {
expect(shouldUseIsolatedTaskDirectory({ ...policy, ...override })).toBe(false);
});
});
describe("isolated task directories", () => {
let root: string | undefined;
afterEach(async () => {
vi.unstubAllEnvs();
if (root) await rm(root, { recursive: true, force: true });
});
async function setup() {
root = await mkdtemp(path.join(os.tmpdir(), "paperclip-isolated-task-"));
vi.stubEnv("PAPERCLIP_HOME", root);
return { companyId: "company-1", issueId: "issue-1" };
}
it("retains a task's files across turns without sharing them with another task or company", async () => {
const identity = await setup();
const cwd = await materializeIsolatedTaskDirectory(identity);
await writeFile(path.join(cwd, "notes.txt"), "private task output");
expect(await materializeIsolatedTaskDirectory(identity)).toBe(cwd);
expect(await readFile(path.join(cwd, "notes.txt"), "utf8")).toBe("private task output");
for (const other of [{ issueId: "issue-2" }, { companyId: "company-2" }]) {
const otherCwd = await materializeIsolatedTaskDirectory({ ...identity, ...other });
expect(otherCwd).not.toBe(cwd);
expect(otherCwd.startsWith(`${cwd}${path.sep}`)).toBe(false);
expect(await readdir(otherCwd)).toEqual([]);
}
});
it("rejects a symlink to another task's directory", async () => {
const identity = await setup();
const cwd = await materializeIsolatedTaskDirectory(identity);
await symlink(cwd, path.join(path.dirname(cwd), "issue-2"));
await expect(materializeIsolatedTaskDirectory({ ...identity, issueId: "issue-2" }))
.rejects.toThrow("not a private directory");
});
it("reuses only the exact private task directory, including a prior fresh attempt", async () => {
const identity = await setup();
for (const attemptId of [undefined, "previous-attempt"]) {
const cwd = await materializeIsolatedTaskDirectory({ ...identity, attemptId });
await writeFile(path.join(cwd, "saved.txt"), "preserved");
expect(await materializeIsolatedTaskDirectory({ ...identity, reuseCwd: cwd })).toBe(cwd);
expect(await readFile(path.join(cwd, "saved.txt"), "utf8")).toBe("preserved");
}
});
it.each(["other-company", "other-issue", "outside", "traversal", "missing", "symlink"])(
"does not admit or recreate a reused task directory with %s binding", async change => {
const identity = await setup();
const cwd = await materializeIsolatedTaskDirectory({ ...identity, attemptId: "prior-attempt" });
await writeFile(path.join(cwd, "saved.txt"), "preserved");
let reuseCwd = cwd;
if (change === "other-company") reuseCwd = cwd.replace(identity.companyId, "other-company");
if (change === "other-issue") reuseCwd = cwd.replace(identity.issueId, "other-issue");
if (change === "outside") reuseCwd = path.dirname(path.dirname(cwd));
if (change === "traversal") reuseCwd = `${cwd}/../prior-attempt`;
if (change === "missing") reuseCwd = path.join(path.dirname(cwd), "missing-attempt");
if (change === "symlink") {
reuseCwd = path.join(path.dirname(cwd), "linked-attempt");
await symlink(cwd, reuseCwd);
}
await expect(materializeIsolatedTaskDirectory({ ...identity, reuseCwd })).rejects.toThrow();
if (change === "missing") await expect(readFile(path.join(reuseCwd, "saved.txt"))).rejects.toThrow();
expect(await readFile(path.join(cwd, "saved.txt"), "utf8")).toBe("preserved");
},
);
it("round-trips sandbox output into the task directory and stages it on the next turn", async () => {
const identity = await setup();
const cwd = await materializeIsolatedTaskDirectory(identity);
// Only provider I/O is emulated. Production archive, ignore, sync-back and
// merge logic runs against distinct host and remote filesystem roots.
const transfer = async (operations: SandboxSyncOperation[]) => ({
operations: await Promise.all(operations.map(async (operation) => {
for (const file of operation.files) {
await mkdir(path.dirname(file.targetPath), { recursive: true });
await cp(file.sourcePath, file.targetPath, { recursive: true, dereference: file.followSymlinks ?? false });
}
for (const command of operation.postUploadCommands ?? []) {
await execFile("sh", ["-c", command.command]);
}
return { operationId: operation.operationId, filesTransferred: operation.files.length, bytesTransferred: 0 };
})),
});
const client: SandboxManagedRuntimeClient = {
makeDir: async (target) => { await mkdir(target, { recursive: true }); },
writeFile: async (target, bytes) => { await writeFile(target, Buffer.from(bytes)); },
readFile: async (target) => readFile(target),
listFiles: async (target) => readdir(target),
remove: async (target) => { await rm(target, { recursive: true, force: true }); },
run: async (command) => { await execFile("sh", ["-c", command]); },
syncIn: transfer,
syncOut: transfer,
};
for (let turn = 0; turn < 2; turn += 1) {
const remoteCwd = path.join(root!, `sandbox-${turn}`);
const runtime = await prepareSandboxManagedRuntime({
spec: { transport: "sandbox", provider: "test", sandboxId: `turn-${turn}`, remoteCwd, timeoutMs: 30_000, apiKey: null },
adapterKey: "test",
client,
workspaceLocalDir: cwd,
});
if (turn === 0) {
await writeFile(path.join(remoteCwd, "result.txt"), "created in sandbox");
} else {
expect(await readFile(path.join(remoteCwd, "result.txt"), "utf8")).toBe("created in sandbox");
await writeFile(path.join(remoteCwd, "result.txt"), "continued in a new sandbox");
}
await runtime.restoreWorkspace();
}
expect(await readFile(path.join(cwd, "result.txt"), "utf8")).toBe("continued in a new sandbox");
const other = await materializeIsolatedTaskDirectory({ ...identity, issueId: "issue-2" });
expect(await readdir(other)).toEqual([]);
});
it("rejects path traversal identities", async () => {
const identity = await setup();
await expect(materializeIsolatedTaskDirectory({ ...identity, issueId: "../outside" }))
.rejects.toThrow("Invalid isolated task workspace identity");
});
});