import { sql } from "drizzle-orm"; import { createHash } from "node:crypto"; import { readSkillMetadata } from "@opengeni/contracts"; import type { OrganizationSkillReach, SkillFile, SkillRecord, SkillWriteContext, SkillWriteReceipt, SkillActor, SkillReviewReference, } from "@opengeni/contracts"; import { rawRows, withWorkspaceRls, withWorkspaceSubjectRls, type Database } from "./database"; import { listSharedWorkspaceIdsForAccount } from "./organization-shared-workspaces"; /** The existing portable artifact framing; never substitutes for a historical content hash. */ export function skillFilesContentHash(files: readonly SkillFile[]): string { const manifest = files .map(({ path, content }) => [path, Buffer.from(content, "utf8").toString("base64")] as const) .sort((left, right) => (left[0] < right[0] ? -1 : left[0] > right[0] ? 1 : 0)); return createHash("sha256").update(JSON.stringify(manifest), "utf8").digest("hex"); } /** * A Skill change the lifecycle refused, rolled back as a whole. `code` is the * SQLSTATE (42501 not permitted, 40001/23505 changed or key reused, 22023/23514 * invalid) and `message` the lifecycle's own fixed explanation, never a query * or its parameters. The original driver error stays as `cause`. */ export class SkillLifecycleRefusedError extends Error { readonly code: string; readonly retryable: boolean; constructor(code: string, message: string, options: { cause: unknown }) { super(message, options); this.name = "SkillLifecycleRefusedError"; this.code = code; this.retryable = code === "40001"; } } const SKILL_LIFECYCLE_REFUSAL_CODES = new Set(["42501", "40001", "23505", "23514", "22023"]); /** The lifecycle routine's RAISE, if that is what failed; driver errors wrap it. */ function skillLifecycleRefusal(error: unknown): SkillLifecycleRefusedError | null { let current: unknown = error; for (let depth = 0; depth < 6 && current && typeof current === "object"; depth++) { const candidate = current as { code?: unknown; message?: unknown; where?: unknown; cause?: unknown; }; if ( typeof candidate.code === "string" && SKILL_LIFECYCLE_REFUSAL_CODES.has(candidate.code) && typeof candidate.message === "string" && typeof candidate.where === "string" && candidate.where.includes("skill_apply_lifecycle") ) { return new SkillLifecycleRefusedError(candidate.code, candidate.message, { cause: error }); } current = candidate.cause; } return null; } /** HTTP authorization must precede this boundary. Agent claims are host-bound, not model input. */ export async function applySkillLifecycle( db: Database, context: SkillWriteContext, request: Record, ): Promise { const run = async (tx: Database) => { if (context.actor.kind !== "agent") { await tx.execute( sql`SELECT set_config('opengeni.principal_kind', ${context.actor.principalKind}, true)`, ); } else await assertSkillReadAttempt(tx, { ...context, actor: context.actor }); if (request.operation === "confirm_response") { const [source] = await rawRows<{ receipt: SkillWriteReceipt }>( tx, sql` SELECT receipt FROM skill_write_receipts WHERE account_id=${context.accountId}::uuid AND workspace_id=${context.workspaceId}::uuid AND operation_id=${request.sourceOperationId as string}::uuid`, ); if (!source?.receipt.skillReview) throw new Error("Skill confirmation source unavailable"); request = { ...request, ...source.receipt.skillReview }; } let content: string | undefined; if (request.operation === "save") { content = (request.files as SkillFile[] | undefined)?.find( (file) => file.path === "SKILL.md", )?.content; } else if (request.operation === "install") { const [main] = await rawRows<{ content: string }>( tx, sql`SELECT content FROM capability_skill_files WHERE skill_facet_id=${request.skillFacetId as string}::uuid AND path='SKILL.md'`, ); content = main?.content; } else if ( request.operation === "approve" || request.operation === "reject" || request.operation === "restore" || request.operation === "confirm_response" ) { const [revision] = await rawRows<{ content: string; title: string; description: string; skill_files: SkillFile[] | null; }>( tx, sql` SELECT content,title,description,skill_files FROM preference_registry_revisions WHERE account_id=${context.accountId}::uuid AND preference_id=${request.skillId as string}::uuid AND id=${request.revisionId as string}::uuid`, ); content = revision?.content; if ( (request.operation === "approve" || request.operation === "confirm_response") && revision ) { const metadata = readSkillMetadata(revision.content); if ( !revision.skill_files || revision.title !== metadata.name || revision.description !== metadata.description ) throw new Error( "Historical Skill approval requires a canonical files-bearing revision; use restore or save", ); } } const removing = request.operation === "remove" || Boolean(request.removalOperationId); if (content === undefined && !removing) throw new Error("Skill lifecycle requires a readable SKILL.md"); const metadata = removing ? null : readSkillMetadata(content!); const canonicalRequest = { ...request, ...(metadata ? { title: metadata.name, description: metadata.description } : {}), }; const rows = await rawRows<{ receipt: SkillWriteReceipt }>( tx, sql` SELECT skill_apply_lifecycle(${context.accountId}::uuid, ${context.workspaceId}::uuid, ${JSON.stringify(context.actor)}::jsonb, ${JSON.stringify(canonicalRequest)}::jsonb) AS receipt `, ); if (!rows[0]) throw new Error("Skill lifecycle returned no durable receipt"); return rows[0].receipt; }; try { return context.actor.kind !== "agent" ? await withWorkspaceSubjectRls(db, context.workspaceId, context.actor.subjectId, run) : await withWorkspaceRls(db, context.workspaceId, run); } catch (error) { // The transaction rolled back. Name the refusal instead of a failed query // that repeats every parameter, including the Skill's text. throw skillLifecycleRefusal(error) ?? error; } } export type SkillReadContext = { accountId: string; workspaceId: string; /** Trusted subject enables the existing user-tier visibility; agents share workspace reads. */ subjectId?: string; }; /** Scope only, for authorizing an exact human deletion retry after the head is gone. * The lifecycle still verifies the complete request fingerprint before replay. */ export async function readSkillRemovalScope( db: Database, context: SkillReadContext & { subjectId: string }, skillId: string, operationId: string, ): Promise<"workspace" | "user" | null> { return withWorkspaceSubjectRls(db, context.workspaceId, context.subjectId, async (tx) => { const [row] = await rawRows<{ scope: string }>( tx, sql` SELECT receipt->>'removedScope' AS scope FROM skill_write_receipts WHERE account_id=${context.accountId}::uuid AND workspace_id=${context.workspaceId}::uuid AND operation_id=${operationId}::uuid AND receipt->>'skillId'=${skillId} AND receipt->>'removed'='true' AND actor->>'kind'='human' AND actor->>'principalKind'='human_session' AND actor->>'subjectId'=${context.subjectId} `, ); return row?.scope === "workspace" || row?.scope === "user" ? row.scope : null; }); } /** Recheck the host-bound attempt before any agent-facing Skill read/search. */ export async function assertSkillReadAttempt( db: Database, context: SkillReadContext & { actor: Extract }, ): Promise { await withWorkspaceRls(db, context.workspaceId, async (tx) => { const rows = await rawRows<{ id: string }>( tx, sql` SELECT a.id FROM sessions s JOIN session_turns t ON t.id=s.active_turn_id AND t.session_id=s.id JOIN session_turn_attempts a ON a.id=t.active_attempt_id AND a.turn_id=t.id WHERE s.account_id=${context.accountId}::uuid AND s.workspace_id=${context.workspaceId}::uuid AND s.id=${context.actor.sessionId}::uuid AND t.account_id=s.account_id AND t.workspace_id=s.workspace_id AND t.id=${context.actor.turnId}::uuid AND t.status IN ('running','requires_action','recovering','waiting_capacity') AND a.id=${context.actor.attemptId}::uuid AND a.account_id=s.account_id AND a.workspace_id=s.workspace_id AND a.session_id=s.id AND a.execution_generation=${context.actor.executionGeneration}::integer AND t.execution_generation=a.execution_generation AND a.state IN ('claimed','running') AND NOT EXISTS (SELECT 1 FROM session_attempt_interruptions i WHERE i.workspace_id=s.workspace_id AND i.attempt_id=a.id AND i.state IN ('pending','delivered','acknowledged')) `, ); if (!rows.length) throw new Error("Skill access requires the exact live attempt"); }); } export type SkillDescriptor = { id: string; stableKey: string; title: string; description: string; revisionId: string; scopeVersion: number; installationVersion: number | null; activationMode: "workspace_managed" | "session_selected"; /** * The SKILL.md of a personal (user-scope) Skill that has no other files and * fits the caller's byte cap; null otherwise. Present only when requested. */ personalSkillMarkdown?: string | null; }; /** Shared visibility predicate for descriptor reads and presence-only projections. */ function activeSkillDescriptorSource(context: SkillReadContext) { return sql` FROM preference_registry_preferences h JOIN preference_registry_revisions r ON r.id=h.active_revision_id AND r.preference_id=h.id AND r.account_id=h.account_id LEFT JOIN skill_source_bindings b ON b.preference_id=h.id AND b.account_id=h.account_id AND b.workspace_id=${context.workspaceId}::uuid LEFT JOIN capability_plugin_installations pi ON pi.plugin_id=b.plugin_id AND pi.account_id=h.account_id AND pi.workspace_id=b.workspace_id AND pi.status='active' ${organizationSkillReachJoin()} WHERE h.account_id=${context.accountId}::uuid AND h.status='active' AND (r.expires_at IS NULL OR r.expires_at > transaction_timestamp()) AND (h.scope='organization' OR (h.scope='workspace' AND h.scope_workspace_id=${context.workspaceId}::uuid) OR (h.scope='user' AND h.scope_subject_id=${context.subjectId ?? null})) AND ${organizationSkillWorksHere(context)} `; } /** The reach row of an organization Skill (migration 1195), aliased `reach`. */ function organizationSkillReachJoin() { return sql`LEFT JOIN organization_skill_reach reach ON h.scope='organization' AND reach.account_id=h.account_id AND reach.preference_id=h.id`; } /** * Whether this workspace's agents use the Skill. Workspace and personal Skills * already passed their scope test. An organization Skill works everywhere * without a reach row; with one, a Personal workspace needs the Personal * switch and a shared workspace needs "all" or its own id in the list. The * workspace's kind is read once, and only when a narrowed Skill asks. */ function organizationSkillWorksHere(context: SkillReadContext) { return sql`(h.scope<>'organization' OR reach.preference_id IS NULL OR CASE WHEN (SELECT get_workspace_kind(${context.accountId}::uuid, ${context.workspaceId}::uuid))='personal' THEN reach.allow_personal_workspaces ELSE reach.allowed_workspace_ids IS NULL OR ${context.workspaceId}::uuid=ANY(reach.allowed_workspace_ids) END)`; } /** Active metadata only: building an index must not transfer every Skill folder. */ export async function listSkillDescriptors( db: Database, context: SkillReadContext, options: { /** Also return the SKILL.md of small single-file personal Skills, up to this many bytes. */ personalSkillMarkdownMaxBytes?: number; } = {}, ): Promise { const cap = options.personalSkillMarkdownMaxBytes; if (cap !== undefined && (!Number.isSafeInteger(cap) || cap <= 0)) throw new Error("personalSkillMarkdownMaxBytes must be a positive integer"); const run = (tx: Database) => rawRows( tx, sql` SELECT h.id, h.stable_key AS "stableKey", r.title, r.description, r.id AS "revisionId", h.scope_version AS "scopeVersion", pi.version AS "installationVersion", coalesce(r.skill_activation_mode,'workspace_managed') AS "activationMode" ${ cap === undefined ? sql`` : sql`, CASE WHEN h.scope='user' THEN CASE WHEN r.skill_files IS NULL THEN CASE WHEN octet_length(r.content) <= ${cap}::int THEN r.content END WHEN jsonb_array_length(r.skill_files)=1 AND r.skill_files->0->>'path'='SKILL.md' AND octet_length(r.skill_files->0->>'content') <= ${cap}::int THEN r.skill_files->0->>'content' END END AS "personalSkillMarkdown"` } ${activeSkillDescriptorSource(context)} ORDER BY h.stable_key,h.id `, ); return context.subjectId ? withWorkspaceSubjectRls(db, context.workspaceId, context.subjectId, run) : withWorkspaceRls(db, context.workspaceId, run); } /** Same live descriptor visibility, without transferring metadata just to test presence. */ export async function hasWorkspaceManagedSkill( db: Database, context: SkillReadContext, ): Promise { const run = async (tx: Database) => { // Aggregate rather than EXISTS: sparse matches must not favor a startup-cost // nested-loop plan that repeatedly probes the same RLS-visible head set. const [row] = await rawRows<{ present: boolean }>( tx, sql`SELECT coalesce(bool_or( coalesce(r.skill_activation_mode,'workspace_managed')='workspace_managed' ), false) AS present ${activeSkillDescriptorSource(context)}`, ); return row!.present; }; return context.subjectId ? withWorkspaceSubjectRls(db, context.workspaceId, context.subjectId, run) : withWorkspaceRls(db, context.workspaceId, run); } export async function listSkillRecords( db: Database, context: SkillReadContext, options: { skillId?: string; revisionId?: string; limit?: number; metadataOnly?: boolean; /** Pending revisions authored by this exact session, independent of event retention. */ sessionId?: string; after?: { stableKey: string; id: string }; /** * People's Skills pages list organization Skills that don't work in this * workspace too, marked `availableHere: false`, so their managers can change * that from anywhere. Agents' reads leave this off and never see them. */ includeOrganizationElsewhere?: boolean; /** Only Skills of this scope (`user` is the person's own). */ scope?: "workspace" | "organization" | "user"; } = {}, ): Promise { const run = async (tx: Database) => { const rows = await rawRows<{ skill: SkillRecord }>( tx, sql` SELECT jsonb_build_object( 'id',h.id,'stableKey',h.stable_key,'scope',h.scope,'scopeVersion',h.scope_version, 'status',CASE WHEN h.status='active' AND EXISTS ( SELECT 1 FROM preference_registry_revisions active WHERE active.id=h.active_revision_id AND active.preference_id=h.id AND active.account_id=h.account_id AND active.expires_at <= transaction_timestamp() ) THEN 'expired' ELSE h.status END, 'activeRevisionId',h.active_revision_id,'revisionId',r.id, 'removalOperationId',r.skill_removal_operation_id, 'activationMode',coalesce(r.skill_activation_mode,'workspace_managed'), 'pendingRevisionIds',coalesce((SELECT jsonb_agg(DISTINCT pending.receipt->>'revisionId') FROM skill_write_receipts pending WHERE pending.account_id=h.account_id AND pending.workspace_id=${context.workspaceId}::uuid AND pending.receipt->>'skillId'=h.id::text AND pending.receipt->>'outcome'='pending' AND coalesce(pending.receipt->>'pendingReason','approval')='approval' AND (pending.receipt->>'revisionId')::uuid=(SELECT newest.id FROM preference_registry_revisions newest WHERE newest.account_id=h.account_id AND newest.preference_id=h.id ORDER BY newest.revision DESC LIMIT 1) AND NOT EXISTS(SELECT 1 FROM preference_registry_events e WHERE e.preference_id=h.id AND e.new_revision_id=(pending.receipt->>'revisionId')::uuid AND e.type IN ('activated','corrected','rejected'))),'[]'::jsonb), 'title',r.title,'description',r.description,'contentHash',r.content_hash, 'files',CASE WHEN ${options.metadataOnly === true} THEN '[]'::jsonb ELSE coalesce(r.skill_files,CASE WHEN r.id IS NULL THEN '[]'::jsonb ELSE jsonb_build_array(jsonb_build_object('path','SKILL.md','content',r.content)) END) END, 'source',CASE WHEN b.preference_id IS NULL THEN NULL ELSE jsonb_build_object( 'pluginId',b.plugin_id,'facetKey',b.facet_key,'skillFacetId',b.skill_facet_id) END, 'reach',CASE WHEN h.scope<>'organization' THEN NULL WHEN reach.preference_id IS NULL THEN jsonb_build_object( 'allowedWorkspaceIds',NULL,'allowPersonalWorkspaces',true) ELSE jsonb_build_object('allowedWorkspaceIds',to_jsonb(reach.allowed_workspace_ids), 'allowPersonalWorkspaces',reach.allow_personal_workspaces) END, 'availableHere',${organizationSkillWorksHere(context)} ) AS skill FROM preference_registry_preferences h LEFT JOIN LATERAL ( SELECT candidate.* FROM preference_registry_revisions candidate WHERE candidate.preference_id=h.id AND candidate.account_id=h.account_id AND (${options.revisionId ?? null}::uuid IS NULL OR candidate.id=${options.revisionId ?? null}::uuid) ORDER BY (${options.sessionId ?? null}::uuid IS NULL AND candidate.id=h.active_revision_id) DESC NULLS LAST,candidate.revision DESC LIMIT 1 ) r ON true LEFT JOIN skill_source_bindings b ON b.preference_id=h.id AND b.account_id=h.account_id AND b.workspace_id=${context.workspaceId}::uuid ${organizationSkillReachJoin()} WHERE h.account_id=${context.accountId}::uuid AND (h.scope='organization' OR (h.scope='workspace' AND h.scope_workspace_id=${context.workspaceId}::uuid) OR (h.scope='user' AND h.scope_subject_id=${context.subjectId ?? null})) AND (${options.includeOrganizationElsewhere === true} OR ${organizationSkillWorksHere(context)}) AND (${options.scope ?? null}::text IS NULL OR h.scope::text=${options.scope ?? null}::text) AND (${options.skillId ?? null}::uuid IS NULL OR h.id=${options.skillId ?? null}::uuid) AND (${options.revisionId ?? null}::uuid IS NULL OR r.id IS NOT NULL) AND (${options.sessionId ?? null}::uuid IS NULL OR EXISTS ( SELECT 1 FROM skill_write_receipts origin WHERE origin.account_id=h.account_id AND origin.workspace_id=${context.workspaceId}::uuid AND origin.actor->>'kind'='agent' AND origin.actor->>'sessionId'=${options.sessionId ?? null} AND origin.receipt->>'skillId'=h.id::text AND origin.receipt->>'revisionId'=r.id::text AND origin.receipt->>'outcome'='pending' AND coalesce(origin.receipt->>'pendingReason','approval')='approval' AND NOT EXISTS (SELECT 1 FROM preference_registry_events settled WHERE settled.account_id=h.account_id AND settled.preference_id=h.id AND settled.new_revision_id=r.id AND settled.type IN ('activated','corrected','rejected')) )) AND (${options.after?.id ?? null}::uuid IS NULL OR (h.stable_key,h.id) > (${options.after?.stableKey ?? ""},${options.after?.id ?? null}::uuid)) ORDER BY h.stable_key,h.id LIMIT ${Math.min(Math.max(options.limit ?? 128, 1), 1000)} `, ); return rows.map((row) => row.skill); }; return context.subjectId ? withWorkspaceSubjectRls(db, context.workspaceId, context.subjectId, run) : withWorkspaceRls(db, context.workspaceId, run); } export type OrganizationSkillReachUpdate = | { status: "updated"; reach: OrganizationSkillReach } | { status: "not_found" } | { status: "not_organization" } | { status: "unknown_workspaces"; workspaceIds: string[] }; /** * Change where an organization Skill works. The caller has checked that the * person may manage organization Skills. Agents in a workspace it no longer * works in stop seeing it from their next turn's Skill index. */ export async function updateOrganizationSkillReach( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; skillId: string; allowedWorkspaceIds: readonly string[] | null; allowPersonalWorkspaces: boolean; }, ): Promise { let allowedWorkspaceIds: string[] | null = null; if (input.allowedWorkspaceIds !== null) { const listed = [...new Set(input.allowedWorkspaceIds)].sort(); if (listed.length > 0) { const sharedIds = new Set(await listSharedWorkspaceIdsForAccount(db, input.accountId)); const unknown = listed.filter((workspaceId) => !sharedIds.has(workspaceId)); if (unknown.length > 0) return { status: "unknown_workspaces", workspaceIds: unknown }; } allowedWorkspaceIds = listed; } return await withWorkspaceSubjectRls(db, input.workspaceId, input.subjectId, async (tx) => { const scope = async () => ( await rawRows<{ scope: string }>( tx, sql`SELECT scope FROM preference_registry_preferences WHERE account_id=${input.accountId}::uuid AND id=${input.skillId}::uuid`, ) )[0]?.scope; const seen = await scope(); if (!seen) return { status: "not_found" }; if (seen !== "organization") return { status: "not_organization" }; // A scope move holds the same head lock and drops the reach row, so taking // it and reading the scope again keeps a reach row off a Skill that just // stopped being the organization's. await rawRows( tx, sql`SELECT preference_id FROM preference_registry_lock_heads(ARRAY[${input.skillId}::uuid])`, ); if ((await scope()) !== "organization") return { status: "not_organization" }; const [before] = await rawRows( tx, sql`SELECT to_jsonb(allowed_workspace_ids) AS "allowedWorkspaceIds", allow_personal_workspaces AS "allowPersonalWorkspaces" FROM organization_skill_reach WHERE account_id=${input.accountId}::uuid AND preference_id=${input.skillId}::uuid`, ); const ids = allowedWorkspaceIds === null ? sql`NULL` : sql`ARRAY(SELECT jsonb_array_elements_text(${JSON.stringify(allowedWorkspaceIds)}::jsonb)::uuid)`; const [reach] = await rawRows( tx, sql`INSERT INTO organization_skill_reach(account_id, preference_id, allowed_workspace_ids, allow_personal_workspaces, updated_by_subject_id) VALUES (${input.accountId}::uuid, ${input.skillId}::uuid, ${ids}, ${input.allowPersonalWorkspaces}, ${input.subjectId}) ON CONFLICT (account_id, preference_id) DO UPDATE SET allowed_workspace_ids=excluded.allowed_workspace_ids, allow_personal_workspaces=excluded.allow_personal_workspaces, updated_by_subject_id=excluded.updated_by_subject_id, updated_at=now() RETURNING to_jsonb(allowed_workspace_ids) AS "allowedWorkspaceIds", allow_personal_workspaces AS "allowPersonalWorkspaces"`, ); await rawRows( tx, sql`INSERT INTO audit_events(account_id, workspace_id, subject_id, action, target_type, target_id, metadata) VALUES (${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.subjectId}, 'skill.reach.changed', 'skill', ${input.skillId}, ${JSON.stringify({ from: before ?? { allowedWorkspaceIds: null, allowPersonalWorkspaces: true }, to: reach, })}::jsonb)`, ); return { status: "updated", reach: reach! }; }); } export class SkillHumanResponseError extends Error { constructor( readonly code: "conflict" | "forbidden" | "invalid", cause: unknown, ) { super( code === "conflict" ? "This Skill changed. Review a new proposal before saving." : code === "forbidden" ? "This Skill approval is not available to this user." : "This Skill proposal cannot be saved.", { cause }, ); this.name = "SkillHumanResponseError"; } } /** Called only inside canonical-human response admission, after the answer and * authorization stamp were written in the same transaction. The lifecycle * independently requires that stamp and the exact initiating human. */ export async function confirmSkillHumanResponse( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; requestId: string }, ): Promise { return withWorkspaceSubjectRls(db, input.workspaceId, input.subjectId, async (tx) => { const [row] = await rawRows<{ questions: Array<{ id: string; skillReview?: { sourceOperationId: string } }>; response: { outcome: string; answers?: Array<{ questionId: string; values: string[] }> }; }>( tx, sql`SELECT questions,response FROM session_human_input_requests WHERE id=${input.requestId}::uuid AND account_id=${input.accountId}::uuid AND workspace_id=${input.workspaceId}::uuid`, ); const question = row?.questions.find((entry) => entry.skillReview); if ( !question || row?.response.outcome !== "answered" || !row.response.answers?.some( (answer) => answer.questionId === question.id && answer.values.length === 1 && ["save", "skip"].includes(answer.values[0]!), ) ) return null; const hash = createHash("sha256") .update("skill-human-response:" + input.requestId) .digest("hex"); const operationId = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-5${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}`; try { return await applySkillLifecycle( tx, { accountId: input.accountId, workspaceId: input.workspaceId, actor: { kind: "human", subjectId: input.subjectId, principalKind: "human_session" }, }, { operation: "confirm_response", operationId, sourceOperationId: question.skillReview!.sourceOperationId, humanInputRequestId: input.requestId, }, ); } catch (error) { let cause: unknown = error; while (cause instanceof Error) { const code = (cause as Error & { code?: string }).code; if (code === "40001" || code === "23505") throw new SkillHumanResponseError("conflict", error); if (code === "42501") throw new SkillHumanResponseError("forbidden", error); if (code === "22023" || code === "23514") throw new SkillHumanResponseError("invalid", error); if ( cause.message === "Skill confirmation source unavailable" || cause.message === "Skill lifecycle requires a readable SKILL.md" ) throw new SkillHumanResponseError("conflict", error); cause = cause.cause; } throw error; } }); } /** Current projection is separate from the immutable original write receipt. */ export async function skillReviewResolution( db: Database, context: SkillReadContext, review: SkillReviewReference, ): Promise<"pending" | "activated" | "removed" | "declined" | "superseded" | "unavailable"> { const run = async (tx: Database) => { const [record] = await listSkillRecords(tx, context, { skillId: review.skillId, revisionId: review.revisionId, metadataOnly: true, limit: 1, }); if (!record) { if (review.removalOperationId) { const [removed] = await rawRows<{ operation_id: string }>( tx, sql` SELECT operation_id FROM skill_write_receipts WHERE account_id=${context.accountId}::uuid AND workspace_id=${context.workspaceId}::uuid AND receipt->>'skillId'=${review.skillId} AND receipt->>'removed'='true' LIMIT 1`, ); if (removed) return "removed" as const; } return "unavailable" as const; } const [event] = await rawRows<{ type: string }>( tx, sql` SELECT type FROM preference_registry_events WHERE account_id=${context.accountId}::uuid AND preference_id=${review.skillId}::uuid AND new_revision_id=${review.revisionId}::uuid AND type IN ('activated','corrected','rejected') ORDER BY version DESC LIMIT 1`, ); if (event) return event.type === "rejected" ? ("declined" as const) : ("activated" as const); const [newer] = await rawRows<{ id: string }>( tx, sql` SELECT newer.id FROM preference_registry_revisions newer JOIN preference_registry_revisions original ON original.id=${review.revisionId}::uuid AND original.account_id=${context.accountId}::uuid AND original.preference_id=${review.skillId}::uuid WHERE newer.account_id=original.account_id AND newer.preference_id=original.preference_id AND newer.revision>original.revision LIMIT 1`, ); if ( newer || record.scopeVersion !== review.expectedScopeVersion || record.activeRevisionId !== review.expectedRevisionId ) return "superseded" as const; return "pending" as const; }; return context.subjectId ? withWorkspaceSubjectRls(db, context.workspaceId, context.subjectId, run) : withWorkspaceRls(db, context.workspaceId, run); }