fix(workspaces): classify Git storage guard failures during clone and archive (#22848)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Remote cloud sandboxes can wrap `git` in a storage guard that exits
with code 75 (`paperclip_git_storage_limit:`) when free space, free
inodes, or per-command disk growth hits its budget, or when the guard
itself is misconfigured
> - Previously, Paperclip's remote workspace archive capture and
repository preparation did not recognize `paperclip_git_storage_limit:`
output, so both reported opaque Git exit 75 failures
> - During archive capture, an unclassified exit 75 prevented fallback
to read-only controller-side capture and caused finalization to burn
retries instead of recognizing sandbox disk exhaustion immediately;
during workspace clone, it reported generic `setup_failed` and left
partial `.preparing-*` directories behind
> - This pull request classifies Git storage-guard space/budget refusals
as sandbox disk full across capture and preparation, cleans up failed
`.preparing-*` staging directories, and labels misconfigured/unavailable
guard failures distinctly so they are never misreported as a full disk
> - The benefit is that low-disk saves can recover through read-only
capture or stop retrying immediately, clone storage refusals classify
accurately, and unavailable guard errors remain clearly distinguishable

## Linked Issues or Issue Description

**What happened?**
When a sandbox Git storage guard stops a Git command with exit code 75
and `paperclip_git_storage_limit:` on stderr:
- Workspace archive capture (`remote-workspace-snapshot-archive.ts` /
`remote-workspace-transport.ts`) drops the storage-limit message and
reports `remote_workspace_capture_failed: stage=archive exit=75
program=git helper_exit=1`. Because this does not match
`REMOTE_WORKSPACE_SANDBOX_DISK_FULL`, `captureRemoteWorkspaceArchive`
skips its read-only controller-side fallback and finalization wastes 3
retries into `native_workspace_sync_out_retry_exhausted`.
- Workspace preparation (`prepareRemoteWorkspaceDirectory` /
`prepareRemoteRepository`) reports `remote_workspace_prepare_failed:
stage=clone exit=75 program=git`, which
`isRemoteWorkspaceSandboxDiskFullError` does not recognize (so setup
records generic `setup_failed`), and `PREPARE` does not remove its
partial `.preparing-*` staging directory on failure.

**Expected behavior**
- Git storage-guard low-space or storage-budget refusals classify as
`REMOTE_WORKSPACE_SANDBOX_DISK_FULL` during capture (triggering
`captureReadOnlyWorkspaceArchive` fallback and single-attempt
storage-exhaustion recognition) and as `disk=full git=storage_limit`
during prepare/repository (matched by
`isRemoteWorkspaceSandboxDiskFullError`), with `.preparing-*` cleanup on
failure.
- Unavailable or misconfigured Git storage-guard errors stay distinct
(`reason=git_storage_guard_unavailable` during capture,
`git=storage_guard_unavailable` during prepare/repository) and are never
misclassified as sandbox disk full.

**Steps to reproduce**
1. Configure a `git` wrapper on `PATH` that writes
`paperclip_git_storage_limit: The sandbox has too little free disk space
or too few free inodes; Git did not start.` (or `stopped at its storage
budget`) to stderr and exits 75.
2. Run `prepareRemoteWorkspaceDirectory`, `prepareRemoteRepository`, or
`captureRemoteWorkspaceArchive` against a Git workspace.
3. Observe opaque `stage=clone exit=75 program=git` or `stage=archive
exit=75 program=git helper_exit=1` with no read-only fallback,
`isRemoteWorkspaceSandboxDiskFullError` returning `false`, and leftover
`.preparing-*` directories on failed clones.

**Paperclip version or commit**
`master` (`ba63f4f8b2`).

**Deployment mode**
Hosted / remote sandbox execution (`paperclip_runner`).

Refs #22837 (companion handling for full reused sandboxes on
`remote_workspace_restore_failed`; this PR keeps
`remote_workspace_restore_failed` untouched and composes cleanly with
it).

## What Changed

