mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 05:47:10 +01:00
fix(skills): settle unreachable remote skill sources when storage moves (#22698)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted stacks move from a disk volume to volume-free storage, and
the durable-data migration must move every skill installation first
> - A remote skill (GitHub, skills.sh or URL) with no local files, no
complete saved version and an unreachable source blocks the move with
`skills:remote_source_unavailable`
> - Both the online and the offline migration refuse it today, so real
stacks stay on volumes forever
> - This pull request settles that case the same way in both paths:
rebuild the skill from its saved instructions, or keep it present but
unavailable until it is reinstalled
> - The benefit is that the move can finish without deleting any bytes
that still exist, and each outcome is logged
## Linked Issues or Issue Description
**What happened?**
A hosted stack could not move to volume-free storage. Two skill
installations had no local files, no complete saved version, and a
remote source that did not answer. The online and offline durable-data
migrations both reported `skills:remote_source_unavailable` and kept the
stack on its volume.
**Expected behavior**
Recovery works without manual repair. If the stored skill instructions
exist, the migration saves them as a new version and marks that version
as rebuilt. If no instructions are stored, the skill stays in the
library, is marked unavailable, is not offered to agents until it is
reinstalled, and does not block the move. The activity log records both
outcomes.
**Steps to reproduce**
1. Create a `github` skill with a pinned commit, an installed inventory
of `SKILL.md` and `reference.md`, and no saved version.
2. Make the remote source return 404.
3. Run the skill installation conversion. It reports `blocked` with code
`remote_source_unavailable`.
**Paperclip version or commit**
`master` at 8ce422e45d.
## What Changed
- `skillInstallationMaintenance().installations` takes a new
`settleUnavailableSources` option. The online and offline migrations
pass it. Direct calls keep the old blocking behavior, so a transient
remote failure outside a storage move never rebuilds a skill.
- Only a source that is gone counts as unavailable: a 404 or 410
response for an installed file. The capture path throws a typed
`RemoteSkillSourceUnavailableError` for these. Other failures (network
errors, 5xx, 429, unpinned revision, blocked scripts, package limits)
keep the `remote_source_unavailable` block.
- When the source is gone and the option is set, the migration rebuilds
the files from the saved incomplete version (if any) plus the stored
`SKILL.md` instructions. It publishes them as a version labelled
"Rebuilt from saved instructions", records
`reconstructedFromStoredContent` (time and missing files) in the skill
metadata, and writes a `company.skill_reconstructed_from_stored_content`
activity entry in the same transaction as the new version. The rebuilt
version is always a new version, never a reuse of the old one.
- When there are no stored instructions either, the migration sets the
existing `missingSource` marker with reason `remote_source_unavailable`
and writes a `company.skill_source_unavailable` activity entry. The
update is conditional on the row being unchanged. Later passes report
`source_unavailable` without calling the remote again.
- Runtime resolution returns `missing` for a marked skill unless a run
explicitly pinned a saved version, which stays usable. Otherwise it
shows with a plain message: the files could not be recovered when
Paperclip moved the company to new storage, and the user can reinstall
the skill. A reinstall replaces the metadata, which clears the marker.
- Eligibility reports `source_unavailable` for a marked skill. The data
contract and the offline skill phases accept it. The version check does
not fail the marked skill's incomplete current version, and it reports
`source_unavailable` for that version when it is an empty or incomplete
database-only snapshot (its bytes are in the database, so nothing stays
on the volume). Package-backed versions keep every check.
- The online migration counts `skillInstallationsReconstructed` and
`skillInstallationsSourceUnavailable` instead of deferring them.
- Other skill blockers (unsafe local source, catalog origin missing,
saved version incomplete without a remote failure, and so on) keep their
existing codes.
## Verification
- Red/green: with the service files from `master`, the three first tests
fail. The three review follow-up tests (503 stays blocked, empty saved
version verifies, pinned version stays available) fail on the first
commit of this PR and pass now. With this change they pass.
- `cd server && npx vitest run
src/__tests__/managed-skill-content.test.ts
src/services/online-durable-data-migration.test.ts` passes (embedded
PostgreSQL, real files, fetch mocked to 404).
- `npx vitest run src/__tests__/company-skills*.test.ts
src/__tests__/agent-runtime-skills.test.ts
src/__tests__/heartbeat-runtime-skills.test.ts`: all pass except two
`project workspace skill discovery` cases in `company-skills.test.ts`.
These fail identically on `master` in this macOS temp-dir checkout, so
they are not related to this change.
- `npx vitest run src/__tests__/ephemeral-server-data.test.ts` passes.
Its new test fails against the `master` data contract.
- `pnpm --filter @paperclipai/server typecheck` passes.
- `src/__tests__/ephemeral-migration.test.ts` needs an S3 endpoint and
was skipped locally. CI covers it.
## Risks
- A rebuilt skill keeps only the files that could be recovered. The
missing file names go to the metadata and the activity log. The old
version rows and the original remote source fields are kept, so a later
update or reinstall can fetch the exact files again.
- A 404 or 410 during a storage move is treated as final. The skill
stays recoverable through a reinstall if the source comes back. Network
errors and 5xx keep the block, so a stack with an outage at move time
waits for the next pass.
- No schema change.
- The marker guard and type now live in `company-skills.ts`, and the
maintenance module imports them.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code
with tool use (shell, file edits, test runs).
## 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>
This commit is contained in:
1 parent
eddaf14504
commit
2e229c311f
8 files changed
+248
-24
No files matched your search
@@ -42,6 +42,20 @@ it("refuses volume-dependent rows before readiness and accepts their durable rep
|
||||
expect(await db.select().from(agentFileRoots)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("lets a skill whose remote source is gone move without blocking the stack", async () => {
|
||||
vi.stubEnv("PAPERCLIP_EPHEMERAL_SERVER", "true"); vi.stubEnv("PAPERCLIP_DURABLE_AGENT_FILES", "true");
|
||||
const companyId = randomUUID(), skillId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Unavailable skill source", issuePrefix: "GONE" });
|
||||
await db.insert(companySkills).values({ id: skillId, companyId, key: "gone", slug: "gone", name: "Gone",
|
||||
sourceType: "github", markdown: "", fileInventory: [{ path: "SKILL.md", kind: "skill" }] });
|
||||
await expect(assertEphemeralServerData(db)).rejects.toThrow("skills_require_migration");
|
||||
await db.update(companySkills).set({ metadata: { missingSource: { reason: "remote_source_unavailable", sourceType: "github",
|
||||
sourceLocator: null, sourcePath: null, detectedAt: new Date().toISOString() } } }).where(eq(companySkills.id, skillId));
|
||||
await expect(assertEphemeralServerData(db)).resolves.toBeUndefined();
|
||||
expect((await readEphemeralServerDataEligibility(db)).blockers).not.toContain("skills_require_migration");
|
||||
await db.delete(companySkills).where(eq(companySkills.id, skillId));
|
||||
});
|
||||
|
||||
it("keeps replacement readiness independent of a serving controller's unfinished skill selection", async () => {
|
||||
vi.stubEnv("PAPERCLIP_EPHEMERAL_SERVER", "true"); vi.stubEnv("PAPERCLIP_DURABLE_AGENT_FILES", "true");
|
||||
const companyId = randomUUID(), agentId = randomUUID(), skillId = randomUUID(), versionId = randomUUID();
|
||||
|
||||
@@ -16,7 +16,7 @@ import { promises as fs } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { applyPendingMigrations, agents, heartbeatRuns, companySkills, companySkillVersions, companies, createDb, instanceSettings } from "@paperclipai/db";
|
||||
import { activityLog, applyPendingMigrations, agents, heartbeatRuns, companySkills, companySkillVersions, companies, createDb, instanceSettings } from "@paperclipai/db";
|
||||
import { companySkillService } from "../services/company-skills.js";
|
||||
import { listCatalogSkills, readCatalogSkillFile } from "../services/skills-catalog.js";
|
||||
import * as storageModule from "../storage/index.js";
|
||||
@@ -671,6 +671,116 @@ describe.skipIf(!support.supported)("managed skills use committed versions", ()
|
||||
} finally { fetchMock.mockRestore(); }
|
||||
});
|
||||
|
||||
it("rebuilds an unreachable remote installation from its saved instructions while moving storage", async () => {
|
||||
const companyId = await company();
|
||||
const commit = "b".repeat(40);
|
||||
const [skill] = await db.insert(companySkills).values({ companyId, key: "remote-stored", slug: "remote-stored", name: "Remote stored",
|
||||
markdown: "---\nname: Remote stored\n---\n# Stored instructions", sourceType: "github",
|
||||
sourceLocator: `https://github.com/fixture/skills/tree/${commit}/stored`, sourceRef: commit,
|
||||
metadata: { owner: "fixture", repo: "skills", repoSkillDir: "stored" },
|
||||
fileInventory: [{ path: "SKILL.md", kind: "skill" }, { path: "reference.md", kind: "reference" }] }).returning();
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("unavailable", { status: 404 }));
|
||||
try {
|
||||
const maintenance = skillInstallationMaintenance(db);
|
||||
expect((await maintenance.installations({ id: skill!.id, apply: true })).results[0])
|
||||
.toMatchObject({ status: "blocked", code: "remote_source_unavailable" });
|
||||
const [result] = (await maintenance.installations({ id: skill!.id, apply: true, settleUnavailableSources: true })).results;
|
||||
expect(result).toMatchObject({ status: "converted", reconstructed: true });
|
||||
const service = companySkillService(db);
|
||||
expect(await service.readFile(companyId, skill!.id, "SKILL.md")).toMatchObject({ content: "---\nname: Remote stored\n---\n# Stored instructions" });
|
||||
const [row] = await db.select().from(companySkills).where(eq(companySkills.id, skill!.id));
|
||||
expect(row!.currentVersionId).toBe(result!.versionId);
|
||||
expect(row!.metadata?.reconstructedFromStoredContent).toMatchObject({ missingFiles: ["reference.md"] });
|
||||
const [version] = await db.select().from(companySkillVersions).where(eq(companySkillVersions.id, result!.versionId!));
|
||||
expect(version!.label).toBe("Rebuilt from saved instructions");
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, skill!.id))).toEqual([expect.objectContaining({
|
||||
companyId, action: "company.skill_reconstructed_from_stored_content",
|
||||
details: expect.objectContaining({ restoredFiles: ["SKILL.md"], missingFiles: ["reference.md"] }) })]);
|
||||
expect((await maintenance.eligibility({ id: skill!.id })).results[0]).toMatchObject({ status: "version_backed" });
|
||||
expect((await maintenance.verifyVersions({ id: result!.versionId! })).results[0]!.status).not.toBe("incomplete_current_version");
|
||||
} finally { fetchMock.mockRestore(); }
|
||||
});
|
||||
|
||||
it("keeps an unreachable remote installation without saved instructions present but unavailable", async () => {
|
||||
const companyId = await company();
|
||||
const commit = "c".repeat(40);
|
||||
const [skill] = await db.insert(companySkills).values({ companyId, key: "remote-empty", slug: "remote-empty", name: "Remote empty",
|
||||
markdown: "---\nname: Remote empty\n---\n", sourceType: "github",
|
||||
sourceLocator: `https://github.com/fixture/skills/tree/${commit}/empty`, sourceRef: commit,
|
||||
metadata: { owner: "fixture", repo: "skills", repoSkillDir: "empty" },
|
||||
fileInventory: [{ path: "SKILL.md", kind: "skill" }, { path: "reference.md", kind: "reference" }] }).returning();
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("unavailable", { status: 404 }));
|
||||
try {
|
||||
const maintenance = skillInstallationMaintenance(db);
|
||||
expect((await maintenance.eligibility({ id: skill!.id })).results[0]).toMatchObject({ status: "missing_current_version" });
|
||||
expect((await maintenance.installations({ id: skill!.id, apply: true, settleUnavailableSources: true })).results)
|
||||
.toEqual([expect.objectContaining({ skillId: skill!.id, status: "source_unavailable", versionId: null })]);
|
||||
const [row] = await db.select().from(companySkills).where(eq(companySkills.id, skill!.id));
|
||||
expect(row).toMatchObject({ currentVersionId: null, sourceType: "github", markdown: skill!.markdown,
|
||||
metadata: expect.objectContaining({ missingSource: expect.objectContaining({ reason: "remote_source_unavailable" }) }) });
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, skill!.id))).toEqual([expect.objectContaining({
|
||||
companyId, action: "company.skill_source_unavailable" })]);
|
||||
expect((await maintenance.eligibility({ id: skill!.id })).results[0]).toMatchObject({ status: "source_unavailable" });
|
||||
const calls = fetchMock.mock.calls.length;
|
||||
expect((await maintenance.installations({ id: skill!.id, apply: true, settleUnavailableSources: true })).results[0])
|
||||
.toMatchObject({ status: "source_unavailable" });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(calls);
|
||||
const entries = await companySkillService(db).listRuntimeSkillEntries(companyId, { onlyKeys: new Set([skill!.key]), materializeMissing: false });
|
||||
expect(entries.find(entry => entry.key === skill!.key)).toMatchObject({ sourceStatus: "missing",
|
||||
missingDetail: expect.stringContaining("Reinstall it to use it again") });
|
||||
} finally { fetchMock.mockRestore(); }
|
||||
});
|
||||
|
||||
it("keeps a remote installation blocked when its source fails for a reason other than being gone", async () => {
|
||||
const companyId = await company();
|
||||
const commit = "d".repeat(40);
|
||||
const [skill] = await db.insert(companySkills).values({ companyId, key: "remote-flaky", slug: "remote-flaky", name: "Remote flaky",
|
||||
markdown: "# Stored instructions", sourceType: "github",
|
||||
sourceLocator: `https://github.com/fixture/skills/tree/${commit}/flaky`, sourceRef: commit,
|
||||
metadata: { owner: "fixture", repo: "skills", repoSkillDir: "flaky" },
|
||||
fileInventory: [{ path: "SKILL.md", kind: "skill" }, { path: "reference.md", kind: "reference" }] }).returning();
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("busy", { status: 503 }));
|
||||
try {
|
||||
expect((await skillInstallationMaintenance(db).installations({ id: skill!.id, apply: true, settleUnavailableSources: true })).results[0])
|
||||
.toMatchObject({ status: "blocked", code: "remote_source_unavailable" });
|
||||
const [row] = await db.select().from(companySkills).where(eq(companySkills.id, skill!.id));
|
||||
expect(row).toMatchObject({ currentVersionId: null, metadata: { owner: "fixture", repo: "skills", repoSkillDir: "flaky" } });
|
||||
} finally { fetchMock.mockRestore(); }
|
||||
});
|
||||
|
||||
it("lets an offline move verify the empty saved version of a skill marked unavailable", async () => {
|
||||
const companyId = await company();
|
||||
const commit = "e".repeat(40);
|
||||
const [skill] = await db.insert(companySkills).values({ companyId, key: "remote-hollow", slug: "remote-hollow", name: "Remote hollow",
|
||||
markdown: "", sourceType: "github", sourceLocator: `https://github.com/fixture/skills/tree/${commit}/hollow`, sourceRef: commit,
|
||||
metadata: { owner: "fixture", repo: "skills", repoSkillDir: "hollow" },
|
||||
fileInventory: [{ path: "SKILL.md", kind: "skill" }, { path: "reference.md", kind: "reference" }] }).returning();
|
||||
const [version] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skill!.id, revisionNumber: 1, fileInventory: [] }).returning();
|
||||
await db.update(companySkills).set({ currentVersionId: version!.id }).where(eq(companySkills.id, skill!.id));
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("gone", { status: 404 }));
|
||||
try {
|
||||
const maintenance = skillInstallationMaintenance(db);
|
||||
expect((await maintenance.installations({ id: skill!.id, apply: true, settleUnavailableSources: true })).results[0])
|
||||
.toMatchObject({ status: "source_unavailable", versionId: version!.id });
|
||||
expect((await maintenance.verifyVersions({ id: version!.id })).results[0]).toMatchObject({ status: "source_unavailable" });
|
||||
} finally { fetchMock.mockRestore(); }
|
||||
});
|
||||
|
||||
it("still serves an explicitly pinned saved version of a skill marked unavailable", async () => {
|
||||
const companyId = await company();
|
||||
const service = companySkillService(db);
|
||||
const skill = await service.createLocalSkill(companyId, { name: "Pinned unavailable", markdown: "# pinned" });
|
||||
await db.update(companySkills).set({ metadata: { sourceKind: "managed", missingSource: { reason: "remote_source_unavailable",
|
||||
sourceType: "github", sourceLocator: null, sourcePath: null, detectedAt: new Date().toISOString() } } })
|
||||
.where(eq(companySkills.id, skill.id));
|
||||
const keys = new Set([skill.key]);
|
||||
expect((await service.listRuntimeSkillEntries(companyId, { onlyKeys: keys, materializeMissing: false }))
|
||||
.find(entry => entry.key === skill.key)).toMatchObject({ sourceStatus: "missing" });
|
||||
expect((await service.listRuntimeSkillEntries(companyId, { onlyKeys: keys, admittedVersionsOnly: true,
|
||||
versionSelections: new Map([[skill.key, skill.currentVersionId!]]) })).find(entry => entry.key === skill.key))
|
||||
.toMatchObject({ sourceStatus: "available" });
|
||||
});
|
||||
|
||||
it("rejects unsafe legacy sources without publishing a partial conversion", async () => {
|
||||
const companyId = await company();
|
||||
const directory = path.join(root, `unsafe-${randomUUID()}`);
|
||||
|
||||
@@ -116,9 +116,11 @@ export async function migrateEphemeralServerData(db: Db, input: {
|
||||
after = undefined;
|
||||
for (;;) {
|
||||
signal.throwIfAborted();
|
||||
const page = await skills.installations({ apply: true, writersStopped: true, after, limit: 50, signal });
|
||||
if (page.results.some(row => !["converted", "unchanged"].includes(row.status))) throw new Error("skill_installation_migration_blocked");
|
||||
const page = await skills.installations({ apply: true, writersStopped: true, settleUnavailableSources: true, after, limit: 50, signal });
|
||||
if (page.results.some(row => !["converted", "unchanged", "source_unavailable"].includes(row.status))) throw new Error("skill_installation_migration_blocked");
|
||||
counts.skillInstallations = (counts.skillInstallations ?? 0) + page.inspected;
|
||||
counts.skillInstallationsReconstructed = (counts.skillInstallationsReconstructed ?? 0) + page.results.filter(row => row.reconstructed).length;
|
||||
counts.skillInstallationsSourceUnavailable = (counts.skillInstallationsSourceUnavailable ?? 0) + page.results.filter(row => row.status === "source_unavailable").length;
|
||||
if (page.inspected < 50 || !page.after) break;
|
||||
after = page.after;
|
||||
}
|
||||
@@ -130,7 +132,7 @@ export async function migrateEphemeralServerData(db: Db, input: {
|
||||
for (;;) {
|
||||
signal.throwIfAborted();
|
||||
const page = await skills.verifyVersions({ after, limit: 50, signal });
|
||||
if (page.results.some(row => !["remote_storage", "database_release_snapshot", "database_snapshot", "expired_git_history"].includes(row.status))) {
|
||||
if (page.results.some(row => !["remote_storage", "database_release_snapshot", "database_snapshot", "expired_git_history", "source_unavailable"].includes(row.status))) {
|
||||
throw new Error("skill_version_verification_failed");
|
||||
}
|
||||
counts.verifiedSkillVersions = (counts.verifiedSkillVersions ?? 0) + page.inspected;
|
||||
|
||||
@@ -125,7 +125,7 @@ import {
|
||||
stringifyFrontmatter,
|
||||
} from "@paperclipai/shared";
|
||||
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
|
||||
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
|
||||
import { conflict, forbidden, HttpError, notFound, unprocessable } from "../errors.js";
|
||||
import { ghFetch, gitHubApiBase, resolveRawGitHubUrl } from "./github-fetch.js";
|
||||
import { agentService } from "./agents.js";
|
||||
import { issueDocumentSelect, mapIssueDocumentRow } from "./documents.js";
|
||||
@@ -374,9 +374,15 @@ type SkillSourceMeta = {
|
||||
auditScanVersion?: string;
|
||||
};
|
||||
|
||||
type SkillMissingSourceMarker = {
|
||||
reason: "local_source_missing";
|
||||
sourceType: "local_path";
|
||||
export class RemoteSkillSourceUnavailableError extends HttpError {
|
||||
constructor(message: string) { super(422, message); }
|
||||
}
|
||||
|
||||
export const REMOTE_SKILL_SOURCE_UNAVAILABLE = "remote_source_unavailable";
|
||||
|
||||
export type SkillMissingSourceMarker = {
|
||||
reason: "local_source_missing" | typeof REMOTE_SKILL_SOURCE_UNAVAILABLE;
|
||||
sourceType: CompanySkillSourceType;
|
||||
sourceLocator: string | null;
|
||||
sourcePath: string | null;
|
||||
detectedAt: string;
|
||||
@@ -2420,8 +2426,15 @@ async function resolveExistingSkillDirectory(skillDir: string | null) {
|
||||
return dirStat?.isDirectory() && skillFileStat?.isFile() ? skillDir : null;
|
||||
}
|
||||
|
||||
export function remoteSourceUnavailable(skill: { metadata: Record<string, unknown> | null }) {
|
||||
return getMissingSourceMarker(skill.metadata)?.reason === REMOTE_SKILL_SOURCE_UNAVAILABLE;
|
||||
}
|
||||
|
||||
function buildMissingRuntimeSourceDetail(skill: Pick<CompanySkill, "name" | "sourceLocator" | "metadata">) {
|
||||
const marker = getMissingSourceMarker(skill.metadata);
|
||||
if (remoteSourceUnavailable(skill)) {
|
||||
return `Company skill "${skill.name}" is in the library, but its files could not be recovered when Paperclip moved this company to new storage. Reinstall it to use it again.`;
|
||||
}
|
||||
const sourcePath = asString(marker?.sourcePath) ?? normalizeSourceLocatorDirectory(skill.sourceLocator);
|
||||
if (sourcePath) {
|
||||
return `Company skill "${skill.name}" is in the library, but Paperclip cannot find its local source at ${sourcePath}.`;
|
||||
@@ -6036,6 +6049,9 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo
|
||||
skill: CompanySkill,
|
||||
options: RuntimeSkillEntryOptions,
|
||||
): Promise<RuntimeSkillSourceResolution | null> {
|
||||
if (remoteSourceUnavailable(skill) && !options.versionSelections?.get(skill.key)) {
|
||||
return { status: "missing", source: resolveRuntimeSkillMaterializedPath(companyId, skill), detail: buildMissingRuntimeSourceDetail(skill) };
|
||||
}
|
||||
const selectedVersionId = options.versionSelections?.get(skill.key)
|
||||
?? (options.snapshotLatest || skill.sourceType !== "local_path" || skill.metadata?.sourceKind === "paperclip_bundled" || (skill.metadata?.skillSourceId && skill.metadata?.snapshotHash) || skill.accessSourceId ? skill.currentVersionId : null);
|
||||
if (selectedVersionId) {
|
||||
@@ -6556,6 +6572,7 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo
|
||||
const dir = typeof metadata.repoSkillDir === "string" ? normalizeGitHubSkillDirectory(metadata.repoSkillDir, "") : skill.slug;
|
||||
const url = resolveRawGitHubUrl(asString(metadata.hostname) ?? "github.com", owner, repo, skill.sourceRef!, path.posix.join(dir, entry.path));
|
||||
const response = await ghFetch(url);
|
||||
if (response.status === 404 || response.status === 410) throw new RemoteSkillSourceUnavailableError(`Installed file ${entry.path} no longer exists at its source: ${response.status}`);
|
||||
if (!response.ok) throw unprocessable(`Could not acquire installed file ${entry.path}: ${response.status}`);
|
||||
if (!response.body) throw unprocessable("Installed file response has no body.");
|
||||
const reader = response.body.getReader();
|
||||
|
||||
@@ -180,7 +180,7 @@ export async function readEphemeralServerDataEligibility(db: Db, options: { purp
|
||||
let after: string | undefined;
|
||||
for (;;) {
|
||||
const page = await skills.eligibility({ after, limit: 50, purpose: options.purpose });
|
||||
if (page.results.some(skill => skill.status !== "version_backed")) return true;
|
||||
if (page.results.some(skill => skill.status !== "version_backed" && skill.status !== "source_unavailable")) return true;
|
||||
if (page.inspected < 50 || !page.after) return false;
|
||||
after = page.after;
|
||||
}
|
||||
|
||||
@@ -84,6 +84,18 @@ describe("online durable-data migration pass", () => {
|
||||
"run_logs:native_log_archive_source_unsettled": 2 });
|
||||
});
|
||||
|
||||
it("settles skills whose remote source is gone instead of deferring them", async () => {
|
||||
const installations = vi.fn(async () => ({ inspected: 3, after: null, results: [
|
||||
{ skillId: "s1", companyId: "c", status: "converted", reconstructed: true },
|
||||
{ skillId: "s2", companyId: "c", status: "source_unavailable" },
|
||||
{ skillId: "s3", companyId: "c", status: "converted" }] }));
|
||||
const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 },
|
||||
owners({ skillInstallations: () => ({ installations }) }).owners);
|
||||
expect(installations).toHaveBeenCalledWith(expect.objectContaining({ apply: true, writersStopped: false, settleUnavailableSources: true }));
|
||||
expect(result.counts).toMatchObject({ skillInstallations: 1, skillInstallationsReconstructed: 1, skillInstallationsSourceUnavailable: 1 });
|
||||
expect(Object.keys(result.deferred).filter(key => key.startsWith("skills:"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("migrates agent files with live writers, never the offline mode", async () => {
|
||||
const agentFiles = vi.fn(async () => ({ results: [], next: null }));
|
||||
await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, owners({ agentFiles }).owners);
|
||||
|
||||
@@ -205,9 +205,10 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number },
|
||||
return result.inspected < limit || !result.after ? null : result.after;
|
||||
}
|
||||
case "skill_installations": {
|
||||
const result = await skills.installations({ apply: true, writersStopped: false, after, limit, signal });
|
||||
const result = await skills.installations({ apply: true, writersStopped: false, settleUnavailableSources: true, after, limit, signal });
|
||||
for (const row of result.results) {
|
||||
if (row.status === "converted") add(counts, "skillInstallations");
|
||||
if (row.status === "converted") add(counts, row.reconstructed ? "skillInstallationsReconstructed" : "skillInstallations");
|
||||
else if (row.status === "source_unavailable") add(counts, "skillInstallationsSourceUnavailable");
|
||||
else if (row.status !== "unchanged") defer(`skills:${row.status === "blocked" ? row.code ?? "blocked" : row.status}`);
|
||||
}
|
||||
return result.inspected < limit || !result.after ? null : result.after;
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { constants, promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { and, asc, eq, gt, sql } from "drizzle-orm";
|
||||
import { and, asc, eq, gt, isNull, sql } from "drizzle-orm";
|
||||
import { companySkills, companySkillVersions, type Db } from "@paperclipai/db";
|
||||
import { parseFrontmatterMarkdown, type CompanySkillVersionFileInventoryEntry } from "@paperclipai/shared";
|
||||
import { HttpError } from "../errors.js";
|
||||
import { classifyInventoryKind, companySkillService } from "./company-skills.js";
|
||||
import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
|
||||
import { classifyInventoryKind, companySkillService, REMOTE_SKILL_SOURCE_UNAVAILABLE, RemoteSkillSourceUnavailableError,
|
||||
remoteSourceUnavailable as skillSourceUnavailable, type SkillMissingSourceMarker } 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";
|
||||
@@ -15,7 +17,8 @@ import { readPinnedCatalogSkillFiles } from "./skills-catalog.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 };
|
||||
type Conversion = Page & { apply?: boolean; writersStopped?: boolean; settleUnavailableSources?: boolean };
|
||||
const RECONSTRUCTED_FROM_STORED_CONTENT_LABEL = "Rebuilt from saved instructions";
|
||||
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"
|
||||
@@ -104,6 +107,39 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
const store = skillPackageStore(db, storage);
|
||||
const content = managedSkillContent(db, db, storage);
|
||||
const provider = () => (storage ?? getStorageService()).provider;
|
||||
function storedContentFiles(skill: typeof companySkills.$inferSelect, saved: CompanySkillVersionFileInventoryEntry[] | null) {
|
||||
const kept = saved ?? [];
|
||||
const savedEntry = kept.find(file => file.path === "SKILL.md" && file.encoding !== "base64");
|
||||
const entry = savedEntry ?? (parseFrontmatterMarkdown(skill.markdown).body.trim()
|
||||
? snapshotFile("SKILL.md", classifyInventoryKind("SKILL.md"), Buffer.from(skill.markdown, "utf8")) : null);
|
||||
if (!entry) return null;
|
||||
const files = [entry, ...kept.filter(file => file.path !== "SKILL.md")];
|
||||
const present = new Set(files.map(file => file.path));
|
||||
const missingFiles = skill.fileInventory.map(file => file.path).filter((file): file is string => typeof file === "string" && !present.has(file));
|
||||
return { files, missingFiles };
|
||||
}
|
||||
async function markSourceUnavailable(skill: typeof companySkills.$inferSelect) {
|
||||
const publications: ActivityPublication[] = [];
|
||||
await db.transaction(async tx => {
|
||||
const [row] = await tx.update(companySkills).set({
|
||||
metadata: { ...(skill.metadata ?? {}), missingSource: { reason: REMOTE_SKILL_SOURCE_UNAVAILABLE,
|
||||
sourceType: skill.sourceType as SkillMissingSourceMarker["sourceType"], sourceLocator: skill.sourceLocator ?? null,
|
||||
sourcePath: null, detectedAt: new Date().toISOString() } satisfies SkillMissingSourceMarker },
|
||||
updatedAt: new Date(),
|
||||
}).where(and(eq(companySkills.companyId, skill.companyId), eq(companySkills.id, skill.id),
|
||||
skill.sourceLocator ? eq(companySkills.sourceLocator, skill.sourceLocator) : isNull(companySkills.sourceLocator),
|
||||
skill.sourceRef ? eq(companySkills.sourceRef, skill.sourceRef) : isNull(companySkills.sourceRef),
|
||||
sql`${companySkills.metadata}->'missingSource' is null`,
|
||||
skill.currentVersionId ? eq(companySkills.currentVersionId, skill.currentVersionId) : isNull(companySkills.currentVersionId)))
|
||||
.returning({ id: companySkills.id });
|
||||
if (!row) throw blocked("source_changed", "Skill changed while its source was being checked. Retry the operation.", 409);
|
||||
await logActivity(tx as unknown as Db, { companyId: skill.companyId, actorType: "system", actorId: "skill-installation-maintenance",
|
||||
action: "company.skill_source_unavailable", entityType: "company_skill", entityId: skill.id,
|
||||
details: { skillName: skill.name, sourceType: skill.sourceType, hadSavedVersion: Boolean(skill.currentVersionId) } }, publications);
|
||||
});
|
||||
for (const publication of publications) publishActivity(publication);
|
||||
return { skillId: skill.id, companyId: skill.companyId, status: "source_unavailable", versionId: skill.currentVersionId };
|
||||
}
|
||||
function scope(options: Page) {
|
||||
return and(options.companyId ? eq(companySkills.companyId, options.companyId) : undefined,
|
||||
options.id ? eq(companySkills.id, options.id) : undefined,
|
||||
@@ -111,7 +147,8 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
}
|
||||
async function installations(options: Conversion = {}) {
|
||||
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; code?: string }> = [];
|
||||
const results: Array<{ skillId: string; companyId: string; status: string; versionId?: string | null; reason?: string; code?: string;
|
||||
reconstructed?: boolean }> = [];
|
||||
for (const skill of skills) {
|
||||
options.signal?.throwIfAborted();
|
||||
const catalogOrigin = skill.sourceType === "catalog" && !skill.metadata?.originVersionId;
|
||||
@@ -119,6 +156,10 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
results.push({ skillId: skill.id, companyId: skill.companyId, status: "linked_local", versionId: skill.currentVersionId });
|
||||
continue;
|
||||
}
|
||||
if (skillSourceUnavailable(skill)) {
|
||||
results.push({ skillId: skill.id, companyId: skill.companyId, status: "source_unavailable", 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));
|
||||
@@ -135,12 +176,21 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
const completeSaved = saved && coversInstalledInventory(skill, saved) ? saved : null;
|
||||
const unmodifiedCatalog = skill.sourceType === "catalog" && !skill.metadata?.userModifiedAt
|
||||
&& typeof skill.metadata?.originHash === "string" && skill.metadata.installedHash === skill.metadata.originHash;
|
||||
const files = local ?? completeSaved ?? ((skill.sourceType === "github" || skill.sourceType === "skills_sh" || skill.sourceType === "url")
|
||||
let remoteUnavailable = false;
|
||||
const remoteFiles = local ?? completeSaved ?? ((skill.sourceType === "github" || skill.sourceType === "skills_sh" || skill.sourceType === "url")
|
||||
? await companySkillService(db).captureLegacyInstallation(skill.companyId, skill.id).catch(error => {
|
||||
if (options.signal?.aborted) throw error;
|
||||
throw blocked("remote_source_unavailable", error instanceof Error ? error.message : "Remote source is unavailable");
|
||||
if (!options.settleUnavailableSources || !(error instanceof RemoteSkillSourceUnavailableError)) throw blocked(REMOTE_SKILL_SOURCE_UNAVAILABLE, error instanceof Error ? error.message : "Remote source is unavailable");
|
||||
remoteUnavailable = true;
|
||||
return null;
|
||||
})
|
||||
: unmodifiedCatalog ? await pinnedCatalogFiles(skill, options.signal) : null);
|
||||
const reconstructed = remoteUnavailable ? storedContentFiles(skill, saved) : null;
|
||||
if (remoteUnavailable && !reconstructed) {
|
||||
if (!options.apply) return { skillId: skill.id, companyId: skill.companyId, status: "conversion_required", versionId: skill.currentVersionId };
|
||||
return await markSourceUnavailable(skill);
|
||||
}
|
||||
const files = reconstructed?.files ?? remoteFiles;
|
||||
const originSource = catalogOrigin && typeof skill.metadata?.originSnapshotLocator === "string"
|
||||
? { ...skill, sourceLocator: skill.metadata.originSnapshotLocator } : null;
|
||||
const originIdentity = originSource ? await legacySourceIdentity(originSource) : null;
|
||||
@@ -150,7 +200,7 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
throw blocked("catalog_origin_unavailable", "Catalog reset snapshot is unavailable; preserve the original installed package before conversion");
|
||||
}
|
||||
if (!files?.length || !files.some(file => file.path === "SKILL.md")) throw blocked("source_files_unavailable", "Neither complete legacy files nor a saved version is available");
|
||||
if (!local && !coversInstalledInventory(skill, files)) {
|
||||
if (!local && !reconstructed && !coversInstalledInventory(skill, files)) {
|
||||
throw blocked("saved_version_incomplete", "Saved version does not cover the installed inventory");
|
||||
}
|
||||
if (!options.apply) {
|
||||
@@ -169,6 +219,7 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
? await content.prepare(skill.companyId, origin, options.signal) : null;
|
||||
if (originCandidate && !originCandidate.packageSnapshotId) throw blocked("catalog_origin_not_durable", "Catalog origin is not durably available");
|
||||
const markdown = files.find(file => file.path === "SKILL.md")!.content;
|
||||
const publications: ActivityPublication[] = [];
|
||||
const parsed = parseFrontmatterMarkdown(markdown);
|
||||
const { missingSource: _missing, ...metadata } = skill.metadata ?? {};
|
||||
// Object preparation is private. Hold the shared cache lock only for
|
||||
@@ -181,9 +232,11 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
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)),
|
||||
...(originVersionId ? { originVersionId } : {}),
|
||||
...(reconstructed ? { reconstructedFromStoredContent: { at: new Date().toISOString(),
|
||||
missingFiles: reconstructed.missingFiles } } : {}) },
|
||||
}, { type: "system" }, { label: reconstructed ? RECONSTRUCTED_FROM_STORED_CONTENT_LABEL : "Legacy installation conversion",
|
||||
reuseCurrentVersion: Boolean(!reconstructed && saved && skillSnapshotHash(saved) === skillSnapshotHash(files)),
|
||||
validate: async tx => {
|
||||
// publish already holds the canonical slug and skill-row locks.
|
||||
// Recheck filesystem writers after upload, before changing authority.
|
||||
@@ -209,11 +262,17 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
}
|
||||
},
|
||||
afterPublish: async (tx, row, version) => {
|
||||
if (reconstructed) await logActivity(tx as unknown as Db, { companyId: skill.companyId, actorType: "system",
|
||||
actorId: "skill-installation-maintenance", action: "company.skill_reconstructed_from_stored_content",
|
||||
entityType: "company_skill", entityId: skill.id, details: { skillName: skill.name, versionId: version.id,
|
||||
restoredFiles: files.map(file => file.path), missingFiles: reconstructed.missingFiles } }, publications);
|
||||
if (catalogOrigin) await tx.update(companySkills)
|
||||
.set({ metadata: { ...row.metadata, originVersionId: originVersionId ?? version.id } }).where(eq(companySkills.id, row.id));
|
||||
},
|
||||
}));
|
||||
return { skillId: skill.id, companyId: skill.companyId, status: "converted", versionId: result.version.id };
|
||||
for (const publication of publications) publishActivity(publication);
|
||||
return { skillId: skill.id, companyId: skill.companyId, status: "converted", versionId: result.version.id,
|
||||
...(reconstructed ? { reconstructed: true } : {}) };
|
||||
};
|
||||
results.push(await convert());
|
||||
} catch (error) {
|
||||
@@ -236,6 +295,7 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
const pins = options.purpose === "startup" ? undefined : 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 (skillSourceUnavailable(skill)) status = "source_unavailable";
|
||||
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) {
|
||||
@@ -283,9 +343,17 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const [unavailableHead] = await db.select({ id: companySkills.id }).from(companySkills).where(and(
|
||||
eq(companySkills.companyId, version.companyId), eq(companySkills.id, version.companySkillId),
|
||||
eq(companySkills.currentVersionId, version.id), sql`${companySkills.metadata}->'missingSource'->>'reason' = ${REMOTE_SKILL_SOURCE_UNAVAILABLE}`));
|
||||
const files = await store.versionFiles(version, false, options.signal);
|
||||
const complete = files.some(file => file.path === "SKILL.md" && file.encoding !== "base64");
|
||||
if (unavailableHead && (!complete || !files.length)) {
|
||||
results.push({ companyId: version.companyId, skillId: version.companySkillId, versionId: version.id, packageId, status: "source_unavailable" });
|
||||
continue;
|
||||
}
|
||||
skillPackageManifest(files);
|
||||
status = files.some(file => file.path === "SKILL.md" && file.encoding !== "base64")
|
||||
status = complete
|
||||
? version.releaseId ? "database_release_snapshot" : "database_snapshot"
|
||||
: "incomplete_database_snapshot";
|
||||
}
|
||||
@@ -296,7 +364,7 @@ export function skillInstallationMaintenance(db: Db, storage?: StorageService) {
|
||||
eq(companySkills.companyId, version.companyId), eq(companySkills.id, version.companySkillId),
|
||||
eq(companySkills.currentVersionId, version.id),
|
||||
));
|
||||
if (installed && !linkedLocal(installed)
|
||||
if (installed && !linkedLocal(installed) && !skillSourceUnavailable(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 });
|
||||
|
||||
Reference in new issue
Block a user