mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-06 21:05:21 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Runs can reference more than one project > - Each referenced project must land in its own sandbox tree so one run does not mix files across projects > - The anchor workspace must keep its own git history and overlay rules > - Fail closed on sync and confinement errors, and keep the other projects alive > - This pull request stages referenced projects into isolated project directories under the run sandbox root > - The benefit is safer multi-project runs with clear failure isolation ## Linked Issues or Issue Description No public issue exists. Related PR: #10448. ## What Changed - Thread additional referenced-project sources through the run prepare path and the runtime layers. - Stage each referenced project into its own `project-<projectId>` directory under the runtime root. - Keep the anchor workspace history and overlay semantics unchanged. - Fail closed on confinement or sync errors for one project, and keep the other projects running. - Keep the path inert by default behind the multi-project workspace-sync kill-switch. - No documentation update was needed for this code-only runtime change. ## Verification - `pnpm --filter @paperclipai/adapter-utils exec vitest run src/sandbox-file-sync.test.ts src/command-managed-runtime.test.ts src/sandbox-managed-runtime.test.ts src/remote-managed-runtime.test.ts` - `pnpm --filter @paperclipai/adapter-utils exec tsc --noEmit` - The branch points at `871378e4064a95adc8e4647e442ec1359768de61` on `origin/feat/stage-referenced-projects-into-sandbox`. - GitHub CI is green on PR #10469. ## Risks - A referenced project can skip if confinement or sync fails. - A new runtime tree layout can affect tools that assume one project root. - The kill-switch keeps the path inert until operators enable it. ## Model Used OpenAI Codex, GPT-5, tool use enabled. ## 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 or confirmed no docs update was needed - [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>
240 lines
7.8 KiB
TypeScript
240 lines
7.8 KiB
TypeScript
import path from "node:path";
|
|
import { GIT_ARCHIVE_EXCLUDES } from "./git-workspace-sync.js";
|
|
import {
|
|
type SshRemoteExecutionSpec,
|
|
prepareWorkspaceForSshExecution,
|
|
runSshCommand,
|
|
restoreWorkspaceFromSshExecution,
|
|
syncDirectoryToSsh,
|
|
} from "./ssh.js";
|
|
import type {
|
|
SandboxAdditionalSource,
|
|
SandboxManagedRuntimeAssetRestoreContext,
|
|
} from "./sandbox-managed-runtime.js";
|
|
import { captureDirectorySnapshot } from "./workspace-restore-merge.js";
|
|
import type { RuntimeProgressSink } from "./runtime-progress.js";
|
|
|
|
const REMOTE_ADDITIONAL_SOURCE_HEAVY_DIR_EXCLUDES = [
|
|
"node_modules",
|
|
"vendor",
|
|
"dist",
|
|
"build",
|
|
"out",
|
|
"coverage",
|
|
".next",
|
|
".turbo",
|
|
".cache",
|
|
".git",
|
|
].flatMap((entry) => [entry, `${entry}/*`, `*/${entry}`, `*/${entry}/*`]);
|
|
|
|
export interface RemoteManagedRuntimeAsset {
|
|
key: string;
|
|
localDir: string;
|
|
followSymlinks?: boolean;
|
|
exclude?: string[];
|
|
restore?: (ctx: SandboxManagedRuntimeAssetRestoreContext) => Promise<void>;
|
|
}
|
|
|
|
export interface PreparedRemoteManagedRuntime {
|
|
spec: SshRemoteExecutionSpec;
|
|
workspaceLocalDir: string;
|
|
workspaceRemoteDir: string;
|
|
runtimeRootDir: string;
|
|
assetDirs: Record<string, string>;
|
|
/**
|
|
* Remote directory of each additional (referenced) project that staged
|
|
* successfully, keyed by `projectId`. A project whose staging failed is
|
|
* absent (per-project failure isolation).
|
|
*/
|
|
additionalSourceDirs: Record<string, string>;
|
|
restoreWorkspace(onProgress?: RuntimeProgressSink): Promise<void>;
|
|
}
|
|
|
|
function asObject(value: unknown): Record<string, unknown> {
|
|
return value && typeof value === "object" && !Array.isArray(value)
|
|
? (value as Record<string, unknown>)
|
|
: {};
|
|
}
|
|
|
|
function asString(value: unknown): string {
|
|
return typeof value === "string" ? value : "";
|
|
}
|
|
|
|
function asNumber(value: unknown): number {
|
|
return typeof value === "number" ? value : Number(value);
|
|
}
|
|
|
|
function shellQuote(value: string): string {
|
|
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
}
|
|
|
|
async function readRemoteFile(spec: SshRemoteExecutionSpec, remotePath: string): Promise<Buffer> {
|
|
const result = await runSshCommand(spec, `base64 < ${shellQuote(remotePath)}`, {
|
|
maxBuffer: 1024 * 1024,
|
|
});
|
|
return Buffer.from(result.stdout.replace(/\s+/g, ""), "base64");
|
|
}
|
|
|
|
export function buildRemoteExecutionSessionIdentity(spec: SshRemoteExecutionSpec | null) {
|
|
if (!spec) return null;
|
|
return {
|
|
transport: "ssh",
|
|
host: spec.host,
|
|
port: spec.port,
|
|
username: spec.username,
|
|
remoteCwd: spec.remoteCwd,
|
|
} as const;
|
|
}
|
|
|
|
export function remoteExecutionSessionMatches(saved: unknown, current: SshRemoteExecutionSpec | null): boolean {
|
|
const currentIdentity = buildRemoteExecutionSessionIdentity(current);
|
|
if (!currentIdentity) return false;
|
|
|
|
const parsedSaved = asObject(saved);
|
|
return (
|
|
asString(parsedSaved.transport) === currentIdentity.transport &&
|
|
asString(parsedSaved.host) === currentIdentity.host &&
|
|
asNumber(parsedSaved.port) === currentIdentity.port &&
|
|
asString(parsedSaved.username) === currentIdentity.username &&
|
|
asString(parsedSaved.remoteCwd) === currentIdentity.remoteCwd
|
|
);
|
|
}
|
|
|
|
export async function prepareRemoteManagedRuntime(input: {
|
|
spec: SshRemoteExecutionSpec;
|
|
runId: string;
|
|
adapterKey: string;
|
|
workspaceLocalDir: string;
|
|
workspaceRemoteDir?: string;
|
|
syncWorkspace?: boolean;
|
|
assets?: RemoteManagedRuntimeAsset[];
|
|
/** Referenced (additional) projects to stage as plain, read-only trees. */
|
|
additionalSources?: SandboxAdditionalSource[];
|
|
// Upload progress sink. Threaded for the byte-counting transport rewrite; the
|
|
// child task wires it into the workspace/asset transfers.
|
|
onProgress?: RuntimeProgressSink;
|
|
}): Promise<PreparedRemoteManagedRuntime> {
|
|
const baseWorkspaceRemoteDir = input.workspaceRemoteDir ?? input.spec.remoteCwd;
|
|
const syncWorkspace = input.syncWorkspace !== false;
|
|
const workspaceRemoteDir = syncWorkspace
|
|
? path.posix.join(
|
|
baseWorkspaceRemoteDir,
|
|
".paperclip-runtime",
|
|
"runs",
|
|
input.runId,
|
|
"workspace",
|
|
)
|
|
: baseWorkspaceRemoteDir;
|
|
const runtimeRootDir = path.posix.join(workspaceRemoteDir, ".paperclip-runtime", input.adapterKey);
|
|
|
|
const preparedWorkspace = syncWorkspace
|
|
? await prepareWorkspaceForSshExecution({
|
|
spec: input.spec,
|
|
localDir: input.workspaceLocalDir,
|
|
remoteDir: workspaceRemoteDir,
|
|
onProgress: input.onProgress,
|
|
})
|
|
: null;
|
|
const baselineSnapshot = preparedWorkspace
|
|
? await captureDirectorySnapshot(input.workspaceLocalDir, {
|
|
exclude: preparedWorkspace.gitBacked
|
|
? [...GIT_ARCHIVE_EXCLUDES, ".paperclip-runtime"]
|
|
: [".paperclip-runtime"],
|
|
})
|
|
: null;
|
|
|
|
const assetDirs: Record<string, string> = {};
|
|
try {
|
|
for (const asset of input.assets ?? []) {
|
|
const remoteDir = path.posix.join(runtimeRootDir, asset.key);
|
|
assetDirs[asset.key] = remoteDir;
|
|
await syncDirectoryToSsh({
|
|
spec: input.spec,
|
|
localDir: asset.localDir,
|
|
remoteDir,
|
|
followSymlinks: asset.followSymlinks,
|
|
exclude: asset.exclude,
|
|
onProgress: input.onProgress,
|
|
progressLabel: asset.key,
|
|
});
|
|
}
|
|
} catch (error) {
|
|
if (preparedWorkspace && baselineSnapshot) {
|
|
await restoreWorkspaceFromSshExecution({
|
|
spec: input.spec,
|
|
localDir: input.workspaceLocalDir,
|
|
remoteDir: workspaceRemoteDir,
|
|
baselineSnapshot,
|
|
restoreGitHistory: preparedWorkspace.gitBacked,
|
|
onProgress: input.onProgress,
|
|
});
|
|
}
|
|
throw error;
|
|
}
|
|
|
|
// Stage each referenced (additional) project as a plain, read-only tree in its
|
|
// OWN isolated remote directory (`project-<projectId>`). Additional sources
|
|
// never get the anchor's git-history/overlay semantics. Per-project failure
|
|
// isolation: one project's failure logs a warning and is skipped; the run and
|
|
// the other projects continue (no workspace restore, unlike an asset failure).
|
|
const additionalSourceDirs: Record<string, string> = {};
|
|
for (const source of input.additionalSources ?? []) {
|
|
const { localPath, projectId } = source;
|
|
try {
|
|
if (!path.posix.isAbsolute(localPath)) {
|
|
throw new Error(`additional source localPath is not an absolute path: ${localPath}`);
|
|
}
|
|
if (
|
|
projectId.length === 0 ||
|
|
projectId.includes("/") ||
|
|
projectId.includes("\\") ||
|
|
projectId.includes("..")
|
|
) {
|
|
throw new Error(`additional source projectId is not a simple path segment: ${projectId}`);
|
|
}
|
|
const remoteDir = path.posix.join(runtimeRootDir, `project-${projectId}`);
|
|
await syncDirectoryToSsh({
|
|
spec: input.spec,
|
|
localDir: localPath,
|
|
remoteDir,
|
|
exclude: REMOTE_ADDITIONAL_SOURCE_HEAVY_DIR_EXCLUDES,
|
|
onProgress: input.onProgress,
|
|
progressLabel: `project-${projectId}`,
|
|
});
|
|
additionalSourceDirs[projectId] = remoteDir;
|
|
} catch (error) {
|
|
console.warn(
|
|
`[paperclip] Failed to stage referenced project ${projectId}; skipping it. ${String(error)}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
return {
|
|
spec: input.spec,
|
|
workspaceLocalDir: input.workspaceLocalDir,
|
|
workspaceRemoteDir,
|
|
runtimeRootDir,
|
|
assetDirs,
|
|
additionalSourceDirs,
|
|
restoreWorkspace: async (onProgress?: RuntimeProgressSink) => {
|
|
if (preparedWorkspace && baselineSnapshot) {
|
|
await restoreWorkspaceFromSshExecution({
|
|
spec: input.spec,
|
|
localDir: input.workspaceLocalDir,
|
|
remoteDir: workspaceRemoteDir,
|
|
baselineSnapshot,
|
|
restoreGitHistory: preparedWorkspace.gitBacked,
|
|
onProgress,
|
|
});
|
|
}
|
|
for (const asset of input.assets ?? []) {
|
|
if (!asset.restore) continue;
|
|
await asset.restore({
|
|
assetDir: path.posix.join(runtimeRootDir, asset.key),
|
|
readFile: (remotePath) => readRemoteFile(input.spec, remotePath),
|
|
});
|
|
}
|
|
},
|
|
};
|
|
}
|