mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
Fix sandbox restore index drift (#8595)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Sandboxed agents can do useful work in a remote workspace, then export that result back to a host review checkout. > - A restore can leave the host checkout's index stale even when the sandbox content and committed state are correct. > - That drift makes reviewers see misleading missing-file or dirty-state results after sandbox execution. > - This pull request repairs the host index refresh path and surfaces a clean/dirty restore signal during finalization. > - The benefit is more reliable review checkouts and clearer sandbox finalization status. ## Linked Issues or Issue Description Refs #248 No exact public GitHub issue was found for this restore/index consistency fix. The underlying bug is that a sandbox restore can update host working-tree content without leaving the host git index aligned, so local review tooling may report stale deletions or misleading dirtiness. This PR keeps the restore/export path consistent and reports the resulting clean/dirty state. GitHub search performed for related or duplicate work: `sandbox runtime status`, `sandbox restore index`, and `runtime progress`. No direct duplicate PR was found. ## What Changed - Refreshed git workspace sync/index handling after sandbox restore/export operations. - Added finalization status that reports whether the restored host checkout is clean or dirty. - Preserved sandbox-managed runtime progress callbacks around restore and finalization. - Added adapter-utils tests covering the host index drift repair and clean/dirty finalization signal. ## Verification - Local PII scan before push: high-confidence secret patterns, internal issue links, local user paths, and private URL patterns checked across all three split diffs; no real secrets or internal links found. - `git diff --check feat/sandbox-runtime-status..fix/sandbox-restore-index-sync` - `pnpm exec vitest run packages/adapter-utils/src/sandbox-managed-runtime.test.ts` — 1 file, 10 tests passed. - `pnpm run typecheck` passed on `fix/sandbox-restore-index-sync`. - `pnpm run build` passed on `fix/sandbox-restore-index-sync`; Vite reported existing CSS `::highlight` and chunk-size warnings. - `pnpm run test:run` was attempted on `fix/sandbox-restore-index-sync`; it failed in two unrelated broad-suite tests. One depends on this host's Git default branch behavior, and one depends on local Claude model-discovery environment. The changed focused suite above passes. ## Risks - Git index refresh behavior needs to remain conservative so it does not hide real uncommitted user changes. - The clean/dirty finalization signal is diagnostic; it should not by itself mark a sandbox run successful or failed. - This PR is stacked on the runtime-status branch so finalization progress can reuse the same callback path. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI GPT-5 via Codex coding agent, with shell/tool execution in a local worktree. Exact context-window metadata is not exposed by the runtime. ## 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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
800dab1c64
commit
721541c41d
4 files changed
+192
-6
No files matched your search
@@ -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.",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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", "test@paperclip.dev"]);
|
||||
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", "test@paperclip.dev"]);
|
||||
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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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?.();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user