fix(adapter-utils): protect nested clone .git directories during workspace copy-back (#18534)

## Thinking Path

> - Paperclip runs agents in local, SSH and sandbox environments.
> - A remote run uploads the agent workspace to the execution host. At
the end the adapter copies the workspace back.
> - The upload excludes Git metadata with the `.git` archive exclude
list.
> - The copy-back uses the same list to decide what it may delete. The
list only matched the top-level `.git` directory.
> - The upload left out nested clones' `.git` data. The copy-back
treated that data as deleted in the sandbox.
> - The copy-back then removed `repo/.git` on the host. Unpushed commits
and branches were lost.
> - This pull request adds the nested patterns that the heavy-directory
excludes already use.
> - The benefit is that a copy-back never deletes Git data that the
upload left out.

## Linked Issues or Issue Description

Fixes: #18299

Refs: #15959 (the same exclude list inconsistency for SSH workspaces)

## What Changed

- Add `*/.git` and `*/.git/*` to `GIT_ARCHIVE_EXCLUDES`. The restore
baseline exclude now matches a nested `.git` at any depth, like the tar
upload already does.
- Add a regression test. The test captures a baseline that contains
`repo/.git` and asserts that the nested `.git` is excluded.

## Verification

- `pnpm vitest run
packages/adapter-utils/src/workspace-restore-merge.test.ts` -> the new
test passes; 47 passed.
- Before the change, the same test fails with `expected true to be
false` because the baseline contained `repo/.git/config`.
- `pnpm --filter @paperclipai/adapter-utils exec tsc --noEmit` -> pass.
- `pnpm vitest run
packages/adapter-utils/src/remote-managed-runtime.test.ts` -> 7 passed.
- `git-workspace-sync.test.ts` and `sandbox-managed-runtime.test.ts`
show the same environment failures with and without the change (8 and
40; local Node 23.11 `node:sqlite` `Incomplete workspace manifest`).
This change adds no failure.
- A live sandbox copy-back is not available locally. After merge, run
one sandbox run with a nested clone in the workspace and confirm that
`repo/.git` stays on the host.

## Risks

- The copy-back no longer removes nested `.git` data. This is intended:
the upload does not send that data to the sandbox.
- The tar upload now names the nested patterns explicitly. The tar
behavior does not change because the old `.git` pattern already matched
at any depth.
- `workspaceFileMode: "all"` keeps the old behavior; it does not use
these excludes.

## Model Used

- DeepSeek V4.1 Flash (model id: `deepseek-v4.1-flash`). Provider:
DeepSeek.
- Capabilities: extended reasoning, tool use, shell command execution,
file edits and test execution.
- No other AI model was used for this change.

## 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
- [x] My branch name describes the change
(`fix/sandbox-nested-git-exclude`) and contains no internal ticket id
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes — no
docs page describes this internal exclude list
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green — CI starts after this PR
- [ ] Greptile is 5/5 with no open P2s — review starts after this PR
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Chen Yufeiyang authored and GitHub committed 2026-12-05 03:08:54 -08:00
1 parent 32e80f80fe
commit ed262f2e9a
3 files changed
+153 -3

No files matched your search

@@ -73,7 +73,7 @@ export function setExpensiveWorkspaceGitExecutor(executor: ExpensiveWorkspaceGit
expensiveWorkspaceGitExecutor = executor;
}
export const GIT_ARCHIVE_EXCLUDES = [".git", ".git/*"] as const;
export const GIT_ARCHIVE_EXCLUDES = [".git", ".git/*", "*/.git", "*/.git/*"] as const;
/**
* Identity flags for commits the sync machinery itself creates (the merge
@@ -0,0 +1,119 @@
import { promises as fsPromises } from "node:fs";
import { lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { shouldExcludePath } from "./exclude-patterns.js";
import { GIT_ARCHIVE_EXCLUDES } from "./git-workspace-sync.js";
import {
captureDirectorySnapshot,
disposeDirectorySnapshot,
mergeDirectoryWithBaseline,
} from "./workspace-restore-merge.js";
describe("workspace restore merge with excluded git entries", () => {
const cleanupDirs: string[] = [];
afterEach(async () => {
while (cleanupDirs.length > 0) {
const dir = cleanupDirs.pop();
if (!dir) continue;
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
}
});
it("keeps restoring other entries when a scanned directory vanishes", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-restore-merge-"));
cleanupDirs.push(rootDir);
const target = path.join(rootDir, "target"), source = path.join(rootDir, "source");
await mkdir(path.join(target, "repo", ".git"), { recursive: true });
await writeFile(path.join(target, "repo", ".git", "config"), "[core]\n");
const baseline = await captureDirectorySnapshot(target, { exclude: [...GIT_ARCHIVE_EXCLUDES], diskBacked: true });
try {
await mkdir(source);
await writeFile(path.join(source, "repo"), "replacement");
await writeFile(path.join(source, "independent"), "applied");
const readdirSpy = vi.spyOn(fsPromises, "readdir").mockRejectedValueOnce(
Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }),
);
try {
await expect(mergeDirectoryWithBaseline({ baseline, sourceDir: source, targetDir: target })).resolves.toBeUndefined();
} finally { readdirSpy.mockRestore(); }
expect(await readFile(path.join(target, "independent"), "utf8")).toBe("applied");
expect(await readFile(path.join(target, "repo"), "utf8")).toBe("replacement");
} finally { await disposeDirectorySnapshot(baseline); await rm(rootDir, { recursive: true, force: true }); }
});
it("fails the restore when the excluded-entry scan hits a permission error", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-restore-merge-"));
cleanupDirs.push(rootDir);
const target = path.join(rootDir, "target"), source = path.join(rootDir, "source");
await mkdir(path.join(target, "repo", ".git"), { recursive: true });
await writeFile(path.join(target, "repo", ".git", "config"), "[core]\n");
const baseline = await captureDirectorySnapshot(target, { exclude: [...GIT_ARCHIVE_EXCLUDES], diskBacked: true });
try {
await mkdir(source);
await writeFile(path.join(source, "repo"), "replacement");
const readdirSpy = vi.spyOn(fsPromises, "readdir").mockRejectedValueOnce(
Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }),
);
try {
await expect(mergeDirectoryWithBaseline({ baseline, sourceDir: source, targetDir: target }))
.rejects.toMatchObject({ code: "EACCES" });
} finally { readdirSpy.mockRestore(); }
} finally { await disposeDirectorySnapshot(baseline); await rm(rootDir, { recursive: true, force: true }); }
});
it("excludes a nested clone's .git from the restore baseline", async () => {
const root = await fsPromises.realpath(await mkdtemp(path.join(os.tmpdir(), "directory-nested-git-")));
try {
await mkdir(path.join(root, "repo", ".git"), { recursive: true });
await writeFile(path.join(root, "repo", ".git", "config"), "[core]\n\trepositoryformatversion = 0\n");
await writeFile(path.join(root, "repo", "tracked.txt"), "host\n");
const baseline = await captureDirectorySnapshot(root, { exclude: [...GIT_ARCHIVE_EXCLUDES] });
try {
const entries: string[] = [];
for (const [entry] of baseline.entries as Iterable<[string, unknown]>) entries.push(entry);
expect(entries).toContain("repo/tracked.txt");
expect(entries.some((entry) => entry === "repo/.git" || entry.startsWith("repo/.git/"))).toBe(false);
expect(shouldExcludePath("repo/.git/config", GIT_ARCHIVE_EXCLUDES)).toBe(true);
expect(shouldExcludePath(".git/config", GIT_ARCHIVE_EXCLUDES)).toBe(true);
expect(shouldExcludePath(".github/workflows/ci.yml", GIT_ARCHIVE_EXCLUDES)).toBe(false);
} finally { await disposeDirectorySnapshot(baseline); }
} finally { await rm(root, { recursive: true, force: true }); }
});
it("preserves excluded descendants when a non-strict restore replaces their parent with a file", async () => {
const root = await fsPromises.realpath(await mkdtemp(path.join(os.tmpdir(), "directory-excluded-replacement-")));
const target = path.join(root, "target"), source = path.join(root, "source");
await mkdir(path.join(target, "repo", ".git"), { recursive: true });
await writeFile(path.join(target, "repo", ".git", "config"), "[core]\n\trepositoryformatversion = 0\n");
await writeFile(path.join(target, "repo", "tracked.txt"), "host\n");
const baseline = await captureDirectorySnapshot(target, { exclude: [...GIT_ARCHIVE_EXCLUDES], diskBacked: true });
try {
await mkdir(source);
await writeFile(path.join(source, "repo"), "replacement");
await writeFile(path.join(source, "independent"), "applied");
await mergeDirectoryWithBaseline({ baseline, sourceDir: source, targetDir: target });
expect((await lstat(path.join(target, "repo"))).isDirectory()).toBe(true);
expect(await readFile(path.join(target, "repo", ".git", "config"), "utf8")).toContain("repositoryformatversion");
expect(await readFile(path.join(target, "independent"), "utf8")).toBe("applied");
} finally { await disposeDirectorySnapshot(baseline); await rm(root, { recursive: true, force: true }); }
});
it.skipIf(process.platform === "win32")("preserves excluded descendants when a non-strict restore replaces their parent with a symlink", async () => {
const root = await fsPromises.realpath(await mkdtemp(path.join(os.tmpdir(), "directory-excluded-replacement-link-")));
const target = path.join(root, "target"), source = path.join(root, "source");
await mkdir(path.join(target, "repo", ".git"), { recursive: true });
await writeFile(path.join(target, "repo", ".git", "config"), "[core]\n\trepositoryformatversion = 0\n");
const baseline = await captureDirectorySnapshot(target, { exclude: [...GIT_ARCHIVE_EXCLUDES], diskBacked: true });
try {
await mkdir(source);
await symlink(root, path.join(source, "repo"));
await mergeDirectoryWithBaseline({ baseline, sourceDir: source, targetDir: target });
expect((await lstat(path.join(target, "repo"))).isDirectory()).toBe(true);
expect(await readFile(path.join(target, "repo", ".git", "config"), "utf8")).toContain("repositoryformatversion");
} finally { await disposeDirectorySnapshot(baseline); await rm(root, { recursive: true, force: true }); }
});
});
@@ -598,10 +598,41 @@ async function withCanonicalDirectoryMergeLock<T>(
}
}
async function copySnapshotEntry(sourceDir: string, targetDir: string, relative: string, entry: SnapshotEntry): Promise<void> {
async function directoryContainsExcludedEntry(directory: string, relative: string, exclude: readonly string[]): Promise<boolean> {
if (exclude.length === 0) return false;
const entries = await fs.readdir(directory, { withFileTypes: true }).catch((error: unknown) => {
if (isVanishedEntry(error)) return null;
throw error;
});
if (!entries) return false;
for (const entry of entries) {
const child = path.posix.join(relative, entry.name);
if (shouldExcludePath(child, exclude)) return true;
if (entry.isDirectory() && await directoryContainsExcludedEntry(path.join(directory, entry.name), child, exclude)) return true;
}
return false;
}
async function replacementWouldDiscardExcludedEntry(targetPath: string, relative: string, exclude: readonly string[]): Promise<boolean> {
const existing = await fs.lstat(targetPath).catch(() => null);
if (!existing?.isDirectory()) return false;
if (!(await directoryContainsExcludedEntry(targetPath, relative, exclude))) return false;
console.warn(`workspace restore: skipped replacing ${relative} because it contains paths excluded from the restored snapshot`);
return true;
}
async function copySnapshotEntry(
sourceDir: string,
targetDir: string,
relative: string,
entry: SnapshotEntry,
exclude: readonly string[],
): Promise<void> {
const sourcePath = path.join(sourceDir, relative);
const targetPath = path.join(targetDir, relative);
if (entry.kind !== "dir" && await replacementWouldDiscardExcludedEntry(targetPath, relative, exclude)) return;
if (entry.kind === "dir") {
const existing = await fs.lstat(targetPath).catch(() => null);
if (existing?.isDirectory()) {
@@ -797,7 +828,7 @@ export async function mergeDirectoryWithBaseline(input: {
}
for (const [relative, entry] of orderedEntries(source)) {
if (!entriesMatch(input.baseline.entries.get(relative), entry) &&
!(input.conflictPolicy === "reject" && entriesMatch(current.entries.get(relative), entry))) await copySnapshotEntry(input.sourceDir, canonicalTargetDir, relative, entry);
!(input.conflictPolicy === "reject" && entriesMatch(current.entries.get(relative), entry))) await copySnapshotEntry(input.sourceDir, canonicalTargetDir, relative, entry, input.baseline.exclude);
}
await input.afterApply?.();
} finally { await disposeDirectorySnapshot(current); }