Files
PaperClipAI/server/src/services/agent-file-maintenance.ts
T
DottaandClaude Opus 5.5 28bdb4d778 feat(cloud): migrate durable data online and name volume-free config blockers (#22240)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Paperclip servers can move from a server with a volume to a
volume-free server, which allows deploys without downtime
> - A server with history can move online only after its durable data is
off the local disk
> - Today only an offline maintenance process moves that data, so each
existing server takes an outage of many minutes
> - Most data owners already work safely while the server keeps serving,
but nothing drives them online
> - This pull request adds a signed, bounded pass that drives those
owners online and reports progress, and it names configuration blockers
> - The benefit is that existing servers can move to volume-free with no
maintenance window

## Linked Issues or Issue Description

**What existing behavior does this improve?**
An existing volume-backed server can move to volume-free only through
offline maintenance, because only the offline process migrates its local
data.

**Subsystem affected**
Server: ephemeral enrollment, durable data owners (agent files, skill
packages and installations, runtime skill assets, native harness backups
and controllers), Cloud control endpoints.

**Current behavior**
- Online preparation refuses while local data remains, and no online
path moves that data.
- When the volume-free configuration is incomplete, preparation fails
with a server error that does not say why.

**Proposed behavior**
- `POST /api/instance/ephemeral-enrollment/migrate` (Cloud control
action `ephemeral-enrollment:migrate`) runs one pass with a 60-second
budget. The pass drives the online-safe owners, defers items that are
busy, and returns counts, deferral reasons and fresh eligibility.
- Preparation and the eligibility read report an incomplete
configuration as a named blocker: `volume_free_storage_flags_required`,
`volume_free_master_key_required`, `volume_free_decision_key_required`,
`volume_free_database_listener_required` or
`volume_free_configuration_required`. Preparation returns 409 with these
blockers.

**Reason and benefit**
Cloud can call the pass until a server is eligible, and then move it
online with no outage.

**Breaking changes**
None. The offline maintenance behavior is unchanged.

## What Changed

- New `services/online-durable-data-migration.ts`. The pass:
- requires S3 storage and `PAPERCLIP_DURABLE_AGENT_FILES=true`, so the
server does not keep creating local data;
- runs these owners in order, with live writers: `migrateAgentFiles`
(`writersStopped: false`), the local skill object copy, skill snapshots
and versions, skill installations, runtime skill assets, and the native
harness and controller prestage;
  - stops between pages when the budget is spent;
  - runs one pass at a time in each process.
- `skill-package-storage-migration.ts`: a new `online` mode. In this
mode a row that another owner holds is skipped and counted as `busy`.
The row claim and the publication already use compare-and-swap. The
offline mode is unchanged and still fails closed on a busy row.
- `services/ephemeral-enrollment.ts`: a configuration check maps the
volume-free contract errors to blocker codes. Preparation and the
eligibility read both use this check.
- `routes/ephemeral-enrollment.ts`, `middleware/cloud-control.ts`,
`services/cloud-runtime-identity.ts`: the new route and action. The
route accepts only an empty body.

## Verification

- `npx vitest run src/routes/ephemeral-enrollment.test.ts
src/services/ephemeral-enrollment.test.ts
src/services/online-durable-data-migration.test.ts
src/services/skill-package-storage-migration.test.ts
src/__tests__/openapi-routes.test.ts
src/services/cloud-runtime-identity.test.ts`: 102/102 pass.
- New tests:
- the pass drives every owner with live writers, aggregates counts and
deferrals, and reports eligibility;
  - the pass does nothing without S3 or durable agent files;
  - the pass stops at the budget;
  - one pass runs at a time;
- the skill object copy refuses outside maintenance unless the mode is
online, skips a busy row online, and still fails closed offline;
- each missing setting becomes a named blocker in preparation and in the
eligibility read;
- the migrate route accepts only a signed migrate assertion and an empty
body.
- `tsc --noEmit` reports no errors in the touched files. A full local
`pnpm verify` needs the Runner build, so CI covers it.

## Risks

- The pass runs real migrations while the server serves. Each owner
keeps its own locks and compare-and-swap rules. Busy items are deferred,
not forced. The budget limits each call.
- The skill object copy can now run online. It copies immutable objects,
verifies the hashes, and publishes only if the row did not change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, browser).

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:36:30 -06:00

