From 0666aff4a4e991ed3709d4570788f90dfa37354b Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Tue, 1 Dec 2026 09:14:24 +0000 Subject: [PATCH] fix(workspaces): clone network repositories blobless in remote sandboxes (#23347) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A Paperclip Runner task in a Cloud sandbox gets a fresh workspace: the server clones the task's repositories into the sandbox before the agent starts > - The clone is a full clone, so it downloads every historical blob. A full clone of `paperclipai/paperclip` now grows the disk by about 856 MiB > - The Cloud sandbox wraps Git in a storage guard. The guard stops one Git command when the net disk growth gets to 1 GiB, and the growth includes other writers on the same disk > - On hosted staging, the clone now stops with `stage=clone disk=full git=storage_limit exit=75`. Paperclip records `sandbox_disk_full`, the run fails during setup, and the task does not start. This happens more frequently as the repository history grows > - This pull request makes a fresh clone from a network remote blobless (`--filter=blob:none`). The clone gets all commits and trees, but only the file contents that the checkout needs > - Agent commands that the managed GitHub launcher treats as local (`git show`, `git blame`, `git log -p`, checkout) do not ask the credential broker. In a blobless clone they can need to fetch an old blob, which fails for a private repository without credentials. So the launcher now gives these commands the broker credential on demand, at most once per command > - The benefit is that the same clone grows the disk by about 409 MiB and takes less than half the time, so large repositories start again in Cloud sandboxes ## Linked Issues or Issue Description Refs #22848 (classifies the Git storage guard refusal during clone as a full sandbox disk; this PR removes the cause of that refusal for large histories) Refs #22837 (moves a restore off a full reused sandbox; the clone path in this PR is a fresh sandbox, so a new sandbox does not help) **What happened?** On hosted staging, Paperclip Runner runs fail before the agent starts. The run error is `remote_workspace_operation_failed: operation=prepare exit=1; remote_workspace_prepare_failed: stage=clone disk=full git=storage_limit exit=75 program=git` (and the same refusal with `operation=repository` for a secondary repository). The error code is `sandbox_disk_full`. Between 2026-11-27 and 2026-11-30 there were 20 such failures for three different agents. The tasks used fresh workspaces for `paperclipai/paperclip` with `paperclipai/paperclip-cloud` as a secondary repository. **Expected behavior** A fresh sandbox workspace for a large repository starts without hitting the sandbox Git storage budget. **Steps to reproduce** 1. Run `git clone --no-hardlinks https://github.com/paperclipai/paperclip.git` and measure the disk growth. I measured 856 MiB (39 s). 2. Compare with the Cloud sandbox Git storage guard budget: it stops one Git command at 1 GiB of net disk growth, and it counts other writers on the same disk. 3. Run the same clone with `--filter=blob:none`. I measured 409 MiB (17 s). **Paperclip version or commit** `master` at `c737187ec7`. The hosted staging failures were on releases `635ed5a364`, `c49e80da6c`, `629281b1e8`, `e55b475f30` and `bc98abda0c`. **Deployment mode** Hosted Cloud, Paperclip Runner with remote sandbox workspaces. ## What Changed - `server/src/services/remote-workspace-transport.ts`: - The primary workspace clone (`prepareRemoteWorkspaceDirectory`) and the secondary repository clone (`prepareRemoteRepository`) add `--filter=blob:none` when the repository URL is a network remote (`https`, `http`, `ssh`, `git`, or `user@host:path`). - The staged checkout steps after the clone (`checkout_branch`, `checkout_ref`) use the clone's credentials. Checkout of a revision other than the default branch can fetch missing blobs from the origin. Without credentials, that fetch fails for a private repository. The checks after publication still run without credentials. - A local path or `file://` origin stays a full clone. A saved workspace keeps only a promisor remote whose URL works on another machine, so a partial clone of a local origin cannot be saved. - A server that does not support filters ignores the filter and sends a full clone, so the old behavior stays available. - `server/src/services/remote-workspace-transport.test.ts`: a real-subprocess regression with a history-only blob and an origin that is reachable only through the clone credentials. It checks the blobless clone, the fetch of an older revision's files with credentials, the full clone of a local origin, and a save and restore of the blobless clone after the origin is removed. - `packages/adapter-utils/src/github-launcher.ts` (managed `git`/`gh` launcher): a local `git` command (one that does not ask the broker since #17886) now runs with the launcher as `GIT_ASKPASS`, when the launcher has a broker capability and is not anonymous. - Git calls askpass only after every credential helper declines, for example on a lazy fetch of a missing blob from a private repository. Askpass was not used before, so a lazy fetch failed with `could not read Username for 'https://github.com'`. - The launcher answers only prompts for `https://github.com` and `https://www.github.com`. It answers `x-access-token` for the username without the broker. For the password, it asks the broker. - The command's launcher keeps the first broker answer in memory and serves later prompts through a Unix socket in a private (`0700`) temporary directory. So one command asks the broker at most once, however many objects Git fetches. A command that fetches nothing does not ask the broker, as before. If the socket cannot be created, each prompt asks the broker itself. - The recursion guard still rejects every launcher invocation inside an operation, except an askpass prompt inside a local operation (which holds no credential). - I used askpass instead of a URL-scoped `credential.helper`, because a Git wrapper that adds its own `credential..helper` reset (as the Paperclip tools Git bundle does through `-c include.path`) is applied after the launcher's `GIT_CONFIG_*` entries and would remove the helper. `GIT_ASKPASS` takes priority over any `core.askPass` configuration. - `packages/adapter-utils/src/github-launcher.test.ts`: launcher tests with real Git. A local command runs `git credential fill` three times for a GitHub URL. The test checks that the managed token is returned with one broker request, that `git status` makes no request, that another host gets no answer and no request, and both broker modes (inherited URL and broker file). A second test checks that askpass is set only for local commands of a connected, non-anonymous launcher, and that the recursion guard still rejects other re-entries. - `doc/workspace-storage.md`: a note about the blobless clone. `doc/execution-github-identity.md`: the askpass behavior for local commands. ## Verification - Red: on the unfixed code, the new test fails because the clone downloads the history-only blob (`expected [] to include ''`). - A second red: with the filter but without credentials for the checkout steps, the test fails with `stage=checkout_ref git=network exit=128`. This proves that the test also covers the private-repository case. - Green: `pnpm --filter @paperclipai/server exec vitest run src/services/remote-workspace-transport.test.ts src/services/remote-workspace-readonly-capture-cause.test.ts src/services/remote-workspace-readonly-inventory-git-guard.test.ts src/services/remote-workspace-restore-disk-full.test.ts` passes (201 tests). - `src/services/remote-workspaces.integration.test.ts`, `remote-workspace-lifecycle.test.ts` and `remote-workspace-migration.test.ts` pass (347 passed, 16 skipped; the integration file skips locally). - `pnpm --filter @paperclipai/server typecheck` passes. - Launcher, red/green: without the launcher change, the 3 new launcher tests fail. With it, `src/github-launcher.test.ts` passes (44 tests). `github-launcher.test.ts`, `github-launcher-environment.test.ts` and `sandbox-callback-bridge.test.ts` in adapter-utils pass (175 tests). `packages/paperclip-runner` `src/drivers/acpx/github-launcher.test.ts` (3) and server `heartbeat-github-launchers.test.ts` (12) pass. `tsc --noEmit` passes in `packages/adapter-utils`. - Launcher, real private repository: I made a blobless clone of a private GitHub repository and ran the generated launcher with a local fake broker that returned a real GitHub token. With the old launcher, `git show :README.md` failed with `could not read Username for 'https://github.com': terminal prompts disabled` / `could not fetch from promisor remote`. With the new launcher, it printed the file with 1 broker request. On a fresh blobless clone, `git log -p -40 -- README.md` (about 150 lazy fetches in the trace) made 1 broker request, and `git status` made 0. - Measurement on a Linux host: a full clone of `paperclipai/paperclip` grows the disk by 856 MiB; a blobless clone grows it by 409 MiB. - Not run: a live Cloud sandbox run. Hosted staging gets this change through the normal automatic deployment. After that deployment, the Sentry case gets a check that new fresh workspaces for this repository start without the refusal. - Local environment note: the tests rewrite the remote URL through `GIT_CONFIG_COUNT`. A Git wrapper first on `PATH` that sets its own `GIT_CONFIG_COUNT` makes the rewrite tests fail, also on `master`. I ran the tests with the system Git first on `PATH`. ## Risks - A blobless clone fetches file contents from the origin when an agent command needs old blobs (for example `git log -p`, `git blame`, or a checkout of another branch). These commands need network access and the run's Git credentials, the same as `git fetch`. The launcher now supplies the credential on demand (one broker request per command that needs it). The Cloud Git storage guard already measures these lazy downloads. - While a local `git` command runs, a process of the same user can read the password from the askpass socket. That user can already get the token with `gh auth token`, so this adds no new access. The token is not written to disk. - A saved workspace of a blobless clone keeps its promisor remote. The existing snapshot capture and restore support this. The new test proves a save and restore after the origin is removed. - Medium-low risk: the clone of a repository on a server without filter support is unchanged (Git ignores the filter). ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use (shell, 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 - [ ] 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 --- doc/execution-github-identity.md | 2 + doc/workspace-storage.md | 9 ++ .../adapter-utils/src/github-launcher.test.ts | 96 +++++++++++++++++- packages/adapter-utils/src/github-launcher.ts | 98 ++++++++++++++++++- .../remote-workspace-transport.test.ts | 67 +++++++++++++ .../services/remote-workspace-transport.ts | 32 ++++-- 6 files changed, 293 insertions(+), 11 deletions(-) diff --git a/doc/execution-github-identity.md b/doc/execution-github-identity.md index 945e7427809..10786facda0 100644 --- a/doc/execution-github-identity.md +++ b/doc/execution-github-identity.md @@ -48,6 +48,8 @@ security boundary: any command that receives the token can call the GitHub API. A `git` command that never uses the network does not ask the broker. The launcher reads past the global options, such as `-C` and `-c`, and checks the subcommand against a short list (for example `status`, `diff`, `diff-files`, `write-tree`, `log`, `rev-parse`, `add`, `config`, `branch`, `checkout`). This includes the index comparison and tree writing used by workspace snapshots. An unknown subcommand or option still asks. `commit` and `var` still ask, because the managed author comes from the broker answer. The launcher keeps no broker answer between invocations and never writes a credential to a file. +A local command can still need GitHub. In a partial (blobless) clone, `git show`, `git blame`, `git log -p` and a checkout of another revision fetch the file contents they need from the origin. For a local `git` command, the launcher sets itself as `GIT_ASKPASS`. Git calls askpass only after every credential helper declines. The launcher answers only for `https://github.com` and `https://www.github.com`. It asks the broker on the first password prompt and keeps that answer in memory for the rest of the command, so one command asks the broker at most once. A command that fetches nothing does not ask the broker. Askpass prompts reach the command's launcher through a Unix socket in a private temporary directory. If that socket cannot be created, each prompt asks the broker itself. Anonymous launchers and launchers without a broker capability do not set askpass. + GitHub credential capture reads the current task, project, and retained trust policy bindings without transferring saved prompts, runner profiles, results, or log excerpts. It keeps the existing task/run lock order and accepted-identity diff --git a/doc/workspace-storage.md b/doc/workspace-storage.md index 92dc535f532..a34af183503 100644 --- a/doc/workspace-storage.md +++ b/doc/workspace-storage.md @@ -111,6 +111,15 @@ precedence over the stored choice. Enrolled workspaces retain remote authority when enrollment is disabled; losing a storage prerequisite fails their admission instead of falling back to a controller checkout. +A fresh sandbox clone of a network Git remote (`https`, `http`, `ssh`, `git`, or +`user@host:path`) is a blobless partial clone (`--filter=blob:none`). It holds all +commits and trees but only the file contents that its checkout needs, so a large +history does not use the sandbox's per-command Git storage budget. Git fetches +other file contents from the origin when a command needs them. Agent commands +get the run's GitHub credential for these fetches through the managed launcher +(see `doc/execution-github-identity.md`). Snapshots keep the promisor remote. A local path or `file://` +origin is cloned in full, because a snapshot cannot keep a machine-local promisor. + After enrollment, roll back only to binaries that understand the same remote workspace authority and saved-version format. Older local-only binaries are unsupported rollback targets. diff --git a/packages/adapter-utils/src/github-launcher.test.ts b/packages/adapter-utils/src/github-launcher.test.ts index 4bf744b0ece..99975e2370f 100644 --- a/packages/adapter-utils/src/github-launcher.test.ts +++ b/packages/adapter-utils/src/github-launcher.test.ts @@ -1,6 +1,6 @@ import { execFile } from "node:child_process"; import { createServer } from "node:http"; -import { mkdtemp, mkdir, readFile, writeFile, rm } from "node:fs/promises"; +import { mkdtemp, mkdir, readFile, realpath, writeFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; @@ -411,6 +411,100 @@ process.stdout.write(JSON.stringify({identity, token:process.env.GH_TOKEN ?? nul expect((await git("-C", "repo", "commit", "--allow-empty", "-m", "Managed work")).posts).toBe(1); expect((await git("-C", "repo", "log", "-1", "--format=%an <%ae>")).stdout).toBe("Managed "); }, 20_000); + it.each([false, true])("lets a local git command fetch a private object with the managed credential only when Git asks (broker file: %s)", async brokerFile => { + const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-lazy-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + // Git runs GIT_ASKPASS without a shell, so a quote and space in the path are safe. + const bin = path.join(root, "it's managed"), realBin = path.join(root, "real"); + await mkdir(bin); await mkdir(realBin); + const realGit = (await exec("sh", ["-c", "command -v git"])).stdout.trim(); + // Stands in for partial-clone lazy fetches: each one makes the real Git + // child ask for credentials for a URL. Other commands run real Git. + await writeFile(path.join(realBin, "git"), `#!${process.execPath} +const {spawnSync} = require("node:child_process"); +const args = process.argv.slice(2); +if (args[0] === "show") { + const host = args[1] || "github.com"; + const fetches = Array.from({length: Number(args[2] || 1)}, () => spawnSync(${JSON.stringify(realGit)}, ["credential", "fill"], {env: process.env, + input: "protocol=https\\nhost=" + host + "\\npath=org/private.git\\n\\n", encoding: "utf8"})); + process.stdout.write(JSON.stringify({status: Math.max(...fetches.map(result => result.status)), stdout: fetches.map(result => result.stdout), + operation: process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE, token: process.env.PAPERCLIP_GIT_TOKEN ?? null})); + process.exit(0); +} +process.exit(spawnSync(${JSON.stringify(realGit)}, args, {stdio: "inherit"}).status ?? 1); +`, { mode: 0o700 }); + await writeFile(path.join(bin, "git"), githubLauncherSource({ brokerFile }), { mode: 0o700 }); + let posts = 0; + const server = createServer((_req, res) => { + posts++; + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ status: "available", env: { PAPERCLIP_GIT_TOKEN: "managed-token", GH_TOKEN: "managed-token" } })); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + cleanups.push(() => new Promise(resolve => server.close(() => resolve()))); + const { port } = server.address() as { port: number }; + const broker = { url: `http://127.0.0.1:${port}`, token: "run-capability" }; + if (brokerFile) await writeFile(path.join(bin, "broker.json"), JSON.stringify(broker), { mode: 0o600 }); + const env = { ...process.env, ...githubBrokerEnvironment({}, brokerFile ? { url: "", token: "" } : broker), + GH_CONFIG_DIR: path.join(root, "config"), PATH: `${bin}${path.delimiter}${realBin}${path.delimiter}${process.env.PATH}` }; + const git = async (...args: string[]) => (await exec(path.join(bin, "git"), args, { cwd: root, env, timeout: 10_000 })).stdout; + + await exec(realGit, ["init", "-q", root]); + await git("status", "--porcelain"); + expect(posts).toBe(0); + + // One operation asks the broker once, however many objects it fetches. + const fetched = JSON.parse(await git("show", "github.com", "3")); + expect(fetched).toMatchObject({ status: 0, operation: "local", token: null }); + expect(fetched.stdout).toEqual(Array(3).fill("protocol=https\nhost=github.com\nusername=x-access-token\npassword=managed-token\n")); + expect(posts).toBe(1); + expect(JSON.parse(await git("show")).stdout).toEqual(["protocol=https\nhost=github.com\nusername=x-access-token\npassword=managed-token\n"]); + expect(posts).toBe(2); + + // Another host gets no answer and causes no broker request. + const other = JSON.parse(await git("show", "example.test")); + expect(other.status).not.toBe(0); + expect(other.stdout).toEqual([""]); + expect(posts).toBe(2); + await expect(exec(path.join(bin, "git"), ["Password for 'https://x-access-token@github.com.example.test': "], + { env: { ...env, PAPERCLIP_GITHUB_OPERATION_ACTIVE: "local" } })).rejects.toMatchObject({ code: 1, stdout: "" }); + expect(posts).toBe(2); + }, 20_000); + + it("gives Git the launcher as askpass only for local commands of a connected launcher", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-lazy-scope-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const bin = path.join(root, "managed"), anonymousBin = path.join(root, "anonymous"), realBin = path.join(root, "real"); + await mkdir(bin); await mkdir(anonymousBin); await mkdir(realBin); + await writeFile(path.join(bin, "git"), githubLauncherSource(), { mode: 0o700 }); + await writeFile(path.join(anonymousBin, "git"), githubLauncherSource({ anonymous: true }), { mode: 0o700 }); + await writeFile(path.join(realBin, "git"), `#!${process.execPath} +process.stdout.write(JSON.stringify({askpass: process.env.GIT_ASKPASS ?? null, operation: process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE})); +`, { mode: 0o700 }); + const server = createServer((_req, res) => { + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ status: "available", env: { PAPERCLIP_GIT_TOKEN: "managed-token" } })); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + cleanups.push(() => new Promise(resolve => server.close(() => resolve()))); + const { port } = server.address() as { port: number }; + const base = { ...process.env, ...githubBrokerEnvironment({}, { url: `http://127.0.0.1:${port}`, token: "run-capability" }) }; + const run = async (launcherBin: string, args: string[], extra: Record = {}) => JSON.parse((await exec( + path.join(launcherBin, "git"), args, { cwd: root, env: { ...base, ...extra, + PATH: `${launcherBin}${path.delimiter}${realBin}${path.delimiter}${process.env.PATH}` } })).stdout); + expect(await run(bin, ["show"])).toEqual({ askpass: path.join(await realpath(bin), "git"), operation: "local" }); + expect(await run(bin, ["fetch"])).toEqual({ askpass: null, operation: "1" }); + expect(await run(anonymousBin, ["show"])).toEqual({ askpass: null, operation: "local" }); + expect(await run(bin, ["show"], { PAPERCLIP_GITHUB_BROKER_TOKEN: "" })).toEqual({ askpass: null, operation: "local" }); + // Only a prompt inside a local operation, which holds no credential, may run the launcher again. + for (const [operation, args] of [["1", ["Password for 'https://x-access-token@github.com': "]], ["local", ["show"]], + ["local", ["Password for 'https://github.com': ", "extra"]]] as const) { + await expect(exec(path.join(bin, "git"), [...args], { env: { ...base, PAPERCLIP_GITHUB_OPERATION_ACTIVE: operation, + PATH: `${bin}${path.delimiter}${realBin}${path.delimiter}${process.env.PATH}` } })) + .rejects.toMatchObject({ code: 126, stderr: expect.stringContaining("launcher_recursion_rejected") }); + } + }); + }); it("captures the current task broker file once per invocation and never falls back to inherited authority", async () => { diff --git a/packages/adapter-utils/src/github-launcher.ts b/packages/adapter-utils/src/github-launcher.ts index 68f6d682535..8c549981cce 100644 --- a/packages/adapter-utils/src/github-launcher.ts +++ b/packages/adapter-utils/src/github-launcher.ts @@ -16,9 +16,19 @@ const fs = require('node:fs'); const path = require('node:path'); const os = require('node:os'); const { spawn } = require('node:child_process'); +// A local git command runs with this launcher as GIT_ASKPASS. Git asks it only +// when no credential helper answers a request, for example when it fetches a +// blob that a blobless clone left at a private origin. Git passes one prompt. +const askpassPrompt = process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE === 'local' && process.argv.length === 3 + ? /^(Username|Password) for '([^']+)': $/.exec(process.argv[2]) : null; +// Only GitHub over HTTPS gets an answer. A GitHub username needs no broker answer. +const askpassUrl = askpassPrompt ? (() => { try { return new URL(askpassPrompt[2]); } catch { return null; } })() : null; +const askpassGitHub = Boolean(askpassUrl && askpassUrl.protocol === 'https:' + && ['github.com', 'www.github.com'].includes(askpassUrl.hostname) && !askpassUrl.port); // A PATH shim can capture this launcher's absolute path and call it again. // Reject that cycle before resolving another executable or capturing authority. -if (process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE) { +// Only a prompt from a local operation, which holds no credential, may continue. +if (process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE && !askpassPrompt) { process.stderr.write('Paperclip: GitHub launcher_recursion_rejected.\n'); process.exit(126); } @@ -57,7 +67,29 @@ function connectorRepositoryTool(args) { if (program !== 'gh' || args[0] !== 'repo' || args.includes('--help') || args.includes('-h')) return null; return connectorRepositoryTools.get(args[1]) || null; } +// The local operation that set GIT_ASKPASS serves its password, so one +// operation asks the broker at most once however many objects Git fetches. +function askOperation(socketPath) { + return new Promise(resolve => { + let answer = ''; + const socket = require('node:net').connect(socketPath, () => socket.end('password')); + socket.setEncoding('utf8'); + socket.on('data', chunk => { answer += chunk; }); + socket.once('error', () => resolve(null)); + socket.once('close', hadError => { if (!hadError) resolve(answer); }); + }); +} async function main() { + if (askpassPrompt) { + if (!askpassGitHub) { process.exitCode = 1; return; } + if (askpassPrompt[1] === 'Username') { process.stdout.write('x-access-token\n'); return; } + const answer = process.env.PAPERCLIP_GITHUB_ASKPASS_SOCKET ? await askOperation(process.env.PAPERCLIP_GITHUB_ASKPASS_SOCKET) : null; + if (answer !== null) { + if (answer && !/[\r\n]/.test(answer)) process.stdout.write(answer + '\n'); + else process.exitCode = 1; + return; + } + } let env = { ...process.env }; const anonymousLauncher = ${anonymousLauncher ? 'true' : 'false'}; let brokerAnonymous = false; @@ -92,6 +124,8 @@ ${options.brokerFile ? String.raw` `} const diagnostic = (code) => process.stderr.write('Paperclip: GitHub ' + code + '; continuing without managed credentials.\n'); let connected = false; + let localOperation = false; + let closeAskpass = () => {}; const configRoot = env.GH_CONFIG_DIR || os.tmpdir(); // A missing/unwritable scratch directory must not break local Git. The // fallback deliberately cannot load the host's gh authentication files. @@ -122,7 +156,55 @@ ${options.brokerFile ? String.raw` GIT_CONFIG_KEY_4: 'user.useConfigOnly', GIT_CONFIG_VALUE_4: 'true', }); const base = env.PAPERCLIP_GITHUB_BROKER_URL || env.PAPERCLIP_API_URL; - const askBroker = !anonymousLauncher && !brokerAnonymous && !isLocalCommand(process.argv.slice(2)); + const brokerAllowed = !anonymousLauncher && !brokerAnonymous; + localOperation = !askpassPrompt && isLocalCommand(process.argv.slice(2)); + const askBroker = brokerAllowed && !localOperation; + // A local command asks no broker. It can still need GitHub when it reads an + // object that a partial clone did not download, so Git can ask the broker + // through this launcher then. Git runs GIT_ASKPASS directly, without a shell. + delete env.PAPERCLIP_GITHUB_ASKPASS_SOCKET; + if (localOperation && program === 'git' && brokerAllowed && base && env.PAPERCLIP_GITHUB_BROKER_TOKEN) { + const launcher = env.GIT_ASKPASS = fs.realpathSync(process.argv[1]); + // The first password prompt runs this launcher once more to ask the broker. + // Later prompts reuse that answer, which stays in this process's memory. + // Without the socket, each prompt asks the broker itself. + let password = null; + const askBrokerOnce = () => password || (password = new Promise(resolve => { + const request = spawn(launcher, ["Password for 'https://github.com': "], { env: { ...env, + PAPERCLIP_GITHUB_OPERATION_ACTIVE: 'local', PAPERCLIP_GITHUB_ASKPASS_SOCKET: '' }, stdio: ['ignore', 'pipe', 'inherit'] }); + let output = ''; + request.stdout.setEncoding('utf8'); + request.stdout.on('data', chunk => { output += chunk; }); + request.once('error', () => resolve('')); + request.once('close', code => resolve(code === 0 ? output.trim() : '')); + })); + const server = require('node:net').createServer({ allowHalfOpen: true }, socket => { + let request = ''; + socket.setEncoding('utf8'); + socket.on('error', () => {}); + socket.on('data', chunk => { request += chunk; if (request.length > 64) socket.destroy(); }); + socket.on('end', () => { + if (request !== 'password') { socket.end(); return; } + askBrokerOnce().then(answer => socket.end(answer)); + }); + }); + // A socket path has a limit of about 100 bytes, and the launcher directory + // can use most of that. So the socket gets its own private temporary directory. + let socketPath = null; + try { + const socketDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'paperclip-askpass-')); + process.once('exit', () => { try { fs.rmSync(socketDirectory, { recursive: true, force: true }); } catch {} }); + socketPath = path.join(socketDirectory, 'socket'); + } catch {} + if (socketPath && await new Promise(resolve => { + server.once('error', () => resolve(false)); + server.listen(socketPath, () => resolve(true)); + })) { + server.unref(); + env.PAPERCLIP_GITHUB_ASKPASS_SOCKET = socketPath; + closeAskpass = () => server.close(); + } + } try { let response; if (askBroker && base && env.PAPERCLIP_GITHUB_BROKER_TOKEN) { @@ -189,6 +271,13 @@ ${options.brokerFile ? String.raw` } else if (askBroker) { diagnostic('capability_missing'); } } catch { diagnostic('broker_transport_unavailable'); } } + if (askpassPrompt) { + // Without an answer, Git fails as it did before. + const token = connected ? env.PAPERCLIP_GIT_TOKEN : ''; + if (token && !/[\r\n]/.test(token)) process.stdout.write(token + '\n'); + else process.exitCode = 1; + return; + } const connectorTool = connected ? connectorRepositoryTool(process.argv.slice(2)) : null; if (connectorTool) { process.stderr.write("Paperclip: use the GitHub connection's " + connectorTool + " tool instead of gh repo " + process.argv[3] + @@ -198,7 +287,8 @@ ${options.brokerFile ? String.raw` return; } // Only this invocation and its children inherit the captured credential. - env.PAPERCLIP_GITHUB_OPERATION_ACTIVE = '1'; + // A local operation holds none, so only its askpass prompts may run the launcher again. + env.PAPERCLIP_GITHUB_OPERATION_ACTIVE = localOperation ? 'local' : '1'; // Its Git children use the real binary, so steering cannot split a gh operation. env.PATH = originalPath.join(path.delimiter); // Nested shell aliases must not reload the parent launcher profile and @@ -209,7 +299,7 @@ ${options.brokerFile ? String.raw` const child = spawn(executable, process.argv.slice(2), { env, stdio: 'inherit' }); for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => child.kill(signal)); child.once('error', () => { process.stderr.write('Paperclip: GitHub command could not start.\n'); process.exitCode = 1; }); - child.once('exit', (code, signal) => { process.exitCode = code === null ? 128 : code; }); + child.once('exit', (code, signal) => { closeAskpass(); process.exitCode = code === null ? 128 : code; }); } main().catch(() => { process.stderr.write('Paperclip: GitHub launcher_setup_failed.\n'); process.exitCode = 1; }); `; diff --git a/server/src/services/remote-workspace-transport.test.ts b/server/src/services/remote-workspace-transport.test.ts index 3c59aa97cc1..056eec604d4 100644 --- a/server/src/services/remote-workspace-transport.test.ts +++ b/server/src/services/remote-workspace-transport.test.ts @@ -2289,4 +2289,71 @@ return result};`); ref: "HEAD~1", pinnedCommit: receipt.pinnedCommit, resolveGitAuth: unavailableAuth })).resolves.toEqual(receipt); expect(unavailableAuth).not.toHaveBeenCalled(); }); + + it("clones without history-only blobs and fetches an older revision's files with the clone credentials", async () => { + // A full clone downloads every historical blob. In a Cloud sandbox that alone + // can spend Git's per-command storage budget, so the clone fails with a full disk. + const origin = await repository({ revisions: true }); + await fs.writeFile(path.join(origin, "history-only.bin"), randomBytes(64 * 1024)); + await git(origin, "add", "history-only.bin"); + await git(origin, "commit", "-m", "History-only blob"); + const historyBlob = (await git(origin, "rev-parse", "HEAD:history-only.bin")).stdout.trim(); + await git(origin, "rm", "-q", "history-only.bin"); + await git(origin, "commit", "-m", "Remove history-only blob"); + await git(origin, "config", "uploadpack.allowFilter", "true"); + // The origin is reachable only through the credential rewrite, like a private repository. + const remoteUrl = "ssh://git@127.0.0.1:1/synthetic-partial-repository"; + const resolveGitAuth = async () => ({ configArgs: [], env: { GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: `url.${pathToFileURL(origin).href}.insteadOf`, GIT_CONFIG_VALUE_0: remoteUrl }, + source: "company_secret" as const, secretName: "SYNTHETIC_FIXTURE" }); + const { remote } = target(); + const missingObjects = async (repo: string) => (await git(repo, "rev-list", "--objects", "--missing=print", "--all")) + .stdout.split("\n").filter(line => line.startsWith("?")).map(line => line.slice(1)); + + const root = path.join(workspace, "partial-root"); + await prepareRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, preparationIdentity: "b".repeat(64), + source: { kind: "git", repoUrl: remoteUrl, ref: "HEAD" }, resolveGitAuth }); + expect(await missingObjects(root)).toContain(historyBlob); + expect((await git(root, "config", "--get", "remote.origin.promisor")).stdout.trim()).toBe("true"); + await expect(fs.access(path.join(root, "history-only.bin"))).rejects.toThrow(); + + // An older configured revision needs a blob the clone left on the server. + const older = path.join(workspace, "partial-older-root"); + await prepareRemoteWorkspaceDirectory({ target: remote, remoteCwd: older, preparationIdentity: "c".repeat(64), + source: { kind: "git", repoUrl: remoteUrl, ref: "HEAD~1" }, resolveGitAuth }); + expect((await fs.readFile(path.join(older, "history-only.bin"))).length).toBe(64 * 1024); + + const nested = path.join(workspace, "partial-repository"); + const receipt = await prepareRemoteRepository({ target: remote, remoteCwd: nested, repoUrl: remoteUrl, + ref: "HEAD~1", resolveGitAuth }); + expect((await fs.readFile(path.join(nested, "history-only.bin"))).length).toBe(64 * 1024); + expect((await git(nested, "config", "--get", "remote.origin.promisor")).stdout.trim()).toBe("true"); + expect(receipt.pinnedCommit).toMatch(/^[a-f0-9]{40}$/); + + // A local origin stays a full clone: a saved workspace cannot keep a promisor + // remote that only exists on this machine. + const local = path.join(workspace, "partial-local-origin"); + await prepareRemoteRepository({ target: remote, remoteCwd: local, repoUrl: pathToFileURL(origin).href, + ref: "HEAD", resolveGitAuth: async () => null }); + expect(await missingObjects(local)).toEqual([]); + await expect(git(local, "config", "--get", "remote.origin.promisor")).rejects.toThrow(); + + // The blobless clone is saved and restored with its promisor remote; the + // restore does not need the origin. + await fs.writeFile(path.join(root, "source.txt"), "agent edit in a blobless clone\n"); + const captured = await captureRemoteWorkspaceArchive({ target: remote, remoteCwd: root, operationId: randomUUID() }); + try { + await fs.rm(origin, { recursive: true }); + const restoredRoot = path.join(scratch, "partial-saved-root"); + const restored = await restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: restoredRoot, + archivePath: captured.archivePath, manifestDigest: captured.manifestDigest, restorationIdentity: "d".repeat(64) }); + await cleanupRemoteWorkspaceArchive({ target: remote, remoteCwd: restored.stagingRoot, operationId: restored.operationId }); + expect(await fs.readFile(path.join(restoredRoot, "source.txt"), "utf8")).toBe("agent edit in a blobless clone\n"); + expect((await git(restoredRoot, "config", "--get", "remote.origin.promisor")).stdout.trim()).toBe("true"); + expect((await git(restoredRoot, "config", "--get", "remote.origin.url")).stdout.trim()).toBe(remoteUrl); + expect(await missingObjects(restoredRoot)).toContain(historyBlob); + expect((await git(restoredRoot, "rev-parse", "HEAD")).stdout.trim()) + .toBe((await git(root, "rev-parse", "HEAD")).stdout.trim()); + } finally { await captured.cleanup(); } + }); }); diff --git a/server/src/services/remote-workspace-transport.ts b/server/src/services/remote-workspace-transport.ts index 6849043940c..45d2f3ecfaa 100644 --- a/server/src/services/remote-workspace-transport.ts +++ b/server/src/services/remote-workspace-transport.ts @@ -355,6 +355,25 @@ export async function removeRemoteRecoveryAttachment(input: { return output === "removed"; } +// A fresh clone from a network remote is blobless (--filter=blob:none): it gets +// every commit and tree, but only the file contents a checkout needs. A full +// clone also downloads every historical blob, which alone can exceed a Cloud +// sandbox's per-command Git storage budget. Checkout of another revision can +// fetch missing blobs, so the staged checkout steps use the clone's credentials. +// A server without filter support ignores the filter and sends a full clone. +// A local path or file:// origin is cloned in full: a saved workspace keeps +// only a promisor remote whose URL works on another machine. +function bloblessCloneSource(repoUrl: string): boolean { + if (!repoUrl || /[\u0000-\x20\u007f\\]/u.test(repoUrl)) return false; + if (/^[a-z][a-z0-9+.-]*:\/\//iu.test(repoUrl)) { + try { + const url = new URL(repoUrl); + return ["http:", "https:", "ssh:", "git:"].includes(url.protocol) && Boolean(url.hostname); + } catch { return false; } + } + return !/^[a-z]:[\/\\]/iu.test(repoUrl) && /^(?:[a-z0-9._-]+@)?(?:[a-z0-9._-]+|\[[a-f0-9:]+\]):[^\s]+$/iu.test(repoUrl); +} + const PREPARE = String.raw` const fs = require('node:fs/promises'), path = require('node:path'), cp = require('node:child_process'); const {promisify}=require('node:util'); const exec=promisify(cp.execFile); @@ -365,7 +384,6 @@ ${DISK_FULL_CHECK}${CAPTURE_FAILURE_CHECK}${SETUP_FAILURE_CHECK}let stage='valid const noConfig={GIT_TERMINAL_PROMPT:'0',GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_CONFIG_SYSTEM:'/dev/null',GIT_CONFIG_COUNT:'0',GIT_CONFIG_PARAMETERS:'',GIT_TEMPLATE_DIR:'',GIT_ASKPASS:'',SSH_ASKPASS:''}; const isolated={...process.env,...noConfig};for(const key of Object.keys(isolated))if(/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(key))delete isolated[key]; const cloneEnv={...isolated};for(const key of input.authEnvKeys)if(/^GIT_CONFIG_(COUNT|(KEY|VALUE)_\d+)$/.test(key)&&process.env[key]!==undefined)cloneEnv[key]=process.env[key]; - const localEnv={...isolated};for(const key of input.authEnvKeys)delete localEnv[key];Object.assign(localEnv,noConfig); stage='create_parent';let current='/'; for(const part of path.dirname(root).split('/').filter(Boolean)) { current=path.join(current,part); await fs.mkdir(current,{mode:0o700}).catch(e=>{if(e.code!=='EEXIST')throw e}); const s=await fs.lstat(current); if(!s.isDirectory()||s.isSymbolicLink())throw Error('unsafe_root'); @@ -383,8 +401,8 @@ ${DISK_FULL_CHECK}${CAPTURE_FAILURE_CHECK}${SETUP_FAILURE_CHECK}let stage='valid stage='stage';const staged=await fs.mkdtemp(root+'.preparing-');let published=false; try{ if(input.kind==='git'){ - stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks','--',input.repoUrl,staged],{env:cloneEnv}); - const git=async args=>exec('git',['-c','core.hooksPath=/dev/null','-C',staged,...args],{env:localEnv}); + stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks',...(input.blobless?['--filter=blob:none']:[]),'--',input.repoUrl,staged],{env:cloneEnv}); + const git=async args=>exec('git',['-c','core.hooksPath=/dev/null',...input.authArgs,'-C',staged,...args],{env:cloneEnv}); if(input.branchMode==='existing'){ stage='checkout_branch';if(!input.branchName)throw Error('existing_branch_required'); await git(['check-ref-format','--branch',input.branchName]); @@ -425,6 +443,7 @@ export async function prepareRemoteWorkspaceDirectory(input: { const auth = input.source.kind === "git" ? await input.resolveGitAuth(input.source.repoUrl) : null; const output = await command(input.target, "prepare", ["-e", PREPARE, input.remoteCwd, JSON.stringify({ ...input.source, preparationIdentity: input.preparationIdentity, + blobless: input.source.kind === "git" && bloblessCloneSource(input.source.repoUrl), authArgs: auth?.configArgs ?? [], authEnvKeys: Object.keys(auth?.env ?? {}) })], auth?.env); const result = JSON.parse(output) as { cwd: string }; if (result.cwd !== input.remoteCwd) throw new Error("remote_workspace_root_changed"); @@ -458,8 +477,8 @@ export async function prepareRemoteRepository(input: { if(existing){if(!existing.isDirectory()||existing.isSymbolicLink())throw Error('unsafe_repository')} else{if(input.verifyOnly||input.savedArchive)throw Error('repository_missing');if(input.probeOnly){process.stdout.write(JSON.stringify({cloneRequired:true}));return;} stage='stage';const staged=await fs.mkdtemp(root+'.preparing-');try{ - stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks','--',input.repoUrl,staged],{env:cloneEnv}); - const git=async args=>exec('git',['-c','core.hooksPath=/dev/null','-C',staged,...args],opts); + stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks',...(input.blobless?['--filter=blob:none']:[]),'--',input.repoUrl,staged],{env:cloneEnv}); + const git=async args=>exec('git',['-c','core.hooksPath=/dev/null',...input.authArgs,'-C',staged,...args],{env:cloneEnv}); stage='checkout_ref'; ${checkoutConfiguredRefScript} stage='publish';await fs.rename(staged,root); @@ -483,7 +502,8 @@ export async function prepareRemoteRepository(input: { } const auth = await input.resolveGitAuth(input.repoUrl); const output = await command(input.target, "repository", ["-e", script, input.remoteCwd, - JSON.stringify({ ...payload, authArgs: auth?.configArgs ?? [], authEnvKeys: Object.keys(auth?.env ?? {}) })], auth?.env); + JSON.stringify({ ...payload, blobless: bloblessCloneSource(input.repoUrl), + authArgs: auth?.configArgs ?? [], authEnvKeys: Object.keys(auth?.env ?? {}) })], auth?.env); const value = JSON.parse(output) as { cwd: string; pinnedCommit: string; branchName: string | null }; if (value.cwd !== input.remoteCwd || !/^[a-f0-9]{40,64}$/.test(value.pinnedCommit)) throw new Error("remote_workspace_repository_receipt_invalid"); return value;