mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-01 23:43:16 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents use installed skills and exact version pins during execution. > - Managed skills still depended on mutable directories on the web server. > - A replacement server could lose acknowledged edits or remove an unassigned skill whose directory was absent. > - This pull request makes immutable versions the authority for managed content and installed repository reads. > - The server can rebuild delivery files from durable content after replacement. > - This establishes skills readiness for ephemeral web servers. General server draining and workspace recovery remain separate work. ## Linked Issues or Issue Description **Subsystem affected** Skills services, shared contracts, database receipts, Skill Studio, and runtime delivery. **Problem or motivation** A fresh web server must discover, read, edit, and deliver protected installed skills using the same database, object storage, secrets, and supported application artifacts. It must not need its predecessor's files or process memory. **Proposed solution** Use `managed` ownership with a null source locator. Read installed content by immutable version. Prepare packages before a short publication transaction. Persist execution selections before materialization. Recover exact pinned runtime assets and reject deletion while active or recovering pins exist. **Alternatives considered** Reconstructing a mutable installed directory preserves the old source-of-truth ambiguity. Permanent dual writes create two competing authorities. This change uses one managed model after a bounded legacy conversion. **Roadmap alignment** This improves the existing Skills Manager, Studio, version history, and Cloud execution capabilities. The maintainer supplied the implementation contract. This does not add a separate skills product or deploy fleet changes. Related work: #18082 supplies immutable package storage. #17273 addresses edits outside the API for linked local skills; this PR keeps that source category separate. #2648 is a closed earlier ephemeral-filesystem proposal. ## What Changed - Add managed ownership and focused content publication and execution materialization modules. Keep the archive format and package storage tables. - Publish managed create, save, delete, fork, rename, restore, and catalog content with version checks. Add durable create receipts. Preserve file-save receipt responses. - Return file version identities. Keep Studio drafts after a conflict and provide an explicit reload action. A delayed reload cannot overwrite newer typing or navigation. - Persist exact runtime selections, including empty selections. Rebuild pinned assets and verify their admitted digests on a replacement server. - Preserve source access on forks and disconnected copies. Keep the existing workspace policy category for managed skills. - Add bounded conversion, eligibility, and independent verification phases. Load persisted Cloud configuration in the standalone CLI without seeding or changing it. Reject partial current versions against installed inventories; recover only complete saved content or the exact source. Document storage migration blockers and the compatible rollback floor. - Add separate-process PostgreSQL/S3 qualification and update domain, retention, policy, and UI regressions. - Pass the plugin worker manager into Studio execution, admit restricted `skill_test` mode through native Runner contracts, and preserve admitted scope across native and REST tools. Native tests cannot create ordinary tasks, browse company data, or use external tools. - Select the exact durable Studio revision even when unassigned or Beta skills is off. Persist Studio output and audit atomically with native task completion, preserving the result on replay. ## Verification - Final revision `13e8af480b88ba6fea5737bac4bd81104d604792` passed full CI: all 49 workflow jobs completed successfully ([run 41127396098](https://github.com/paperclipai/paperclip/actions/runs/41127396098)). This includes typecheck, test suites, Runner checks, browser checks and build. Greptile review 15 is 5/5 on that same revision, with zero unresolved threads. The PR is ready for review. - Local workspace typecheck and build passed after integrating master. Focused checks passed: 33 execution/completion cases, 52 Runner HTTP cases, 16 managed-content cases, 17 Studio cases, the new real-process CLI regression, map checks and UI token gates. The CLI regression proves inspection does not seed missing Cloud configuration. Server typecheck passed after that fix. - The independent-process PostgreSQL/S3 matrix passed through normal HTTP skill routes. It covers A → B → C replacement, lost commit responses, upload crashes, concurrent saves, binary contents and executable delivery. Metadata listing and warm selected delivery retain zero object downloads. Local timing measurements are recorded; they do not establish hosted latency. - Hosted A → B → C passed on the owned disposable test tenant with external Postgres, S3 and a real remote Paperclip Computer. Predecessor temporary homes were absent. C read and executed B's acknowledged managed save. New runs used repository v1 while v2 was installed. Hashes matched an independently checked exact upstream commit. - Compatible image rollback to `6518b323` passed. Studio retained the unassigned fork's C save. A fresh remote run executed the newer managed content and historical repository pin. The actual shell event confirmed expected hashes, stdout, exit 0 and mode 0555. - Runtime candidate `9200e3fcb4` deployed successfully ([Cloud run 41124147876](https://github.com/paperclipai/paperclip-cloud/actions/runs/41124147876)). The final Studio test delivered only the unassigned fork's exact v3, executed its script and persisted a successful output snapshot. Independent command-event inspection confirmed all three hashes, stdout, exit 0 and mode 0555. All 14 installations were version-backed. Independent verification checked all 25 versions: 23 remote objects, two bundled database snapshots, zero blockers. - The deployed image is `9200e3fcb4`. Later master integration, the client-only delayed-reload draft guard and the CLI bootstrap have separate automated proof. The CLI bootstrap was also exercised against the tenant's stored configuration and storage through the same read-only services. This PR does not claim that the deployed image is the final PR revision. - Live Studio checks exposed worker wiring, admission, access scope, exact selection and completion-publication gaps. They are fixed. Failed attempts remain in the evidence. The full local suite exceeded 80 minutes under host contention and was stopped. Later combined/isolated local attempts also timed out; they are not counted as passes. Full CI covers the integrated suites. Earlier CI found an obsolete restart-scope fixture, which was corrected and passed all 52 HTTP cases. - Reproduction and migration: [`doc/skill-ephemeral-web-servers.md`](doc/skill-ephemeral-web-servers.md). Source revisions, deployments, versions, run IDs, hashes and failure history: [`doc/plans/2026-10-30-ephemeral-web-skills.md`](doc/plans/2026-10-30-ephemeral-web-skills.md). ## Risks - Legacy conversion requires stopped admission and retired filesystem-authoritative writers. Pre-conversion binaries are not supported rollback targets afterward. - Cloud readiness requires remote object storage. Local provider receipts and provider mismatches remain blockers until objects are copied and verified. - Linked local sources retain filesystem semantics and are outside the cloud guarantee. - Cold reads still fetch the existing archive format. Warm runtime preparation retains the verified-cache path. - Bundled reconciliation preserves an installed head. Existing release snapshots remain selectable. An older server must not replace a newer head with its shipped files. - No production volumes, fleet defaults, or general deployment coordination change in this PR. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository tools, code execution, and browser use. The exact backend model ID and context-window size are not exposed in this session. No subagents were used. ## 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>
237 lines
16 KiB
TypeScript
237 lines
16 KiB
TypeScript
import { constants, promises as fs } from "node:fs";
|
|
import path from "node:path";
|
|
import { and, asc, eq, gt, sql } from "drizzle-orm";
|
|
import { companySkills, companySkillVersions, type Db } from "@paperclipai/db";
|
|
import { parseFrontmatterMarkdown, type CompanySkillVersionFileInventoryEntry } from "@paperclipai/shared";
|
|
import { conflict } from "../errors.js";
|
|
import { classifyInventoryKind, companySkillService } from "./company-skills.js";
|
|
import { managedSkillContent } from "./managed-skill-content.js";
|
|
import { skillPackageStore, skillVersionMetadataColumns } from "./skill-package-store.js";
|
|
import { skillPackageMaintenance } from "./skill-package-maintenance.js";
|
|
import { skillPackageManifest } from "./skill-package-files.js";
|
|
import { assertSkillSnapshotPath, MAX_SKILL_SNAPSHOT_BYTES, MAX_SKILL_SNAPSHOT_FILES, skillSnapshotHash, snapshotFile } from "./skill-snapshot.js";
|
|
import { protectedVersions, withSkillVersionCacheLock } from "./skill-version-cache.js";
|
|
import { getStorageService, type StorageService } from "../storage/index.js";
|
|
|
|
type Page = { companyId?: string; after?: string; id?: string; limit?: number; signal?: AbortSignal };
|
|
type Conversion = Page & { apply?: boolean; writersStopped?: boolean };
|
|
const limit = (options: Page) => Math.min(50, Math.max(1, options.limit ?? 10));
|
|
const legacyManaged = (skill: typeof companySkills.$inferSelect) => skill.sourceType === "local_path" && skill.metadata?.sourceKind === "managed_local";
|
|
const linkedLocal = (skill: typeof companySkills.$inferSelect) => skill.sourceType === "local_path"
|
|
&& !legacyManaged(skill) && skill.metadata?.sourceKind !== "paperclip_bundled";
|
|
function coversInstalledInventory(skill: typeof companySkills.$inferSelect, files: Array<{ path: string }>) {
|
|
const paths = new Set(files.map(file => file.path));
|
|
return paths.has("SKILL.md") && skill.fileInventory.every(file => typeof file.path === "string" && paths.has(file.path));
|
|
}
|
|
|
|
async function legacyFiles(skill: typeof companySkills.$inferSelect, signal?: AbortSignal) {
|
|
if (!skill.sourceLocator || !path.isAbsolute(skill.sourceLocator)) return null;
|
|
const source = path.resolve(skill.sourceLocator);
|
|
const root = path.basename(source) === "SKILL.md" ? path.dirname(source) : source;
|
|
const stat = await fs.lstat(root).catch((error: NodeJS.ErrnoException) => {
|
|
if (error.code === "ENOENT") return null;
|
|
throw error;
|
|
});
|
|
if (!stat) return null;
|
|
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Legacy skill root is not a safe directory");
|
|
const files: CompanySkillVersionFileInventoryEntry[] = [];
|
|
let bytes = 0;
|
|
async function visit(directory: string) {
|
|
for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
|
|
signal?.throwIfAborted();
|
|
if (entry.name === ".git" || entry.name === "node_modules") continue;
|
|
const absolute = path.join(directory, entry.name);
|
|
if (entry.isSymbolicLink()) throw new Error("Legacy skill contains a symbolic link");
|
|
if (entry.isDirectory()) { await visit(absolute); continue; }
|
|
if (!entry.isFile()) throw new Error("Legacy skill contains an unsupported file");
|
|
const relative = assertSkillSnapshotPath(path.relative(root, absolute).split(path.sep).join("/"));
|
|
const handle = await fs.open(absolute, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
try {
|
|
const stat = await handle.stat();
|
|
if (!stat.isFile()) throw new Error("Legacy skill contains an unsupported file");
|
|
bytes += stat.size;
|
|
if (files.length >= MAX_SKILL_SNAPSHOT_FILES || bytes > MAX_SKILL_SNAPSHOT_BYTES) throw new Error("Legacy skill exceeds package limits");
|
|
const body = Buffer.alloc(stat.size);
|
|
let offset = 0;
|
|
while (offset < body.length) {
|
|
signal?.throwIfAborted();
|
|
const { bytesRead } = await handle.read(body, offset, body.length - offset, offset);
|
|
if (!bytesRead) throw new Error("Legacy skill changed during conversion");
|
|
offset += bytesRead;
|
|
}
|
|
const after = await handle.stat();
|
|
if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) throw new Error("Legacy skill changed during conversion");
|
|
files.push(snapshotFile(relative, classifyInventoryKind(relative), body, Boolean(stat.mode & 0o111)));
|
|
} finally { await handle.close(); }
|
|
}
|
|
}
|
|
await visit(root);
|
|
if (!files.some(file => file.path === "SKILL.md" && file.encoding !== "base64")) throw new Error("Legacy skill is missing UTF-8 SKILL.md");
|
|
return files;
|
|
}
|
|
|
|
export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
|
const store = skillPackageStore(db, storage);
|
|
const content = managedSkillContent(db, db, storage);
|
|
const provider = () => (storage ?? getStorageService()).provider;
|
|
function scope(options: Page) {
|
|
return and(options.companyId ? eq(companySkills.companyId, options.companyId) : undefined,
|
|
options.id ? eq(companySkills.id, options.id) : undefined,
|
|
options.after ? gt(companySkills.id, options.after) : undefined);
|
|
}
|
|
async function installations(options: Conversion = {}) {
|
|
if (options.apply && !options.writersStopped) throw conflict("Installation conversion requires stopped admission and retired legacy writers (--writers-stopped).");
|
|
const skills = await db.select().from(companySkills).where(scope(options)).orderBy(asc(companySkills.id)).limit(limit(options));
|
|
const results: Array<{ skillId: string; companyId: string; status: string; versionId?: string | null; reason?: string }> = [];
|
|
for (const skill of skills) {
|
|
options.signal?.throwIfAborted();
|
|
const catalogOrigin = skill.sourceType === "catalog" && !skill.metadata?.originVersionId;
|
|
if (linkedLocal(skill)) {
|
|
results.push({ skillId: skill.id, companyId: skill.companyId, status: "linked_local", versionId: skill.currentVersionId });
|
|
continue;
|
|
}
|
|
try {
|
|
const version = skill.currentVersionId ? await store.version(skill.companyId, skill.id, skill.currentVersionId) : null;
|
|
const complete = version && coversInstalledInventory(skill, await store.versionInventory(version));
|
|
if (!legacyManaged(skill) && !catalogOrigin && complete) {
|
|
results.push({ skillId: skill.id, companyId: skill.companyId, status: "unchanged", versionId: skill.currentVersionId });
|
|
continue;
|
|
}
|
|
const pins = await protectedVersions(db, skill.companyId);
|
|
if (pins.versions === null) throw new Error("Active run lacks an exact durable skill selection; settle or snapshot it on the legacy server first");
|
|
const saved = version ? await store.versionFiles(version) : null;
|
|
const local = await legacyFiles(skill, options.signal);
|
|
const completeSaved = saved && coversInstalledInventory(skill, saved) ? saved : null;
|
|
const files = local ?? completeSaved ?? ((skill.sourceType === "github" || skill.sourceType === "skills_sh" || skill.sourceType === "url")
|
|
? await companySkillService(db).captureLegacyInstallation(skill.companyId, skill.id) : null);
|
|
const origin = catalogOrigin && typeof skill.metadata?.originSnapshotLocator === "string"
|
|
? await legacyFiles({ ...skill, sourceLocator: skill.metadata.originSnapshotLocator }, options.signal) : null;
|
|
if (catalogOrigin && !origin && skill.metadata?.userModifiedAt) {
|
|
throw new Error("Catalog reset snapshot is unavailable; preserve the original installed package before conversion");
|
|
}
|
|
if (!files?.length || !files.some(file => file.path === "SKILL.md")) throw new Error("Neither complete legacy files nor a saved version is available");
|
|
if (!local && !coversInstalledInventory(skill, files)) {
|
|
throw new Error("Saved version does not cover the installed inventory");
|
|
}
|
|
if (!options.apply) {
|
|
results.push({ skillId: skill.id, companyId: skill.companyId, status: "conversion_required", versionId: skill.currentVersionId });
|
|
continue;
|
|
}
|
|
if (version && saved && !version.packageSnapshotId && skillSnapshotHash(saved) === skillSnapshotHash(files)) {
|
|
await skillPackageMaintenance(db, storage).migrateVersions({ id: version.id, apply: true, clearLegacy: true, signal: options.signal });
|
|
}
|
|
const candidate = await content.prepare(skill.companyId, files, options.signal);
|
|
if (!candidate.packageSnapshotId || !await store.verifyDurable(skill.companyId, candidate.packageSnapshotId, options.signal)) {
|
|
throw new Error("Final snapshot is not independently recoverable from object storage");
|
|
}
|
|
let originVersionId = typeof skill.metadata?.originVersionId === "string" ? skill.metadata.originVersionId : null;
|
|
if (catalogOrigin && origin && skillSnapshotHash(origin) !== skillSnapshotHash(files)) {
|
|
originVersionId = (await companySkillService(db).createVersion(skill.companyId, skill.id,
|
|
{ label: "Original catalog package" }, { type: "system" }, {
|
|
fileInventory: origin, updateCurrentVersion: false, skipInventoryRefresh: true,
|
|
})).id;
|
|
}
|
|
const markdown = files.find(file => file.path === "SKILL.md")!.content;
|
|
const parsed = parseFrontmatterMarkdown(markdown);
|
|
const { missingSource: _missing, ...metadata } = skill.metadata ?? {};
|
|
const result = await withSkillVersionCacheLock(db, skill.companyId, () => content.publish(skill, candidate, {
|
|
...(legacyManaged(skill) ? { sourceType: "managed", sourceLocator: null } : {}), markdown,
|
|
name: typeof parsed.frontmatter.name === "string" ? parsed.frontmatter.name : skill.name,
|
|
description: typeof parsed.frontmatter.description === "string" ? parsed.frontmatter.description : skill.description,
|
|
fileInventory: files.map(({ path, kind }) => ({ path, kind })),
|
|
trustLevel: files.some(file => file.kind === "script" || file.executable) ? "scripts_executables"
|
|
: files.some(file => file.kind === "asset" || file.kind === "other") ? "assets" : "markdown_only",
|
|
metadata: { ...metadata, ...(legacyManaged(skill) ? { sourceKind: "managed" } : {}),
|
|
...(originVersionId ? { originVersionId } : {}) },
|
|
}, { type: "system" }, { label: "Legacy installation conversion",
|
|
reuseCurrentVersion: Boolean(saved && skillSnapshotHash(saved) === skillSnapshotHash(files)),
|
|
afterPublish: async (tx, row, version) => {
|
|
if (catalogOrigin && !originVersionId) await tx.update(companySkills)
|
|
.set({ metadata: { ...row.metadata, originVersionId: version.id } }).where(eq(companySkills.id, row.id));
|
|
},
|
|
}));
|
|
results.push({ skillId: skill.id, companyId: skill.companyId, status: "converted", versionId: result.version.id });
|
|
} catch (error) {
|
|
results.push({ skillId: skill.id, companyId: skill.companyId, status: "blocked", reason: error instanceof Error ? error.message : "Conversion failed" });
|
|
}
|
|
}
|
|
return { inspected: skills.length, after: skills.at(-1)?.id ?? null, results };
|
|
}
|
|
|
|
async function eligibility(options: Page = {}) {
|
|
const skills = await db.select().from(companySkills).where(scope(options)).orderBy(asc(companySkills.id)).limit(limit(options));
|
|
const results = [];
|
|
for (const skill of skills) {
|
|
const pins = await protectedVersions(db, skill.companyId);
|
|
let status = linkedLocal(skill) ? "linked_local" : legacyManaged(skill) ? "legacy_managed" : "version_backed";
|
|
if (pins.versions === null) status = "unsupported_active_run";
|
|
else if (!linkedLocal(skill) && !skill.currentVersionId) status = "missing_current_version";
|
|
else if (skill.sourceType === "catalog" && !skill.metadata?.originVersionId) status = "legacy_catalog_origin";
|
|
else if (status === "version_backed" && skill.currentVersionId) {
|
|
try {
|
|
const version = await store.version(skill.companyId, skill.id, skill.currentVersionId);
|
|
if (!version) status = "unavailable_current_version";
|
|
else if (!coversInstalledInventory(skill, await store.versionInventory(version))) status = "incomplete_current_version";
|
|
} catch { status = "unavailable_current_version"; }
|
|
}
|
|
results.push({ skillId: skill.id, companyId: skill.companyId, sourceType: skill.sourceType, versionId: skill.currentVersionId, status });
|
|
}
|
|
return { inspected: skills.length, after: skills.at(-1)?.id ?? null, results, contentVerified: false };
|
|
}
|
|
|
|
async function verifyVersions(options: Page = {}) {
|
|
const versions = await db.select(skillVersionMetadataColumns).from(companySkillVersions).where(and(
|
|
options.companyId ? eq(companySkillVersions.companyId, options.companyId) : undefined,
|
|
options.id ? eq(companySkillVersions.id, options.id) : undefined,
|
|
options.after ? gt(companySkillVersions.id, options.after) : undefined,
|
|
)).orderBy(asc(companySkillVersions.id)).limit(limit(options));
|
|
const results = [];
|
|
for (const version of versions) {
|
|
options.signal?.throwIfAborted();
|
|
const packageId = version.repositorySnapshotId ?? version.packageSnapshotId;
|
|
let status = "missing_package";
|
|
try {
|
|
if (packageId) {
|
|
const receipt = await store.descriptor(version.companyId, packageId);
|
|
status = !receipt.storage ? "no_durable_receipt" : receipt.storage.provider !== provider() ? "provider_mismatch"
|
|
: receipt.storage.provider === "local_disk" ? "local_storage" : "remote_storage";
|
|
if (receipt.storage && receipt.storage.provider === provider()
|
|
&& !await store.verifyDurable(version.companyId, packageId, options.signal)) status = "corrupt_package";
|
|
if (!receipt.storage && receipt.restorable && version.repositorySnapshotId === packageId) {
|
|
const active = await protectedVersions(db, version.companyId);
|
|
const [protectedRow] = await db.execute(sql`select 1 from company_skills
|
|
where company_id = ${version.companyId} and current_version_id = ${version.id}
|
|
union all select 1 from company_skill_test_runs where company_id = ${version.companyId}
|
|
and status in ('queued', 'running') and skill_version_id = ${version.id}
|
|
union all select 1 from agents where company_id = ${version.companyId}
|
|
and adapter_config::text like ${`%${version.id}%`} limit 1`);
|
|
if (!protectedRow && active.versions && !active.versions.has(version.id)
|
|
&& Date.now() - receipt.createdAt.getTime() >= 30 * 24 * 60 * 60_000) {
|
|
await store.recoveryRecipe(version.companyId, packageId);
|
|
status = "expired_git_history";
|
|
}
|
|
}
|
|
} else {
|
|
const files = await store.versionFiles(version, false, options.signal);
|
|
skillPackageManifest(files);
|
|
status = files.some(file => file.path === "SKILL.md" && file.encoding !== "base64")
|
|
? version.releaseId ? "database_release_snapshot" : "database_snapshot"
|
|
: "incomplete_database_snapshot";
|
|
}
|
|
// A valid archive can still be an incomplete legacy installation. Compare
|
|
// only the current head: historical revisions may legitimately omit files
|
|
// that were added later. Inventory reads do not load SQL package bodies.
|
|
const [installed] = await db.select().from(companySkills).where(and(
|
|
eq(companySkills.companyId, version.companyId), eq(companySkills.id, version.companySkillId),
|
|
eq(companySkills.currentVersionId, version.id),
|
|
));
|
|
if (installed && !linkedLocal(installed)
|
|
&& !coversInstalledInventory(installed, await store.versionInventory(version))) status = "incomplete_current_version";
|
|
} catch { status = "unavailable_or_corrupt_package"; }
|
|
results.push({ companyId: version.companyId, skillId: version.companySkillId, versionId: version.id, packageId, status });
|
|
}
|
|
return { inspected: versions.length, after: versions.at(-1)?.id ?? null, results };
|
|
}
|
|
return { installations, eligibility, verifyVersions };
|
|
}
|