diff --git a/server/src/__tests__/ephemeral-server-data.test.ts b/server/src/__tests__/ephemeral-server-data.test.ts index fdb0c119dd5..52601406b4e 100644 --- a/server/src/__tests__/ephemeral-server-data.test.ts +++ b/server/src/__tests__/ephemeral-server-data.test.ts @@ -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(); diff --git a/server/src/__tests__/managed-skill-content.test.ts b/server/src/__tests__/managed-skill-content.test.ts index 92a993769a4..34927f11ab5 100644 --- a/server/src/__tests__/managed-skill-content.test.ts +++ b/server/src/__tests__/managed-skill-content.test.ts @@ -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()}`); diff --git a/server/src/maintenance/ephemeral-migration-data.ts b/server/src/maintenance/ephemeral-migration-data.ts index 3087f6be256..40fe49d1fa1 100644 --- a/server/src/maintenance/ephemeral-migration-data.ts +++ b/server/src/maintenance/ephemeral-migration-data.ts @@ -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; diff --git a/server/src/services/company-skills.ts b/server/src/services/company-skills.ts index 363f7e229f5..d94bd419018 100644 --- a/server/src/services/company-skills.ts +++ b/server/src/services/company-skills.ts @@ -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 | null }) { + return getMissingSourceMarker(skill.metadata)?.reason === REMOTE_SKILL_SOURCE_UNAVAILABLE; +} + function buildMissingRuntimeSourceDetail(skill: Pick) { 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 { + 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(); diff --git a/server/src/services/ephemeral-server-contract.ts b/server/src/services/ephemeral-server-contract.ts index 7c0bc6107b7..f1cb867d102 100644 --- a/server/src/services/ephemeral-server-contract.ts +++ b/server/src/services/ephemeral-server-contract.ts @@ -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; } diff --git a/server/src/services/online-durable-data-migration.test.ts b/server/src/services/online-durable-data-migration.test.ts index ac7dc188ba8..ab5c327daa2 100644 --- a/server/src/services/online-durable-data-migration.test.ts +++ b/server/src/services/online-durable-data-migration.test.ts @@ -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); diff --git a/server/src/services/online-durable-data-migration.ts b/server/src/services/online-durable-data-migration.ts index a56bbc1d568..e22fc7ae0ff 100644 --- a/server/src/services/online-durable-data-migration.ts +++ b/server/src/services/online-durable-data-migration.ts @@ -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; diff --git a/server/src/services/skill-installation-maintenance.ts b/server/src/services/skill-installation-maintenance.ts index 5360d80a129..5b421cebf85 100644 --- a/server/src/services/skill-installation-maintenance.ts +++ b/server/src/services/skill-installation-maintenance.ts @@ -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 });