mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 12:33:05 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A native session retains its workspace and provider session across turns. > - An ephemeral web server must restore those files without its predecessor's disk. > - Legacy enrollment changes the workspace authority and can change both workspace addresses. > - The retained provider backup checks those addresses as part of its identity. > - This pull request preserves the exact addresses in a verified migration receipt. > - The benefit is that the next turn can use the original session after enrollment. ## Linked Issues or Issue Description Refs #18932, merged as `612d9931a6`. This pull request builds on that all-Runner durability change. Related: #18918 fixes concurrent workspace preservation locks. This change covers identity preservation during offline enrollment. ## What Changed - The native workspace migration owner records the selected session bindings in the successful workspace migration operation. - Runtime selection retains the original logical address only for the exact agent, task and session. - Remote workspace preparation restores the original provider address. It refuses conflicting targets, forged receipts and occupied unowned roots. - The environment owner includes the migration operation in the reusable lease fingerprint. Warm policy stays warm and receives a fresh allocation through normal lease cleanup. - Exact migration evidence permits the existing verified provider backup to restore into that fresh warm allocation. - Preserve verified provider allocation files through a normalized, lease-bound digest receipt. Unknown files and altered markers remain refused; interrupted publication is retryable. - Retain legacy managed-instruction session fingerprints using the exact imported content hash and recorded paths, preserving all other configuration and credential checks. - Migrate existing local skill archive/manifest objects through upload claims, readback verification and receipt compare-and-swap; retain original objects and IDs. - Add explicit two-turn browser qualification for every released native Daytona profile, with warm and per-turn variants. The production maintenance entry runs offline. The old home is deleted only after a verified export and successor readiness. The oracle checks provider identity, native session, addresses, reference bytes, question and final document. ## Verification - Full repository typecheck passed at `b12ecd823e`. The production session fix passed 198 session/credential tests. Full repository build passed at `94bb917947`. The final Rust-only provider fix passed 57 ACPX provider tests and the exact Linux release build. - Workspace and transport checks passed: 117 transport/workspace tests, six final real PostgreSQL migration boundary cases, 178 environment tests, 539 Daytona tests (eight skips), and the native warm-backup admission control. - Local skill migration passed eight PostgreSQL/S3 tests (one existing opt-in skip). Failed readback retains the source. Successful readback still works after deletion of the old home. - Latest Product E2E typecheck and 38 focused harness tests pass. Earlier catalog/admission/report checks passed. Twelve unrelated support-test failures reproduce on unchanged base `1a39dea9aa`; these are not reported as passing. - Live Codex per-turn at `2d5bb9a6d1` retained the native and provider sessions, both workspace paths and exact reference bytes after deletion of the old home. It completed the task and delivered its saved document and original reference. Its original failure was an output-count grading defect. The corrected grader passes all 21 checks against retained, hashed evidence; the original result remains unchanged. - Live OpenCode per-turn and Codex warm at harness `94bb917947` pass all 21 product checks. Their launcher cleanup failed because a read-only diagnostic observer kept its disposable database open. The observer now closes before ordinary database cleanup; a no-provider reproduction confirms the fix. All owned sandboxes were independently verified absent, child keys revoked and buckets removed. Original failed campaign dispositions remain unchanged. - Claude at `94bb917947` kept its sessions and reference bytes but omitted the final clickable document link. That user-delivery failure remains recorded. The fixture now explicitly asks for the link and records migration evidence before checking navigation. The fresh Claude attempt at `b12ecd823e` passed both strict migration checks: exact provider/native session, both paths, original file bytes and independently downloaded attachment. Its full browser workflow failed again: it requested unnecessary confirmation, used the answer sentence as the reference, and omitted the clickable document link. This is retained as a failed user-workflow result, not a full pass. - Earlier live failures exposed and reproduced the skill-object, fresh-allocation marker and managed-instruction fingerprint bugs. The fixes retain original identity checks. No provider session reset or accounting bypass was used. - The real Grok continuation at `b12ecd823e` failed before provider execution because its immutable-instruction attach policy rejected relocated registered file copies. A no-provider regression reproduced the exact rejection. `b05ba3728a` selects the existing strict authenticated asset-path policy for Grok; content digests, unknown context fields, session/workspace identity and same-run mutations remain enforced. The regression and all 57 ACPX provider controls pass. The Grok browser migration now passes all 21 checks with the b05 Linux Runner, including provider identity, exact reference bytes and final user output; the launcher also reports successful cleanup. - `24fabf1d81` applies the same policy to released ACPX Codex after a second no-provider reproduction. All 58 ACPX provider controls and the final Linux release build pass. Its live browser migration passes all 21 checks on the final binary, including exact original session/file preservation and completed user output. - The full native-session executor suite passes all 1,121 tests after updating its existing lease database fixture for the migration-receipt join. The prior CI failure was this unsupported test-double method; the production guard still rejects ordinary unproven recovery. CI and Greptile 5/5 passed at `ca1e0d5fe6`. The first CI attempt lost several workers and had one rotated-recovery transport failure; its seven descriptor cases passed locally, and the single unchanged retry passed. The original failure remains recorded. Staging enrollment has not started. Initial offline enrollment and subsequent rolling availability are separate checks. - The final review follow-up adds real runtime-selection PostgreSQL cases for exact, different-session and absent receipts, plus executor-level warm restoration that copies actual backup files and verifies provider identity and the new lease stamp. Both complete affected suites pass (1,172 tests), and full repository typecheck passes. Removing either production migration connection independently makes its new positive case fail; both source files were restored byte-for-byte after these negative controls. - Final commit `0971d373a3` passes all 63 checks (57 successes, five expected skips, one neutral); Greptile is 5/5 and every review thread is resolved. ## Risks - An identity conflict blocks enrollment and keeps the original files. It does not silently reset the session. - A new migration generation retires a reusable lease through its existing owner. The original sandbox must finish normal cleanup before reuse proceeds. - Initial enrollment has an offline step. The separate rolling suites prove uninterrupted deploy behavior after enrollment. - This adds no schema migration and changes no provider credentials or accounting gate. ## Model Used OpenAI Codex, GPT-6 family. The exact serving model build and context window are not exposed in this session. The agent used reasoning, terminal tools, code edits, PostgreSQL/filesystem tests and isolated live browser qualification. ## 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>
125 lines
9.2 KiB
TypeScript
125 lines
9.2 KiB
TypeScript
import { spawn, type ChildProcess } from "node:child_process";
|
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
import { createWriteStream } from "node:fs";
|
|
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { setTimeout as delay } from "node:timers/promises";
|
|
import { paperclipConfigSchema } from "../../packages/shared/src/config-schema.js";
|
|
import { makeDirectoryTreeRemovable } from "./directory-cleanup.js";
|
|
import { runnerE2EServerControlPaths } from "./harness-env.js";
|
|
import { reserveRunnerE2EServerPort } from "./ports.js";
|
|
import { startRollingDeploymentProcess } from "./rolling-deployment-process.js";
|
|
import { startRollingDeploymentProxy } from "./rolling-deployment-proxy.js";
|
|
import { readRestartRequest } from "./server-restart-request.js";
|
|
import { createRunnerE2EServerStopper } from "./server-stop.js";
|
|
import { runnerE2ETypeScriptProcessArgs } from "./web-server-command.js";
|
|
|
|
type Server = Awaited<ReturnType<typeof startRollingDeploymentProcess>>;
|
|
|
|
export async function superviseLegacyWorkspaceMigration(input: {
|
|
temporaryRoot: string; repositoryRoot: string; configPath: string; port: number;
|
|
environment: NodeJS.ProcessEnv; executionIds: string[]; cancelled: () => boolean;
|
|
}) {
|
|
const config = paperclipConfigSchema.parse(JSON.parse(await readFile(input.configPath, "utf8")));
|
|
if (input.executionIds.length !== 1 || config.database.mode !== "postgres" || !config.database.connectionString
|
|
|| input.environment.PAPERCLIP_STORAGE_PROVIDER !== "s3") throw new Error("Migration qualification requires one owned Postgres/S3 cell");
|
|
const databaseUrl = config.database.connectionString, controls = runnerE2EServerControlPaths(input.temporaryRoot);
|
|
const proxy = await startRollingDeploymentProxy(input.port), servers: Server[] = [];
|
|
const environment: NodeJS.ProcessEnv = { ...input.environment,
|
|
PAPERCLIP_DATABASE_LISTEN_URL: databaseUrl, PAPERCLIP_SECRETS_MASTER_KEY: randomBytes(32).toString("base64"),
|
|
HEARTBEAT_SCHEDULER_ENABLED: "true", PAPERCLIP_EPHEMERAL_SERVER: "true",
|
|
PAPERCLIP_DURABLE_AGENT_FILES: "true", PAPERCLIP_SHARED_UI_ASSETS: "true",
|
|
RUN_LOG_S3_BUCKET: input.environment.PAPERCLIP_STORAGE_S3_BUCKET,
|
|
RUN_LOG_S3_ENDPOINT: input.environment.PAPERCLIP_STORAGE_S3_ENDPOINT,
|
|
RUN_LOG_S3_REGION: input.environment.PAPERCLIP_STORAGE_S3_REGION,
|
|
RUN_LOG_S3_FORCE_PATH_STYLE: input.environment.PAPERCLIP_STORAGE_S3_FORCE_PATH_STYLE };
|
|
const start = async (name: string, env: NodeJS.ProcessEnv) => {
|
|
const server = await startRollingDeploymentProcess({ root: input.temporaryRoot, name, repositoryRoot: input.repositoryRoot,
|
|
databaseUrl, ingressOrigin: proxy.origin, sharedEnvironment: env, browser: {} });
|
|
servers.push(server); return server;
|
|
};
|
|
const json = async (filename: string, value: unknown) => {
|
|
await mkdir(path.dirname(filename), { recursive: true });
|
|
await writeFile(`${filename}.tmp`, JSON.stringify(value), { mode: 0o600 }); await rename(`${filename}.tmp`, filename);
|
|
};
|
|
const settings = async (enabled: boolean) => {
|
|
const response = await fetch(`${proxy.origin}/api/instance/settings/experimental`, { method: "PATCH",
|
|
headers: { "content-type": "application/json", origin: proxy.origin },
|
|
body: JSON.stringify({ remoteWorkspaceStorageEnabled: enabled, enableExperimentalFileViewer: true }), signal: AbortSignal.timeout(10_000) });
|
|
if (!response.ok) throw new Error(`Migration fixture settings returned ${response.status}`);
|
|
await response.body?.cancel();
|
|
};
|
|
let maintenance: { stop(): Promise<void> } | undefined;
|
|
try {
|
|
const keyPath = path.resolve(config.secrets.localEncrypted.keyFilePath);
|
|
if (!keyPath.startsWith(`${path.resolve(input.temporaryRoot)}${path.sep}`)) throw new Error("Migration fixture key escaped its root");
|
|
await mkdir(path.dirname(keyPath), { recursive: true, mode: 0o700 });
|
|
await writeFile(keyPath, environment.PAPERCLIP_SECRETS_MASTER_KEY!, { mode: 0o600, flag: "wx" });
|
|
const legacyEnvironment: NodeJS.ProcessEnv = { ...environment, PAPERCLIP_EPHEMERAL_SERVER: "false", PAPERCLIP_DURABLE_AGENT_FILES: "false",
|
|
PAPERCLIP_SHARED_UI_ASSETS: "false", PAPERCLIP_STORAGE_PROVIDER: "local_disk" };
|
|
for (const name of Object.keys(legacyEnvironment)) if (name.startsWith("RUN_LOG_S3_")) delete legacyEnvironment[name];
|
|
let current = await start("legacy-controller", legacyEnvironment);
|
|
await current.waitForReady(); proxy.routeTo(current.origin); await settings(false);
|
|
let migrated = false, lastRequest: string | undefined;
|
|
while (!input.cancelled()) {
|
|
if (current.child.exitCode !== null || current.child.signalCode !== null) throw new Error("Migration controller exited unexpectedly");
|
|
const request = await readRestartRequest(controls.restartRequestPath, input.executionIds);
|
|
if (!request || request.requestId === lastRequest) { await delay(100); continue; }
|
|
lastRequest = request.requestId;
|
|
try {
|
|
if (migrated || request.rollingDeployment || request.controllerOutage || request.preserveRunner || request.crashAfterResult) {
|
|
throw new Error("Legacy migration permits exactly one offline enrollment");
|
|
}
|
|
await settings(true);
|
|
const previous = current; await previous.stop({ requireGraceful: true });
|
|
const port = await reserveRunnerE2EServerPort(), token = randomBytes(32).toString("base64url"), id = randomUUID();
|
|
const log = createWriteStream(path.join(input.temporaryRoot, "legacy-maintenance.log"), { mode: 0o600 });
|
|
const errors = new WeakMap<ChildProcess, Error>();
|
|
const stopper = createRunnerE2EServerStopper({ gracefulTimeoutMs: 15_000, forcedTimeoutMs: 5_000,
|
|
hasSpawnError: child => errors.has(child), markExpectedStop() {}, log: message => log.write(message) });
|
|
const child = spawn(process.execPath, runnerE2ETypeScriptProcessArgs(input.repositoryRoot,
|
|
path.join(previous.home, "app/server/dist/maintenance/ephemeral-migration.js")), {
|
|
cwd: input.repositoryRoot, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"],
|
|
env: { ...environment, HOME: previous.home, PAPERCLIP_HOME: previous.home, PAPERCLIP_CONFIG: previous.configPath,
|
|
PAPERCLIP_INSTANCE_ID: "default", DATABASE_URL: databaseUrl, PORT: String(port),
|
|
PAPERCLIP_EPHEMERAL_MIGRATION: "true", PAPERCLIP_EPHEMERAL_MIGRATION_ID: id, PAPERCLIP_EPHEMERAL_MIGRATION_TOKEN: token } });
|
|
child.on("error", error => errors.set(child, error));
|
|
child.stdout!.pipe(log, { end: false }); child.stderr!.pipe(log, { end: false });
|
|
await stopper.watch(child);
|
|
maintenance = { async stop() { await stopper.stopAll(); await new Promise<void>(resolve => log.end(resolve)); } };
|
|
const endpoint = `http://127.0.0.1:${port}`;
|
|
const headers = { authorization: `Bearer ${token}` };
|
|
const deadline = Date.now() + 180_000;
|
|
let receipt: Record<string, any> | undefined;
|
|
while (!input.cancelled() && Date.now() < deadline) {
|
|
if (errors.has(child) || child.exitCode !== null || child.signalCode !== null) throw new Error("Maintenance exited before a verified export");
|
|
receipt = await fetch(`${endpoint}/status`, { headers, signal: AbortSignal.timeout(2_000) })
|
|
.then(async response => response.ok ? await response.json() as Record<string, any> : undefined).catch(() => undefined);
|
|
if (receipt?.state === "blocked") throw new Error(`Migration blocked: ${receipt.failure}`);
|
|
if (receipt?.state === "ready") break;
|
|
await delay(250);
|
|
}
|
|
if (receipt?.state !== "ready" || receipt.id !== id || receipt.eligibility?.eligible !== true) throw new Error("Maintenance did not qualify migration");
|
|
const exported = await fetch(`${endpoint}/export`, { method: "POST", headers, signal: AbortSignal.timeout(10_000) });
|
|
if (!exported.ok) throw new Error(`Migration export returned ${exported.status}`);
|
|
const data = await exported.json() as Record<string, any>;
|
|
if (data.id !== id || typeof data.decisionSigningSecret !== "string" || data.decisionSigningSecret.length < 32) throw new Error("Migration key export is incomplete");
|
|
environment.PAPERCLIP_DECISION_SIGNING_SECRET = data.decisionSigningSecret;
|
|
await json(path.join(controls.controlDirectory, "legacy-migration-receipt.json"), receipt);
|
|
await maintenance.stop(); maintenance = undefined;
|
|
current = await start("ephemeral-controller", environment); await current.waitForReady(); proxy.routeTo(current.origin);
|
|
await makeDirectoryTreeRemovable(previous.home); await rm(previous.home, { recursive: true });
|
|
migrated = true;
|
|
await json(controls.restartAcknowledgementPath, { requestId: request.requestId, status: "ready", controllerCacheDiscarded: true,
|
|
completedAt: new Date().toISOString(), legacyMigration: { ...receipt, oldHomeDeleted: true } });
|
|
} catch (error) {
|
|
await json(controls.restartAcknowledgementPath, { requestId: request.requestId, status: "failed", message: String(error) }); throw error;
|
|
}
|
|
}
|
|
} finally {
|
|
try { await maintenance?.stop(); } finally {
|
|
try { await Promise.all(servers.map(server => server.stop())); } finally { await proxy.close(); }
|
|
}
|
|
}
|
|
}
|