fix(workspaces): report git's failure when archive git stops reading input (#23358)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip saves a remote agent workspace as an archive. A worker
thread makes the archive and copies each Git repository into it.
> - The worker sends all source refs to `git update-ref --stdin`. Git
can stop before it reads all of this input, for example when it rejects
a ref update or when it is stopped.
> - The write to git's input then fails with `EPIPE`. The input stream
had no `error` listener, so the error was uncaught in the worker thread.
The worker stopped, and the capture failed with `write EPIPE` instead of
git's own error.
> - Sentry recorded this as an unhandled `write EPIPE` from a server
worker thread on staging.
> - This pull request adds an `error` listener on git's input in the
archive `git()` helper. The helper reports git's exit failure. It
reports the input error only when git exits with success.
> - The benefit is that a failed capture shows the real Git failure and
does not crash the archive worker.

## Linked Issues or Issue Description

Refs #20813
Refs #21068 (draft). That PR adds the same kind of listener to six other
call sites, and since `6ede87b` also to this line. This PR changes only
the archive worker and adds a test that goes through the real worker
thread. If #21068 merges first, rebase it to drop its hunk in
`remote-workspace-snapshot-archive.ts`, or keep this change.

**What happened?**
A workspace capture failed with `Error: write EPIPE` from the archive
worker thread. The real `git update-ref --stdin` failure was not
reported.

**Steps to reproduce**
1. Make a Git repository with about 3000 refs, so that the ref list is
larger than a pipe buffer.
2. Put a `git` on `PATH` that exits with code 128 on `update-ref` and
does not read its input.
3. Capture the directory with `captureRemoteWorkspaceDirectory`.

**Expected behavior**
The capture fails with the `update-ref` error (exit code 128).

**Actual behavior**
The archive worker stops with an uncaught `write EPIPE`, and the capture
fails with `write EPIPE`.

## What Changed

- `server/src/services/remote-workspace-snapshot-archive.ts`: the
`git()` helper listens for `error` on the child's stdin before it
writes. It rejects with git's exit error. It rejects with the input
error only if git exits with success.
-
`server/src/services/remote-workspace-snapshot-archive-git-stdin.test.ts`:
a new regression test. It captures a repository with 3000 refs through
the real archive worker thread. A `git` shim closes its input and exits
128 on `update-ref`. The test expects git's error (code 128, message has
`update-ref`) and no `EPIPE`.

## Verification

- Red before the fix: `npx vitest run
src/services/remote-workspace-snapshot-archive-git-stdin.test.ts` (in
`server/`) failed with `expected 'write EPIPE' not to match /EPIPE/u`.
- Green after the fix: the same test passed 3 times in a row.
- The test uses `git --exec-path` to find the real git binary, so it
does not depend on a git wrapper on `PATH`.
- `pnpm verify` selected 1984/2340 files (most of the suite), so the
broad coverage comes from required CI.

## Risks

- Low risk. Only the archive `git()` helper changes. Calls without input
are not changed.
- A git call that exits with success but did not read all of its input
now fails. Before, the uncaught error stopped the worker in that case
too.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code with tool use
and code execution.

## 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
- [ ] I have updated relevant documentation to reflect my changes (not
applicable: no behavior or command docs change)
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 15:11:35 +00:00
1 parent ea56320e10
commit 3f80675409
2 files changed
+84 -2

No files matched your search