- `server/src/services/remote-workspace-snapshot-archive.ts`:
- Recognize `paperclip_git_storage_limit:` low-space and storage-budget
refusals as `remote_workspace_sandbox_disk_full` inside
`remoteWorkspaceCaptureFailureMessage`.
- In `remoteWorkspaceFailureDetail`, emit the closed field
`reason=git_storage_guard_unavailable` when Git fails with any other
`paperclip_git_storage_limit:` message (such as misconfigured or
unreadable capacity), never copying raw stderr text and never
misclassifying it as disk full.
- `server/src/services/remote-workspace-transport.ts`:
- Extend `DISK_FULL_CHECK` to recognize `paperclip_git_storage_limit:`
space/budget refusals (not unavailable/misconfigured guard errors).
- Extend `SETUP_FAILURE_CHECK` to emit `git=storage_limit` (with
`disk=full`) or `git=storage_guard_unavailable` (without `disk=full`)
within the existing closed `SANDBOX_SETUP_CAUSE` grammar.
- Extend `isRemoteWorkspaceSandboxDiskFullError` to match
`RemoteWorkspaceOperationError` carrying
`remote_workspace_(?:prepare|repository)_failed: ... disk=full`, while
leaving host-side `ENOSPC` and `remote_workspace_restore_failed`
unaffected.
- Remove unpublished `.preparing-*` staging directories in `PREPARE`'s
`finally` block so failed or aborted clones do not leak partial data on
the sandbox disk.
- `server/src/services/remote-workspace-transport.test.ts`:
- Add real-subprocess red-green regressions for serialized `archive.cjs`
helper classification, read-only capture fallback, clone/repository
storage-limit classification and `.preparing-*` cleanup, and negative
cases proving unavailable/misconfigured guard errors stay distinct and
do not trigger read-only fallback or
`isRemoteWorkspaceSandboxDiskFullError`.

## Verification

