fix(workspaces): keep selected source provisioning off controller

Bind provisioning to the selected execution environment and durable copy-only
source lineage. Preserve suppression through reuse, rebuild, metadata changes
and reopen while retaining implicit trusted local defaults.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-12 20:03:37 -05:00
1 parent 474aed9fe5
commit ea970f478c
20 files changed
+379 -96

No files matched your search

@@ -261,7 +261,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
}
describe.each(["configured", "builtin"] as const)("reopen %s host provision containment", kind => {
it.each(["task", "agent", "organization", "source", "same-source", "trusted"] as const)("honors persisted %s policy before running repository scripts", async restriction => {
it.each(["task", "agent", "organization", "source", "same-source", "trusted", "explicit", "projectless", "nondefault", "foreign-source-task", "retained-missing", "retained-false", "retained-null"] as const)("honors persisted %s policy before running repository scripts", async restriction => {
const { companyId, projectId, projectWorkspaceId } = await seedCompanyProject();
const directory = await makeExistingDir();
const base = join(directory, "source"), target = join(directory, "target"), marker = join(directory, "host-provision-ran");
@@ -279,7 +279,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
[EXECUTION_WORKSPACE_LIFECYCLE_GENERATION_METADATA_KEY]: 1, config: { provisionCommand: command },
} }).where(eq(executionWorkspaces.id, workspaceId));
const issueId = await seedIssue({ companyId, projectId, workspaceId, issueNumber: 4199 });
let organizationId: string | null = restriction === "same-source" ? projectId : null;
let organizationId: string | null = restriction === "projectless" ? null : projectId;
if (restriction === "organization") {
organizationId = randomUUID();
await db.insert(projects).values({ id: organizationId, companyId, name: "Organizational policy" });
@@ -296,6 +296,30 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
await db.update(projects).set({ executionWorkspacePolicy: policy })
.where(eq(projects.id, restriction === "organization" ? organizationId! : projectId));
}
if (restriction === "explicit" || restriction.startsWith("retained-")) {
await db.update(issues).set({ workspaceSelection: { version: 1, source: "explicit",
selection: { kind: "configured_source", projectWorkspaceId, mode: "managed_isolated" } } })
.where(eq(issues.id, issueId));
}
if (restriction === "nondefault") {
await db.insert(projectWorkspaces).values({ companyId, projectId, name: "Earlier default",
sourceType: "local_path", cwd: base, createdAt: new Date(0) });
}
if (restriction === "foreign-source-task") {
const sourceIssueId = await seedIssue({ companyId, projectId, workspaceId, issueNumber: 4198 });
await db.update(executionWorkspaces).set({ sourceIssueId }).where(eq(executionWorkspaces.id, workspaceId));
}
if (restriction.startsWith("retained-")) {
const workspace = await readWorkspace(workspaceId);
await db.update(executionWorkspaces).set({ metadata: { ...workspace?.metadata,
_controllerProvisionCopyOnly: true } }).where(eq(executionWorkspaces.id, workspaceId));
await db.update(issues).set({ workspaceSelection: null }).where(eq(issues.id, issueId));
const service = executionWorkspaceService(db);
await service.update(workspaceId, { metadata: restriction === "retained-null" ? null
: restriction === "retained-false" ? { _controllerProvisionCopyOnly: false } : {} });
if (kind === "configured") await service.update(workspaceId, { metadata: { config: { provisionCommand: command } } });
expect((await readWorkspace(workspaceId))?.metadata).toMatchObject({ _controllerProvisionCopyOnly: true });
}
const result = await executionWorkspaceService(db).reopenClosedIsolatedExecutionWorkspaceForIssue({
workspaceId, issue: { id: issueId, companyId, projectId: organizationId },
actor: { agentId: null, actorType: "user" },
@@ -306,6 +330,8 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
if (restriction === "trusted") await expect(readFile(marker, "utf8")).resolves.toBe("host execution\n");
else await expect(readFile(marker, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
expect(await readWorkspace(workspaceId)).toMatchObject({ status: "active", projectId, projectWorkspaceId });
if (["explicit", "projectless", "nondefault", "foreign-source-task"].includes(restriction) || restriction.startsWith("retained-")) expect((await readWorkspace(workspaceId))?.metadata)
.toMatchObject({ _controllerProvisionCopyOnly: true });
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0])
.toMatchObject({ projectId: organizationId, executionWorkspaceId: workspaceId, assigneeAgentId: agentId });
});
@@ -469,10 +469,11 @@ suite("task project repository provisioning", () => {
expect(await readFile(path.join(cwd, "work.txt"), "utf8")).toBe("Protected source content");
}, 30_000);
it.each(["success", "provision_failure", "occupied_target"] as const)("checks nested private source access before worktree copy and retains it after read-grant revocation (%s)", async (scenario) => {
it.each(["success", "provision_failure", "copy_only_provision", "occupied_target"] as const)("checks nested private source access before worktree copy and retains it after read-grant revocation (%s)", async (scenario) => {
const previousPrivacyMode = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
vi.stubEnv("PAPERCLIP_ISSUE_PRIVACY_MODE", "enforce");
try {
if (scenario === "provision_failure") await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true });
const companyId = randomUUID(), projectId = randomUUID(), privateProjectId = randomUUID();
const sourceId = randomUUID(), agentId = randomUUID(), issueId = randomUUID();
const cwd = path.join(root, companyId, "public-source");
@@ -504,9 +505,15 @@ suite("task project repository provisioning", () => {
sourceType: "local_path", cwd: path.dirname(occupiedTarget), isPrimary: false,
});
await db.insert(agents).values({ id: agentId, companyId, name: "Isolated reader", status: "idle", adapterType: "codex_local", adapterConfig: {}, permissions: {} });
if (scenario === "provision_failure") await db.insert(companyMemberships).values({ companyId, principalType: "agent", principalId: agentId, status: "active", membershipRole: "member" });
await db.insert(issues).values({ id: issueId, companyId, title: "Read isolated source", status: "todo", assigneeAgentId: agentId,
projectWorkspaceId: sourceId, executionWorkspaceSettings: { mode: "isolated_workspace", workspaceStrategy: { type: "git_worktree", ...(scenario === "provision_failure" ? { provisionCommand: "exit 42" } : {}), ...(scenario === "occupied_target" ? { branchTemplate: "occupied-private", provisionCommand: "touch provision-ran" } : {}) } },
workspaceSelection: { version: 1, source: "explicit", selection: { kind: "configured_source", projectWorkspaceId: sourceId, mode: "managed_isolated" } } });
projectId: scenario === "provision_failure" ? projectId : null,
projectWorkspaceId: sourceId, executionWorkspaceSettings: { mode: "isolated_workspace", workspaceStrategy: { type: "git_worktree", ...(scenario === "provision_failure" ? { provisionCommand: "exit 42" } : {}), ...(scenario === "copy_only_provision" ? { provisionCommand: "touch provision-ran; exit 42" } : {}), ...(scenario === "occupied_target" ? { branchTemplate: "occupied-private", provisionCommand: "touch provision-ran" } : {}) } },
workspaceSelection: scenario === "provision_failure" ? null : { version: 1, source: "explicit", selection: { kind: "configured_source", projectWorkspaceId: sourceId, mode: "managed_isolated" } } });
if (scenario === "provision_failure") await db.insert(principalPermissionGrants).values([
{ companyId, principalType: "agent", principalId: agentId, permissionKey: "tasks:assign_scope", scope: { projectId, assigneeAgentId: agentId } },
{ companyId, principalType: "user", principalId: "responsible-user", permissionKey: "tasks:assign_scope", scope: { projectId, assigneeAgentId: agentId } },
]);
const admit = async () => {
const run = await heartbeat.wakeup(agentId, { source: "on_demand", triggerDetail: "manual", contextSnapshot: { issueId } });
expect(run).not.toBeNull();
@@ -524,11 +531,11 @@ suite("task project repository provisioning", () => {
{ companyId, projectId: privateProjectId, subjectType: "user", subjectId: "responsible-user" },
]);
expect(await accessService(db).decide({ actor: { type: "agent", agentId, companyId, source: "agent_jwt", onBehalfOfUserId: "responsible-user" },
action: "tasks:assign", resource: { type: "issue", companyId, projectId, assigneeAgentId: agentId }, scope: { projectId, assigneeAgentId: agentId } })).toMatchObject({ allowed: false });
action: "tasks:assign", resource: { type: "issue", companyId, projectId, assigneeAgentId: agentId }, scope: { projectId, assigneeAgentId: agentId } })).toMatchObject({ allowed: scenario === "provision_failure" });
const allowed = await admit();
const calls = execute.mock.calls.filter(([input]) => input.runId === allowed.id);
let copiedCwd: string;
if (scenario !== "success") {
if (scenario === "provision_failure" || scenario === "occupied_target") {
expect(allowed.status).toBe("failed");
expect(calls).toHaveLength(0);
if (scenario === "provision_failure") {
@@ -558,6 +565,12 @@ suite("task project repository provisioning", () => {
expect(calls).toHaveLength(1);
expect(calls[0]![0].context.paperclipWorkspace.strategy).toBe("git_worktree");
copiedCwd = calls[0]![0].context.paperclipWorkspace.cwd;
if (scenario === "copy_only_provision") {
await expect(readFile(path.join(copiedCwd, "provision-ran"), "utf8")).rejects.toMatchObject({ code: "ENOENT" });
const [bound] = await db.select().from(issues).where(eq(issues.id, issueId));
const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, bound.executionWorkspaceId!));
expect(workspace.metadata?._controllerProvisionCopyOnly).toBe(true);
}
}
const workspace = { cwd: copiedCwd };
expect(await realpath(workspace.cwd)).not.toBe(await realpath(cwd));
@@ -37,7 +37,6 @@ import {
resolveWorkspaceAfterLowTrustPreflight,
resolveRuntimeSessionParamsForWorkspace,
shouldDeferFollowupWakeForSameIssue,
stripHostWorkspaceProvisionForLowTrustSandbox,
stripWorkspaceRuntimeFromExecutionRunConfig,
shouldResetTaskSessionForModelChange,
stripConfiguredModelFromSessionParams,
@@ -49,6 +48,7 @@ import {
buildAnchorFallbackWorkspaceNotes,
type ResolvedWorkspaceForRun,
} from "../services/heartbeat.ts";
import { stripHostWorkspaceProvision } from "../services/heartbeat/workspaces.js";
import type { TrustPresetResolution } from "../services/trust-preset-resolver.ts";
const execFile = promisify(execFileCallback);
@@ -1125,8 +1125,15 @@ describe("requiresPushCapabilityPreflight", () => {
});
});
describe("stripHostWorkspaceProvisionForLowTrustSandbox", () => {
it("removes only the host-side provision command for sandbox-backed low-trust runs", () => {
describe("stripHostWorkspaceProvision", () => {
it.each(["sandbox", "ssh"])("removes nested and top-level runtime commands immutably for %s", selectedEnvironmentDriver => {
const config = { runtimeProvisionCommand: "top-level", workspaceStrategy: { type: "git_worktree", provisionCommand: "host", runtimeProvisionCommand: "nested" } };
const original = structuredClone(config);
expect(stripHostWorkspaceProvision({ config, skipHostProvision: true }))
.toEqual({ workspaceStrategy: { type: "git_worktree" } });
expect(config).toEqual(original);
});
it("removes controller provisioning while retaining unrelated settings", () => {
const config = {
workspaceStrategy: {
type: "git_worktree",
@@ -1139,10 +1146,9 @@ describe("stripHostWorkspaceProvisionForLowTrustSandbox", () => {
},
};
const result = stripHostWorkspaceProvisionForLowTrustSandbox({
const result = stripHostWorkspaceProvision({
config,
trustPreset: lowTrustResolution(),
selectedEnvironmentDriver: "sandbox",
skipHostProvision: true,
});
expect(result).not.toBe(config);
@@ -1155,7 +1161,7 @@ describe("stripHostWorkspaceProvisionForLowTrustSandbox", () => {
expect(config.workspaceStrategy.provisionCommand).toBe("bash ./scripts/provision-worktree.sh");
});
it("preserves provision commands for standard-trust runs", () => {
it("strips provision commands when the controller is not the execution target", () => {
const config = {
workspaceStrategy: {
type: "git_worktree",
@@ -1163,14 +1169,13 @@ describe("stripHostWorkspaceProvisionForLowTrustSandbox", () => {
},
};
expect(stripHostWorkspaceProvisionForLowTrustSandbox({
expect(stripHostWorkspaceProvision({
config,
trustPreset: standardTrustResolution(),
selectedEnvironmentDriver: "sandbox",
})).toBe(config);
skipHostProvision: true,
})).toEqual({ workspaceStrategy: { type: "git_worktree" } });
});
it("preserves provision commands when a low-trust run is not sandbox-backed", () => {
it("preserves provision commands when the server permits controller provisioning", () => {
const config = {
workspaceStrategy: {
type: "git_worktree",
@@ -1178,10 +1183,9 @@ describe("stripHostWorkspaceProvisionForLowTrustSandbox", () => {
},
};
expect(stripHostWorkspaceProvisionForLowTrustSandbox({
expect(stripHostWorkspaceProvision({
config,
trustPreset: lowTrustResolution(),
selectedEnvironmentDriver: "local",
skipHostProvision: false,
})).toBe(config);
});
});
@@ -139,4 +139,81 @@ suite("heartbeat physical workspace source trust", () => {
}
});
it.each([
["configured", "none", "sandbox"], ["builtin", "none", "sandbox"],
["configured", "agent", "sandbox"], ["builtin", "agent", "sandbox"],
["configured", "both", "sandbox"], ["builtin", "both", "sandbox"],
["configured", "both", "local"], ["builtin", "both", "local"],
["configured", "none", "local"], ["builtin", "none", "local"],
["configured", "both", "local_default"], ["builtin", "both", "local_default"],
] as const)("places standard source %s provisioning with %s grants on %s", async (provisionKind, grants, placement) => {
const implicitDefault = placement === "local_default";
const companyId = randomUUID(), projectId = randomUUID(), sourceId = randomUUID(), agentId = randomUUID(), issueId = randomUUID();
await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true });
const cwd = path.join(root, companyId, "read-only-source");
const marker = path.join(root, companyId, "host-script-ran");
await mkdir(path.join(cwd, "scripts"), { recursive: true });
await writeFile(path.join(cwd, "source.txt"), "read-only source bytes");
await writeFile(path.join(cwd, "scripts", "provision-worktree.sh"), `printf host-script-ran > '${marker}'\n`);
const git = (...args: string[]) => execFileSync("git", args, { cwd, stdio: "ignore" });
git("init", "-b", "main"); git("add", ".");
git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "source");
git("remote", "add", "origin", pathToFileURL(cwd).href);
await db.insert(companies).values({ id: companyId, name: "Read-only source", issuePrefix: `R${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: "Protected source", executionWorkspacePolicy: {
authorizationPolicy: { assignmentPolicy: { mode: "protected" } },
} });
await db.insert(projectWorkspaces).values({ id: sourceId, companyId, projectId, name: "Source", sourceType: "local_path", cwd, repoUrl: pathToFileURL(cwd).href, isPrimary: true });
await db.insert(agents).values({ id: agentId, companyId, name: "Reader", status: "idle", adapterType: "codex_local", adapterConfig: { fullAuto: grants === "both" }, permissions: {} });
await db.insert(companyMemberships).values({ companyId, principalType: "agent", principalId: agentId, status: "active", membershipRole: "member" });
await db.insert(issues).values({ id: issueId, companyId, projectId: implicitDefault ? projectId : null, title: "Read-only isolated source", status: "todo", assigneeAgentId: agentId,
projectWorkspaceId: sourceId, executionWorkspaceSettings: { mode: "isolated_workspace", workspaceStrategy: { type: "git_worktree",
worktreeParentDir: path.join(root, companyId, "worktrees"), ...(provisionKind === "configured" ? { provisionCommand: `printf host-script-ran > '${marker}'` } : {}) } },
workspaceSelection: implicitDefault ? null : { version: 1, source: "explicit", selection: { kind: "configured_source", projectWorkspaceId: sourceId, mode: "managed_isolated" } } });
if (grants !== "none") await db.insert(principalPermissionGrants).values({ companyId, principalType: "agent", principalId: agentId,
permissionKey: "tasks:assign_scope", scope: { projectId, assigneeAgentId: agentId } });
if (grants === "both") await db.insert(principalPermissionGrants).values({ companyId, principalType: "user", principalId: "responsible-user",
permissionKey: "tasks:assign_scope", scope: { projectId, assigneeAgentId: agentId } });
const actor = { type: "agent" as const, agentId, companyId, source: "agent_jwt" as const, onBehalfOfUserId: "responsible-user" };
expect(await accessService(db).decide({ actor, action: "project:read", resource: { type: "project", companyId, projectId } })).toMatchObject({ allowed: true });
expect(await accessService(db).decide({ actor, action: "project:write_workspace", resource: { type: "issue", companyId, projectId, issueId, assigneeAgentId: agentId }, scope: { projectId, assigneeAgentId: agentId } })).toMatchObject({ allowed: grants === "both" });
const environmentId = randomUUID();
await db.insert(environments).values({ id: environmentId, name: `Standard sandbox ${companyId}`, driver: "sandbox", status: "active", config: { provider: "fake", image: "fake:test" } });
await db.update(agents).set({ defaultEnvironmentId: placement === "sandbox" ? environmentId : null }).where(eq(agents.id, agentId));
const driver = heartbeatService(db, { environmentRuntime: { ...environmentRuntimeService(db), execute: async input => ({
exitCode: 0, stdout: execFileSync(input.command, input.args ?? [], { cwd: root, input: input.stdin, encoding: "utf8", env: { ...process.env, ...input.env } }),
stderr: "", signal: null, timedOut: false,
}) } });
const run = await driver.wakeup(agentId, { source: "on_demand", triggerDetail: "manual", contextSnapshot: { issueId } });
expect(run).not.toBeNull();
await vi.waitFor(async () => expect((await driver.getRun(run!.id))?.status).toMatch(/^(succeeded|failed)$/), { timeout: 15_000 });
await drainHeartbeatRunsToQuiescence(db, driver);
expect(await driver.getRun(run!.id)).toMatchObject({ status: "succeeded", error: null });
const [bound] = await db.select().from(issues).where(eq(issues.id, issueId));
const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, bound.executionWorkspaceId!));
expect(workspace.cwd).not.toBe(cwd);
expect(await readFile(path.join(workspace.cwd!, "source.txt"), "utf8")).toBe("read-only source bytes");
const calls = execute.mock.calls.filter(([input]) => input.runId === run!.id);
expect(calls).toHaveLength(1);
expect(calls[0][0].context.paperclipEnvironment.driver).toBe(placement === "sandbox" ? "sandbox" : "local");
if (!implicitDefault) await expect(readFile(marker, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
else expect(await readFile(marker, "utf8")).toBe("host-script-ran");
await rm(marker, { force: true });
if (grants === "none") await rm(workspace.cwd!, { recursive: true, force: true });
await db.update(issues).set({ status: "todo" }).where(eq(issues.id, issueId));
const { executionWorkspaceService } = await import("../services/execution-workspaces.js");
if (placement === "local" && grants === "both") await db.update(issues).set({ projectId, workspaceSelection: null }).where(eq(issues.id, issueId));
await executionWorkspaceService(db).update(workspace.id, { metadata: { ...workspace.metadata,
_controllerProvisionCopyOnly: false, config: { provisionCommand: `printf host-script-ran > '${marker}'` } } });
const resumed = await driver.wakeup(agentId, { source: "on_demand", triggerDetail: "manual", contextSnapshot: { issueId } });
await vi.waitFor(async () => expect((await driver.getRun(resumed!.id))?.status).toMatch(/^(succeeded|failed)$/), { timeout: 15_000 });
await drainHeartbeatRunsToQuiescence(db, driver);
expect(await driver.getRun(resumed!.id)).toMatchObject({ status: "succeeded", error: null });
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].executionWorkspaceId).toBe(workspace.id);
expect(await readFile(path.join(workspace.cwd!, "source.txt"), "utf8")).toBe("read-only source bytes");
if (!implicitDefault) await expect(readFile(marker, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
else expect(await readFile(marker, "utf8")).toBe("host-script-ran");
}, 30_000);
});
@@ -0,0 +1,44 @@
import type { Db } from "@paperclipai/db";
import { describe, expect, it, vi } from "vitest";
import { workspaceRequiresCopyOnlyProvisioning } from "../services/workspace-host-provision.js";
describe("controller provision source classification", () => {
function fixture(rows: Array<{ id: string }> = [{ id: "default-source" }]) {
const query = { from: vi.fn(), where: vi.fn(), orderBy: vi.fn(), limit: vi.fn(async () => rows) };
query.from.mockReturnValue(query);
query.where.mockReturnValue(query);
query.orderBy.mockReturnValue(query);
const db = { select: vi.fn(() => query) } as unknown as Db;
const input = { companyId: "company", task: { id: "task", projectId: "project" },
sourceProjectId: "project", sourceWorkspaceId: "default-source" };
return { db, input };
}
it.each(["explicit", "channel", "parent", "legacy"] as const)("keeps %s source choice copy-only even on the organizational default", async source => {
const { db, input } = fixture();
expect(await workspaceRequiresCopyOnlyProvisioning(db, { ...input, task: { ...input.task,
workspaceSelection: { version: 1, source, selection: { kind: "configured_source", projectWorkspaceId: "default-source", mode: "managed_isolated" } } } })).toBe(true);
});
it("preserves the implicit organizational default and server-generated operator cwd", async () => {
const { db, input } = fixture();
expect(await workspaceRequiresCopyOnlyProvisioning(db, input)).toBe(false);
expect(await workspaceRequiresCopyOnlyProvisioning(db, { ...input, sourceProjectId: null, sourceWorkspaceId: null,
task: { ...input.task, workspaceSelection: { version: 1, source: "operator_cwd", selection: { kind: "task_directory" } } } })).toBe(false);
expect(await workspaceRequiresCopyOnlyProvisioning(db, { ...input, task: null, sourceProjectId: null, sourceWorkspaceId: null })).toBe(false);
});
it("preserves copy-only lineage after intent clearing and source ownership changes", async () => {
const { db, input } = fixture();
expect(await workspaceRequiresCopyOnlyProvisioning(db, { ...input, boundWorkspace: { metadata: { _controllerProvisionCopyOnly: true } } })).toBe(true);
expect(await workspaceRequiresCopyOnlyProvisioning(db, { ...input, boundWorkspace: { sourceIssueId: "parent-task" } })).toBe(true);
expect(await workspaceRequiresCopyOnlyProvisioning(db, { ...input, task: { ...input.task, projectId: null } })).toBe(true);
expect(await workspaceRequiresCopyOnlyProvisioning(db, { ...input, sourceWorkspaceId: null })).toBe(true);
});
it("does not upgrade missing or fallback source identities to a default approval", async () => {
const { db, input } = fixture([{ id: "earlier-unusable-source" }]);
expect(await workspaceRequiresCopyOnlyProvisioning(db, input)).toBe(true);
expect(await workspaceRequiresCopyOnlyProvisioning(fixture([]).db, input)).toBe(true);
});
});
@@ -4314,6 +4314,34 @@ describe("ensureRuntimeServicesForRun", () => {
};
}
it.each(["configured", "builtin"] as const)("suppresses %s runtime provision scripts for remote runs without disabling local provisioning", async kind => {
const workspaceRoot = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-remote-runtime-provision-"));
const restorePaperclipEnv = configureRuntimeProvisionTestHome(workspaceRoot, "remote-runtime-provision");
const marker = path.join(workspaceRoot, "runtime-script-ran");
const command = `printf host-runtime > '${marker}'`;
await fs.mkdir(path.join(workspaceRoot, "scripts"));
await fs.writeFile(path.join(workspaceRoot, "scripts", "provision-worktree-runtime.sh"), `${command}\n`);
const workspace = { ...buildWorkspace(workspaceRoot), strategy: "git_worktree" as const, worktreePath: workspaceRoot };
const config = runtimeProvisionTestConfig({ provisionCommand: kind === "configured" ? command : undefined });
const { recorder, operations } = createWorkspaceOperationRecorderDouble();
const input = { runId: randomUUID(), agent: { id: "agent-1", name: "Remote worker", companyId: "company-1" },
issue: null, workspace, config, executionWorkspaceId: randomUUID(), adapterEnv: {}, recorder };
try {
expect(await ensureRuntimeServicesForRun({ ...input, skipHostProvision: true })).toHaveLength(1);
await expect(fs.readFile(marker, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
expect(operations.filter(operation => ["workspace_seed", "workspace_runtime_provision"].includes(operation.phase))).toHaveLength(0);
await stopRuntimeServicesForExecutionWorkspace({ executionWorkspaceId: input.executionWorkspaceId, workspaceCwd: workspaceRoot });
const local = ensureRuntimeServicesForRun({ ...input, runId: randomUUID() });
if (kind === "builtin") await expect(local).rejects.toThrow(/without a readable seed manifest/);
else expect(await local).toHaveLength(1);
expect(await fs.readFile(marker, "utf8")).toBe("host-runtime");
} finally {
await stopRuntimeServicesForExecutionWorkspace({ executionWorkspaceId: input.executionWorkspaceId, workspaceCwd: workspaceRoot });
await fs.rm(workspaceRoot, { recursive: true, force: true });
restorePaperclipEnv();
}
});
it("runs runtime provisioning once when service starts race for the same workspace", async () => {
const workspaceRoot = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-runtime-provision-race-"));
const restorePaperclipEnv = configureRuntimeProvisionTestHome(workspaceRoot, "runtime-provision-race");
+10 -1
View File
@@ -1,6 +1,7 @@
import { assertTaskWorkspaceAccess, assertTaskWorkspaceSourceProjectAccess } from "./task-workspace-source-access.js";
import { parseObject } from "../adapters/utils.js";
import { resolveCoreTrustPreset } from "./trust-preset-resolver.js";
import { CONTROLLER_PROVISION_COPY_ONLY, workspaceRequiresCopyOnlyProvisioning } from "./workspace-host-provision.js";
import { instanceSettingsService } from "./instance-settings.js";
import { taskWorkspaceSelectableCondition } from "./task-workspace-selection.js";
import { executionWorkspaceRepositoryService, lockExecutionWorkspaceRootProvenance, preserveExecutionWorkspaceRootProvenance, assertExecutionWorkspaceRootWriteAccess, assertExecutionWorkspaceRootReadAccess, assertIsolatedWorkspaceSourceReadAccess, retainIsolatedWorkspaceSourceAccess, canonicalRepositoryRoot, type IsolatedWorkspaceSourceAccess, type TaskWorkspaceCreationTrustContext } from "./execution-workspace-repositories.js";
@@ -258,6 +259,9 @@ async function preserveWorkspaceOwnershipForPatch(
_issuePrivacySources: retainedSources,
};
}
if (current.metadata?.[CONTROLLER_PROVISION_COPY_ONLY] === true) {
nextPatch.metadata = { ...(nextPatch.metadata ?? current.metadata), [CONTROLLER_PROVISION_COPY_ONLY]: true };
}
return nextPatch;
}
@@ -3417,9 +3421,14 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
const trust = resolveCoreTrustPreset({ companyId: row.companyId, agent: assignee, issue: boundTask,
project: organization, workspaceSourceProject: sourceProject });
if (trust.kind === "denied") throw forbidden(trust.detail);
const copyOnlyProvisioning = await workspaceRequiresCopyOnlyProvisioning(tx, {
companyId: row.companyId, task: boundTask, sourceProjectId: row.projectId,
sourceWorkspaceId: row.projectWorkspaceId, boundWorkspace: row,
});
if (copyOnlyProvisioning) nextMetadata[CONTROLLER_PROVISION_COPY_ONLY] = true;
const realized = await ensurePersistedExecutionWorkspaceAvailable({
db: tx as unknown as Db,
skipHostProvision: trust.kind === "low_trust_review",
skipHostProvision: trust.kind === "low_trust_review" || copyOnlyProvisioning,
beforeSourceCopy: verifyCopyIdentity,
afterSourceCopy: verifyCopyIdentity,
base: {
+3 -2
View File
@@ -148,7 +148,6 @@ export {
mergeExecutionWorkspaceMetadataForPersistence,
resolveExecutionWorkspaceBranchOwnership,
stripWorkspaceRuntimeFromExecutionRunConfig,
stripHostWorkspaceProvisionForLowTrustSandbox,
preflightLowTrustWorkspaceIsolation,
resolveWorkspaceAfterLowTrustPreflight,
ensureManagedProjectWorkspace,
@@ -2669,6 +2668,7 @@ export function heartbeatService(
const {
resolvedWorkspace,
hostExecutionWorkspaceConfig,
skipHostProvision,
latestWorkspaceConfigMetadata,
workspaceConfigFreshness,
workspaceOperationRecorder,
@@ -2693,6 +2693,7 @@ export function heartbeatService(
context,
responsibleUserId,
previousSessionParams,
workspaceSelection: taskWorkspaceIntentRow?.intent ?? null,
},
policy: {
trustPreset,
@@ -3203,7 +3204,7 @@ export function heartbeatService(
);
const runtimeServices = await startHeartbeatRuntimeServices(db, {
run, agent, issueId, issueRef, executionWorkspace, context, issuesSvc, onLog,
persistedExecutionWorkspace, hostExecutionWorkspaceConfig, adapterEnv, workspaceOperationRecorder,
persistedExecutionWorkspace, hostExecutionWorkspaceConfig, skipHostProvision, adapterEnv, workspaceOperationRecorder,
});
const adapter = getServerAdapter(agent.adapterType);
const durableGoalControlRun =
@@ -92,6 +92,7 @@ export function prepareHeartbeatRuntimeServiceIntents(input: {
export async function startHeartbeatRuntimeServices(db: Db, input: RuntimeServiceContext & {
persistedExecutionWorkspace: { id: string } | null;
hostExecutionWorkspaceConfig: Record<string, unknown>;
skipHostProvision?: boolean;
adapterEnv: RuntimeInput["adapterEnv"];
workspaceOperationRecorder: RuntimeInput["recorder"];
}) {
@@ -112,6 +113,7 @@ export async function startHeartbeatRuntimeServices(db: Db, input: RuntimeServic
issueRef?.executionWorkspaceId ??
null,
config: hostExecutionWorkspaceConfig,
skipHostProvision: input.skipHostProvision,
adapterEnv,
onLog,
recorder: workspaceOperationRecorder,
@@ -116,6 +116,24 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",
expect(input.controllerLease.assertOwned).toHaveBeenCalledTimes(2);
});
it.each(["sandbox", "ssh", "local", null] as const)("uses the selected %s placement for controller provisioning", async driver => {
const { input, source, issue, envOrchestrator } = await fixture(true);
const marker = join(source, "host-provision-ran");
const provisionCommand = `printf host > '${marker}'`;
input.config.mergedConfig = { workspaceStrategy: { type: "git_worktree", provisionCommand, runtimeProvisionCommand: "printf runtime" } };
const originalConfig = structuredClone(input.config.mergedConfig);
input.environment.selectedEnvironmentForConfig = driver === null ? null : { ...input.environment.localEnvironment, driver };
const stopped = new Error("Fixture stops before transport acquisition");
vi.spyOn(envOrchestrator, "acquireForRun").mockRejectedValue(stopped);
await expect(prepareHeartbeatWorkspace(db, input)).rejects.toBe(stopped);
const bound = await readIssue(issue.id);
const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, bound.executionWorkspaceId!));
expect(await readFile(join(workspace.cwd!, "README.md"), "utf8")).toBe("source content\n");
if (driver === "sandbox" || driver === "ssh") await expect(readFile(marker, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
else expect(await readFile(marker, "utf8")).toBe("host");
expect(input.config.mergedConfig).toEqual(originalConfig);
});
it("checks physical root admission before publishing configured sibling repositories", async () => {
const { input, source, issue } = await fixture();
await db.insert(projectWorkspaces).values({ companyId: issue.companyId, projectId: issue.projectId!,
@@ -1,7 +1,7 @@
import {
resolveWorkspaceAfterLowTrustPreflight,
WorkspaceValidationFailure,
stripHostWorkspaceProvisionForLowTrustSandbox,
stripHostWorkspaceProvision,
assertGitWorktreeBaseWorkspaceReady,
buildEffectiveRunWorkspaceConfigMetadata,
resolveExecutionWorkspaceConfigFreshness,
@@ -16,6 +16,7 @@ import {
import { resolvePaperclipInstanceRoot } from "../../home-paths.js";
import fs from "node:fs/promises";
import path from "node:path";
import { CONTROLLER_PROVISION_COPY_ONLY, workspaceRequiresCopyOnlyProvisioning } from "../workspace-host-provision.js";
import { and, asc, eq } from "drizzle-orm";
import { type ExecutionWorkspace } from "@paperclipai/shared";
import { heartbeatRuns, projectWorkspaces } from "@paperclipai/db";
@@ -93,6 +94,7 @@ export interface HeartbeatWorkspacePreparationInput {
context: Record<string, unknown>;
responsibleUserId: string | null;
previousSessionParams: Record<string, unknown> | null;
workspaceSelection?: import("@paperclipai/shared").TaskWorkspaceIntent | null;
};
policy: {
trustPreset: TrustPresetResolution;
@@ -326,13 +328,19 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac
: workspace;
},
});
const skipHostProvision = trustPreset.kind === "low_trust_review"
&& lowTrustPreflightEnvironmentDriver === "sandbox";
const hostProvisionDriver = selectedEnvironmentForConfig?.driver ?? lowTrustPreflightEnvironmentDriver;
const copyOnlyProvisioning = await workspaceRequiresCopyOnlyProvisioning(db, {
companyId: agent.companyId,
task: issueRef ? { ...issueRef, workspaceSelection: input.task.workspaceSelection } : null,
sourceProjectId: resolvedWorkspace.projectId,
sourceWorkspaceId: resolvedWorkspace.workspaceId,
boundWorkspace: reusableExistingExecutionWorkspace ?? existingExecutionWorkspace,
});
const skipHostProvision = copyOnlyProvisioning || hostProvisionDriver === "sandbox" || hostProvisionDriver === "ssh";
const hostExecutionWorkspaceConfig = isDotRun ? {} :
stripHostWorkspaceProvisionForLowTrustSandbox({
stripHostWorkspaceProvision({
config: mergedConfig,
trustPreset,
selectedEnvironmentDriver: lowTrustPreflightEnvironmentDriver,
skipHostProvision,
});
const executionWorkspaceBase = {
baseCwd: resolvedWorkspace.cwd,
@@ -743,6 +751,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac
}
const nextExecutionWorkspaceMetadata = {
...baseExecutionWorkspaceMetadata,
...(copyOnlyProvisioning ? { [CONTROLLER_PROVISION_COPY_ONLY]: true } : {}),
...(persistedWorktreeInstanceRoot
? {
[WORKTREE_INSTANCE_ROOT_METADATA_KEY]:
@@ -1126,6 +1135,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac
return {
resolvedWorkspace,
hostExecutionWorkspaceConfig,
skipHostProvision,
latestWorkspaceConfigMetadata,
workspaceConfigFreshness,
workspaceOperationRecorder,
+8 -10
View File
@@ -330,18 +330,17 @@ export function buildExecutionWorkspaceConfigSnapshot(
return hasSnapshot ? snapshot : null;
}
export function stripHostWorkspaceProvisionForLowTrustSandbox(input: {
export function stripHostWorkspaceProvision(input: {
config: Record<string, unknown>;
trustPreset: TrustPresetResolution;
selectedEnvironmentDriver: string | null | undefined;
skipHostProvision: boolean;
}): Record<string, unknown> {
if (input.trustPreset.kind !== "low_trust_review") return input.config;
if (input.selectedEnvironmentDriver !== "sandbox") return input.config;
if (!input.skipHostProvision) return input.config;
const workspaceStrategy = parseObject(input.config.workspaceStrategy);
if (
typeof workspaceStrategy.provisionCommand !== "string" &&
typeof workspaceStrategy.runtimeProvisionCommand !== "string"
typeof workspaceStrategy.runtimeProvisionCommand !== "string" &&
typeof input.config.runtimeProvisionCommand !== "string"
)
return input.config;
@@ -349,10 +348,9 @@ export function stripHostWorkspaceProvisionForLowTrustSandbox(input: {
delete nextWorkspaceStrategy.provisionCommand;
delete nextWorkspaceStrategy.runtimeProvisionCommand;
return {
...input.config,
workspaceStrategy: nextWorkspaceStrategy,
};
const nextConfig: Record<string, unknown> = { ...input.config, workspaceStrategy: nextWorkspaceStrategy };
delete nextConfig.runtimeProvisionCommand;
return nextConfig;
}
export async function preflightLowTrustWorkspaceIsolation(input: {
@@ -0,0 +1,27 @@
import { projectWorkspaces, type Db } from "@paperclipai/db";
import type { TaskWorkspaceIntent } from "@paperclipai/shared";
import { and, asc, eq } from "drizzle-orm";
export const CONTROLLER_PROVISION_COPY_ONLY = "_controllerProvisionCopyOnly";
export async function workspaceRequiresCopyOnlyProvisioning(db: Db | Parameters<Parameters<Db["transaction"]>[0]>[0], input: {
companyId: string;
task: { id: string; projectId: string | null; workspaceSelection?: TaskWorkspaceIntent | null } | null;
sourceProjectId: string | null;
sourceWorkspaceId: string | null;
boundWorkspace?: { sourceIssueId?: string | null; metadata?: Record<string, unknown> | null } | null;
}) {
if (input.boundWorkspace?.metadata?.[CONTROLLER_PROVISION_COPY_ONLY] === true) return true;
const task = input.task;
if (!task) return Boolean(input.sourceProjectId || input.sourceWorkspaceId);
const intent = task.workspaceSelection;
if (intent && !["project", "operator_cwd", "task_default"].includes(intent.source)) return true;
if (intent?.selection.kind === "existing") return true;
if (input.boundWorkspace?.sourceIssueId && input.boundWorkspace.sourceIssueId !== task.id) return true;
if (intent?.source === "operator_cwd" && !input.sourceProjectId && !input.sourceWorkspaceId) return false;
if (!input.sourceProjectId || input.sourceProjectId !== task.projectId || !input.sourceWorkspaceId) return true;
const [defaultSource] = await db.select({ id: projectWorkspaces.id }).from(projectWorkspaces)
.where(and(eq(projectWorkspaces.companyId, input.companyId), eq(projectWorkspaces.projectId, input.sourceProjectId)))
.orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)).limit(1);
return !defaultSource || defaultSource.id !== input.sourceWorkspaceId;
}
+4 -1
View File
@@ -7448,6 +7448,7 @@ type EnsureRuntimeServicesForRunInput = {
workspace: RealizedExecutionWorkspace;
executionWorkspaceId?: string | null;
config: Record<string, unknown>;
skipHostProvision?: boolean;
adapterEnv: Record<string, string>;
onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
recorder?: WorkspaceOperationRecorder | null;
@@ -7464,7 +7465,9 @@ async function ensureRuntimeServicesForRunInvocation(
});
const acquiredServiceIds: string[] = [];
const refs: RuntimeServiceRef[] = [];
const runtimeProvision = resolveRuntimeProvision(input);
const runtimeProvision = input.skipHostProvision
? { command: "", kind: null }
: resolveRuntimeProvision(input);
const runtimeProvisionCommand = runtimeProvision.command;
const provisionCoordinator = createRuntimeProvisionCoordinator();
const allowFixedPortFallback = await isPersistedIsolatedExecutionWorkspace({