Realize persistent personal homes before remote execution setup

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-10 08:50:21 -05:00
1 parent 2d7eddd175
commit f4f085b83d
4 files changed
+79 -6

No files matched your search

@@ -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")]]);
+27
View File
@@ -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<string | null> {
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<T>(companyId: string, agentId: string, actor: AuthorizationActor, write: boolean,
fn: (tx: Tx, agent: Agent, root: string, bound: AuthorizationActor, remote: Awaited<ReturnType<typeof persistentAgentFiles>>) => Promise<T>) {