diff --git a/packages/adapters/claude-local/src/server/execute.remote.test.ts b/packages/adapters/claude-local/src/server/execute.remote.test.ts index 8295829e54c..58118a838e6 100644 --- a/packages/adapters/claude-local/src/server/execute.remote.test.ts +++ b/packages/adapters/claude-local/src/server/execute.remote.test.ts @@ -238,8 +238,8 @@ describe("claude remote execution", () => { runId: "run-in-place", agent: { id: "agent-1", companyId: "company-1", name: "Claude", adapterType: "claude_local", adapterConfig: {} }, runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null }, - config: { engine: "cli", command: "claude" }, - context: { paperclipWorkspace: { cwd: rootDir, source: "task_session" } }, + config: { engine: "cli", command: "claude", cwd: "/stale-host-cwd" }, + context: { paperclipWorkspace: { cwd: "/remote-only-agent-home", source: "agent_home" } }, executionTarget: { kind: "remote", transport: "ssh", remoteCwd: "/old-copied-workspace", workspaceRealization: { mode: "in_place", authoritativeRoot: "/persistent-project", pathAliases: [], outboundRestorePaths: [] }, diff --git a/packages/adapters/claude-local/src/server/execute.ts b/packages/adapters/claude-local/src/server/execute.ts index b32c8535648..53b3baf0453 100644 --- a/packages/adapters/claude-local/src/server/execute.ts +++ b/packages/adapters/claude-local/src/server/execute.ts @@ -206,7 +206,9 @@ async function buildClaudeRuntimeConfig(input: ClaudeExecutionInput): Promise 0; - const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; + const effectiveWorkspaceCwd = executionTarget?.workspaceRealization?.mode === "in_place" + ? executionTarget.workspaceRealization.authoritativeRoot + : useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); const executionTargetIsRemote = adapterExecutionTargetIsRemote(executionTarget); let effectiveExecutionCwd = adapterExecutionTargetRemoteCwd(executionTarget, cwd); @@ -217,7 +219,9 @@ async function buildClaudeRuntimeConfig(input: ClaudeExecutionInput): Promise = { ...buildPaperclipEnv(agent, input.agentIdentity) }; @@ -454,7 +458,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise 0; - const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; + const effectiveWorkspaceCwd = executionTarget?.workspaceRealization?.mode === "in_place" + ? executionTarget.workspaceRealization.authoritativeRoot + : useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; const hasExplicitClaudeConfigDir = typeof configEnv.CLAUDE_CONFIG_DIR === "string" && configEnv.CLAUDE_CONFIG_DIR.trim().length > 0; const instructionsFilePath = asString(config.instructionsFilePath, "").trim(); diff --git a/server/src/__tests__/agent-directory-working-copies.test.ts b/server/src/__tests__/agent-directory-working-copies.test.ts index c21e51da6d5..468f3f9ee5e 100644 --- a/server/src/__tests__/agent-directory-working-copies.test.ts +++ b/server/src/__tests__/agent-directory-working-copies.test.ts @@ -10,7 +10,7 @@ import path from "node:path"; import { createHash, randomUUID } from "node:crypto"; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { eq } from "drizzle-orm"; -import { agentFileStore, fileHash, inspectAgentFile, snapshotAgentFiles, MAX_AGENT_FILE_BYTES, MAX_AGENT_DIRECTORY_BYTES, MAX_AGENT_DIRECTORY_ENTRIES } from "../services/agent-file-store.js"; +import { agentFileStore, preparePersistentAgentExecutionHome, fileHash, inspectAgentFile, snapshotAgentFiles, MAX_AGENT_FILE_BYTES, MAX_AGENT_DIRECTORY_BYTES, MAX_AGENT_DIRECTORY_ENTRIES } from "../services/agent-file-store.js"; import { agents, companies, authUsers, companyMemberships, principalPermissionGrants, heartbeatRuns, environmentLeases, environments, agentInstructionWorkingCopies, agentInstructionRevisions, agentInstructionHeads, createDb } from "@paperclipai/db"; import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { agentInstructionRevisionService } from "../services/agent-instruction-revisions.js"; @@ -75,6 +75,46 @@ describe("persistent agent directories", () => { await fs.writeFile(path.join(root, entryFile), initial); }); + it("seeds a persistent execution home before a run or instruction-copy receipt exists", async () => { + const remoteRoot = "/home/user/paperclip/test/agents/target"; + let exists = false; + const seedBytes = vi.fn(async () => { exists = true; }); + const remote = { root: remoteRoot, list: async () => { + if (!exists) throw { code: "not_found" }; + return []; + }, seedBytes }; + const lookup = vi.spyOn(persistentFiles, "persistentAgentFiles").mockResolvedValue(remote as never); + const environmentId = randomUUID(); + const executionTarget = { kind: "remote", transport: "computer", environmentId, + fileAuthority: { kind: "remote-persistent", agentHome: remoteRoot } } as never; + try { + await fs.writeFile(path.join(root, "memory.bin"), Buffer.from([0, 255, 7])); + expect(await preparePersistentAgentExecutionHome(db, { companyId, agentId, target: executionTarget })).toBe(remoteRoot); + expect(lookup).toHaveBeenCalledWith(db, companyId, agentId, environmentId); + expect(seedBytes).toHaveBeenCalledOnce(); + expect(seedBytes).toHaveBeenCalledWith(expect.objectContaining({ + [entryFile]: Buffer.from(initial), "memory.bin": Buffer.from([0, 255, 7]), + })); + // Subsequent setup adopts the remote tree, regardless of controller edits. + await fs.writeFile(path.join(root, "memory.bin"), "stale controller bytes"); + await preparePersistentAgentExecutionHome(db, { companyId, agentId, target: executionTarget }); + expect(seedBytes).toHaveBeenCalledOnce(); + expect(await db.select().from(agentInstructionWorkingCopies).where(eq(agentInstructionWorkingCopies.agentId, agentId))).toEqual([]); + } finally { lookup.mockRestore(); } + }); + + it("creates an external-instruction agent home without importing the external path", async () => { + await db.update(agents).set({ adapterConfig: { instructionsBundleMode: "external", instructionsFilePath: "/private/external.md" } }).where(eq(agents.id, agentId)); + const remote = { root: "/home/user/agents/external", seedBytes: vi.fn(async () => ({ seeded: true })) }; + const lookup = vi.spyOn(persistentFiles, "persistentAgentFiles").mockResolvedValue(remote as never); + try { + const executionTarget = { kind: "remote", transport: "computer", environmentId: randomUUID(), + fileAuthority: { kind: "remote-persistent", agentHome: remote.root } } as never; + await preparePersistentAgentExecutionHome(db, { companyId, agentId, target: executionTarget }); + expect(remote.seedBytes).toHaveBeenCalledWith({}); + } finally { lookup.mockRestore(); } + }); + it("keeps Boat personal bytes authoritative through warm checkpoints, collection, and editor conflicts", async () => { const remoteRoot = "/home/user/paperclip/test/agents/target"; const remoteFiles = new Map([[entryFile, Buffer.from("remote instructions")], ["memory.txt", Buffer.from("remote memory")]]); diff --git a/server/src/services/agent-file-store.ts b/server/src/services/agent-file-store.ts index 60479177832..4d0a3b7ae57 100644 --- a/server/src/services/agent-file-store.ts +++ b/server/src/services/agent-file-store.ts @@ -1,4 +1,5 @@ import { persistentAgentFiles, readPersistentAgentFile, seedPersistentAgentHome } from "./persistent-agent-files.js"; +import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target"; import { createHash } from "node:crypto"; import fs from "node:fs/promises"; import { cachedAgentFileManifest, checkpointSnapshot, type AgentFileManifest } from "./agent-file-checkpoints.js"; @@ -162,6 +163,32 @@ export async function snapshotAgentFiles(root: string, enforceLimits = true): Pr return (await inspectAgentDirectory(root, enforceLimits)).snapshot; } +/** Realize personal authority before any remote command needs it as cwd. + * This is runtime setup, not a working-copy checkout: no run receipt or copyback + * is created, and an existing remote home is always adopted untouched. */ +export async function preparePersistentAgentExecutionHome(db: Db, input: { + companyId: string; agentId: string; target?: AdapterExecutionTarget | null; +}): Promise { + const target = input.target; + if (target?.kind !== "remote" || target.transport !== "computer") return null; + if (!target.environmentId) throw conflict("Persistent agent environment is missing"); + return db.transaction(async tx => { + const [agent] = await tx.select().from(agents) + .where(and(eq(agents.companyId, input.companyId), eq(agents.id, input.agentId))).for("update"); + if (!agent) throw notFound("Agent not found"); + const remote = await persistentAgentFiles(db, input.companyId, input.agentId, target.environmentId!); + if (!remote || remote.root !== target.fileAuthority.agentHome) throw conflict("Persistent agent placement changed"); + if (agentInstructionsBundleMode(agent) === "managed") { + await seedPersistentAgentHome(remote, await adoptAgentFiles(tx, agent)); + } else { + // An external instruction path is not an authority for personal files. + // The seed primitive atomically creates an absent home or adopts it. + await remote.seedBytes({}); + } + return remote.root; + }); +} + export function agentFileStore(db: Db) { async function locked(companyId: string, agentId: string, actor: AuthorizationActor, write: boolean, fn: (tx: Tx, agent: Agent, root: string, bound: AuthorizationActor, remote: Awaited>) => Promise) {