@@ -0,0 +1,75 @@
import { execFile } from "node:child_process";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { captureRemoteWorkspaceDirectory } from "./remote-workspace-snapshot-archive.js";
const execute = promisify(execFile);
const gitEnv = {
...process.env, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: os.devNull,
GIT_AUTHOR_NAME: "Snapshot", GIT_COMMITTER_NAME: "Snapshot",
GIT_AUTHOR_EMAIL: "snapshot@example.test", GIT_COMMITTER_EMAIL: "snapshot@example.test",
};
// The git shim is a POSIX shell script, which native Windows cannot run.
describe.skipIf(process.platform === "win32")("workspace archive git input", () => {
let root: string;
beforeEach(async () => {
root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-archive-git-stdin-")));
});
afterEach(async () => {
vi.unstubAllEnvs();
await fs.rm(root, { recursive: true, force: true });
});
it("reports git's own failure when git exits before reading streamed ref updates", async () => {
// The git executable itself, not a wrapper that PATH may resolve to.
const gitExecPath = (await execute("git", ["--exec-path"])).stdout.trim();
const realGit = path.join(gitExecPath, "git");
const cwd = path.join(root, "source");
await fs.mkdir(cwd);
const git = (args: string[], input?: string) => new Promise<string>((resolve, reject) => {
const child = execFile(realGit, ["-C", cwd, ...args], { env: gitEnv, maxBuffer: 16 * 1024 * 1024 },
(error, stdout) => error ? reject(error) : resolve(stdout.trim()));
if (input !== undefined) child.stdin?.end(input);
});
await git(["init", "-q", "-b", "main"]);
await fs.writeFile(path.join(cwd, "work.txt"), "base work\n");
await git(["add", "."]);
await git(["commit", "-qm", "base"]);
const head = await git(["rev-parse", "HEAD"]);
// Enough refs that the streamed `update-ref --stdin` input is larger than a
// pipe buffer, so the archive is still writing when git stops reading.
const refs = Array.from({ length: 3000 }, (_, index) =>
`create refs/tags/archive-stdin-${String(index).padStart(5, "0")} ${head}`).join("\n");
await git(["update-ref", "--stdin"], `${refs}\n`);
// A git that rejects the ref update without reading its input, like a
// locked or rejected ref, a fatal start-up error, or a killed process.
const bin = path.join(root, "bin");
await fs.mkdir(bin);
await fs.writeFile(path.join(bin, "git"), `#!/bin/sh
for arg in "$@"; do
if [ "$arg" = "update-ref" ]; then
exec 0<&-
printf '%s\\n' 'fatal: update-ref rejected' >&2
exit 128
fi
done
exec ${JSON.stringify(realGit)} "$@"
`, { mode: 0o700 });
vi.stubEnv("PATH", [bin, gitExecPath, process.env.PATH ?? ""].join(path.delimiter));
const failure = await captureRemoteWorkspaceDirectory({
cwd, archivePath: path.join(root, "snapshot.pcws"), gitSourceRoots: [root],
}).then(() => null, (error: unknown) => error as { code?: unknown; message?: string });
expect(failure).not.toBeNull();
expect(failure?.message).not.toMatch(/EPIPE/u);
expect(failure).toMatchObject({ code: 128, message: expect.stringContaining("update-ref") });
}, 60_000);
});
@@ -72,8 +72,15 @@ export async function workspaceArchive(input: {
GIT_OBJECT_DIRECTORY: undefined, GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined, GIT_CONFIG_PARAMETERS: undefined, GIT_CONFIG_COUNT: "0", GIT_TEMPLATE_DIR: undefined,
GIT_AUTHOR_NAME: "Paperclip", GIT_COMMITTER_NAME: "Paperclip", GIT_AUTHOR_EMAIL: "workspace@paperclip.invalid", GIT_COMMITTER_EMAIL: "workspace@paperclip.invalid",
GIT_AUTHOR_DATE: "@0 +0000", GIT_COMMITTER_DATE: "@0 +0000", GIT_NO_LAZY_FETCH: "1" },
}, (error, stdout) => error ? reject(error) : resolve(stdout));
if (stdin !== undefined) command.stdin?.end(stdin);
}, (error, stdout) => error ? reject(error) : inputError ? reject(inputError) : resolve(stdout));
// Git can exit before it reads all of its input, for example when it
// rejects a ref update. The write then fails with EPIPE. Report git's own
// failure; the input error matters only if git claims success.
let inputError: Error | undefined;
if (stdin !== undefined) {
command.stdin?.on("error", error => { inputError = error; });
command.stdin?.end(stdin);
}
});
const portableRemoteUrl = (value: string) => {
if (!value || /[\u0000-\x20\u007f\\]/u.test(value)) return false;