fix(server): name why agent files could not be excluded from task Git staging (#21499)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Before a remote run starts, Paperclip prepares the agent's files in
the sandbox and keeps the reserved runtime directory out of task Git
staging
> - A short program in the sandbox writes the Git exclusion. When it
failed, the run error said only "Could not exclude agent files from task
Git staging"
> - The error dropped the exit code, the timeout state and the program
output. Many staging runs failed with this message, and none of them
showed the cause
> - This pull request adds a closed reason code to the error
> - The benefit is that the next failures show what to fix, without
leaking sandbox paths or user names

## Linked Issues or Issue Description

**What happened?**
Many staging runs failed in the preparing stage with "Could not exclude
agent files from task Git staging". The error had no cause.

**Steps to reproduce**
1. Start a remote run where the Git exclusion program fails (for
example, it times out, Node is missing, or the exclusion file is
unsafe).
2. Read the run error.

**Expected behavior**
The error names why the exclusion failed.

**Actual behavior**
The error gives no reason, so the failure cannot be diagnosed.

## What Changed

- `agent-instruction-files.ts`: add
`instructionGitExcludeFailureReason`. It maps the result to a closed
reason: `timed_out`, `unsafe_directory`, `unsafe_file`, a Node error
code such as `enoent` or `eacces`, `node_unavailable`, `signal_<name>`,
`exit_<code>` or `unknown`.
- `agent-directory-working-copies.ts`: append `(reason=<code>)` to the
existing error message.
- The reason never copies sandbox output, paths or user names.
- Tests: run the real exclusion program against failing fixtures and
check the reason.

## Verification

- `pnpm vitest run
server/src/__tests__/agent-instruction-git-exclusion.test.ts`: 16/16
pass.
- Working copy suite: 136/136 pass.
- These local results are from the earlier master base. The rebase onto
the current master had no conflicts. CI verifies the current head.

## Risks

- Low. The change adds a suffix to one error message. It does not change
when the error is thrown.

## Model Used

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

## 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
- [ ] 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

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-17 13:56:09 -08:00
1 parent 23ce68a8dc
commit f5f60cfcb2
3 files changed
+59 -3

No files matched your search

@@ -4,7 +4,7 @@ import path from "node:path";
import { execFile as execFileCallback } from "node:child_process";
import { promisify } from "node:util";
import { afterEach, beforeEach, expect, it } from "vitest";
import { instructionGitExcludeProgram } from "../services/agent-instruction-files.js";
import { instructionGitExcludeFailureReason, instructionGitExcludeProgram } from "../services/agent-instruction-files.js";
const execFile = promisify(execFileCallback);
let root: string;
@@ -85,3 +85,43 @@ it("replaces a linked ignore file without writing through its external inode", a
expect(await fs.readFile(externalFile, "utf8")).toBe("untouched\n");
expect(await fs.readFile(path.join(runtime, ".gitignore"), "utf8")).toBe("*\n");
});
async function failureReason(cwd: string) {
const failed = await exclude(cwd).then(() => null, (error: { code?: number; signal?: string | null; stderr?: string }) => error);
expect(failed).not.toBeNull();
const reason = instructionGitExcludeFailureReason({ exitCode: typeof failed!.code === "number" ? failed!.code : null,
timedOut: false, signal: failed!.signal ?? null, stderr: failed!.stderr ?? "" });
expect(reason).not.toContain(root);
return reason;
}
it("names a missing task directory without its path", async () => {
await expect(failureReason(path.join(root, "missing"))).resolves.toBe("enoent");
});
it.each(["directory", "file"])("names an unsafe runtime exclusion %s", async kind => {
const workspace = path.join(root, "workspace"), runtime = path.join(workspace, ".paperclip-runtime");
await fs.mkdir(workspace);
if (kind === "directory") await fs.writeFile(runtime, "not a directory");
else await fs.mkdir(path.join(runtime, ".gitignore"), { recursive: true });
await expect(failureReason(workspace)).resolves.toBe(`unsafe_${kind}`);
});
it.skipIf(process.getuid?.() === 0)("names a task directory the sandbox user cannot write", async () => {
const workspace = path.join(root, "workspace");
await fs.mkdir(workspace, { mode: 0o500 });
try {
await expect(failureReason(workspace)).resolves.toBe("eacces");
} finally { await fs.chmod(workspace, 0o700); }
});
it.each([
[{ exitCode: null, timedOut: true, stderr: "" }, "timed_out"],
[{ exitCode: 127, timedOut: false, stderr: "sh: 1: node: not found" }, "node_unavailable"],
[{ exitCode: null, timedOut: false, signal: "SIGKILL", stderr: "" }, "signal_sigkill"],
[{ exitCode: 1, timedOut: false, stderr: "Error: ENOSPC: no space left on device, open '/home/user/x'" }, "enospc"],
[{ exitCode: 3, timedOut: false, stderr: "something else at /home/user/secret" }, "exit_3"],
[{ exitCode: null, timedOut: false, signal: "not a signal", stderr: "" }, "unknown"],
] as const)("classifies %j as %s", (result, reason) => {
expect(instructionGitExcludeFailureReason(result)).toBe(reason);
});
@@ -9,7 +9,7 @@ import { prepareAdapterExecutionTargetRuntime, runAdapterExecutionTargetShellCom
import { withDirectoryMergeLock, directorySnapshotSha256, parseDirectorySnapshot, serializeDirectorySnapshot, type DirectoryMergeLockOperation } from "@paperclipai/adapter-utils/workspace-restore-merge";
import { AGENT_FILES_CONTRACT, AgentFileLimitError, agentFileStore, agentStorageWarning, inspectAgentDirectory } from "./agent-file-store.js";
import { agentInstructionsBundleMode, deriveBundleState, resolveManagedInstructionsRoot } from "./agent-instructions.js";
import { instructionGitExcludeProgram } from "./agent-instruction-files.js";
import { instructionGitExcludeFailureReason, instructionGitExcludeProgram } from "./agent-instruction-files.js";
import { resolveInstructionActor } from "./agent-instruction-authorization.js";
import { HttpError, conflict, notFound } from "../errors.js";
import type { AuthorizationActor } from "./authorization.js";
@@ -239,7 +239,9 @@ export function agentDirectoryWorkingCopyService(db: Db, get: (companyId: string
const excluded = await runAdapterExecutionTargetShellCommand(input.runId, input.target,
`node -e ${quote(instructionGitExcludeProgram)} ${quote(input.target.remoteCwd)}`,
{ cwd: input.target.remoteCwd, env: {}, timeoutSec: 15 });
if (excluded.exitCode !== 0 || excluded.timedOut) throw new Error("Could not exclude agent files from task Git staging");
if (excluded.exitCode !== 0 || excluded.timedOut) {
throw new Error(`Could not exclude agent files from task Git staging (reason=${instructionGitExcludeFailureReason(excluded)})`);
}
const runtime = await transport(row, input.target, false);
transports.set(key(row), runtime);
if (input.target.transport === "sandbox") {
@@ -176,3 +176,17 @@ if(existing && (existing.isSymbolicLink() || !existing.isFile()))throw Error('Un
const temporary=path.join(root,'.ignore-'+crypto.randomUUID()+'.tmp');
try{fs.writeFileSync(temporary,'*\n',{flag:'wx',mode:0o600});fs.renameSync(temporary,filename)}finally{fs.rmSync(temporary,{force:true})}
`;
export function instructionGitExcludeFailureReason(result: {
exitCode: number | null; timedOut: boolean; signal?: string | null; stderr?: string | null;
}): string {
if (result.timedOut) return "timed_out";
const stderr = result.stderr ?? "";
if (stderr.includes("Unsafe runtime exclusion directory")) return "unsafe_directory";
if (stderr.includes("Unsafe runtime exclusion file")) return "unsafe_file";
const nodeCode = /\b(E[A-Z]{2,15})\b(?::| )/.exec(stderr)?.[1];
if (nodeCode) return nodeCode.toLowerCase();
if (result.exitCode === 127) return "node_unavailable";
if (result.signal && /^SIG[A-Z0-9]{1,10}$/.test(result.signal)) return `signal_${result.signal.toLowerCase()}`;
return Number.isSafeInteger(result.exitCode) ? `exit_${result.exitCode}` : "unknown";
}