import type { SkillActor } from "@opengeni/contracts"; import { and, eq, inArray, sql, type SQLWrapper } from "drizzle-orm"; import type { Database } from "./database"; import { releaseOrphanedSkillHeads, type SkillSourceReleaseReceipt } from "./skill-source-release"; import * as schema from "./schema"; export type CapabilityComponentOwnerIdentity = { kind: "direct" | "plugin" | "migration"; id: string; }; export class CapabilityComponentVersionConflictError extends Error { readonly name = "CapabilityComponentVersionConflictError"; constructor(readonly pluginKey: string) { super("Capability component version is pinned by another owner"); } } /** * Plugin ownership is effective only while its installation is active. * Direct and migration ownership is intrinsic. */ export function effectiveCapabilityOwnerSql( ownerKind: SQLWrapper, ownerId: SQLWrapper, ): ReturnType { return sql`( ${ownerKind} in ('direct', 'migration') or ( ${ownerKind} = 'plugin' and exists ( select 1 from ${schema.capabilityPluginInstallations} owning_plugin where owning_plugin.id::text = ${ownerId} and owning_plugin.status = 'active' ) ) )`; } /** Serialize one workspace-local component identity across direct and Plugin installers. */ export async function lockCapabilityComponentIdentity( db: Database, workspaceId: string, pluginKey: string, ): Promise { await db.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`capability-component:${workspaceId}:${pluginKey}`}, 0))`, ); } /** * A child installation selects exactly one immutable Plugin version. Changing * that version is safe only when every retained facet owner is the caller. */ export async function assertCapabilityComponentVersionCanChange( db: Database, input: { workspaceId: string; pluginKey: string; pluginInstallationId: string; owner: CapabilityComponentOwnerIdentity; }, ): Promise { const owners = await db .select({ kind: schema.capabilityComponentOwners.ownerKind, id: schema.capabilityComponentOwners.ownerId, }) .from(schema.capabilityComponentOwners) .innerJoin( schema.capabilityFacetInstallations, eq( schema.capabilityFacetInstallations.id, schema.capabilityComponentOwners.facetInstallationId, ), ) .where( and( eq(schema.capabilityComponentOwners.workspaceId, input.workspaceId), eq(schema.capabilityFacetInstallations.pluginInstallationId, input.pluginInstallationId), effectiveCapabilityOwnerSql( schema.capabilityComponentOwners.ownerKind, schema.capabilityComponentOwners.ownerId, ), ), ); if (owners.some((owner) => owner.kind !== input.owner.kind || owner.id !== input.owner.id)) { throw new CapabilityComponentVersionConflictError(input.pluginKey); } } export async function cleanupOrphanedCapabilityComponents( db: Database, workspaceId: string, facetInstallationIds: string[], skillActor?: SkillActor, lockedSkillHeadIds?: readonly string[], ): Promise { const uniqueIds = [...new Set(facetInstallationIds)]; if (uniqueIds.length === 0) return []; // Source refresh locks the installation before the canonical Skill head. // Use the same order here before taking any newly introduced head locks. await db.execute(sql`SELECT p.id FROM capability_plugin_installations p WHERE p.workspace_id=${workspaceId}::uuid AND p.id IN ( SELECT f.plugin_installation_id FROM capability_facet_installations f WHERE f.workspace_id=${workspaceId}::uuid AND f.id=ANY(string_to_array(${uniqueIds.join(",")},',')::uuid[]) ) ORDER BY p.id FOR UPDATE`); const orphanRows = await db .select({ facetInstallationId: schema.capabilityFacetInstallations.id, pluginInstallationId: schema.capabilityFacetInstallations.pluginInstallationId, }) .from(schema.capabilityFacetInstallations) .where( and( eq(schema.capabilityFacetInstallations.workspaceId, workspaceId), inArray(schema.capabilityFacetInstallations.id, uniqueIds), sql`not exists ( select 1 from ${schema.capabilityComponentOwners} owner where owner.facet_installation_id = ${schema.capabilityFacetInstallations.id} )`, ), ) .for("update"); if (orphanRows.length === 0) return []; const skillReleases = await releaseOrphanedSkillHeads(db, { workspaceId, facetInstallationIds: orphanRows.map((row) => row.facetInstallationId), ...(skillActor ? { skillActor } : {}), ...(lockedSkillHeadIds !== undefined ? { lockedHeadIds: lockedSkillHeadIds } : {}), }); await db.delete(schema.capabilityFacetInstallations).where( inArray( schema.capabilityFacetInstallations.id, orphanRows.map((row) => row.facetInstallationId), ), ); const childInstallations = [...new Set(orphanRows.map((row) => row.pluginInstallationId))]; for (const childInstallationId of childInstallations) { const [remaining] = await db .select({ id: schema.capabilityFacetInstallations.id }) .from(schema.capabilityFacetInstallations) .where(eq(schema.capabilityFacetInstallations.pluginInstallationId, childInstallationId)) .limit(1); if (remaining) continue; await db .update(schema.capabilityPluginInstallations) .set({ status: "disabled", version: sql`${schema.capabilityPluginInstallations.version} + 1`, updatedAt: new Date(), }) .where(eq(schema.capabilityPluginInstallations.id, childInstallationId)); await db .update(schema.capabilityInstallations) .set({ status: "disabled", updatedAt: new Date() }) .where( and( eq(schema.capabilityInstallations.workspaceId, workspaceId), sql`${schema.capabilityInstallations.metadata} ->> 'pluginInstallationId' = ${childInstallationId}`, ), ); } return skillReleases; }