138 lines
7.8 KiB
TypeScript

import { createHash } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { and, asc, eq, gt, inArray } from "drizzle-orm";
import { agentFileRoots, agents, fileStorageDb, heartbeatRuns, type Db } from "@paperclipai/db";
import { offlineMigrationExecutionWhere } from "./offline-migration-execution.js";
import type { StorageProvider, StorageService } from "../storage/types.js";
import { adoptAgentFiles, inspectAgentDirectory } from "./agent-file-store.js";
import { agentInstructionsBundleMode, deriveBundleState, resolveManagedInstructionsRoot } from "./agent-instructions.js";
import { durableAgentFilesEnabled } from "./agent-file-durability.js";
import { hasUnsettledLocalInstructionCopies } from "./agent-instruction-copy-preservation.js";
export const AGENT_FILE_OBJECT_GRACE_MS = 30 * 24 * 60 * 60_000;
/** Run on the host that owns the legacy volume. The canonical agent row lock
* serializes file writers and new admission. First adoption also requires its
* local working copies to be settled. A dry run never adopts local files. */
export async function migrateAgentFiles(db: Db, input: {
apply: boolean; writersStopped: boolean; companyId?: string; after?: string; limit?: number; signal?: AbortSignal;
}) {
if (input.apply && !durableAgentFilesEnabled()) {
throw new Error("Agent file migration requires PAPERCLIP_DURABLE_AGENT_FILES=true");
}
const limit = input.limit ?? 25;
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error("Migration limit must be between 1 and 100");
const rows = await db.select({ id: agents.id }).from(agents).where(and(
input.companyId ? eq(agents.companyId, input.companyId) : undefined,
input.after ? gt(agents.id, input.after) : undefined,
)).orderBy(asc(agents.id)).limit(limit + 1);
const results: Array<{ agentId: string; state: string }> = [];
for (const candidate of rows.slice(0, limit)) {
input.signal?.throwIfAborted();
const state = await fileStorageDb(db).transaction(async tx => {
const [agent] = await tx.select().from(agents).where(eq(agents.id, candidate.id)).for("update");
if (!agent) return "removed";
if (agentInstructionsBundleMode(agent) === "external") return "external_instructions";
const [head] = await tx.select({ generation: agentFileRoots.generation }).from(agentFileRoots)
.where(and(eq(agentFileRoots.companyId, agent.companyId), eq(agentFileRoots.agentId, agent.id)));
// Current shared authority needs no local rewrite, even during a run.
if (head) return "durable";
const [run] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, agent.companyId), eq(heartbeatRuns.agentId, agent.id),
input.writersStopped && process.env.PAPERCLIP_EPHEMERAL_MIGRATION === "true"
? offlineMigrationExecutionWhere() : inArray(heartbeatRuns.status, ["running", "queued"]),
)).limit(1);
if (run) return "active_execution";
if (await hasUnsettledLocalInstructionCopies(tx, { companyId: agent.companyId, agentId: agent.id }))
return "working_copy_unsettled";
if (input.apply) {
await adoptAgentFiles(tx, agent);
return "durable";
}
const root = resolveManagedInstructionsRoot(agent);
const stored = agent.adapterConfig.instructionsRootPath;
if (typeof stored === "string" && (path.resolve(stored) !== root
|| !await fs.stat(path.join(root, deriveBundleState(agent).entryFile)).then(s => s.isFile()).catch(() => false))) {
return "legacy_files_missing";
}
if (await fs.stat(root).then(s => s.isDirectory()).catch(() => false)) await inspectAgentDirectory(root, false);
return "needs_import";
});
results.push({ agentId: candidate.id, state });
}
return { results, next: rows.length > limit ? results.at(-1)!.agentId : null,
pageReady: results.every(row => row.state === "durable" || row.state === "removed") };
}
/** Bounded, explicit maintenance, with no idle polling. Keep every object for
* an unadopted agent: a rolled-back first save may have a local import receipt.
* The agent row lock prevents a concurrent publisher from reusing an object
* between the current-head check and deletion. Deleted agents have no writer. */
export async function collectAgentFileObjects(db: Db, provider: Pick<StorageProvider, "id" | "listObjects">, storage: StorageService, input: {
companyId: string; agentId: string; apply: boolean; continuationToken?: string; now?: number;
}) {
if (provider.id !== "s3" || storage.provider !== "s3" || !provider.listObjects) throw new Error("Shared object storage is required");
const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
if (!uuid.test(input.companyId) || !uuid.test(input.agentId)) throw new Error("Company and agent UUIDs are required");
const prefix = `${input.companyId}/agent-files/${input.agentId}/`;
const signal = AbortSignal.timeout(30_000);
const page = await provider.listObjects({ prefix, continuationToken: input.continuationToken, signal });
let retained = 0, eligible = 0, deleted = 0;
for (const key of page.keys) {
signal.throwIfAborted();
if (!key.startsWith(prefix) || key.includes("..") || key.includes("\\")) throw new Error("Agent file object scope is invalid");
await fileStorageDb(db).transaction(async tx => {
const [agent] = await tx.select({ id: agents.id }).from(agents)
.where(and(eq(agents.companyId, input.companyId), eq(agents.id, input.agentId))).for("update");
const [head] = await tx.select({ entries: agentFileRoots.entries }).from(agentFileRoots)
.where(and(eq(agentFileRoots.companyId, input.companyId), eq(agentFileRoots.agentId, input.agentId)));
if ((agent && !head) || head?.entries.some(entry => entry.kind === "file" && entry.objectKey === key)) {
retained++; return;
}
const object = await storage.headObject(input.companyId, key, { signal });
if (!object.exists || !object.lastModified || object.lastModified.getTime() + AGENT_FILE_OBJECT_GRACE_MS > (input.now ?? Date.now())) {
retained++; return;
}
eligible++;
if (input.apply) {
await storage.deleteObject(input.companyId, key, { signal, allVersions: true });
if ((await storage.headObject(input.companyId, key, { signal })).exists) throw new Error("Agent file object remains after deletion");
deleted++;
}
});
}
return { retained, eligible, deleted, next: page.continuationToken ?? null };
}
/** Verify all authoritative bytes before the legacy volume can be detached.
* This runs only with writers stopped, using bounded pages and streams. */
export async function verifyAgentFileObjects(db: Db, storage: StorageService, signal: AbortSignal): Promise<number> {
if (storage.provider !== "s3") throw new Error("shared_object_storage_required");
let after: string | undefined;
let verified = 0;
for (;;) {
signal.throwIfAborted();
const heads = await db.select().from(agentFileRoots).where(after ? gt(agentFileRoots.agentId, after) : undefined)
.orderBy(asc(agentFileRoots.agentId)).limit(25);
for (const head of heads) for (const file of head.entries) {
if (file.kind !== "file") continue;
const hash = createHash("sha256");
let bytes = 0;
if (file.objectKey !== null) {
const object = await storage.getObject(head.companyId, file.objectKey, { signal });
for await (const chunk of object.stream) {
signal.throwIfAborted(); bytes += chunk.length;
if (bytes > file.size) throw new Error("agent_file_object_size_mismatch");
hash.update(chunk);
}
}
if (bytes !== file.size || hash.digest("hex") !== file.sha256) throw new Error("agent_file_object_digest_mismatch");
verified++;
}
if (heads.length < 25) break;
after = heads.at(-1)!.agentId;
}
return verified;
}