mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 02:30:43 +01:00
fix(runner): persist warm Daytona workspaces (#12901)
## Thinking Path > - Paperclip manages AI agent work and the execution state for each task. > - Remote agents run in sandbox environments such as Daytona. > - Daytona keeps files while a sandbox is stopped, but deletion removes those files. > - Runner Codex did not copy successful remote workspace changes back to the host workspace. > - A warm sandbox could therefore hide data loss until Daytona replaced or deleted the sandbox. > - This pull request makes the host workspace durable after every successful turn and keeps verified reusable sandboxes warm. > - The benefit is reliable multi-turn work across warm reuse, restart, stop, and sandbox replacement. ## Linked Issues or Issue Description **What happened?** A successful native Codex turn in Daytona could leave workspace changes only in the remote sandbox. A later warm turn appeared to work because it reused that filesystem. A replacement sandbox could start from stale host data and lose the successful changes. **Expected behavior** Paperclip must merge each successful remote turn into the authoritative host workspace before it completes the run. A verified warm lease may reuse its remote files. A replacement lease must reconstruct the exact durable workspace seed. **Steps to reproduce** 1. Run Codex in a reusable Daytona environment. 2. Write a file during one successful turn. 3. Replace the Daytona sandbox before the next turn. 4. Observe that the next turn can start without the prior file on the unpatched code. Related remote workspace foundation: #10070. ## What Changed - Added explicit `host_current`, `durable_seed`, and `adopt_remote` workspace preparation modes. - Added atomic, versioned native workspace descriptors and seed archives under `PAPERCLIP_HOME`. - Added real native sandbox export and three-way host merge before terminal result completion. - Added workspace-only recovery after a proposed result. Recovery does not submit another provider turn or consume the provider retry budget. - Added fail-closed handling when a sandbox with unexported changes is gone. - Kept healthy reusable Daytona sandboxes started for legacy Codex and Runner Codex. - Kept the Runner Codex process and provider session across verified warm turns. - Added the paid `daytona-warm-continuity` browser suite. It contains exactly the legacy Codex and Runner Codex cells. Each cell performs three measured turns. - Documented `pnpm test:e2e:runner -- --suite daytona-warm-continuity`. No package script was added. - Added no database migration. The metadata format is backward compatible and idempotent. ## Verification - `pnpm typecheck` - `pnpm test:e2e:runner:unit` — 114 passed - Native workspace, finalizer, session, and environment tests — 232 passed - Daytona provider tests — 150 passed - Workspace staging and merge tests — 98 passed - Runner transport tests — 63 passed - Legacy Codex restore tests — 5 passed - Rust format and compile checks pass through root typecheck - The paid Daytona suite was not run locally because the required Daytona, OpenAI, and immutable image credentials are not present. ## Risks - The main risk is an incorrect workspace identity or merge after a crash. Durable descriptors bind the run, workspace, lease, provider lease, local root, remote root, and baseline digest. Ambiguous evidence fails closed. - The host merge may conflict with concurrent host edits. The existing three-way merge and exclusion rules handle this case and surface failures. - A deleted sandbox cannot recover unexported bytes. Paperclip now blocks with `workspace_sync_out_unrecoverable` instead of reporting success or rerunning the provider. - There is no database migration. Descriptor writes and recovery are atomic and idempotent. ## Model Used OpenAI Codex with GPT-5. The run used agentic reasoning, repository inspection, code execution, test execution, Git, and GitHub CLI tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
1 parent
be407f3456
commit
1dceee9a4e
47 files changed
+4296
-359
No files matched your search
@@ -12,11 +12,15 @@ import {
|
||||
type SandboxRemoteExecutionSpec,
|
||||
type SandboxSyncOperation,
|
||||
type SandboxSyncResult,
|
||||
type WorkspaceDurableSeedPaths,
|
||||
type WorkspaceInboundMode,
|
||||
} from "./sandbox-managed-runtime.js";
|
||||
import { preferredShellForSandbox, shellCommandArgs } from "./sandbox-shell.js";
|
||||
import type { RunProcessResult } from "./server-utils.js";
|
||||
import type { RuntimeProgressSink, RuntimeStatusSink } from "./runtime-progress.js";
|
||||
import type { RuntimeSpanRunner } from "./acpx-engine/startup-timing.js";
|
||||
import type { GitWorkspaceSnapshot } from "./git-workspace-sync.js";
|
||||
import type { DirectorySnapshot } from "./workspace-restore-merge.js";
|
||||
|
||||
/**
|
||||
* Input for a duplex channel open. The caller supplies only the command argument
|
||||
@@ -516,6 +520,10 @@ export async function prepareCommandManagedRuntime(input: {
|
||||
workspaceLocalDir: string;
|
||||
workspaceRemoteDir?: string;
|
||||
syncWorkspace?: boolean;
|
||||
workspaceInboundMode?: WorkspaceInboundMode;
|
||||
workspaceDurableSeed?: WorkspaceDurableSeedPaths;
|
||||
workspaceBaseline?: DirectorySnapshot;
|
||||
workspaceGitSnapshot?: GitWorkspaceSnapshot | null;
|
||||
workspaceExclude?: string[];
|
||||
preserveAbsentOnRestore?: string[];
|
||||
assets?: CommandManagedRuntimeAsset[];
|
||||
@@ -577,6 +585,10 @@ export async function prepareCommandManagedRuntime(input: {
|
||||
workspaceLocalDir: input.workspaceLocalDir,
|
||||
workspaceRemoteDir,
|
||||
syncWorkspace: input.syncWorkspace,
|
||||
workspaceInboundMode: input.workspaceInboundMode,
|
||||
workspaceDurableSeed: input.workspaceDurableSeed,
|
||||
workspaceBaseline: input.workspaceBaseline,
|
||||
workspaceGitSnapshot: input.workspaceGitSnapshot,
|
||||
workspaceExclude: mergeRuntimeExcludes(input.workspaceExclude),
|
||||
preserveAbsentOnRestore: input.preserveAbsentOnRestore,
|
||||
assets: input.assets,
|
||||
@@ -616,6 +628,10 @@ export async function prepareCommandManagedRuntime(input: {
|
||||
workspaceLocalDir: input.workspaceLocalDir,
|
||||
workspaceRemoteDir,
|
||||
syncWorkspace: input.syncWorkspace,
|
||||
workspaceInboundMode: input.workspaceInboundMode,
|
||||
workspaceDurableSeed: input.workspaceDurableSeed,
|
||||
workspaceBaseline: input.workspaceBaseline,
|
||||
workspaceGitSnapshot: input.workspaceGitSnapshot,
|
||||
workspaceExclude: mergeRuntimeExcludes(input.workspaceExclude),
|
||||
preserveAbsentOnRestore: input.preserveAbsentOnRestore,
|
||||
assets: input.assets,
|
||||
|
||||
@@ -18,10 +18,12 @@ import {
|
||||
import type {
|
||||
AdditionalSourceStagingFailure,
|
||||
SandboxAdditionalSource,
|
||||
WorkspaceDurableSeedPaths,
|
||||
WorkspaceInboundMode,
|
||||
} from "./sandbox-managed-runtime.js";
|
||||
export {
|
||||
resolveReferencedSourceIgnore,
|
||||
} from "./sandbox-managed-runtime.js";
|
||||
import type { GitWorkspaceSnapshot } from "./git-workspace-sync.js";
|
||||
import type { DirectorySnapshot } from "./workspace-restore-merge.js";
|
||||
export { resolveReferencedSourceIgnore } from "./sandbox-managed-runtime.js";
|
||||
export type {
|
||||
AdditionalSourceStagingFailure,
|
||||
ReferencedSourceIgnoreResolution,
|
||||
@@ -249,6 +251,10 @@ export interface PreparedAdapterExecutionTargetRuntime {
|
||||
* stage referenced projects, or when every requested project staged.
|
||||
*/
|
||||
additionalSourceFailures: AdditionalSourceStagingFailure[];
|
||||
workspaceSyncSnapshot: {
|
||||
baseline: DirectorySnapshot;
|
||||
gitSnapshot: GitWorkspaceSnapshot | null;
|
||||
} | null;
|
||||
restoreWorkspace(onProgress?: RuntimeProgressSink): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -1374,6 +1380,10 @@ export async function prepareAdapterExecutionTargetRuntime(input: {
|
||||
timeoutSec?: number;
|
||||
workspaceRemoteDir?: string;
|
||||
syncWorkspace?: boolean;
|
||||
workspaceInboundMode?: WorkspaceInboundMode;
|
||||
workspaceDurableSeed?: WorkspaceDurableSeedPaths;
|
||||
workspaceBaseline?: DirectorySnapshot;
|
||||
workspaceGitSnapshot?: GitWorkspaceSnapshot | null;
|
||||
workspaceExclude?: string[];
|
||||
preserveAbsentOnRestore?: string[];
|
||||
assets?: AdapterManagedRuntimeAsset[];
|
||||
@@ -1403,6 +1413,7 @@ export async function prepareAdapterExecutionTargetRuntime(input: {
|
||||
assetDirs: {},
|
||||
additionalSourceDirs: {},
|
||||
additionalSourceFailures: [],
|
||||
workspaceSyncSnapshot: null,
|
||||
restoreWorkspace: async () => {},
|
||||
};
|
||||
}
|
||||
@@ -1428,6 +1439,7 @@ export async function prepareAdapterExecutionTargetRuntime(input: {
|
||||
// The SSH transport does not stage referenced projects (it is out of scope), so it never
|
||||
// reports a per-project staging failure.
|
||||
additionalSourceFailures: [],
|
||||
workspaceSyncSnapshot: null,
|
||||
restoreWorkspace: prepared.restoreWorkspace,
|
||||
};
|
||||
}
|
||||
@@ -1448,6 +1460,10 @@ export async function prepareAdapterExecutionTargetRuntime(input: {
|
||||
workspaceLocalDir: input.workspaceLocalDir,
|
||||
workspaceRemoteDir: input.workspaceRemoteDir,
|
||||
syncWorkspace: input.syncWorkspace,
|
||||
workspaceInboundMode: input.workspaceInboundMode,
|
||||
workspaceDurableSeed: input.workspaceDurableSeed,
|
||||
workspaceBaseline: input.workspaceBaseline,
|
||||
workspaceGitSnapshot: input.workspaceGitSnapshot,
|
||||
workspaceExclude: input.workspaceExclude,
|
||||
preserveAbsentOnRestore: input.preserveAbsentOnRestore,
|
||||
assets: input.assets,
|
||||
@@ -1465,6 +1481,7 @@ export async function prepareAdapterExecutionTargetRuntime(input: {
|
||||
assetDirs: prepared.assetDirs,
|
||||
additionalSourceDirs: prepared.additionalSourceDirs,
|
||||
additionalSourceFailures: prepared.additionalSourceFailures,
|
||||
workspaceSyncSnapshot: prepared.workspaceSyncSnapshot,
|
||||
restoreWorkspace: prepared.restoreWorkspace,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -348,6 +348,129 @@ describe("sandbox managed runtime", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("adopts a warm remote workspace without inbound overwrite and still merges outbound changes", async () => {
|
||||
const rootDir = await mkdtemp(
|
||||
path.join(os.tmpdir(), "paperclip-sandbox-adopt-"),
|
||||
);
|
||||
cleanupDirs.push(rootDir);
|
||||
const localWorkspaceDir = path.join(rootDir, "local-workspace");
|
||||
const remoteWorkspaceDir = path.join(rootDir, "remote-workspace");
|
||||
await mkdir(localWorkspaceDir, { recursive: true });
|
||||
await mkdir(remoteWorkspaceDir, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(localWorkspaceDir, "continuity.txt"),
|
||||
"host baseline\n",
|
||||
"utf8",
|
||||
);
|
||||
await writeFile(
|
||||
path.join(remoteWorkspaceDir, "continuity.txt"),
|
||||
"remote retained\n",
|
||||
"utf8",
|
||||
);
|
||||
const client = makeFilesystemClient();
|
||||
const syncIn = vi.spyOn(client, "syncIn");
|
||||
|
||||
const prepared = await prepareSandboxManagedRuntime({
|
||||
spec: {
|
||||
transport: "sandbox",
|
||||
provider: "test",
|
||||
sandboxId: "sandbox-warm",
|
||||
remoteCwd: remoteWorkspaceDir,
|
||||
timeoutMs: 30_000,
|
||||
apiKey: null,
|
||||
},
|
||||
adapterKey: "test-adapter",
|
||||
client,
|
||||
workspaceLocalDir: localWorkspaceDir,
|
||||
workspaceInboundMode: "adopt_remote",
|
||||
});
|
||||
|
||||
expect(syncIn).not.toHaveBeenCalled();
|
||||
await expect(
|
||||
readFile(path.join(remoteWorkspaceDir, "continuity.txt"), "utf8"),
|
||||
).resolves.toBe("remote retained\n");
|
||||
expect(prepared.workspaceSyncSnapshot).not.toBeNull();
|
||||
|
||||
await writeFile(
|
||||
path.join(remoteWorkspaceDir, "continuity.txt"),
|
||||
"remote finalized\n",
|
||||
"utf8",
|
||||
);
|
||||
await prepared.restoreWorkspace();
|
||||
await expect(
|
||||
readFile(path.join(localWorkspaceDir, "continuity.txt"), "utf8"),
|
||||
).resolves.toBe("remote finalized\n");
|
||||
});
|
||||
|
||||
it("reconstructs a replacement workspace from the exact durable pre-turn seed", async () => {
|
||||
const rootDir = await mkdtemp(
|
||||
path.join(os.tmpdir(), "paperclip-sandbox-durable-seed-"),
|
||||
);
|
||||
cleanupDirs.push(rootDir);
|
||||
const localWorkspaceDir = path.join(rootDir, "local-workspace");
|
||||
const firstRemoteDir = path.join(rootDir, "first-remote");
|
||||
const replacementRemoteDir = path.join(rootDir, "replacement-remote");
|
||||
const durableSeed = {
|
||||
workspaceArchivePath: path.join(rootDir, "state", "workspace.tar"),
|
||||
gitArchivePath: path.join(rootDir, "state", "git.tar"),
|
||||
};
|
||||
await mkdir(localWorkspaceDir, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(localWorkspaceDir, "continuity.txt"),
|
||||
"durable pre-turn bytes\n",
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const first = await prepareSandboxManagedRuntime({
|
||||
spec: {
|
||||
transport: "sandbox",
|
||||
provider: "test",
|
||||
sandboxId: "sandbox-first",
|
||||
remoteCwd: firstRemoteDir,
|
||||
timeoutMs: 30_000,
|
||||
apiKey: null,
|
||||
},
|
||||
adapterKey: "test-adapter",
|
||||
client: makeFilesystemClient(),
|
||||
workspaceLocalDir: localWorkspaceDir,
|
||||
workspaceInboundMode: "host_current",
|
||||
workspaceDurableSeed: durableSeed,
|
||||
});
|
||||
expect(first.workspaceSyncSnapshot).not.toBeNull();
|
||||
await expect(stat(durableSeed.workspaceArchivePath)).resolves.toMatchObject(
|
||||
{
|
||||
mode: expect.any(Number),
|
||||
},
|
||||
);
|
||||
|
||||
await writeFile(
|
||||
path.join(localWorkspaceDir, "continuity.txt"),
|
||||
"concurrent host edit must not enter replacement\n",
|
||||
"utf8",
|
||||
);
|
||||
await prepareSandboxManagedRuntime({
|
||||
spec: {
|
||||
transport: "sandbox",
|
||||
provider: "test",
|
||||
sandboxId: "sandbox-replacement",
|
||||
remoteCwd: replacementRemoteDir,
|
||||
timeoutMs: 30_000,
|
||||
apiKey: null,
|
||||
},
|
||||
adapterKey: "test-adapter",
|
||||
client: makeFilesystemClient(),
|
||||
workspaceLocalDir: localWorkspaceDir,
|
||||
workspaceInboundMode: "durable_seed",
|
||||
workspaceDurableSeed: durableSeed,
|
||||
workspaceBaseline: first.workspaceSyncSnapshot!.baseline,
|
||||
workspaceGitSnapshot: first.workspaceSyncSnapshot!.gitSnapshot,
|
||||
});
|
||||
|
||||
await expect(
|
||||
readFile(path.join(replacementRemoteDir, "continuity.txt"), "utf8"),
|
||||
).resolves.toBe("durable pre-turn bytes\n");
|
||||
});
|
||||
|
||||
it("preserves excluded local workspace artifacts during restore mirroring", async () => {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-sandbox-restore-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { constants as fsConstants, promises as fs } from "node:fs";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import {
|
||||
constants as fsConstants,
|
||||
createReadStream,
|
||||
promises as fs,
|
||||
} from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
@@ -12,6 +16,7 @@ import {
|
||||
deleteLocalGitRef,
|
||||
fetchGitBundleIntoLocalRef,
|
||||
GIT_ARCHIVE_EXCLUDES,
|
||||
type GitWorkspaceSnapshot,
|
||||
integrateImportedGitHead,
|
||||
readGitWorkspaceSnapshot,
|
||||
ReferencedSourceIgnoreScanLimitExceededError,
|
||||
@@ -20,7 +25,11 @@ import {
|
||||
withShallowGitWorkspaceClone,
|
||||
WORKSPACE_GIT_SCAN_SATURATED_CODE,
|
||||
} from "./git-workspace-sync.js";
|
||||
import { captureDirectorySnapshot, mergeDirectoryWithBaseline } from "./workspace-restore-merge.js";
|
||||
import {
|
||||
captureDirectorySnapshot,
|
||||
mergeDirectoryWithBaseline,
|
||||
type DirectorySnapshot,
|
||||
} from "./workspace-restore-merge.js";
|
||||
import {
|
||||
createRuntimeProgressReporter,
|
||||
type RuntimeProgressDirection,
|
||||
@@ -553,9 +562,29 @@ export interface PreparedSandboxManagedRuntime {
|
||||
* staged, or when no additional sources were requested.
|
||||
*/
|
||||
additionalSourceFailures: AdditionalSourceStagingFailure[];
|
||||
/** Durable merge inputs used to resume an outbound restore after host restart. */
|
||||
workspaceSyncSnapshot: {
|
||||
baseline: DirectorySnapshot;
|
||||
gitSnapshot: GitWorkspaceSnapshot | null;
|
||||
} | null;
|
||||
restoreWorkspace(onProgress?: RuntimeProgressSink): Promise<void>;
|
||||
}
|
||||
|
||||
export type WorkspaceInboundMode =
|
||||
"host_current" | "durable_seed" | "adopt_remote";
|
||||
|
||||
/**
|
||||
* Controller-owned archives for replaying the exact pre-turn workspace into a
|
||||
* replacement sandbox. Paths are never sent to the provider as credentials or
|
||||
* persisted in database metadata.
|
||||
*/
|
||||
export interface WorkspaceDurableSeedPaths {
|
||||
workspaceArchivePath: string;
|
||||
workspaceArchiveSha256?: string;
|
||||
gitArchivePath?: string | null;
|
||||
gitArchiveSha256?: string | null;
|
||||
}
|
||||
|
||||
/** One additional (referenced) project that failed to stage into the sandbox. */
|
||||
export interface AdditionalSourceStagingFailure {
|
||||
projectId: string;
|
||||
@@ -719,6 +748,57 @@ async function withTempDir<T>(prefix: string, fn: (dir: string) => Promise<T>):
|
||||
}
|
||||
}
|
||||
|
||||
async function sha256File(filePath: string): Promise<string> {
|
||||
return await new Promise((resolveDigest, rejectDigest) => {
|
||||
const digest = createHash("sha256");
|
||||
const stream = createReadStream(filePath);
|
||||
stream.on("data", (chunk) => digest.update(chunk));
|
||||
stream.on("error", rejectDigest);
|
||||
stream.on("end", () => resolveDigest(digest.digest("hex")));
|
||||
});
|
||||
}
|
||||
|
||||
async function copyDurableSeedArchive(input: {
|
||||
sourcePath: string;
|
||||
targetPath: string;
|
||||
expectedSha256?: string | null;
|
||||
}): Promise<void> {
|
||||
const source = await fs.lstat(input.sourcePath);
|
||||
if (source.isSymbolicLink() || !source.isFile()) {
|
||||
throw new Error("workspace_durable_seed_invalid");
|
||||
}
|
||||
if (
|
||||
input.expectedSha256 &&
|
||||
(await sha256File(input.sourcePath)) !== input.expectedSha256
|
||||
) {
|
||||
throw new Error("workspace_durable_seed_digest_mismatch");
|
||||
}
|
||||
await fs.copyFile(input.sourcePath, input.targetPath);
|
||||
}
|
||||
|
||||
async function persistDurableSeedArchive(input: {
|
||||
sourcePath: string;
|
||||
targetPath: string;
|
||||
}): Promise<void> {
|
||||
const parent = path.dirname(input.targetPath);
|
||||
await fs.mkdir(parent, { recursive: true, mode: 0o700 });
|
||||
const parentStat = await fs.lstat(parent);
|
||||
if (parentStat.isSymbolicLink() || !parentStat.isDirectory()) {
|
||||
throw new Error("workspace_durable_seed_root_invalid");
|
||||
}
|
||||
const temporary = path.join(
|
||||
parent,
|
||||
`.${path.basename(input.targetPath)}.${randomUUID()}.tmp`,
|
||||
);
|
||||
try {
|
||||
await fs.copyFile(input.sourcePath, temporary);
|
||||
await fs.chmod(temporary, 0o600);
|
||||
await fs.rename(temporary, input.targetPath);
|
||||
} finally {
|
||||
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async function execTar(args: string[]): Promise<void> {
|
||||
await execFile("tar", args, {
|
||||
env: {
|
||||
@@ -976,6 +1056,12 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
workspaceLocalDir: string;
|
||||
workspaceRemoteDir?: string;
|
||||
syncWorkspace?: boolean;
|
||||
/** Selects authoritative host staging, exact durable-seed replay, or no-overwrite adoption. */
|
||||
workspaceInboundMode?: WorkspaceInboundMode;
|
||||
workspaceDurableSeed?: WorkspaceDurableSeedPaths;
|
||||
/** Durable snapshots supplied when reconstructing an interrupted restore. */
|
||||
workspaceBaseline?: DirectorySnapshot;
|
||||
workspaceGitSnapshot?: GitWorkspaceSnapshot | null;
|
||||
workspaceExclude?: string[];
|
||||
preserveAbsentOnRestore?: string[];
|
||||
assets?: SandboxManagedRuntimeAsset[];
|
||||
@@ -999,6 +1085,16 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
const workspaceRemoteDir = input.workspaceRemoteDir ?? input.spec.remoteCwd;
|
||||
const runtimeRootDir = path.posix.join(workspaceRemoteDir, ".paperclip-runtime", input.adapterKey);
|
||||
const syncWorkspace = input.syncWorkspace !== false;
|
||||
const workspaceInboundMode = input.workspaceInboundMode ?? "host_current";
|
||||
const stageWorkspace =
|
||||
syncWorkspace && workspaceInboundMode !== "adopt_remote";
|
||||
const prepareWorkspaceSeed =
|
||||
syncWorkspace &&
|
||||
workspaceInboundMode === "adopt_remote" &&
|
||||
input.workspaceDurableSeed !== undefined;
|
||||
if (workspaceInboundMode === "durable_seed" && !input.workspaceDurableSeed) {
|
||||
throw new Error("workspace_durable_seed_missing");
|
||||
}
|
||||
|
||||
// Reject any unsafe asset key before an archive path or an asset directory is
|
||||
// built from it. This runs before the git snapshot work so a bad key fails fast.
|
||||
@@ -1025,7 +1121,11 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
// It reads git's own bookkeeping to decide what to include/exclude, so it is
|
||||
// usually fast, but on a large working tree the `--ignored` walk is not free.
|
||||
const gitSnapshot = syncWorkspace
|
||||
? await runStepSpan("snapshot.git", () => readGitWorkspaceSnapshot(input.workspaceLocalDir))
|
||||
? input.workspaceGitSnapshot !== undefined
|
||||
? input.workspaceGitSnapshot
|
||||
: await runStepSpan("snapshot.git", () =>
|
||||
readGitWorkspaceSnapshot(input.workspaceLocalDir),
|
||||
)
|
||||
: null;
|
||||
const gitIgnoredExcludes = gitSnapshot?.ignoredPaths;
|
||||
const workspaceArchiveExclude = mergeExcludes(
|
||||
@@ -1047,9 +1147,12 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
// dominant cost in the pre-`pack` window — it reads the content of every
|
||||
// non-excluded file, serially — so it earns its own span.
|
||||
const baselineSnapshot = syncWorkspace
|
||||
? await runStepSpan("snapshot.baseline", () =>
|
||||
captureDirectorySnapshot(input.workspaceLocalDir, { exclude: restoreExclude }),
|
||||
)
|
||||
? (input.workspaceBaseline ??
|
||||
(await runStepSpan("snapshot.baseline", () =>
|
||||
captureDirectorySnapshot(input.workspaceLocalDir, {
|
||||
exclude: restoreExclude,
|
||||
}),
|
||||
)))
|
||||
: null;
|
||||
|
||||
// Every inbound staging step delegates to the provider through `client.syncIn`:
|
||||
@@ -1172,7 +1275,7 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
// records its own failure and never rejects.
|
||||
const inboundTaskIsRequired: boolean[] = [];
|
||||
|
||||
if (syncWorkspace) {
|
||||
if (stageWorkspace || prepareWorkspaceSeed) {
|
||||
inboundTaskIsRequired.push(true);
|
||||
inboundTasks.push(() =>
|
||||
runStepSpan("stage.workspace", async () => {
|
||||
@@ -1203,18 +1306,49 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
if (gitSnapshot) {
|
||||
await emitRuntimeStatus(input.onRuntimeProgress, "git_sync", "Syncing git history to environment");
|
||||
const gitTarPath = path.join(tempDir, "git-workspace.tar");
|
||||
const remoteGitTar = path.posix.join(runtimeRootDir, "git-workspace-upload.tar");
|
||||
await withShallowGitWorkspaceClone({
|
||||
localDir: input.workspaceLocalDir,
|
||||
snapshot: gitSnapshot,
|
||||
}, async (cloneDir) => {
|
||||
await createTarballFromDirectory({
|
||||
localDir: cloneDir,
|
||||
archivePath: gitTarPath,
|
||||
exclude: [".paperclip-runtime"],
|
||||
const remoteGitTar = path.posix.join(
|
||||
runtimeRootDir,
|
||||
"git-workspace-upload.tar",
|
||||
);
|
||||
if (workspaceInboundMode === "durable_seed") {
|
||||
const durableGitArchive =
|
||||
input.workspaceDurableSeed?.gitArchivePath;
|
||||
if (!durableGitArchive) {
|
||||
throw new Error("workspace_durable_seed_git_missing");
|
||||
}
|
||||
await copyDurableSeedArchive({
|
||||
sourcePath: durableGitArchive,
|
||||
targetPath: gitTarPath,
|
||||
expectedSha256: input.workspaceDurableSeed?.gitArchiveSha256,
|
||||
});
|
||||
} else {
|
||||
await withShallowGitWorkspaceClone(
|
||||
{
|
||||
localDir: input.workspaceLocalDir,
|
||||
snapshot: gitSnapshot,
|
||||
},
|
||||
async (cloneDir) => {
|
||||
await createTarballFromDirectory({
|
||||
localDir: cloneDir,
|
||||
archivePath: gitTarPath,
|
||||
exclude: [".paperclip-runtime"],
|
||||
});
|
||||
},
|
||||
);
|
||||
if (input.workspaceDurableSeed?.gitArchivePath) {
|
||||
await persistDurableSeedArchive({
|
||||
sourcePath: gitTarPath,
|
||||
targetPath: input.workspaceDurableSeed.gitArchivePath,
|
||||
});
|
||||
}
|
||||
}
|
||||
workspaceFiles.push({
|
||||
sourcePath: gitTarPath,
|
||||
targetPath: remoteGitTar,
|
||||
kind: "file",
|
||||
access: "rw",
|
||||
writablePath: workspaceRemoteDir,
|
||||
});
|
||||
workspaceFiles.push({ sourcePath: gitTarPath, targetPath: remoteGitTar, kind: "file", access: "rw", writablePath: workspaceRemoteDir });
|
||||
workspacePostUploadCommands.push({
|
||||
command: buildWorkspaceTarExtractCommand({
|
||||
workspaceRemoteDir,
|
||||
@@ -1230,22 +1364,48 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
// the preserved names first. The extract runs AFTER the git extract.
|
||||
await emitRuntimeStatus(input.onRuntimeProgress, "config_sync", "Syncing workspace to environment");
|
||||
const workspaceTarPath = path.join(tempDir, "workspace.tar");
|
||||
const workspaceArchiveDir = gitSnapshot ? path.join(tempDir, "workspace-overlay") : input.workspaceLocalDir;
|
||||
if (gitSnapshot) {
|
||||
await copySelectedWorkspaceEntries({
|
||||
sourceDir: input.workspaceLocalDir,
|
||||
targetDir: workspaceArchiveDir,
|
||||
relativePaths: gitSnapshot.overlayPaths,
|
||||
exclude: workspaceArchiveExclude,
|
||||
if (workspaceInboundMode === "durable_seed") {
|
||||
await copyDurableSeedArchive({
|
||||
sourcePath: input.workspaceDurableSeed!.workspaceArchivePath,
|
||||
targetPath: workspaceTarPath,
|
||||
expectedSha256:
|
||||
input.workspaceDurableSeed!.workspaceArchiveSha256,
|
||||
});
|
||||
} else {
|
||||
const workspaceArchiveDir = gitSnapshot
|
||||
? path.join(tempDir, "workspace-overlay")
|
||||
: input.workspaceLocalDir;
|
||||
if (gitSnapshot) {
|
||||
await copySelectedWorkspaceEntries({
|
||||
sourceDir: input.workspaceLocalDir,
|
||||
targetDir: workspaceArchiveDir,
|
||||
relativePaths: gitSnapshot.overlayPaths,
|
||||
exclude: workspaceArchiveExclude,
|
||||
});
|
||||
}
|
||||
await createTarballFromDirectory({
|
||||
localDir: workspaceArchiveDir,
|
||||
archivePath: workspaceTarPath,
|
||||
exclude: gitSnapshot ? undefined : workspaceArchiveExclude,
|
||||
});
|
||||
if (input.workspaceDurableSeed) {
|
||||
await persistDurableSeedArchive({
|
||||
sourcePath: workspaceTarPath,
|
||||
targetPath: input.workspaceDurableSeed.workspaceArchivePath,
|
||||
});
|
||||
}
|
||||
}
|
||||
await createTarballFromDirectory({
|
||||
localDir: workspaceArchiveDir,
|
||||
archivePath: workspaceTarPath,
|
||||
exclude: gitSnapshot ? undefined : workspaceArchiveExclude,
|
||||
const remoteWorkspaceTar = path.posix.join(
|
||||
runtimeRootDir,
|
||||
"workspace-upload.tar",
|
||||
);
|
||||
workspaceFiles.push({
|
||||
sourcePath: workspaceTarPath,
|
||||
targetPath: remoteWorkspaceTar,
|
||||
kind: "file",
|
||||
access: "rw",
|
||||
writablePath: workspaceRemoteDir,
|
||||
});
|
||||
const remoteWorkspaceTar = path.posix.join(runtimeRootDir, "workspace-upload.tar");
|
||||
workspaceFiles.push({ sourcePath: workspaceTarPath, targetPath: remoteWorkspaceTar, kind: "file", access: "rw", writablePath: workspaceRemoteDir });
|
||||
workspacePostUploadCommands.push({
|
||||
command: buildWorkspaceTarExtractCommand({
|
||||
workspaceRemoteDir,
|
||||
@@ -1265,6 +1425,8 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
workspaceUploadBytes += (await fs.stat(workspaceTarPath)).size;
|
||||
});
|
||||
|
||||
if (!stageWorkspace) return;
|
||||
|
||||
// One confined `syncIn` for the whole merged workspace file set. The confine
|
||||
// guard covers every mapping BEFORE any bytes upload (fail-closed): a source
|
||||
// or target escape in EITHER tar mapping stops the upload of both.
|
||||
@@ -1457,6 +1619,10 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
assetDirs,
|
||||
additionalSourceDirs,
|
||||
additionalSourceFailures,
|
||||
workspaceSyncSnapshot:
|
||||
syncWorkspace && baselineSnapshot
|
||||
? { baseline: baselineSnapshot, gitSnapshot }
|
||||
: null,
|
||||
restoreWorkspace: async (onProgress?: RuntimeProgressSink) => {
|
||||
const restoreSink = onProgress ?? input.onProgress;
|
||||
|
||||
|
||||
@@ -9,9 +9,12 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { resolvePaperclipInstanceRootForAdapter } from "./server-utils.js";
|
||||
import {
|
||||
captureDirectorySnapshot,
|
||||
directorySnapshotSha256,
|
||||
classifyWorkspaceRestoreFailure,
|
||||
describeWorkspaceRestoreFailure,
|
||||
mergeDirectoryWithBaseline,
|
||||
parseDirectorySnapshot,
|
||||
serializeDirectorySnapshot,
|
||||
withDirectoryMergeLock,
|
||||
WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE,
|
||||
} from "./workspace-restore-merge.js";
|
||||
@@ -27,6 +30,36 @@ describe("workspace restore merge", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("round-trips a deterministic durable snapshot and rejects traversal", async () => {
|
||||
const rootDir = await mkdtemp(
|
||||
path.join(os.tmpdir(), "paperclip-snapshot-"),
|
||||
);
|
||||
cleanupDirs.push(rootDir);
|
||||
await mkdir(path.join(rootDir, "nested"), { recursive: true });
|
||||
await writeFile(path.join(rootDir, "b.txt"), "bravo\n", "utf8");
|
||||
await writeFile(path.join(rootDir, "nested", "a.txt"), "alpha\n", "utf8");
|
||||
|
||||
const snapshot = await captureDirectorySnapshot(rootDir, { exclude: [] });
|
||||
const serialized = serializeDirectorySnapshot(snapshot);
|
||||
const restored = parseDirectorySnapshot(serialized);
|
||||
|
||||
expect(serialized.entries.map(([relativePath]) => relativePath)).toEqual([
|
||||
"b.txt",
|
||||
"nested",
|
||||
"nested/a.txt",
|
||||
]);
|
||||
expect(restored).not.toBeNull();
|
||||
expect(directorySnapshotSha256(restored!)).toBe(
|
||||
directorySnapshotSha256(snapshot),
|
||||
);
|
||||
expect(
|
||||
parseDirectorySnapshot({
|
||||
...serialized,
|
||||
entries: [["../escape", serialized.entries[0]![1]]],
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves sibling files when sequential stale-baseline restores create the same nested directory tree", async () => {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-restore-merge-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from "node:path";
|
||||
import { shouldExcludePath } from "./exclude-patterns.js";
|
||||
import { resolvePaperclipInstanceRootForAdapter } from "./server-utils.js";
|
||||
|
||||
type SnapshotEntry =
|
||||
export type SnapshotEntry =
|
||||
| { kind: "dir" }
|
||||
| { kind: "file"; mode: number; hash: string }
|
||||
| { kind: "symlink"; target: string };
|
||||
@@ -15,6 +15,87 @@ export interface DirectorySnapshot {
|
||||
entries: Map<string, SnapshotEntry>;
|
||||
}
|
||||
|
||||
export interface SerializedDirectorySnapshot {
|
||||
version: 1;
|
||||
exclude: string[];
|
||||
entries: Array<[string, SnapshotEntry]>;
|
||||
}
|
||||
|
||||
function isSafeSnapshotRelativePath(value: string): boolean {
|
||||
if (!value || path.posix.isAbsolute(value) || path.win32.isAbsolute(value)) {
|
||||
return false;
|
||||
}
|
||||
return !value.split(/[\\/]/).some((segment) => segment === "..");
|
||||
}
|
||||
|
||||
function parseSnapshotEntry(value: unknown): SnapshotEntry | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const candidate = value as Record<string, unknown>;
|
||||
if (candidate.kind === "dir") return { kind: "dir" };
|
||||
if (candidate.kind === "symlink" && typeof candidate.target === "string") {
|
||||
return { kind: "symlink", target: candidate.target };
|
||||
}
|
||||
if (
|
||||
candidate.kind === "file" &&
|
||||
typeof candidate.mode === "number" &&
|
||||
Number.isInteger(candidate.mode) &&
|
||||
candidate.mode >= 0 &&
|
||||
typeof candidate.hash === "string" &&
|
||||
/^[0-9a-f]{64}$/.test(candidate.hash)
|
||||
) {
|
||||
return { kind: "file", mode: candidate.mode, hash: candidate.hash };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function serializeDirectorySnapshot(
|
||||
snapshot: DirectorySnapshot,
|
||||
): SerializedDirectorySnapshot {
|
||||
return {
|
||||
version: 1,
|
||||
exclude: [...snapshot.exclude],
|
||||
entries: [...snapshot.entries.entries()].sort(([left], [right]) =>
|
||||
left.localeCompare(right),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseDirectorySnapshot(
|
||||
value: unknown,
|
||||
): DirectorySnapshot | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const candidate = value as Record<string, unknown>;
|
||||
if (
|
||||
candidate.version !== 1 ||
|
||||
!Array.isArray(candidate.exclude) ||
|
||||
!candidate.exclude.every((entry) => typeof entry === "string") ||
|
||||
!Array.isArray(candidate.entries)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const entries = new Map<string, SnapshotEntry>();
|
||||
for (const rawEntry of candidate.entries) {
|
||||
if (!Array.isArray(rawEntry) || rawEntry.length !== 2) return null;
|
||||
const [relative, rawSnapshotEntry] = rawEntry;
|
||||
if (typeof relative !== "string" || !isSafeSnapshotRelativePath(relative)) {
|
||||
return null;
|
||||
}
|
||||
const entry = parseSnapshotEntry(rawSnapshotEntry);
|
||||
if (!entry || entries.has(relative)) return null;
|
||||
entries.set(relative, entry);
|
||||
}
|
||||
return {
|
||||
exclude: [...new Set(candidate.exclude as string[])],
|
||||
entries,
|
||||
};
|
||||
}
|
||||
|
||||
export function directorySnapshotSha256(snapshot: DirectorySnapshot): string {
|
||||
return createHash("sha256")
|
||||
.update(JSON.stringify(serializeDirectorySnapshot(snapshot)))
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
async function hashFile(filePath: string): Promise<string> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const hash = createHash("sha256");
|
||||
|
||||
Reference in new issue
Block a user