# Taking an agent's changes out of the sandbox as a patch, and checking it before it touches your repo

> A coding agent that works in a sandbox should hand back a patch, not push a branch. How to produce a binary-safe patch inside the sandbox, and a TypeScript check on your side that refuses symlinks, renames and oversized diffs and flags CI, hooks, dependencies and agent instruction files for a person.

A coding agent that works in a sandbox should hand back a patch, not push a branch. How to produce a binary-safe patch inside the sandbox, and a TypeScript check on your side that refuses symlinks, renames and oversized diffs and flags CI, hooks, dependencies and agent instruction files for a person.

November 26, 2026 · 8 min read · The Sandscale team

A coding agent edits a repository inside a sandbox. At some point its work has to leave the sandbox and land somewhere real: a branch, a pull request, a commit on main. The easy way is to give the sandbox a Git token and let the agent push. That puts a credential where the least trusted code runs, and it lets that code decide what reaches your remote.

The alternative is a hand-off. The sandbox produces a patch, your own code reads it, checks it, and only then applies and pushes it with credentials the sandbox never sees. This post covers both halves: making a patch that survives the trip, and a check that decides whether it may be applied at all.

## Why a patch and not a push

- **No credential in the sandbox.** The code that wrote the change cannot also publish it. Our post on [Git credentials for coding agents](https://sandscale.dev/blog/git-credentials-for-coding-agents) covers the options when a sandbox really does need to push; the patch route makes the question go away.
- **One choke point.** Every change passes through a function you wrote and can test. Rules live there, not in a prompt.
- **A clean base.** You apply the patch to the exact commit the run started from, in a checkout the agent never touched, so nothing else the agent did in its copy (hooks, Git config, stray files outside the diff) comes along.

## Making the patch inside the sandbox

Record the commit you uploaded before the agent starts, for example from `git rev-parse HEAD` in your own checkout. When the agent is done, run one command in the sandbox’s copy of the repository:

```sh
git add -A && git diff --cached --binary --full-index --no-renames --no-ext-diff --no-textconv "$BASE" > /workspace/agent.patch
```

Each flag earns its place:

- `git add -A` stages new files too. A plain `git diff` leaves out untracked files, which is how a patch silently loses the new test the agent wrote.
- Diffing the index against `$BASE` captures the agent’s work whether it committed along the way or not.
- `--binary` and `--full-index` make binary changes representable, so they arrive as binary hunks you can see and refuse, rather than as a “Binary files differ” line that applies as nothing.
- `--no-renames` turns every rename into a delete plus an add. Both paths then show up in the file list, and the check below can treat every file the same way.
- `--no-ext-diff` and `--no-textconv` ignore external diff drivers and text conversion filters. The agent controls the repository’s config and `.gitattributes` inside the sandbox; you want Git’s own diff format, not whatever a configured filter prints.

With the Sandscale TypeScript SDK, that is a `run` followed by a `readFile`. The `builtin:base` template includes Git:

```ts
import { writeFileSync } from 'node:fs';
import { Sandscale } from '@sandscale/sdk';

const sandscale = new Sandscale({ apiKey: process.env.SANDSCALE_API_KEY });

// Runs inside the sandbox: stage everything the agent changed, including new files,
// and write one binary-safe patch against the commit the run started from.
const MAKE_PATCH =
  'git add -A && git diff --cached --binary --full-index --no-renames --no-ext-diff --no-textconv "$BASE" > /workspace/agent.patch';

export async function takePatch(box: { id: string; region: string }, baseSha: string, outPath: string): Promise<void> {
  const run = await sandscale.sandboxes.run(box.id, ['sh', '-c', MAKE_PATCH], {
    region: box.region,
    workdir: '/workspace/repo',
    env: { BASE: baseSha },
    timeoutSeconds: 120,
  });
  if (run.exitCode !== 0 || run.timedOut) {
    throw new Error(`making the patch failed (exit ${run.exitCode}): ${run.stderr.slice(-2000)}`);
  }
  const bytes = await sandscale.sandboxes.readFile(box.id, '/workspace/agent.patch', { region: box.region });
  writeFileSync(outPath, bytes);
}
```

Reading the patch from a file rather than from `stdout` keeps it byte-exact. If you uploaded the repository with the project endpoint, the [change list endpoint](https://sandscale.dev/blog/uploading-a-project-into-a-sandbox) gives you a second, independent view of which files moved, which is a useful cross-check against the patch.

Nothing about the patch is trusted yet. The agent controlled every byte of the environment that produced it.

## Checking the patch on your side

The check runs in your own process, against a clean checkout of `$BASE`, using Git’s own parser. It answers three questions: does it apply, what does it touch, and does anything in it need a person.

```ts
import { execFileSync } from 'node:child_process';

export interface PatchFile {
  path: string;
  added: number | null; // null for binary files
  deleted: number | null;
}

export interface PatchReview {
  files: PatchFile[];
  blocked: string[]; // reasons the patch must not be applied
  needsHuman: string[]; // reasons a person must look before merge
}

const BLOCKED_MODES = new Set(['120000', '160000']); // symlinks, submodules

const NEEDS_HUMAN: Array<[RegExp, string]> = [
  [/^\.github\//, 'CI or repository settings'],
  [/(^|\/)(\.gitlab-ci\.yml|Jenkinsfile|\.circleci\/)/, 'CI configuration'],
  [/(^|\/)(\.husky\/|\.githooks\/|\.pre-commit-config\.yaml$)/, 'hooks that run on developer machines'],
  [/(^|\/)(\.gitattributes|\.gitmodules)$/, 'Git behaviour'],
  [/(^|\/)(AGENTS\.md|CLAUDE\.md|\.cursorrules|\.cursor\/|\.github\/copilot-instructions\.md)/, 'instructions future agent runs will read'],
  [/(^|\/)(package\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|requirements[^/]*\.txt|pyproject\.toml|poetry\.lock|go\.mod|go\.sum|Cargo\.toml|Cargo\.lock)$/, 'dependencies'],
  [/(^|\/)(Dockerfile|Makefile|[^/]*\.sh)$/, 'build or shell scripts'],
];

function git(repo: string, args: string[]): string {
  return execFileSync('git', args, { cwd: repo, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
}

export function reviewPatch(repo: string, patchPath: string, limits = { maxFiles: 50, maxLines: 2000 }): PatchReview {
  const blocked: string[] = [];
  const needsHuman: string[] = [];

  // 1. Does it apply cleanly to the commit the sandbox started from? git also refuses
  //    paths inside .git and paths that climb out of the repository here.
  try {
    git(repo, ['apply', '--check', '--index', patchPath]);
  } catch (e) {
    return { files: [], blocked: [`does not apply: ${(e as Error).message.split('\n')[0]}`], needsHuman };
  }

  // 2. Which files, and how much. -z keeps unusual file names intact.
  const fields = git(repo, ['apply', '--numstat', '-z', patchPath]).split('\0');
  const files: PatchFile[] = [];
  for (const field of fields.slice(0, -1)) {
    const [added, deleted, path] = field.split('\t');
    files.push({
      path,
      added: added === '-' ? null : Number(added),
      deleted: deleted === '-' ? null : Number(deleted),
    });
  }

  // 3. File modes: symlinks and submodules are refused, new executables need a person.
  //    Renames are refused too: the sandbox makes the patch with --no-renames, so a rename
  //    arrives as a delete plus an add and both paths go through the checks below.
  for (const line of git(repo, ['apply', '--summary', patchPath]).split('\n')) {
    if (/^ (rename|copy) /.test(line)) blocked.push(`rename or copy: ${line.trim()}`);
    const mode = line.match(/(?:create|delete) mode (\d{6}) |mode change \d{6} => (\d{6}) /);
    const m = mode?.[1] ?? mode?.[2];
    if (m && BLOCKED_MODES.has(m)) blocked.push(`mode ${m}: ${line.trim()}`);
    else if (m === '100755') needsHuman.push(`executable: ${line.trim()}`);
  }

  // 4. Size, binaries and sensitive paths.
  if (files.length > limits.maxFiles) blocked.push(`${files.length} files changed (limit ${limits.maxFiles})`);
  const lines = files.reduce((n, f) => n + (f.added ?? 0) + (f.deleted ?? 0), 0);
  if (lines > limits.maxLines) blocked.push(`${lines} lines changed (limit ${limits.maxLines})`);
  for (const f of files) {
    if (f.added === null) needsHuman.push(`binary file: ${f.path}`);
    for (const [re, why] of NEEDS_HUMAN) if (re.test(f.path)) needsHuman.push(`${why}: ${f.path}`);
  }
  return { files, blocked, needsHuman };
}
```

## What the check refuses, and why

**Anything that does not apply cleanly to the base.** `git apply --check` is the first gate. As a side effect it also refuses paths inside `.git` and paths that climb out of the repository, such as `../evil`: Git reports those as invalid paths. That matters, because a patch is free text and can name any path it likes.

**Symlinks and submodules.** A symlink in a patch can point anywhere, including at files outside the repository that a later step reads or writes. A submodule entry points the repository at another repository. Neither is something an agent should introduce without a person deciding to. The check reads file modes from `git apply --summary` and refuses `120000` (symlink) and `160000` (submodule).

**Renames and copies.** Because the sandbox was asked for `--no-renames`, a rename in the patch means the patch did not come from the command you ran. Refusing it is cheap and keeps the path list complete.

**Oversized diffs.** The limits here, 50 files and 2,000 changed lines, are examples. Pick numbers from the tasks you give the agent. A task to fix one failing test that comes back touching 300 files is a run to look at, not to merge.

## What the check flags for a person

Flags do not stop the patch from becoming a pull request. They go into its description and decide which reviewers are required.

- **CI configuration.** A changed workflow runs with your CI’s permissions on the next push. This is the single most important file class to keep out of automatic merges.
- **Hooks and hook managers.** `.husky/`, `.githooks/` and `.pre-commit-config.yaml` run on developers’ machines.
- **Dependency manifests and lockfiles.** A new package is new code from a stranger. Our post on [supply chain risk when agents install packages](https://sandscale.dev/blog/supply-chain-risk-when-agents-install-packages) covers what to look for.
- **Agent instruction files.** `AGENTS.md`, `CLAUDE.md`, `.cursorrules`, `.cursor/` and `.github/copilot-instructions.md` are read by the next agent run. An agent that edits them is writing instructions for its successors, which is exactly the persistence a prompt injection wants.
- **New executables, binaries and shell scripts.** A binary cannot be reviewed as a diff at all, and a new executable bit is easy to miss in a review tool.

Keep the list next to your [code review checklist for agent diffs](https://sandscale.dev/blog/reviewing-an-agent-diff-checklist) so the automated flags and the human checklist agree.

## Applying it

If nothing is blocked, apply and commit in the clean checkout, with an identity that says an agent wrote it:

```sh
git checkout -b "agent/$TASK_ID" "$BASE"
git apply --index agent.patch
git commit -m "Agent change for $TASK_ID" -m "Agent-Run: $RUN_ID"
git push origin "agent/$TASK_ID"
```

Then open the pull request with the `needsHuman` reasons in its body. Two details are worth keeping:

- **Do not run the patch on your side.** Applying it is safe; running its tests, its install scripts or its build on your CI runner before review is not. Run them in a sandbox instead, as in [running an agent PR’s tests in a sandbox from GitHub Actions](https://sandscale.dev/blog/github-actions-run-agent-pr-tests-in-sandbox).
- **Tell the model what happened.** When a patch is refused, return the reasons to the agent as the tool result, for example “refused: creates a symlink at link”. A specific reason lets it fix the change; a bare failure invites it to try something stranger.

## Where Sandscale fits

A Sandscale sandbox is a Firecracker microVM with its own kernel, and its network mode defaults to `none`, so with the default settings, reading files back through the API is how the agent’s work leaves the box. The sandbox never needs a push credential, the commands you run in it and the files you move in and out are written to the [audit log](https://sandscale.dev/security/audit-log), and the patch you read back with `readFile` is what crosses the boundary. The check in this post is yours to own; the sandbox keeps it the place where changes come through.

**On this page**

1. Why a patch and not a push
2. Making the patch inside the sandbox
3. Checking the patch on your side
4. What the check refuses, and why
5. What the check flags for a person
6. Applying it
7. Where Sandscale fits

**Run your agents in a box of their own**

Each sandbox is a Firecracker microVM. Free includes 100 awake vCPU-hours a month.

[Start free](https://cloud.sandscale.dev/auth/signup)

## Keep reading

- [November 26, 2026 · **30 questions to ask any agent sandbox provider before you sign up** · A vendor-neutral checklist for choosing where your agents run code: isolation, network, secrets, lifecycle, billing for waiting time, governance, data location, reliability and leaving. With where to find each answer for Sandscale.](https://sandscale.dev/blog/questions-to-ask-an-agent-sandbox-provider)
- [November 26, 2026 · **Agent sandbox glossary: 41 terms in plain English** · Plain definitions for the words that come up when you run AI agent code in isolation: microVM, VMM, KVM, jailer, gVisor, seccomp, namespaces, egress allowlist, lease, snapshot, warm pool, awake vCPU-hour and more.](https://sandscale.dev/blog/agent-sandbox-glossary)

---
Source: https://sandscale.dev/blog/checking-an-agent-patch-before-applying
