The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
Fix sandbox restore index drift (#8595)
Devin Foley721541c41d71
diff --git a/packages/adapter-utils/src/git-workspace-sync.ts b/packages/adapter-utils/src/git-workspace-sync.tsindex 9d69b7165a..1e0a37d8a1 100644--- a/packages/adapter-utils/src/git-workspace-sync.ts+++ b/packages/adapter-utils/src/git-workspace-sync.ts@@ -202,6 +202,7 @@ export function buildRemoteGitDeltaBundleScript(input: {baseSha: string;exportRef: string;bundlePath: string;+ statusPath?: string;catBundle?: boolean;cleanupBundle?: boolean;}): string {@@ -209,8 +210,10 @@ export function buildRemoteGitDeltaBundleScript(input: {const bundlePath = shellQuote(input.bundlePath);const exportRef = shellQuote(input.exportRef);const baseSha = shellQuote(input.baseSha);+ const statusPath = input.statusPath ? shellQuote(input.statusPath) : null;const cleanupParts = [`rm -f ${bundlePath}`,+ ...(statusPath ? [`rm -f ${statusPath}`] : []),`git -C ${remoteDir} update-ref -d ${exportRef} >/dev/null 2>&1 || true`,];return [@@ -227,6 +230,15 @@ export function buildRemoteGitDeltaBundleScript(input: {"else",` : > ${bundlePath}`,"fi",+ statusPath+ ? [+ `if [ -z "$(git -C ${remoteDir} status --porcelain=v1 --untracked-files=normal)" ]; then`,+ ` printf clean > ${statusPath}`,+ "else",+ ` printf dirty > ${statusPath}`,+ "fi",+ ].join("\n")+ : "",input.catBundle ? `cat ${bundlePath}` : "",].filter(Boolean).join("\n");}@@ -319,3 +331,46 @@ export async function integrateImportedGitHead(input: {throw new Error(`Failed to integrate concurrent remote git history for ${input.importedHead.slice(0, 12)} after multiple retries.`);}++export async function resetLocalGitIndexToHead(input: {+ localDir: string;+ checkWorkingTreeClean?: boolean;+}): Promise<void> {+ try {+ await runLocalGit(input.localDir, ["reset", "--quiet", "HEAD", "--", "."], {+ timeout: 60_000,+ maxBuffer: 1024 * 1024,+ });+ } catch (error) {+ const detail = error && typeof error === "object"+ ? [+ (error as { message?: unknown }).message,+ (error as { stderr?: unknown }).stderr,+ (error as { stdout?: unknown }).stdout,+ ].filter((value): value is string => typeof value === "string" && value.trim().length > 0).join("\n")+ : String(error);+ throw new Error(`Failed to reset local git index to HEAD after workspace restore: ${detail}`);+ }++ const stagedDiff = await runLocalGit(input.localDir, ["diff", "--cached", "--name-status", "HEAD", "--"], {+ timeout: 10_000,+ maxBuffer: 1024 * 1024,+ });+ if (stagedDiff.stdout.trim().length > 0) {+ throw new Error(+ `Workspace restore left staged git index changes after reset:\n${stagedDiff.stdout.trim()}`,+ );+ }++ if (!input.checkWorkingTreeClean) return;++ const workingTreeDiff = await runLocalGit(input.localDir, ["diff", "--name-status", "HEAD", "--"], {+ timeout: 10_000,+ maxBuffer: 1024 * 1024,+ });+ if (workingTreeDiff.stdout.trim().length > 0) {+ console.warn(+ "[paperclip] Workspace restore preserved local working tree changes after clean sandbox restore.",+ );+ }+}diff --git a/packages/adapter-utils/src/sandbox-managed-runtime.test.ts b/packages/adapter-utils/src/sandbox-managed-runtime.test.tsindex 2681928d74..6a002521ce 100644--- a/packages/adapter-utils/src/sandbox-managed-runtime.test.ts+++ b/packages/adapter-utils/src/sandbox-managed-runtime.test.ts@@ -3,7 +3,8 @@ import os from "node:os";import path from "node:path";import { execFile as execFileCallback } from "node:child_process";import { promisify } from "node:util";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";+import { resetLocalGitIndexToHead } from "./git-workspace-sync.js";import {mirrorDirectory,@@ -277,6 +278,116 @@ describe("sandbox managed runtime", () => {]);});+ it("repairs stale host index deletions when the sandbox restores a clean git worktree", async () => {+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-sandbox-clean-restore-"));+ cleanupDirs.push(rootDir);+ const sourceRepoDir = path.join(rootDir, "source-repo");+ const localWorkspaceDir = path.join(rootDir, "local-worktree");+ const remoteWorkspaceDir = path.join(rootDir, "remote-workspace");++ await mkdir(sourceRepoDir, { recursive: true });+ await git(sourceRepoDir, ["init"]);+ await git(sourceRepoDir, ["checkout", "-b", "main"]);+ await git(sourceRepoDir, ["config", "user.name", "Paperclip Test"]);+ await git(sourceRepoDir, ["config", "user.email", "[email protected]"]);+ await writeFile(path.join(sourceRepoDir, "kept.txt"), "kept\n", "utf8");+ await writeFile(path.join(sourceRepoDir, "restored.txt"), "restored\n", "utf8");+ await git(sourceRepoDir, ["add", "kept.txt", "restored.txt"]);+ await git(sourceRepoDir, ["commit", "-m", "base"]);+ await git(sourceRepoDir, ["worktree", "add", "-b", "work", localWorkspaceDir, "HEAD"]);++ await git(localWorkspaceDir, ["rm", "restored.txt"]);+ expect(await git(localWorkspaceDir, ["status", "--short"])).toContain("D restored.txt");++ const missingStatusReads: string[] = [];+ const client: SandboxManagedRuntimeClient = {+ makeDir: async (remotePath) => {+ await mkdir(remotePath, { recursive: true });+ },+ writeFile: async (remotePath, bytes) => {+ await mkdir(path.dirname(remotePath), { recursive: true });+ await writeFile(remotePath, Buffer.from(bytes));+ },+ readFile: async (remotePath) => {+ if (remotePath.endsWith("workspace-status.txt")) {+ missingStatusReads.push(remotePath);+ throw new Error("status file unavailable");+ }+ return await readFile(remotePath);+ },+ listFiles: async () => [],+ remove: async (remotePath) => {+ await rm(remotePath, { recursive: true, force: true });+ },+ run: async (command) => {+ await execFile("sh", ["-c", command], { maxBuffer: 32 * 1024 * 1024 });+ },+ };++ const prepared = await prepareSandboxManagedRuntime({+ spec: {+ transport: "sandbox",+ provider: "test",+ sandboxId: "sandbox-1",+ remoteCwd: remoteWorkspaceDir,+ timeoutMs: 30_000,+ apiKey: null,+ },+ adapterKey: "test-adapter",+ client,+ workspaceLocalDir: localWorkspaceDir,+ });++ expect(await git(remoteWorkspaceDir, ["status", "--short"])).toContain("D restored.txt");+ await git(remoteWorkspaceDir, ["reset", "--hard", "HEAD"]);+ expect(await git(remoteWorkspaceDir, ["status", "--short"])).toBe("");++ await prepared.restoreWorkspace();++ await expect(readFile(path.join(localWorkspaceDir, "restored.txt"), "utf8")).resolves.toBe("restored\n");+ expect(await git(localWorkspaceDir, ["ls-files", "restored.txt"])).toBe("restored.txt");+ expect(await git(localWorkspaceDir, ["status", "--short"])).toBe("");+ expect(await git(localWorkspaceDir, ["diff", "--name-status", "HEAD", "--"])).toBe("");+ expect(await git(localWorkspaceDir, ["diff", "--cached", "--name-status", "HEAD", "--"])).toBe("");+ expect(missingStatusReads).toHaveLength(1);+ });++ it("does not fail clean restore checks when local working tree changes survive", async () => {+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-sandbox-preserved-local-"));+ cleanupDirs.push(rootDir);+ const sourceRepoDir = path.join(rootDir, "source-repo");+ const localWorkspaceDir = path.join(rootDir, "local-worktree");++ await mkdir(sourceRepoDir, { recursive: true });+ await git(sourceRepoDir, ["init"]);+ await git(sourceRepoDir, ["checkout", "-b", "main"]);+ await git(sourceRepoDir, ["config", "user.name", "Paperclip Test"]);+ await git(sourceRepoDir, ["config", "user.email", "[email protected]"]);+ await writeFile(path.join(sourceRepoDir, "kept.txt"), "base\n", "utf8");+ await git(sourceRepoDir, ["add", "kept.txt"]);+ await git(sourceRepoDir, ["commit", "-m", "base"]);+ await git(sourceRepoDir, ["worktree", "add", "-b", "work", localWorkspaceDir, "HEAD"]);++ await writeFile(path.join(localWorkspaceDir, "kept.txt"), "local user change\n", "utf8");++ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ try {+ await resetLocalGitIndexToHead({+ localDir: localWorkspaceDir,+ checkWorkingTreeClean: true,+ });+ expect(warnSpy).toHaveBeenCalledWith(+ "[paperclip] Workspace restore preserved local working tree changes after clean sandbox restore.",+ );+ } finally {+ warnSpy.mockRestore();+ }++ await expect(readFile(path.join(localWorkspaceDir, "kept.txt"), "utf8")).resolves.toBe("local user change\n");+ expect(await git(localWorkspaceDir, ["diff", "--cached", "--name-status", "HEAD", "--"])).toBe("");+ expect(await git(localWorkspaceDir, ["status", "--short"])).toContain("M kept.txt");+ });+it("excludes unignored dependency trees from git-backed workspace overlay archives", async () => {const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-sandbox-unignored-deps-"));cleanupDirs.push(rootDir);diff --git a/packages/adapter-utils/src/sandbox-managed-runtime.ts b/packages/adapter-utils/src/sandbox-managed-runtime.tsindex 7c763f42b8..e6fb7355d9 100644--- a/packages/adapter-utils/src/sandbox-managed-runtime.ts+++ b/packages/adapter-utils/src/sandbox-managed-runtime.ts@@ -12,6 +12,7 @@ import {GIT_ARCHIVE_EXCLUDES,integrateImportedGitHead,readGitWorkspaceSnapshot,+ resetLocalGitIndexToHead,withShallowGitWorkspaceClone,} from "./git-workspace-sync.js";import { captureDirectorySnapshot, mergeDirectoryWithBaseline } from "./workspace-restore-merge.js";@@ -544,11 +545,13 @@ export async function prepareSandboxManagedRuntime(input: {await withTempDir("paperclip-sandbox-restore-", async (tempDir) => {let importedRef: string | null = null;let importedHead: string | null = null;+ let remoteWorkspaceStatus = "dirty";try {if (gitSnapshot) {await emitRuntimeStatus(input.onRuntimeProgress, "export", "Exporting git changes from sandbox");importedRef = createImportedGitRef("sandbox");const remoteGitBundle = path.posix.join(runtimeRootDir, "git-delta.bundle");+ const remoteWorkspaceStatusPath = path.posix.join(runtimeRootDir, "workspace-status.txt");const exportRef = createRemoteGitExportRef("sandbox");await input.client.run(`sh -c ${shellQuote(buildRemoteGitDeltaBundleScript({@@ -556,6 +559,7 @@ export async function prepareSandboxManagedRuntime(input: {baseSha: gitSnapshot.headCommit,exportRef,bundlePath: remoteGitBundle,+ statusPath: remoteWorkspaceStatusPath,}))}`,{ timeoutMs: input.spec.timeoutMs },);@@ -563,6 +567,11 @@ export async function prepareSandboxManagedRuntime(input: {const bundleBytes = await input.client.readFile(remoteGitBundle, gitExport.options);await gitExport.finish();await input.client.remove(remoteGitBundle).catch(() => undefined);+ remoteWorkspaceStatus = await input.client.readFile(remoteWorkspaceStatusPath)+ .then((bytes) => toBuffer(bytes).toString("utf8").trim())+ .catch(() => "dirty");+ remoteWorkspaceStatus = remoteWorkspaceStatus === "clean" ? "clean" : "dirty";+ await input.client.remove(remoteWorkspaceStatusPath).catch(() => undefined);const bundlePath = path.join(tempDir, "git-delta.bundle");await fs.writeFile(bundlePath, toBuffer(bundleBytes));importedHead = await fetchGitBundleIntoLocalRef({@@ -602,11 +611,19 @@ export async function prepareSandboxManagedRuntime(input: {targetDir: input.workspaceLocalDir,beforeApply: gitHeadToIntegrate? async () => {- await integrateImportedGitHead({- localDir: input.workspaceLocalDir,- importedHead: gitHeadToIntegrate,- });- }+ await integrateImportedGitHead({+ localDir: input.workspaceLocalDir,+ importedHead: gitHeadToIntegrate,+ });+ }+ : undefined,+ afterApply: gitSnapshot+ ? async () => {+ await resetLocalGitIndexToHead({+ localDir: input.workspaceLocalDir,+ checkWorkingTreeClean: remoteWorkspaceStatus === "clean",+ });+ }: undefined,});} finally {diff --git a/packages/adapter-utils/src/workspace-restore-merge.ts b/packages/adapter-utils/src/workspace-restore-merge.tsindex c46cfdb844..dd4760dcc9 100644--- a/packages/adapter-utils/src/workspace-restore-merge.ts+++ b/packages/adapter-utils/src/workspace-restore-merge.ts@@ -215,6 +215,7 @@ export async function mergeDirectoryWithBaseline(input: {sourceDir: string;targetDir: string;beforeApply?: () => Promise<void>;+ afterApply?: () => Promise<void>;}): Promise<void> {const source = await captureDirectorySnapshot(input.sourceDir, { exclude: input.baseline.exclude });await withDirectoryMergeLock(input.targetDir, async () => {@@ -244,6 +245,8 @@ export async function mergeDirectoryWithBaseline(input: {for (const [relative, entry] of changedSourceEntries) {await copySnapshotEntry(input.sourceDir, input.targetDir, relative, entry);}++ await input.afterApply?.();});}