- **Red (before production edits)**: 9/9 new real-subprocess tests
failed with the exact unfixed diagnostics (`stage=clone exit=75
program=git`, `stage=archive exit=75 program=git helper_exit=1`).
- **Green (commit `3de3c3181d`, rebased onto `ba63f4f8b2`)**:
- `pnpm --filter @paperclipai/server exec tsc -p tsconfig.json
--noEmit`: passes.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/remote-workspace-transport.test.ts -t "Git storage guard"`:
9/9 pass.
- Affected suites verified locally:
`remote-workspace-transport.test.ts`,
`native-workspace-finalizer-failure.test.ts`,
`remote-workspace-readonly-capture-cause.test.ts`, and
`run-completion.test.ts -t "sandbox disk"` all pass.
- Full PR CI runs on this commit to provide broad coverage across the
workspace.
- **Limitations**: Verified locally via real serialized `archive.cjs`
and Node/Git subprocesses; live cloud sandbox verification requires
deployment after merge alongside the companion sandbox-image guard
update.

## Risks

- Low risk: all new diagnostic values use closed literal tokens within
existing `SANDBOX_CAPTURE_CAUSE` and `SANDBOX_SETUP_CAUSE` grammars, so
raw stderr/paths never cross into error records.
- `isRemoteWorkspaceSandboxDiskFullError` only matches
`RemoteWorkspaceOperationError` for `prepare`/`repository` with
`disk=full`, preserving existing `RemoteWorkspaceRestoreError` handling
(#22837) and keeping host-side `ENOSPC` distinct.
- `PREPARE` only removes its own newly created `.preparing-*` directory
when publish (`fs.rename`) has not completed, matching
`prepareRemoteRepository`.

## Model Used

- Google Gemini 4 Neon (High) (`gemini-4-neon-high`) in Antigravity with
tool use (shell, file edit, test 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
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-11-25 04:34:26 -06:00
1 parent cd02a8e0e4
commit 0e12237d16
3 files changed
+136 -10

No files matched your search

@@ -851,7 +851,8 @@ export function remoteWorkspaceCaptureFailureMessage(error: unknown): string | n
if (typeof failure.message === "string" && validation.includes(failure.message)) return failure.message;
const childText = (typeof failure.stderr === "string" ? failure.stderr : "")
+ (typeof failure.message === "string" ? failure.message : "");
if (failure.code === "ENOSPC" || failure.code === "EDQUOT" || /No space left on device|Disk quota exceeded/i.test(childText)) return diskFull;
if (failure.code === "ENOSPC" || failure.code === "EDQUOT"
|| /No space left on device|Disk quota exceeded|paperclip_git_storage_limit:[^\n]*(?:too little free disk space|too few free inodes|stopped at its storage budget)/i.test(childText)) return diskFull;
for (const code of ["EACCES", "EPERM", "ENOENT", "ENOTDIR", "EISDIR", "ELOOP", "EMFILE", "ENFILE", "EIO", "EROFS", "EEXIST"]) {
const message = `remote_workspace_archive_fs_${code.toLowerCase()}`;
if (failure.code === code || failure.message === message) return message;
@@ -867,20 +868,28 @@ export function remoteWorkspaceCaptureFailureMessage(error: unknown): string | n
*/
export function remoteWorkspaceFailureDetail(error: unknown): string {
if (!error || typeof error !== "object") return "";
const failure = error as { code?: unknown; signal?: unknown; syscall?: unknown; killed?: unknown; cmd?: unknown; name?: unknown; message?: unknown };
const failure = error as { code?: unknown; signal?: unknown; syscall?: unknown; killed?: unknown; cmd?: unknown; name?: unknown; message?: unknown; stderr?: unknown };
const fields: string[] = [];
if (typeof failure.code === "string" && /^(E[A-Z0-9]{1,20}|ERR_[A-Z0-9_]{1,56})$/.test(failure.code)) fields.push(`code=${failure.code}`);
if (typeof failure.code === "number" && Number.isSafeInteger(failure.code) && failure.code >= 0 && failure.code <= 255) fields.push(`exit=${failure.code}`);
if (typeof failure.signal === "string" && /^SIG[A-Z0-9]{1,12}$/.test(failure.signal)) fields.push(`signal=${failure.signal}`);
if (typeof failure.syscall === "string" && /^[a-z_]{1,24}$/.test(failure.syscall)) fields.push(`syscall=${failure.syscall}`);
if (failure.killed === true) fields.push("killed=true");
if (typeof failure.cmd === "string" && failure.cmd.startsWith("git ")) fields.push("program=git");
const isGit = typeof failure.cmd === "string" && failure.cmd.startsWith("git ");
if (isGit) fields.push("program=git");
if (typeof failure.name === "string" && ["TypeError", "RangeError", "SyntaxError", "ReferenceError", "AbortError"].includes(failure.name)) {
fields.push(`name=${failure.name}`);
}
const reason = typeof failure.message === "string" ? /^(?:remote_workspace_archive_)?([a-z_]{1,48})$/.exec(failure.message)?.[1] : undefined;
if (reason && (failure.message !== reason || ["unsafe", "unsafe_capture", "invalid_capture", "capture_missing"].includes(reason))) {
fields.push(`reason=${reason}`);
} else if (isGit) {
const childText = (typeof failure.stderr === "string" ? failure.stderr : "")
+ (typeof failure.message === "string" ? failure.message : "");
if (/paperclip_git_storage_limit:/i.test(childText)
&& !/paperclip_git_storage_limit:[^\n]*(?:too little free disk space|too few free inodes|stopped at its storage budget)/i.test(childText)) {
fields.push("reason=git_storage_guard_unavailable");
}
}
return fields.join(" ");
}
@@ -13,6 +13,7 @@ import {
captureRemoteWorkspaceArchive,
cleanupRemoteWorkspaceArchive,
hasRemoteRecoveryAttachment,
isRemoteWorkspaceSandboxDiskFullError,
prepareRemoteRepository,
prepareRemoteWorkspaceDirectory,
remoteWorkspaceFailureCause,
@@ -23,7 +24,7 @@ import {
} from "./remote-workspace-transport.js";
import { classifyNativeWorkspaceFailure } from "./native-runtime/native-workspace-failure.js";
import { createRunPreparationTiming, drainRunPreparationPhases, measureRunPhase } from "./execution-preparation-timing.js";
import { restoreRemoteWorkspaceArchive } from "./remote-workspace-snapshot-archive.js";
import { remoteWorkspaceArchiveScript, restoreRemoteWorkspaceArchive } from "./remote-workspace-snapshot-archive.js";
import { readWorkspaceInventory, readonlyWorkspaceInventoryScript } from "./remote-workspace-readonly-inventory.js";
const archiveReads = vi.hoisted(() => ({ paths: [] as string[] }));
@@ -1049,6 +1050,114 @@ return result};`);
.rejects.toThrow(/^remote_workspace_operation_failed: operation=prepare exit=1; remote_workspace_prepare_failed: stage=checkout_branch exit=1 program=git$/);
});
it.each([
["low free space", "paperclip_git_storage_limit: The sandbox has too little free disk space or too few free inodes; Git did not start. SYNTHETIC_PRIVATE_PATH"],
["storage budget exceeded", "paperclip_git_storage_limit: Git was stopped at its storage budget to leave room for the runner and saved state. SYNTHETIC_PRIVATE_PATH"],
])("classifies a Git storage guard %s refusal during clone as sandbox disk full and cleans staged leftovers", async (_label, stderrText) => {
const origin = await repository();
const bin = path.join(scratch, "git-guard-clone-bin"); await fs.mkdir(bin, { recursive: true });
await fs.writeFile(path.join(bin, "git"), `#!/bin/sh\nprintf '%s\\n' ${JSON.stringify(stderrText)} >&2\nexit 75\n`, { mode: 0o700 });
const { remote } = target({ PATH: `${bin}${path.delimiter}${process.env.PATH}` });
const root = path.join(workspace, "storage-limit-clone");
const failure = await prepareRemoteWorkspaceDirectory({ target: remote, remoteCwd: root,
preparationIdentity: createHash("sha256").update("synthetic-storage-limit-clone").digest("hex"),
source: { kind: "git", repoUrl: origin, ref: "main" },
resolveGitAuth: async () => null }).then(() => null, (error: unknown) => error as Error);
expect(failure?.message).toBe(
"remote_workspace_operation_failed: operation=prepare exit=1; remote_workspace_prepare_failed: stage=clone disk=full git=storage_limit exit=75 program=git",
);
expect(failure?.message).not.toContain("SYNTHETIC");
expect(isRemoteWorkspaceSandboxDiskFullError(failure)).toBe(true);
expect((await fs.readdir(workspace)).filter(name => name.startsWith("storage-limit-clone.preparing-"))).toEqual([]);
const repoFailure = await prepareRemoteRepository({ target: remote, remoteCwd: path.join(workspace, "storage-limit-repo"),
repoUrl: origin, ref: "main", resolveGitAuth: async () => null }).then(() => null, (error: unknown) => error as Error);
expect(repoFailure?.message).toBe(
"remote_workspace_operation_failed: operation=repository exit=1; remote_workspace_repository_failed: stage=clone disk=full git=storage_limit exit=75 program=git",
);
expect(isRemoteWorkspaceSandboxDiskFullError(repoFailure)).toBe(true);
});
it("keeps a misconfigured Git storage guard during clone distinct from sandbox disk full", async () => {
const origin = await repository();
const bin = path.join(scratch, "git-guard-misconfigured-clone-bin"); await fs.mkdir(bin, { recursive: true });
await fs.writeFile(path.join(bin, "git"),
"#!/bin/sh\nprintf '%s\\n' \"paperclip_git_storage_limit: Git's storage guard is unavailable or misconfigured; Git did not complete. SYNTHETIC_PRIVATE_PATH\" >&2\nexit 75\n",
{ mode: 0o700 });
const { remote } = target({ PATH: `${bin}${path.delimiter}${process.env.PATH}` });
const root = path.join(workspace, "guard-misconfigured-clone");
const failure = await prepareRemoteWorkspaceDirectory({ target: remote, remoteCwd: root,
preparationIdentity: createHash("sha256").update("synthetic-guard-misconfigured-clone").digest("hex"),
source: { kind: "git", repoUrl: origin, ref: "main" },
resolveGitAuth: async () => null }).then(() => null, (error: unknown) => error as Error);
expect(failure?.message).toBe(
"remote_workspace_operation_failed: operation=prepare exit=1; remote_workspace_prepare_failed: stage=clone git=storage_guard_unavailable exit=75 program=git",
);
expect(failure?.message).not.toContain("SYNTHETIC");
expect(isRemoteWorkspaceSandboxDiskFullError(failure)).toBe(false);
expect(isRemoteWorkspaceSandboxDiskFullError(new Error(
"remote_workspace_operation_failed: operation=prepare exit=1; remote_workspace_prepare_failed: stage=clone disk=full exit=75 program=git",
))).toBe(false);
});
it("falls back to read-only capture when the Git storage guard stops in-sandbox archive mirroring", async () => {
await git(workspace, "init", "--initial-branch=main");
await fs.writeFile(path.join(workspace, "saved.txt"), "retained source bytes\n");
await git(workspace, "add", "saved.txt");
await git(workspace, "commit", "-qm", "Initial commit");
const realGit = path.join((await exec("git", ["--exec-path"])).stdout.trim(), "git");
const bin = path.join(scratch, "git-guard-archive-bin"); await fs.mkdir(bin, { recursive: true });
// Mirror the real guard: allow read-only metadata reads (`rev-parse`, `ls-files`),
// refuse `clone` when free space is below floor with exit 75.
await fs.writeFile(path.join(bin, "git"),
`#!/bin/sh\ncase " $* " in *" clone "*) printf '%s\\n' 'paperclip_git_storage_limit: The sandbox has too little free disk space or too few free inodes; Git did not start. SYNTHETIC_PRIVATE' >&2; exit 75;; esac\nexec '${realGit}' "$@"\n`,
{ mode: 0o700 });
const { remote } = target({ PATH: `${bin}${path.delimiter}${process.env.PATH}` });
const captured = await captureRemoteWorkspaceArchive({ target: remote, remoteCwd: workspace, operationId: randomUUID() });
try {
expect(captured.sha256).toMatch(/^[a-f0-9]{64}$/);
const restoredRoot = path.join(scratch, "restored-from-guard-fallback");
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, "saved.txt"), "utf8")).toBe("retained source bytes\n");
} finally { await captured.cleanup(); }
});
it("does not misclassify an unavailable Git storage guard during capture as sandbox disk full", async () => {
await git(workspace, "init", "--initial-branch=main");
await fs.writeFile(path.join(workspace, "saved.txt"), "retained source bytes\n");
const bin = path.join(scratch, "git-guard-unavailable-capture-bin"); await fs.mkdir(bin, { recursive: true });
await fs.writeFile(path.join(bin, "git"),
"#!/bin/sh\nprintf '%s\\n' \"paperclip_git_storage_limit: Git's storage guard is unavailable or misconfigured; Git did not complete. SYNTHETIC_PRIVATE\" >&2\nexit 75\n",
{ mode: 0o700 });
const { remote } = target({ PATH: `${bin}${path.delimiter}${process.env.PATH}` });
const syncOut = vi.fn(remote.runner!.syncOut!);
remote.runner!.syncOut = syncOut;
const failure = await captureRemoteWorkspaceArchive({ target: remote, remoteCwd: workspace, operationId: randomUUID() })
.then(() => null, (error: unknown) => error as Error);
expect(failure?.message).toBe(
"remote_workspace_operation_failed: operation=capture exit=1; remote_workspace_capture_failed: stage=archive exit=75 program=git reason=git_storage_guard_unavailable helper_exit=1",
);
expect(failure?.message).not.toContain("SYNTHETIC");
expect(isRemoteWorkspaceSandboxDiskFullError(failure)).toBe(false);
expect(syncOut).not.toHaveBeenCalled();
});
it.each([
["low free space", "paperclip_git_storage_limit: The sandbox has too little free disk space or too few free inodes; Git did not start.", REMOTE_WORKSPACE_SANDBOX_DISK_FULL],
["storage budget exceeded", "paperclip_git_storage_limit: Git was stopped at its storage budget to leave room for the runner and saved state.", REMOTE_WORKSPACE_SANDBOX_DISK_FULL],
["misconfigured", "paperclip_git_storage_limit: Git's storage guard is unavailable or misconfigured; Git did not complete.", "remote_workspace_archive_failed: exit=75 program=git reason=git_storage_guard_unavailable"],
["unreadable capacity", "paperclip_git_storage_limit: Cannot verify available sandbox storage; Git did not start.", "remote_workspace_archive_failed: exit=75 program=git reason=git_storage_guard_unavailable"],
])("classifies Git storage guard %s directly in the serialized archive helper", async (_label, stderrText, expectedStderr) => {
await git(workspace, "init", "--initial-branch=main");
const bin = path.join(scratch, "archive-helper-guard-bin"); await fs.mkdir(bin, { recursive: true });
await fs.writeFile(path.join(bin, "git"), `#!/bin/sh\nprintf '%s\\n' ${JSON.stringify(stderrText)} >&2\nexit 75\n`, { mode: 0o700 });
const helper = path.join(scratch, "archive.cjs"); await fs.writeFile(helper, remoteWorkspaceArchiveScript());
await expect(exec(process.execPath, [helper, "capture", workspace, path.join(scratch, "helper.pcws")],
{ env: { ...process.env, PATH: `${bin}${path.delimiter}${process.env.PATH ?? ""}` } }))
.rejects.toMatchObject({ code: 1, stdout: "", stderr: expectedStderr });
});
it("names the repository step that found a changed origin", async () => {
const origin = await repository(), { remote } = target(), root = path.join(workspace, "repos", "changed-origin");
await prepareRemoteRepository({ target: remote, remoteCwd: root, repoUrl: origin, ref: "HEAD", resolveGitAuth: async () => null });
@@ -66,16 +66,20 @@ export const REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE = "remote_workspace_sandbox
export const REMOTE_WORKSPACE_SANDBOX_DISK_FULL =
`${REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE}: the sandbox disk is full; free space in the sandbox before saving the workspace`;
const SANDBOX_PREPARE_DISK_FULL =
/(?:^|; )remote_workspace_(?:prepare|repository)_failed: stage=[a-z_]{1,32}(?: (?:reason|archive|disk|git|code|exit|signal|syscall|killed|program|name)=[A-Za-z0-9_]{1,64}){0,16}? disk=full(?: |$)/;
export function isRemoteWorkspaceSandboxDiskFullError(error: unknown): boolean {
let current = error;
for (let depth = 0; depth < 5 && current instanceof Error; depth++) {
if (current.message === REMOTE_WORKSPACE_SANDBOX_DISK_FULL) return true;
if (current instanceof RemoteWorkspaceOperationError && SANDBOX_PREPARE_DISK_FULL.test(current.message)) return true;
current = current.cause;
}
return false;
}
// Node reports ENOSPC or EDQUOT. Git and tar child processes report the text.
const DISK_FULL_CHECK = String.raw`const diskFull=e=>['ENOSPC','EDQUOT'].includes(e?.code)||/No space left on device|Disk quota exceeded/i.test(String(e?.stderr??'')+String(e?.message??''));`;
// Node reports ENOSPC or EDQUOT. Git, tar, and sandbox Git storage-guard child processes report the text.
const DISK_FULL_CHECK = String.raw`const diskFull=e=>['ENOSPC','EDQUOT'].includes(e?.code)||/No space left on device|Disk quota exceeded|paperclip_git_storage_limit:[^\n]*(?:too little free disk space|too few free inodes|stopped at its storage budget)/i.test(String(e?.stderr??'')+String(e?.message??''));`;
const CAPTURE_FAILURE_CHECK = `const captureFailure=${remoteWorkspaceCaptureFailureMessage.toString()};const failureDetail=${remoteWorkspaceFailureDetail.toString()};`;
// The only sandbox text a capture failure may add: a fixed stage plus bounded
// structured fields from remoteWorkspaceFailureDetail. Anything else is dropped.
@@ -95,9 +99,11 @@ const SETUP_FAILURE_CHECK = String.raw`const setupFailure=(prefix,stage,error)=>
const git=[[/Authentication failed|could not read Username|Permission denied \(publickey\)|terminal prompts disabled|returned error: 40[13]/i,'auth_failed'],
[/Repository not found|does not appear to be a git repository|returned error: 404/i,'repository_not_found'],
[/Could not resolve host|Connection (?:timed out|refused|reset)|Failed to connect|unable to access/i,'network'],
[/unknown revision|not a valid ref|Needed a single revision|invalid reference|did not match any|couldn't find remote ref/i,'ref_not_found']]
[/unknown revision|not a valid ref|Needed a single revision|invalid reference|did not match any|couldn't find remote ref/i,'ref_not_found'],
[/paperclip_git_storage_limit:[^\n]*(?:too little free disk space|too few free inodes|stopped at its storage budget)/i,'storage_limit'],
[/paperclip_git_storage_limit:/i,'storage_guard_unavailable']]
.find(([pattern])=>pattern.test(stderr))?.[1];if(git)fields.push('git='+git);}
for(const field of failureDetail(error).split(' ').filter(Boolean))if(!fields.some(value=>value.startsWith(field.split('=')[0]+'=')))fields.push(field);
for(const field of failureDetail(error).split(' ').filter(Boolean))if(!fields.some(value=>value.startsWith(field.split('=')[0]+'='))&&!(field==='reason=git_storage_guard_unavailable'&&fields.includes('git=storage_guard_unavailable')))fields.push(field);
return prefix+': '+fields.join(' ');};`;
const SANDBOX_SETUP_CAUSE = /^remote_workspace_(prepare|repository|restore)_failed: stage=[a-z_]{1,32}(?: (?:reason|archive|disk|git|code|exit|signal|syscall|killed|program|name)=[A-Za-z0-9_]{1,64}){0,16}$/;
@@ -374,7 +380,8 @@ ${DISK_FULL_CHECK}${CAPTURE_FAILURE_CHECK}${SETUP_FAILURE_CHECK}let stage='valid
process.stdout.write(JSON.stringify({cwd:root}));return;
}
if(input.probeOnly){process.stdout.write(JSON.stringify({cloneRequired:true}));return;}
stage='stage';const staged=await fs.mkdtemp(root+'.preparing-');
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});
@@ -399,8 +406,9 @@ ${DISK_FULL_CHECK}${CAPTURE_FAILURE_CHECK}${SETUP_FAILURE_CHECK}let stage='valid
const runtimeStat=await fs.lstat(runtime);if(!runtimeStat.isDirectory()||runtimeStat.isSymbolicLink())throw Error('unsafe_receipt');
await fs.writeFile(path.join(runtime,'workspace-ready.json'),JSON.stringify({preparationIdentity:input.preparationIdentity}),{flag:'wx',mode:0o600});
stage='publish';if(await fs.realpath(path.dirname(root))!==path.dirname(root))throw Error('unsafe_root');
await fs.rename(staged,root);
await fs.rename(staged,root);published=true;
process.stdout.write(JSON.stringify({cwd:await fs.realpath(root)}));
}finally{if(!published)await fs.rm(staged,{recursive:true,force:true}).catch(()=>{});}
})().catch(error=>{process.stderr.write(setupFailure('remote_workspace_prepare_failed',stage,error));process.exitCode=1});`;
export async function prepareRemoteWorkspaceDirectory(input: {