fix(runtime): support in-place workspace realization (#10230)

## Thinking Path

> - Paperclip is the control plane people use to coordinate AI agents
and their execution environments.
> - Environment realization decides where an agent runs and which
filesystem and toolchain are authoritative.
> - Copy-based realization is unsafe for container-anchored tasks
because absolute paths such as `/app` can point outside the synchronized
tree and task-specific binaries may be absent.
> - That mismatch can let an agent successfully verify work in a phantom
writable path while sync-back silently discards the result.
> - Existing task environments already provide the authoritative
filesystem and toolchain, so they should be executed in place rather
than copied.
> - Copy mode still needs explicit confinement rules so aliases target
the synchronized workspace and unsynchronized writable paths fail
visibly.
> - This pull request adds typed realization metadata, propagates the
authoritative root through orchestration, and teaches Codex to honor it.
> - The benefit is that container-anchored tasks operate on
verifier-visible state with the intended tools, while copy mode remains
safe and backward compatible.

## Linked Issues or Issue Description

No public GitHub issue exists for this defect.

GitHub duplicate searches for in-place execution, workspace realization,
and authoritative workspace roots found no related pull request to link.

### What happened?

Environment-backed agent runs were always realized through a copied
workspace. Tasks anchored to absolute container paths could therefore
write outside the synchronized tree, and task-provided toolchains were
unavailable in the copy. A run could report success even though
sync-back discarded its output.

### Expected behavior

Existing task environments should run against their real authoritative
root and toolchain. Copy-mode runs should map declared absolute aliases
into the synchronized tree and reject writable paths that cannot be
restored.

### Steps to reproduce

1. Run a Codex task environment whose required files live under `/app`
or `/workspace` and whose required binary exists only in the task
container.
2. Observe that copy realization changes the effective
filesystem/toolchain or permits writes outside the synchronized root.
3. Complete and verify the task inside the agent sandbox.
4. Observe that the verifier cannot see out-of-tree artifacts or that
task-specific commands were unavailable.

### Reproduction context

- Paperclip commit: `3a16b91217483d2c233926de5b7f7bc3a1077924`
- Deployment: built from source in a task-container execution
environment
- Adapter: Codex local
- Database: not database-related
- Access context: agent execution

## What Changed

- Added typed `copy | in_place` workspace-realization metadata,
authoritative roots, confined aliases, and outbound restore paths to
shared execution-target contracts.
- Selected in-place realization for existing task environments and
skipped archive prepare/restore when the authoritative environment is
used directly.
- Propagated the authoritative root into adapter context so Codex uses
it for cwd and `PAPERCLIP_WORKSPACE_*` semantics, including ACP
execution.
- Bound copy-mode aliases such as `/app` to the synchronized workspace
and rejected writable out-of-tree paths without explicit restore
mappings.
- Added focused regression coverage while preserving existing copy-mode
archive restore behavior.

## Verification

- `pnpm --filter @paperclipai/shared typecheck` — passed.
- `pnpm exec vitest run
packages/adapter-utils/src/local-process-sandbox.test.ts
packages/adapters/codex-local/src/server/acp.test.ts
packages/adapters/codex-local/src/server/execute.remote.test.ts
server/src/__tests__/environment-run-orchestrator.test.ts` — 48 passed,
4 skipped.
- `pnpm -r typecheck` — passed.
- `env -u AWS_ACCESS_KEY_ID -u AWS_SECRET_ACCESS_KEY -u
AWS_SESSION_TOKEN pnpm test:run` — passed across all general and
serialized Vitest shards.
- `pnpm build` — passed.
- Codex `k=1` acceptance run completed July 24, 2026 at 23:54:30 UTC
with 4 completed, 0 exceptions, and mean reward 1.0: `build-cython-ext`,
`openssl-selfsigned-cert`, `prove-plus-comm`, and `sqlite-db-truncate`
each received terminal grade 1.0 against real task-environment paths and
toolchains.

## Risks

- In-place mode deliberately exposes the authoritative task root to the
adapter; incorrect environment metadata could point execution at the
wrong root. Typed metadata and focused orchestration tests cover
selection and propagation.
- Copy-mode writable-path validation is stricter and may reject
previously accepted unsafe configurations. The rejection is intentional
and produces a visible error instead of silently losing output.
- The acceptance run is focused on four Codex task-environment
workloads, not a broad cross-adapter benchmark. Existing copy-mode
archive tests and the full repository suite remain green.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex CLI coding agent; exact model ID and context-window size
were not exposed to this runtime. Capabilities used: extended reasoning,
repository editing, shell execution, test/build execution, Git, GitHub
CLI, and Paperclip API tool use.

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-07-25 08:29:26 -05:00
1 parent cca2806e57
commit 4e00818574
18 files changed
+681 -103

No files matched your search

@@ -186,6 +186,10 @@ function makeMockRuntime(overrides: Partial<EnvironmentRuntimeService> = {}): En
metadata: {
workspaceRealization: {
version: 1,
mode: "copy",
authoritativeRoot: "/workspace/project",
pathAliases: [],
outboundRestorePaths: [],
driver: "local",
cwd: "/workspace/project",
},
@@ -254,7 +258,15 @@ describe("environmentRunOrchestrator — realizeForRun", () => {
const result = await orchestrator.realizeForRun(makeRealizeInput());
expect(result.lease).toBeDefined();
expect(result.executionTarget).toEqual(executionTarget);
expect(result.executionTarget).toEqual({
...executionTarget,
workspaceRealization: {
mode: "copy",
authoritativeRoot: "/workspace/project",
pathAliases: [],
outboundRestorePaths: [],
},
});
expect(result.remoteExecution).toEqual(remoteExecution);
expect(result.workspaceRealization).toEqual(
expect.objectContaining({ version: 1, driver: "local" }),
@@ -264,6 +276,45 @@ describe("environmentRunOrchestrator — realizeForRun", () => {
expect(mockResolveEnvironmentExecutionTarget).toHaveBeenCalledOnce();
});
it("uses an in-place authoritative root on the adapter execution target", async () => {
mockResolveEnvironmentExecutionTarget.mockResolvedValue({
kind: "remote",
transport: "sandbox",
remoteCwd: "/copied/workspace",
});
const runtime = makeMockRuntime({
realizeWorkspace: vi.fn().mockResolvedValue({
cwd: "/app",
metadata: {
workspaceRealization: {
version: 1,
mode: "in_place",
authoritativeRoot: "/app",
pathAliases: [],
outboundRestorePaths: [],
},
},
}),
});
const orchestrator = environmentRunOrchestrator(mockDb, { environmentRuntime: runtime });
const result = await orchestrator.realizeForRun(
makeRealizeInput({ environment: makeEnvironment("sandbox") }),
);
expect(result.executionTarget).toEqual(expect.objectContaining({
kind: "remote",
transport: "sandbox",
remoteCwd: "/app",
workspaceRealization: {
mode: "in_place",
authoritativeRoot: "/app",
pathAliases: [],
outboundRestorePaths: [],
},
}));
});
it("realization failure: runtime.realizeWorkspace throws → EnvironmentRunError with code workspace_realization_failed", async () => {
const runtime = makeMockRuntime({
realizeWorkspace: vi.fn().mockRejectedValue(new Error("sandbox unreachable")),
@@ -40,6 +40,7 @@ import {
adapterExecutionTargetToRemoteSpec,
type AdapterExecutionTarget,
type AdapterRemoteExecutionSpec,
type AdapterWorkspaceRealization,
} from "@paperclipai/adapter-utils/execution-target";
import { buildWorkspaceRealizationRequest } from "./workspace-realization.js";
import { executionWorkspaceService } from "./execution-workspaces.js";
@@ -485,6 +486,35 @@ export function environmentRunOrchestrator(
lease,
environmentRuntime,
});
const realizationMode = workspaceRealization.mode === "in_place" ? "in_place" : "copy";
const authoritativeRoot =
typeof workspaceRealization.authoritativeRoot === "string" && workspaceRealization.authoritativeRoot.trim().length > 0
? workspaceRealization.authoritativeRoot.trim()
: realizedCwd;
const workspaceTargetMetadata: AdapterWorkspaceRealization = {
mode: realizationMode,
authoritativeRoot,
pathAliases: Array.isArray(workspaceRealization.pathAliases)
? workspaceRealization.pathAliases.filter(
(entry): entry is { path: string; target: string } =>
typeof entry === "object" && entry !== null &&
typeof (entry as { path?: unknown }).path === "string" &&
typeof (entry as { target?: unknown }).target === "string",
)
: [],
outboundRestorePaths: Array.isArray(workspaceRealization.outboundRestorePaths)
? workspaceRealization.outboundRestorePaths.filter((entry): entry is string => typeof entry === "string")
: [],
};
if (executionTarget) {
executionTarget = {
...executionTarget,
...(executionTarget.kind === "remote" && realizationMode === "in_place"
? { remoteCwd: authoritativeRoot }
: {}),
workspaceRealization: workspaceTargetMetadata,
} as AdapterExecutionTarget;
}
} catch (err) {
throw new EnvironmentRunError(
"transport_resolution_failed",
+35 -1
View File
@@ -21,6 +21,22 @@ function readNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function readStringArray(value: unknown): string[] {
return Array.isArray(value)
? value.map(readString).filter((entry): entry is string => entry !== null)
: [];
}
function readPathAliases(value: unknown): Array<{ path: string; target: string }> {
if (!Array.isArray(value)) return [];
return value.flatMap((entry) => {
const parsed = parseObject(entry);
const aliasPath = readString(parsed.path);
const target = readString(parsed.target);
return aliasPath && target ? [{ path: aliasPath, target }] : [];
});
}
function readWorkspaceRealizationRequest(value: unknown): WorkspaceRealizationRequest | null {
const parsed = parseObject(value);
if (parsed.version !== 1) return null;
@@ -129,9 +145,23 @@ export function buildWorkspaceRealizationRecord(input: {
const port = readNumber(leaseMetadata.port);
const username = readString(leaseMetadata.username);
const sandboxId = readString(leaseMetadata.sandboxId) ?? readString(providerMetadata.sandboxId);
const realizationMetadata = {
...parseObject(leaseMetadata.workspaceRealization),
...parseObject(providerMetadata.workspaceRealization),
...providerMetadata,
};
const mode = realizationMetadata.mode === "in_place" || realizationMetadata.realizationMode === "in_place"
? "in_place" as const
: "copy" as const;
const authoritativeRoot =
readString(realizationMetadata.authoritativeRoot) ??
(mode === "in_place" ? remotePath : null) ??
input.request.source.localPath;
const pathAliases = readPathAliases(realizationMetadata.pathAliases ?? realizationMetadata.workspaceAliases);
const outboundRestorePaths = readStringArray(realizationMetadata.outboundRestorePaths);
const sync = (() => {
if (transport === "local") {
if (mode === "in_place" || transport === "local") {
return {
strategy: "none" as const,
prepare: "Use the realized local execution workspace directly.",
@@ -174,6 +204,10 @@ export function buildWorkspaceRealizationRecord(input: {
return {
version: 1,
mode,
authoritativeRoot,
pathAliases,
outboundRestorePaths,
transport,
provider,
environmentId: input.environment.id,