mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-02 02:07:25 +08:00
## Thinking Path > - Paperclip manages AI agents and keeps their instructions and files durable. > - Native Codex runners can keep a process alive between compatible turns. > - Managed file collection stopped that process after each turn, which defeated warm reuse. > - Agent folders can contain large images and other files, so full copies on every turn are expensive. > - This change keeps one managed directory for the live session and saves only file changes after each turn. > - Ownership, authorization, instruction changes, and process retirement still control when reuse is safe. ## Linked Issues or Issue Description Related: #13710 introduced native warm session reuse. This fixes managed file collection that still forced those sessions to stop. No duplicate open PR or issue was found. **What happened?** With managed instructions and warm native Codex enabled, consecutive turns reused a Daytona sandbox but started a new runner process each time. The managed directory collector required process termination before saving files. **Expected behavior** Compatible turns keep the same process and managed `AGENT_HOME`. Each completed turn saves added, changed, and deleted files before the next turn starts. Unchanged large files do not transfer again. **Steps to reproduce** 1. Use a native Codex agent with managed instructions and a reusable Daytona environment. 2. Enable warm session reuse and run three turns on the same task. 3. Write a large binary on the first turn, edit a small note on each turn, and delete a file on the second turn. 4. Compare process identity across turns and read the canonical files through the public agent-files API. **Paperclip version or commit** Reproduced on `d30b03bd8c17604cdab1533eeeeb087aba30e8b1`. **Deployment mode** Local server with remote Daytona execution; cloud native runner uses the same path. ## What Changed - Retain the managed directory only for the verified owner of a live native Codex session. - Checkpoint each completed turn before releasing the session for reuse. Retry unstable captures, then stop and collect when a warm checkpoint cannot be validated. - Compare metadata and cached hashes, stream only changed file payloads, record deletions, and validate path, content, quota, and authorization before saving. - Rotate sessions when canonical files, loaded instructions, credentials, or launch policy change. Fence stale collection and cleanup callbacks from later owners. - Keep cleanup and recovery aware of the current session owner. Recheck canonical files under the writer lock at handoff, attach the successor collector before fallible bookkeeping, and emit one final save receipt on checkpoint fallback. Preserve storage warnings across unchanged checkpoints. - Add regression coverage and a three-turn Daytona test with independent public API file checks, an unchanged 8 MiB binary, deletion checks, and strict process identity checks. - Document checkpoint consistency, lifecycle behavior, and local run-log counters. - Replace a timing assumption in the Daytona teardown test with explicit transfer-arrival gates after CI exposed an unset release callback. ## Verification - Full local `pnpm -r typecheck` and `pnpm build` passed. Server checks were repeated after the final storage-warning fix. - Runner E2E typecheck and 749 runner E2E unit tests passed. - Focused file checkpoint, directory ownership, instruction collection, native session, and merge tests passed. After review fixes, the managed-directory and native-session suites passed 550 tests, including intervening canonical edits, same-run fresh restore, failed handoff collection, and one-call fallback collection. Server typecheck passed again. The Daytona plugin suite passed 218 tests. The quota-warning regression failed before the fix and passed afterward. - Three real Daytona campaigns passed before the final handoff review fixes. The latest kept PID 547 across all three turns. The first checkpoint copied 8,388,635 bytes; the next two copied 36 and 54 bytes. Public API reads verified the binary, note contents, and deletion after every turn. Test cleanup deleted the sandbox. - The final head was also deployed to an isolated cloud staging instance and passed three UI-triggered native Codex turns with managed instructions. All three retained the same process ID/start time, native session, provider session, runner instance, and Daytona sandbox. Checkpoints copied 8,388,643 bytes on turn 1, then only 52 and 78 bytes on turns 2 and 3; those warm captures also hashed only 52 and 78 bytes. Independent canonical API reads verified every byte of the unchanged 8 MiB binary and the exact note contents after every turn; the deleted file returned 404 after turns 2 and 3. After restoring the original lifecycle and agent-auth configuration, removing the temporary secret, pausing the test agent, and deleting both test sandboxes, independent canonical API reads still verified the entire binary, the final 78-byte three-line note, and the deletion. The native runner flag remained enabled and the final serving revision remained the PR head. - Two earlier staging attempts are preserved as failures and are excluded from the acceptance result: a saved ChatGPT login failed with a provider routing 401, and its subsequent stopped-sandbox retry failed before provider startup with a closed-lease admission error. The successful campaign used a fresh sandbox and a temporary encrypted API-key binding. The stopped-lease retry remains unexplained; this campaign does not establish recovery of that failed sandbox. - All [Paperclip CI gates](https://github.com/paperclipai/paperclip/actions/runs/36750397355) pass on `26ef2ef56a389259246809805c0b34a4747eb86b`, including full test partitions, build, typecheck, runner verification, E2E shards, and the Canary clean public-npm install. Greptile reviewed that exact head at 5/5 with no unresolved review threads or outstanding findings. - Full local repository coverage used the existing CI partitions, but the 40,000-file Git streaming stress test timed out and its local retry was interrupted by macOS thermal emergency sleep; this is not a green full local suite claim. The exact stress test passed on the final head in [CI server shard 2/12](https://github.com/paperclipai/paperclip/actions/runs/36750397355/job/110008294290), in 111.9 seconds. - Repeat the live test with configured credentials and a Linux runner artifact: `pnpm test:e2e:runner -- --id daytona-warm-continuity.runner-codex.daytona.warm-three-turn`. ## Risks - This is a file-level checkpoint, not an atomic snapshot of the whole folder. Background writes after a capture are saved by the next checkpoint or final stopped collection. - Metadata scans still visit all paths. Modified files transfer in full; unchanged files do not rehash or transfer. - Incorrect ownership or reuse could collect the wrong directory. Run ownership fences, current authorization, stable capture validation, and stopped collection fallbacks are covered by tests. - Warm reuse remains opt-in. No database migration or fleet default changes. ## Model Used OpenAI GPT-6 through Codex, with reasoning, code editing, tool use, and test execution. The exact serving model ID and context-window size are not exposed by this session. ## 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>
139 lines
7.1 KiB
JavaScript
139 lines
7.1 KiB
JavaScript
// This module also runs verbatim in a remote workspace. Keep it dependency-free.
|
|
import fs from "node:fs/promises";
|
|
import { constants } from "node:fs";
|
|
import { createHash } from "node:crypto";
|
|
import path from "node:path";
|
|
|
|
const MAX_FILE = 256 * 1024 * 1024;
|
|
const MAX_BYTES = 2 * 1024 * 1024 * 1024;
|
|
const MAX_ENTRIES = 100_000;
|
|
const stamp = s => [s.dev, s.ino, s.size, s.mode, s.mtimeNs, s.ctimeNs].map(String).join(":");
|
|
const sameContent = (a, b) => a?.kind === b?.kind && (a?.kind === "dir" || a?.hash === b?.hash && a?.mode === b?.mode);
|
|
const fail = (code) => { throw Object.assign(new Error(code), { code }); };
|
|
|
|
export function checkpointPath(name) {
|
|
if (typeof name !== "string" || !name || name.includes("\\") || name.includes("\0") || name.startsWith("/") ||
|
|
name.split("/").some(p => !p || p === "." || p === ".." || p === ".paperclip-runtime") || name === "promptTemplate.legacy.md") fail("AGENT_FILES_UNSAFE_PATH");
|
|
return name;
|
|
}
|
|
|
|
async function assertRoot(root) {
|
|
let absolute = path.resolve(root);
|
|
// Match the managed-file store: macOS owns these aliases. Accepting them
|
|
// does not permit a user-created symlink anywhere inside the agent tree.
|
|
if (process.platform === "darwin") for (const alias of ["var", "tmp", "etc"]) {
|
|
const systemPath = `/${alias}`;
|
|
if (absolute.startsWith(`${systemPath}/`)) {
|
|
const stat = await fs.lstat(systemPath);
|
|
if (stat.isSymbolicLink() && stat.uid === 0 && await fs.realpath(systemPath) === `/private/${alias}`) {
|
|
absolute = `/private${absolute}`;
|
|
}
|
|
}
|
|
}
|
|
if (await fs.realpath(absolute) !== absolute || !(await fs.lstat(absolute)).isDirectory()) fail("AGENT_FILES_UNSAFE_PATH");
|
|
return absolute;
|
|
}
|
|
|
|
/** Metadata is a hash cache, never a dirty-file journal. ctime also detects
|
|
* same-size edits whose mtime was restored. Every checkpoint enumerates paths. */
|
|
export async function captureAgentFiles(root, previous = { entries: [] }, output, enforceLimits = true, excludeTransportRuntime = false) {
|
|
root = await assertRoot(root);
|
|
const cache = new Map(previous.entries);
|
|
const entries = [];
|
|
const observed = new Map();
|
|
const stats = { hashedBytes: 0, copiedBytes: 0, copiedFiles: 0, scannedEntries: 0 };
|
|
let total = 0;
|
|
if (output) await fs.mkdir(path.join(output, "files"), { recursive: true, mode: 0o700 });
|
|
const list = async dir => (await fs.readdir(path.join(root, dir)))
|
|
.filter(name => !(excludeTransportRuntime && dir === "" && name === ".paperclip-runtime")).sort();
|
|
async function walk(dir) {
|
|
const names = await list(dir);
|
|
observed.set(dir, names);
|
|
for (const name of names) {
|
|
const relative = checkpointPath(dir ? `${dir}/${name}` : name);
|
|
const filename = path.join(root, relative);
|
|
const s = await fs.lstat(filename, { bigint: true });
|
|
stats.scannedEntries++;
|
|
if (enforceLimits && stats.scannedEntries > MAX_ENTRIES) fail("AGENT_FILES_LIMIT_EXCEEDED");
|
|
if (s.isDirectory()) {
|
|
entries.push([relative, { kind: "dir" }]);
|
|
await walk(relative);
|
|
} else {
|
|
if (!s.isFile() || s.nlink !== 1n) fail("AGENT_FILES_UNSAFE_PATH");
|
|
const size = Number(s.size), mode = Number(s.mode), fingerprint = stamp(s);
|
|
total += size;
|
|
if (enforceLimits && (size > MAX_FILE || total > MAX_BYTES)) fail("AGENT_FILES_LIMIT_EXCEEDED");
|
|
const old = cache.get(relative);
|
|
let hash = old?.kind === "file" && old.stamp === fingerprint ? old.hash : null;
|
|
if (!hash) {
|
|
const h = createHash("sha256");
|
|
const f = await fs.open(filename, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
try {
|
|
if (stamp(await f.stat({ bigint: true })) !== fingerprint) fail("AGENT_FILES_CHANGED_DURING_CHECKPOINT");
|
|
let read = 0;
|
|
for await (const chunk of f.createReadStream({ autoClose: false })) {
|
|
read += chunk.length;
|
|
if (read > size) fail("AGENT_FILES_CHANGED_DURING_CHECKPOINT");
|
|
h.update(chunk); stats.hashedBytes += chunk.length;
|
|
}
|
|
if (stamp(await f.stat({ bigint: true })) !== fingerprint) fail("AGENT_FILES_CHANGED_DURING_CHECKPOINT");
|
|
hash = h.digest("hex");
|
|
} finally { await f.close(); }
|
|
}
|
|
const entry = { kind: "file", size, mode, hash, stamp: fingerprint };
|
|
if (output && !sameContent(old, entry)) {
|
|
const target = path.join(output, "files", relative);
|
|
await fs.mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
const source = await fs.open(filename, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
let dest;
|
|
try {
|
|
dest = await fs.open(target, "wx", mode & 0o777);
|
|
if (stamp(await source.stat({ bigint: true })) !== fingerprint) fail("AGENT_FILES_CHANGED_DURING_CHECKPOINT");
|
|
const h = createHash("sha256");
|
|
let copied = 0;
|
|
for await (const chunk of source.createReadStream({ autoClose: false })) {
|
|
copied += chunk.length;
|
|
if (copied > size) fail("AGENT_FILES_CHANGED_DURING_CHECKPOINT");
|
|
h.update(chunk);
|
|
let offset = 0;
|
|
while (offset < chunk.length) {
|
|
const { bytesWritten } = await dest.write(chunk, offset, chunk.length - offset);
|
|
if (!bytesWritten) fail("AGENT_FILES_CHECKPOINT_WRITE_FAILED");
|
|
offset += bytesWritten;
|
|
}
|
|
stats.copiedBytes += chunk.length;
|
|
}
|
|
if (h.digest("hex") !== hash || stamp(await source.stat({ bigint: true })) !== fingerprint) fail("AGENT_FILES_CHANGED_DURING_CHECKPOINT");
|
|
await dest.sync();
|
|
await dest.chmod(mode & 0o777);
|
|
stats.copiedFiles++;
|
|
} finally { await source.close(); await dest?.close(); }
|
|
}
|
|
entries.push([relative, entry]);
|
|
}
|
|
}
|
|
}
|
|
await walk("");
|
|
// Catch deletions, renames, additions and writers racing the scan/copy. These
|
|
// are per-file checkpoints, not an atomic snapshot of arbitrary live writers.
|
|
for (const [dir, names] of observed) if (JSON.stringify(await list(dir)) !== JSON.stringify(names)) fail("AGENT_FILES_CHANGED_DURING_CHECKPOINT");
|
|
for (const [name, entry] of entries) {
|
|
const s = await fs.lstat(path.join(root, name), { bigint: true });
|
|
if (entry.kind === "dir" ? !s.isDirectory() : stamp(s) !== entry.stamp || !s.isFile() || s.nlink !== 1n) fail("AGENT_FILES_CHANGED_DURING_CHECKPOINT");
|
|
}
|
|
await assertRoot(root);
|
|
const manifest = { version: 1, entries, totalBytes: total };
|
|
if (output) await fs.writeFile(path.join(output, "checkpoint.json"), JSON.stringify(manifest), { mode: 0o600, flag: "wx" });
|
|
return { manifest, stats };
|
|
}
|
|
|
|
if (process.argv[1] === "--checkpoint") {
|
|
try {
|
|
const input = JSON.parse(process.argv[2]);
|
|
const bytes = await fs.readFile(input.cacheFile);
|
|
if (createHash("sha256").update(bytes).digest("hex") !== input.cacheHash) fail("AGENT_FILES_CHECKPOINT_CACHE_MISMATCH");
|
|
const result = await captureAgentFiles(input.root, JSON.parse(bytes), input.output, true, true);
|
|
console.log(JSON.stringify(result.stats));
|
|
} catch (e) { console.error(e.code ?? "AGENT_FILES_CHECKPOINT_FAILED"); process.exitCode = 1; }
|
|
}
|