mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 02:30:43 +01:00
feat: give tasks durable project-optional workspaces
Separate task organization from filesystem ownership. Add channel defaults, workspace and repository tools, safe admission transitions, and sparse native workspace persistence. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
3389bea708
commit
ec2210e4f8
120 files changed
+4984
-921
No files matched your search
@@ -7556,6 +7556,39 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
expect((await db.select().from(chatDeliveries).where(eq(chatDeliveries.id, delivery.id)))[0].state).toBe("filtered");
|
||||
});
|
||||
|
||||
it("snapshots channel workspace defaults on new tasks and preserves them on replies", async () => {
|
||||
const fixture = await seedCompany();
|
||||
const { callbacks, endpoint, service } = await configuredSlackEndpoint(fixture);
|
||||
await service.update(endpoint.id, { executionDefaults: { workspace: { kind: "task_directory" } } }, "owner-user");
|
||||
const thread = makeThread({ channelId: "C-WORKSPACE", id: "slack:C-WORKSPACE:8100.1", name: "workspace" });
|
||||
await deliverMessage({ callbacks, endpointId: endpoint.id, thread: thread.thread,
|
||||
message: makeMessage({ id: "8100.1", text: "@maya make a report", mentioned: true }), trigger: "mention" });
|
||||
const conversations = () => db.select().from(chatConversations).where(eq(chatConversations.endpointId, endpoint.id)).orderBy(asc(chatConversations.createdAt));
|
||||
const [first] = await conversations();
|
||||
const [task] = await db.select().from(issues).where(eq(issues.id, first.issueId));
|
||||
expect(task.projectId).toBeNull();
|
||||
expect(task.workspaceSelection).toEqual({ version: 1, selection: { kind: "task_directory" }, source: "channel" });
|
||||
const [resource] = (await service.listResources(endpoint.id)).filter(row => row.providerResourceId === "C-WORKSPACE");
|
||||
expect(resource).toBeDefined();
|
||||
await service.replaceResources(endpoint.id, [{ id: resource.id, executionDefaults: { workspace: null } }], "owner-user");
|
||||
expect((await service.listResources(endpoint.id)).find(row => row.id === resource.id)?.enabled).toBe(resource.enabled);
|
||||
await service.update(endpoint.id, { executionDefaults: null }, "owner-user");
|
||||
await deliverMessage({ callbacks, endpointId: endpoint.id, thread: thread.thread,
|
||||
message: makeMessage({ id: "8100.2", text: "Continue" }), trigger: "subscribed_message" });
|
||||
const [unchanged] = await db.select().from(issues).where(eq(issues.id, first.issueId));
|
||||
expect(unchanged.workspaceSelection).toEqual(task.workspaceSelection);
|
||||
await service.update(endpoint.id, { executionDefaults: { workspace: { kind: "task_directory" } } }, "owner-user");
|
||||
const next = makeThread({ channelId: "C-WORKSPACE", id: "slack:C-WORKSPACE:8200.1", name: "workspace" });
|
||||
await deliverMessage({ callbacks, endpointId: endpoint.id, thread: next.thread,
|
||||
message: makeMessage({ id: "8200.1", text: "@maya another report", mentioned: true }), trigger: "mention" });
|
||||
const rows = await conversations();
|
||||
expect(rows).toHaveLength(2);
|
||||
const [second] = await db.select().from(issues).where(eq(issues.id, rows[1].issueId));
|
||||
expect(second.workspaceSelection).toBeNull();
|
||||
await expect(service.update(endpoint.id, { executionDefaults: { projectId: randomUUID() } }, "owner-user")).rejects.toMatchObject({ status: 404 });
|
||||
expect((await service.get(endpoint.id)).executionDefaults).toEqual({ workspace: { kind: "task_directory" } });
|
||||
});
|
||||
|
||||
it("captures initial Slack communication guidance once per task, ignoring forged message configuration", async () => {
|
||||
const fixture = await seedCompany();
|
||||
const { callbacks, endpoint, service } = await configuredSlackEndpoint(fixture);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { chatExecutionDefaultsSchema, updateChatEndpointSchema, replaceChatEndpointResourcesSchema } from "@paperclipai/shared";
|
||||
import { resolveChatExecutionDefaults } from "../services/chat-execution-defaults.js";
|
||||
|
||||
const projectId = "11f01381-578d-4bb7-9de4-57e6d9678313";
|
||||
const workspaceId = "13f01381-578d-4bb7-9de4-57e6d9678313";
|
||||
|
||||
describe("channel execution defaults", () => {
|
||||
it("leaves unconfigured channels on common task defaults", () => {
|
||||
expect(resolveChatExecutionDefaults(null, null)).toEqual({});
|
||||
});
|
||||
it("inherits omitted properties and clears explicit null independently", () => {
|
||||
expect(resolveChatExecutionDefaults({ projectId, workspace: { kind: "existing", workspaceId } }, { projectId: null }))
|
||||
.toEqual({ projectId: null, workspace: { kind: "existing", workspaceId } });
|
||||
expect(resolveChatExecutionDefaults({ projectId, workspace: { kind: "existing", workspaceId } }, { workspace: null }))
|
||||
.toEqual({ projectId, workspace: null });
|
||||
});
|
||||
it("resource task directories override endpoint shared choices", () => {
|
||||
expect(resolveChatExecutionDefaults({ workspace: { kind: "existing", workspaceId } }, { workspace: { kind: "task_directory" } }))
|
||||
.toEqual({ workspace: { kind: "task_directory" } });
|
||||
});
|
||||
it("rejects unknown fields, paths and commands rather than granting filesystem authority", () => {
|
||||
for (const input of [{ cwd: "/tmp" }, { workspace: { kind: "task_directory", command: "echo hello" } }, { projectId: "not-a-uuid" }]) {
|
||||
expect(chatExecutionDefaultsSchema.safeParse(input).success).toBe(false);
|
||||
}
|
||||
});
|
||||
it("accepts defaults through both endpoint and resource management contracts", () => {
|
||||
expect(updateChatEndpointSchema.parse({ executionDefaults: { projectId } })).toEqual({ executionDefaults: { projectId } });
|
||||
expect(replaceChatEndpointResourcesSchema.parse({ resources: [{ id: workspaceId, enabled: true, executionDefaults: { workspace: null } }] }).resources[0].executionDefaults)
|
||||
.toEqual({ workspace: null });
|
||||
});
|
||||
});
|
||||
@@ -475,6 +475,22 @@ describe("AgentMail durable email pipeline", () => {
|
||||
await db.select().from(issues).where(eq(issues.companyId, f.companyId)),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
it("snapshots email workspace defaults only when a conversation creates a task", async () => {
|
||||
const f = await fixture();
|
||||
await db.update(chatEndpoints).set({ executionDefaults: { workspace: { kind: "task_directory" } } }).where(eq(chatEndpoints.id, f.endpointId));
|
||||
const first = f.message();
|
||||
await f.receive(first);
|
||||
const tasks = () => db.select().from(issues).where(eq(issues.companyId, f.companyId));
|
||||
const [task] = await tasks();
|
||||
expect(task.workspaceSelection).toEqual({ version: 1, selection: { kind: "task_directory" }, source: "channel" });
|
||||
expect(task.projectId).toBeNull();
|
||||
await db.update(chatEndpoints).set({ executionDefaults: null }).where(eq(chatEndpoints.id, f.endpointId));
|
||||
await f.receive(f.message(randomUUID(), first.thread_id));
|
||||
expect((await tasks())[0].workspaceSelection).toEqual(task.workspaceSelection);
|
||||
await f.receive(f.message());
|
||||
expect(await tasks()).toEqual(expect.arrayContaining([expect.objectContaining({ workspaceSelection: null })]));
|
||||
});
|
||||
|
||||
it("deduplicates events/messages, keeps identical subjects separate, and never grants sender board identity", async () => {
|
||||
const f = await fixture();
|
||||
const m = f.message();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { mkdtemp, rm, stat } from "node:fs/promises";
|
||||
@@ -48,7 +49,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-reopen-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 20_000);
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(activityLog);
|
||||
@@ -261,6 +262,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
|
||||
workspaceId,
|
||||
issue: { id: issueId, companyId, projectId },
|
||||
actor: { agentId: null, actorType: "user" },
|
||||
authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true },
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
@@ -282,6 +284,22 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
|
||||
expect(issueRow?.executionWorkspaceId).toBe(workspaceId);
|
||||
});
|
||||
|
||||
it("reopens the persisted source after the task leaves its organizational project", async () => {
|
||||
const { companyId, projectId, projectWorkspaceId } = await seedCompanyProject();
|
||||
const cwd = await makeExistingDir();
|
||||
const workspaceId = await seedClosedWorkspace({ companyId, projectId, projectWorkspaceId, cwd });
|
||||
const issueId = await seedIssue({ companyId, projectId, workspaceId, issueNumber: 4105 });
|
||||
await db.update(issues).set({ projectId: null }).where(eq(issues.id, issueId));
|
||||
const result = await executionWorkspaceService(db).reopenClosedIsolatedExecutionWorkspaceForIssue({
|
||||
workspaceId,
|
||||
issue: { id: issueId, companyId, projectId: null },
|
||||
actor: { agentId: null, actorType: "user" },
|
||||
authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true },
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
expect((await readWorkspace(workspaceId))?.projectId).toBe(projectId);
|
||||
});
|
||||
|
||||
it("keeps access for every issue that shares the reopened row", async () => {
|
||||
const { companyId, projectId, projectWorkspaceId } = await seedCompanyProject();
|
||||
const cwd = await makeExistingDir();
|
||||
@@ -294,6 +312,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
|
||||
workspaceId,
|
||||
issue: { id: firstIssueId, companyId, projectId },
|
||||
actor: { agentId: null, actorType: "user" },
|
||||
authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true },
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
|
||||
@@ -324,6 +343,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
|
||||
workspaceId,
|
||||
issue: { id: issueId, companyId, projectId },
|
||||
actor: { agentId: null, actorType: "user" },
|
||||
authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true },
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
@@ -369,6 +389,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
|
||||
workspaceId,
|
||||
issue: { id: issueId, companyId, projectId },
|
||||
actor: { agentId: null, actorType: "user" },
|
||||
authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true },
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
@@ -406,6 +427,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
|
||||
// The issue belongs to a different company than the workspace.
|
||||
issue: { id: randomUUID(), companyId: second.companyId, projectId: second.projectId },
|
||||
actor: { agentId: null, actorType: "user" },
|
||||
authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true },
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
@@ -434,6 +456,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
|
||||
workspaceId,
|
||||
issue: { id: issueId, companyId, projectId },
|
||||
actor: { agentId: null, actorType: "user" },
|
||||
authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true },
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
@@ -497,6 +520,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
|
||||
workspaceId,
|
||||
issue: { id: issueId, companyId, projectId },
|
||||
actor: { agentId: null, actorType: "user" },
|
||||
authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true },
|
||||
});
|
||||
expect(reopenResult.ok).toBe(true);
|
||||
if (!reopenResult.ok) throw new Error("reopen failed");
|
||||
@@ -558,6 +582,7 @@ describeEmbeddedPostgres("reopen archived isolated execution workspace", () => {
|
||||
workspaceId,
|
||||
issue: { id: issueId, companyId, projectId },
|
||||
actor: { agentId: null, actorType: "user" },
|
||||
authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true },
|
||||
});
|
||||
expect(reopenResult.ok).toBe(true);
|
||||
if (!reopenResult.ok) throw new Error("reopen failed");
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import * as localServiceSupervisor from "../services/local-service-supervisor.js";
|
||||
import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import fs from "node:fs/promises";
|
||||
@@ -264,7 +266,7 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
|
||||
// tests further down.
|
||||
workspaceReaperCooldownDays: 0,
|
||||
});
|
||||
}, 20_000);
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(workspaceRuntimeServices);
|
||||
@@ -3704,6 +3706,11 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
|
||||
].join(" ");
|
||||
const command = `${JSON.stringify(process.execPath)} -e ${JSON.stringify(serverScript)}`;
|
||||
|
||||
// This case proves the DB reservation/start race, not host-wide lsof latency.
|
||||
// Keep the real process and HTTP readiness; its freshly allocated port has no prior owner.
|
||||
const portOwner = vi.spyOn(localServiceSupervisor, "readLocalServicePortOwner").mockResolvedValue(null);
|
||||
const adoption = vi.spyOn(localServiceSupervisor, "findAdoptableLocalService").mockResolvedValue(null);
|
||||
const runtimeOutput: string[] = [];
|
||||
let startedServices: Awaited<ReturnType<typeof startRuntimeServicesForWorkspaceControl>> = [];
|
||||
try {
|
||||
const startPromise = startRuntimeServicesForWorkspaceControl({
|
||||
@@ -3750,9 +3757,11 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
|
||||
},
|
||||
},
|
||||
adapterEnv: {},
|
||||
onLog: async (stream, chunk) => { runtimeOutput.push(`${stream}: ${chunk}`); },
|
||||
});
|
||||
|
||||
await Promise.race([
|
||||
try {
|
||||
await Promise.race([
|
||||
waitForPath(runtimeStartedMarker),
|
||||
startPromise.then(
|
||||
() => {
|
||||
@@ -3762,7 +3771,13 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
|
||||
throw error;
|
||||
},
|
||||
),
|
||||
]);
|
||||
]);
|
||||
} catch (error) {
|
||||
const activity = await db.execute(sql`select state, wait_event_type, wait_event,
|
||||
left(query, 240) as query from pg_stat_activity
|
||||
where datname = current_database() and pid <> pg_backend_pid()`);
|
||||
throw new Error(`Runtime activation did not reach its process marker. Output: ${runtimeOutput.join("") || "<none>"}. Database activity: ${JSON.stringify(activity)}`, { cause: error });
|
||||
}
|
||||
|
||||
const reconcileErrorPromise = svc.reconcileExecutionWorkspaceBranch(executionWorkspaceId, {
|
||||
mode: "override",
|
||||
@@ -3800,12 +3815,17 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await stopRuntimeServicesForExecutionWorkspace({
|
||||
db,
|
||||
executionWorkspaceId,
|
||||
workspaceCwd: worktreePath,
|
||||
});
|
||||
await fs.rm(runtimeStartedMarker, { force: true });
|
||||
try {
|
||||
await stopRuntimeServicesForExecutionWorkspace({
|
||||
db,
|
||||
executionWorkspaceId,
|
||||
workspaceCwd: worktreePath,
|
||||
});
|
||||
await fs.rm(runtimeStartedMarker, { force: true });
|
||||
} finally {
|
||||
portOwner.mockRestore();
|
||||
adoption.mockRestore();
|
||||
}
|
||||
}
|
||||
|
||||
const [workspace] = await db
|
||||
|
||||
@@ -200,12 +200,14 @@ describeEmbeddedPostgres("workspace file resources", () => {
|
||||
let db: Db;
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.stubEnv("PAPERCLIP_ISSUE_PRIVACY_MODE", "enforce");
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-file-resources-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await tempDb?.cleanup();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it("withholds private task files and private cross-project targets", async () => {
|
||||
@@ -311,6 +313,36 @@ describeEmbeddedPostgres("workspace file resources", () => {
|
||||
expect(resolved.capabilities.preview).toBe(true);
|
||||
});
|
||||
|
||||
it("reads projectless task files before and after organizational project assignment", async () => {
|
||||
const { projectRoot, executionRoot } = await makeWorkspace();
|
||||
const graph = await seedGraph(db, { projectRoot, executionRoot });
|
||||
await db.update(issues).set({ projectId: null, projectWorkspaceId: null }).where(eq(issues.id, graph.issueId));
|
||||
await db.update(executionWorkspaces).set({ projectId: null, projectWorkspaceId: null, strategyType: "project_primary", providerType: "local_fs" }).where(eq(executionWorkspaces.sourceIssueId, graph.issueId));
|
||||
await fs.writeFile(path.join(executionRoot, "report.txt"), "Task-owned report", "utf8");
|
||||
const app = createApp(db, { type: "board", userId: "board-user", companyIds: [graph.companyId], source: "session", isInstanceAdmin: false });
|
||||
for (const projectId of [null, graph.targetProjectId]) {
|
||||
await db.update(issues).set({ projectId }).where(eq(issues.id, graph.issueId));
|
||||
const result = await request(app).get(`/api/issues/${graph.issueId}/file-resources/content`).query({ workspace: "execution", path: "report.txt" }).expect(200);
|
||||
expect(result.body.content.data).toBe("Task-owned report");
|
||||
expect(result.body.resource.workspaceKind).toBe("execution_workspace");
|
||||
}
|
||||
});
|
||||
|
||||
it("reads a selected source independently of task project while retaining source privacy", async () => {
|
||||
const { projectRoot, targetProjectRoot, executionRoot } = await makeWorkspace();
|
||||
const graph = await seedGraph(db, { projectRoot, targetProjectRoot, executionRoot });
|
||||
await fs.writeFile(path.join(projectRoot, "source.txt"), "Selected source", "utf8");
|
||||
const app = createApp(db, { type: "board", userId: "board-user", companyIds: [graph.companyId], source: "session", isInstanceAdmin: false });
|
||||
for (const projectId of [null, graph.targetProjectId]) {
|
||||
await db.update(issues).set({ projectId }).where(eq(issues.id, graph.issueId));
|
||||
const result = await request(app).get(`/api/issues/${graph.issueId}/file-resources/content`).query({ workspace: "project", path: "source.txt" }).expect(200);
|
||||
expect(result.body.content.data).toBe("Selected source");
|
||||
expect(result.body.resource.workspaceId).toBe(graph.projectWorkspaceId);
|
||||
}
|
||||
await db.update(projects).set({ visibility: "private" }).where(eq(projects.id, graph.projectId));
|
||||
await request(app).get(`/api/issues/${graph.issueId}/file-resources/content`).query({ workspace: "project", path: "source.txt" }).expect(404);
|
||||
});
|
||||
|
||||
it("auto-discovers unhinted same-company project files when issue workspaces miss", async () => {
|
||||
const { projectRoot, targetProjectRoot, executionRoot } = await makeWorkspace();
|
||||
const graph = await seedGraph(db, { projectRoot, targetProjectRoot, executionRoot });
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { execFileSync } from "node:child_process";
|
||||
@@ -6,7 +7,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, companies, createDb, environments, executionWorkspaces, heartbeatRuns, issues, projects, projectWorkspaces } from "@paperclipai/db";
|
||||
import { agents, companies, companyMemberships, createDb, environments, executionWorkspaces, heartbeatRuns, issues, projects, projectWorkspaces } from "@paperclipai/db";
|
||||
import { setExpensiveWorkspaceGitExecutor } from "@paperclipai/adapter-utils/git-workspace-sync";
|
||||
import { buildProjectMentionHref } from "@paperclipai/shared";
|
||||
import { createWorkspaceGitOperationScheduler, WorkspaceGitScanError } from "../services/workspace-git-operation-scheduler.js";
|
||||
@@ -41,7 +42,7 @@ suite("task project repository provisioning", () => {
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, input.context.issueId));
|
||||
return { exitCode: 0, signal: null, timedOut: false };
|
||||
});
|
||||
}, 30_000);
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
afterAll(async () => {
|
||||
if (db && heartbeat) await drainHeartbeatRunsToQuiescence(db, heartbeat);
|
||||
await db?.$client.end({ timeout: 5 });
|
||||
@@ -65,6 +66,7 @@ suite("task project repository provisioning", () => {
|
||||
vi.stubEnv("PAPERCLIP_MULTI_PROJECT_WORKSPACE_SYNC", "true");
|
||||
await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true });
|
||||
await db.insert(companies).values({ id: companyId, name: "Email company", issuePrefix: `E${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: "Onboarding" });
|
||||
for (const id of [referencedProjectId, deniedProjectId]) {
|
||||
const source = path.join(root, companyId, id);
|
||||
@@ -147,6 +149,7 @@ suite("task project repository provisioning", () => {
|
||||
enableIsolatedWorkspacesByDefault: true,
|
||||
});
|
||||
await db.insert(companies).values({ id: companyId, name: "Research", 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: "Research", status: "in_progress",
|
||||
executionWorkspacePolicy: explicitIsolation === "project" ? { enabled: true, defaultMode: "isolated_workspace" } : null,
|
||||
@@ -186,7 +189,7 @@ suite("task project repository provisioning", () => {
|
||||
expect(workspace.strategy).toBe("git_worktree");
|
||||
expect(execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: workspace.cwd, encoding: "utf8" }).trim()).toBe("true");
|
||||
} else {
|
||||
expect(workspace.cwd).toContain(`${projectId}/_default`);
|
||||
expect(workspace.cwd).toContain(`/isolated-workspaces/${companyId}/${issueId}`);
|
||||
}
|
||||
}
|
||||
}, 25_000);
|
||||
@@ -212,6 +215,7 @@ suite("task project repository provisioning", () => {
|
||||
await writeFile(path.join(source, "README.md"), "preserved dirty work");
|
||||
await writeFile(path.join(source, "private.secret"), "must not copy");
|
||||
await db.insert(companies).values({ id: companyId, name: "Bootstrap recovery", 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: "Local source", status: "in_progress" });
|
||||
await db.insert(projectWorkspaces).values([
|
||||
{ id: randomUUID(), companyId, projectId, name: "Anchor", sourceType: "local_path", cwd: source, isPrimary: true, createdAt: new Date(Date.now() - 1000) },
|
||||
@@ -313,6 +317,7 @@ suite("task project repository provisioning", () => {
|
||||
repositoryRows.push({ id: randomUUID(), companyId, projectId, name: `Repo ${index}`, sourceType: "git_repo", repoUrl: pathToFileURL(source).href, cwd: null, isPrimary: index === 0 });
|
||||
}
|
||||
await db.insert(companies).values({ id: companyId, name: "Repo test", 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: "Multi-repo", status: "in_progress" });
|
||||
await db.insert(projectWorkspaces).values(repositoryRows);
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Test", role: "engineer", status: "idle", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} });
|
||||
|
||||
@@ -525,7 +525,7 @@ describeEmbeddedPostgres("shared-workspace run serialization", () => {
|
||||
expect(retryRuns).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("allow passes the busy gate for a sandbox environment and adds coordination context", async () => {
|
||||
it("rejects unproven concurrent physical sharing in a sandbox environment", async () => {
|
||||
const fixture = await seedWorkspaceFixture({
|
||||
issueWorkspaceSettings: { sharedWorkspaceConcurrency: "allow" },
|
||||
agentEnvironmentDriver: "sandbox",
|
||||
@@ -540,11 +540,8 @@ describeEmbeddedPostgres("shared-workspace run serialization", () => {
|
||||
expect(run).not.toBeNull();
|
||||
|
||||
const finishedRun = await waitForRunToLeaveActiveStates(run!.id);
|
||||
expect(finishedRun?.errorCode).not.toBe(WORKSPACE_BUSY_ERROR_CODE);
|
||||
expect(executedRunIds).toContain(run!.id);
|
||||
expect((finishedRun?.contextSnapshot as Record<string, unknown>)?.paperclipTaskMarkdown).toContain(
|
||||
`shared workspace is concurrently held by run ${fixture.holderRunId}`,
|
||||
);
|
||||
expect(executedRunIds).not.toContain(run!.id);
|
||||
expect(finishedRun?.error).toContain("cannot place concurrent agents in one physical shared folder");
|
||||
const retryRuns = await db
|
||||
.select({ id: heartbeatRuns.id })
|
||||
.from(heartbeatRuns)
|
||||
|
||||
@@ -250,19 +250,19 @@ function buildIssueAncestryDb(rows: Array<{ id: string; companyId: string; paren
|
||||
}
|
||||
|
||||
describe("assertGitSensitiveAdapterWorkspaceValid", () => {
|
||||
it("rejects a project-workspace-linked issue that is missing its project id before adapter launch", async () => {
|
||||
await expectWorkspaceValidationFailure(
|
||||
buildWorkspaceValidationInput({
|
||||
issue: {
|
||||
id: "issue-1",
|
||||
identifier: "PAP-1",
|
||||
projectId: null,
|
||||
projectWorkspaceId: "workspace-1",
|
||||
},
|
||||
}),
|
||||
"missing_project_id",
|
||||
"linked to a project workspace but has no project id",
|
||||
);
|
||||
it("accepts a projectless issue using an authorized persisted source workspace", async () => {
|
||||
await expect(assertGitSensitiveAdapterWorkspaceValid(buildWorkspaceValidationInput({
|
||||
issue: { id: "issue-1", identifier: "PAP-1", projectId: null, projectWorkspaceId: "workspace-1" },
|
||||
resolvedWorkspace: buildResolvedWorkspace({ localPathOnlyWorkspace: true }),
|
||||
}))).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects a configured source without source-project evidence", async () => {
|
||||
const input = buildWorkspaceValidationInput();
|
||||
await expectWorkspaceValidationFailure(buildWorkspaceValidationInput({
|
||||
issue: { id: "issue-1", identifier: "PAP-1", projectId: null, projectWorkspaceId: "workspace-1" },
|
||||
persistedExecutionWorkspace: { ...input.persistedExecutionWorkspace!, projectId: null },
|
||||
}), "missing_project_id", "linked to a project workspace but has no project id");
|
||||
});
|
||||
|
||||
it("rejects a git-sensitive local adapter when effective cwd differs from the persisted workspace cwd", async () => {
|
||||
|
||||
@@ -267,6 +267,7 @@ describe("closed isolated workspace issue routes", () => {
|
||||
workspaceId: closedWorkspaceId,
|
||||
issue: { id: issueId, companyId: "company-1", projectId: null },
|
||||
actor: expect.objectContaining({ actorType: "user" }),
|
||||
authorizationActor: expect.objectContaining({ type: "board", source: "local_implicit" }),
|
||||
});
|
||||
// The closed-workspace dead end is gone: the comment is accepted.
|
||||
expect(res.status).toBe(201);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { mkdtemp, mkdir, writeFile, readFile, readdir, rm, stat } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { materializeManagedProjectWorkspace, ensureManagedRepositoriesIgnored } from "../services/managed-repository-checkout.js";
|
||||
|
||||
const execFile = promisify(execFileCallback);
|
||||
const directories: string[] = [];
|
||||
afterEach(async () => { await Promise.all(directories.splice(0).map(dir => rm(dir, { recursive: true, force: true }))); });
|
||||
async function fixture() {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paperclip-repository-publication-"));
|
||||
directories.push(root);
|
||||
const source = path.join(root, "source");
|
||||
await mkdir(source);
|
||||
await execFile("git", ["init", "--initial-branch=main", source]);
|
||||
await writeFile(path.join(source, "source.txt"), "initial\n");
|
||||
await execFile("git", ["-C", source, "add", "."]);
|
||||
await execFile("git", ["-C", source, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "initial"]);
|
||||
return { root, source, target: path.join(root, "target") };
|
||||
}
|
||||
describe("atomic managed repository publication", () => {
|
||||
it("keeps managed repositories separate without requiring Git or touching an ancestor", async () => {
|
||||
const { source, target } = await fixture();
|
||||
await mkdir(target);
|
||||
await expect(ensureManagedRepositoriesIgnored(target)).resolves.toBeUndefined();
|
||||
const nestedPlainRoot = path.join(source, "plain-task");
|
||||
await mkdir(nestedPlainRoot);
|
||||
const original = await readFile(path.join(source, ".git", "info", "exclude"), "utf8");
|
||||
await ensureManagedRepositoriesIgnored(nestedPlainRoot);
|
||||
expect(await readFile(path.join(source, ".git", "info", "exclude"), "utf8")).toBe(original);
|
||||
await ensureManagedRepositoriesIgnored(source);
|
||||
expect(await readFile(path.join(source, ".git", "info", "exclude"), "utf8")).toContain("/.paperclip-repositories/");
|
||||
});
|
||||
it("writes the pinned receipt inside the clone before making it visible", async () => {
|
||||
const { source, target } = await fixture();
|
||||
const result = await materializeManagedProjectWorkspace(target, { repoUrl: "https://github.com/test/source", localSource: source, beforePublish: async clone => {
|
||||
expect(await stat(target).catch(() => null)).toBeNull();
|
||||
const commit = (await execFile("git", ["-C", clone, "rev-parse", "HEAD"])).stdout.trim();
|
||||
await writeFile(path.join(clone, ".git", "paperclip-workspace-owner.json"), JSON.stringify({ repositoryId: "receipt", pinnedCommit: commit }));
|
||||
} });
|
||||
expect(result.warning).toBeNull();
|
||||
expect(JSON.parse(await readFile(path.join(target, ".git", "paperclip-workspace-owner.json"), "utf8"))).toMatchObject({ repositoryId: "receipt", pinnedCommit: expect.stringMatching(/^[a-f0-9]{40}$/) });
|
||||
expect(await readFile(path.join(target, "source.txt"), "utf8")).toBe("initial\n");
|
||||
});
|
||||
it("does not publish an incomplete checkout when its receipt cannot be committed", async () => {
|
||||
const { root, source, target } = await fixture();
|
||||
await expect(materializeManagedProjectWorkspace(target, { repoUrl: "https://github.com/test/source", localSource: source, beforePublish: async () => { throw new Error("receipt failed"); } })).rejects.toThrow(/receipt failed/);
|
||||
expect(await stat(target).catch(() => null)).toBeNull();
|
||||
expect((await readdir(root)).filter(name => name.startsWith("target.clone-"))).toEqual([]);
|
||||
expect(await readFile(path.join(source, "source.txt"), "utf8")).toBe("initial\n");
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import type { EnvironmentLease } from "@paperclipai/shared";
|
||||
import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
|
||||
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
||||
import { runLocalGit } from "@paperclipai/adapter-utils/git-workspace-sync";
|
||||
import { prepareNativeWorkspaceSync } from "../services/native-runtime/native-workspace-sync.js";
|
||||
import { prepareNativeWorkspaceSync, nativeWorkspaceSyncInternals } from "../services/native-runtime/native-workspace-sync.js";
|
||||
|
||||
const runner: CommandManagedRuntimeRunner = {
|
||||
execute: (input) => new Promise((resolve, reject) => {
|
||||
@@ -44,7 +44,7 @@ describe("native warm workspace Git history", () => {
|
||||
await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
it.each(["unchanged", "host_commit", "host_branch", "remote_commit", "nested_commit"] as const)(
|
||||
it.each(["unchanged", "host_commit", "host_branch", "host_origin", "remote_commit", "nested_commit", "plain_nested_commit"] as const)(
|
||||
"checks Git identity before reusing a warm sandbox: %s", async (change) => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-warm-history-"));
|
||||
roots.push(root);
|
||||
@@ -61,9 +61,10 @@ describe("native warm workspace Git history", () => {
|
||||
await git(dir, "add", ".");
|
||||
await git(dir, "commit", "-m", "base");
|
||||
}
|
||||
await initRepo(host);
|
||||
if (change === "plain_nested_commit") await mkdir(host, { recursive: true });
|
||||
else await initRepo(host);
|
||||
const nestedPath = path.join(".paperclip-repositories", "nested");
|
||||
if (change === "nested_commit") await initRepo(path.join(host, nestedPath));
|
||||
if (change === "nested_commit" || change === "plain_nested_commit") await initRepo(path.join(host, nestedPath));
|
||||
const lease = { id: "lease", providerLeaseId: "sandbox", metadata: {} } as EnvironmentLease;
|
||||
let runnerProfileJson: Record<string, unknown> = {};
|
||||
// Persist the real service's descriptors and stamps; only the DB query
|
||||
@@ -94,29 +95,40 @@ describe("native warm workspace Git history", () => {
|
||||
const input = { db: db as unknown as Db, companyId: "company", workspaceId: "workspace", workspaceLocalDir: host, lease, target };
|
||||
const first = (await prepareNativeWorkspaceSync({ ...input, runId: "first" }))!;
|
||||
expect(first.mode).toBe("host_current");
|
||||
expect(first.reference.schema).toBe("paperclip.native-workspace-sync/v3");
|
||||
if (change === "plain_nested_commit") {
|
||||
const recovered = await nativeWorkspaceSyncInternals.readDescriptor({ runId: "first", reference: first.reference });
|
||||
expect(recovered.descriptor.gitSnapshot).toBeNull();
|
||||
expect(recovered.descriptor.repositories?.[0]?.path).toBe(nestedPath);
|
||||
}
|
||||
await first.restoreWorkspace();
|
||||
await first.cleanup();
|
||||
|
||||
if (change === "host_commit" || change === "nested_commit") {
|
||||
await git(change === "nested_commit" ? path.join(host, nestedPath) : host, "commit", "--allow-empty", "-m", "host only");
|
||||
if (change === "host_commit" || change === "nested_commit" || change === "plain_nested_commit") {
|
||||
await git(change === "nested_commit" || change === "plain_nested_commit" ? path.join(host, nestedPath) : host, "commit", "--allow-empty", "-m", "host only");
|
||||
} else if (change === "host_branch") {
|
||||
await git(host, "checkout", "-b", "other");
|
||||
} else if (change === "host_origin") {
|
||||
await git(host, "remote", "add", "origin", "https://github.com/paperclipai/new-source.git");
|
||||
} else if (change === "remote_commit") {
|
||||
await git(remote, "-c", "user.name=Test", "-c", "user.email=test@paperclip.dev", "commit", "--allow-empty", "-m", "remote only");
|
||||
}
|
||||
const expectedHead = await git(host, "rev-parse", "HEAD");
|
||||
const expectedBranch = await git(host, "symbolic-ref", "--short", "HEAD");
|
||||
const nestedHead = change === "nested_commit" ? await git(path.join(host, nestedPath), "rev-parse", "HEAD") : null;
|
||||
const hostRepo = change === "plain_nested_commit" ? path.join(host, nestedPath) : host;
|
||||
const remoteRepo = change === "plain_nested_commit" ? path.join(remote, nestedPath) : remote;
|
||||
const expectedHead = await git(hostRepo, "rev-parse", "HEAD");
|
||||
const expectedBranch = await git(hostRepo, "symbolic-ref", "--short", "HEAD");
|
||||
const nestedHead = change === "nested_commit" || change === "plain_nested_commit" ? await git(path.join(host, nestedPath), "rev-parse", "HEAD") : null;
|
||||
runnerProfileJson = {};
|
||||
const second = (await prepareNativeWorkspaceSync({ ...input, runId: "second", target: {
|
||||
...target, sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId: "sandbox" },
|
||||
} }))!;
|
||||
try {
|
||||
expect(second.mode).toBe(change === "unchanged" ? "adopt_remote" : "host_current");
|
||||
expect(await git(remote, "rev-parse", "HEAD")).toBe(expectedHead);
|
||||
expect(await git(remote, "symbolic-ref", "--short", "HEAD")).toBe(expectedBranch);
|
||||
expect(await git(remoteRepo, "rev-parse", "HEAD")).toBe(expectedHead);
|
||||
expect(await git(remoteRepo, "symbolic-ref", "--short", "HEAD")).toBe(expectedBranch);
|
||||
if (change === "host_origin") expect(await git(remote, "remote", "get-url", "origin")).toBe("https://github.com/paperclipai/new-source.git");
|
||||
await second.restoreWorkspace();
|
||||
expect(await git(host, "rev-parse", "HEAD")).toBe(expectedHead);
|
||||
expect(await git(hostRepo, "rev-parse", "HEAD")).toBe(expectedHead);
|
||||
if (nestedHead) {
|
||||
expect(await git(path.join(remote, nestedPath), "rev-parse", "HEAD")).toBe(nestedHead);
|
||||
expect(await git(path.join(host, nestedPath), "rev-parse", "HEAD")).toBe(nestedHead);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { ensurePersistedExecutionWorkspaceAvailable } from "../services/workspace-runtime.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { canApplyTaskWorkspaceSelectionAtAdmission, taskWorkspaceRuntimeSelectionEnabled, parseIssueExecutionWorkspaceSettings, resolveExecutionWorkspaceMode } from "../services/execution-workspace-policy.js";
|
||||
|
||||
describe("task workspace admission authority", () => {
|
||||
it.each([{ hasTypedSelection: true, hasBinding: false }, { hasTypedSelection: false, hasBinding: true }])("keeps isolated intent authoritative with the legacy UI disabled: %j", flags => {
|
||||
const enabled = taskWorkspaceRuntimeSelectionEnabled({ legacyUiEnabled: false, ...flags });
|
||||
const settings = enabled ? parseIssueExecutionWorkspaceSettings({ mode: "isolated_workspace" }) : null;
|
||||
expect(resolveExecutionWorkspaceMode({ projectPolicy: null, issueSettings: settings, legacyUseProjectWorkspace: null })).toBe("isolated_workspace");
|
||||
});
|
||||
it.each([
|
||||
{ admittedInput: { schema: "paperclip.native-execution-input.v3", binding: { executionWorkspaceId: "old-projectless-run" } }, restarting: false, hasLeaseOwner: false },
|
||||
{ admittedInput: null, restarting: true, hasLeaseOwner: false },
|
||||
{ admittedInput: null, restarting: false, hasLeaseOwner: true },
|
||||
])("defers pending root changes while immutable execution/recovery owns the root", admission => {
|
||||
expect(canApplyTaskWorkspaceSelectionAtAdmission(admission)).toBe(false);
|
||||
});
|
||||
it("keeps a persisted task-owned source projectless when current organizational defaults have a project", async () => {
|
||||
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-source-authority-"));
|
||||
try {
|
||||
const restored = await ensurePersistedExecutionWorkspaceAvailable({
|
||||
base: { baseCwd: cwd, source: "project_primary", projectId: "org-project", workspaceId: "org-source", repoUrl: null, repoRef: null },
|
||||
workspace: { mode: "shared_workspace", strategyType: "project_primary", cwd, providerRef: cwd,
|
||||
projectId: null, projectWorkspaceId: null, repoUrl: null, baseRef: null, branchName: null },
|
||||
issue: { id: "task", identifier: null, title: "Retain files" },
|
||||
agent: { id: "agent", companyId: "company", name: "Agent" },
|
||||
});
|
||||
expect(restored).toMatchObject({ cwd, projectId: null, workspaceId: null });
|
||||
} finally { await fs.rm(cwd, { recursive: true, force: true }); }
|
||||
});
|
||||
it("permits new admission to apply explicit pending intent", () => {
|
||||
expect(canApplyTaskWorkspaceSelectionAtAdmission({ admittedInput: null, restarting: false, hasLeaseOwner: false })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { executionWorkspaces, issues, heartbeatRuns } from "@paperclipai/db";
|
||||
import { startRunnerApiTestServer } from "./helpers/runner-api-server.js";
|
||||
import { getEmbeddedPostgresTestSupport } from "./helpers/embedded-postgres.js";
|
||||
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
(support.supported ? describe : describe.skip)("task workspace API and native semantic authority", () => {
|
||||
let server: Awaited<ReturnType<typeof startRunnerApiTestServer>>;
|
||||
const originalSecret = process.env.PAPERCLIP_AGENT_JWT_SECRET;
|
||||
beforeAll(async () => { process.env.PAPERCLIP_AGENT_JWT_SECRET = randomUUID(); server = await startRunnerApiTestServer(); }, 60_000);
|
||||
afterAll(async () => { await server?.close(); if (originalSecret === undefined) delete process.env.PAPERCLIP_AGENT_JWT_SECRET; else process.env.PAPERCLIP_AGENT_JWT_SECRET = originalSecret; });
|
||||
it("inspects admitted files, durably requests a repository, and stages root selection without interrupting", async () => {
|
||||
const f = await server.fixture({ conversation: true, disableWakeOnDemand: true });
|
||||
const [workspace] = await server.db.insert(executionWorkspaces).values({ companyId: f.companyId, projectId: null, sourceIssueId: f.issueId, name: "Task files", cwd: f.workspace, mode: "shared_workspace", strategyType: "task_directory" }).returning();
|
||||
await server.db.update(issues).set({ projectId: null, projectWorkspaceId: null, executionWorkspaceId: workspace.id }).where(eq(issues.id, f.issueId));
|
||||
const authority = new PaperclipRunnerToolAuthority(server.db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, runId: f.runId, apiUrl: server.apiUrl, workspaceRoot: "/admitted/task" });
|
||||
const call = (tool: string, args: Record<string, unknown>) => authority.execute({ tool, arguments: args, callId: randomUUID() });
|
||||
const view = await call("get_workspace", {}) as { bindingRevision: number; cwd: string; workspace: { id: string } };
|
||||
expect(view).toMatchObject({ cwd: "/admitted/task", workspace: { id: workspace.id } });
|
||||
const args = { repository: { kind: "url", url: "https://github.com/public/example" }, requestKey: "repository-one" };
|
||||
const first = await call("prepare_repository", args) as { preparationId: string; kind: string };
|
||||
expect(first.kind).toBe("requires_next_admission");
|
||||
expect(await call("prepare_repository", args)).toMatchObject({ preparationId: first.preparationId });
|
||||
expect(await call("select_workspace", { selection: { kind: "task_directory" }, expectedBindingRevision: view.bindingRevision, requestKey: "root-one" })).toMatchObject({ kind: "scheduled", applies: "next_normal_admission" });
|
||||
const [task] = await server.db.select().from(issues).where(eq(issues.id, f.issueId));
|
||||
expect(task).toMatchObject({ executionWorkspaceId: workspace.id, projectId: null, workspacePendingSelection: { requestKey: "root-one" } });
|
||||
const runs = await server.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId));
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(runs[0]).toMatchObject({ id: f.runId, status: "running" });
|
||||
});
|
||||
it("does not expose repository preparation or workspace selection to Ask mode", async () => {
|
||||
const f = await server.fixture({ mode: "ask", conversation: true, disableWakeOnDemand: true });
|
||||
await expect(f.authority.execute({ tool: "prepare_repository", callId: randomUUID(), arguments: { repository: { kind: "url", url: "https://github.com/public/example" }, requestKey: "denied" } })).rejects.toThrow();
|
||||
await expect(f.authority.execute({ tool: "select_workspace", callId: randomUUID(), arguments: { selection: { kind: "task_directory" }, expectedBindingRevision: 0, requestKey: "denied" } })).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { findNativeChatWorkspaceScope } from "../services/native-runtime/native-chat-workspace.js";
|
||||
import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
||||
import { createHeartbeatWorkspaceResolver } from "../services/heartbeat/workspaces.js";
|
||||
import { resolveDefaultAgentWorkspaceDir } from "../home-paths.js";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { agents, companies, createDb, executionWorkspaces, issues, projects } from "@paperclipai/db";
|
||||
import { executionWorkspaceService } from "../services/execution-workspaces.js";
|
||||
import { deleteCompany } from "../services/company-deletion.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
(support.supported ? describe : describe.skip)("task-owned workspace bindings", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("paperclip-task-workspace-");
|
||||
db = createDb(temporary.connectionString);
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
afterAll(async () => { await temporary?.cleanup(); });
|
||||
|
||||
async function fixture() {
|
||||
const companyId = randomUUID(), issueId = randomUUID(), workspaceId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Task files", issuePrefix: `T${companyId.slice(0, 6)}` });
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Write a report" });
|
||||
await db.insert(executionWorkspaces).values({ id: workspaceId, companyId, projectId: null, sourceIssueId: issueId,
|
||||
mode: "shared_workspace", strategyType: "project_primary", name: "Task files", cwd: `/tmp/task-${issueId}` });
|
||||
return { companyId, issueId, workspaceId, actor: { type: "board" as const, source: "local_implicit" as const, isInstanceAdmin: true } };
|
||||
}
|
||||
|
||||
it("persists a projectless binding, preserves it on project edits, and lists it in overview", async () => {
|
||||
const f = await fixture(), svc = executionWorkspaceService(db);
|
||||
await svc.bindTaskWorkspace(f.companyId, f.issueId, f.workspaceId);
|
||||
const projectId = randomUUID();
|
||||
await db.insert(projects).values({ id: projectId, companyId: f.companyId, name: "Reports" });
|
||||
const updated = await issueService(db).update(f.issueId, { projectId });
|
||||
expect(updated?.executionWorkspaceId).toBe(f.workspaceId);
|
||||
const view = await svc.inspectTaskWorkspace(f.companyId, f.issueId, f.actor);
|
||||
expect(view.workspace?.projectId).toBeNull();
|
||||
expect(view.workspace?.cwd).toBe(`/tmp/task-${f.issueId}`);
|
||||
expect(view.bindingRevision).toBe(1);
|
||||
const overview = await svc.listOverview(f.companyId, { limit: 20, offset: 0 });
|
||||
expect(overview.items).toEqual(expect.arrayContaining([expect.objectContaining({ workspaceId: f.workspaceId, projectId: null })]));
|
||||
});
|
||||
|
||||
it("queues explicit root changes without changing the current binding and applies at admission", async () => {
|
||||
const f = await fixture(), svc = executionWorkspaceService(db);
|
||||
await svc.bindTaskWorkspace(f.companyId, f.issueId, f.workspaceId);
|
||||
const request = { ...f, selection: { kind: "task_directory" as const }, expectedBindingRevision: 1, requestKey: "choose-task-directory" };
|
||||
expect(await svc.selectTaskWorkspace(request)).toMatchObject({ kind: "scheduled", applies: "next_normal_admission" });
|
||||
expect(await svc.selectTaskWorkspace(request)).toMatchObject({ kind: "scheduled" });
|
||||
await expect(svc.selectTaskWorkspace({ ...request, selection: { kind: "existing", workspaceId: f.workspaceId } })).rejects.toThrow("different intent");
|
||||
expect((await svc.inspectTaskWorkspace(f.companyId, f.issueId, f.actor)).workspace?.id).toBe(f.workspaceId);
|
||||
await svc.applyPendingTaskWorkspaceSelection({ ...f, runId: randomUUID() });
|
||||
const view = await svc.inspectTaskWorkspace(f.companyId, f.issueId, f.actor);
|
||||
expect(view.workspace).toBeNull();
|
||||
expect(view.selection).toMatchObject({ selection: { kind: "task_directory" } });
|
||||
expect(view.bindingRevision).toBe(2);
|
||||
expect(await svc.selectTaskWorkspace(request)).toMatchObject({ kind: "applied", bindingRevision: 2 });
|
||||
expect((await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)))[0]?.metadata)
|
||||
.toMatchObject({ _issuePrivacySources: { [f.issueId]: true } });
|
||||
await expect(svc.selectTaskWorkspace({ ...request, requestKey: "stale" })).rejects.toThrow("binding changed");
|
||||
});
|
||||
|
||||
it("defaults app and chat tasks to independent directories without hydrating legacy agent files", async () => {
|
||||
const f = await fixture();
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "task-workspace-default-"));
|
||||
vi.stubEnv("PAPERCLIP_HOME", root);
|
||||
try {
|
||||
const [agent] = await db.insert(agents).values({ companyId: f.companyId, name: "File worker", adapterType: "process", status: "idle" }).returning();
|
||||
const legacy = resolveDefaultAgentWorkspaceDir(agent!.id);
|
||||
await fs.mkdir(legacy, { recursive: true });
|
||||
const old = await fs.open(path.join(legacy, "unrelated.bin"), "w");
|
||||
await old.truncate(1_200_000_000); await old.close();
|
||||
const resolver = createHeartbeatWorkspaceResolver(db);
|
||||
const first = await resolver.resolveWorkspaceForRun(agent!, { issueId: f.issueId }, null);
|
||||
expect(first.cwd).not.toBe(legacy);
|
||||
expect(await fs.readdir(first.cwd)).toEqual([]);
|
||||
await fs.writeFile(path.join(first.cwd, "report.txt"), "task output");
|
||||
const again = await resolver.resolveWorkspaceForRun(agent!, { issueId: f.issueId }, null);
|
||||
expect(again.cwd).toBe(first.cwd);
|
||||
const chatId = randomUUID();
|
||||
await db.insert(issues).values({ id: chatId, companyId: f.companyId, title: "Chat report", originKind: "chat_channel" });
|
||||
const chat = await resolver.resolveWorkspaceForRun(agent!, { issueId: chatId }, null);
|
||||
expect(chat.cwd).not.toBe(first.cwd);
|
||||
expect(path.dirname(chat.cwd)).toBe(path.dirname(first.cwd));
|
||||
const organizationId = randomUUID();
|
||||
await db.insert(projects).values({ id: organizationId, companyId: f.companyId, name: "Organization only" });
|
||||
await db.update(issues).set({ projectId: organizationId }).where(eq(issues.id, chatId));
|
||||
const organized = await resolver.resolveWorkspaceForRun(agent!, { issueId: chatId }, null);
|
||||
expect(organized.cwd).toBe(chat.cwd);
|
||||
expect(organized.projectId).toBeNull();
|
||||
const nativeChatScope = await findNativeChatWorkspaceScope(db, {
|
||||
adapterType: "paperclip_runner", environmentDriver: "local", companyId: f.companyId,
|
||||
agentId: agent!.id, issueId: chatId, instanceRoot: root,
|
||||
});
|
||||
expect(nativeChatScope?.projectId).toBeNull();
|
||||
expect((await fs.stat(path.join(legacy, "unrelated.bin"))).size).toBe(1_200_000_000);
|
||||
} finally { vi.unstubAllEnvs(); await fs.rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it("retains every task privacy source when simultaneous tasks bind the same folder", async () => {
|
||||
const f = await fixture(), secondIssueId = randomUUID(), svc = executionWorkspaceService(db);
|
||||
await db.insert(issues).values({ id: secondIssueId, companyId: f.companyId, title: "Second task" });
|
||||
await Promise.all([svc.bindTaskWorkspace(f.companyId, f.issueId, f.workspaceId), svc.bindTaskWorkspace(f.companyId, secondIssueId, f.workspaceId)]);
|
||||
const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId));
|
||||
expect(workspace?.metadata).toMatchObject({ _issuePrivacySources: { [f.issueId]: true, [secondIssueId]: true } });
|
||||
});
|
||||
|
||||
it("deletes a whole company in source-workspace dependency order", async () => {
|
||||
const f = await fixture(), sourceProjectId = randomUUID();
|
||||
await db.insert(projects).values({ id: sourceProjectId, companyId: f.companyId, name: "Source policy" });
|
||||
await db.update(executionWorkspaces).set({ projectId: sourceProjectId }).where(eq(executionWorkspaces.id, f.workspaceId));
|
||||
expect(await deleteCompany(db, f.companyId)).toMatchObject({ id: f.companyId });
|
||||
expect(await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId))).toEqual([]);
|
||||
expect(await db.select().from(projects).where(eq(projects.id, sourceProjectId))).toEqual([]);
|
||||
});
|
||||
|
||||
it("retains source-project policy until workspaces are explicitly cleaned up", async () => {
|
||||
const f = await fixture(), sourceProjectId = randomUUID();
|
||||
await db.insert(projects).values({ id: sourceProjectId, companyId: f.companyId, name: "Source policy" });
|
||||
await db.update(executionWorkspaces).set({ projectId: sourceProjectId }).where(eq(executionWorkspaces.id, f.workspaceId));
|
||||
await expect(db.delete(projects).where(eq(projects.id, sourceProjectId))).rejects.toThrow();
|
||||
expect((await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)))[0]?.projectId).toBe(sourceProjectId);
|
||||
});
|
||||
|
||||
it("rejects foreign-company selections before changing pending state", async () => {
|
||||
const f = await fixture(), other = await fixture(), svc = executionWorkspaceService(db);
|
||||
await expect(svc.selectTaskWorkspace({ ...f, expectedBindingRevision: 0, requestKey: "foreign",
|
||||
selection: { kind: "existing", workspaceId: other.workspaceId } })).rejects.toThrow("unavailable or inaccessible");
|
||||
expect((await svc.inspectTaskWorkspace(f.companyId, f.issueId, f.actor)).pendingSelection).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm, mkdir, writeFile, readFile, realpath, open } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { agents, companies, createDb, executionWorkspaces, executionWorkspaceRepositories, issues } from "@paperclipai/db";
|
||||
import { executionWorkspaceService } from "../services/execution-workspaces.js";
|
||||
import { executionWorkspaceRepositoryService } from "../services/execution-workspace-repositories.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
const catalog = vi.hoisted(() => ({ available: true }));
|
||||
vi.mock("../services/tool-access.js", () => ({ toolAccessService: () => ({ listProjectRepositories: async () => ({ repositories: catalog.available ? [{ id: "123", fullName: "team/source", url: "https://github.com/team/source", connections: [] }] : [] }) }) }));
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
(support.supported ? describe : describe.skip)("durable task repository receipts", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let companyId: string, issueId: string, workspaceId: string, cwd: string;
|
||||
const actor = { type: "board" as const, source: "local_implicit" as const, userId: "local-board" };
|
||||
beforeAll(async () => {
|
||||
vi.stubEnv("PAPERCLIP_ISSUE_PRIVACY_MODE", "enforce");
|
||||
temporary = await startEmbeddedPostgresTestDatabase("paperclip-task-repositories-");
|
||||
db = createDb(temporary.connectionString);
|
||||
cwd = await mkdtemp(path.join(tmpdir(), "paperclip-task-repositories-files-"));
|
||||
[companyId] = (await db.insert(companies).values({ name: "Task repositories", issuePrefix: "TREPO" }).returning()).map(row => row.id);
|
||||
[workspaceId] = (await db.insert(executionWorkspaces).values({ companyId, projectId: null, name: "Task files", cwd, mode: "shared_workspace", strategyType: "task_directory" }).returning()).map(row => row.id);
|
||||
[issueId] = (await db.insert(issues).values({ companyId, title: "Projectless task", executionWorkspaceId: workspaceId }).returning()).map(row => row.id);
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
afterAll(async () => { vi.unstubAllEnvs(); await temporary?.cleanup(); if (cwd) await rm(cwd, { recursive: true, force: true }); });
|
||||
const request = (requestKey: string, ref?: string) => executionWorkspaceRepositoryService(db).request({ companyId, issueId, actor, request: { repository: { kind: "catalog", id: "123" }, requestKey, ...(ref ? { ref } : {}) } });
|
||||
it("converges concurrent requests and persists each retry key without creating a project", async () => {
|
||||
const [peerIssue] = await db.insert(issues).values({ companyId, title: "Peer task sharing the root", executionWorkspaceId: workspaceId }).returning();
|
||||
await db.update(executionWorkspaces).set({ sourceIssueId: issueId }).where(eq(executionWorkspaces.id, workspaceId));
|
||||
const [first, second] = await Promise.all([
|
||||
request("one"),
|
||||
executionWorkspaceRepositoryService(db).request({ companyId, issueId: peerIssue.id, actor, request: { repository: { kind: "catalog", id: "123" }, requestKey: "two" } }),
|
||||
]);
|
||||
expect(first.operationId).toBe(second.operationId);
|
||||
expect(first).toMatchObject({ kind: "requires_next_admission", applies: "next_normal_admission" });
|
||||
const rows = await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.executionWorkspaceId, workspaceId));
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].requestKeys.sort()).toEqual(["one", "two"]);
|
||||
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ projectId: null, executionWorkspaceId: workspaceId });
|
||||
await expect(request("two", "different-ref")).rejects.toThrow(/conflicts/);
|
||||
await expect(executionWorkspaceRepositoryService(db).request({ companyId, issueId, actor, request: { repository: { kind: "url", url: "https://github.com/other/source" }, requestKey: "two" } })).rejects.toThrow(/conflicts/);
|
||||
});
|
||||
it("rejects cross-company task IDs and revoked catalog permission even with a saved receipt", async () => {
|
||||
const [other] = await db.insert(companies).values({ name: "Foreign", issuePrefix: "FOREIGN" }).returning();
|
||||
await expect(executionWorkspaceRepositoryService(db).request({ companyId: other.id, issueId, actor, request: { repository: { kind: "catalog", id: "123" }, requestKey: "foreign" } })).rejects.toThrow(/not found/);
|
||||
catalog.available = false;
|
||||
await expect(request("one")).rejects.toThrow(/no longer available/);
|
||||
await expect(executionWorkspaceRepositoryService(db).prepareForAdmission({ companyId, issueId, workspaceId, cwd, agentId: randomUUID(), runId: randomUUID(), responsibleUserId: "local-board" })).rejects.toThrow(/no longer available/);
|
||||
catalog.available = true;
|
||||
});
|
||||
it("retains durable ownership when Git bundle restoration omits the temporary receipt", async () => {
|
||||
const [inventory] = await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.executionWorkspaceId, workspaceId));
|
||||
const checkout = path.join(cwd, inventory.relativePath);
|
||||
await mkdir(checkout, { recursive: true });
|
||||
const git = async (...args: string[]) => (await promisify(execFileCallback)("git", ["-C", checkout, ...args])).stdout.trim();
|
||||
await git("init", "--initial-branch=main");
|
||||
await git("remote", "add", "origin", inventory.repoUrl);
|
||||
await writeFile(path.join(checkout, "source.txt"), "restored repository\n");
|
||||
await git("add", ".");
|
||||
await git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "restored");
|
||||
const commit = await git("rev-parse", "HEAD");
|
||||
await db.update(executionWorkspaceRepositories).set({ pinnedCommit: commit, state: "ready" }).where(eq(executionWorkspaceRepositories.id, inventory.id));
|
||||
await writeFile(path.join(checkout, "source.txt"), "uncommitted work\n");
|
||||
const prepared = await executionWorkspaceRepositoryService(db).prepareForAdmission({ companyId, issueId, workspaceId, cwd, agentId: randomUUID(), runId: randomUUID(), responsibleUserId: "local-board" });
|
||||
expect(prepared).toHaveLength(1);
|
||||
expect(prepared[0].pinnedCommit).toBe(commit);
|
||||
expect(await readFile(path.join(checkout, "source.txt"), "utf8")).toBe("uncommitted work\n");
|
||||
// A malicious/non-regular receipt cannot block admission. The durable DB
|
||||
// pin remains authoritative, so this invalid receipt is ignored.
|
||||
if (process.platform !== "win32") {
|
||||
const receiptPath = path.join(checkout, ".git", "paperclip-workspace-owner.json");
|
||||
await promisify(execFileCallback)("mkfifo", [receiptPath]);
|
||||
let deadline: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
executionWorkspaceRepositoryService(db).prepareForAdmission({ companyId, issueId, workspaceId, cwd, agentId: randomUUID(), runId: randomUUID(), responsibleUserId: "local-board" }),
|
||||
new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error("FIFO receipt blocked admission")), 3000); }),
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(deadline);
|
||||
// Release a blocked reader if this regression ever returns, so a failed
|
||||
// assertion cannot leave the test process stuck in its filesystem pool.
|
||||
const writer = await open(receiptPath, fsConstants.O_WRONLY | fsConstants.O_NONBLOCK).catch(() => null);
|
||||
await writer?.close();
|
||||
await rm(receiptPath, { force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
it("reuses the same physical checkout across logical workspaces and rechecks retained privacy", async () => {
|
||||
const [secondAgent] = await db.insert(agents).values({ companyId, name: "Second agent", adapterType: "process" }).returning();
|
||||
const [secondWorkspace] = await db.insert(executionWorkspaces).values({ companyId, projectId: null, name: "Same configured folder", cwd, mode: "shared_workspace", strategyType: "operator_directory" }).returning();
|
||||
const [secondIssue] = await db.insert(issues).values({ companyId, title: "Second task", assigneeAgentId: secondAgent.id, executionWorkspaceId: secondWorkspace.id }).returning();
|
||||
const service = executionWorkspaceRepositoryService(db);
|
||||
const intent = await service.request({ companyId, issueId: secondIssue.id, actor, request: { repository: { kind: "catalog", id: "123" }, requestKey: "shared-second" } });
|
||||
const admission = { companyId, issueId: secondIssue.id, workspaceId: secondWorkspace.id, cwd, agentId: secondAgent.id, runId: randomUUID(), responsibleUserId: null };
|
||||
const [original] = await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.executionWorkspaceId, workspaceId));
|
||||
const prepared = await service.prepareForAdmission(admission);
|
||||
expect(prepared[0]).toMatchObject({ id: intent.operationId, cwd: path.join(await realpath(cwd), original.relativePath), pinnedCommit: original.pinnedCommit });
|
||||
expect(await readFile(path.join(prepared[0].cwd, "source.txt"), "utf8")).toBe("uncommitted work\n");
|
||||
// There is still one physical checkout and neither its files nor Git metadata were rewritten.
|
||||
expect(await readFile(path.join(prepared[0].cwd, ".git", "paperclip-workspace-owner.json"), "utf8").catch(() => null)).toBeNull();
|
||||
const [differentRefWorkspace] = await db.insert(executionWorkspaces).values({ companyId, name: "Conflicting ref", cwd, mode: "shared_workspace", strategyType: "operator_directory" }).returning();
|
||||
const [differentRefIssue] = await db.insert(issues).values({ companyId, title: "Different ref", executionWorkspaceId: differentRefWorkspace.id }).returning();
|
||||
await service.request({ companyId, issueId: differentRefIssue.id, actor, request: { repository: { kind: "catalog", id: "123" }, ref: "release", requestKey: "conflicting-ref" } });
|
||||
await expect(service.prepareForAdmission({ ...admission, issueId: differentRefIssue.id, workspaceId: differentRefWorkspace.id })).rejects.toThrow(/different ref/);
|
||||
const [privateSource] = await db.insert(issues).values({ companyId, title: "Retained private source", visibility: "private" }).returning();
|
||||
const owner = executionWorkspaceService(db);
|
||||
await owner.bindTaskWorkspace(companyId, privateSource.id, workspaceId);
|
||||
const [movedWorkspace] = await db.insert(executionWorkspaces).values({ companyId, name: "Private task moved away", cwd: path.join(cwd, "moved-private-task"), mode: "shared_workspace", strategyType: "task_directory" }).returning();
|
||||
await owner.bindTaskWorkspace(companyId, privateSource.id, movedWorkspace.id);
|
||||
const [retainedWorkspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceId));
|
||||
expect(retainedWorkspace.metadata?._issuePrivacySources).toMatchObject({ [privateSource.id]: true });
|
||||
// Reauthorization also applies after the second inventory has a durable pin.
|
||||
await expect(service.prepareForAdmission(admission)).rejects.toThrow(/outside this actor's access/);
|
||||
expect(await readFile(path.join(prepared[0].cwd, "source.txt"), "utf8")).toBe("uncommitted work\n");
|
||||
});
|
||||
it("stages a root change without replacing active files or adding a wake", async () => {
|
||||
const owner = executionWorkspaceService(db);
|
||||
await expect(owner.selectTaskWorkspace({ companyId, issueId, actor, selection: { kind: "task_directory" }, expectedBindingRevision: 0, requestKey: "move" })).resolves.toMatchObject({ kind: "scheduled", applies: "next_normal_admission" });
|
||||
const [issue] = await db.select().from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId)));
|
||||
expect(issue.executionWorkspaceId).toBe(workspaceId);
|
||||
expect(issue.workspacePendingSelection?.requestKey).toBe("move");
|
||||
expect(issue.workspaceBindingRevision).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { prepareWorkspaceRepositorySchema } from "@paperclipai/shared";
|
||||
import { resolveTaskRepository, taskRepositoryRelativePath, assertRepositoryRetryMatches } from "../services/execution-workspace-repositories.js";
|
||||
|
||||
const repository = { id: "123", fullName: "team/source", url: "https://github.com/team/source", connections: [] };
|
||||
describe("task repository acquisition authority", () => {
|
||||
it("requires a currently authorized catalog ID, including on retry after revocation", () => {
|
||||
expect(resolveTaskRepository({ kind: "catalog", id: "123" }, [repository])).toMatchObject({ catalogRepositoryId: "123" });
|
||||
expect(() => resolveTaskRepository({ kind: "catalog", id: "123" }, [])).toThrow(/no longer available/);
|
||||
expect(() => resolveTaskRepository({ kind: "catalog", id: "other-company-repo" }, [repository])).toThrow(/no longer available/);
|
||||
});
|
||||
it("normalizes HTTPS URLs and never accepts credentials, alternate hosts, or shell paths", () => {
|
||||
expect(resolveTaskRepository({ kind: "url", url: "https://github.com/team/source.git" }, [repository])).toMatchObject({ catalogRepositoryId: "123", repositoryIdentity: repository.url });
|
||||
expect(resolveTaskRepository({ kind: "url", url: "https://github.com/public/repo" }, [])).toMatchObject({ catalogRepositoryId: null });
|
||||
for (const url of ["git@github.com:team/source", "https://token@github.com/team/source", "https://evil.example/team/source", "file:///tmp/source", "https://github.com/team/source?q=secret"]) {
|
||||
expect(() => resolveTaskRepository({ kind: "url", url }, [])).toThrow(/HTTPS GitHub/);
|
||||
}
|
||||
});
|
||||
it("converges repository aliases into a stable contained path and rejects conflicting refs", () => {
|
||||
const source = resolveTaskRepository({ kind: "catalog", id: "123" }, [repository]);
|
||||
const alias = resolveTaskRepository({ kind: "url", url: "https://github.com/TEAM/SOURCE.git" }, [repository]);
|
||||
expect(taskRepositoryRelativePath(source.repositoryIdentity)).toBe(taskRepositoryRelativePath(alias.repositoryIdentity));
|
||||
expect(taskRepositoryRelativePath(source.repositoryIdentity)).toMatch(/^\.paperclip-repositories\/task-repo-[a-f0-9]{24}$/);
|
||||
const receipt = { repositoryIdentity: source.repositoryIdentity, requestedRef: "main" };
|
||||
expect(() => assertRepositoryRetryMatches(receipt, source.repositoryIdentity, "main")).not.toThrow();
|
||||
expect(() => assertRepositoryRetryMatches(receipt, source.repositoryIdentity, "release")).toThrow(/different ref/);
|
||||
expect(() => assertRepositoryRetryMatches(receipt, "another", "main")).toThrow(/conflicts/);
|
||||
});
|
||||
it("accepts refs as data while rejecting options and traversal", () => {
|
||||
const parse = (ref: string) => prepareWorkspaceRepositorySchema.parse({ repository: { kind: "catalog", id: "123" }, requestKey: "retry", ref });
|
||||
expect(parse("feature/task-files").ref).toBe("feature/task-files");
|
||||
for (const ref of ["--upload-pack=sh", "../main", "a..b", "main;echo x", "refs//heads/main"]) expect(() => parse(ref)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { callTaskWorkspaceTool } from "../services/task-workspace-tools.js";
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const base = { apiUrl: "https://paperclip.example/api", token: "run-token", companyId: "company", issueId: "task" };
|
||||
describe("task workspace semantic transport", () => {
|
||||
it("uses the normal bound task routes without passing caller identities or interrupt requests", async () => {
|
||||
const fetcher = vi.fn(async () => Response.json({ kind: "scheduled", applies: "next_normal_admission" }));
|
||||
vi.stubGlobal("fetch", fetcher);
|
||||
await expect(callTaskWorkspaceTool({ ...base, name: "select_workspace", arguments: { selection: { kind: "task_directory" }, expectedBindingRevision: 3, requestKey: "move-1" } })).resolves.toMatchObject({ applies: "next_normal_admission" });
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
expect(fetcher.mock.calls[0]).toEqual(["https://paperclip.example/api/issues/task/workspace", expect.objectContaining({ method: "PUT", body: JSON.stringify({ selection: { kind: "task_directory" }, expectedBindingRevision: 3, requestKey: "move-1" }) })]);
|
||||
});
|
||||
it("prepares a repository without creating a project or choosing a host path", async () => {
|
||||
const fetcher = vi.fn(async () => Response.json({ kind: "requires_next_admission" }));
|
||||
vi.stubGlobal("fetch", fetcher);
|
||||
const args = { repository: { kind: "catalog", id: "repo" }, requestKey: "acquire-1" };
|
||||
await callTaskWorkspaceTool({ ...base, name: "prepare_repository", arguments: args });
|
||||
expect(fetcher.mock.calls[0]).toEqual(["https://paperclip.example/api/issues/task/workspace/repositories", expect.objectContaining({ method: "POST", body: JSON.stringify(args) })]);
|
||||
await expect(callTaskWorkspaceTool({ ...base, name: "prepare_repository", arguments: { ...args, cwd: "/home" } })).rejects.toThrow();
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,7 @@ import { publicMcpIngressRoutes, publicMcpManagementRoutes } from "./routes/publ
|
||||
import { agentAvatarRoutes } from "./routes/agent-avatars.js";
|
||||
import { decisionModelRoutes } from "./routes/decision-models.js";
|
||||
import { aiConnectionRoutes } from "./routes/ai-connections.js";
|
||||
import { taskWorkspaceRoutes } from "./routes/task-workspaces.js";
|
||||
import { projectToolRoutes } from "./routes/project-tools.js";
|
||||
import { emailChannelService } from "./services/email-channels.js";
|
||||
import { emailRoutes, emailWebhookRoutes } from "./routes/email.js";
|
||||
@@ -806,6 +807,7 @@ export async function createApp(
|
||||
api.use(assetRoutes(db, opts.storageService));
|
||||
api.use(agentProfileAvatarRoutes(db, opts.storageService));
|
||||
api.use(projectToolRoutes(db));
|
||||
api.use(taskWorkspaceRoutes(db));
|
||||
api.use(projectRoutes(db));
|
||||
api.use(caseRoutes(db, opts.storageService));
|
||||
api.use(issueTreeControlRoutes(db, { pluginWorkerManager: workerManager }));
|
||||
|
||||
@@ -341,7 +341,9 @@ const NATIVE_RUN_SPAN_NAMES = new Set([
|
||||
"runner.turn.submit",
|
||||
"task.prepare",
|
||||
"task.run",
|
||||
"task.provider_session",
|
||||
"task.run.measured",
|
||||
"task.provider_session.measured",
|
||||
"task.settle",
|
||||
]);
|
||||
const CLI_SECRET_FLAG_RE = new RegExp(
|
||||
|
||||
@@ -3,7 +3,7 @@ import { canActorReadExecutionWorkspace, executionWorkspaceReadSqlCondition } fr
|
||||
import { spawn } from "node:child_process";
|
||||
import { accessSync, constants as fsConstants, existsSync, readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { issues, projects, projectWorkspaces } from "@paperclipai/db";
|
||||
@@ -321,7 +321,7 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
|
||||
and(
|
||||
eq(projectWorkspaces.id, existing.projectWorkspaceId),
|
||||
eq(projectWorkspaces.companyId, existing.companyId),
|
||||
eq(projectWorkspaces.projectId, existing.projectId),
|
||||
existing.projectId ? eq(projectWorkspaces.projectId, existing.projectId) : sql`false`,
|
||||
),
|
||||
)
|
||||
.then((rows) => rows[0] ?? null)
|
||||
|
||||
@@ -3710,6 +3710,7 @@ export function issueRoutes(
|
||||
input: Record<string, unknown>,
|
||||
) {
|
||||
return (
|
||||
input.workspaceSelection !== undefined ||
|
||||
input.parentId !== undefined ||
|
||||
input.inheritExecutionWorkspaceFromIssueId !== undefined ||
|
||||
input.projectWorkspaceId !== undefined ||
|
||||
@@ -4765,31 +4766,12 @@ export function issueRoutes(
|
||||
executionWorkspacePreference?: string | null;
|
||||
executionWorkspaceSettings?: unknown;
|
||||
}) {
|
||||
// Match create()'s project precedence before checking any assignment or
|
||||
// trust policy. A workspace or explicit inheritance source can supply the
|
||||
// project even when a caller omits projectId and the parent is projectless.
|
||||
// Organizational project inheritance never comes from filesystem sources.
|
||||
if (input.projectId) return input.projectId;
|
||||
const sourceId = input.inheritExecutionWorkspaceFromIssueId ?? input.parentId;
|
||||
const source = sourceId ? await svc.getById(sourceId) : null;
|
||||
if (sourceId && (!source || source.companyId !== input.companyId)) throw notFound("Workspace inheritance issue not found");
|
||||
if (source?.projectId) return source.projectId;
|
||||
const projectWorkspaceId = input.projectWorkspaceId ?? source?.projectWorkspaceId;
|
||||
if (projectWorkspaceId) {
|
||||
const [workspace] = await db.select({ projectId: projectWorkspaces.projectId }).from(projectWorkspaces)
|
||||
.where(and(eq(projectWorkspaces.id, projectWorkspaceId), eq(projectWorkspaces.companyId, input.companyId)));
|
||||
if (!workspace) throw notFound("Project workspace not found");
|
||||
return workspace.projectId;
|
||||
}
|
||||
const hasExecutionOverride = input.executionWorkspaceId !== undefined ||
|
||||
input.executionWorkspacePreference !== undefined || input.executionWorkspaceSettings !== undefined;
|
||||
const executionWorkspaceId = input.executionWorkspaceId ?? (hasExecutionOverride ? null : source?.executionWorkspaceId);
|
||||
if (executionWorkspaceId && (await instanceSettings.getExperimental()).enableIsolatedWorkspaces) {
|
||||
const [workspace] = await db.select({ projectId: executionWorkspaces.projectId }).from(executionWorkspaces)
|
||||
.where(and(eq(executionWorkspaces.id, executionWorkspaceId), eq(executionWorkspaces.companyId, input.companyId)));
|
||||
if (!workspace) throw notFound("Execution workspace not found");
|
||||
return workspace.projectId;
|
||||
}
|
||||
return null;
|
||||
return source?.projectId ?? null;
|
||||
}
|
||||
|
||||
async function assertCanAssignTasks(
|
||||
@@ -7623,7 +7605,7 @@ export function issueRoutes(
|
||||
// must not install the guard, or it can clear the flag that
|
||||
// the other request still owns.
|
||||
// null - this function sent an error response, so the caller stops.
|
||||
// The reopen is scoped to the issue company and project inside the service, and
|
||||
// The reopen checks the persisted task binding and source access inside the service, and
|
||||
// it runs only after the route already authorized the request on the issue.
|
||||
async function reopenClosedIssueExecutionWorkspaceOrRespond(
|
||||
req: Request,
|
||||
@@ -7645,6 +7627,7 @@ export function issueRoutes(
|
||||
projectId: issue.projectId ?? null,
|
||||
},
|
||||
actor: { agentId: actor.agentId, actorType: actor.actorType },
|
||||
authorizationActor: req.actor,
|
||||
},
|
||||
);
|
||||
if (result.ok) {
|
||||
@@ -12260,6 +12243,7 @@ export function issueRoutes(
|
||||
null;
|
||||
const createInput = {
|
||||
...createBody,
|
||||
workspaceSelectionActor: req.actor,
|
||||
projectId: createAssignmentScope.projectId,
|
||||
...(taskBridgeOriginForActor(req) ?? {}),
|
||||
id: issueId,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { issues, type Db } from "@paperclipai/db";
|
||||
import { Router, type Request } from "express";
|
||||
import { prepareWorkspaceRepositorySchema, selectTaskWorkspaceSchema } from "@paperclipai/shared";
|
||||
import { accessService } from "../services/access.js";
|
||||
import { executionWorkspaceService } from "../services/execution-workspaces.js";
|
||||
import { canActorReadExecutionWorkspace, issueReadSqlCondition } from "../services/authorization.js";
|
||||
import { projectToolContext } from "../services/project-tool-context.js";
|
||||
import { logActivity } from "../services/activity-log.js";
|
||||
import { forbidden, notFound } from "../errors.js";
|
||||
import { assertCompanyAccess, getActorInfo } from "./authz.js";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
|
||||
/** App and agent transports share task/workspace authorization and the aggregate owner. */
|
||||
export function taskWorkspaceRoutes(db: Db) {
|
||||
const router = Router();
|
||||
const workspaces = executionWorkspaceService(db);
|
||||
async function task(req: Request, write = false) {
|
||||
const [issue] = await db.select().from(issues).where(and(eq(issues.id, req.params.id as string), await issueReadSqlCondition(db, req.actor)));
|
||||
if (!issue) throw notFound("Task not found");
|
||||
assertCompanyAccess(req, issue.companyId);
|
||||
const decision = await accessService(db).decide({ actor: req.actor, action: write ? "issue:mutate" : "issue:read", resource: { type: "issue", companyId: issue.companyId, issueId: issue.id } });
|
||||
if (!decision.allowed) throw forbidden("Task workspace is outside this actor's authorization boundary");
|
||||
if (issue.executionWorkspaceId && !(await canActorReadExecutionWorkspace(db, req.actor, issue.executionWorkspaceId))) throw notFound("Execution workspace not found");
|
||||
if (write && req.actor.type === "agent") {
|
||||
const context = await projectToolContext(db, req.actor, true, "Workspace");
|
||||
if (context.issue.id !== issue.id) throw forbidden("Workspace selection is scoped to the current task");
|
||||
}
|
||||
return issue;
|
||||
}
|
||||
router.get("/issues/:id/workspace", async (req, res) => {
|
||||
const issue = await task(req);
|
||||
const view = await workspaces.inspectTaskWorkspace(issue.companyId, issue.id, req.actor);
|
||||
res.json({ ...view, repositories: issue.executionWorkspaceId ? await workspaces.listTaskRepositories(issue.companyId, issue.executionWorkspaceId) : [], capabilities: { prepareRepository: "next_normal_admission", selectWorkspace: "next_normal_admission" }, fileLocations: { taskFiles: "workspace", personalInstructionsAndMemory: "AGENT_HOME", providerHome: "runtime_managed" } });
|
||||
});
|
||||
router.put("/issues/:id/workspace", validate(selectTaskWorkspaceSchema), async (req, res) => {
|
||||
const issue = await task(req, true);
|
||||
const result = await workspaces.selectTaskWorkspace({ companyId: issue.companyId, issueId: issue.id, actor: req.actor, ...req.body });
|
||||
const actor = getActorInfo(req);
|
||||
await logActivity(db, { companyId: issue.companyId, ...actor, action: "issue.workspace.selection_requested", entityType: "issue", entityId: issue.id, details: { selection: req.body.selection, applies: "next_normal_admission" } });
|
||||
res.json(result);
|
||||
});
|
||||
router.post("/issues/:id/workspace/repositories", validate(prepareWorkspaceRepositorySchema), async (req, res) => {
|
||||
const issue = await task(req, true);
|
||||
res.json(await workspaces.requestTaskRepository({ companyId: issue.companyId, issueId: issue.id, actor: req.actor, request: req.body }));
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import { instanceSettingsService } from "./instance-settings.js";
|
||||
import { registerSlackTaskAuthority, slackRunOrigin } from "./connectors/slack-authority.js";
|
||||
import { captureRunIdentity } from "./run-identity.js";
|
||||
import { buildChatCommunicationGuidance } from "./chat-communication-guidance.js";
|
||||
import { assertChatExecutionDefaultsAccess, resolveChatExecutionDefaults } from "./chat-execution-defaults.js";
|
||||
function githubPolicyRecord(value: unknown): Record<string, unknown> { return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {}; }
|
||||
import { githubChatManagementService } from "./chat-github-management.js";
|
||||
import { githubReviewCheckService } from "./chat-github-checks.js";
|
||||
@@ -146,6 +147,7 @@ import {
|
||||
} from "@paperclipai/db";
|
||||
import type {
|
||||
ChatAdapterCapabilities,
|
||||
ChatExecutionDefaults,
|
||||
ChatEndpointCallbackSurfaces,
|
||||
ChatEventKind,
|
||||
ChatEndpoint,
|
||||
@@ -5839,6 +5841,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
botLabel: endpoint.botDisplayName ?? row.assignedAgentName,
|
||||
botAvatarUrl: endpoint.botAvatarUrl,
|
||||
communicationInstructions: endpoint.communicationInstructions,
|
||||
executionDefaults: endpoint.executionDefaults,
|
||||
...(endpoint.provider === "imessage-photon" && endpoint.botExternalId ? { photonAllocation: endpoint.botExternalId.startsWith("photon-project:") ? "shared" as const : "dedicated" as const } : {}),
|
||||
allowDirectMessages: endpoint.allowDirectMessages,
|
||||
requireAtMention: endpoint.requireAtMention,
|
||||
@@ -6061,7 +6064,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
) {
|
||||
const initial = await endpointRecord(endpointId);
|
||||
if (!initial) throw notFound("Chat endpoint not found");
|
||||
if (initial.endpoint.provider === "agentmail") throw badRequest("Use the email inbox API for AgentMail");
|
||||
if (initial.endpoint.provider === "agentmail" && Object.keys(input).some((key) => key !== "executionDefaults")) throw badRequest("Use the email inbox API for AgentMail");
|
||||
await withCredentialMutationLease(
|
||||
initial.endpoint,
|
||||
async (credentialLease) => {
|
||||
@@ -6121,6 +6124,14 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
values.allowUnlinkedPeople = input.allowUnlinkedPeople;
|
||||
await db.transaction(async (tx) => {
|
||||
await credentialLease.assertOwned(tx);
|
||||
if (input.executionDefaults !== undefined) {
|
||||
await assertChatExecutionDefaultsAccess(db, {
|
||||
companyId: existing.endpoint.companyId,
|
||||
actor: { type: "board", userId: actorUserId, source: actorUserId ? "session" : "local_implicit" },
|
||||
defaults: input.executionDefaults,
|
||||
}, tx);
|
||||
values.executionDefaults = input.executionDefaults;
|
||||
}
|
||||
await tx
|
||||
.update(chatEndpoints)
|
||||
.set(values)
|
||||
@@ -15938,6 +15949,20 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
) => {
|
||||
let conversation = existingConversation;
|
||||
if (!conversation) {
|
||||
const [taskResource] = await taskTx.select({ executionDefaults: chatEndpointResources.executionDefaults })
|
||||
.from(chatEndpointResources).where(and(eq(chatEndpointResources.id, resource.id), eq(chatEndpointResources.endpointId, taskEndpoint.id)));
|
||||
const executionDefaults = resolveChatExecutionDefaults(taskEndpoint.executionDefaults, taskResource?.executionDefaults);
|
||||
const responsibleUserId = taskUserId ?? endpoint.sponsorUserId;
|
||||
await assertChatExecutionDefaultsAccess(db, {
|
||||
companyId: endpoint.companyId,
|
||||
actor: responsibleUserId ? { type: "board", userId: responsibleUserId, source: "session", ignoreInstanceAdmin: true } : { type: "none" },
|
||||
defaults: executionDefaults,
|
||||
}, taskTx);
|
||||
await assertChatExecutionDefaultsAccess(db, {
|
||||
companyId: endpoint.companyId,
|
||||
actor: { type: "agent", agentId: endpoint.assignedAgentId, companyId: endpoint.companyId, onBehalfOfUserId: responsibleUserId, source: "agent_key" },
|
||||
defaults: executionDefaults,
|
||||
}, taskTx);
|
||||
const sessionGeneration = isLinear
|
||||
? (latestConversation?.sessionGeneration ?? 0) + 1
|
||||
: 1;
|
||||
@@ -15959,6 +15984,8 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
originKind: "chat_channel",
|
||||
originId: `${endpoint.id}:${thread.id}:${sessionGeneration}`,
|
||||
idempotencyKey: `chat:${endpoint.id}:${thread.id}:${sessionGeneration}`,
|
||||
...(executionDefaults.projectId !== undefined ? { projectId: executionDefaults.projectId } : {}),
|
||||
...(executionDefaults.workspace ? { workspaceSelection: executionDefaults.workspace, workspaceSelectionSource: "channel" as const } : {}),
|
||||
},
|
||||
taskTx,
|
||||
);
|
||||
@@ -28085,7 +28112,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
|
||||
async function replaceResources(
|
||||
endpointId: string,
|
||||
updates: Array<{ id: string; enabled: boolean }>,
|
||||
updates: Array<{ id: string; enabled?: boolean; executionDefaults?: ChatExecutionDefaults | null }>,
|
||||
actorUserId?: string | null,
|
||||
options?: { initialGitHubImport?: boolean },
|
||||
) {
|
||||
@@ -28100,7 +28127,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
|
||||
async function updateResourceSelection(
|
||||
endpointId: string,
|
||||
updates: Array<{ id: string; enabled: boolean }>,
|
||||
updates: Array<{ id: string; enabled?: boolean; executionDefaults?: ChatExecutionDefaults | null }>,
|
||||
actorUserId?: string | null,
|
||||
options?: { initialGitHubImport?: boolean; allGitHubRepositoriesEnabled?: boolean },
|
||||
) {
|
||||
@@ -28140,6 +28167,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
id: chatEndpointResources.id,
|
||||
availability: chatEndpointResources.availability,
|
||||
enabled: chatEndpointResources.enabled,
|
||||
executionDefaults: chatEndpointResources.executionDefaults,
|
||||
})
|
||||
.from(chatEndpointResources)
|
||||
.where(
|
||||
@@ -28160,7 +28188,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
.for("no key update");
|
||||
if (!bulk && rows.length !== new Set(ids).size)
|
||||
throw unprocessable("Every resource must belong to this endpoint");
|
||||
const selectedUpdates = bulk
|
||||
const selectedUpdates: typeof updates = bulk
|
||||
? rows.map((row) => ({ id: row.id, enabled: options!.allGitHubRepositoriesEnabled! }))
|
||||
: updates;
|
||||
const availabilityById = new Map(
|
||||
@@ -28177,15 +28205,26 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
"A destination must still be available from the provider before it can be enabled",
|
||||
{ code: "chat_resource_unavailable", resourceId: unavailable.id },
|
||||
);
|
||||
const finalEnabled = new Map(
|
||||
selectedUpdates.map((entry) => [entry.id, entry.enabled]),
|
||||
);
|
||||
const finalEnabled = new Map(rows.map((row) => [row.id, row.enabled]));
|
||||
for (const entry of selectedUpdates) {
|
||||
if (entry.enabled !== undefined) finalEnabled.set(entry.id, entry.enabled);
|
||||
}
|
||||
const finalDefaults = new Map(rows.map((row) => [row.id, row.executionDefaults]));
|
||||
for (const entry of selectedUpdates) {
|
||||
if (entry.executionDefaults === undefined) continue;
|
||||
await assertChatExecutionDefaultsAccess(db, {
|
||||
companyId: endpoint.companyId,
|
||||
actor: { type: "board", userId: actorUserId, source: actorUserId ? "session" : "local_implicit" },
|
||||
defaults: entry.executionDefaults,
|
||||
}, tx);
|
||||
finalDefaults.set(entry.id, entry.executionDefaults);
|
||||
}
|
||||
const changes = rows
|
||||
.filter((row) => row.enabled !== finalEnabled.get(row.id))
|
||||
.filter((row) => row.enabled !== finalEnabled.get(row.id) || JSON.stringify(row.executionDefaults) !== JSON.stringify(finalDefaults.get(row.id)))
|
||||
.map((row) => ({
|
||||
resourceId: row.id,
|
||||
before: { enabled: row.enabled },
|
||||
after: { enabled: finalEnabled.get(row.id)! },
|
||||
before: { enabled: row.enabled, ...(JSON.stringify(row.executionDefaults) !== JSON.stringify(finalDefaults.get(row.id)) ? { executionDefaults: row.executionDefaults } : {}) },
|
||||
after: { enabled: finalEnabled.get(row.id)!, ...(JSON.stringify(row.executionDefaults) !== JSON.stringify(finalDefaults.get(row.id)) ? { executionDefaults: finalDefaults.get(row.id) } : {}) },
|
||||
}));
|
||||
if (bulk) {
|
||||
// One atomic database update, independent of pagination/search and
|
||||
@@ -28203,7 +28242,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
} else for (const entry of selectedUpdates)
|
||||
await tx
|
||||
.update(chatEndpointResources)
|
||||
.set({ enabled: entry.enabled, updatedAt: new Date() })
|
||||
.set({ enabled: entry.enabled, ...(entry.executionDefaults !== undefined ? { executionDefaults: entry.executionDefaults } : {}), updatedAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
eq(chatEndpointResources.companyId, endpoint.companyId),
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { chatExecutionDefaultsSchema, type ChatExecutionDefaults } from "@paperclipai/shared";
|
||||
import { type Db, projects } from "@paperclipai/db";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { projectReadSqlCondition, type AuthorizationActor } from "./authorization.js";
|
||||
import { executionWorkspaceService } from "./execution-workspaces.js";
|
||||
import { notFound } from "../errors.js";
|
||||
|
||||
type DbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
|
||||
/** Configuration selects resources; it never grants their access to future senders. */
|
||||
export async function assertChatExecutionDefaultsAccess(
|
||||
db: Db,
|
||||
input: { companyId: string; actor: AuthorizationActor; defaults: ChatExecutionDefaults | null | undefined },
|
||||
reader: Db | DbTransaction = db,
|
||||
): Promise<void> {
|
||||
const defaults = chatExecutionDefaultsSchema.parse(input.defaults ?? {});
|
||||
if (defaults.projectId) {
|
||||
const [project] = await reader.select({ id: projects.id }).from(projects).where(and(
|
||||
eq(projects.id, defaults.projectId), eq(projects.companyId, input.companyId),
|
||||
await projectReadSqlCondition(reader, input.actor),
|
||||
));
|
||||
if (!project) throw notFound("Default project is unavailable or inaccessible");
|
||||
}
|
||||
if (defaults.workspace) await executionWorkspaceService(db).validateSelection({
|
||||
companyId: input.companyId, actor: input.actor, selection: defaults.workspace,
|
||||
}, reader);
|
||||
}
|
||||
|
||||
/** Resolve once when a conversation creates its task. Later endpoint edits are irrelevant. */
|
||||
export function resolveChatExecutionDefaults(
|
||||
endpoint: ChatExecutionDefaults | null | undefined,
|
||||
resource: ChatExecutionDefaults | null | undefined,
|
||||
): ChatExecutionDefaults {
|
||||
const base = chatExecutionDefaultsSchema.parse(endpoint ?? {});
|
||||
const override = chatExecutionDefaultsSchema.parse(resource ?? {});
|
||||
return {
|
||||
...(base.projectId !== undefined ? { projectId: base.projectId } : {}),
|
||||
...(base.workspace !== undefined ? { workspace: base.workspace } : {}),
|
||||
...(override.projectId !== undefined ? { projectId: override.projectId } : {}),
|
||||
...(override.workspace !== undefined ? { workspace: override.workspace } : {}),
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
issues,
|
||||
issueComments,
|
||||
projects,
|
||||
executionWorkspaces,
|
||||
goals,
|
||||
heartbeatRuns,
|
||||
runIdentityContexts,
|
||||
@@ -99,6 +100,9 @@ export async function deleteCompany(db: Db, id: string) {
|
||||
await tx.delete(companyLogos).where(eq(companyLogos.companyId, id));
|
||||
await tx.delete(assets).where(eq(assets.companyId, id));
|
||||
await tx.delete(goals).where(eq(goals.companyId, id));
|
||||
// A retained workspace protects its source project from individual deletion.
|
||||
// Whole-company deletion explicitly removes both in dependency order.
|
||||
await tx.delete(executionWorkspaces).where(eq(executionWorkspaces.companyId, id));
|
||||
await tx.delete(projects).where(eq(projects.companyId, id));
|
||||
await agentLifecycleCompanyDeletion.deleteCompanyData(tx, id);
|
||||
const rows = await tx
|
||||
|
||||
@@ -45,6 +45,7 @@ import { resolveExecutionWorkspaceEnvironmentId } from "./execution-workspace-po
|
||||
import { emailConnectionService } from "./email-connections.js";
|
||||
import { secretService } from "./secrets.js";
|
||||
import { authorizationService } from "./authorization.js";
|
||||
import { assertChatExecutionDefaultsAccess, resolveChatExecutionDefaults } from "./chat-execution-defaults.js";
|
||||
import { issueService } from "./issues.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
@@ -1318,10 +1319,27 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
|
||||
endpoint.companyId,
|
||||
endpoint.assignedAgentId,
|
||||
);
|
||||
const defaults = resolveChatExecutionDefaults(endpoint.executionDefaults, null);
|
||||
// A channel default cannot widen the receiving agent's trust boundary.
|
||||
if ("projectId" in placement && defaults.projectId !== undefined && defaults.projectId !== placement.projectId) {
|
||||
throw forbidden("Default project conflicts with the assigned agent's trust boundary");
|
||||
}
|
||||
await assertChatExecutionDefaultsAccess(db, {
|
||||
companyId: endpoint.companyId,
|
||||
actor: endpoint.sponsorUserId ? { type: "board", userId: endpoint.sponsorUserId, source: "session", ignoreInstanceAdmin: true } : { type: "none" },
|
||||
defaults,
|
||||
}, tx);
|
||||
await assertChatExecutionDefaultsAccess(db, {
|
||||
companyId: endpoint.companyId,
|
||||
actor: { type: "agent", agentId: endpoint.assignedAgentId, companyId: endpoint.companyId, onBehalfOfUserId: endpoint.sponsorUserId, source: "agent_key" },
|
||||
defaults,
|
||||
}, tx);
|
||||
const task = await issueService(db).create(
|
||||
endpoint.companyId,
|
||||
{
|
||||
...(defaults.projectId !== undefined ? { projectId: defaults.projectId } : {}),
|
||||
...placement,
|
||||
...(defaults.workspace ? { workspaceSelection: defaults.workspace, workspaceSelectionSource: "channel" as const } : {}),
|
||||
title: message.subject.slice(0, 200),
|
||||
description: `Email conversation for ${endpoint.botExternalId}`,
|
||||
status: "todo",
|
||||
|
||||
@@ -446,3 +446,21 @@ export function buildExecutionWorkspaceAdapterConfig(input: {
|
||||
|
||||
return nextConfig;
|
||||
}
|
||||
|
||||
/** Persisted filesystem authority survives UI feature-flag changes. */
|
||||
export function taskWorkspaceRuntimeSelectionEnabled(input: {
|
||||
legacyUiEnabled: boolean;
|
||||
hasTypedSelection: boolean;
|
||||
hasBinding: boolean;
|
||||
}): boolean {
|
||||
return input.legacyUiEnabled || input.hasTypedSelection || input.hasBinding;
|
||||
}
|
||||
|
||||
/** Defaults and pending intent never rewrite an already admitted native run. */
|
||||
export function canApplyTaskWorkspaceSelectionAtAdmission(input: {
|
||||
admittedInput: unknown;
|
||||
restarting: boolean;
|
||||
hasLeaseOwner: boolean;
|
||||
}): boolean {
|
||||
return input.admittedInput == null && !input.restarting && !input.hasLeaseOwner;
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import fs from "node:fs/promises";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { and, eq, or, sql } from "drizzle-orm";
|
||||
import { activityLog, executionWorkspaceRepositories, executionWorkspaces, issues, type Db } from "@paperclipai/db";
|
||||
import { prepareWorkspaceRepositorySchema, type PrepareWorkspaceRepository, type ProjectRepository } from "@paperclipai/shared";
|
||||
import { withDirectoryMergeLock } from "@paperclipai/adapter-utils/workspace-restore-merge";
|
||||
import { conflict, forbidden, notFound } from "../errors.js";
|
||||
import { accessService } from "./access.js";
|
||||
import { canActorReadExecutionWorkspace, issueReadSqlCondition, type AuthorizationActor } from "./authorization.js";
|
||||
import { captureRunIdentity } from "./run-identity.js";
|
||||
import { toolAccessService } from "./tool-access.js";
|
||||
import { normalizeProjectRepositoryUrl } from "./project-repositories.js";
|
||||
import { buildGitAuthInvocation, createGitRemoteAuthProvider } from "./git-credentials.js";
|
||||
import { materializeManagedProjectWorkspace, ensureManagedRepositoriesIgnored } from "./managed-repository-checkout.js";
|
||||
|
||||
const execFile = promisify(execFileCallback);
|
||||
type RepositoryRow = typeof executionWorkspaceRepositories.$inferSelect;
|
||||
|
||||
/** The catalog is refreshed on request and admission; saved IDs are not grants. */
|
||||
export function resolveTaskRepository(request: PrepareWorkspaceRepository["repository"], available: ProjectRepository[]) {
|
||||
const selected = request.kind === "catalog" ? available.find(repo => repo.id === request.id) : null;
|
||||
if (request.kind === "catalog" && !selected) throw forbidden("Repository access is no longer available; refresh the repository catalog");
|
||||
const source = normalizeProjectRepositoryUrl(selected?.url ?? (request.kind === "url" ? request.url : ""));
|
||||
const match = selected ?? available.find(repo => normalizeProjectRepositoryUrl(repo.url).url.toLowerCase() === source.url.toLowerCase());
|
||||
return { repoUrl: source.url, repositoryIdentity: source.url.toLowerCase(), catalogRepositoryId: match?.id ?? null };
|
||||
}
|
||||
|
||||
export function taskRepositoryRelativePath(identity: string) {
|
||||
return `.paperclip-repositories/task-repo-${createHash("sha256").update(identity).digest("hex").slice(0, 24)}`;
|
||||
}
|
||||
|
||||
export function assertRepositoryRetryMatches(row: Pick<RepositoryRow, "repositoryIdentity" | "requestedRef">, identity: string, ref: string) {
|
||||
if (row.repositoryIdentity !== identity || row.requestedRef !== ref) {
|
||||
throw conflict("Repository preparation conflicts with an existing receipt. A different ref requires a separate workspace; existing files are never switched automatically.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Workspace aggregate child. It owns acquisition receipts, never task binding or provider sessions. */
|
||||
export function executionWorkspaceRepositoryService(db: Db) {
|
||||
async function catalog(companyId: string, userId: string | null, localTrusted: boolean) {
|
||||
return (await toolAccessService(db).listProjectRepositories(companyId, userId, localTrusted)).repositories;
|
||||
}
|
||||
async function request(input: { companyId: string; issueId: string; actor: AuthorizationActor; request: PrepareWorkspaceRepository }) {
|
||||
const parsed = prepareWorkspaceRepositorySchema.parse(input.request);
|
||||
const decision = await accessService(db).decide({ actor: input.actor, action: "issue:mutate", resource: { type: "issue", companyId: input.companyId, issueId: input.issueId } });
|
||||
if (!decision.allowed) throw forbidden("Task workspace modification is not allowed");
|
||||
let userId = input.actor.userId ?? null;
|
||||
let localTrusted = input.actor.source === "local_implicit";
|
||||
if (input.actor.type === "agent") {
|
||||
if (input.actor.source !== "agent_jwt" || !input.actor.agentId || !input.actor.runId || input.actor.companyId !== input.companyId) throw forbidden("Repository preparation requires an authenticated task run");
|
||||
const identity = await captureRunIdentity(db, { companyId: input.companyId, agentId: input.actor.agentId, runId: input.actor.runId });
|
||||
const runIssueId = identity.run.nativeIssueId ?? identity.run.contextSnapshot?.issueId;
|
||||
if (runIssueId !== input.issueId) throw forbidden("Repository preparation is scoped to the current task");
|
||||
userId = identity.run.responsibleUserId;
|
||||
localTrusted = userId === "local-board";
|
||||
if (!userId) throw forbidden("Repository access requires a responsible user");
|
||||
}
|
||||
const source = resolveTaskRepository(parsed.repository, await catalog(input.companyId, userId, localTrusted));
|
||||
const requestedRef = parsed.ref ?? "HEAD";
|
||||
const receipt = await db.transaction(async tx => {
|
||||
const [issue] = await tx.select().from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId), await issueReadSqlCondition(tx, input.actor))).for("no key update");
|
||||
if (!issue) throw notFound("Task not found");
|
||||
if (input.actor.type === "agent" && !["standard", "skill_test"].includes(issue.workMode)) throw forbidden("Repository preparation is unavailable in Ask or Plan mode");
|
||||
if (!issue.executionWorkspaceId) throw conflict("The task has no admitted workspace yet. Start it once before preparing a repository.");
|
||||
if (!(await canActorReadExecutionWorkspace(db, input.actor, issue.executionWorkspaceId))) throw notFound("Execution workspace not found");
|
||||
// Serialize receipts across tasks without blocking unchanged-ID foreign-key reads.
|
||||
const [workspace] = await tx.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, issue.executionWorkspaceId), eq(executionWorkspaces.companyId, input.companyId))).for("no key update");
|
||||
if (!workspace || workspace.status !== "active") throw conflict("Execution workspace is unavailable");
|
||||
const existing = await tx.select().from(executionWorkspaceRepositories).where(and(eq(executionWorkspaceRepositories.executionWorkspaceId, workspace.id), or(eq(executionWorkspaceRepositories.repositoryIdentity, source.repositoryIdentity), sql`${executionWorkspaceRepositories.requestKeys} ? ${parsed.requestKey}`)));
|
||||
for (const row of existing) assertRepositoryRetryMatches(row, source.repositoryIdentity, requestedRef);
|
||||
if (existing[0]) {
|
||||
const row = existing[0];
|
||||
if (!row.requestKeys.includes(parsed.requestKey)) {
|
||||
const [updated] = await tx.update(executionWorkspaceRepositories).set({ requestKeys: [...row.requestKeys, parsed.requestKey] }).where(eq(executionWorkspaceRepositories.id, row.id)).returning();
|
||||
return updated;
|
||||
}
|
||||
return row;
|
||||
}
|
||||
const [row] = await tx.insert(executionWorkspaceRepositories).values({ companyId: input.companyId, executionWorkspaceId: workspace.id, requestedByIssueId: input.issueId, ...source, relativePath: taskRepositoryRelativePath(source.repositoryIdentity), requestedRef, requestKey: parsed.requestKey, requestKeys: [parsed.requestKey] }).returning();
|
||||
await tx.insert(activityLog).values({ companyId: input.companyId, actorType: input.actor.type === "agent" ? "agent" : "user", actorId: input.actor.agentId ?? input.actor.userId ?? "local-board", action: "workspace.repository.requested", entityType: "execution_workspace", entityId: workspace.id, runId: input.actor.runId ?? null, responsibleUserId: userId, details: { repositoryId: row.id, issueId: input.issueId, applies: "next_normal_admission" } });
|
||||
return row;
|
||||
});
|
||||
// No host-only checkout is represented as ready in an already admitted remote session.
|
||||
return { kind: "requires_next_admission" as const, applies: "next_normal_admission" as const, operationId: receipt.id, repository: receipt, reason: "immutable_admitted_workspace" };
|
||||
}
|
||||
async function list(companyId: string, workspaceId: string) {
|
||||
return db.select().from(executionWorkspaceRepositories).where(and(eq(executionWorkspaceRepositories.companyId, companyId), eq(executionWorkspaceRepositories.executionWorkspaceId, workspaceId)));
|
||||
}
|
||||
/** Logical rows may deliberately name one physical folder. Reuse bytes only
|
||||
* after validating every published owner's retained privacy and source intent. */
|
||||
async function sharedPublicationPin(input: { row: RepositoryRow; root: string; actor: AuthorizationActor; ownership: { repositoryId?: string; pinnedCommit?: string } | null }) {
|
||||
const candidates = await db.select({ repository: executionWorkspaceRepositories, workspace: executionWorkspaces })
|
||||
.from(executionWorkspaceRepositories).innerJoin(executionWorkspaces, eq(executionWorkspaces.id, executionWorkspaceRepositories.executionWorkspaceId))
|
||||
.where(and(eq(executionWorkspaceRepositories.companyId, input.row.companyId), eq(executionWorkspaces.companyId, input.row.companyId),
|
||||
eq(executionWorkspaceRepositories.repositoryIdentity, input.row.repositoryIdentity), eq(executionWorkspaceRepositories.relativePath, input.row.relativePath)));
|
||||
let pin = input.row.pinnedCommit;
|
||||
for (const { repository, workspace } of candidates) {
|
||||
if (repository.id === input.row.id || !workspace.cwd) continue;
|
||||
const candidatePin = repository.pinnedCommit ?? (input.ownership?.repositoryId === repository.id ? input.ownership.pinnedCommit : null);
|
||||
// An intent that has not published anything cannot claim another task's checkout.
|
||||
if (!candidatePin || !/^[a-f0-9]{40,64}$/.test(candidatePin)) continue;
|
||||
if (await fs.realpath(workspace.cwd).catch(() => null) !== input.root) continue;
|
||||
assertRepositoryRetryMatches(repository, input.row.repositoryIdentity, input.row.requestedRef);
|
||||
if (!(await canActorReadExecutionWorkspace(db, input.actor, workspace.id))) throw forbidden("The shared repository retains files from a workspace outside this actor's access");
|
||||
if (workspace.projectId && !(await accessService(db).decide({ actor: input.actor, action: "project:read", resource: { type: "project", companyId: input.row.companyId, projectId: workspace.projectId } })).allowed) throw forbidden("The shared repository's source project is outside this actor's access");
|
||||
if (pin && pin !== candidatePin) throw conflict("Shared repository publication receipts disagree; repair is required before reuse");
|
||||
pin = candidatePin;
|
||||
}
|
||||
return pin;
|
||||
}
|
||||
async function prepareForAdmission(input: { companyId: string; issueId: string; workspaceId: string; cwd: string; agentId: string; runId: string; responsibleUserId: string | null }) {
|
||||
const rows = await list(input.companyId, input.workspaceId);
|
||||
if (!rows.length) return [];
|
||||
const available = await catalog(input.companyId, input.responsibleUserId, input.responsibleUserId === "local-board");
|
||||
const resolveAuth = createGitRemoteAuthProvider(db, input.companyId, { issueId: input.issueId, heartbeatRunId: input.runId, agentId: input.agentId, responsibleUserId: input.responsibleUserId });
|
||||
const actor: AuthorizationActor = { type: "agent", source: "agent_jwt", companyId: input.companyId,
|
||||
agentId: input.agentId, runId: input.runId,
|
||||
// local-board is a server identity, not a membership record. Preserve the
|
||||
// agent's own authority rather than promoting it to a board actor.
|
||||
onBehalfOfUserId: input.responsibleUserId === "local-board" ? null : input.responsibleUserId };
|
||||
const root = await fs.realpath(input.cwd);
|
||||
const repositoryRoot = path.join(root, ".paperclip-repositories");
|
||||
await fs.mkdir(repositoryRoot, { recursive: true });
|
||||
if ((await fs.lstat(repositoryRoot)).isSymbolicLink() || await fs.realpath(repositoryRoot) !== repositoryRoot) throw conflict("Repository directory escapes the task workspace");
|
||||
await ensureManagedRepositoriesIgnored(root);
|
||||
const prepared: Array<{ id: string; cwd: string; repoUrl: string; relativePath: string; pinnedCommit: string; branchName: string | null }> = [];
|
||||
for (const row of rows) {
|
||||
const source = resolveTaskRepository(row.catalogRepositoryId ? { kind: "catalog", id: row.catalogRepositoryId } : { kind: "url", url: row.repoUrl }, available);
|
||||
if (source.repositoryIdentity !== row.repositoryIdentity || row.relativePath !== taskRepositoryRelativePath(row.repositoryIdentity)) throw conflict("Repository preparation receipt does not match its source");
|
||||
const cwd = path.join(root, row.relativePath);
|
||||
await withDirectoryMergeLock(cwd, async () => {
|
||||
const existing = await fs.lstat(cwd).catch(() => null);
|
||||
if (existing && (!existing.isDirectory() || existing.isSymbolicLink() || await fs.realpath(cwd) !== cwd)) throw conflict("Repository checkout path is not a contained directory");
|
||||
if (existing) {
|
||||
const gitDir = path.join(cwd, ".git");
|
||||
const metadata = await fs.lstat(gitDir).catch(() => null);
|
||||
if (!metadata?.isDirectory() || metadata.isSymbolicLink() || await fs.realpath(gitDir) !== gitDir) throw conflict("Repository Git metadata escapes the managed checkout");
|
||||
}
|
||||
// Uncataloged URLs may use anonymous public Git only. Never borrow a user's/company's credential for an arbitrary URL.
|
||||
const anonymous = buildGitAuthInvocation({ token: "", source: "managed_connection", secretName: null });
|
||||
anonymous.env = { ...anonymous.env, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null" };
|
||||
await db.update(executionWorkspaceRepositories).set({ state: "preparing", catalogRepositoryId: source.catalogRepositoryId, failureCode: null, updatedAt: new Date() }).where(eq(executionWorkspaceRepositories.id, row.id));
|
||||
try {
|
||||
const ownershipPath = path.join(cwd, ".git", "paperclip-workspace-owner.json");
|
||||
const readOwnership = async () => {
|
||||
const handle = await fs.open(ownershipPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK).catch(() => null);
|
||||
if (!handle) return null;
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
if (!stat.isFile() || stat.size > 4096) return null;
|
||||
const bytes = Buffer.alloc(4097);
|
||||
const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
|
||||
return bytesRead <= 4096 ? JSON.parse(bytes.subarray(0, bytesRead).toString("utf8")) : null;
|
||||
} catch { return null; } finally { await handle.close(); }
|
||||
};
|
||||
const initialOwnership = await readOwnership();
|
||||
const authorizedPin = await sharedPublicationPin({ row, root, actor, ownership: initialOwnership });
|
||||
if (existing && !authorizedPin && initialOwnership?.repositoryId !== row.id) {
|
||||
throw conflict("Repository directory has no matching preparation receipt; repair it before retrying");
|
||||
}
|
||||
const result = await materializeManagedProjectWorkspace(cwd, {
|
||||
repoUrl: row.repoUrl,
|
||||
repoRef: authorizedPin ?? (row.requestedRef === "HEAD" ? null : row.requestedRef),
|
||||
resolveGitAuth: source.catalogRepositoryId ? resolveAuth : async () => anonymous,
|
||||
beforePublish: async cloneCwd => {
|
||||
const pinnedCommit = (await execFile("git", ["-C", cloneCwd, "rev-parse", "HEAD"], { timeout: 30_000 })).stdout.trim();
|
||||
await fs.writeFile(path.join(cloneCwd, ".git", "paperclip-workspace-owner.json"), JSON.stringify({ version: 1, repositoryId: row.id, pinnedCommit }), { flag: "wx", mode: 0o600 });
|
||||
},
|
||||
});
|
||||
if (result.warning) throw conflict(result.warning);
|
||||
const git = async (...args: string[]) => (await execFile("git", ["-C", cwd, ...args], { timeout: 30_000 })).stdout.trim();
|
||||
const origin = normalizeProjectRepositoryUrl(await git("remote", "get-url", "origin"));
|
||||
if (origin.url.toLowerCase() !== row.repositoryIdentity) throw conflict("Repository checkout belongs to a different origin");
|
||||
const ownership = await readOwnership();
|
||||
if (!authorizedPin && (ownership?.repositoryId !== row.id || !/^[a-f0-9]{40,64}$/.test(ownership.pinnedCommit))) throw conflict("Repository publication has no valid preparation receipt");
|
||||
// The pre-publication commit survives a crash before the database update.
|
||||
const pinnedCommit: string = authorizedPin ?? ownership.pinnedCommit;
|
||||
const branchName = await git("symbolic-ref", "--quiet", "--short", "HEAD").catch(() => null);
|
||||
await db.update(executionWorkspaceRepositories).set({ state: "ready", pinnedCommit, branchName, failureCode: null, updatedAt: new Date() }).where(eq(executionWorkspaceRepositories.id, row.id));
|
||||
prepared.push({ id: row.id, cwd, repoUrl: row.repoUrl, relativePath: row.relativePath, pinnedCommit, branchName });
|
||||
} catch (error) {
|
||||
await db.update(executionWorkspaceRepositories).set({ state: "needs_repair", failureCode: "repository_preparation_failed", updatedAt: new Date() }).where(eq(executionWorkspaceRepositories.id, row.id));
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
return prepared;
|
||||
}
|
||||
return { request, list, prepareForAdmission };
|
||||
}
|
||||
@@ -1,3 +1,8 @@
|
||||
import { executionWorkspaceRepositoryService } from "./execution-workspace-repositories.js";
|
||||
import { accessService } from "./access.js";
|
||||
import { forbidden } from "../errors.js";
|
||||
import { taskWorkspaceSelectionSchema, type TaskWorkspaceSelection, type TaskWorkspaceIntent } from "@paperclipai/shared";
|
||||
import { executionWorkspaceReadSqlCondition, projectReadSqlCondition, issueReadSqlCondition, type AuthorizationActor } from "./authorization.js";
|
||||
import type { SQL } from "drizzle-orm";
|
||||
import { createWorkspaceGitInspectionCache } from "./workspace-git-inspection-cache.js";
|
||||
import { execFile } from "node:child_process";
|
||||
@@ -10,6 +15,7 @@ import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
executionWorkspaces,
|
||||
heartbeatRuns,
|
||||
nativeRunFinalizations,
|
||||
issueComments,
|
||||
issueWorkProducts,
|
||||
issues,
|
||||
@@ -64,6 +70,10 @@ import {
|
||||
selectConfiguredRuntimeServiceRows,
|
||||
} from "./workspace-runtime-read-model.js";
|
||||
|
||||
export type TaskWorkspaceBindingPatch = Partial<Pick<typeof issues.$inferInsert,
|
||||
"executionWorkspaceId" | "projectWorkspaceId" | "executionWorkspacePreference" | "executionWorkspaceSettings"
|
||||
>>;
|
||||
|
||||
type ExecutionWorkspaceRow = typeof executionWorkspaces.$inferSelect;
|
||||
type WorkspaceRuntimeServiceRow = typeof workspaceRuntimeServices.$inferSelect;
|
||||
type RuntimeServiceReadDb = Pick<Db, "select">;
|
||||
@@ -1265,7 +1275,7 @@ async function loadEffectiveRuntimeServicesByExecutionWorkspace(
|
||||
}
|
||||
|
||||
type WorkspaceOverviewPageRow = ExecutionWorkspaceRow & {
|
||||
projectName: string;
|
||||
projectName: string | null;
|
||||
projectWorkspaceMetadata: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
@@ -1276,6 +1286,115 @@ type WorkspaceOverviewIssueRow = WorkspaceOverviewLinkedIssue & {
|
||||
const inspectGitForDisplay = createWorkspaceGitInspectionCache(inspectGitCloseReadiness);
|
||||
|
||||
export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServiceOptions = {}) {
|
||||
/** Validate intent without allocating files or changing a task binding. */
|
||||
async function validateSelection(input: { companyId: string; actor: AuthorizationActor; selection: TaskWorkspaceSelection }, reader: Db | DbTransaction = db) {
|
||||
const selection = taskWorkspaceSelectionSchema.parse(input.selection);
|
||||
if (selection.kind === "existing") {
|
||||
const [workspace] = await reader.select().from(executionWorkspaces).where(and(
|
||||
eq(executionWorkspaces.id, selection.workspaceId), eq(executionWorkspaces.companyId, input.companyId),
|
||||
await executionWorkspaceReadSqlCondition(reader, input.actor),
|
||||
));
|
||||
if (!workspace || !["active", "idle"].includes(workspace.status)) throw notFound("Workspace is unavailable or inaccessible");
|
||||
return { executionWorkspaceId: workspace.id, projectWorkspaceId: workspace.projectWorkspaceId,
|
||||
executionWorkspacePreference: "reuse_existing", executionWorkspaceSettings: { mode: workspace.mode } };
|
||||
}
|
||||
if (selection.kind === "configured_source") {
|
||||
const [source] = await reader.select({ id: projectWorkspaces.id }).from(projectWorkspaces)
|
||||
.innerJoin(projects, eq(projects.id, projectWorkspaces.projectId)).where(and(
|
||||
eq(projectWorkspaces.id, selection.projectWorkspaceId), eq(projectWorkspaces.companyId, input.companyId),
|
||||
await projectReadSqlCondition(reader, input.actor),
|
||||
));
|
||||
if (!source) throw notFound("Workspace source is unavailable or inaccessible");
|
||||
return { executionWorkspaceId: null, projectWorkspaceId: source.id, executionWorkspacePreference: null,
|
||||
executionWorkspaceSettings: { mode: selection.mode === "shared" ? "shared_workspace" : "isolated_workspace" } };
|
||||
}
|
||||
return { executionWorkspaceId: null, projectWorkspaceId: null, executionWorkspacePreference: null,
|
||||
executionWorkspaceSettings: { mode: "shared_workspace" } };
|
||||
}
|
||||
|
||||
async function inspectTaskWorkspace(companyId: string, issueId: string, actor: AuthorizationActor) {
|
||||
const [task] = await db.select().from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, companyId), await issueReadSqlCondition(db, actor)));
|
||||
if (!task) throw notFound("Task not found");
|
||||
const [workspace] = task.executionWorkspaceId ? await db.select().from(executionWorkspaces)
|
||||
.where(and(eq(executionWorkspaces.id, task.executionWorkspaceId), eq(executionWorkspaces.companyId, companyId), await executionWorkspaceReadSqlCondition(db, actor))) : [];
|
||||
if (task.executionWorkspaceId && !workspace) throw notFound("Workspace is unavailable or inaccessible");
|
||||
return { issueId, bindingRevision: task.workspaceBindingRevision, selection: task.workspaceSelection,
|
||||
pendingSelection: task.workspacePendingSelection, workspace: workspace ? toExecutionWorkspace(workspace) : null };
|
||||
}
|
||||
|
||||
async function selectTaskWorkspace(input: { companyId: string; issueId: string; actor: AuthorizationActor;
|
||||
selection: TaskWorkspaceSelection; expectedBindingRevision: number; requestKey: string }) {
|
||||
const decision = await accessService(db).decide({ actor: input.actor, action: "issue:mutate", resource: { type: "issue", companyId: input.companyId, issueId: input.issueId } });
|
||||
if (!decision.allowed) throw forbidden("Task workspace modification is not allowed");
|
||||
return db.transaction(async tx => {
|
||||
const [task] = await tx.select().from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId),
|
||||
await issueReadSqlCondition(tx, input.actor))).for("update");
|
||||
if (!task) throw notFound("Task not found");
|
||||
if (task.workspaceSelection?.request?.key === input.requestKey) {
|
||||
if (task.workspaceSelection.request.expectedBindingRevision !== input.expectedBindingRevision ||
|
||||
JSON.stringify(taskWorkspaceSelectionSchema.parse(task.workspaceSelection.selection)) !== JSON.stringify(taskWorkspaceSelectionSchema.parse(input.selection))) {
|
||||
throw conflict("Workspace selection request key was already used for different intent");
|
||||
}
|
||||
return { kind: "applied" as const, bindingRevision: task.workspaceBindingRevision };
|
||||
}
|
||||
if (task.workspacePendingSelection?.requestKey === input.requestKey) {
|
||||
if (task.workspacePendingSelection.expectedBindingRevision !== input.expectedBindingRevision ||
|
||||
JSON.stringify(taskWorkspaceSelectionSchema.parse(task.workspacePendingSelection.intent.selection)) !== JSON.stringify(taskWorkspaceSelectionSchema.parse(input.selection))) {
|
||||
throw conflict("Workspace selection request key was already used for different intent");
|
||||
}
|
||||
return { kind: "scheduled" as const, applies: "next_normal_admission" as const, bindingRevision: task.workspaceBindingRevision };
|
||||
}
|
||||
if (task.workspaceBindingRevision !== input.expectedBindingRevision) throw conflict("Task workspace binding changed; inspect it before selecting again");
|
||||
await validateSelection(input, tx);
|
||||
const intent: TaskWorkspaceIntent = { version: 1, request: { key: input.requestKey, expectedBindingRevision: input.expectedBindingRevision }, selection: input.selection, source: "explicit" };
|
||||
// Root changes always wait for a new admission. The current provider and
|
||||
// any export-only recovery retain their immutable roots and input evidence.
|
||||
await tx.update(issues).set({ workspacePendingSelection: { version: 1, requestKey: input.requestKey,
|
||||
expectedBindingRevision: task.workspaceBindingRevision, intent }, updatedAt: new Date() }).where(eq(issues.id, task.id));
|
||||
return { kind: "scheduled" as const, applies: "next_normal_admission" as const, bindingRevision: task.workspaceBindingRevision };
|
||||
});
|
||||
}
|
||||
|
||||
async function applyPendingTaskWorkspaceSelection(input: { companyId: string; issueId: string; runId: string; actor: AuthorizationActor }) {
|
||||
return db.transaction(async tx => {
|
||||
const [task] = await tx.select().from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId))).for("update");
|
||||
if (!task?.workspacePendingSelection) return false;
|
||||
const pending = task.workspacePendingSelection;
|
||||
if (pending.expectedBindingRevision !== task.workspaceBindingRevision) throw conflict("Pending workspace selection is stale");
|
||||
const [holder] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.companyId, input.companyId), ne(heartbeatRuns.id, input.runId),
|
||||
sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId') = ${input.issueId}`,
|
||||
eq(heartbeatRuns.status, "running"),
|
||||
)).limit(1);
|
||||
if (holder) throw conflict("Previous task run must finish persistence before changing its workspace");
|
||||
const [unsettled] = await tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations).where(and(
|
||||
eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.issueId, input.issueId),
|
||||
ne(nativeRunFinalizations.runId, input.runId), ne(nativeRunFinalizations.phase, "committed"),
|
||||
)).limit(1);
|
||||
if (unsettled) throw conflict("Previous task run still owns workspace recovery; finish recovery before changing its workspace");
|
||||
const patch = await validateSelection({ ...input, selection: pending.intent.selection }, tx);
|
||||
await tx.update(issues).set({ ...patch, workspaceSelection: pending.intent, workspacePendingSelection: null,
|
||||
workspaceBindingRevision: task.workspaceBindingRevision + 1, updatedAt: new Date() }).where(eq(issues.id, task.id));
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
async function bindTaskWorkspace(companyId: string, issueId: string, workspaceId: string, patch: TaskWorkspaceBindingPatch = {}) {
|
||||
return db.transaction(async tx => {
|
||||
// Serialize binding and metadata writes without blocking unchanged-ID foreign-key reads.
|
||||
const [task] = await tx.select().from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, companyId))).for("no key update");
|
||||
const [workspace] = await tx.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, workspaceId), eq(executionWorkspaces.companyId, companyId))).for("no key update");
|
||||
if (!task || !workspace) throw notFound("Task workspace unavailable");
|
||||
// Retain confidentiality even after a task is moved to another root.
|
||||
await tx.update(executionWorkspaces).set({ metadata: { ...workspace.metadata,
|
||||
_issuePrivacySources: { ...(workspace.metadata?._issuePrivacySources as Record<string, unknown> ?? {}), [task.id]: true } } }).where(eq(executionWorkspaces.id, workspaceId));
|
||||
const [bound] = await tx.update(issues).set({ ...patch, executionWorkspaceId: workspaceId,
|
||||
workspaceBindingRevision: task.workspaceBindingRevision + (task.executionWorkspaceId === workspaceId ? 0 : 1), updatedAt: new Date() })
|
||||
.where(eq(issues.id, issueId)).returning();
|
||||
return bound;
|
||||
});
|
||||
}
|
||||
|
||||
const inspectDisplay = opts.inspectGitCloseReadiness
|
||||
? createWorkspaceGitInspectionCache(opts.inspectGitCloseReadiness)
|
||||
: inspectGitForDisplay;
|
||||
@@ -1723,7 +1842,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
|
||||
db
|
||||
.select({ executionWorkspacePolicy: projects.executionWorkspacePolicy })
|
||||
.from(projects)
|
||||
.where(and(eq(projects.companyId, workspace.companyId), eq(projects.id, workspace.projectId)))
|
||||
.where(and(eq(projects.companyId, workspace.companyId), workspace.projectId ? eq(projects.id, workspace.projectId) : sql`false`))
|
||||
.then((rows) => parseProjectExecutionWorkspacePolicy(rows[0]?.executionWorkspacePolicy)),
|
||||
]);
|
||||
const config = readExecutionWorkspaceConfig((workspace.metadata as Record<string, unknown> | null) ?? null);
|
||||
@@ -1869,6 +1988,10 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
|
||||
}
|
||||
|
||||
return {
|
||||
requestTaskRepository: executionWorkspaceRepositoryService(db).request,
|
||||
listTaskRepositories: executionWorkspaceRepositoryService(db).list,
|
||||
prepareTaskRepositoriesForAdmission: executionWorkspaceRepositoryService(db).prepareForAdmission,
|
||||
validateSelection, inspectTaskWorkspace, selectTaskWorkspace, applyPendingTaskWorkspaceSelection, bindTaskWorkspace,
|
||||
listOverview: async (
|
||||
companyId: string,
|
||||
filters: WorkspaceOverviewQuery,
|
||||
@@ -1876,13 +1999,13 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
|
||||
): Promise<WorkspaceOverviewResponse> => {
|
||||
const conditions = buildOverviewConditions(companyId, filters);
|
||||
if (readCondition) conditions.push(readCondition);
|
||||
const whereClause = and(...conditions);
|
||||
const whereClause = and(...conditions, sql`(${executionWorkspaces.projectId} IS NULL OR ${projects.id} IS NOT NULL)`);
|
||||
|
||||
const [totalRow, rows] = await Promise.all([
|
||||
db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(executionWorkspaces)
|
||||
.innerJoin(
|
||||
.leftJoin(
|
||||
projects,
|
||||
and(
|
||||
eq(projects.id, executionWorkspaces.projectId),
|
||||
@@ -1921,7 +2044,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
|
||||
projectWorkspaceMetadata: projectWorkspaces.metadata,
|
||||
})
|
||||
.from(executionWorkspaces)
|
||||
.innerJoin(
|
||||
.leftJoin(
|
||||
projects,
|
||||
and(
|
||||
eq(projects.id, executionWorkspaces.projectId),
|
||||
@@ -2042,7 +2165,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
|
||||
workspaceId: row.id,
|
||||
workspaceName: row.name,
|
||||
projectId: row.projectId,
|
||||
projectUrlKey: deriveProjectUrlKey(row.projectName, row.projectId),
|
||||
projectUrlKey: row.projectId && row.projectName ? deriveProjectUrlKey(row.projectName, row.projectId) : null,
|
||||
projectName: row.projectName,
|
||||
mode: row.mode as WorkspaceOverviewItem["mode"],
|
||||
strategyType: row.strategyType as WorkspaceOverviewItem["strategyType"],
|
||||
@@ -2919,29 +3042,31 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
|
||||
workspaceId: string;
|
||||
issue: { id: string; companyId: string; projectId: string | null };
|
||||
actor: { agentId: string | null; actorType: string };
|
||||
authorizationActor: AuthorizationActor;
|
||||
}): Promise<ReopenClosedIsolatedExecutionWorkspaceResult> => {
|
||||
const { issue, actor } = input;
|
||||
// Bind the workspace to the issue company and project. A null project on
|
||||
// the issue must match a null project on the row (IS NOT DISTINCT FROM).
|
||||
const projectIdCondition =
|
||||
issue.projectId == null
|
||||
? sql`${executionWorkspaces.projectId} IS NULL`
|
||||
: eq(executionWorkspaces.projectId, issue.projectId);
|
||||
|
||||
return db.transaction(async (tx): Promise<ReopenClosedIsolatedExecutionWorkspaceResult> => {
|
||||
await acquireExecutionWorkspaceLifecycleLock(tx, input.workspaceId);
|
||||
// Organizational project assignment does not identify the source of files.
|
||||
// Reopen only the task's persisted binding, with current source access.
|
||||
const [boundTask] = await tx.select({ id: issues.id }).from(issues).where(and(
|
||||
eq(issues.id, issue.id), eq(issues.companyId, issue.companyId),
|
||||
eq(issues.executionWorkspaceId, input.workspaceId),
|
||||
await issueReadSqlCondition(tx, input.authorizationActor),
|
||||
));
|
||||
if (!boundTask) return { ok: false, code: "not_reopenable", message: "Execution workspace is not reopenable" };
|
||||
const row = await tx
|
||||
.select()
|
||||
.from(executionWorkspaces)
|
||||
.where(and(
|
||||
eq(executionWorkspaces.id, input.workspaceId),
|
||||
eq(executionWorkspaces.companyId, issue.companyId),
|
||||
projectIdCondition,
|
||||
await executionWorkspaceReadSqlCondition(tx, input.authorizationActor),
|
||||
eq(executionWorkspaces.mode, "isolated_workspace"),
|
||||
))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!row) {
|
||||
// Wrong company, wrong project, wrong mode, or missing. Fail closed and
|
||||
// Wrong company, inaccessible source, wrong mode, or missing. Fail closed and
|
||||
// disclose no workspace detail.
|
||||
return { ok: false, code: "not_reopenable", message: "Execution workspace is not reopenable" };
|
||||
}
|
||||
@@ -2983,7 +3108,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
|
||||
db
|
||||
.select({ executionWorkspacePolicy: projects.executionWorkspacePolicy })
|
||||
.from(projects)
|
||||
.where(and(eq(projects.companyId, row.companyId), eq(projects.id, row.projectId)))
|
||||
.where(and(eq(projects.companyId, row.companyId), row.projectId ? eq(projects.id, row.projectId) : sql`false`))
|
||||
.then((rows) => parseProjectExecutionWorkspacePolicy(rows[0]?.executionWorkspacePolicy)),
|
||||
]);
|
||||
// Resolve the base checkout that the rebuild spawns git in. A
|
||||
|
||||
+291
-212
@@ -10,6 +10,8 @@ import {
|
||||
formatIssueIdentifierLink,
|
||||
parseNativeSessionGoalControl,
|
||||
} from "./heartbeat/scheduling.js";
|
||||
import { canApplyTaskWorkspaceSelectionAtAdmission, taskWorkspaceRuntimeSelectionEnabled } from "./execution-workspace-policy.js";
|
||||
import { canActorReadExecutionWorkspace } from "./authorization.js";
|
||||
import { agentExecutionsHaveStopped } from "./agent-execution-stop.js";
|
||||
import {
|
||||
cancelHeartbeatNativeRun,
|
||||
@@ -381,6 +383,7 @@ import {
|
||||
inArray,
|
||||
isNull,
|
||||
notInArray,
|
||||
ne,
|
||||
or,
|
||||
sql,
|
||||
} from "drizzle-orm";
|
||||
@@ -598,6 +601,7 @@ import {
|
||||
} from "./plan-review-context.js";
|
||||
import {
|
||||
executionWorkspaceService,
|
||||
type TaskWorkspaceBindingPatch,
|
||||
} from "./execution-workspaces.js";
|
||||
import {
|
||||
workspaceOperationService,
|
||||
@@ -2475,6 +2479,15 @@ export function heartbeatService(
|
||||
const taskKey = deriveTaskKeyWithHeartbeatFallback(context, null);
|
||||
const sessionCodec = getAdapterSessionCodec(agent.adapterType);
|
||||
const issueId = readNonEmptyString(context.issueId);
|
||||
if (issueId && canApplyTaskWorkspaceSelectionAtAdmission({ admittedInput: parseObject(run.runnerProfileJson).nativeExecutionInput, restarting: Boolean(runOptions.nativeRestartRecovery), hasLeaseOwner: Boolean(runOptions.nativeLeaseOwner) })) {
|
||||
const changed = await executionWorkspacesSvc.applyPendingTaskWorkspaceSelection({ companyId: agent.companyId,
|
||||
issueId, runId: run.id, actor: { type: "agent", agentId: agent.id, companyId: agent.companyId, source: "agent_key" } });
|
||||
if (changed) {
|
||||
delete context.resumeSessionParams;
|
||||
delete context.resumeSessionDisplayId;
|
||||
context.workspaceSelectionChanged = true;
|
||||
}
|
||||
}
|
||||
let issueContext = issueId
|
||||
? await getIssueExecutionContext(agent.companyId, issueId)
|
||||
: null;
|
||||
@@ -2626,20 +2639,31 @@ export function heartbeatService(
|
||||
const defaultIsolatedWorkspacesEnabled =
|
||||
isolatedWorkspacesEnabled &&
|
||||
experimentalInstanceSettings.enableIsolatedWorkspacesByDefault;
|
||||
const [taskWorkspaceIntentRow] = issueId ? await db.select({ intent: issues.workspaceSelection }).from(issues)
|
||||
.where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))) : [];
|
||||
// Typed selections and durable bindings are authoritative even when the
|
||||
// legacy isolated-workspace UI is disabled. Never downgrade isolation.
|
||||
const runtimeWorkspaceSelectionEnabled = taskWorkspaceRuntimeSelectionEnabled({ legacyUiEnabled: isolatedWorkspacesEnabled, hasTypedSelection: Boolean(taskWorkspaceIntentRow?.intent), hasBinding: Boolean(issueContext?.executionWorkspaceId) });
|
||||
const parsedIssueExecutionWorkspaceSettings =
|
||||
parseIssueExecutionWorkspaceSettings(
|
||||
issueContext?.executionWorkspaceSettings,
|
||||
);
|
||||
const issueExecutionWorkspaceSettings = isolatedWorkspacesEnabled
|
||||
const issueExecutionWorkspaceSettings = runtimeWorkspaceSelectionEnabled
|
||||
? parsedIssueExecutionWorkspaceSettings
|
||||
: null;
|
||||
const environmentExecutionWorkspaceSettings =
|
||||
selectEnvironmentExecutionWorkspaceSettings(
|
||||
parsedIssueExecutionWorkspaceSettings,
|
||||
isolatedWorkspacesEnabled,
|
||||
runtimeWorkspaceSelectionEnabled,
|
||||
);
|
||||
const contextProjectId = readNonEmptyString(context.projectId);
|
||||
const executionProjectId = issueContext?.projectId ?? contextProjectId;
|
||||
const boundSourceWorkspace = issueContext?.executionWorkspaceId
|
||||
? await executionWorkspacesSvc.getById(issueContext.executionWorkspaceId) : null;
|
||||
const [selectedWorkspaceSource] = !boundSourceWorkspace && issueContext?.projectWorkspaceId
|
||||
? await db.select({ projectId: projectWorkspaces.projectId }).from(projectWorkspaces)
|
||||
.where(and(eq(projectWorkspaces.id, issueContext.projectWorkspaceId), eq(projectWorkspaces.companyId, agent.companyId))) : [];
|
||||
const executionProjectId = boundSourceWorkspace ? boundSourceWorkspace.projectId
|
||||
: taskWorkspaceIntentRow?.intent?.selection.kind === "task_directory" ? null : selectedWorkspaceSource?.projectId ?? issueContext?.projectId ?? contextProjectId;
|
||||
const projectContext = executionProjectId
|
||||
? await db
|
||||
.select({
|
||||
@@ -2893,7 +2917,7 @@ export function heartbeatService(
|
||||
delete context.paperclipContinuationSummary;
|
||||
}
|
||||
const taskSessionDecodedParams = normalizeSessionParams(
|
||||
sessionCodec.deserialize(taskSession?.sessionParamsJson ?? null),
|
||||
sessionCodec.deserialize(context.workspaceSelectionChanged ? null : taskSession?.sessionParamsJson ?? null),
|
||||
);
|
||||
const explicitResumeSessionParams = normalizeResumeParamsForAdapter(
|
||||
agent.adapterType,
|
||||
@@ -3296,6 +3320,11 @@ export function heartbeatService(
|
||||
workspaceReuseRequest.existingExecutionWorkspaceAvailable
|
||||
? existingExecutionWorkspace
|
||||
: null;
|
||||
if (reusableExistingExecutionWorkspace && !nativeRecoveryExecutionWorkspaceId && !(await canActorReadExecutionWorkspace(db,
|
||||
{ type: "agent", agentId: agent.id, companyId: agent.companyId, source: "agent_jwt", runId: run.id,
|
||||
onBehalfOfUserId: responsibleUserId === "local-board" ? null : responsibleUserId }, reusableExistingExecutionWorkspace.id))) {
|
||||
throw new Error("Task workspace access is no longer available");
|
||||
}
|
||||
const requestedReusableExecutionWorkspaceConfig =
|
||||
reusableExistingExecutionWorkspace?.config ?? null;
|
||||
const localEnvironment = await environmentsSvc.ensureLocalEnvironment(
|
||||
@@ -3416,6 +3445,8 @@ export function heartbeatService(
|
||||
companyId: agent.companyId,
|
||||
agentId: agent.id,
|
||||
issueId,
|
||||
admittedCwd: persistedNativeExecutionInput && persistedNativeExecutionInput.schema !== "paperclip.native-execution-input.v6"
|
||||
? persistedNativeExecutionInput.workspace.cwd : null,
|
||||
});
|
||||
const nativeChatExpectedCwd = nativeChatWorkspaceScope
|
||||
? nativeChatWorkspaceCwd(
|
||||
@@ -3455,6 +3486,19 @@ export function heartbeatService(
|
||||
},
|
||||
);
|
||||
}
|
||||
if (!nativeRecoveryExecutionWorkspaceId && reusableExistingExecutionWorkspace &&
|
||||
effectiveExecutionWorkspaceMode === "shared_workspace" &&
|
||||
selectedEnvironmentForConfig?.driver !== "local" && selectedEnvironmentForConfig?.driver !== "ssh") {
|
||||
const [remoteSharedHolder] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.companyId, agent.companyId), ne(heartbeatRuns.id, run.id), eq(heartbeatRuns.status, "running"),
|
||||
sql`exists (select 1 from ${issues} where ${issues.companyId} = ${agent.companyId}
|
||||
and ${issues.executionWorkspaceId} = ${reusableExistingExecutionWorkspace.id}
|
||||
and (${issues.executionRunId} = ${heartbeatRuns.id} or ${issues.id}::text = coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId')))`,
|
||||
)).limit(1);
|
||||
if (remoteSharedHolder) throw new ConfigurationIncompleteFailure("This environment cannot place concurrent agents in one physical shared folder. Use local/SSH sharing or isolated task workspaces.", {
|
||||
configurationIncomplete: { reason: "shared_realization_unsupported", issueId },
|
||||
});
|
||||
}
|
||||
const sharedWorkspaceConcurrency = resolveSharedWorkspaceConcurrency({
|
||||
projectPolicy: projectExecutionWorkspacePolicy,
|
||||
issueSettings: issueExecutionWorkspaceSettings,
|
||||
@@ -3473,11 +3517,17 @@ export function heartbeatService(
|
||||
projectWorkspaceId: issueRef.projectWorkspaceId,
|
||||
excludeIssueId: issueRef.id,
|
||||
excludeRunId: run.id,
|
||||
honorIsolatedWorkspaceModes: isolatedWorkspacesEnabled,
|
||||
honorIsolatedWorkspaceModes: runtimeWorkspaceSelectionEnabled,
|
||||
});
|
||||
if (workspaceHolder) {
|
||||
const environmentDriver =
|
||||
selectedEnvironmentForConfig?.driver ?? null;
|
||||
if (!nativeRecoveryExecutionWorkspaceId && sharedWorkspaceConcurrency === "allow" &&
|
||||
(executionForcedToKubernetes || (environmentDriver !== "local" && environmentDriver !== "ssh"))) {
|
||||
throw new ConfigurationIncompleteFailure("This environment cannot place concurrent agents in one physical shared folder. Use local/SSH sharing or isolated task workspaces.", {
|
||||
configurationIncomplete: { reason: "shared_realization_unsupported", issueId },
|
||||
});
|
||||
}
|
||||
const shouldSerialize =
|
||||
sharedWorkspaceConcurrency !== "allow" &&
|
||||
(executionForcedToKubernetes ||
|
||||
@@ -3540,6 +3590,12 @@ export function heartbeatService(
|
||||
);
|
||||
}
|
||||
}
|
||||
if (taskWorkspaceIntentRow?.intent && !nativeRecoveryExecutionWorkspaceId) {
|
||||
await executionWorkspacesSvc.validateSelection({ companyId: agent.companyId,
|
||||
actor: { type: "agent", agentId: agent.id, companyId: agent.companyId, runId: run.id, source: "agent_jwt", onBehalfOfUserId: responsibleUserId === "local-board" ? null : responsibleUserId },
|
||||
selection: taskWorkspaceIntentRow.intent.selection });
|
||||
}
|
||||
const explicitTaskDirectory = taskWorkspaceIntentRow?.intent?.selection.kind === "task_directory";
|
||||
const useIsolatedTaskDirectory = issueRef !== null && shouldUseIsolatedTaskDirectory({
|
||||
trustPreset: trustPreset.kind,
|
||||
environmentDriver: selectedEnvironmentForConfig?.driver ?? null,
|
||||
@@ -3567,7 +3623,7 @@ export function heartbeatService(
|
||||
...(requestedAiBinding?.mode === "router" ? parseObject(parseObject(context.aiRouterSelection).runtimeConfig) : {}),
|
||||
// The base below is already task-owned. Keep directory transport while
|
||||
// preserving isolated mode and the mandatory sandbox preflight.
|
||||
...(useIsolatedTaskDirectory ? { workspaceStrategy: { type: "project_primary" } } : {}),
|
||||
...((useIsolatedTaskDirectory || explicitTaskDirectory) ? { workspaceStrategy: { type: "project_primary" } } : {}),
|
||||
};
|
||||
const configSnapshot = buildExecutionWorkspaceConfigSnapshot(
|
||||
mergedConfig,
|
||||
@@ -3845,7 +3901,7 @@ export function heartbeatService(
|
||||
acceptedPlanContinuationWake && !acceptedPlanWakeRoutingDecision && !agentIdentity,
|
||||
});
|
||||
const resetTaskSession =
|
||||
shouldResetTaskSessionForWake(context) || sessionConfigFreshness.reset;
|
||||
context.workspaceSelectionChanged === true || shouldResetTaskSessionForWake(context) || sessionConfigFreshness.reset;
|
||||
const sessionResetReason =
|
||||
sessionConfigFreshness.reasons.join("; ") || null;
|
||||
const taskSessionForRun = resetTaskSession ? null : taskSession;
|
||||
@@ -3881,7 +3937,7 @@ export function heartbeatService(
|
||||
} = await resolveWorkspaceAfterLowTrustPreflight({
|
||||
db,
|
||||
trustPreset,
|
||||
isolatedWorkspacesEnabled,
|
||||
isolatedWorkspacesEnabled: runtimeWorkspaceSelectionEnabled,
|
||||
effectiveExecutionWorkspaceMode,
|
||||
issue: issueRef
|
||||
? {
|
||||
@@ -3916,7 +3972,6 @@ export function heartbeatService(
|
||||
});
|
||||
if (reusableExistingExecutionWorkspace && (
|
||||
reusableExistingExecutionWorkspace.companyId !== agent.companyId ||
|
||||
reusableExistingExecutionWorkspace.projectId !== issueRef.projectId ||
|
||||
reusableExistingExecutionWorkspace.sourceIssueId !== issueRef.id ||
|
||||
reusableExistingExecutionWorkspace.mode !== "isolated_workspace" ||
|
||||
reusableExistingExecutionWorkspace.strategyType !== "project_primary" ||
|
||||
@@ -3931,7 +3986,7 @@ export function heartbeatService(
|
||||
anchorWorkspace: {
|
||||
cwd,
|
||||
source: "task_session",
|
||||
projectId: issueRef.projectId,
|
||||
projectId: reusableExistingExecutionWorkspace?.projectId ?? null,
|
||||
workspaceId: null,
|
||||
repoUrl: null,
|
||||
repoRef: null,
|
||||
@@ -3983,7 +4038,14 @@ export function heartbeatService(
|
||||
issueId,
|
||||
runId: run.id,
|
||||
})
|
||||
: undefined,
|
||||
: requestedShouldReuseExisting && reusableExistingExecutionWorkspace?.cwd ? {
|
||||
cwd: reusableExistingExecutionWorkspace.cwd, source: "task_session" as const,
|
||||
projectId: reusableExistingExecutionWorkspace.projectId,
|
||||
workspaceId: reusableExistingExecutionWorkspace.projectWorkspaceId,
|
||||
repoUrl: reusableExistingExecutionWorkspace.repoUrl, repoRef: reusableExistingExecutionWorkspace.baseRef,
|
||||
localPathOnlyWorkspace: reusableExistingExecutionWorkspace.strategyType === "project_primary" && !reusableExistingExecutionWorkspace.repoUrl && !reusableExistingExecutionWorkspace.branchName,
|
||||
workspaceHints: [], warnings: [], baseCwdFallback: false, materializationFailures: [],
|
||||
} : undefined,
|
||||
// Thread the selected environment driver so run-workspace resolution can tell a local
|
||||
// target from a remote one, and a confined sandbox target from an unconfined remote
|
||||
// target. A remote run resolves referenced projects only for the confined sandbox
|
||||
@@ -4252,7 +4314,7 @@ export function heartbeatService(
|
||||
},
|
||||
);
|
||||
const resolvedProjectId =
|
||||
executionWorkspace.projectId ??
|
||||
reusableExistingExecutionWorkspace ? reusableExistingExecutionWorkspace.projectId : executionWorkspace.projectId ??
|
||||
issueRef?.projectId ??
|
||||
executionProjectId ??
|
||||
null;
|
||||
@@ -4290,8 +4352,8 @@ export function heartbeatService(
|
||||
issueRef?.executionWorkspacePreference === "reuse_existing" ||
|
||||
requestedExecutionWorkspaceMode === "isolated_workspace" ||
|
||||
requestedExecutionWorkspaceMode === "operator_branch" ||
|
||||
warmReusableExecutionWorkspace || nativeSharedWorkspace;
|
||||
const nextIssuePatch: Record<string, unknown> = {};
|
||||
warmReusableExecutionWorkspace || nativeSharedWorkspace || Boolean(issueId);
|
||||
const nextIssuePatch: TaskWorkspaceBindingPatch = {};
|
||||
if (issueExecutionWorkspaceIdForRun !== workspace.id) {
|
||||
nextIssuePatch.executionWorkspaceId = workspace.id;
|
||||
}
|
||||
@@ -4313,14 +4375,7 @@ export function heartbeatService(
|
||||
};
|
||||
}
|
||||
if (Object.keys(nextIssuePatch).length > 0) {
|
||||
await issuesSvc.update(
|
||||
issueId,
|
||||
{ ...nextIssuePatch, companyGuard: agent.companyId },
|
||||
db,
|
||||
undefined,
|
||||
undefined,
|
||||
{ bindRuntimeSharedWorkspace: (warmReusableExecutionWorkspace || nativeSharedWorkspace) && workspace.mode === "shared_workspace" },
|
||||
);
|
||||
await executionWorkspacesSvc.bindTaskWorkspace(agent.companyId, issueId, workspace.id, nextIssuePatch);
|
||||
issueExecutionWorkspaceIdForRun = workspace.id;
|
||||
issueProjectWorkspaceIdForRun =
|
||||
resolvedProjectWorkspaceId ?? issueProjectWorkspaceIdForRun;
|
||||
@@ -4427,7 +4482,7 @@ export function heartbeatService(
|
||||
),
|
||||
},
|
||||
)
|
||||
: resolvedProjectId
|
||||
: !isDotRun && !persistedNativeExecutionInput && (resolvedProjectId || issueRef)
|
||||
? await executionWorkspacesSvc.create({
|
||||
companyId: agent.companyId,
|
||||
projectId: resolvedProjectId,
|
||||
@@ -4549,7 +4604,9 @@ export function heartbeatService(
|
||||
}
|
||||
await bindIssueToPersistedExecutionWorkspace(persistedExecutionWorkspace);
|
||||
const projectRepositoryPaths: string[] = [];
|
||||
if (executionWorkspace.projectId && resolvedWorkspace.source === "project_primary" && !resolvedWorkspace.baseCwdFallback) {
|
||||
if (executionWorkspace.projectId
|
||||
&& (resolvedWorkspace.source === "project_primary" || Boolean(reusableExistingExecutionWorkspace?.projectWorkspaceId))
|
||||
&& !resolvedWorkspace.baseCwdFallback && !persistedNativeExecutionInput) {
|
||||
const repositoryRows = await db.select().from(projectWorkspaces).where(and(
|
||||
eq(projectWorkspaces.companyId, agent.companyId),
|
||||
eq(projectWorkspaces.projectId, executionWorkspace.projectId),
|
||||
@@ -4563,10 +4620,21 @@ export function heartbeatService(
|
||||
const paths = new Map(repositories.map((repo) => [repo.workspaceId, repo.cwd]));
|
||||
projectRepositoryPaths.push(...repositories.map((repo) => path.relative(executionWorkspace.cwd, repo.cwd)));
|
||||
if (resolvedWorkspace.workspaceId) paths.set(resolvedWorkspace.workspaceId, executionWorkspace.cwd);
|
||||
resolvedWorkspace.workspaceHints = resolvedWorkspace.workspaceHints.map((hint) => ({
|
||||
...hint, cwd: paths.get(hint.workspaceId) ?? hint.cwd,
|
||||
// Reused roots may have no transient hints. Rebuild from the currently
|
||||
// authorized source rows and the paths actually prepared for this admission.
|
||||
resolvedWorkspace.workspaceHints = repositoryRows.map((source) => ({
|
||||
workspaceId: source.id,
|
||||
cwd: paths.get(source.id) ?? readNonEmptyString(source.cwd),
|
||||
repoUrl: readNonEmptyString(source.repoUrl),
|
||||
repoRef: readNonEmptyString(source.repoRef),
|
||||
}));
|
||||
}
|
||||
if (persistedExecutionWorkspace && issueId && !persistedNativeExecutionInput) {
|
||||
const taskRepositories = await executionWorkspacesSvc.prepareTaskRepositoriesForAdmission({ companyId: agent.companyId,
|
||||
issueId, workspaceId: persistedExecutionWorkspace.id, cwd: executionWorkspace.cwd,
|
||||
agentId: agent.id, runId: run.id, responsibleUserId });
|
||||
projectRepositoryPaths.push(...taskRepositories.map(repository => repository.relativePath));
|
||||
}
|
||||
if (persistedExecutionWorkspace) {
|
||||
context.executionWorkspaceId = persistedExecutionWorkspace.id;
|
||||
await db
|
||||
@@ -4613,7 +4681,7 @@ export function heartbeatService(
|
||||
await controllerLease.assertOwned();
|
||||
nativeRunnerPreparationSpans.push({
|
||||
name: "environment.acquire",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: environmentAcquireStartedAtMs,
|
||||
endedAtMs: Date.now(),
|
||||
attributes: { adapter: agent.adapterType },
|
||||
@@ -4621,7 +4689,7 @@ export function heartbeatService(
|
||||
} catch (error) {
|
||||
nativeRunnerPreparationSpans.push({
|
||||
name: "environment.acquire",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: environmentAcquireStartedAtMs,
|
||||
endedAtMs: Date.now(),
|
||||
outcome: "failed",
|
||||
@@ -4699,7 +4767,7 @@ export function heartbeatService(
|
||||
});
|
||||
nativeRunnerPreparationSpans.push({
|
||||
name: "environment.workspace.realize",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: environmentRealizeStartedAtMs,
|
||||
endedAtMs: Date.now(),
|
||||
attributes: { driver: selectedEnvironment.driver },
|
||||
@@ -4707,7 +4775,7 @@ export function heartbeatService(
|
||||
} catch (error) {
|
||||
nativeRunnerPreparationSpans.push({
|
||||
name: "environment.workspace.realize",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: environmentRealizeStartedAtMs,
|
||||
endedAtMs: Date.now(),
|
||||
outcome: "failed",
|
||||
@@ -6463,6 +6531,16 @@ export function heartbeatService(
|
||||
restartRecovery: runOptions.nativeRestartRecovery,
|
||||
sameRunRecovery: Boolean(runOptions.nativeLeaseOwner),
|
||||
resourceDisposition: providerResourceDispositionForRun,
|
||||
onCheckpoint: async (metrics) => {
|
||||
await appendRunEvent(run, { eventType: "lifecycle", stream: "system", level: "info",
|
||||
message: "workspace_checkpoint", payload: { phase: "workspace_checkpoint", ...metrics } });
|
||||
},
|
||||
onPhase: async (name, work) => {
|
||||
const started = Date.now();
|
||||
try { return await work(); }
|
||||
finally { await appendRunEvent(run, { eventType: "lifecycle", stream: "system", level: "info",
|
||||
message: name, payload: { phase: name, durationMs: Date.now() - started } }); }
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const legacyWarmLifecycle =
|
||||
@@ -6556,192 +6634,186 @@ export function heartbeatService(
|
||||
const recordWorkspaceFinalize = async (
|
||||
status: "succeeded" | "failed",
|
||||
metadata?: Record<string, unknown>,
|
||||
restore?: () => Promise<void>,
|
||||
) => {
|
||||
if (adapterFinalizeOutcome) return;
|
||||
let finalizeBranchMetadata: Record<string, unknown> | null = null;
|
||||
let finalizeBranchRepairMetadata: Record<string, unknown> | null =
|
||||
null;
|
||||
if (status === "succeeded") {
|
||||
const branchInspection = await inspectFinalizeWorkspaceBranch();
|
||||
if (branchInspection) {
|
||||
let inspection = branchInspection.inspection;
|
||||
const initialManagedGitWorktreeBranch =
|
||||
formatManagedGitWorktreeBranchInspection(inspection);
|
||||
if (
|
||||
!inspection.valid &&
|
||||
inspection.reasonCode === "branch_mismatch" &&
|
||||
inspection.repoRoot
|
||||
) {
|
||||
let repairedExpectedBranchName = inspection.expectedBranchName;
|
||||
try {
|
||||
const coherence = await ensureGitWorktreeBranchCoherent({
|
||||
db,
|
||||
repoRoot: inspection.repoRoot,
|
||||
worktreePath: inspection.worktreePath,
|
||||
expectedBranchName: inspection.expectedBranchName,
|
||||
actualBranchName: inspection.actualBranchName,
|
||||
sourceIssue: issueRef
|
||||
? {
|
||||
id: issueRef.id,
|
||||
identifier: issueRef.identifier,
|
||||
title: issueRef.title,
|
||||
workMode: issueRef.workMode,
|
||||
}
|
||||
: null,
|
||||
executionWorkspaceId: branchInspection.workspaceRecord.id,
|
||||
heartbeatRunId: run.id,
|
||||
enableWorkspaceBranchReconcileForward:
|
||||
resolvedInstanceSettings.experimental
|
||||
.enableWorkspaceBranchReconcileForward,
|
||||
enableWorkspaceDirtyQuarantineRepair:
|
||||
resolvedInstanceSettings.experimental
|
||||
.enableWorkspaceDirtyQuarantineRepair,
|
||||
persistForwardReconcile: false,
|
||||
reconcileOperationPhase: "workspace_finalize",
|
||||
recorder: workspaceOperationRecorder,
|
||||
});
|
||||
await workspaceOperationRecorder.recordOperation({
|
||||
phase: "workspace_finalize", cwd: executionWorkspace.cwd,
|
||||
metadata: { adapterType: agent.adapterType, executionTargetKind: executionTarget?.kind ?? "local",
|
||||
...(restore ? { owningService: "native_workspace_finalizer" } : {}), ...metadata },
|
||||
run: async () => {
|
||||
await restore?.();
|
||||
let finalizeBranchMetadata: Record<string, unknown> | null = null;
|
||||
let finalizeBranchRepairMetadata: Record<string, unknown> | null =
|
||||
null;
|
||||
if (status === "succeeded") {
|
||||
const branchInspection = await inspectFinalizeWorkspaceBranch();
|
||||
if (branchInspection) {
|
||||
let inspection = branchInspection.inspection;
|
||||
const initialManagedGitWorktreeBranch =
|
||||
formatManagedGitWorktreeBranchInspection(inspection);
|
||||
if (
|
||||
coherence.branchName &&
|
||||
coherence.branchName !==
|
||||
branchInspection.workspaceRecord.branchName
|
||||
!inspection.valid &&
|
||||
inspection.reasonCode === "branch_mismatch" &&
|
||||
inspection.repoRoot
|
||||
) {
|
||||
repairedExpectedBranchName = coherence.branchName;
|
||||
executionWorkspace.branchName = coherence.branchName;
|
||||
executionWorkspace.warnings.push(...coherence.warnings);
|
||||
}
|
||||
} catch (repairErr) {
|
||||
const workspaceValidationFailure =
|
||||
isWorkspaceValidationFailure(repairErr) ? repairErr : null;
|
||||
finalizeBranchMetadata = {
|
||||
executionWorkspaceId: branchInspection.workspaceRecord.id,
|
||||
...initialManagedGitWorktreeBranch,
|
||||
};
|
||||
finalizeBranchRepairMetadata = {
|
||||
attempted: true,
|
||||
succeeded: false,
|
||||
initial: initialManagedGitWorktreeBranch,
|
||||
reason:
|
||||
repairErr instanceof Error
|
||||
? repairErr.message
|
||||
: String(repairErr),
|
||||
};
|
||||
await workspaceOperationRecorder.recordOperation({
|
||||
phase: "workspace_finalize",
|
||||
cwd: executionWorkspace.cwd,
|
||||
metadata: {
|
||||
adapterType: agent.adapterType,
|
||||
executionTargetKind: executionTarget?.kind ?? "local",
|
||||
...metadata,
|
||||
managedGitWorktreeBranch: finalizeBranchMetadata,
|
||||
managedGitWorktreeBranchRepair:
|
||||
finalizeBranchRepairMetadata,
|
||||
...(workspaceValidationFailure?.resultJson
|
||||
? {
|
||||
workspaceValidation:
|
||||
workspaceValidationFailure.resultJson
|
||||
.workspaceValidation ??
|
||||
workspaceValidationFailure.resultJson,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
run: async () => ({
|
||||
status: "failed",
|
||||
stderr: `Managed git worktree branch check failed: ${repairErr instanceof Error ? repairErr.message : String(repairErr)}\n`,
|
||||
}),
|
||||
});
|
||||
adapterFinalizeOutcome = "failed";
|
||||
throw repairErr;
|
||||
}
|
||||
|
||||
const repairedInspection =
|
||||
await inspectManagedGitWorktreeBranch({
|
||||
worktreePath: inspection.worktreePath,
|
||||
expectedBranchName: repairedExpectedBranchName,
|
||||
repoRoot: inspection.repoRoot,
|
||||
});
|
||||
finalizeBranchRepairMetadata = {
|
||||
attempted: true,
|
||||
succeeded: repairedInspection.valid,
|
||||
initial: initialManagedGitWorktreeBranch,
|
||||
repaired:
|
||||
formatManagedGitWorktreeBranchInspection(
|
||||
repairedInspection,
|
||||
),
|
||||
};
|
||||
inspection = repairedInspection;
|
||||
}
|
||||
|
||||
const managedGitWorktreeBranch =
|
||||
formatManagedGitWorktreeBranchInspection(inspection);
|
||||
finalizeBranchMetadata = {
|
||||
executionWorkspaceId: branchInspection.workspaceRecord.id,
|
||||
...managedGitWorktreeBranch,
|
||||
};
|
||||
if (!inspection.valid) {
|
||||
const workspaceValidationFingerprint =
|
||||
fingerprintFinalizeWorkspaceBranchValidation({
|
||||
issueId: issueRef?.id ?? null,
|
||||
executionWorkspaceId: branchInspection.workspaceRecord.id,
|
||||
inspection: managedGitWorktreeBranch,
|
||||
});
|
||||
await workspaceOperationRecorder.recordOperation({
|
||||
phase: "workspace_finalize",
|
||||
cwd: executionWorkspace.cwd,
|
||||
metadata: {
|
||||
adapterType: agent.adapterType,
|
||||
executionTargetKind: executionTarget?.kind ?? "local",
|
||||
...metadata,
|
||||
managedGitWorktreeBranch: finalizeBranchMetadata,
|
||||
...(finalizeBranchRepairMetadata
|
||||
? {
|
||||
let repairedExpectedBranchName = inspection.expectedBranchName;
|
||||
try {
|
||||
const coherence = await ensureGitWorktreeBranchCoherent({
|
||||
db,
|
||||
repoRoot: inspection.repoRoot,
|
||||
worktreePath: inspection.worktreePath,
|
||||
expectedBranchName: inspection.expectedBranchName,
|
||||
actualBranchName: inspection.actualBranchName,
|
||||
sourceIssue: issueRef
|
||||
? {
|
||||
id: issueRef.id,
|
||||
identifier: issueRef.identifier,
|
||||
title: issueRef.title,
|
||||
workMode: issueRef.workMode,
|
||||
}
|
||||
: null,
|
||||
executionWorkspaceId: branchInspection.workspaceRecord.id,
|
||||
heartbeatRunId: run.id,
|
||||
enableWorkspaceBranchReconcileForward:
|
||||
resolvedInstanceSettings.experimental
|
||||
.enableWorkspaceBranchReconcileForward,
|
||||
enableWorkspaceDirtyQuarantineRepair:
|
||||
resolvedInstanceSettings.experimental
|
||||
.enableWorkspaceDirtyQuarantineRepair,
|
||||
persistForwardReconcile: false,
|
||||
reconcileOperationPhase: "workspace_finalize",
|
||||
recorder: workspaceOperationRecorder,
|
||||
});
|
||||
if (
|
||||
coherence.branchName &&
|
||||
coherence.branchName !==
|
||||
branchInspection.workspaceRecord.branchName
|
||||
) {
|
||||
repairedExpectedBranchName = coherence.branchName;
|
||||
executionWorkspace.branchName = coherence.branchName;
|
||||
executionWorkspace.warnings.push(...coherence.warnings);
|
||||
}
|
||||
} catch (repairErr) {
|
||||
const workspaceValidationFailure =
|
||||
isWorkspaceValidationFailure(repairErr) ? repairErr : null;
|
||||
finalizeBranchMetadata = {
|
||||
executionWorkspaceId: branchInspection.workspaceRecord.id,
|
||||
...initialManagedGitWorktreeBranch,
|
||||
};
|
||||
finalizeBranchRepairMetadata = {
|
||||
attempted: true,
|
||||
succeeded: false,
|
||||
initial: initialManagedGitWorktreeBranch,
|
||||
reason:
|
||||
repairErr instanceof Error
|
||||
? repairErr.message
|
||||
: String(repairErr),
|
||||
};
|
||||
await workspaceOperationRecorder.recordOperation({
|
||||
phase: "workspace_finalize",
|
||||
cwd: executionWorkspace.cwd,
|
||||
metadata: {
|
||||
adapterType: agent.adapterType,
|
||||
executionTargetKind: executionTarget?.kind ?? "local",
|
||||
...metadata,
|
||||
managedGitWorktreeBranch: finalizeBranchMetadata,
|
||||
managedGitWorktreeBranchRepair:
|
||||
finalizeBranchRepairMetadata,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
run: async () => ({
|
||||
status: "failed",
|
||||
stderr: `Managed git worktree branch check failed: ${inspection.reason ?? "unknown branch mismatch"}\n`,
|
||||
}),
|
||||
});
|
||||
adapterFinalizeOutcome = "failed";
|
||||
throw new WorkspaceValidationFailure(
|
||||
`Execution workspace ${branchInspection.workspaceRecord.id} expected git worktree branch "${inspection.expectedBranchName}" at "${inspection.worktreePath}", but ${inspection.reason ?? "the checked-out branch could not be verified"}. Record a sanctioned execution-workspace branch transition or restore the workspace branch before completing the run.`,
|
||||
{
|
||||
workspaceValidation: {
|
||||
reason: "git_worktree_branch_incoherence",
|
||||
fingerprint: workspaceValidationFingerprint,
|
||||
adapterType: agent.adapterType,
|
||||
issueId: issueRef?.id ?? null,
|
||||
issueIdentifier: issueRef?.identifier ?? null,
|
||||
persistedExecutionWorkspaceId:
|
||||
branchInspection.workspaceRecord.id,
|
||||
executionWorkspaceCwd: executionWorkspace.cwd,
|
||||
managedGitWorktreeBranch: finalizeBranchMetadata,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
await workspaceOperationRecorder.recordOperation({
|
||||
phase: "workspace_finalize",
|
||||
cwd: executionWorkspace.cwd,
|
||||
metadata: {
|
||||
adapterType: agent.adapterType,
|
||||
executionTargetKind: executionTarget?.kind ?? "local",
|
||||
...metadata,
|
||||
...(finalizeBranchMetadata
|
||||
? { managedGitWorktreeBranch: finalizeBranchMetadata }
|
||||
: {}),
|
||||
...(finalizeBranchRepairMetadata
|
||||
? {
|
||||
managedGitWorktreeBranchRepair:
|
||||
finalizeBranchRepairMetadata,
|
||||
...(workspaceValidationFailure?.resultJson
|
||||
? {
|
||||
workspaceValidation:
|
||||
workspaceValidationFailure.resultJson
|
||||
.workspaceValidation ??
|
||||
workspaceValidationFailure.resultJson,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
run: async () => ({
|
||||
status: "failed",
|
||||
stderr: `Managed git worktree branch check failed: ${repairErr instanceof Error ? repairErr.message : String(repairErr)}\n`,
|
||||
}),
|
||||
});
|
||||
adapterFinalizeOutcome = "failed";
|
||||
throw repairErr;
|
||||
}
|
||||
|
||||
const repairedInspection =
|
||||
await inspectManagedGitWorktreeBranch({
|
||||
worktreePath: inspection.worktreePath,
|
||||
expectedBranchName: repairedExpectedBranchName,
|
||||
repoRoot: inspection.repoRoot,
|
||||
});
|
||||
finalizeBranchRepairMetadata = {
|
||||
attempted: true,
|
||||
succeeded: repairedInspection.valid,
|
||||
initial: initialManagedGitWorktreeBranch,
|
||||
repaired:
|
||||
formatManagedGitWorktreeBranchInspection(
|
||||
repairedInspection,
|
||||
),
|
||||
};
|
||||
inspection = repairedInspection;
|
||||
}
|
||||
: {}),
|
||||
|
||||
const managedGitWorktreeBranch =
|
||||
formatManagedGitWorktreeBranchInspection(inspection);
|
||||
finalizeBranchMetadata = {
|
||||
executionWorkspaceId: branchInspection.workspaceRecord.id,
|
||||
...managedGitWorktreeBranch,
|
||||
};
|
||||
if (!inspection.valid) {
|
||||
const workspaceValidationFingerprint =
|
||||
fingerprintFinalizeWorkspaceBranchValidation({
|
||||
issueId: issueRef?.id ?? null,
|
||||
executionWorkspaceId: branchInspection.workspaceRecord.id,
|
||||
inspection: managedGitWorktreeBranch,
|
||||
});
|
||||
await workspaceOperationRecorder.recordOperation({
|
||||
phase: "workspace_finalize",
|
||||
cwd: executionWorkspace.cwd,
|
||||
metadata: {
|
||||
adapterType: agent.adapterType,
|
||||
executionTargetKind: executionTarget?.kind ?? "local",
|
||||
...metadata,
|
||||
managedGitWorktreeBranch: finalizeBranchMetadata,
|
||||
...(finalizeBranchRepairMetadata
|
||||
? {
|
||||
managedGitWorktreeBranchRepair:
|
||||
finalizeBranchRepairMetadata,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
run: async () => ({
|
||||
status: "failed",
|
||||
stderr: `Managed git worktree branch check failed: ${inspection.reason ?? "unknown branch mismatch"}\n`,
|
||||
}),
|
||||
});
|
||||
adapterFinalizeOutcome = "failed";
|
||||
throw new WorkspaceValidationFailure(
|
||||
`Execution workspace ${branchInspection.workspaceRecord.id} expected git worktree branch "${inspection.expectedBranchName}" at "${inspection.worktreePath}", but ${inspection.reason ?? "the checked-out branch could not be verified"}. Record a sanctioned execution-workspace branch transition or restore the workspace branch before completing the run.`,
|
||||
{
|
||||
workspaceValidation: {
|
||||
reason: "git_worktree_branch_incoherence",
|
||||
fingerprint: workspaceValidationFingerprint,
|
||||
adapterType: agent.adapterType,
|
||||
issueId: issueRef?.id ?? null,
|
||||
issueIdentifier: issueRef?.identifier ?? null,
|
||||
persistedExecutionWorkspaceId:
|
||||
branchInspection.workspaceRecord.id,
|
||||
executionWorkspaceCwd: executionWorkspace.cwd,
|
||||
managedGitWorktreeBranch: finalizeBranchMetadata,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { status, metadata: {
|
||||
...(finalizeBranchMetadata ? { managedGitWorktreeBranch: finalizeBranchMetadata } : {}),
|
||||
...(finalizeBranchRepairMetadata ? { managedGitWorktreeBranchRepair: finalizeBranchRepairMetadata } : {}),
|
||||
} };
|
||||
},
|
||||
run: async () => ({ status }),
|
||||
});
|
||||
// Only mark the outcome after the row landed, so a transient write
|
||||
// failure on the succeeded path can still be recovered by recording
|
||||
@@ -7182,10 +7254,11 @@ export function heartbeatService(
|
||||
eq(workspaceOperations.status, "succeeded"),
|
||||
)).limit(1);
|
||||
if (exported.length) adapterFinalizeOutcome = "succeeded";
|
||||
else await restoreNativeWorkspaceBestEffort({
|
||||
db, runId: run.id, assertOwnership: ownership?.assertHeld,
|
||||
restore: () => nativeWorkspaceSync!.restoreWorkspace(ownership?.assertHeld),
|
||||
});
|
||||
else await recordWorkspaceFinalize(hasWorkspaceRestoreFailure(adapterResult.resultJson) ? "failed" : "succeeded", undefined,
|
||||
async () => { await restoreNativeWorkspaceBestEffort({
|
||||
db, runId: run.id, assertOwnership: ownership?.assertHeld,
|
||||
restore: () => nativeWorkspaceSync!.restoreWorkspace(ownership?.assertHeld),
|
||||
}); });
|
||||
}
|
||||
await ownership?.assertHeld();
|
||||
await db
|
||||
@@ -7874,6 +7947,12 @@ export function heartbeatService(
|
||||
eq(heartbeatRuns.controllerBootId, legacyControllerBootId),
|
||||
inArray(heartbeatRuns.status, ["succeeded", "failed", "cancelled", "timed_out", "interrupted"])));
|
||||
|
||||
latestRun = await getRun(run.id).catch(() => null);
|
||||
if (latestRun && isHeartbeatRunTerminalStatus(latestRun.status) && !isNativeRunnerOwnershipHeld(latestRun)) {
|
||||
await appendRunEvent(run, { eventType: "lifecycle", stream: "system", level: "info", message: "task.run.measured",
|
||||
payload: { phase: "task.run.measured", durationMs: Date.now() - (latestRun.startedAt ?? latestRun.createdAt).getTime(),
|
||||
outcome: latestRun.status, durableSettlement: true } }).catch(error => logger.warn({ runId: run.id, error }, "Could not record terminal run duration"));
|
||||
}
|
||||
} finally {
|
||||
controllerLease.stop();
|
||||
activeRunExecutions.delete(run.id);
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
import { readGitConnectionFailure } from "../git-connection-failure.js";
|
||||
import { materializeManagedProjectWorkspace, ensureManagedRepositoriesIgnored } from "../managed-repository-checkout.js";
|
||||
export { materializeManagedProjectWorkspace } from "../managed-repository-checkout.js";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { materializeIsolatedTaskDirectory } from "../isolated-task-directory.js";
|
||||
import { readConnectionFailure, type GitConnectionFailure } from "@paperclipai/adapter-utils/connection-failure";
|
||||
import { classifyGitCloneFailure, GitConnectionFailureError, readGitConnectionFailure } from "../git-connection-failure.js";
|
||||
import { managedAiSessionFingerprintConfig } from "../ai-connection-runtime.js";
|
||||
import {
|
||||
PROJECT_REPOSITORIES_DIR,
|
||||
readGitWorkspaceSnapshot,
|
||||
disposeGitWorkspaceSnapshot,
|
||||
} from "@paperclipai/adapter-utils/git-workspace-sync";
|
||||
import {
|
||||
isWorkspaceGitScanError,
|
||||
WorkspaceGitScanError,
|
||||
} from "../workspace-git-operation-scheduler.js";
|
||||
import {
|
||||
captureDirectorySnapshot,
|
||||
disposeDirectorySnapshot,
|
||||
mergeDirectoryWithBaseline,
|
||||
} from "@paperclipai/adapter-utils/workspace-restore-merge";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
@@ -43,7 +37,6 @@ import {
|
||||
import { logger } from "../../middleware/logger.js";
|
||||
import {
|
||||
createGitRemoteAuthProvider,
|
||||
describeGitAuthFailure,
|
||||
scrubGitCredentialText,
|
||||
type GitRemoteAuthProvider,
|
||||
} from "../git-credentials.js";
|
||||
@@ -61,7 +54,6 @@ import {
|
||||
inspectManagedGitWorktreeBranch,
|
||||
type ExecutionWorkspaceInput,
|
||||
type RealizedExecutionWorkspace,
|
||||
sanitizeRuntimeServiceBaseEnv,
|
||||
} from "../workspace-runtime.js";
|
||||
import { resolvePersistedGitWorkspaceSource } from "../persisted-workspace-source.js";
|
||||
import { issueService } from "../issues.js";
|
||||
@@ -97,7 +89,6 @@ const execFile = promisify(execFileCallback);
|
||||
|
||||
const REPO_ONLY_CWD_SENTINEL = "/__paperclip_repo_only__";
|
||||
|
||||
const MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
export const WORKSPACE_VALIDATION_FAILURE_CODE = "workspace_validation_failed";
|
||||
|
||||
@@ -503,133 +494,6 @@ export async function ensureManagedProjectWorkspace(input: {
|
||||
return result;
|
||||
}
|
||||
|
||||
async function materializeManagedProjectWorkspace(
|
||||
cwd: string,
|
||||
input: {
|
||||
repoUrl: string | null;
|
||||
repoRef?: string | null;
|
||||
localSource?: string | null;
|
||||
resolveGitAuth?: GitRemoteAuthProvider | null;
|
||||
},
|
||||
): Promise<{ cwd: string; warning: string | null }> {
|
||||
await fs.mkdir(path.dirname(cwd), { recursive: true });
|
||||
const stats = await fs.stat(cwd).catch(() => null);
|
||||
|
||||
if (!input.repoUrl) {
|
||||
if (!stats) {
|
||||
await fs.mkdir(cwd, { recursive: true });
|
||||
}
|
||||
return { cwd, warning: null };
|
||||
}
|
||||
|
||||
const hasAdoptableGitDir = () =>
|
||||
fs
|
||||
.stat(path.resolve(cwd, ".git"))
|
||||
.then((entry) => entry.isDirectory())
|
||||
.catch(() => false);
|
||||
if (await hasAdoptableGitDir()) {
|
||||
return { cwd, warning: null };
|
||||
}
|
||||
|
||||
if (stats) {
|
||||
const entries = await fs.readdir(cwd).catch(() => []);
|
||||
if (entries.length > 0) {
|
||||
return {
|
||||
cwd,
|
||||
warning: `Managed workspace path "${cwd}" already exists but is not a git checkout. Using it as-is.`,
|
||||
};
|
||||
}
|
||||
await fs.rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
// Clone into a temp sibling, then move into place atomically. The shared target directory
|
||||
// is never created in a partial state and never removed on failure, so a concurrent
|
||||
// materialization (another process, or a run racing this one) can neither adopt a broken
|
||||
// checkout nor lose its own completed one.
|
||||
const auth = input.resolveGitAuth && !input.localSource
|
||||
? await input.resolveGitAuth(input.repoUrl)
|
||||
: null;
|
||||
const cloneTmpDir = await fs.mkdtemp(`${cwd}.clone-`);
|
||||
try {
|
||||
try {
|
||||
await execFile(
|
||||
"git",
|
||||
[...(auth?.configArgs ?? []), "clone", "--no-hardlinks", "--", input.localSource ?? input.repoUrl, cloneTmpDir],
|
||||
{
|
||||
env: {
|
||||
// Spread order matters: the sanitizer strips PAPERCLIP_*, which would remove the
|
||||
// credential-helper token env if it came first. GIT_TERMINAL_PROMPT=0 fails a
|
||||
// credential-less private clone immediately instead of hanging on a prompt until
|
||||
// the clone timeout.
|
||||
...sanitizeRuntimeServiceBaseEnv(process.env),
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
...(auth?.env ?? {}),
|
||||
},
|
||||
timeout: MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
const connectionFailure = !input.localSource ? classifyGitCloneFailure(input.repoUrl, error) : null;
|
||||
if (connectionFailure) throw new GitConnectionFailureError(
|
||||
error instanceof Error ? error.message : "Git clone failed", connectionFailure,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
if (input.localSource) {
|
||||
const snapshot = await readGitWorkspaceSnapshot(input.localSource, false);
|
||||
if (!snapshot) throw new Error("Configured repository folder is not a Git checkout");
|
||||
let baseline;
|
||||
try {
|
||||
baseline = await captureDirectorySnapshot(cloneTmpDir, { exclude: [".git", ".paperclip-runtime", PROJECT_REPOSITORIES_DIR], ignoredPaths: snapshot.ignoredPaths, diskBacked: true });
|
||||
await mergeDirectoryWithBaseline({ baseline, sourceDir: input.localSource, targetDir: cloneTmpDir });
|
||||
} finally {
|
||||
if (baseline) await disposeDirectorySnapshot(baseline);
|
||||
await disposeGitWorkspaceSnapshot(snapshot);
|
||||
}
|
||||
await execFile("git", ["-C", cloneTmpDir, "remote", "set-url", "origin", input.repoUrl], { timeout: 10_000 });
|
||||
} else if (input.repoRef) {
|
||||
await execFile("git", ["-C", cloneTmpDir, "checkout", input.repoRef], { timeout: MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS });
|
||||
}
|
||||
} catch (error) {
|
||||
await fs
|
||||
.rm(cloneTmpDir, { recursive: true, force: true })
|
||||
.catch(() => undefined);
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
const authNote = describeGitAuthFailure({
|
||||
error: reason,
|
||||
used: auth ? { source: auth.source, secretName: auth.secretName } : null,
|
||||
});
|
||||
const message = scrubGitCredentialText(
|
||||
`Failed to prepare managed checkout for "${input.repoUrl}" at "${cwd}": ${reason}${authNote ? ` ${authNote}` : ""}`,
|
||||
);
|
||||
// Preserve the closed failure code without copying subprocess output or
|
||||
// credentials into the durable run. Setup recovery needs the actual cause.
|
||||
if (isWorkspaceGitScanError(error)) throw new WorkspaceGitScanError(error.code, message);
|
||||
const connectionFailure = readGitConnectionFailure(error);
|
||||
if (connectionFailure) throw new GitConnectionFailureError(message, connectionFailure);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
try {
|
||||
await fs.rename(cloneTmpDir, cwd);
|
||||
} catch (renameError) {
|
||||
await fs
|
||||
.rm(cloneTmpDir, { recursive: true, force: true })
|
||||
.catch(() => undefined);
|
||||
// The target appearing between the emptiness check and the rename means another
|
||||
// materialization won the race; adopt its checkout instead of failing the run.
|
||||
if (await hasAdoptableGitDir()) {
|
||||
return { cwd, warning: null };
|
||||
}
|
||||
const reason =
|
||||
renameError instanceof Error ? renameError.message : String(renameError);
|
||||
throw new Error(
|
||||
`Failed to move managed checkout into place at "${cwd}": ${reason}`,
|
||||
);
|
||||
}
|
||||
return { cwd, warning: null };
|
||||
}
|
||||
|
||||
/** Keep every distinct project repository inside the task's writable/synced root. */
|
||||
export async function prepareProjectRepositoryWorkspaces(input: {
|
||||
cwd: string;
|
||||
@@ -650,13 +514,7 @@ export async function prepareProjectRepositoryWorkspaces(input: {
|
||||
if (await fs.realpath(root) !== path.join(await fs.realpath(input.cwd), PROJECT_REPOSITORIES_DIR)) {
|
||||
throw new Error("Project repositories directory escapes the task workspace");
|
||||
}
|
||||
const excludePath = await execFile("git", ["-C", input.cwd, "rev-parse", "--git-path", "info/exclude"], { timeout: 10_000 })
|
||||
.then((result) => path.resolve(input.cwd, result.stdout.trim()));
|
||||
const exclude = await fs.readFile(excludePath, "utf8").catch(() => "");
|
||||
if (!exclude.split(/\r?\n/).includes(`/${PROJECT_REPOSITORIES_DIR}/`)) {
|
||||
await fs.mkdir(path.dirname(excludePath), { recursive: true });
|
||||
await fs.appendFile(excludePath, `\n/${PROJECT_REPOSITORIES_DIR}/\n`);
|
||||
}
|
||||
await ensureManagedRepositoriesIgnored(input.cwd);
|
||||
const results = [];
|
||||
for (const workspace of selected) {
|
||||
const repoUrl = workspace.repoUrl!;
|
||||
@@ -675,7 +533,7 @@ export async function prepareProjectRepositoryWorkspaces(input: {
|
||||
// Retain detached checkout work outside the synchronized repository set.
|
||||
const active = new Set(results.map((repo) => path.basename(repo.cwd)));
|
||||
for (const entry of await fs.readdir(root)) {
|
||||
if (active.has(entry) || entry.includes(".clone-")) continue;
|
||||
if (active.has(entry) || entry.startsWith("task-repo-") || entry.includes(".clone-")) continue;
|
||||
const retained = path.join(input.cwd, ".paperclip-runtime", "detached-repositories", randomUUID());
|
||||
await fs.mkdir(path.dirname(retained), { recursive: true });
|
||||
await fs.rename(path.join(root, entry), retained);
|
||||
@@ -1282,7 +1140,7 @@ export async function assertGitSensitiveAdapterWorkspaceValid(input: {
|
||||
});
|
||||
};
|
||||
|
||||
if (issue.projectWorkspaceId && !issue.projectId) {
|
||||
if (issue.projectWorkspaceId && !issue.projectId && !input.persistedExecutionWorkspace?.projectId) {
|
||||
fail(
|
||||
"missing_project_id",
|
||||
`Issue ${issue.identifier ?? issue.id} is linked to a project workspace but has no project id; refusing to launch ${input.adapterType} from fallback cwd.`,
|
||||
@@ -1371,6 +1229,7 @@ export async function assertGitSensitiveAdapterWorkspaceValid(input: {
|
||||
|
||||
if (
|
||||
workspaceExpectation &&
|
||||
!(input.resolvedWorkspace.localPathOnlyWorkspace === true && input.executionWorkspace.strategy === "project_primary" && !input.executionWorkspace.repoUrl && !input.executionWorkspace.branchName) &&
|
||||
effectiveCwd &&
|
||||
!(await hasGitMetadata(effectiveCwd))
|
||||
) {
|
||||
@@ -3390,15 +3249,15 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
|
||||
? await db.select({ projectId: issues.projectId, projectWorkspaceId: issues.projectWorkspaceId }).from(issues)
|
||||
.where(and(eq(issues.id, input.issueId), eq(issues.companyId, agent.companyId))).then(rows => rows[0] ?? null)
|
||||
: null;
|
||||
const sourceProjectId = input.issueId && !input.immutableNativeBinding ? currentIssueSource?.projectId ?? null : input.projectId;
|
||||
const sourceProjectId = workspace.projectId;
|
||||
const explicitProjectWorkspaceId = currentIssueSource?.projectWorkspaceId ?? input.explicitProjectWorkspaceId;
|
||||
const projectWorkspaceRows = await db.select().from(projectWorkspaces).where(and(
|
||||
eq(projectWorkspaces.companyId, agent.companyId),
|
||||
eq(projectWorkspaces.projectId, workspace.projectId),
|
||||
workspace.projectId ? eq(projectWorkspaces.projectId, workspace.projectId) : sql`false`,
|
||||
)).orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id));
|
||||
const boundProjectWorkspace = projectWorkspaceRows.find(row => row.id === workspace.projectWorkspaceId) ?? null;
|
||||
const configuredSource = prioritizeProjectWorkspaceCandidatesForRun(projectWorkspaceRows, explicitProjectWorkspaceId)[0];
|
||||
const managedBase = workspace.repoUrl ? resolveManagedProjectWorkspaceDir({
|
||||
const managedBase = workspace.repoUrl && workspace.projectId ? resolveManagedProjectWorkspaceDir({
|
||||
companyId: agent.companyId,
|
||||
projectId: workspace.projectId,
|
||||
repoName: deriveRepoNameFromRepoUrl(workspace.repoUrl),
|
||||
@@ -3416,10 +3275,10 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
|
||||
boundProjectWorkspace,
|
||||
candidateBaseCwds,
|
||||
managedSourceRoot: resolvePaperclipInstanceRoot(),
|
||||
materializeOriginalRepository: workspace.repoUrl ? async () => {
|
||||
materializeOriginalRepository: workspace.repoUrl && workspace.projectId ? async () => {
|
||||
const original = await ensureManagedProjectWorkspace({
|
||||
companyId: agent.companyId,
|
||||
projectId: workspace.projectId,
|
||||
projectId: workspace.projectId!,
|
||||
repoUrl: workspace.repoUrl,
|
||||
resolveGitAuth: createGitRemoteAuthProvider(db, agent.companyId, {
|
||||
issueId: input.issueId, heartbeatRunId: input.runId, agentId: agent.id,
|
||||
@@ -3476,6 +3335,7 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
|
||||
.select({
|
||||
projectId: issues.projectId,
|
||||
projectWorkspaceId: issues.projectWorkspaceId,
|
||||
workspaceSelection: issues.workspaceSelection,
|
||||
})
|
||||
.from(issues)
|
||||
.where(
|
||||
@@ -3486,9 +3346,12 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
|
||||
const issueProjectId = issueProjectRef?.projectId ?? null;
|
||||
const preferredProjectWorkspaceId =
|
||||
issueProjectRef?.projectWorkspaceId ?? contextProjectWorkspaceId ?? null;
|
||||
const resolvedProjectId = issueProjectId ?? contextProjectId;
|
||||
const [selectedSource] = preferredProjectWorkspaceId ? await db.select({ projectId: projectWorkspaces.projectId }).from(projectWorkspaces)
|
||||
.where(and(eq(projectWorkspaces.id, preferredProjectWorkspaceId), eq(projectWorkspaces.companyId, agent.companyId))) : [];
|
||||
const resolvedProjectId = selectedSource?.projectId ?? issueProjectId ?? contextProjectId;
|
||||
const forceTaskDirectory = issueProjectRef?.workspaceSelection?.selection.kind === "task_directory";
|
||||
const useProjectWorkspace = opts?.useProjectWorkspace !== false;
|
||||
const workspaceProjectId = useProjectWorkspace ? resolvedProjectId : null;
|
||||
const workspaceProjectId = useProjectWorkspace && !forceTaskDirectory ? resolvedProjectId : null;
|
||||
|
||||
const unorderedProjectWorkspaceRows = workspaceProjectId
|
||||
? await db
|
||||
@@ -3592,52 +3455,12 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
|
||||
missingProjectCwds.push(projectCwd);
|
||||
}
|
||||
|
||||
const fallbackCwd = resolveDefaultAgentWorkspaceDir(agent.id);
|
||||
await fs.mkdir(fallbackCwd, { recursive: true });
|
||||
const warnings = buildAnchorFallbackWorkspaceNotes({
|
||||
fallbackCwd,
|
||||
preferredWorkspaceWarning,
|
||||
materializationFailures,
|
||||
missingProjectCwds,
|
||||
hasConfiguredProjectCwd,
|
||||
});
|
||||
return {
|
||||
cwd: fallbackCwd,
|
||||
source: "project_primary" as const,
|
||||
projectId: resolvedProjectId,
|
||||
workspaceId: projectWorkspaceRows[0]?.id ?? null,
|
||||
repoUrl: projectWorkspaceRows[0]?.repoUrl ?? null,
|
||||
repoRef: projectWorkspaceRows[0]?.repoRef ?? null,
|
||||
workspaceHints,
|
||||
warnings,
|
||||
baseCwdFallback: true,
|
||||
materializationFailures,
|
||||
};
|
||||
}
|
||||
|
||||
if (workspaceProjectId) {
|
||||
const managedWorkspace = await ensureManagedProjectWorkspace({
|
||||
companyId: agent.companyId,
|
||||
projectId: workspaceProjectId,
|
||||
repoUrl: null,
|
||||
});
|
||||
return {
|
||||
cwd: managedWorkspace.cwd,
|
||||
source: "project_primary" as const,
|
||||
projectId: resolvedProjectId,
|
||||
workspaceId: null,
|
||||
repoUrl: null,
|
||||
repoRef: null,
|
||||
workspaceHints,
|
||||
warnings: managedWorkspace.warning ? [managedWorkspace.warning] : [],
|
||||
baseCwdFallback: false,
|
||||
materializationFailures: [],
|
||||
};
|
||||
throw new Error(`Configured project workspace is unavailable: ${preferredWorkspaceWarning ?? materializationFailures[0]?.error ?? missingProjectCwds[0] ?? "source could not be prepared"}`);
|
||||
}
|
||||
|
||||
const sessionCwd = readNonEmptyString(previousSessionParams?.cwd);
|
||||
const sessionCwdLooksUnsafe = isUnsafeSessionWorkspaceCwd(sessionCwd);
|
||||
if (sessionCwd && !sessionCwdLooksUnsafe) {
|
||||
if (!forceTaskDirectory && sessionCwd && !sessionCwdLooksUnsafe) {
|
||||
const sessionCwdExists = await fs
|
||||
.stat(sessionCwd)
|
||||
.then((stats) => stats.isDirectory())
|
||||
@@ -3658,7 +3481,10 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
|
||||
}
|
||||
}
|
||||
|
||||
const cwd = resolveDefaultAgentWorkspaceDir(agent.id);
|
||||
const configuredCwd = !forceTaskDirectory ? readNonEmptyString(parseObject(agent.adapterConfig).cwd) : null;
|
||||
const cwd = configuredCwd ? path.resolve(configuredCwd)
|
||||
: issueId ? await materializeIsolatedTaskDirectory({ companyId: agent.companyId, issueId })
|
||||
: resolveDefaultAgentWorkspaceDir(agent.id);
|
||||
await fs.mkdir(cwd, { recursive: true });
|
||||
const warnings: string[] = [];
|
||||
if (sessionCwd && sessionCwdLooksUnsafe) {
|
||||
@@ -3680,8 +3506,8 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
|
||||
}
|
||||
return {
|
||||
cwd,
|
||||
source: "agent_home" as const,
|
||||
projectId: resolvedProjectId,
|
||||
source: issueId || configuredCwd ? "task_session" as const : "agent_home" as const,
|
||||
projectId: null,
|
||||
workspaceId: null,
|
||||
repoUrl: null,
|
||||
repoRef: null,
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { type AuthorizationActor, executionWorkspaceReadSqlCondition, projectReadSqlCondition } from "./authorization.js";
|
||||
import { type TaskWorkspaceSelection, type TaskWorkspaceIntent } from "@paperclipai/shared";
|
||||
import { executionWorkspaceService } from "./execution-workspaces.js";
|
||||
import { recordChatHandoff, recordChatCompletion, existingChatCompletionReply, acknowledgeChatCompletionReply } from "./chat-completion-delivery.js";
|
||||
import { mirrorSlackBoardComment, slackBoardReplyBindings } from "./slack-board-messages.js";
|
||||
import { assertAgentRunWriteAllowed } from "../agent-run-cancellation.js";
|
||||
@@ -1937,7 +1940,10 @@ async function assertExecutionTaskParent(db: Db, companyId: string, parentId?: s
|
||||
}
|
||||
|
||||
type DbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
type IssueCreateInput = Omit<typeof issues.$inferInsert, "companyId" | "title" | "titleNeedsGeneration"> & {
|
||||
type IssueCreateInput = Omit<typeof issues.$inferInsert, "companyId" | "title" | "titleNeedsGeneration" | "workspaceSelection"> & {
|
||||
workspaceSelection?: TaskWorkspaceSelection;
|
||||
workspaceSelectionSource?: "explicit" | "channel";
|
||||
workspaceSelectionActor?: AuthorizationActor;
|
||||
title?: string;
|
||||
initialPlan?: string | null;
|
||||
labelIds?: string[];
|
||||
@@ -4999,6 +5005,9 @@ const issueListSelect = {
|
||||
executionWorkspaceId: issues.executionWorkspaceId,
|
||||
executionWorkspacePreference: issues.executionWorkspacePreference,
|
||||
executionWorkspaceSettings: sql<null>`null`,
|
||||
workspaceSelection: sql<null>`null`,
|
||||
workspacePendingSelection: sql<null>`null`,
|
||||
workspaceBindingRevision: issues.workspaceBindingRevision,
|
||||
sourceTrust: issues.sourceTrust,
|
||||
unblockDescriptor: issues.unblockDescriptor,
|
||||
blockedTransitionAt: issues.blockedTransitionAt,
|
||||
@@ -7301,11 +7310,6 @@ export function issueService(db: Db) {
|
||||
if (!workspace) throw notFound("Execution workspace not found");
|
||||
if (workspace.companyId !== companyId)
|
||||
throw unprocessable("Execution workspace must belong to same company");
|
||||
if (projectId && workspace.projectId !== projectId) {
|
||||
throw unprocessable(
|
||||
"Execution workspace must belong to the selected project",
|
||||
);
|
||||
}
|
||||
return workspace;
|
||||
}
|
||||
|
||||
@@ -9913,6 +9917,7 @@ export function issueService(db: Db) {
|
||||
dbOrTx: Db | DbTransaction = db,
|
||||
) => {
|
||||
const {
|
||||
workspaceSelection, workspaceSelectionSource = "explicit", workspaceSelectionActor,
|
||||
initialPlan,
|
||||
labelIds: inputLabelIds,
|
||||
blockedByIssueIds,
|
||||
@@ -10080,12 +10085,14 @@ export function issueService(db: Db) {
|
||||
let executionWorkspaceSettings =
|
||||
(issueData.executionWorkspaceSettings as
|
||||
Record<string, unknown> | null | undefined) ?? null;
|
||||
let inheritedWorkspaceSelection = false;
|
||||
const workspaceInheritanceIssueId = skipExecutionWorkspaceInheritance
|
||||
? null
|
||||
: (inheritExecutionWorkspaceFromIssueId ??
|
||||
issueData.parentId ??
|
||||
null);
|
||||
const hasExplicitExecutionWorkspaceOverride =
|
||||
(workspaceSelection !== undefined && workspaceSelectionSource === "explicit") ||
|
||||
issueData.executionWorkspaceId !== undefined ||
|
||||
issueData.executionWorkspacePreference !== undefined ||
|
||||
issueData.executionWorkspaceSettings !== undefined;
|
||||
@@ -10113,6 +10120,7 @@ export function issueService(db: Db) {
|
||||
workspaceSource.projectWorkspaceId
|
||||
) {
|
||||
projectWorkspaceId = workspaceSource.projectWorkspaceId;
|
||||
inheritedWorkspaceSelection = true;
|
||||
}
|
||||
if (
|
||||
inheritsSourceProject &&
|
||||
@@ -10135,6 +10143,7 @@ export function issueService(db: Db) {
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (sourceWorkspace) {
|
||||
executionWorkspaceId = sourceWorkspace.id;
|
||||
inheritedWorkspaceSelection = true;
|
||||
executionWorkspacePreference = "reuse_existing";
|
||||
executionWorkspaceSettings = {
|
||||
...((workspaceSource.executionWorkspaceSettings as
|
||||
@@ -10146,23 +10155,19 @@ export function issueService(db: Db) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (issueData.projectId == null && projectWorkspaceId) {
|
||||
const workspace = await assertValidProjectWorkspace(
|
||||
companyId,
|
||||
null,
|
||||
projectWorkspaceId,
|
||||
tx,
|
||||
);
|
||||
issueData.projectId = workspace.projectId;
|
||||
}
|
||||
if (issueData.projectId == null && executionWorkspaceId) {
|
||||
const workspace = await assertValidExecutionWorkspace(
|
||||
companyId,
|
||||
null,
|
||||
executionWorkspaceId,
|
||||
tx,
|
||||
);
|
||||
issueData.projectId = workspace.projectId;
|
||||
const workspaceActor: AuthorizationActor = workspaceSelectionActor ?? (issueData.createdByUserId
|
||||
? { type: "board", userId: issueData.createdByUserId, companyIds: [companyId] }
|
||||
: { type: "agent", agentId: issueData.createdByAgentId ?? issueData.assigneeAgentId, companyId });
|
||||
let workspaceIntent: TaskWorkspaceIntent | null = null;
|
||||
if (workspaceSelection && (workspaceSelectionSource === "explicit" || !inheritedWorkspaceSelection)) {
|
||||
const projection = await executionWorkspaceService(db).validateSelection({ companyId,
|
||||
actor: workspaceActor,
|
||||
selection: workspaceSelection }, tx);
|
||||
projectWorkspaceId = projection.projectWorkspaceId;
|
||||
executionWorkspaceId = projection.executionWorkspaceId;
|
||||
executionWorkspacePreference = projection.executionWorkspacePreference;
|
||||
executionWorkspaceSettings = projection.executionWorkspaceSettings;
|
||||
workspaceIntent = { version: 1, selection: workspaceSelection, source: workspaceSelectionSource };
|
||||
}
|
||||
const projectGoalId = await getProjectDefaultGoalId(
|
||||
tx,
|
||||
@@ -10210,7 +10215,7 @@ export function issueService(db: Db) {
|
||||
),
|
||||
) as Record<string, unknown> | null;
|
||||
}
|
||||
if (!projectWorkspaceId && issueData.projectId) {
|
||||
if (!projectWorkspaceId && issueData.projectId && workspaceIntent?.selection.kind !== "task_directory") {
|
||||
const project = await tx
|
||||
.select({
|
||||
executionWorkspacePolicy: projects.executionWorkspacePolicy,
|
||||
@@ -10245,10 +10250,21 @@ export function issueService(db: Db) {
|
||||
.then((rows) => rows[0]?.id ?? null);
|
||||
}
|
||||
}
|
||||
if (projectWorkspaceId && workspaceSelectionActor) {
|
||||
const [readableSource] = await tx.select({ id: projectWorkspaces.id }).from(projectWorkspaces)
|
||||
.innerJoin(projects, eq(projects.id, projectWorkspaces.projectId))
|
||||
.where(and(eq(projectWorkspaces.id, projectWorkspaceId), eq(projectWorkspaces.companyId, companyId), await projectReadSqlCondition(tx, workspaceActor)));
|
||||
if (!readableSource) throw notFound("Workspace source is unavailable or inaccessible");
|
||||
}
|
||||
if (executionWorkspaceId && workspaceSelectionActor) {
|
||||
const [readableWorkspace] = await tx.select({ id: executionWorkspaces.id }).from(executionWorkspaces)
|
||||
.where(and(eq(executionWorkspaces.id, executionWorkspaceId), eq(executionWorkspaces.companyId, companyId), await executionWorkspaceReadSqlCondition(tx, workspaceActor)));
|
||||
if (!readableWorkspace) throw notFound("Workspace is unavailable or inaccessible");
|
||||
}
|
||||
if (projectWorkspaceId) {
|
||||
await assertValidProjectWorkspace(
|
||||
companyId,
|
||||
issueData.projectId,
|
||||
null,
|
||||
projectWorkspaceId,
|
||||
tx,
|
||||
);
|
||||
@@ -10256,7 +10272,7 @@ export function issueService(db: Db) {
|
||||
if (executionWorkspaceId) {
|
||||
await assertValidExecutionWorkspace(
|
||||
companyId,
|
||||
issueData.projectId,
|
||||
null,
|
||||
executionWorkspaceId,
|
||||
tx,
|
||||
);
|
||||
@@ -10367,6 +10383,7 @@ export function issueService(db: Db) {
|
||||
|
||||
const values = {
|
||||
...issueData,
|
||||
workspaceSelection: workspaceIntent,
|
||||
visibility,
|
||||
privacyRootIssueId,
|
||||
privacyParentIssueId,
|
||||
@@ -11083,46 +11100,8 @@ export function issueService(db: Db) {
|
||||
? { ...nextExecutionWorkspaceSettings }
|
||||
: null;
|
||||
}
|
||||
let validatedProjectWorkspace: { projectId: string } | null = null;
|
||||
let validatedExecutionWorkspace: { projectId: string } | null = null;
|
||||
if (!nextProjectId && nextProjectWorkspaceId) {
|
||||
const workspace = await assertValidProjectWorkspace(
|
||||
existing.companyId,
|
||||
null,
|
||||
nextProjectWorkspaceId,
|
||||
);
|
||||
validatedProjectWorkspace = workspace;
|
||||
nextProjectId = workspace.projectId;
|
||||
patch.projectId = workspace.projectId;
|
||||
}
|
||||
if (!nextProjectId && nextExecutionWorkspaceId) {
|
||||
const workspace = await assertValidExecutionWorkspace(
|
||||
existing.companyId,
|
||||
null,
|
||||
nextExecutionWorkspaceId,
|
||||
);
|
||||
validatedExecutionWorkspace = workspace;
|
||||
nextProjectId = workspace.projectId;
|
||||
patch.projectId = workspace.projectId;
|
||||
}
|
||||
if (nextProjectWorkspaceId) {
|
||||
if (!validatedProjectWorkspace) {
|
||||
await assertValidProjectWorkspace(
|
||||
existing.companyId,
|
||||
nextProjectId,
|
||||
nextProjectWorkspaceId,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (nextExecutionWorkspaceId) {
|
||||
if (!validatedExecutionWorkspace) {
|
||||
await assertValidExecutionWorkspace(
|
||||
existing.companyId,
|
||||
nextProjectId,
|
||||
nextExecutionWorkspaceId,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (nextProjectWorkspaceId) await assertValidProjectWorkspace(existing.companyId, null, nextProjectWorkspaceId);
|
||||
if (nextExecutionWorkspaceId) await assertValidExecutionWorkspace(existing.companyId, null, nextExecutionWorkspaceId);
|
||||
if (
|
||||
isolatedWorkspacesEnabled &&
|
||||
issueData.executionWorkspaceSettings !== undefined
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { PROJECT_REPOSITORIES_DIR, readGitWorkspaceSnapshot, disposeGitWorkspaceSnapshot } from "@paperclipai/adapter-utils/git-workspace-sync";
|
||||
import { captureDirectorySnapshot, disposeDirectorySnapshot, mergeDirectoryWithBaseline } from "@paperclipai/adapter-utils/workspace-restore-merge";
|
||||
import { sanitizeRuntimeServiceBaseEnv } from "./runtime-service-env.js";
|
||||
import { describeGitAuthFailure, scrubGitCredentialText, type GitRemoteAuthProvider } from "./git-credentials.js";
|
||||
import { classifyGitCloneFailure, GitConnectionFailureError, readGitConnectionFailure } from "./git-connection-failure.js";
|
||||
import { isWorkspaceGitScanError, WorkspaceGitScanError } from "./workspace-git-operation-scheduler.js";
|
||||
|
||||
const execFile = promisify(execFileCallback);
|
||||
const MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
/** Atomically publish a complete managed checkout; never delete a competing checkout. */
|
||||
export async function materializeManagedProjectWorkspace(
|
||||
cwd: string,
|
||||
input: {
|
||||
repoUrl: string | null;
|
||||
repoRef?: string | null;
|
||||
localSource?: string | null;
|
||||
resolveGitAuth?: GitRemoteAuthProvider | null;
|
||||
/** Internal preparation receipt is committed inside the clone before atomic publication. */
|
||||
beforePublish?: (cloneCwd: string) => Promise<void>;
|
||||
},
|
||||
): Promise<{ cwd: string; warning: string | null }> {
|
||||
await fs.mkdir(path.dirname(cwd), { recursive: true });
|
||||
const stats = await fs.stat(cwd).catch(() => null);
|
||||
|
||||
if (!input.repoUrl) {
|
||||
if (!stats) {
|
||||
await fs.mkdir(cwd, { recursive: true });
|
||||
}
|
||||
return { cwd, warning: null };
|
||||
}
|
||||
|
||||
const hasAdoptableGitDir = () =>
|
||||
fs
|
||||
.stat(path.resolve(cwd, ".git"))
|
||||
.then((entry) => entry.isDirectory())
|
||||
.catch(() => false);
|
||||
if (await hasAdoptableGitDir()) {
|
||||
return { cwd, warning: null };
|
||||
}
|
||||
|
||||
if (stats) {
|
||||
const entries = await fs.readdir(cwd).catch(() => []);
|
||||
if (entries.length > 0) {
|
||||
return {
|
||||
cwd,
|
||||
warning: `Managed workspace path "${cwd}" already exists but is not a git checkout. Using it as-is.`,
|
||||
};
|
||||
}
|
||||
await fs.rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
// Clone into a temp sibling, then move into place atomically. The shared target directory
|
||||
// is never created in a partial state and never removed on failure, so a concurrent
|
||||
// materialization (another process, or a run racing this one) can neither adopt a broken
|
||||
// checkout nor lose its own completed one.
|
||||
const auth = input.resolveGitAuth && !input.localSource
|
||||
? await input.resolveGitAuth(input.repoUrl)
|
||||
: null;
|
||||
const cloneTmpDir = await fs.mkdtemp(`${cwd}.clone-`);
|
||||
try {
|
||||
try {
|
||||
await execFile(
|
||||
"git",
|
||||
[...(auth?.configArgs ?? []), "clone", "--no-hardlinks", "--", input.localSource ?? input.repoUrl, cloneTmpDir],
|
||||
{
|
||||
env: {
|
||||
// Spread order matters: the sanitizer strips PAPERCLIP_*, which would remove the
|
||||
// credential-helper token env if it came first. GIT_TERMINAL_PROMPT=0 fails a
|
||||
// credential-less private clone immediately instead of hanging on a prompt until
|
||||
// the clone timeout.
|
||||
...sanitizeRuntimeServiceBaseEnv(process.env),
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
...(auth?.env ?? {}),
|
||||
},
|
||||
timeout: MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
const connectionFailure = !input.localSource ? classifyGitCloneFailure(input.repoUrl, error) : null;
|
||||
if (connectionFailure) throw new GitConnectionFailureError(
|
||||
error instanceof Error ? error.message : "Git clone failed", connectionFailure,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
if (input.localSource) {
|
||||
const snapshot = await readGitWorkspaceSnapshot(input.localSource, false);
|
||||
if (!snapshot) throw new Error("Configured repository folder is not a Git checkout");
|
||||
let baseline;
|
||||
try {
|
||||
baseline = await captureDirectorySnapshot(cloneTmpDir, { exclude: [".git", ".paperclip-runtime", PROJECT_REPOSITORIES_DIR], ignoredPaths: snapshot.ignoredPaths, diskBacked: true });
|
||||
await mergeDirectoryWithBaseline({ baseline, sourceDir: input.localSource, targetDir: cloneTmpDir });
|
||||
} finally {
|
||||
if (baseline) await disposeDirectorySnapshot(baseline);
|
||||
await disposeGitWorkspaceSnapshot(snapshot);
|
||||
}
|
||||
await execFile("git", ["-C", cloneTmpDir, "remote", "set-url", "origin", input.repoUrl], { timeout: 10_000 });
|
||||
} else if (input.repoRef) {
|
||||
await execFile("git", ["-C", cloneTmpDir, "checkout", input.repoRef], { timeout: MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS });
|
||||
}
|
||||
await input.beforePublish?.(cloneTmpDir);
|
||||
} catch (error) {
|
||||
await fs
|
||||
.rm(cloneTmpDir, { recursive: true, force: true })
|
||||
.catch(() => undefined);
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
const authNote = describeGitAuthFailure({
|
||||
error: reason,
|
||||
used: auth ? { source: auth.source, secretName: auth.secretName } : null,
|
||||
});
|
||||
const message = scrubGitCredentialText(
|
||||
`Failed to prepare managed checkout for "${input.repoUrl}" at "${cwd}": ${reason}${authNote ? ` ${authNote}` : ""}`,
|
||||
);
|
||||
// Preserve the closed failure code without copying subprocess output or
|
||||
// credentials into the durable run. Setup recovery needs the actual cause.
|
||||
if (isWorkspaceGitScanError(error)) throw new WorkspaceGitScanError(error.code, message);
|
||||
const connectionFailure = readGitConnectionFailure(error);
|
||||
if (connectionFailure) throw new GitConnectionFailureError(message, connectionFailure);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
try {
|
||||
await fs.rename(cloneTmpDir, cwd);
|
||||
} catch (renameError) {
|
||||
await fs
|
||||
.rm(cloneTmpDir, { recursive: true, force: true })
|
||||
.catch(() => undefined);
|
||||
// The target appearing between the emptiness check and the rename means another
|
||||
// materialization won the race; adopt its checkout instead of failing the run.
|
||||
if (await hasAdoptableGitDir()) {
|
||||
return { cwd, warning: null };
|
||||
}
|
||||
const reason =
|
||||
renameError instanceof Error ? renameError.message : String(renameError);
|
||||
throw new Error(
|
||||
`Failed to move managed checkout into place at "${cwd}": ${reason}`,
|
||||
);
|
||||
}
|
||||
return { cwd, warning: null };
|
||||
}
|
||||
|
||||
|
||||
/** The container is independently captured, never an accidental Git submodule.
|
||||
* A plain task root must not discover and mutate an ancestor repository. */
|
||||
export async function ensureManagedRepositoriesIgnored(cwd: string): Promise<void> {
|
||||
const gitEntry = await fs.lstat(path.join(cwd, ".git")).catch(() => null);
|
||||
if (!gitEntry) return;
|
||||
if (gitEntry.isSymbolicLink()) throw new Error("Workspace Git metadata must not be a symlink");
|
||||
const excludePath = await execFile("git", ["-C", cwd, "rev-parse", "--git-path", "info/exclude"], { timeout: 10_000 })
|
||||
.then((result) => path.resolve(cwd, result.stdout.trim()));
|
||||
const exclude = await fs.readFile(excludePath, "utf8").catch(() => "");
|
||||
if (!exclude.split(/\r?\n/).includes(`/${PROJECT_REPOSITORIES_DIR}/`)) {
|
||||
await fs.mkdir(path.dirname(excludePath), { recursive: true });
|
||||
await fs.appendFile(excludePath, `\n/${PROJECT_REPOSITORIES_DIR}/\n`);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { lstat, mkdir, realpath } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { chatConversations, issues, type Db } from "@paperclipai/db";
|
||||
import { chatConversations, issues, executionWorkspaces, projectWorkspaces, type Db } from "@paperclipai/db";
|
||||
import { resolvePaperclipInstanceRoot } from "../../home-paths.js";
|
||||
|
||||
export type NativeChatWorkspaceScope = {
|
||||
@@ -30,6 +30,8 @@ export async function findNativeChatWorkspaceScope(
|
||||
agentId: string;
|
||||
issueId: string | null;
|
||||
instanceRoot?: string;
|
||||
/** Immutable admitted input only; never a wake or prompt path. */
|
||||
admittedCwd?: string | null;
|
||||
},
|
||||
): Promise<NativeChatWorkspaceScope | null> {
|
||||
if (
|
||||
@@ -43,6 +45,19 @@ export async function findNativeChatWorkspaceScope(
|
||||
id: issues.id,
|
||||
projectId: issues.projectId,
|
||||
originKind: issues.originKind,
|
||||
selection: issues.workspaceSelection,
|
||||
configuredProjectId: projectWorkspaces.projectId,
|
||||
hasConfiguredDefault: sql<boolean>`exists (
|
||||
select 1 from ${projectWorkspaces}
|
||||
where ${projectWorkspaces.projectId} = ${issues.projectId}
|
||||
and ${projectWorkspaces.companyId} = ${input.companyId}
|
||||
and (nullif(btrim(${projectWorkspaces.cwd}), '') is not null
|
||||
or nullif(btrim(${projectWorkspaces.repoUrl}), '') is not null)
|
||||
)`,
|
||||
boundWorkspaceId: executionWorkspaces.id,
|
||||
boundProjectId: executionWorkspaces.projectId,
|
||||
boundSourceIssueId: executionWorkspaces.sourceIssueId,
|
||||
boundCwd: executionWorkspaces.cwd,
|
||||
hasConversation: sql<boolean>`exists (
|
||||
select 1 from ${chatConversations}
|
||||
where ${chatConversations.issueId} = ${issues.id}
|
||||
@@ -50,6 +65,8 @@ export async function findNativeChatWorkspaceScope(
|
||||
)`,
|
||||
})
|
||||
.from(issues)
|
||||
.leftJoin(projectWorkspaces, and(eq(projectWorkspaces.id, issues.projectWorkspaceId), eq(projectWorkspaces.companyId, input.companyId)))
|
||||
.leftJoin(executionWorkspaces, and(eq(executionWorkspaces.id, issues.executionWorkspaceId), eq(executionWorkspaces.companyId, input.companyId)))
|
||||
.where(
|
||||
and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId)),
|
||||
)
|
||||
@@ -64,23 +81,18 @@ export async function findNativeChatWorkspaceScope(
|
||||
companyId: input.companyId,
|
||||
agentId: input.agentId,
|
||||
issueId: issue.id,
|
||||
projectId: issue.projectId,
|
||||
projectId: issue.boundWorkspaceId ? issue.boundProjectId : issue.selection?.selection.kind === "task_directory" ? null : issue.configuredProjectId ?? (issue.hasConfiguredDefault ? issue.projectId : null),
|
||||
instanceRoot,
|
||||
// This must be a sibling of agent homes, not a child readable by an old
|
||||
// provider thread whose immutable permission root is the entire agent home.
|
||||
taskRoot: path.join(
|
||||
instanceRoot,
|
||||
"chat-workspaces",
|
||||
segment(input.companyId),
|
||||
segment(input.agentId),
|
||||
segment(issue.id),
|
||||
),
|
||||
taskRoot: issue.boundSourceIssueId === issue.id && issue.boundCwd
|
||||
? issue.boundCwd : input.admittedCwd ?? path.join(instanceRoot, "isolated-workspaces", segment(input.companyId), segment(issue.id)),
|
||||
};
|
||||
}
|
||||
|
||||
export type NativeChatProjectWorkspace = {
|
||||
companyId: string;
|
||||
projectId: string;
|
||||
projectId: string | null;
|
||||
sourceIssueId: string | null;
|
||||
mode: string;
|
||||
strategyType: string;
|
||||
@@ -95,7 +107,10 @@ export function nativeChatWorkspaceCwd(
|
||||
workspace: NativeChatProjectWorkspace | null,
|
||||
reuseExisting: boolean,
|
||||
): string | null {
|
||||
if (!scope.projectId) return workspace === null ? scope.taskRoot : null;
|
||||
if (!scope.projectId) return workspace === null || (
|
||||
workspace.companyId === scope.companyId && workspace.sourceIssueId === scope.issueId &&
|
||||
workspace.projectId === null && workspace.cwd === scope.taskRoot && ["active", "idle"].includes(workspace.status)
|
||||
) ? scope.taskRoot : null;
|
||||
if (
|
||||
!reuseExisting ||
|
||||
!workspace ||
|
||||
@@ -120,12 +135,13 @@ export async function materializeNativeChatTaskRoot(
|
||||
if (scope.projectId)
|
||||
throw new Error("native_chat_workspace_project_requires_isolation");
|
||||
let cursor = scope.instanceRoot;
|
||||
for (const part of [
|
||||
"chat-workspaces",
|
||||
segment(scope.companyId),
|
||||
segment(scope.agentId),
|
||||
segment(scope.issueId),
|
||||
]) {
|
||||
const relative = path.relative(scope.instanceRoot, scope.taskRoot);
|
||||
const allowedTask = path.join("isolated-workspaces", segment(scope.companyId), segment(scope.issueId));
|
||||
const legacyParts = relative.split(path.sep);
|
||||
const allowedLegacy = legacyParts.length === 4 && legacyParts[0] === "chat-workspaces" &&
|
||||
legacyParts[1] === scope.companyId && /^[a-zA-Z0-9_-]+$/.test(legacyParts[2]!) && legacyParts[3] === scope.issueId;
|
||||
if (relative !== allowedTask && !allowedLegacy) throw new Error("native_chat_workspace_path_not_isolated");
|
||||
for (const part of relative.split(path.sep)) {
|
||||
cursor = path.join(cursor, part);
|
||||
await mkdir(cursor, { mode: 0o700 }).catch(
|
||||
(error: NodeJS.ErrnoException) => {
|
||||
|
||||
@@ -80,7 +80,7 @@ describe("native runner performance trace", () => {
|
||||
});
|
||||
expect(ingress).toEqual({
|
||||
name: "question_response.to_run_created",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: answeredAtMs,
|
||||
endedAtMs: answeredAtMs + 10,
|
||||
});
|
||||
@@ -120,7 +120,7 @@ describe("native runner performance trace", () => {
|
||||
clock.mockRestore();
|
||||
}
|
||||
expect(
|
||||
events.find((event) => event.payload?.span === "task.run.measured")
|
||||
events.find((event) => event.payload?.span === "task.provider_session.measured")
|
||||
?.payload,
|
||||
).toMatchObject({ durationMs: 19_000 });
|
||||
expect(original.createdAt).toBe(new Date(1_000).toISOString());
|
||||
@@ -144,7 +144,7 @@ describe("native runner performance trace", () => {
|
||||
}),
|
||||
).toEqual({
|
||||
name: "comment.to_run_created",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: 1_000,
|
||||
endedAtMs: 3_000,
|
||||
});
|
||||
@@ -210,7 +210,7 @@ describe("native runner performance trace", () => {
|
||||
},
|
||||
});
|
||||
const prepare = trace.start("task.prepare", {
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: starts.preparationStartedAtMs,
|
||||
});
|
||||
await trace.end(prepare, { endedAtMs: attemptStartedAtMs + 50 });
|
||||
@@ -263,7 +263,7 @@ describe("native runner performance trace", () => {
|
||||
schema: "paperclip.run-performance-span.v1",
|
||||
traceSchemaVersion: NATIVE_RUN_TRACE_SCHEMA_VERSION,
|
||||
span: "runner.transport.selected",
|
||||
parentSpan: "task.run",
|
||||
parentSpan: "task.provider_session",
|
||||
startOffsetMs: 125,
|
||||
durationMs: 0,
|
||||
outcome: "ok",
|
||||
@@ -304,7 +304,7 @@ describe("native runner performance trace", () => {
|
||||
const { traceContext, spans } = createRecordingTraceContext();
|
||||
const trace = createNativeRunTrace({ runId: "skills-run", startedAtMs: 100,
|
||||
traceContext, onEvent: async () => { throw new Error("run log unavailable"); } });
|
||||
const preparation = trace.start("task.prepare", { parentName: "task.run", startedAtMs: 100 });
|
||||
const preparation = trace.start("task.prepare", { parentName: "task.provider_session", startedAtMs: 100 });
|
||||
await expect(trace.record({ name: "skills.prepare", parentName: "task.prepare", startedAtMs: 120, endedAtMs: 170 })).resolves.toBeUndefined();
|
||||
await trace.end(preparation, { endedAtMs: 200 });
|
||||
expect(spans.find((span) => span.name === "skills.prepare")).toMatchObject({ name: "skills.prepare", parentName: "task.prepare", endedAtMs: 170 });
|
||||
@@ -350,7 +350,7 @@ describe("native runner performance trace", () => {
|
||||
});
|
||||
|
||||
const prepare = trace.start("task.prepare", {
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: 1_010,
|
||||
});
|
||||
const environment = trace.start("environment.startup", {
|
||||
@@ -367,7 +367,7 @@ describe("native runner performance trace", () => {
|
||||
await trace.end(prepare, { endedAtMs: 1_040 });
|
||||
|
||||
const execute = trace.start("native.session.execute", {
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: 1_050,
|
||||
});
|
||||
const startup = trace.start("runner.session.startup", {
|
||||
@@ -417,11 +417,11 @@ describe("native runner performance trace", () => {
|
||||
|
||||
const parentOf = (name: string) =>
|
||||
spans.find((span) => span.name === name)?.parentName;
|
||||
expect(parentOf("task.run")).toBeNull();
|
||||
expect(parentOf("task.prepare")).toBe("task.run");
|
||||
expect(parentOf("task.provider_session")).toBeNull();
|
||||
expect(parentOf("task.prepare")).toBe("task.provider_session");
|
||||
expect(parentOf("environment.startup")).toBe("task.prepare");
|
||||
expect(parentOf("environment.acquire")).toBe("environment.startup");
|
||||
expect(parentOf("native.session.execute")).toBe("task.run");
|
||||
expect(parentOf("native.session.execute")).toBe("task.provider_session");
|
||||
expect(parentOf("runner.session.startup")).toBe("native.session.execute");
|
||||
expect(parentOf("runner.artifact.prepare")).toBe("runner.session.startup");
|
||||
expect(parentOf("runner.artifact.discover")).toBe(
|
||||
@@ -437,10 +437,10 @@ describe("native runner performance trace", () => {
|
||||
expect(parentOf("provider.dynamic")).toBe("agent.turn");
|
||||
expect(parentOf("provider.turn.queue")).toBe("agent.turn");
|
||||
|
||||
expect(spans.filter((span) => span.name === "task.run")).toHaveLength(1);
|
||||
expect(spans.some((span) => span.name === "task.run.measured")).toBe(false);
|
||||
expect(spans.filter((span) => span.name === "task.provider_session")).toHaveLength(1);
|
||||
expect(spans.some((span) => span.name === "task.provider_session.measured")).toBe(false);
|
||||
expect(
|
||||
events.some((event) => event.payload?.span === "task.run.measured"),
|
||||
events.some((event) => event.payload?.span === "task.provider_session.measured"),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
} from "../../instrumentation.js";
|
||||
|
||||
export const NATIVE_RUN_SPAN_EVENT_TYPE = "run.performance.span";
|
||||
export const NATIVE_RUN_TRACE_SCHEMA_VERSION = 2;
|
||||
export const NATIVE_RUN_TRACE_SCHEMA_VERSION = 3;
|
||||
|
||||
export type NativeRunSpanOutcome = "ok" | "failed";
|
||||
|
||||
@@ -41,7 +41,7 @@ export function buildNativeWakeIngressSpan(input: {
|
||||
if (answeredAt !== null && Number.isFinite(answeredAt) && answeredAt >= 0) {
|
||||
return {
|
||||
name: "question_response.to_run_created",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: answeredAt,
|
||||
endedAtMs: Math.max(answeredAt, input.runCreatedAtMs),
|
||||
};
|
||||
@@ -60,7 +60,7 @@ export function buildNativeWakeIngressSpan(input: {
|
||||
? null
|
||||
: {
|
||||
name: "comment.to_run_created",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: createdAt,
|
||||
endedAtMs: Math.max(createdAt, input.runCreatedAtMs),
|
||||
};
|
||||
@@ -77,13 +77,13 @@ export function buildNativeHeartbeatPreparationSpans(input: {
|
||||
return [
|
||||
{
|
||||
name: "heartbeat.queue",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: input.runCreatedAtMs,
|
||||
endedAtMs: Math.max(input.runCreatedAtMs, input.runStartedAtMs),
|
||||
},
|
||||
{
|
||||
name: "heartbeat.prepare_before_environment",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
// A same-run resume retains startedAt for wall-time accounting; it is
|
||||
// not the beginning of this dispatch attempt's preparation.
|
||||
startedAtMs: input.attemptStartedAtMs,
|
||||
@@ -94,7 +94,7 @@ export function buildNativeHeartbeatPreparationSpans(input: {
|
||||
},
|
||||
{
|
||||
name: "heartbeat.prepare_after_environment",
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: Math.min(
|
||||
input.nativeDispatchAtMs,
|
||||
input.environmentRealizeEndedAtMs,
|
||||
@@ -210,7 +210,7 @@ export function createNativeRunTrace(input: {
|
||||
const runIdHash = hashedId(input.runId);
|
||||
let rootSpan: SpanHandle;
|
||||
try {
|
||||
rootSpan = tracing.tracer.startSpan("task.run", {
|
||||
rootSpan = tracing.tracer.startSpan("task.provider_session", {
|
||||
startTime: traceStartedAtMs,
|
||||
attributes: {
|
||||
"paperclip.task.run.run_id": runIdHash,
|
||||
@@ -249,19 +249,19 @@ export function createNativeRunTrace(input: {
|
||||
? { name: active.name, context: active.context }
|
||||
: runtimeParentScope && !runtimeParentScope.ended
|
||||
? { name: runtimeParentScope.name, context: runtimeParentScope.context }
|
||||
: { name: "task.run", context: rootContext };
|
||||
: { name: "task.provider_session", context: rootContext };
|
||||
};
|
||||
|
||||
const parentFor = (
|
||||
parentName?: string,
|
||||
): { name: string; context: unknown } => {
|
||||
if (parentName && parentName !== "task.run") {
|
||||
if (parentName && parentName !== "task.provider_session") {
|
||||
const named = namedScopes.get(parentName);
|
||||
if (named) return { name: named.name, context: named.context };
|
||||
return currentParent();
|
||||
}
|
||||
if (parentName === "task.run")
|
||||
return { name: "task.run", context: rootContext };
|
||||
if (parentName === "task.provider_session")
|
||||
return { name: "task.provider_session", context: rootContext };
|
||||
return currentParent();
|
||||
};
|
||||
|
||||
@@ -298,7 +298,7 @@ export function createNativeRunTrace(input: {
|
||||
schema: "paperclip.run-performance-span.v1",
|
||||
traceSchemaVersion: NATIVE_RUN_TRACE_SCHEMA_VERSION,
|
||||
span: span.name,
|
||||
parentSpan: span.parentName ?? "task.run",
|
||||
parentSpan: span.parentName ?? "task.provider_session",
|
||||
startOffsetMs: startedAtMs - traceStartedAtMs,
|
||||
durationMs,
|
||||
outcome,
|
||||
@@ -508,8 +508,8 @@ export function createNativeRunTrace(input: {
|
||||
// Preserve the historical run-log record without emitting a duplicate
|
||||
// full-width child span into the OpenTelemetry waterfall.
|
||||
await emitCompletedSpanEvent({
|
||||
name: "task.run.measured",
|
||||
parentName: "task.run",
|
||||
name: "task.provider_session.measured",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: traceStartedAtMs,
|
||||
endedAtMs,
|
||||
outcome,
|
||||
@@ -541,7 +541,7 @@ export async function recordFailedSkillPreparation(input: {
|
||||
}): Promise<void> {
|
||||
try {
|
||||
const trace = createNativeRunTrace(input);
|
||||
const preparation = trace.start("task.prepare", { parentName: "task.run", startedAtMs: input.startedAtMs });
|
||||
const preparation = trace.start("task.prepare", { parentName: "task.provider_session", startedAtMs: input.startedAtMs });
|
||||
const endedAtMs = Date.now();
|
||||
await trace.record({ name: "skills.prepare", parentName: "task.prepare", startedAtMs: input.startedAtMs, endedAtMs, outcome: "failed" });
|
||||
await trace.end(preparation, { endedAtMs, outcome: "failed" });
|
||||
|
||||
@@ -5842,7 +5842,7 @@ describe("native resumed preparation timing", () => {
|
||||
const payloadFor = (span: string) =>
|
||||
events.find((event) => event.payload?.span === span)?.payload;
|
||||
expect(payloadFor("question_response.to_run_created")).toMatchObject({
|
||||
parentSpan: "task.run",
|
||||
parentSpan: "task.provider_session",
|
||||
durationMs: 50,
|
||||
startOffsetMs: 0,
|
||||
});
|
||||
@@ -5850,7 +5850,7 @@ describe("native resumed preparation timing", () => {
|
||||
durationMs: 30,
|
||||
startOffsetMs: 70,
|
||||
});
|
||||
expect(payloadFor("task.run.measured")).toMatchObject({ durationMs: 100 });
|
||||
expect(payloadFor("task.provider_session.measured")).toMatchObject({ durationMs: 100 });
|
||||
});
|
||||
|
||||
it("uses attempt-local preparation in the executor without truncating run elapsed time", async () => {
|
||||
@@ -5904,7 +5904,7 @@ describe("native resumed preparation timing", () => {
|
||||
durationMs: 1_000,
|
||||
startOffsetMs: 0,
|
||||
});
|
||||
expect(payloadFor("task.run.measured")).toMatchObject({
|
||||
expect(payloadFor("task.provider_session.measured")).toMatchObject({
|
||||
durationMs: 984_050,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7691,7 +7691,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
});
|
||||
const toolTrace = createNativeToolTrace(trace);
|
||||
const taskPrepareScope = trace.start("task.prepare", {
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: preparationStarts.preparationStartedAtMs,
|
||||
});
|
||||
const environmentSpans = preparationSpans.filter(
|
||||
@@ -7719,7 +7719,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
await trace.record({
|
||||
...span,
|
||||
parentName: rootMilestone
|
||||
? "task.run"
|
||||
? "task.provider_session"
|
||||
: environmentSpans.includes(span)
|
||||
? "environment.startup"
|
||||
: "task.prepare",
|
||||
@@ -8280,7 +8280,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
outcome,
|
||||
});
|
||||
taskSettleScope = trace.start("task.settle", {
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: milestoneAtMs,
|
||||
});
|
||||
trace.activate(taskSettleScope);
|
||||
@@ -8950,7 +8950,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
});
|
||||
return result;
|
||||
},
|
||||
{ parentName: "task.run" },
|
||||
{ parentName: "task.provider_session" },
|
||||
);
|
||||
// A detached consumer can resolve successfully after its stream closes.
|
||||
// Only the replacement controller may settle the run or certify accounting.
|
||||
@@ -9054,7 +9054,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
).slice(-4_096);
|
||||
if (!taskSettleScope) {
|
||||
taskSettleScope = trace.start("task.settle", {
|
||||
parentName: "task.run",
|
||||
parentName: "task.provider_session",
|
||||
startedAtMs: failedAtMs,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { WorkspaceCheckpointMetrics } from "@paperclipai/adapter-utils/workspace-checkpoint";
|
||||
import type { RuntimeSpanRunner } from "@paperclipai/adapter-utils/acpx-engine/startup-timing";
|
||||
import fs from "node:fs/promises";
|
||||
import { createReadStream } from "node:fs";
|
||||
import path from "node:path";
|
||||
@@ -31,8 +33,9 @@ import { parseObject } from "../../adapters/utils.js";
|
||||
import type { NativeRestartRecoveryClaim } from "./native-restart-recovery.js";
|
||||
|
||||
const LEGACY_DESCRIPTOR_SCHEMA = "paperclip.native-workspace-sync/v1";
|
||||
const DESCRIPTOR_SCHEMA = "paperclip.native-workspace-sync/v2";
|
||||
type DescriptorSchema = typeof DESCRIPTOR_SCHEMA | typeof LEGACY_DESCRIPTOR_SCHEMA;
|
||||
const PREVIOUS_DESCRIPTOR_SCHEMA = "paperclip.native-workspace-sync/v2";
|
||||
const DESCRIPTOR_SCHEMA = "paperclip.native-workspace-sync/v3";
|
||||
type DescriptorSchema = typeof DESCRIPTOR_SCHEMA | typeof PREVIOUS_DESCRIPTOR_SCHEMA | typeof LEGACY_DESCRIPTOR_SCHEMA;
|
||||
const STAMP_SCHEMA = "paperclip.native-workspace-stamp/v1";
|
||||
const STATE_ROOT_NAME = "native-workspace-sync";
|
||||
const DESCRIPTOR_NAME = "descriptor";
|
||||
@@ -61,6 +64,7 @@ interface NativeWorkspaceSyncDescriptor {
|
||||
baselineSha256: string;
|
||||
baseline: SerializedDirectorySnapshot;
|
||||
gitSnapshot: GitWorkspaceSnapshot | null;
|
||||
repositories?: NonNullable<GitWorkspaceSnapshot["repositories"]>;
|
||||
seed: {
|
||||
workspaceArchiveSha256: string;
|
||||
gitArchiveSha256: string | null;
|
||||
@@ -190,6 +194,7 @@ async function verifiedDurableSeed(input: {
|
||||
runId: string;
|
||||
seed: NonNullable<NativeWorkspaceSyncDescriptor["seed"]>;
|
||||
gitSnapshot: GitWorkspaceSnapshot | null;
|
||||
repositories?: NonNullable<GitWorkspaceSnapshot["repositories"]>;
|
||||
}): Promise<WorkspaceDurableSeedPaths> {
|
||||
try {
|
||||
const paths = durableSeedPaths(input.runId);
|
||||
@@ -203,7 +208,7 @@ async function verifiedDurableSeed(input: {
|
||||
) {
|
||||
throw new Error("workspace_sync_out_unrecoverable");
|
||||
}
|
||||
if (input.gitSnapshot) {
|
||||
if (input.gitSnapshot || input.repositories?.length) {
|
||||
const gitStat = await fs.lstat(paths.gitArchivePath);
|
||||
if (
|
||||
gitStat.isSymbolicLink() ||
|
||||
@@ -219,7 +224,7 @@ async function verifiedDurableSeed(input: {
|
||||
return {
|
||||
workspaceArchivePath: paths.workspaceArchivePath,
|
||||
workspaceArchiveSha256: input.seed.workspaceArchiveSha256,
|
||||
gitArchivePath: input.gitSnapshot ? paths.gitArchivePath : null,
|
||||
gitArchivePath: input.gitSnapshot || input.repositories?.length ? paths.gitArchivePath : null,
|
||||
gitArchiveSha256: input.seed.gitArchiveSha256,
|
||||
};
|
||||
} catch (error) {
|
||||
@@ -281,7 +286,7 @@ export function readNativeWorkspaceSyncReference(
|
||||
): NativeWorkspaceSyncReference | null {
|
||||
const candidate = parseObject(value);
|
||||
if (
|
||||
(candidate.schema !== DESCRIPTOR_SCHEMA && candidate.schema !== LEGACY_DESCRIPTOR_SCHEMA) ||
|
||||
(candidate.schema !== DESCRIPTOR_SCHEMA && candidate.schema !== PREVIOUS_DESCRIPTOR_SCHEMA && candidate.schema !== LEGACY_DESCRIPTOR_SCHEMA) ||
|
||||
(candidate.state !== "prepared" && candidate.state !== "finalized") ||
|
||||
typeof candidate.descriptorSha256 !== "string" ||
|
||||
!/^[0-9a-f]{64}$/.test(candidate.descriptorSha256) ||
|
||||
@@ -360,6 +365,7 @@ async function persistSnapshotManifests(runId: string, snapshot: NonNullable<Pre
|
||||
if (baseline.ignoredPaths && isPathManifest(baseline.ignoredPaths)) yield baseline.ignoredPaths;
|
||||
}
|
||||
yield* gitManifests(snapshot.gitSnapshot);
|
||||
for (const repo of snapshot.repositories ?? []) yield* gitManifests(repo.snapshot);
|
||||
};
|
||||
const copies = new Map<string, string>();
|
||||
for (const manifest of manifests()) {
|
||||
@@ -385,6 +391,7 @@ async function persistSnapshotManifests(runId: string, snapshot: NonNullable<Pre
|
||||
// Ownership tracks original scratch directories, never the new durable path.
|
||||
await disposeDirectorySnapshot(snapshot.baseline);
|
||||
await disposeGitWorkspaceSnapshot(snapshot.gitSnapshot);
|
||||
for (const repo of snapshot.repositories ?? []) await disposeGitWorkspaceSnapshot(repo.snapshot);
|
||||
}
|
||||
|
||||
function parseGitSnapshot(
|
||||
@@ -394,7 +401,7 @@ function parseGitSnapshot(
|
||||
if (value === null) return null;
|
||||
const candidate = parseObject(value);
|
||||
const paths = [candidate.overlayPaths, candidate.deletedPaths, candidate.ignoredPaths];
|
||||
if (typeof candidate.headCommit !== "string" || (candidate.branchName !== null && typeof candidate.branchName !== "string")
|
||||
if ((candidate.originUrl !== undefined && candidate.originUrl !== null && typeof candidate.originUrl !== "string") || typeof candidate.headCommit !== "string" || (candidate.branchName !== null && typeof candidate.branchName !== "string")
|
||||
|| !paths.every((entries) => validManifestShape(entries) || (Array.isArray(entries) && entries.every((entry) =>
|
||||
typeof entry === "string" && entry.length > 0 && !entry.includes("\0") && !path.posix.isAbsolute(entry) && !path.win32.isAbsolute(entry)
|
||||
&& !entry.split(/[\\/]/).some((segment) => segment === ".." || segment === "."))))) return undefined;
|
||||
@@ -414,6 +421,7 @@ function parseGitSnapshot(
|
||||
return {
|
||||
headCommit: candidate.headCommit,
|
||||
branchName: candidate.branchName as string | null,
|
||||
...(candidate.originUrl !== undefined ? { originUrl: candidate.originUrl as string | null } : {}),
|
||||
overlayPaths: candidate.overlayPaths as WorkspacePaths,
|
||||
deletedPaths: candidate.deletedPaths as WorkspacePaths,
|
||||
ignoredPaths: candidate.ignoredPaths as WorkspacePaths,
|
||||
@@ -464,7 +472,7 @@ async function readDescriptor(input: {
|
||||
const binding = parseObject(candidate.binding);
|
||||
const rawBaseline = parseObject(candidate.baseline);
|
||||
let baseline: DirectorySnapshot | null;
|
||||
if (candidate.schema === DESCRIPTOR_SCHEMA && rawBaseline.version === 2
|
||||
if ((candidate.schema === DESCRIPTOR_SCHEMA || candidate.schema === PREVIOUS_DESCRIPTOR_SCHEMA) && rawBaseline.version === 2
|
||||
&& Array.isArray(rawBaseline.exclude) && rawBaseline.exclude.every((entry) => typeof entry === "string")
|
||||
&& validManifestShape(rawBaseline.entries) && rawBaseline.entries.category === "baseline"
|
||||
&& (rawBaseline.ignoredPaths === undefined || validManifestShape(rawBaseline.ignoredPaths))) {
|
||||
@@ -475,6 +483,12 @@ async function readDescriptor(input: {
|
||||
baseline = parseDirectorySnapshot(candidate.baseline);
|
||||
}
|
||||
const gitSnapshot = parseGitSnapshot(candidate.gitSnapshot);
|
||||
const repositoryContainer = candidate.repositories === undefined ? null : parseGitSnapshot({
|
||||
headCommit: "", branchName: null, overlayPaths: [], deletedPaths: [], ignoredPaths: [], repositories: candidate.repositories,
|
||||
});
|
||||
if (candidate.repositories !== undefined && (!repositoryContainer || candidate.schema !== DESCRIPTOR_SCHEMA || gitSnapshot)) throw new Error("native_workspace_sync_repositories_invalid");
|
||||
const repositories = repositoryContainer?.repositories;
|
||||
for (const repo of repositories ?? []) for (const manifest of gitManifests(repo.snapshot)) await verifyManifest(input.runId, manifest);
|
||||
for (const manifest of gitManifests(gitSnapshot ?? null)) await verifyManifest(input.runId, manifest);
|
||||
const rawSeed =
|
||||
candidate.seed === null || candidate.seed === undefined
|
||||
@@ -509,7 +523,7 @@ async function readDescriptor(input: {
|
||||
? null
|
||||
: undefined;
|
||||
if (
|
||||
(candidate.schema !== DESCRIPTOR_SCHEMA && candidate.schema !== LEGACY_DESCRIPTOR_SCHEMA) ||
|
||||
(candidate.schema !== DESCRIPTOR_SCHEMA && candidate.schema !== PREVIOUS_DESCRIPTOR_SCHEMA && candidate.schema !== LEGACY_DESCRIPTOR_SCHEMA) ||
|
||||
(candidate.state !== "prepared" && candidate.state !== "finalized") ||
|
||||
!baseline ||
|
||||
gitSnapshot === undefined ||
|
||||
@@ -560,6 +574,7 @@ async function readDescriptor(input: {
|
||||
baselineSha256: candidate.baselineSha256,
|
||||
baseline: candidate.baseline as SerializedDirectorySnapshot,
|
||||
gitSnapshot,
|
||||
...(repositories?.length ? { repositories } : {}),
|
||||
seed,
|
||||
createdAt: candidate.createdAt,
|
||||
finalizedAt:
|
||||
@@ -681,6 +696,7 @@ async function remoteStampMatches(input: {
|
||||
target: Extract<AdapterExecutionTarget, { transport: "sandbox" }>;
|
||||
expected: Record<string, unknown>;
|
||||
gitSnapshot?: GitWorkspaceSnapshot | null;
|
||||
repositories?: NonNullable<GitWorkspaceSnapshot["repositories"]>;
|
||||
}): Promise<boolean> {
|
||||
if (!input.target.runner) return false;
|
||||
const stampPath = path.posix.join(
|
||||
@@ -699,11 +715,15 @@ async function remoteStampMatches(input: {
|
||||
gitChecks.push(snapshot.branchName === null
|
||||
? `(${git} symbolic-ref --quiet HEAD >/dev/null 2>&1; test $? -eq 1)`
|
||||
: `test "$(${git} symbolic-ref --quiet --short HEAD)" = ${shellQuote(snapshot.branchName)}`);
|
||||
if (snapshot.originUrl !== undefined) gitChecks.push(snapshot.originUrl === null
|
||||
? `! ${git} config --get remote.origin.url >/dev/null 2>&1`
|
||||
: `test "$(${git} config --get remote.origin.url)" = ${shellQuote(snapshot.originUrl)}`);
|
||||
for (const repository of snapshot.repositories ?? []) {
|
||||
checkGit(path.posix.join(remoteDir, repository.path), repository.snapshot);
|
||||
}
|
||||
};
|
||||
if (input.gitSnapshot) checkGit(input.target.remoteCwd, input.gitSnapshot);
|
||||
for (const repo of input.repositories ?? []) checkGit(path.posix.join(input.target.remoteCwd, repo.path), repo.snapshot);
|
||||
const result = await input.target.runner.execute({
|
||||
command: input.target.shellCommand ?? "sh",
|
||||
args: [
|
||||
@@ -767,7 +787,11 @@ async function prepareRuntime(input: {
|
||||
mode: WorkspaceInboundMode;
|
||||
baseline?: DirectorySnapshot;
|
||||
gitSnapshot?: GitWorkspaceSnapshot | null;
|
||||
repositories?: NonNullable<GitWorkspaceSnapshot["repositories"]>;
|
||||
durableSeed?: WorkspaceDurableSeedPaths;
|
||||
seedCacheDirectory?: string;
|
||||
onPhase?: RuntimeSpanRunner;
|
||||
onCheckpoint?: (metrics: WorkspaceCheckpointMetrics) => Promise<void>;
|
||||
}): Promise<PreparedAdapterExecutionTargetRuntime> {
|
||||
return prepareAdapterExecutionTargetRuntime({
|
||||
runId: input.runId,
|
||||
@@ -779,6 +803,11 @@ async function prepareRuntime(input: {
|
||||
workspaceDurableSeed: input.durableSeed,
|
||||
workspaceBaseline: input.baseline,
|
||||
workspaceGitSnapshot: input.gitSnapshot,
|
||||
workspaceRepositories: input.repositories ?? (input.baseline ? [] : undefined),
|
||||
workspaceCheckpoint: true,
|
||||
onWorkspaceCheckpoint: input.onCheckpoint,
|
||||
workspaceSeedCacheDirectory: input.seedCacheDirectory,
|
||||
runtimeSpan: input.onPhase,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -789,8 +818,11 @@ async function finalizePreparedRuntime(input: {
|
||||
runtime: PreparedAdapterExecutionTargetRuntime;
|
||||
descriptor: NativeWorkspaceSyncDescriptor;
|
||||
assertOwnership?: () => Promise<void>;
|
||||
onPhase?: RuntimeSpanRunner;
|
||||
onCheckpoint?: (metrics: WorkspaceCheckpointMetrics) => Promise<void>;
|
||||
}): Promise<NativeWorkspaceSyncReference> {
|
||||
await input.runtime.restoreWorkspace();
|
||||
if (input.onPhase) await input.onPhase("workspace.restore", () => input.runtime.restoreWorkspace());
|
||||
else await input.runtime.restoreWorkspace();
|
||||
await input.assertOwnership?.();
|
||||
const finalSnapshot =
|
||||
await import("@paperclipai/adapter-utils/workspace-restore-merge").then(
|
||||
@@ -836,6 +868,8 @@ export async function prepareNativeWorkspaceSync(input: {
|
||||
restartRecovery?: NativeRestartRecoveryClaim;
|
||||
sameRunRecovery?: boolean;
|
||||
resourceDisposition?: NativeWorkspaceResourceDisposition;
|
||||
onPhase?: RuntimeSpanRunner;
|
||||
onCheckpoint?: (metrics: WorkspaceCheckpointMetrics) => Promise<void>;
|
||||
}): Promise<PreparedNativeWorkspaceSync | null> {
|
||||
if (input.target?.kind !== "remote" || input.target.transport !== "sandbox") {
|
||||
return null;
|
||||
@@ -896,6 +930,7 @@ export async function prepareNativeWorkspaceSync(input: {
|
||||
runId: input.runId,
|
||||
seed: existing.descriptor.seed,
|
||||
gitSnapshot: existing.descriptor.gitSnapshot,
|
||||
repositories: existing.descriptor.repositories,
|
||||
})
|
||||
: (() => {
|
||||
throw new Error("workspace_sync_out_unrecoverable");
|
||||
@@ -904,10 +939,13 @@ export async function prepareNativeWorkspaceSync(input: {
|
||||
runtime = await prepareRuntime({
|
||||
runId: input.runId,
|
||||
target,
|
||||
onPhase: input.onPhase,
|
||||
onCheckpoint: input.onCheckpoint,
|
||||
workspaceLocalDir: input.workspaceLocalDir,
|
||||
mode,
|
||||
baseline: existing.baseline,
|
||||
gitSnapshot: existing.descriptor.gitSnapshot,
|
||||
repositories: existing.descriptor.repositories,
|
||||
durableSeed,
|
||||
});
|
||||
descriptor = {
|
||||
@@ -934,8 +972,11 @@ export async function prepareNativeWorkspaceSync(input: {
|
||||
runtime = await prepareRuntime({
|
||||
runId: input.runId,
|
||||
target,
|
||||
onPhase: input.onPhase,
|
||||
onCheckpoint: input.onCheckpoint,
|
||||
workspaceLocalDir: input.workspaceLocalDir,
|
||||
mode,
|
||||
seedCacheDirectory: path.join(resolvePaperclipInstanceRoot(), STATE_ROOT_NAME, "generations", requireSafeSegment(input.companyId, "company_id"), requireSafeSegment(input.workspaceId, "workspace_id")),
|
||||
durableSeed: {
|
||||
workspaceArchivePath: seedPaths.workspaceArchivePath,
|
||||
gitArchivePath: seedPaths.gitArchivePath,
|
||||
@@ -951,7 +992,7 @@ export async function prepareNativeWorkspaceSync(input: {
|
||||
);
|
||||
const verifiedWarmAdoption =
|
||||
priorStamp.hostSha256 === currentHostSha256 &&
|
||||
(await remoteStampMatches({ target, expected: priorStamp, gitSnapshot: currentSnapshot.gitSnapshot }));
|
||||
(await remoteStampMatches({ target, expected: priorStamp, gitSnapshot: currentSnapshot.gitSnapshot, repositories: currentSnapshot.repositories }));
|
||||
if (verifiedWarmAdoption) {
|
||||
mode = "adopt_remote";
|
||||
} else {
|
||||
@@ -963,6 +1004,9 @@ export async function prepareNativeWorkspaceSync(input: {
|
||||
mode,
|
||||
baseline: currentSnapshot.baseline,
|
||||
gitSnapshot: currentSnapshot.gitSnapshot,
|
||||
repositories: currentSnapshot.repositories,
|
||||
onPhase: input.onPhase,
|
||||
onCheckpoint: input.onCheckpoint,
|
||||
durableSeed: {
|
||||
workspaceArchivePath: seedPaths.workspaceArchivePath,
|
||||
gitArchivePath: seedPaths.gitArchivePath,
|
||||
@@ -977,7 +1021,7 @@ export async function prepareNativeWorkspaceSync(input: {
|
||||
const workspaceArchiveSha256 = await sha256File(
|
||||
seedPaths.workspaceArchivePath,
|
||||
);
|
||||
const gitArchiveSha256 = snapshot.gitSnapshot
|
||||
const gitArchiveSha256 = snapshot.gitSnapshot || snapshot.repositories?.length
|
||||
? await sha256File(seedPaths.gitArchivePath)
|
||||
: null;
|
||||
descriptor = {
|
||||
@@ -995,6 +1039,7 @@ export async function prepareNativeWorkspaceSync(input: {
|
||||
baselineSha256: directorySnapshotSha256(snapshot.baseline),
|
||||
baseline: serializeDirectorySnapshot(snapshot.baseline),
|
||||
gitSnapshot: snapshot.gitSnapshot,
|
||||
...(snapshot.repositories?.length ? { repositories: snapshot.repositories } : {}),
|
||||
seed: { workspaceArchiveSha256, gitArchiveSha256 },
|
||||
createdAt: now,
|
||||
finalizedAt: null,
|
||||
@@ -1021,6 +1066,8 @@ export async function prepareNativeWorkspaceSync(input: {
|
||||
runtime: preparedRuntime,
|
||||
descriptor,
|
||||
assertOwnership,
|
||||
onPhase: input.onPhase,
|
||||
onCheckpoint: input.onCheckpoint,
|
||||
})
|
||||
.then((finalizedReference) => {
|
||||
reference = finalizedReference;
|
||||
@@ -1046,6 +1093,8 @@ export async function resumeNativeWorkspaceSync(input: {
|
||||
runId: string;
|
||||
target: AdapterExecutionTarget;
|
||||
assertOwnership?: () => Promise<void>;
|
||||
onPhase?: RuntimeSpanRunner;
|
||||
onCheckpoint?: (metrics: WorkspaceCheckpointMetrics) => Promise<void>;
|
||||
}): Promise<boolean> {
|
||||
if (input.target.kind !== "remote" || input.target.transport !== "sandbox") {
|
||||
throw new Error("workspace_sync_out_unrecoverable");
|
||||
@@ -1094,10 +1143,13 @@ export async function resumeNativeWorkspaceSync(input: {
|
||||
const runtime = await prepareRuntime({
|
||||
runId: input.runId,
|
||||
target: input.target,
|
||||
onPhase: input.onPhase,
|
||||
onCheckpoint: input.onCheckpoint,
|
||||
workspaceLocalDir: existing.descriptor.binding.localCwd,
|
||||
mode: "adopt_remote",
|
||||
baseline: existing.baseline,
|
||||
gitSnapshot: existing.descriptor.gitSnapshot,
|
||||
repositories: existing.descriptor.repositories,
|
||||
});
|
||||
await finalizePreparedRuntime({
|
||||
db: input.db,
|
||||
@@ -1106,6 +1158,8 @@ export async function resumeNativeWorkspaceSync(input: {
|
||||
runtime,
|
||||
descriptor: existing.descriptor,
|
||||
assertOwnership: input.assertOwnership,
|
||||
onPhase: input.onPhase,
|
||||
onCheckpoint: input.onCheckpoint,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { callTaskWorkspaceTool } from "../task-workspace-tools.js";
|
||||
import { TaskAttachmentReadCache, TASK_ATTACHMENT_DEFINITIONS, TASK_ATTACHMENT_SCHEMAS, listTaskAttachments, readTaskAttachment } from "./runner-task-attachments.js";
|
||||
import { RUNNER_BRIDGE_SCHEMAS, runnerBridgeDefinitions, readAssignedSkill, executeWorkspaceTool, readWorkspaceUploadFile, settleRunnerBridgeRead, assertRunnerWorkspacePathAllowed } from "./runner-bridge-tools.js";
|
||||
import type { NativeRuntimeContextSnapshot } from "../../vendor/paperclip-runner/index.js";
|
||||
@@ -110,7 +111,7 @@ const IMPLEMENTED_OPERATIONS = new Set([
|
||||
"search_api", "call_api", "hire_agent",
|
||||
"get_task_context", "get_task_history", "search_tasks", "report_progress", "set_task_title", "set_task_monitor",
|
||||
"request_human_input",
|
||||
"create_skill", "update_skill", "create_task", "reassign_task", "set_dependencies", "create_project", "list_project_repositories", "list_projects", "register_deliverable",
|
||||
"get_workspace", "list_workspaces", "select_workspace", "prepare_repository", "create_skill", "update_skill", "create_task", "reassign_task", "set_dependencies", "create_project", "list_project_repositories", "list_projects", "register_deliverable",
|
||||
"list_documents", "read_document", "list_document_revisions", "write_document",
|
||||
"list_agents", "get_agent", "list_approvals", "get_approval", "get_approval_context",
|
||||
]);
|
||||
@@ -507,6 +508,15 @@ export class PaperclipRunnerToolAuthority {
|
||||
if (!apiUrl || !token) throw new Error("Skill tool authentication is unavailable");
|
||||
return callUpdateSkillTool({ arguments: input, apiUrl, token, companyId: this.binding.companyId });
|
||||
}
|
||||
case "get_workspace":
|
||||
case "list_workspaces":
|
||||
case "select_workspace":
|
||||
case "prepare_repository": {
|
||||
const apiUrl = this.binding.apiUrl ?? process.env.PAPERCLIP_API_URL;
|
||||
const token = createLocalAgentJwt(this.binding.agentId, this.binding.companyId, context.actor.adapterType, this.binding.runId, context.run.responsibleUserId);
|
||||
if (!apiUrl || !token) throw new Error("Workspace tool authentication is unavailable");
|
||||
return callTaskWorkspaceTool({ name: call.tool, arguments: input, apiUrl, token, companyId: this.binding.companyId, issueId: this.binding.issueId, workspaceRoot: this.binding.workspaceRoot });
|
||||
}
|
||||
case "create_project":
|
||||
case "list_project_repositories":
|
||||
case "list_projects": {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { and, asc, desc, eq, gt, inArray, isNull, or, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
projects,
|
||||
executionWorkspaces,
|
||||
projectAccessMembers,
|
||||
projectGoals,
|
||||
goals,
|
||||
@@ -30,7 +31,7 @@ import {
|
||||
type PluginManagedProjectDeclaration,
|
||||
type PluginManagedProjectResolution,
|
||||
} from "@paperclipai/shared";
|
||||
import { unprocessable } from "../errors.js";
|
||||
import { conflict, unprocessable } from "../errors.js";
|
||||
import { listCurrentRuntimeServicesForProjectWorkspaces } from "./workspace-runtime-read-model.js";
|
||||
import { parseProjectExecutionWorkspacePolicy } from "./execution-workspace-policy.js";
|
||||
import { mergeProjectWorkspaceRuntimeConfig, readProjectWorkspaceRuntimeConfig } from "./project-workspace-runtime-config.js";
|
||||
@@ -1054,16 +1055,13 @@ export function projectService(db: Db, options: { captureWorkspaceUpdates?: bool
|
||||
return cleared;
|
||||
},
|
||||
|
||||
remove: (id: string) =>
|
||||
db
|
||||
.delete(projects)
|
||||
.where(eq(projects.id, id))
|
||||
.returning()
|
||||
.then((rows) => {
|
||||
const row = rows[0] ?? null;
|
||||
if (!row) return null;
|
||||
return { ...row, urlKey: deriveProjectUrlKey(row.name, row.id) };
|
||||
}),
|
||||
remove: async (id: string) => {
|
||||
const [retained] = await db.select({ id: executionWorkspaces.id }).from(executionWorkspaces)
|
||||
.where(eq(executionWorkspaces.projectId, id)).limit(1);
|
||||
if (retained) throw conflict("This project still supplies access policy for retained task workspaces. Archive the project or explicitly clean up its workspaces before deleting it.");
|
||||
const [row] = await db.delete(projects).where(eq(projects.id, id)).returning();
|
||||
return row ? { ...row, urlKey: deriveProjectUrlKey(row.name, row.id) } : null;
|
||||
},
|
||||
|
||||
listWorkspaces: async (projectId: string): Promise<ProjectWorkspace[]> => {
|
||||
const rows = await db
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
export function sanitizeRuntimeServiceBaseEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = { ...baseEnv };
|
||||
for (const key of Object.keys(env)) {
|
||||
if (key.startsWith("PAPERCLIP_")) {
|
||||
delete env[key];
|
||||
}
|
||||
}
|
||||
// These origin settings belong to the parent instance. Letting them leak into a
|
||||
// managed worktree runtime can send auth cookies and OAuth callbacks to the wrong
|
||||
// Paperclip instance. Runtime/service overrides are merged back after sanitizing.
|
||||
delete env.BETTER_AUTH_URL;
|
||||
delete env.BETTER_AUTH_BASE_URL;
|
||||
delete env.DATABASE_URL;
|
||||
delete env.npm_config_tailscale_auth;
|
||||
delete env.npm_config_authenticated_private;
|
||||
return env;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { prepareWorkspaceRepositorySchema, selectTaskWorkspaceSchema } from "@paperclipai/shared";
|
||||
import { badRequest } from "../errors.js";
|
||||
|
||||
function repositoryView(repo: Record<string, unknown>) {
|
||||
return { id: repo.id, repoUrl: repo.repoUrl, relativePath: repo.relativePath, requestedRef: repo.requestedRef,
|
||||
state: repo.state, pinnedCommit: repo.pinnedCommit, branchName: repo.branchName };
|
||||
}
|
||||
|
||||
/** Transport only: authorization, receipts, and workspace decisions remain in ordinary APIs. */
|
||||
export async function callTaskWorkspaceTool(input: { name: string; arguments: Record<string, unknown>; apiUrl: string; token: string; companyId: string; issueId: string; workspaceRoot?: string }) {
|
||||
let route = `/issues/${input.issueId}/workspace`;
|
||||
let method = "GET";
|
||||
let body: unknown;
|
||||
switch (input.name) {
|
||||
case "get_workspace": break;
|
||||
case "list_workspaces": route = `/companies/${input.companyId}/execution-workspaces?summary=true&reuseEligible=true`; break;
|
||||
case "select_workspace": method = "PUT"; body = selectTaskWorkspaceSchema.parse(input.arguments); break;
|
||||
case "prepare_repository": method = "POST"; route += "/repositories"; body = prepareWorkspaceRepositorySchema.parse(input.arguments); break;
|
||||
default: throw badRequest("Unknown workspace tool");
|
||||
}
|
||||
const response = await fetch(`${input.apiUrl.replace(/\/+$/, "").replace(/\/api$/, "")}/api${route}`, { method, headers: { Authorization: `Bearer ${input.token}`, "Content-Type": "application/json" }, ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(60_000) });
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(typeof result.error === "string" ? result.error : `Workspace tool failed (${response.status})`);
|
||||
if (input.name === "prepare_repository") {
|
||||
const { operationId, ...rest } = result;
|
||||
// PRP reserves operationId for the semantic operation name.
|
||||
return { ...rest, ...(result.repository ? { repository: repositoryView(result.repository) } : {}), preparationId: operationId };
|
||||
}
|
||||
if (input.name === "get_workspace") {
|
||||
const workspace = result.workspace;
|
||||
return { issueId: result.issueId, bindingRevision: result.bindingRevision, selection: result.selection,
|
||||
pendingSelection: result.pendingSelection, cwd: input.workspaceRoot ?? null,
|
||||
workspace: workspace ? { id: workspace.id, projectId: workspace.projectId, mode: workspace.mode, status: workspace.status } : null,
|
||||
repositories: (result.repositories ?? []).map(repositoryView),
|
||||
capabilities: result.capabilities, fileLocations: result.fileLocations };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1094,7 +1094,7 @@ export function workspaceFileResourceService(db: Db, actor?: AuthorizationActor)
|
||||
if (explicitTarget) return [explicitTarget];
|
||||
|
||||
const candidates: WorkspaceCandidate[] = [];
|
||||
if ((selector === "auto" || selector === "execution") && issue.projectId) {
|
||||
if (selector === "auto" || selector === "execution") {
|
||||
const executionIds = [issue.executionWorkspaceId].filter((id): id is string => Boolean(id));
|
||||
let executionRows: ExecutionWorkspaceRow[] = [];
|
||||
if (executionIds.length > 0) {
|
||||
@@ -1110,7 +1110,6 @@ export function workspaceFileResourceService(db: Db, actor?: AuthorizationActor)
|
||||
const activeRows = await db.select().from(executionWorkspaces).where(
|
||||
and(
|
||||
eq(executionWorkspaces.companyId, issue.companyId),
|
||||
eq(executionWorkspaces.projectId, issue.projectId),
|
||||
inArray(executionWorkspaces.sourceIssueId, sourceIssueIds),
|
||||
eq(executionWorkspaces.status, "active"),
|
||||
isNull(executionWorkspaces.closedAt),
|
||||
@@ -1126,24 +1125,23 @@ export function workspaceFileResourceService(db: Db, actor?: AuthorizationActor)
|
||||
}
|
||||
}
|
||||
|
||||
if ((selector === "auto" || selector === "project") && issue.projectId) {
|
||||
if ((selector === "auto" || selector === "project") && (issue.projectId || issue.projectWorkspaceId)) {
|
||||
if (issue.projectWorkspaceId) {
|
||||
const rows = await db.select().from(projectWorkspaces).where(
|
||||
and(
|
||||
eq(projectWorkspaces.companyId, issue.companyId),
|
||||
eq(projectWorkspaces.projectId, issue.projectId),
|
||||
eq(projectWorkspaces.id, issue.projectWorkspaceId),
|
||||
),
|
||||
).limit(1);
|
||||
if (rows[0]) candidates.push(candidateFromProjectWorkspace(rows[0]));
|
||||
}
|
||||
const primaryRows = await db.select().from(projectWorkspaces).where(
|
||||
const primaryRows = issue.projectId ? await db.select().from(projectWorkspaces).where(
|
||||
and(
|
||||
eq(projectWorkspaces.companyId, issue.companyId),
|
||||
eq(projectWorkspaces.projectId, issue.projectId),
|
||||
eq(projectWorkspaces.isPrimary, true),
|
||||
),
|
||||
).limit(1);
|
||||
).limit(1) : [];
|
||||
if (primaryRows[0] && !candidates.some((candidate) => candidate.workspaceId === primaryRows[0]!.id)) {
|
||||
candidates.push(candidateFromProjectWorkspace(primaryRows[0]));
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { sanitizeRuntimeServiceBaseEnv } from "./runtime-service-env.js";
|
||||
export { sanitizeRuntimeServiceBaseEnv } from "./runtime-service-env.js";
|
||||
import { execFile, spawn, type ChildProcess } from "node:child_process";
|
||||
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
|
||||
import fs from "node:fs/promises";
|
||||
@@ -681,23 +683,6 @@ export async function ensureServerWorkspaceLinksCurrent(
|
||||
);
|
||||
}
|
||||
|
||||
export function sanitizeRuntimeServiceBaseEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = { ...baseEnv };
|
||||
for (const key of Object.keys(env)) {
|
||||
if (key.startsWith("PAPERCLIP_")) {
|
||||
delete env[key];
|
||||
}
|
||||
}
|
||||
// These origin settings belong to the parent instance. Letting them leak into a
|
||||
// managed worktree runtime can send auth cookies and OAuth callbacks to the wrong
|
||||
// Paperclip instance. Runtime/service overrides are merged back after sanitizing.
|
||||
delete env.BETTER_AUTH_URL;
|
||||
delete env.BETTER_AUTH_BASE_URL;
|
||||
delete env.DATABASE_URL;
|
||||
delete env.npm_config_tailscale_auth;
|
||||
delete env.npm_config_authenticated_private;
|
||||
return env;
|
||||
}
|
||||
|
||||
function stableRuntimeServiceId(input: {
|
||||
adapterType: string;
|
||||
@@ -3781,8 +3766,8 @@ export async function ensurePersistedExecutionWorkspaceAvailable(input: {
|
||||
const realized: RealizedExecutionWorkspace = {
|
||||
baseCwd: input.base.baseCwd,
|
||||
source: input.workspace.mode === "shared_workspace" ? "project_primary" : "task_session",
|
||||
projectId: input.workspace.projectId ?? input.base.projectId,
|
||||
workspaceId: input.workspace.projectWorkspaceId ?? input.base.workspaceId,
|
||||
projectId: input.workspace.projectId === undefined ? input.base.projectId : input.workspace.projectId,
|
||||
workspaceId: input.workspace.projectWorkspaceId === undefined ? input.base.workspaceId : input.workspace.projectWorkspaceId,
|
||||
repoUrl: input.workspace.repoUrl ?? input.base.repoUrl,
|
||||
repoRef: input.workspace.baseRef ?? input.base.repoRef,
|
||||
additionalWorkspaces: input.base.additionalWorkspaces ?? [],
|
||||
|
||||
Reference in new issue
Block a user