Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
[MUL-6125] Ship Private Skill Plugin developer loop (#6900)
Jiayuan Zhang31645cc51014
diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex af71da799d..80c8f005f2 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -82,6 +82,19 @@ multica workspace member invite [email protected]multica workspace member invite [email protected] --role admin```+## Private Plugin development++```bash+multica plugin init ./my-plugin+multica plugin validate ./my-plugin+multica plugin pack ./my-plugin --output ./my-plugin.zip+multica plugin install ./my-plugin.zip --workspace <workspace>+multica plugin list --workspace <workspace>+multica plugin status [installation-id|plugin-key] --workspace <workspace>+```++Private acquisition requires workspace `owner` or `admin` access and both Plugin feature flags. See [Private Skill Plugins](/docs/developers/private-plugins) for the manifest contract, trust model, immutable versions, scope management, and current limits.+## Common issue operations```bashdiff --git a/apps/docs/content/docs/developers/meta.json b/apps/docs/content/docs/developers/meta.jsonindex a3ecbd2741..c197f429b3 100644--- a/apps/docs/content/docs/developers/meta.json+++ b/apps/docs/content/docs/developers/meta.json@@ -1,4 +1,4 @@{"title": "Developers",- "pages": ["contributing", "architecture", "conventions"]+ "pages": ["contributing", "architecture", "conventions", "private-plugins"]}diff --git a/apps/docs/content/docs/developers/private-plugins.mdx b/apps/docs/content/docs/developers/private-plugins.mdxnew file mode 100644index 0000000000..c8d021c065--- /dev/null+++ b/apps/docs/content/docs/developers/private-plugins.mdx@@ -0,0 +1,83 @@+---+title: Private Skill Plugins+description: Build, validate, install, upgrade, roll back, and remove workspace-private Agent capabilities.+---++Private Skill Plugins let a workspace add declarative Agent guidance without publishing a new Multica release. V1 accepts static UTF-8 text for `agent.skill.v1`; it is not an npm, Node, Python, WASM, or native extension system, and Multica never runs package-manager or installation hooks from a Plugin.++The feature is intended for internal and self-hosted dogfood. Both `plugins_v1` and `private_plugins_v1` must be enabled to discover, upload, enable, upgrade, or roll back Private Plugins. If `private_plugins_v1` is turned off after installation, existing Private Plugins remain visible in the generic Installed list so administrators can disable or uninstall them safely. Already pinned Runs remain reproducible. Turning off the base `plugins_v1` flag disables all Plugin management APIs.++## Create a Plugin++```bash+multica plugin init ./my-plugin \+ --key dev.example.release-notes \+ --name "Release Notes" \+ --publisher example.internal+```++The generated directory has one strict manifest and one Skill:++```text+my-plugin/+├── multica.plugin.json+└── skills/+ └── example-skill/+ └── SKILL.md+```++`multica.plugin.json` uses `api_version: multica.plugin/v1`, `kind: Plugin`, a reverse-DNS `metadata.key`, semantic `metadata.version`, the V1 daemon features, and only the `agent.skill.contribute` requested capability. Unknown fields or capabilities are rejected. Each contribution entry must be `skills/<contribution-key>/SKILL.md`.++See `examples/plugins/incident-triage` for a complete reference that is deliberately not part of the production bundled catalog.++## Validate and pack++```bash+multica plugin validate ./my-plugin+multica plugin pack ./my-plugin --output ./my-plugin-0.1.0.zip+multica plugin validate ./my-plugin-0.1.0.zip+```++Packing is deterministic: stable input bytes produce the same ordered ZIP and the same manifest, archive, and artifact digests. Validation rejects unsafe paths, duplicate or case-colliding paths, symlinks, executable files, binary text, undeclared contribution paths, package manifests and install/build hooks, oversized files, and package limits. The Server repeats the complete validation after upload; CLI success is never trusted as authorization or integrity evidence.++## Install or update++Authenticate as a workspace `owner` or `admin`, then run:++```bash+multica plugin install ./my-plugin --workspace acme+multica plugin list --workspace acme+multica plugin status dev.example.release-notes --workspace acme+```++Only archive bytes are uploaded. The Server does not fetch Git or HTTP URLs, and the stored `source_ref` is derived from the archive digest, so local usernames and absolute paths are not retained.++The first install creates a disabled Installation. Review it in **Settings → Plugins**, where it is labeled **Private / Unverified**, then enable it for the whole workspace or selected Agents. Plugin content does not grant authority by itself: effective access remains the intersection of Kernel Policy, Agent tool permissions, Plugin Grant, Binding, and actor approval.++To publish an update, change `metadata.version` and install again. Releases are immutable:++- Re-uploading the same key, version, and content is idempotent.+- Reusing a key and version with different content returns a conflict.+- A new version creates a new immutable release and moves the Installation to it.+- Existing tasks and retries keep their pinned Execution Manifest and never drift.++Use Settings to roll back to an earlier stored version. Installing the source again upgrades to the new version without a Server restart or deployment.++## Isolation and lifecycle++Private identity is owned by a workspace. Two workspaces may use the same manifest key and version with different artifacts, but cannot enumerate, install, bind, roll back to, or resolve each other's identities and releases. Official identity remains global and separately keyed; a Private Plugin cannot claim official trust or enter the global catalog.++Disabling a Binding removes the capability from matching new tasks. Uninstalling disables the Installation and removes it from future capability snapshots. Immutable releases and artifacts referenced by historical Runs remain available for replay; physical garbage collection is outside V1.++Workspace quotas currently allow 100 private releases and 256 MiB of validated artifact content. A failed validation, conflict, or quota check is transactional and leaves no partial identity, release, or Installation.++## Troubleshooting++- **Private Plugin management is not enabled**: enable both `plugins_v1` and `private_plugins_v1` in the Server feature-flag configuration.+- **Package is invalid**: run `multica plugin validate <path>` and fix the first fail-closed diagnostic.+- **Immutable registry conflict**: bump `metadata.version`; never reuse a version for changed content.+- **Incompatible release**: keep `host_api` within the V1 host range and require both `execution-manifest-v1` and `agent-skill-v1`.+- **Installation is healthy but the Skill is absent**: confirm at least one workspace or Agent Binding is enabled and that the new task matches that scope.+- **Permission denied**: installation, update, rollback, Binding changes, and uninstall require a workspace `owner` or `admin`.++V1 does not include remote MCP, Secrets, network grants, Git/HTTP registries, install hooks, arbitrary executable code, UI contributions, automation contributions, community distribution, publisher verification, billing, or artifact garbage collection.diff --git a/examples/plugins/incident-triage/multica.plugin.json b/examples/plugins/incident-triage/multica.plugin.jsonnew file mode 100644index 0000000000..f97e4f535b--- /dev/null+++ b/examples/plugins/incident-triage/multica.plugin.json@@ -0,0 +1,26 @@+{+ "api_version": "multica.plugin/v1",+ "kind": "Plugin",+ "metadata": {+ "key": "dev.multica.incident-triage",+ "name": "Incident Triage",+ "description": "Private incident intake and handoff guidance for workspace Agents.",+ "version": "0.1.0",+ "publisher": "multica.examples"+ },+ "compatibility": {+ "host_api": ">=1.0.0 <2.0.0",+ "required_daemon_features": ["execution-manifest-v1", "agent-skill-v1"]+ },+ "requested_capabilities": ["agent.skill.contribute"],+ "contributes": {+ "agent_skills": [+ {+ "key": "incident-triage",+ "name": "Incident Triage",+ "description": "Structure incident intake, severity assessment, evidence capture, and handoff.",+ "entry": "skills/incident-triage/SKILL.md"+ }+ ]+ }+}diff --git a/examples/plugins/incident-triage/skills/incident-triage/SKILL.md b/examples/plugins/incident-triage/skills/incident-triage/SKILL.mdnew file mode 100644index 0000000000..a03e2ff41b--- /dev/null+++ b/examples/plugins/incident-triage/skills/incident-triage/SKILL.md@@ -0,0 +1,16 @@+---+name: incident-triage+description: Structure incident intake, severity assessment, evidence capture, and handoff.+---++# Incident triage++Use this Skill when a report may describe a production incident.++1. Separate observed facts from hypotheses.+2. Record impact, affected users, start time, and the latest known good state.+3. Assign a provisional severity and state why.+4. Preserve links to logs, alerts, dashboards, and recent changes without copying secrets.+5. End with the current owner, the next decision, and the next update time.++Do not claim a cause until evidence supports it. Do not include credentials, tokens, or private customer content in the handoff.diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex bbbba6b53e..3090c80805 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2215,6 +2215,12 @@ export class ApiClient {});}+ async uninstallPlugin(workspaceId: string, installationId: string): Promise<void> {+ await this.fetch(`/api/workspaces/${workspaceId}/plugins/${installationId}`, {+ method: "DELETE",+ });+ }+// Membersasync listMembers(workspaceId: string): Promise<MemberWithUser[]> {return this.fetch(`/api/workspaces/${workspaceId}/members`);diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 51f2805f4b..72aed3c4a8 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -1383,6 +1383,9 @@ describe("Plugin catalog schemas", () => {expect(parsed.enabled).toBe(false);expect(parsed.lifecycle_status).toBe("error");expect(parsed.bindings).toEqual([]);+ expect(parsed.trust_tier).toBe("");+ expect(parsed.signature_verified).toBe(false);+ expect(parsed.contribution_details).toEqual([]);});it("degrades a malformed catalog response to unsupported and empty", () => {diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 7404a07cc9..cf5c1e928e 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -86,7 +86,28 @@ export const PluginInstallationSchema = z.object({lifecycle_status: z.string().default("error"),health_state: z.string().optional(),health_reason: z.string().optional(),+ description: z.string().optional(),+ publisher: z.string().default(""),+ publisher_type: z.string().default(""),+ trust_tier: z.string().default(""),+ source_kind: z.string().default("bundled"),+ source_ref: z.string().default(""),+ uploader_id: z.string().optional(),+ manifest_digest: z.string().default(""),+ archive_digest: z.string().default(""),+ artifact_digest: z.string().default(""),+ signature_verified: z.boolean().default(false),+ requested_capabilities: z.array(z.string()).default([]),+ available_versions: z.array(z.string()).default([]),contributions: z.array(z.string()).default([]),+ contribution_details: z.array(z.object({+ key: z.string(),+ type: z.string().default(""),+ name: z.string().default(""),+ description: z.string().default(""),+ entry_path: z.string().default(""),+ entry_digest: z.string().default(""),+ }).loose()).default([]),bindings: z.array(PluginBindingSchema).default([]),}).loose();@@ -99,7 +120,19 @@ export const EMPTY_PLUGIN_INSTALLATION: PluginInstallation = {desired_generation: 0,active_generation: 0,lifecycle_status: "error",+ publisher: "",+ publisher_type: "",+ trust_tier: "",+ source_kind: "bundled",+ source_ref: "",+ manifest_digest: "",+ archive_digest: "",+ artifact_digest: "",+ signature_verified: false,+ requested_capabilities: [],+ available_versions: [],contributions: [],+ contribution_details: [],bindings: [],};diff --git a/packages/core/feature-flags/index.ts b/packages/core/feature-flags/index.tsindex b8de1a631d..338037fe5d 100644--- a/packages/core/feature-flags/index.ts+++ b/packages/core/feature-flags/index.ts@@ -17,7 +17,11 @@ export type {export { FeatureFlagService } from "./service";export { StaticProvider } from "./static-provider";export { ChainProvider } from "./chain-provider";-export { COMPOSIO_MCP_APPS_FLAG, PLUGINS_V1_FLAG } from "./keys";+export {+ COMPOSIO_MCP_APPS_FLAG,+ PLUGINS_V1_FLAG,+ PRIVATE_PLUGINS_V1_FLAG,+} from "./keys";export {FeatureFlagsProvider,useFeatureFlagService,diff --git a/packages/core/feature-flags/keys.ts b/packages/core/feature-flags/keys.tsindex 2b234ee230..b613a55632 100644--- a/packages/core/feature-flags/keys.ts+++ b/packages/core/feature-flags/keys.ts@@ -1,2 +1,3 @@export const COMPOSIO_MCP_APPS_FLAG = "composio_mcp_apps";export const PLUGINS_V1_FLAG = "plugins_v1";+export const PRIVATE_PLUGINS_V1_FLAG = "private_plugins_v1";diff --git a/packages/core/plugins/mutations.ts b/packages/core/plugins/mutations.tsindex 0b50d04ae9..e24facc7b6 100644--- a/packages/core/plugins/mutations.ts+++ b/packages/core/plugins/mutations.ts@@ -45,3 +45,11 @@ export function useRollbackPlugin(wsId: string) {onSettled: invalidate,});}++export function useUninstallPlugin(wsId: string) {+ const invalidate = useInvalidatePlugins(wsId);+ return useMutation({+ mutationFn: (installationId: string) => api.uninstallPlugin(wsId, installationId),+ onSettled: invalidate,+ });+}diff --git a/packages/core/types/plugin.ts b/packages/core/types/plugin.tsindex 51e946ad63..6d03d5cf34 100644--- a/packages/core/types/plugin.ts+++ b/packages/core/types/plugin.ts@@ -17,7 +17,21 @@ export interface PluginInstallation {lifecycle_status: string;health_state?: string;health_reason?: string;+ description?: string;+ publisher: string;+ publisher_type: string;+ trust_tier: string;+ source_kind: string;+ source_ref: string;+ uploader_id?: string;+ manifest_digest: string;+ archive_digest: string;+ artifact_digest: string;+ signature_verified: boolean;+ requested_capabilities: string[];+ available_versions: string[];contributions: string[];+ contribution_details: PluginCatalogContribution[];bindings: PluginBinding[];}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 2c4f81e954..8d815bb55c 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -200,6 +200,8 @@"read_only_description": "Workspace owners and admins can install or change Plugin bindings.","empty": "No bundled Plugins are available.","official": "Official",+ "private": "Private",+ "unverified": "Unverified","signed": "Signature verified","signature_unverified": "Signature unverified","incompatible": "Incompatible release",@@ -211,6 +213,7 @@"health": "Health:","bindings": "Enabled scopes","unknown_agent": "Unknown agent",+ "unknown_member": "Unknown member","workspace_scope": "Workspace","agent_scope": "Agent","binding_disabled": "Plugin binding disabled",@@ -222,6 +225,11 @@"disabled": "Plugin disabled for new tasks","upgraded": "Plugin upgraded","rolled_back": "Plugin rolled back",+ "source": "Source and uploader",+ "private_upload": "Private workspace upload",+ "uploaded_by": "Uploaded by",+ "uninstall": "Uninstall",+ "uninstalled": "Plugin uninstalled for future runs","upgrade_to": "Upgrade to v{{version}}","rollback_to": "Rollback to v{{version}}","action_failed": "Plugin action failed",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex b2d2d25547..4fc24dfe53 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -200,6 +200,8 @@"read_only_description": "ワークスペースの owner と admin が Plugin とバインドを変更できます。","empty": "利用可能な bundled Plugins はありません。","official": "公式",+ "private": "プライベート",+ "unverified": "未検証","signed": "署名検証済み","signature_unverified": "署名未検証","incompatible": "互換性のない release",@@ -211,6 +213,7 @@"health": "状態:","bindings": "有効なスコープ","unknown_agent": "不明なエージェント",+ "unknown_member": "不明なメンバー","workspace_scope": "ワークスペース","agent_scope": "エージェント","binding_disabled": "Plugin バインドを無効にしました",@@ -222,6 +225,11 @@"disabled": "新しい作業で Plugin を無効にしました","upgraded": "Plugin をアップグレードしました","rolled_back": "Plugin をロールバックしました",+ "source": "ソースとアップロード者",+ "private_upload": "ワークスペースへのプライベートアップロード",+ "uploaded_by": "アップロード者",+ "uninstall": "アンインストール",+ "uninstalled": "今後の実行から Plugin をアンインストールしました","upgrade_to": "v{{version}} にアップグレード","rollback_to": "v{{version}} にロールバック","action_failed": "Plugin 操作に失敗しました",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 6501856b91..229ca5f19e 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -200,6 +200,8 @@"read_only_description": "워크스페이스 owner와 admin이 Plugin 및 바인딩을 변경할 수 있습니다.","empty": "사용 가능한 bundled Plugins가 없습니다.","official": "공식",+ "private": "비공개",+ "unverified": "확인되지 않음","signed": "서명 확인됨","signature_unverified": "서명 미확인","incompatible": "호환되지 않는 release",@@ -211,6 +213,7 @@"health": "상태:","bindings": "활성 범위","unknown_agent": "알 수 없는 에이전트",+ "unknown_member": "알 수 없는 멤버","workspace_scope": "워크스페이스","agent_scope": "에이전트","binding_disabled": "Plugin 바인딩을 비활성화했습니다",@@ -222,6 +225,11 @@"disabled": "새 작업에서 Plugin을 비활성화했습니다","upgraded": "Plugin을 업그레이드했습니다","rolled_back": "Plugin을 롤백했습니다",+ "source": "소스 및 업로더",+ "private_upload": "워크스페이스 비공개 업로드",+ "uploaded_by": "업로드한 사용자",+ "uninstall": "제거",+ "uninstalled": "향후 실행에서 Plugin을 제거했습니다","upgrade_to": "v{{version}}로 업그레이드","rollback_to": "v{{version}}로 롤백","action_failed": "Plugin 작업에 실패했습니다",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex aa845499e9..12c876adc2 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -200,6 +200,8 @@"read_only_description": "工作区 owner 和 admin 可以安装 Plugin 或更改绑定。","empty": "没有可用的 bundled Plugins。","official": "官方",+ "private": "私有",+ "unverified": "未验证","signed": "签名已验证","signature_unverified": "签名未验证","incompatible": "Release 不兼容",@@ -211,6 +213,7 @@"health": "健康状态:","bindings": "已启用的作用范围","unknown_agent": "未知智能体",+ "unknown_member": "未知成员","workspace_scope": "工作区","agent_scope": "智能体","binding_disabled": "Plugin 绑定已停用",@@ -222,6 +225,11 @@"disabled": "Plugin 已对新 task 停用","upgraded": "Plugin 已升级","rolled_back": "Plugin 已回滚",+ "source": "来源与上传者",+ "private_upload": "工作区私有上传",+ "uploaded_by": "上传者",+ "uninstall": "卸载",+ "uninstalled": "Plugin 已卸载,后续 task 不再使用","upgrade_to": "升级到 v{{version}}","rollback_to": "回滚到 v{{version}}","action_failed": "Plugin 操作失败",diff --git a/packages/views/settings/components/plugins-tab.test.tsx b/packages/views/settings/components/plugins-tab.test.tsxindex b2c94735f1..d4a395d1ad 100644--- a/packages/views/settings/components/plugins-tab.test.tsx+++ b/packages/views/settings/components/plugins-tab.test.tsx@@ -10,6 +10,7 @@ const mockInstall = vi.hoisted(() => vi.fn());const mockSetEnabled = vi.hoisted(() => vi.fn());const mockUpgrade = vi.hoisted(() => vi.fn());const mockRollback = vi.hoisted(() => vi.fn());+const mockUninstall = vi.hoisted(() => vi.fn());const data = vi.hoisted(() => ({catalog: {@@ -46,6 +47,7 @@ const data = vi.hoisted(() => ({},installed: { plugins: [] as Array<Record<string, unknown>> },agents: [{ id: "agent-1", name: "Reviewer", archived_at: null }],+ members: [{ user_id: "member-1", name: "Alice", email: "[email protected]", role: "admin" }],role: "owner" as "owner" | "admin" | "member",}));@@ -54,6 +56,7 @@ vi.mock("@tanstack/react-query", () => ({const key = options.queryKey?.join(":") ?? "";if (key.includes("catalog")) return { data: data.catalog, isPending: false, isError: false };if (key.includes("installed")) return { data: data.installed, isPending: false, isError: false };+ if (key.includes("members")) return { data: data.members, isPending: false, isError: false };return { data: data.agents, isPending: false, isError: false };},}));@@ -66,10 +69,12 @@ vi.mock("@multica/core/plugins", () => ({useSetPluginEnabled: () => ({ mutateAsync: mockSetEnabled, isPending: false }),useUpgradePlugin: () => ({ mutateAsync: mockUpgrade, isPending: false }),useRollbackPlugin: () => ({ mutateAsync: mockRollback, isPending: false }),+ useUninstallPlugin: () => ({ mutateAsync: mockUninstall, isPending: false }),}));vi.mock("@multica/core/workspace/queries", () => ({agentListOptions: () => ({ queryKey: ["agents"] }),+ memberListOptions: () => ({ queryKey: ["members"] }),}));vi.mock("@multica/core/paths", () => ({@@ -99,6 +104,7 @@ describe("PluginsTab", () => {data.installed.plugins = [];mockInstall.mockResolvedValue({});mockSetEnabled.mockResolvedValue({});+ mockUninstall.mockResolvedValue({});});it("renders the install review and keeps installation disabled by default", async () => {@@ -160,4 +166,51 @@ describe("PluginsTab", () => {expect(screen.getByText("review-readiness")).toBeInTheDocument();expect(screen.getByRole("button", { name: "Install" })).toBeDisabled();});++ it("shows a private unverified installation outside the official catalog", async () => {+ const user = userEvent.setup();+ data.installed.plugins = [{+ id: "private-installation-1",+ plugin_key: "dev.acme.incident-guide",+ display_name: "Incident Guide",+ desired_version: "0.2.0",+ active_version: "0.2.0",+ enabled: false,+ desired_generation: 2,+ active_generation: 2,+ lifecycle_status: "installed",+ description: "Private incident response guidance.",+ publisher: "acme.internal",+ publisher_type: "private_dev",+ trust_tier: "private_dev",+ source_kind: "private_dev",+ source_ref: "private://sha256:archive",+ uploader_id: "member-1",+ manifest_digest: "sha256:manifest",+ archive_digest: "sha256:archive",+ artifact_digest: "sha256:artifact",+ signature_verified: false,+ requested_capabilities: ["agent.skill.contribute"],+ available_versions: ["0.2.0", "0.1.0"],+ contributions: ["incident-guide"],+ contribution_details: [{+ key: "incident-guide",+ type: "agent.skill.v1",+ name: "Incident Guide",+ description: "Guide incident response.",+ entry_path: "skills/incident-guide/SKILL.md",+ entry_digest: "sha256:entry",+ }],+ bindings: [],+ }];+ render(<PluginsTab />, { wrapper: Wrapper });++ expect(screen.getByText("Private")).toBeInTheDocument();+ expect(screen.getByText("Unverified")).toBeInTheDocument();+ expect(screen.getByText(/Private workspace upload/)).toBeInTheDocument();+ expect(screen.getByText(/Uploaded by Alice/)).toBeInTheDocument();+ expect(screen.queryByText(/member-1/)).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Uninstall" }));+ await waitFor(() => expect(mockUninstall).toHaveBeenCalledWith("private-installation-1"));+ });});diff --git a/packages/views/settings/components/plugins-tab.tsx b/packages/views/settings/components/plugins-tab.tsxindex fca75224ca..e3c119dff8 100644--- a/packages/views/settings/components/plugins-tab.tsx+++ b/packages/views/settings/components/plugins-tab.tsx@@ -2,9 +2,9 @@import { useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";-import { AlertCircle, CheckCircle2, Loader2, PackageCheck, ShieldCheck } from "lucide-react";+import { AlertCircle, CheckCircle2, Loader2, PackageCheck, ShieldCheck, Trash2 } from "lucide-react";import { toast } from "sonner";-import { agentListOptions } from "@multica/core/workspace/queries";+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";import { useCurrentMember } from "@multica/core/permissions";import {comparePluginVersions,@@ -13,6 +13,7 @@ import {useInstallPlugin,useRollbackPlugin,useSetPluginEnabled,+ useUninstallPlugin,useUpgradePlugin,} from "@multica/core/plugins";import { useCurrentWorkspace } from "@multica/core/paths";@@ -50,10 +51,12 @@ export function PluginsTab() {const catalogQuery = useQuery(pluginCatalogOptions(wsId));const installationsQuery = useQuery(pluginInstallationsOptions(wsId));const agentsQuery = useQuery(agentListOptions(wsId));+ const membersQuery = useQuery(memberListOptions(wsId));const installMutation = useInstallPlugin(wsId);const upgradeMutation = useUpgradePlugin(wsId);const enabledMutation = useSetPluginEnabled(wsId);const rollbackMutation = useRollbackPlugin(wsId);+ const uninstallMutation = useUninstallPlugin(wsId);const [selectedVersions, setSelectedVersions] = useState<Record<string, string>>({});const [selectedScopes, setSelectedScopes] = useState<Record<string, BindingScope>>({});const [selectedAgents, setSelectedAgents] = useState<Record<string, string>>({});@@ -71,12 +74,18 @@ export function PluginsTab() {return [...grouped.entries()];}, [catalogQuery.data?.releases]);- const installations = useMemo(- () => new Map((installationsQuery.data?.plugins ?? []).map((installation) => [installation.plugin_key, installation])),+ const officialInstallations = useMemo(+ () => new Map((installationsQuery.data?.plugins ?? [])+ .filter((installation) => installation.source_kind !== "private_dev")+ .map((installation) => [installation.plugin_key, installation])),[installationsQuery.data?.plugins],);+ const privateInstallations = (installationsQuery.data?.plugins ?? [])+ .filter((installation) => installation.source_kind === "private_dev");const agents = (agentsQuery.data ?? []).filter((agent) => !agent.archived_at);- const isMutating = installMutation.isPending || upgradeMutation.isPending || enabledMutation.isPending || rollbackMutation.isPending;+ const members = membersQuery.data ?? [];+ const isMutating = installMutation.isPending || upgradeMutation.isPending || enabledMutation.isPending+ || rollbackMutation.isPending || uninstallMutation.isPending;const reportError = (error: unknown) => {toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));@@ -138,7 +147,7 @@ export function PluginsTab() {</Alert>) : null}- {releasesByPlugin.length === 0 ? (+ {releasesByPlugin.length === 0 && privateInstallations.length === 0 ? (<SettingsCard><div className="p-6 text-center text-body text-muted-foreground">{t(($) => $.plugins.empty)}@@ -149,7 +158,7 @@ export function PluginsTab() {{releasesByPlugin.map(([pluginKey, versions]) => {const latest = versions[0];if (!latest) return null;- const installation = installations.get(pluginKey) ?? latest.installation;+ const installation = officialInstallations.get(pluginKey) ?? latest.installation;const selectedVersion = selectedVersions[pluginKey] ?? latest.version;const selectedRelease = versions.find((release) => release.version === selectedVersion) ?? latest;const upgrade = installation && comparePluginVersions(latest.version, installation.desired_version) > 0 ? latest : null;@@ -375,6 +384,15 @@ export function PluginsTab() {{t(($) => $.plugins.rollback_to, { version: rollback.version })}</Button>) : null}+ <Button+ variant="destructive"+ disabled={!canManage || isMutating}+ onClick={() => uninstallMutation.mutateAsync(installation.id)+ .then(() => toast.success(t(($) => $.plugins.uninstalled))).catch(reportError)}+ >+ {uninstallMutation.isPending ? <Loader2 className="animate-spin" /> : <Trash2 />}+ {t(($) => $.plugins.uninstall)}+ </Button></div></div>)}@@ -383,6 +401,171 @@ export function PluginsTab() {</SettingsSection>);})}++ {privateInstallations.map((installation) => {+ const scope = selectedScopes[installation.id] ?? "workspace";+ const selectedAgent = selectedAgents[installation.id] ?? agents[0]?.id ?? "";+ const state = installationState(installation);+ const activeBindings = installation.bindings.filter((binding) => binding.enabled === true);+ const uploaderName = members.find((member) => member.user_id === installation.uploader_id)?.name;+ const rollbackVersion = [...installation.available_versions]+ .sort((left, right) => comparePluginVersions(right, left))+ .find((version) => comparePluginVersions(version, installation.desired_version) < 0);+ return (+ <SettingsSection key={installation.id}>+ <SettingsCard>+ <div className="space-y-5 p-4 sm:p-5">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <PackageCheck className="size-4 text-brand" />+ <h3 className="text-title font-semibold">{installation.display_name}</h3>+ <Badge variant="outline">{t(($) => $.plugins.private)}</Badge>+ <Badge variant="destructive">{t(($) => $.plugins.unverified)}</Badge>+ <Badge variant={state === "failed" ? "destructive" : state === "healthy" ? "default" : "secondary"}>+ {state === "activating" ? <Loader2 className="animate-spin" /> : null}+ {t(($) => $.plugins.states[state])}+ </Badge>+ </div>+ {installation.description ? <p className="mt-1 text-body text-muted-foreground">{installation.description}</p> : null}+ <p className="mt-1 break-all font-mono text-caption text-muted-foreground">{installation.plugin_key}</p>+ </div>+ <Badge variant="outline">{installation.desired_version}</Badge>+ </div>++ <div className="grid gap-4 text-caption sm:grid-cols-2">+ <div>+ <div className="font-medium text-foreground">{t(($) => $.plugins.review.contributes)}</div>+ <ul className="mt-1 space-y-1 text-muted-foreground">+ {installation.contribution_details.map((contribution) => (+ <li key={contribution.key}>+ <span className="font-medium text-foreground">{contribution.name || contribution.key}</span>+ {" · "}{contribution.type}{contribution.description ? ` — ${contribution.description}` : ""}+ </li>+ ))}+ </ul>+ </div>+ <div>+ <div className="font-medium text-foreground">{t(($) => $.plugins.review.permissions)}</div>+ <p className="mt-1 text-muted-foreground">+ {installation.requested_capabilities.join(", ") || t(($) => $.plugins.review.none)}+ </p>+ </div>+ <div>+ <div className="font-medium text-foreground">{t(($) => $.plugins.review.publisher)}</div>+ <p className="mt-1 break-all text-muted-foreground">{installation.publisher}</p>+ </div>+ <div>+ <div className="font-medium text-foreground">{t(($) => $.plugins.source)}</div>+ <p className="mt-1 text-muted-foreground">+ {t(($) => $.plugins.private_upload)}+ {installation.uploader_id ? ` · ${t(($) => $.plugins.uploaded_by)} ${uploaderName ?? t(($) => $.plugins.unknown_member)}` : ""}+ </p>+ </div>+ </div>++ <div className="space-y-4 border-t border-surface-border pt-4">+ <div className="flex flex-wrap items-center gap-2 text-caption text-muted-foreground">+ <span>{t(($) => $.plugins.active_version)} {installation.active_version || t(($) => $.plugins.none)}</span>+ <span>·</span>+ <span>{t(($) => $.plugins.health)} {installation.health_state || installation.lifecycle_status}</span>+ </div>++ {activeBindings.length > 0 ? (+ <div className="space-y-2">+ <div className="text-caption font-medium">{t(($) => $.plugins.bindings)}</div>+ {activeBindings.map((binding) => {+ const agentName = binding.scope_type === "agent"+ ? agents.find((agent) => agent.id === binding.scope_id)?.name ?? t(($) => $.plugins.unknown_agent)+ : workspace?.name ?? t(($) => $.plugins.workspace_scope);+ return (+ <div key={`${binding.scope_type}:${binding.scope_id}`} className="flex items-center justify-between gap-3 rounded-lg bg-muted px-3 py-2">+ <span className="text-caption">{binding.scope_type === "agent" ? t(($) => $.plugins.agent_scope) : t(($) => $.plugins.workspace_scope)} · {agentName}</span>+ <Button+ size="xs"+ variant="ghost"+ disabled={!canManage || isMutating}+ onClick={() => enabledMutation.mutateAsync({+ installationId: installation.id,+ enabled: false,+ binding: { scope_type: binding.scope_type === "agent" ? "agent" : "workspace", scope_id: binding.scope_id },+ }).then(() => toast.success(t(($) => $.plugins.binding_disabled))).catch(reportError)}+ >+ {t(($) => $.plugins.disable_binding)}+ </Button>+ </div>+ );+ })}+ </div>+ ) : <p className="text-caption text-muted-foreground">{t(($) => $.plugins.no_bindings)}</p>}++ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">+ <Select+ items={[+ { value: "workspace", label: t(($) => $.plugins.workspace_scope) },+ { value: "agent", label: t(($) => $.plugins.agent_scope) },+ ]}+ value={scope}+ onValueChange={(value) => value && setSelectedScopes((current) => ({ ...current, [installation.id]: value as BindingScope }))}+ >+ <SelectTrigger><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectItem value="workspace">{t(($) => $.plugins.workspace_scope)}</SelectItem>+ <SelectItem value="agent">{t(($) => $.plugins.agent_scope)}</SelectItem>+ </SelectContent>+ </Select>+ {scope === "agent" ? (+ <Select+ items={agents.map((agent) => ({ value: agent.id, label: agent.name }))}+ value={selectedAgent}+ onValueChange={(value) => value && setSelectedAgents((current) => ({ ...current, [installation.id]: value }))}+ >+ <SelectTrigger className="max-w-56"><SelectValue /></SelectTrigger>+ <SelectContent>+ {agents.map((agent) => <SelectItem key={agent.id} value={agent.id}>{agent.name}</SelectItem>)}+ </SelectContent>+ </Select>+ ) : null}+ <Button+ disabled={!canManage || isMutating || (scope === "agent" && !selectedAgent)}+ onClick={() => enabledMutation.mutateAsync({+ installationId: installation.id,+ enabled: true,+ binding: { scope_type: scope, scope_id: scope === "workspace" ? wsId : selectedAgent },+ }).then(() => toast.success(t(($) => $.plugins.enabled))).catch(reportError)}+ >+ {enabledMutation.isPending ? <Loader2 className="animate-spin" /> : <CheckCircle2 />}+ {t(($) => $.plugins.enable_scope)}+ </Button>+ </div>++ <div className="flex flex-wrap gap-2">+ {rollbackVersion ? (+ <Button+ variant="outline"+ disabled={!canManage || isMutating}+ onClick={() => rollbackMutation.mutateAsync({ installationId: installation.id, version: rollbackVersion })+ .then(() => toast.success(t(($) => $.plugins.rolled_back))).catch(reportError)}+ >+ {t(($) => $.plugins.rollback_to, { version: rollbackVersion })}+ </Button>+ ) : null}+ <Button+ variant="destructive"+ disabled={!canManage || isMutating}+ onClick={() => uninstallMutation.mutateAsync(installation.id)+ .then(() => toast.success(t(($) => $.plugins.uninstalled))).catch(reportError)}+ >+ {uninstallMutation.isPending ? <Loader2 className="animate-spin" /> : <Trash2 />}+ {t(($) => $.plugins.uninstall)}+ </Button>+ </div>+ </div>+ </div>+ </SettingsCard>+ </SettingsSection>+ );+ })}</SettingsTab>);}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex d5d6325903..51336bd390 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -103,6 +103,7 @@ var concurrentIndexCleanups = map[string]string{"305_dingtalk_group_route_installation_conversation_unique": "idx_dingtalk_group_route_installation_conversation","306_dingtalk_group_route_workspace_index": "idx_dingtalk_group_route_workspace","307_dingtalk_group_route_id_unique": "idx_dingtalk_group_route_id_unique",+ "311_plugin_identity_scoped_key_index": "idx_plugin_identity_scoped_key",}// concurrentDownIndexCleanups covers every migration whose down direction@@ -120,6 +121,7 @@ var concurrentDownIndexCleanups = map[string]string{"301_drop_redundant_sys_cron_job_plan_index": "idx_sys_cron_exec_job_plan","302_drop_redundant_channel_chat_session_binding_index": "idx_channel_chat_session_binding_session","303_drop_redundant_lark_chat_session_binding_index": "idx_lark_chat_session_binding_session",+ "312_drop_global_plugin_identity_key_index": "idx_plugin_identity_key",}var preMigrationHooks = func() map[string]preMigrationHook {diff --git a/server/cmd/multica/cmd_plugin.go b/server/cmd/multica/cmd_plugin.gonew file mode 100644index 0000000000..18aa0aee5d--- /dev/null+++ b/server/cmd/multica/cmd_plugin.go@@ -0,0 +1,327 @@+package main++import (+ "context"+ "encoding/json"+ "fmt"+ "net/url"+ "os"+ "path/filepath"+ "time"++ "github.com/spf13/cobra"++ "github.com/multica-ai/multica/server/internal/cli"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+)++var pluginCmd = &cobra.Command{Use: "plugin", Short: "Develop and manage Plugins"}++var pluginInitCmd = &cobra.Command{+ Use: "init <dir>",+ Short: "Create a minimal private Skill Plugin",+ Args: exactArgs(1),+ RunE: runPluginInit,+}++var pluginValidateCmd = &cobra.Command{+ Use: "validate <dir|archive>",+ Short: "Validate a Plugin source directory or ZIP",+ Args: exactArgs(1),+ RunE: runPluginValidate,+}++var pluginPackCmd = &cobra.Command{+ Use: "pack <dir>",+ Short: "Create a deterministic Plugin ZIP",+ Args: exactArgs(1),+ RunE: runPluginPack,+}++var pluginInstallCmd = &cobra.Command{+ Use: "install <dir|archive>",+ Short: "Install or update a workspace-private Plugin",+ Args: exactArgs(1),+ RunE: runPluginInstall,+}++var pluginListCmd = &cobra.Command{+ Use: "list",+ Short: "List workspace-private Plugin installations",+ Args: cobra.NoArgs,+ RunE: runPluginList,+}++var pluginStatusCmd = &cobra.Command{+ Use: "status [installation-id|plugin-key]",+ Short: "Show workspace-private Plugin status",+ Args: cobra.MaximumNArgs(1),+ RunE: runPluginStatus,+}++func init() {+ pluginCmd.AddCommand(pluginInitCmd, pluginValidateCmd, pluginPackCmd, pluginInstallCmd, pluginListCmd, pluginStatusCmd)+ pluginInitCmd.Flags().String("key", "dev.local.example-skill", "Reverse-DNS Plugin key")+ pluginInitCmd.Flags().String("name", "Example Skill", "Plugin and Skill display name")+ pluginInitCmd.Flags().String("publisher", "private.local", "Private publisher label")+ pluginValidateCmd.Flags().String("output", "json", "Output format: table or json")+ pluginPackCmd.Flags().String("output", "", "Output ZIP path (required)")+ pluginPackCmd.Flags().String("format", "table", "Result format: table or json")+ pluginInstallCmd.Flags().String("workspace", "", "Workspace ID, slug, or ID prefix")+ pluginInstallCmd.Flags().String("output", "json", "Output format: table or json")+ pluginListCmd.Flags().String("workspace", "", "Workspace ID, slug, or ID prefix")+ pluginListCmd.Flags().String("output", "table", "Output format: table or json")+ pluginStatusCmd.Flags().String("workspace", "", "Workspace ID, slug, or ID prefix")+ pluginStatusCmd.Flags().String("output", "json", "Output format: table or json")+}++func runPluginInit(cmd *cobra.Command, args []string) error {+ dir := filepath.Clean(args[0])+ entries, err := os.ReadDir(dir)+ if err == nil && len(entries) > 0 {+ return fmt.Errorf("plugin directory %q is not empty", dir)+ }+ if err != nil && !os.IsNotExist(err) {+ return fmt.Errorf("inspect plugin directory: %w", err)+ }+ key, _ := cmd.Flags().GetString("key")+ name, _ := cmd.Flags().GetString("name")+ publisher, _ := cmd.Flags().GetString("publisher")+ manifest := plugincontract.Manifest{+ APIVersion: plugincontract.APIVersionV1,+ Kind: plugincontract.KindPlugin,+ Metadata: plugincontract.Metadata{+ Key: key, Name: name, Description: "A workspace-private declarative Skill Plugin.", Version: "0.1.0", Publisher: publisher,+ },+ Compatibility: plugincontract.Compatibility{+ HostAPI: ">=1.0.0 <2.0.0",+ RequiredDaemonFeatures: []string{+ plugincontract.DaemonFeatureExecutionManifestV1,+ plugincontract.DaemonFeatureAgentSkillV1,+ },+ },+ RequestedCapabilities: []string{plugincontract.CapabilityAgentSkillContribute},+ Contributes: plugincontract.ManifestContributions{AgentSkills: []plugincontract.AgentSkillContribution{{+ Key: "example-skill", Name: name, Description: "Explain when and how this Skill should be used.", Entry: "skills/example-skill/SKILL.md",+ }}},+ }+ manifestBytes, err := json.MarshalIndent(manifest, "", " ")+ if err != nil {+ return err+ }+ manifestBytes = append(manifestBytes, '\n')+ if _, _, err := plugincontract.ParseManifest(manifestBytes); err != nil {+ return err+ }+ if err := os.MkdirAll(filepath.Join(dir, "skills", "example-skill"), 0o755); err != nil {+ return err+ }+ if err := os.WriteFile(filepath.Join(dir, plugincontract.ManifestFilename), manifestBytes, 0o644); err != nil {+ return err+ }+ skill := []byte("---\nname: example-skill\ndescription: Explain when this Skill should be used.\n---\n\n# Example Skill\n\nDescribe the declarative instructions the Agent should follow.\n")+ if err := os.WriteFile(filepath.Join(dir, "skills", "example-skill", "SKILL.md"), skill, 0o644); err != nil {+ return err+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Initialized Private Plugin in %s\n", dir)+ return nil+}++type pluginDigestOutput struct {+ PluginKey string `json:"plugin_key"`+ Version string `json:"version"`+ ManifestDigest string `json:"manifest_digest"`+ ArchiveDigest string `json:"archive_digest"`+ ArtifactDigest string `json:"artifact_digest"`+ SizeBytes int64 `json:"size_bytes"`+ FileCount int `json:"file_count"`+}++func loadPluginSource(source string) ([]byte, plugincontract.Artifact, error) {+ info, err := os.Stat(source)+ if err != nil {+ return nil, plugincontract.Artifact{}, err+ }+ if info.IsDir() {+ return plugincontract.PackDirectory(source)+ }+ if !info.Mode().IsRegular() {+ return nil, plugincontract.Artifact{}, fmt.Errorf("plugin source %q is not a directory or regular ZIP", source)+ }+ if info.Size() > plugincontract.MaxArchiveSize {+ return nil, plugincontract.Artifact{}, fmt.Errorf("plugin archive exceeds %d bytes", plugincontract.MaxArchiveSize)+ }+ archive, err := os.ReadFile(source)+ if err != nil {+ return nil, plugincontract.Artifact{}, err+ }+ artifact, err := plugincontract.ValidateArtifact(archive)+ return archive, artifact, err+}++func pluginDigestResult(artifact plugincontract.Artifact) pluginDigestOutput {+ return pluginDigestOutput{+ PluginKey: artifact.Manifest.Metadata.Key, Version: artifact.Manifest.Metadata.Version,+ ManifestDigest: plugincontract.DigestBytes(artifact.CanonicalManifest), ArchiveDigest: artifact.ArchiveDigest,+ ArtifactDigest: artifact.ArtifactDigest, SizeBytes: artifact.SizeBytes, FileCount: len(artifact.Files),+ }+}++func printPluginDigest(cmd *cobra.Command, result pluginDigestOutput, output string) error {+ if output == "json" {+ return cli.PrintJSON(cmd.OutOrStdout(), result)+ }+ cli.PrintTable(cmd.OutOrStdout(), []string{"PLUGIN", "VERSION", "MANIFEST", "ARCHIVE", "ARTIFACT"}, [][]string{{+ result.PluginKey, result.Version, result.ManifestDigest, result.ArchiveDigest, result.ArtifactDigest,+ }})+ return nil+}++func runPluginValidate(cmd *cobra.Command, args []string) error {+ _, artifact, err := loadPluginSource(args[0])+ if err != nil {+ return fmt.Errorf("validate Plugin: %w", err)+ }+ output, _ := cmd.Flags().GetString("output")+ return printPluginDigest(cmd, pluginDigestResult(artifact), output)+}++func runPluginPack(cmd *cobra.Command, args []string) error {+ outputPath, _ := cmd.Flags().GetString("output")+ if outputPath == "" {+ return fmt.Errorf("--output is required")+ }+ archive, artifact, err := plugincontract.PackDirectory(args[0])+ if err != nil {+ return fmt.Errorf("pack Plugin: %w", err)+ }+ if err := os.WriteFile(filepath.Clean(outputPath), archive, 0o644); err != nil {+ return fmt.Errorf("write Plugin archive: %w", err)+ }+ format, _ := cmd.Flags().GetString("format")+ return printPluginDigest(cmd, pluginDigestResult(artifact), format)+}++func pluginWorkspaceID(cmd *cobra.Command) (string, error) {+ workspace, _ := cmd.Flags().GetString("workspace")+ if workspace == "" {+ return requireWorkspaceID(cmd)+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()+ resolved, err := resolveWorkspaceRef(ctx, cmd, workspace)+ if err != nil {+ return "", err+ }+ return resolved.ID, nil+}++func runPluginInstall(cmd *cobra.Command, args []string) error {+ if err := requireHumanLocalCommand("plugin install"); err != nil {+ return err+ }+ archive, artifact, err := loadPluginSource(args[0])+ if err != nil {+ return fmt.Errorf("validate Plugin before install: %w", err)+ }+ workspaceID, err := pluginWorkspaceID(cmd)+ if err != nil {+ return err+ }+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ client.WorkspaceID = workspaceID+ ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(time.Minute))+ defer cancel()+ var result map[string]any+ path := "/api/workspaces/" + workspaceID + "/plugins/private/install"+ if err := client.UploadPrivatePlugin(ctx, path, archive, artifact.Manifest.Metadata.Key+"-"+artifact.Manifest.Metadata.Version+".zip", &result); err != nil {+ return fmt.Errorf("install Private Plugin: %w", err)+ }+ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(cmd.OutOrStdout(), result)+ }+ return printPluginRows(cmd, []map[string]any{result})+}++func fetchPrivatePlugins(cmd *cobra.Command) ([]map[string]any, error) {+ workspaceID, err := pluginWorkspaceID(cmd)+ if err != nil {+ return nil, err+ }+ client, err := newAPIClient(cmd)+ if err != nil {+ return nil, err+ }+ client.WorkspaceID = workspaceID+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()+ var response struct {+ Plugins []map[string]any `json:"plugins"`+ }+ if err := client.GetJSON(ctx, "/api/workspaces/"+workspaceID+"/plugins/private", &response); err != nil {+ return nil, err+ }+ return response.Plugins, nil+}++func printPluginRows(cmd *cobra.Command, plugins []map[string]any) error {+ rows := make([][]string, 0, len(plugins))+ for _, plugin := range plugins {+ rows = append(rows, []string{+ strVal(plugin, "plugin_key"), strVal(plugin, "desired_version"), strVal(plugin, "lifecycle_status"),+ strVal(plugin, "trust_tier"), strVal(plugin, "uploader_id"),+ })+ }+ cli.PrintTable(cmd.OutOrStdout(), []string{"PLUGIN", "VERSION", "STATUS", "TRUST", "UPLOADER"}, rows)+ return nil+}++func runPluginList(cmd *cobra.Command, _ []string) error {+ plugins, err := fetchPrivatePlugins(cmd)+ if err != nil {+ return fmt.Errorf("list Private Plugins: %w", err)+ }+ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(cmd.OutOrStdout(), plugins)+ }+ return printPluginRows(cmd, plugins)+}++func runPluginStatus(cmd *cobra.Command, args []string) error {+ if len(args) == 1 {+ workspaceID, err := pluginWorkspaceID(cmd)+ if err != nil {+ return err+ }+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ client.WorkspaceID = workspaceID+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()+ var plugin map[string]any+ if err := client.GetJSON(ctx, "/api/workspaces/"+workspaceID+"/plugins/private/"+url.PathEscape(args[0]), &plugin); err != nil {+ return fmt.Errorf("get Private Plugin status: %w", err)+ }+ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(cmd.OutOrStdout(), plugin)+ }+ return printPluginRows(cmd, []map[string]any{plugin})+ }+ plugins, err := fetchPrivatePlugins(cmd)+ if err != nil {+ return fmt.Errorf("get Private Plugin status: %w", err)+ }+ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(cmd.OutOrStdout(), plugins)+ }+ return printPluginRows(cmd, plugins)+}diff --git a/server/cmd/multica/cmd_plugin_test.go b/server/cmd/multica/cmd_plugin_test.gonew file mode 100644index 0000000000..8d27e7b6cf--- /dev/null+++ b/server/cmd/multica/cmd_plugin_test.go@@ -0,0 +1,80 @@+package main++import (+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/spf13/cobra"+)++func pluginInitTestCommand(output *bytes.Buffer) *cobra.Command {+ cmd := &cobra.Command{}+ cmd.SetOut(output)+ cmd.Flags().String("key", "dev.example.private-skill", "")+ cmd.Flags().String("name", "Private Skill", "")+ cmd.Flags().String("publisher", "example.local", "")+ return cmd+}++func TestPluginInitValidateAndDeterministicPack(t *testing.T) {+ root := filepath.Join(t.TempDir(), "plugin")+ var output bytes.Buffer+ if err := runPluginInit(pluginInitTestCommand(&output), []string{root}); err != nil {+ t.Fatalf("plugin init: %v", err)+ }++ validate := &cobra.Command{}+ validate.SetOut(&output)+ validate.Flags().String("output", "json", "")+ output.Reset()+ if err := runPluginValidate(validate, []string{root}); err != nil {+ t.Fatalf("plugin validate: %v", err)+ }+ var digest pluginDigestOutput+ if err := json.Unmarshal(output.Bytes(), &digest); err != nil {+ t.Fatalf("decode validate output: %v\n%s", err, output.String())+ }+ if digest.PluginKey != "dev.example.private-skill" || digest.Version != "0.1.0" || digest.ArchiveDigest == "" || digest.ArtifactDigest == "" {+ t.Fatalf("unexpected validate output: %+v", digest)+ }++ first := filepath.Join(t.TempDir(), "first.zip")+ second := filepath.Join(t.TempDir(), "second.zip")+ for _, destination := range []string{first, second} {+ pack := &cobra.Command{}+ pack.SetOut(&output)+ pack.Flags().String("output", destination, "")+ pack.Flags().String("format", "json", "")+ output.Reset()+ if err := runPluginPack(pack, []string{root}); err != nil {+ t.Fatalf("plugin pack: %v", err)+ }+ }+ firstBytes, err := os.ReadFile(first)+ if err != nil {+ t.Fatal(err)+ }+ secondBytes, err := os.ReadFile(second)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(firstBytes, secondBytes) {+ t.Fatal("plugin pack output was not deterministic")+ }+ if _, _, err := loadPluginSource(first); err != nil {+ t.Fatalf("load packed archive: %v", err)+ }+}++func TestPluginInitRefusesNonEmptyDirectory(t *testing.T) {+ root := t.TempDir()+ if err := os.WriteFile(filepath.Join(root, "keep.txt"), []byte("keep"), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := runPluginInit(pluginInitTestCommand(&bytes.Buffer{}), []string{root}); err == nil {+ t.Fatal("plugin init unexpectedly replaced a non-empty directory")+ }+}diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.goindex 81d14b6c0c..8538a7f485 100644--- a/server/cmd/multica/main.go+++ b/server/cmd/multica/main.go@@ -54,6 +54,7 @@ func init() {workspaceCmd.GroupID = groupCorerepoCmd.GroupID = groupCoreskillCmd.GroupID = groupCore+ pluginCmd.GroupID = groupCoresquadCmd.GroupID = groupCorechatCmd.GroupID = groupCore@@ -80,6 +81,7 @@ func init() {rootCmd.AddCommand(workspaceCmd)rootCmd.AddCommand(repoCmd)rootCmd.AddCommand(skillCmd)+ rootCmd.AddCommand(pluginCmd)rootCmd.AddCommand(squadCmd)rootCmd.AddCommand(chatCmd)rootCmd.AddCommand(daemonCmd)diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex c4b85af3f6..d19e03e7f3 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1160,6 +1160,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/runtime-profiles", h.ListRuntimeProfiles)r.Get("/runtime-profiles/{profileId}", h.GetRuntimeProfile)r.Get("/plugins", h.ListPlugins)+ r.Get("/plugins/private", h.ListPrivatePlugins)+ r.Get("/plugins/private/{pluginRef}", h.GetPrivatePluginStatus)r.Get("/plugins/catalog", h.ListPluginCatalog)r.Get("/plugins/catalog/{pluginKey}", h.GetPluginCatalogRelease)})@@ -1180,10 +1182,12 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Put("/runtime-profiles/{profileId}", h.UpdateRuntimeProfile)r.Delete("/runtime-profiles/{profileId}", h.DeleteRuntimeProfile)r.Post("/plugins/install", h.InstallPlugin)+ r.Post("/plugins/private/install", h.InstallPrivatePlugin)r.Post("/plugins/{installationId}/upgrade", h.UpgradePlugin)r.Post("/plugins/{installationId}/enable", h.EnablePlugin)r.Post("/plugins/{installationId}/disable", h.DisablePlugin)r.Post("/plugins/{installationId}/rollback", h.RollbackPlugin)+ r.Delete("/plugins/{installationId}", h.UninstallPlugin)})// Owner-only accessr.With(middleware.RequireWorkspaceRoleFromURL(queries, "id", "owner")).Delete("/", h.DeleteWorkspace)diff --git a/server/internal/cli/client.go b/server/internal/cli/client.goindex b896d6d531..f819cb0a99 100644--- a/server/internal/cli/client.go+++ b/server/internal/cli/client.go@@ -669,6 +669,44 @@ func (c *APIClient) ImportSkillFile(ctx context.Context, fileData []byte, filenareturn json.NewDecoder(resp.Body).Decode(out)}+// UploadPrivatePlugin installs workspace-private Plugin archive bytes. The+// filename is transport metadata only; the Server derives source identity from+// validated manifest content and digests.+func (c *APIClient) UploadPrivatePlugin(ctx context.Context, path string, archive []byte, filename string, out any) error {+ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ part, err := writer.CreateFormFile("artifact", filepath.Base(filename))+ if err != nil {+ return fmt.Errorf("create Plugin artifact form file: %w", err)+ }+ if _, err := part.Write(archive); err != nil {+ return fmt.Errorf("write Plugin artifact: %w", err)+ }+ if err := writer.Close(); err != nil {+ return fmt.Errorf("close Plugin artifact upload: %w", err)+ }++ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+path, &body)+ if err != nil {+ return err+ }+ req.Header.Set("Content-Type", writer.FormDataContentType())+ c.setHeaders(req)+ resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ if resp.StatusCode >= 400 {+ return newHTTPError(http.MethodPost, path, resp)+ }+ if out == nil {+ return nil+ }+ return json.NewDecoder(resp.Body).Decode(out)+}+// DownloadFile downloads a file from the given URL and returns the response body.// This is used for downloading attachments via their signed download_url.// Downloads are limited to 100 MB to match the upload size limit.diff --git a/server/internal/cli/client_test.go b/server/internal/cli/client_test.goindex 0f6f05942a..64e8775639 100644--- a/server/internal/cli/client_test.go+++ b/server/internal/cli/client_test.go@@ -414,6 +414,42 @@ func TestUploadFileWithURL(t *testing.T) {})}+func TestUploadPrivatePlugin(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost || r.URL.Path != "/api/workspaces/ws-1/plugins/private/install" {+ t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)+ }+ if r.Header.Get("Authorization") != "Bearer test-token" || r.Header.Get("X-Workspace-ID") != "ws-1" {+ t.Fatalf("missing authenticated workspace headers: %#v", r.Header)+ }+ file, header, err := r.FormFile("artifact")+ if err != nil {+ t.Fatalf("artifact form file: %v", err)+ }+ defer file.Close()+ contents, err := io.ReadAll(file)+ if err != nil {+ t.Fatal(err)+ }+ if header.Filename != "private.zip" || string(contents) != "zip-bytes" {+ t.Fatalf("unexpected artifact filename=%q content=%q", header.Filename, contents)+ }+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]string{"id": "installation-1"})+ }))+ defer server.Close()++ client := NewAPIClient(server.URL, "ws-1", "test-token")+ var response map[string]string+ err := client.UploadPrivatePlugin(context.Background(), "/api/workspaces/ws-1/plugins/private/install", []byte("zip-bytes"), "private.zip", &response)+ if err != nil {+ t.Fatalf("UploadPrivatePlugin: %v", err)+ }+ if response["id"] != "installation-1" {+ t.Fatalf("unexpected response: %#v", response)+ }+}+func TestNormalizeGOOS(t *testing.T) {cases := map[string]string{"darwin": "macos",diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.goindex c9af98d736..bf3795ac00 100644--- a/server/internal/featureflags/keys.go+++ b/server/internal/featureflags/keys.go@@ -23,6 +23,9 @@ const (// gate pinned Task/Run execution: disabling discovery and management must not// mutate an immutable execution manifest that is already in flight.PluginsV1 = "plugins_v1"+ // PrivatePluginsV1 independently gates workspace-uploaded, unsigned Skill+ // Plugins. It is effective only while the base PluginsV1 contract is also on.+ PrivatePluginsV1 = "private_plugins_v1"// agentBuilderCompat is no longer a release flag. Keep publishing the key// as enabled so installed desktop clients that still gate the AI creation// entry on this config decision receive the permanently enabled behavior.@@ -44,6 +47,7 @@ var frontendPublicFlags = []string{BillingWorkspaceSubscriptions,ComposioMCPApps,PluginsV1,+ PrivatePluginsV1,}func BillingWorkspaceSubscriptionsEnabled(ctx context.Context, flags *featureflag.Service) bool {@@ -58,6 +62,10 @@ func PluginsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {return flags.IsEnabled(ctx, PluginsV1, false)}+func PrivatePluginsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {+ return PluginsV1Enabled(ctx, flags) && flags.IsEnabled(ctx, PrivatePluginsV1, false)+}+func EvaluateFrontendPublicFlags(ctx context.Context, flags *featureflag.Service) map[string]bool {out := make(map[string]bool, len(frontendPublicFlags)+3)for _, key := range frontendPublicFlags {diff --git a/server/internal/featureflags/keys_test.go b/server/internal/featureflags/keys_test.goindex c38abcf093..5caa01b507 100644--- a/server/internal/featureflags/keys_test.go+++ b/server/internal/featureflags/keys_test.go@@ -3,6 +3,8 @@ package featureflagsimport ("context""testing"++ "github.com/multica-ai/multica/server/pkg/featureflag")func TestResourceLabelsCompatDecisionStaysEnabled(t *testing.T) {@@ -44,3 +46,29 @@ func TestPluginsV1DefaultsOff(t *testing.T) {t.Fatal("plugins_v1 must stay disabled unless explicitly enabled")}}++func TestPrivatePluginsV1DefaultsOff(t *testing.T) {+ flags := EvaluateFrontendPublicFlags(context.Background(), nil)+ if flags[PrivatePluginsV1] {+ t.Fatal("private_plugins_v1 must stay disabled unless explicitly enabled")+ }+}++func TestPrivatePluginsV1RequiresBothFlags(t *testing.T) {+ provider := featureflag.NewStaticProvider()+ flags := featureflag.NewService(provider)+ ctx := context.Background()++ provider.Set(PrivatePluginsV1, featureflag.Rule{Default: true})+ if PrivatePluginsV1Enabled(ctx, flags) {+ t.Fatal("private_plugins_v1 must stay off while plugins_v1 is off")+ }+ provider.Set(PluginsV1, featureflag.Rule{Default: true})+ if !PrivatePluginsV1Enabled(ctx, flags) {+ t.Fatal("private_plugins_v1 must be on when both flags are on")+ }+ provider.Set(PrivatePluginsV1, featureflag.Rule{Default: false})+ if PrivatePluginsV1Enabled(ctx, flags) {+ t.Fatal("private_plugins_v1 must stay off when its own flag is off")+ }+}diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.goindex 2a7b689994..77377834f6 100644--- a/server/internal/handler/config_test.go+++ b/server/internal/handler/config_test.go@@ -418,6 +418,9 @@ func TestGetConfigExposesFrontendFeatureFlags(t *testing.T) {if cfg.FeatureFlags["plugins_v1"] {t.Fatalf("plugins_v1: want false by default, got true")}+ if cfg.FeatureFlags["private_plugins_v1"] {+ t.Fatalf("private_plugins_v1: want false by default, got true")+ }if !cfg.FeatureFlags["agents_skill_toggles"] {t.Fatalf("agents_skill_toggles: want true for installed v0.4.0 clients, got false")}@@ -457,3 +460,22 @@ func TestGetConfigExposesEnabledPluginsV1Flag(t *testing.T) {t.Fatal("plugins_v1: want true with flag enabled, got false")}}++func TestGetConfigExposesEnabledPrivatePluginsV1Flag(t *testing.T) {+ h := &Handler{}+ withPrivatePluginsV1Flag(t, h, true, true)++ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)+ w := httptest.NewRecorder()+ h.GetConfig(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetConfig enabled private_plugins_v1: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var cfg AppConfig+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {+ t.Fatalf("decode enabled config: %v", err)+ }+ if !cfg.FeatureFlags["plugins_v1"] || !cfg.FeatureFlags["private_plugins_v1"] {+ t.Fatalf("private Plugin flags not published together: %#v", cfg.FeatureFlags)+ }+}diff --git a/server/internal/handler/featureflag_test.go b/server/internal/handler/featureflag_test.goindex 683f159849..cb73181b03 100644--- a/server/internal/handler/featureflag_test.go+++ b/server/internal/handler/featureflag_test.go@@ -15,6 +15,17 @@ func withPluginsV1Flag(t *testing.T, h *Handler, enabled bool) {withFeatureFlag(t, h, featureflags.PluginsV1, enabled)}+func withPrivatePluginsV1Flag(t *testing.T, h *Handler, pluginsEnabled, privateEnabled bool) {+ t.Helper()+ provider := featureflag.NewStaticProvider()+ provider.Set(featureflags.PluginsV1, featureflag.Rule{Default: pluginsEnabled})+ provider.Set(featureflags.PrivatePluginsV1, featureflag.Rule{Default: privateEnabled})+ flags := featureflag.NewService(provider)+ original := h.FeatureFlags+ h.FeatureFlags = flags+ t.Cleanup(func() { h.FeatureFlags = original })+}+func withFeatureFlag(t *testing.T, h *Handler, key string, enabled bool) {t.Helper()provider := featureflag.NewStaticProvider()diff --git a/server/internal/handler/plugin.go b/server/internal/handler/plugin.goindex 6e31b5d9fd..74e66c2b2a 100644--- a/server/internal/handler/plugin.go+++ b/server/internal/handler/plugin.go@@ -4,6 +4,7 @@ import ("context""encoding/json""errors"+ "io""log/slog""net/http"@@ -15,6 +16,7 @@ import ("github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract")func (h *Handler) pluginsV1Enabled(ctx context.Context) bool {@@ -29,6 +31,18 @@ func (h *Handler) requirePluginsV1(w http.ResponseWriter, r *http.Request) boolreturn false}+func (h *Handler) privatePluginsV1Enabled(ctx context.Context) bool {+ return featureflags.PrivatePluginsV1Enabled(ctx, h.FeatureFlags)+}++func (h *Handler) requirePrivatePluginsV1(w http.ResponseWriter, r *http.Request) bool {+ if h.privatePluginsV1Enabled(r.Context()) {+ return true+ }+ writeError(w, http.StatusServiceUnavailable, "Private Plugin management is not enabled")+ return false+}+type pluginBindingResponse struct {ScopeType string `json:"scope_type"`ScopeID string `json:"scope_id"`@@ -36,23 +50,50 @@ type pluginBindingResponse struct {Revision int64 `json:"revision"`}+type pluginContributionResponse struct {+ Key string `json:"key"`+ Type string `json:"type"`+ Name string `json:"name"`+ Description string `json:"description"`+ EntryPath string `json:"entry_path"`+ EntryDigest string `json:"entry_digest"`+}+type pluginInstallationResponse struct {- ID string `json:"id"`- PluginKey string `json:"plugin_key"`- DisplayName string `json:"display_name"`- DesiredVersion string `json:"desired_version"`- ActiveVersion string `json:"active_version,omitempty"`- Enabled bool `json:"enabled"`- DesiredGeneration int64 `json:"desired_generation"`- ActiveGeneration int64 `json:"active_generation"`- LifecycleStatus string `json:"lifecycle_status"`- HealthState string `json:"health_state,omitempty"`- HealthReason string `json:"health_reason,omitempty"`- Contributions []string `json:"contributions"`- Bindings []pluginBindingResponse `json:"bindings"`+ ID string `json:"id"`+ PluginKey string `json:"plugin_key"`+ DisplayName string `json:"display_name"`+ DesiredVersion string `json:"desired_version"`+ ActiveVersion string `json:"active_version,omitempty"`+ Enabled bool `json:"enabled"`+ DesiredGeneration int64 `json:"desired_generation"`+ ActiveGeneration int64 `json:"active_generation"`+ LifecycleStatus string `json:"lifecycle_status"`+ HealthState string `json:"health_state,omitempty"`+ HealthReason string `json:"health_reason,omitempty"`+ Description string `json:"description,omitempty"`+ Publisher string `json:"publisher"`+ PublisherType string `json:"publisher_type"`+ TrustTier string `json:"trust_tier"`+ SourceKind string `json:"source_kind"`+ SourceRef string `json:"source_ref"`+ UploaderID string `json:"uploader_id,omitempty"`+ ManifestDigest string `json:"manifest_digest"`+ ArchiveDigest string `json:"archive_digest"`+ ArtifactDigest string `json:"artifact_digest"`+ SignatureVerified bool `json:"signature_verified"`+ RequestedCaps []string `json:"requested_capabilities"`+ AvailableVersions []string `json:"available_versions"`+ Contributions []string `json:"contributions"`+ ContributionInfo []pluginContributionResponse `json:"contribution_details"`+ Bindings []pluginBindingResponse `json:"bindings"`}func (h *Handler) pluginInstallationResponse(r *http.Request, installation db.PluginInstallation, health *db.PluginHealth) (pluginInstallationResponse, error) {+ return h.pluginInstallationResponseWithReleases(r, installation, health, nil)+}++func (h *Handler) pluginInstallationResponseWithReleases(r *http.Request, installation db.PluginInstallation, health *db.PluginHealth, prefetchedReleases *[]db.PluginRelease) (pluginInstallationResponse, error) {identity, err := h.Queries.GetPluginIdentity(r.Context(), installation.PluginID)if err != nil {return pluginInstallationResponse{}, err@@ -61,6 +102,10 @@ func (h *Handler) pluginInstallationResponse(r *http.Request, installation db.Plif err != nil {return pluginInstallationResponse{}, err}+ var manifest plugincontract.Manifest+ if err := json.Unmarshal(desired.Manifest, &manifest); err != nil {+ return pluginInstallationResponse{}, err+ }response := pluginInstallationResponse{ID: uuidToString(installation.ID),PluginKey: identity.PluginKey,@@ -70,15 +115,49 @@ func (h *Handler) pluginInstallationResponse(r *http.Request, installation db.PlDesiredGeneration: installation.DesiredGeneration,ActiveGeneration: installation.ActiveGeneration,LifecycleStatus: installation.LifecycleStatus,+ Description: manifest.Metadata.Description,+ Publisher: identity.PublisherID,+ PublisherType: identity.PublisherType,+ TrustTier: identity.TrustTier,+ SourceKind: desired.SourceKind,+ SourceRef: desired.SourceRef,+ UploaderID: uuidToString(installation.InstalledBy),+ ManifestDigest: desired.ManifestDigest,+ ArchiveDigest: desired.ArchiveDigest,+ ArtifactDigest: desired.ArtifactDigest,+ SignatureVerified: desired.SourceKind == plugincontract.SourceBundled && desired.SignatureKeyID.Valid,+ RequestedCaps: append([]string(nil), manifest.RequestedCapabilities...),+ AvailableVersions: []string{},Contributions: []string{},+ ContributionInfo: []pluginContributionResponse{},Bindings: []pluginBindingResponse{},}+ var releases []db.PluginRelease+ if prefetchedReleases != nil {+ releases = *prefetchedReleases+ } else {+ releases, err = h.Queries.ListPluginReleasesByPlugin(r.Context(), installation.PluginID)+ if err != nil {+ return pluginInstallationResponse{}, err+ }+ }+ for _, release := range releases {+ response.AvailableVersions = append(response.AvailableVersions, release.Version)+ }contributions, err := h.Queries.ListPluginContributionsByRelease(r.Context(), desired.ID)if err != nil {return pluginInstallationResponse{}, err}for _, contribution := range contributions {response.Contributions = append(response.Contributions, contribution.ContributionKey)+ response.ContributionInfo = append(response.ContributionInfo, pluginContributionResponse{+ Key: contribution.ContributionKey,+ Type: contribution.Type,+ Name: contribution.DisplayName,+ Description: contribution.Description,+ EntryPath: contribution.EntryPath,+ EntryDigest: contribution.EntryDigest,+ })}bindings, err := h.Queries.ListLatestPluginBindings(r.Context(), installation.ID)if err != nil {@@ -119,6 +198,65 @@ func (h *Handler) ListPlugins(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list Plugins")return}+ h.writePluginInstallations(w, r, workspaceID, installations)+}++func (h *Handler) ListPrivatePlugins(w http.ResponseWriter, r *http.Request) {+ if !h.requirePrivatePluginsV1(w, r) {+ return+ }+ workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")+ if !ok {+ return+ }+ installations, err := h.Queries.ListWorkspacePrivatePluginInstallations(r.Context(), workspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list Private Plugins")+ return+ }+ h.writePluginInstallations(w, r, workspaceID, installations)+}++func (h *Handler) GetPrivatePluginStatus(w http.ResponseWriter, r *http.Request) {+ if !h.requirePrivatePluginsV1(w, r) {+ return+ }+ workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")+ if !ok {+ return+ }+ installation, err := h.Queries.GetWorkspacePrivatePluginInstallationByRef(r.Context(), db.GetWorkspacePrivatePluginInstallationByRefParams{+ WorkspaceID: workspaceID,+ PluginRef: chi.URLParam(r, "pluginRef"),+ })+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "Private Plugin installation not found")+ return+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load Private Plugin")+ return+ }+ var health *db.PluginHealth+ healthRow, healthErr := h.Queries.GetWorkspacePluginHealthByInstallation(r.Context(), db.GetWorkspacePluginHealthByInstallationParams{+ WorkspaceID: workspaceID,+ InstallationID: installation.ID,+ })+ if healthErr == nil {+ health = &healthRow+ } else if !errors.Is(healthErr, pgx.ErrNoRows) {+ writeError(w, http.StatusInternalServerError, "failed to load Private Plugin")+ return+ }+ response, responseErr := h.pluginInstallationResponse(r, installation, health)+ if responseErr != nil {+ writeError(w, http.StatusInternalServerError, "failed to load Private Plugin")+ return+ }+ writeJSON(w, http.StatusOK, response)+}++func (h *Handler) writePluginInstallations(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, installations []db.PluginInstallation) {healthRows, _ := h.Queries.ListWorkspacePluginHealth(r.Context(), workspaceID)healthByInstallation := make(map[string]db.PluginHealth)for _, health := range healthRows {@@ -127,6 +265,16 @@ func (h *Handler) ListPlugins(w http.ResponseWriter, r *http.Request) {healthByInstallation[key] = health}}+ releaseRows, err := h.Queries.ListWorkspacePluginReleases(r.Context(), workspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load Plugin releases")+ return+ }+ releasesByPlugin := make(map[string][]db.PluginRelease)+ for _, release := range releaseRows {+ key := uuidToString(release.PluginID)+ releasesByPlugin[key] = append(releasesByPlugin[key], release)+ }responses := make([]pluginInstallationResponse, 0, len(installations))for _, installation := range installations {health, hasHealth := healthByInstallation[uuidToString(installation.ID)]@@ -134,7 +282,8 @@ func (h *Handler) ListPlugins(w http.ResponseWriter, r *http.Request) {if hasHealth {healthPtr = &health}- response, err := h.pluginInstallationResponse(r, installation, healthPtr)+ releases := releasesByPlugin[uuidToString(installation.PluginID)]+ response, err := h.pluginInstallationResponseWithReleases(r, installation, healthPtr, &releases)if err != nil {writeError(w, http.StatusInternalServerError, "failed to load Plugin")return@@ -144,37 +293,28 @@ func (h *Handler) ListPlugins(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, map[string]any{"plugins": responses})}-type pluginCatalogContributionResponse struct {- Key string `json:"key"`- Type string `json:"type"`- Name string `json:"name"`- Description string `json:"description"`- EntryPath string `json:"entry_path"`- EntryDigest string `json:"entry_digest"`-}-type pluginCatalogReleaseResponse struct {- PluginKey string `json:"plugin_key"`- Name string `json:"name"`- Description string `json:"description"`- Version string `json:"version"`- Publisher string `json:"publisher"`- PublisherType string `json:"publisher_type"`- TrustTier string `json:"trust_tier"`- SourceKind string `json:"source_kind"`- SourceRef string `json:"source_ref"`- RequestedCapabilities []string `json:"requested_capabilities"`- HostAPI string `json:"host_api"`- RequiredDaemonFeatures []string `json:"required_daemon_features"`- SignatureKeyID string `json:"signature_key_id"`- SignatureVerified bool `json:"signature_verified"`- ManifestDigest string `json:"manifest_digest"`- ArchiveDigest string `json:"archive_digest"`- ArtifactDigest string `json:"artifact_digest"`- Compatible bool `json:"compatible"`- CompatibilityReason string `json:"compatibility_reason,omitempty"`- Contributions []pluginCatalogContributionResponse `json:"contributions"`- Installation *pluginInstallationResponse `json:"installation,omitempty"`+ PluginKey string `json:"plugin_key"`+ Name string `json:"name"`+ Description string `json:"description"`+ Version string `json:"version"`+ Publisher string `json:"publisher"`+ PublisherType string `json:"publisher_type"`+ TrustTier string `json:"trust_tier"`+ SourceKind string `json:"source_kind"`+ SourceRef string `json:"source_ref"`+ RequestedCapabilities []string `json:"requested_capabilities"`+ HostAPI string `json:"host_api"`+ RequiredDaemonFeatures []string `json:"required_daemon_features"`+ SignatureKeyID string `json:"signature_key_id"`+ SignatureVerified bool `json:"signature_verified"`+ ManifestDigest string `json:"manifest_digest"`+ ArchiveDigest string `json:"archive_digest"`+ ArtifactDigest string `json:"artifact_digest"`+ Compatible bool `json:"compatible"`+ CompatibilityReason string `json:"compatibility_reason,omitempty"`+ Contributions []pluginContributionResponse `json:"contributions"`+ Installation *pluginInstallationResponse `json:"installation,omitempty"`}func (h *Handler) catalogReleaseResponse(r *http.Request, workspaceID pgtype.UUID, entry pluginbundled.CatalogEntry) (pluginCatalogReleaseResponse, error) {@@ -199,10 +339,10 @@ func (h *Handler) catalogReleaseResponse(r *http.Request, workspaceID pgtype.UUIArtifactDigest: entry.Release.ArtifactDigest,Compatible: entry.Compatible,CompatibilityReason: entry.CompatibilityWhy,- Contributions: make([]pluginCatalogContributionResponse, 0, len(entry.Release.Contributions)),+ Contributions: make([]pluginContributionResponse, 0, len(entry.Release.Contributions)),}for _, contribution := range entry.Release.Contributions {- response.Contributions = append(response.Contributions, pluginCatalogContributionResponse{+ response.Contributions = append(response.Contributions, pluginContributionResponse{Key: contribution.Key,Type: contribution.Type,Name: contribution.DisplayName,@@ -211,7 +351,7 @@ func (h *Handler) catalogReleaseResponse(r *http.Request, workspaceID pgtype.UUIEntryDigest: contribution.EntryDigest,})}- identity, err := h.Queries.GetPluginIdentityByKey(r.Context(), manifest.Metadata.Key)+ identity, err := h.Queries.GetOfficialPluginIdentityByKey(r.Context(), manifest.Metadata.Key)if errors.Is(err, pgx.ErrNoRows) {return response, nil}@@ -316,6 +456,46 @@ func (h *Handler) InstallPlugin(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusCreated, response)}+func (h *Handler) InstallPrivatePlugin(w http.ResponseWriter, r *http.Request) {+ if !h.requirePrivatePluginsV1(w, r) {+ return+ }+ workspaceID, actorID, ok := pluginRequestIDs(w, r)+ if !ok {+ return+ }+ r.Body = http.MaxBytesReader(w, r.Body, plugincontract.MaxArchiveSize+plugincontract.MaxManifestSize)+ if err := r.ParseMultipartForm(plugincontract.MaxArchiveSize + 1); err != nil {+ writeError(w, http.StatusBadRequest, "Private Plugin package is required and must fit the package limit")+ return+ }+ if r.MultipartForm != nil {+ defer r.MultipartForm.RemoveAll() //nolint:errcheck+ }+ file, _, err := r.FormFile("artifact")+ if err != nil {+ writeError(w, http.StatusBadRequest, "artifact file is required")+ return+ }+ defer file.Close()+ archive, err := io.ReadAll(io.LimitReader(file, plugincontract.MaxArchiveSize+1))+ if err != nil || len(archive) > plugincontract.MaxArchiveSize {+ writeError(w, http.StatusBadRequest, "Private Plugin package exceeds the package limit")+ return+ }+ installation, err := h.PluginService.InstallPrivateArchive(r.Context(), workspaceID, actorID, archive)+ if err != nil {+ writePluginError(w, r, err)+ return+ }+ response, err := h.pluginInstallationResponse(r, installation, nil)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load Private Plugin")+ return+ }+ writeJSON(w, http.StatusCreated, response)+}+func (h *Handler) UpgradePlugin(w http.ResponseWriter, r *http.Request) {if !h.requirePluginsV1(w, r) {return@@ -328,6 +508,9 @@ func (h *Handler) UpgradePlugin(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requirePluginInstallationFeature(w, r, workspaceID, installationID, false) {+ return+ }var request pluginReleaseRequestif err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.PluginKey == "" || request.Version == "" {writeError(w, http.StatusBadRequest, "plugin_key and version are required")@@ -374,6 +557,9 @@ func (h *Handler) setPluginEnabled(w http.ResponseWriter, r *http.Request, enablif !ok {return}+ if !h.requirePluginInstallationFeature(w, r, workspaceID, installationID, !enabled) {+ return+ }request := pluginBindingRequest{ScopeType: "workspace", ScopeID: uuidToString(workspaceID)}if r.Body != nil && r.ContentLength != 0 {if err := json.NewDecoder(r.Body).Decode(&request); err != nil {@@ -419,6 +605,9 @@ func (h *Handler) RollbackPlugin(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requirePluginInstallationFeature(w, r, workspaceID, installationID, false) {+ return+ }var request struct {Version string `json:"version"`}@@ -439,6 +628,40 @@ func (h *Handler) RollbackPlugin(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, response)}+func (h *Handler) UninstallPlugin(w http.ResponseWriter, r *http.Request) {+ if !h.requirePluginsV1(w, r) {+ return+ }+ workspaceID, actorID, ok := pluginRequestIDs(w, r)+ if !ok {+ return+ }+ installationID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation_id")+ if !ok {+ return+ }+ if !h.requirePluginInstallationFeature(w, r, workspaceID, installationID, true) {+ return+ }+ if err := h.PluginService.UninstallPlugin(r.Context(), workspaceID, installationID, actorID); err != nil {+ writePluginError(w, r, err)+ return+ }+ w.WriteHeader(http.StatusNoContent)+}++func (h *Handler) requirePluginInstallationFeature(w http.ResponseWriter, r *http.Request, workspaceID, installationID pgtype.UUID, allowPrivateTeardown bool) bool {+ installation, err := h.Queries.GetPluginInstallation(r.Context(), installationID)+ if err != nil || installation.WorkspaceID != workspaceID || installation.UninstalledAt.Valid {+ writeError(w, http.StatusNotFound, "Plugin installation not found")+ return false+ }+ if installation.SourceKind == plugincontract.SourcePrivateDev && !allowPrivateTeardown && !h.requirePrivatePluginsV1(w, r) {+ return false+ }+ return true+}+func writePluginError(w http.ResponseWriter, r *http.Request, err error) {var pluginErr *service.PluginErrorif !errors.As(err, &pluginErr) {diff --git a/server/internal/handler/plugin_test.go b/server/internal/handler/plugin_test.goindex 60e9ade78f..3a717dd70b 100644--- a/server/internal/handler/plugin_test.go+++ b/server/internal/handler/plugin_test.go@@ -5,8 +5,10 @@ import ("context""encoding/json""errors"+ "mime/multipart""net/http""net/http/httptest"+ "path/filepath""strings""testing"@@ -14,6 +16,7 @@ import ("github.com/jackc/pgx/v5""github.com/multica-ai/multica/server/internal/testutil/plugintest"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract")type failPluginDetailQueryDB struct {@@ -68,6 +71,7 @@ func TestPluginHTTPLifecycleForInstalledReferenceRelease(t *testing.T) {testPool.Exec(ctx, `DELETE FROM plugin_binding WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, testWorkspaceID)testPool.Exec(ctx, `DELETE FROM plugin_grant WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, testWorkspaceID)testPool.Exec(ctx, `DELETE FROM plugin_installation WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM activity_log WHERE workspace_id = $1 AND action = 'plugin_uninstalled'`, testWorkspaceID)}cleanup()t.Cleanup(cleanup)@@ -136,6 +140,7 @@ func TestPluginHTTPLifecycleForInstalledReferenceRelease(t *testing.T) {}{{name: "contributions", queryFragment: "FROM plugin_contribution"},{name: "bindings", queryFragment: "FROM plugin_binding"},+ {name: "available releases", queryFragment: "FROM plugin_release release"},{name: "active release", queryRowFragment: "FROM plugin_release\nWHERE id = $1", failQueryRowAtMatch: 2},} {t.Run("list fails closed when "+test.name+" cannot be read", func(t *testing.T) {@@ -193,6 +198,19 @@ func TestPluginHTTPLifecycleForInstalledReferenceRelease(t *testing.T) {if recorder.Code != http.StatusNotFound || bytes.Contains(recorder.Body.Bytes(), []byte("no rows")) {t.Fatalf("safe missing rollback status=%d body=%s", recorder.Code, recorder.Body.String())}++ recorder = httptest.NewRecorder()+ testHandler.UninstallPlugin(recorder, pluginHandlerRequest(http.MethodDelete, "/plugins/"+installed.ID, nil, params))+ if recorder.Code != http.StatusNoContent {+ t.Fatalf("official uninstall status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var uninstallAuditCount int+ if err := testPool.QueryRow(context.Background(), `+ SELECT count(*) FROM activity_log+ WHERE workspace_id = $1 AND action = 'plugin_uninstalled'+ `, testWorkspaceID).Scan(&uninstallAuditCount); err != nil || uninstallAuditCount != 1 {+ t.Fatalf("official uninstall audit count=%d err=%v", uninstallAuditCount, err)+ }}func TestPluginManagementUnavailableWhenFlagDisabled(t *testing.T) {@@ -202,18 +220,23 @@ func TestPluginManagementUnavailableWhenFlagDisabled(t *testing.T) {"id": testWorkspaceID,"installationId": "00000000-0000-0000-0000-000000000001","pluginKey": plugintest.ReviewReadinessPluginKey,+ "pluginRef": plugintest.ReviewReadinessPluginKey,})}for name, handler := range map[string]http.HandlerFunc{- "list installed": h.ListPlugins,- "list catalog": h.ListPluginCatalog,- "catalog detail": h.GetPluginCatalogRelease,- "install": h.InstallPlugin,- "upgrade": h.UpgradePlugin,- "enable": h.EnablePlugin,- "disable": h.DisablePlugin,- "rollback": h.RollbackPlugin,+ "list installed": h.ListPlugins,+ "list catalog": h.ListPluginCatalog,+ "catalog detail": h.GetPluginCatalogRelease,+ "install": h.InstallPlugin,+ "upgrade": h.UpgradePlugin,+ "enable": h.EnablePlugin,+ "disable": h.DisablePlugin,+ "rollback": h.RollbackPlugin,+ "private list": h.ListPrivatePlugins,+ "private status": h.GetPrivatePluginStatus,+ "private install": h.InstallPrivatePlugin,+ "uninstall": h.UninstallPlugin,} {t.Run(name, func(t *testing.T) {recorder := httptest.NewRecorder()@@ -227,3 +250,132 @@ func TestPluginManagementUnavailableWhenFlagDisabled(t *testing.T) {})}}++func TestPrivatePluginManagementRequiresBothFlags(t *testing.T) {+ for _, flags := range []struct {+ name string+ plugins, privatePlugin bool+ }{+ {name: "base off", plugins: false, privatePlugin: true},+ {name: "private off", plugins: true, privatePlugin: false},+ } {+ t.Run(flags.name, func(t *testing.T) {+ h := &Handler{}+ withPrivatePluginsV1Flag(t, h, flags.plugins, flags.privatePlugin)+ for name, handler := range map[string]http.HandlerFunc{+ "list": h.ListPrivatePlugins,+ "status": h.GetPrivatePluginStatus,+ "install": h.InstallPrivatePlugin,+ } {+ t.Run(name, func(t *testing.T) {+ recorder := httptest.NewRecorder()+ handler(recorder, pluginHandlerRequest(http.MethodGet, "/plugins/private", nil, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusServiceUnavailable {+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ })+ }+ })+ }+}++func TestPrivatePluginHTTPUploadListAndUninstall(t *testing.T) {+ withPrivatePluginsV1Flag(t, testHandler, true, true)+ cleanup := func() {+ ctx := context.Background()+ testPool.Exec(ctx, `DELETE FROM plugin_health WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_capability_snapshot WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_workspace_capability_state WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_binding WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_grant WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_installation WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_contribution WHERE release_id IN (SELECT id FROM plugin_release WHERE plugin_id IN (SELECT id FROM plugin_identity WHERE owner_workspace_id = $1))`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_artifact_file WHERE release_id IN (SELECT id FROM plugin_release WHERE plugin_id IN (SELECT id FROM plugin_identity WHERE owner_workspace_id = $1))`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_release WHERE plugin_id IN (SELECT id FROM plugin_identity WHERE owner_workspace_id = $1)`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_identity WHERE owner_workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM activity_log WHERE workspace_id = $1 AND action LIKE 'plugin_private_%'`, testWorkspaceID)+ }+ cleanup()+ t.Cleanup(cleanup)++ archive, _, err := plugincontract.PackDirectory(filepath.Join("..", "..", "..", "examples", "plugins", "incident-triage"))+ if err != nil {+ t.Fatalf("pack example private Plugin: %v", err)+ }+ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ part, err := writer.CreateFormFile("artifact", "incident-triage.zip")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := part.Write(archive); err != nil {+ t.Fatal(err)+ }+ if err := writer.Close(); err != nil {+ t.Fatal(err)+ }+ request := pluginHandlerRequest(http.MethodPost, "/plugins/private/install", body.Bytes(), map[string]string{"id": testWorkspaceID})+ request.Header.Set("Content-Type", writer.FormDataContentType())+ recorder := httptest.NewRecorder()+ testHandler.InstallPrivatePlugin(recorder, request)+ if recorder.Code != http.StatusCreated || !bytes.Contains(recorder.Body.Bytes(), []byte(`"trust_tier":"private_dev"`)) || !bytes.Contains(recorder.Body.Bytes(), []byte(`"signature_verified":false`)) {+ t.Fatalf("private install status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var installed pluginInstallationResponse+ if err := json.Unmarshal(recorder.Body.Bytes(), &installed); err != nil {+ t.Fatal(err)+ }++ recorder = httptest.NewRecorder()+ testHandler.ListPrivatePlugins(recorder, pluginHandlerRequest(http.MethodGet, "/plugins/private", nil, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte("dev.multica.incident-triage")) {+ t.Fatalf("private list status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ recorder = httptest.NewRecorder()+ testHandler.GetPrivatePluginStatus(recorder, pluginHandlerRequest(http.MethodGet, "/plugins/private/dev.multica.incident-triage", nil, map[string]string{+ "id": testWorkspaceID, "pluginRef": "dev.multica.incident-triage",+ }))+ if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte(`"desired_version":"0.1.0"`)) {+ t.Fatalf("private status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ params := map[string]string{"id": testWorkspaceID, "installationId": installed.ID}+ recorder = httptest.NewRecorder()+ testHandler.EnablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/enable", nil, params))+ if recorder.Code != http.StatusOK {+ t.Fatalf("private enable status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ withPrivatePluginsV1Flag(t, testHandler, true, false)+ recorder = httptest.NewRecorder()+ testHandler.ListPlugins(recorder, pluginHandlerRequest(http.MethodGet, "/plugins", nil, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte("dev.multica.incident-triage")) {+ t.Fatalf("private Plugin must remain visible for teardown when flag is off: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ recorder = httptest.NewRecorder()+ testHandler.EnablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/enable", nil, params))+ if recorder.Code != http.StatusServiceUnavailable {+ t.Fatalf("private enable with flag off status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ recorder = httptest.NewRecorder()+ testHandler.DisablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/disable", nil, params))+ if recorder.Code != http.StatusOK {+ t.Fatalf("private disable with flag off status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ recorder = httptest.NewRecorder()+ testHandler.UninstallPlugin(recorder, pluginHandlerRequest(http.MethodDelete, "/plugins/"+installed.ID, nil, map[string]string{+ "id": testWorkspaceID, "installationId": installed.ID,+ }))+ if recorder.Code != http.StatusNoContent {+ t.Fatalf("private uninstall status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ withPrivatePluginsV1Flag(t, testHandler, true, true)+ recorder = httptest.NewRecorder()+ testHandler.GetPrivatePluginStatus(recorder, pluginHandlerRequest(http.MethodGet, "/plugins/private/dev.multica.incident-triage", nil, map[string]string{+ "id": testWorkspaceID, "pluginRef": "dev.multica.incident-triage",+ }))+ if recorder.Code != http.StatusNotFound {+ t.Fatalf("uninstalled private status=%d body=%s", recorder.Code, recorder.Body.String())+ }+}diff --git a/server/internal/pluginbundled/catalog.go b/server/internal/pluginbundled/catalog.goindex bfef13a013..591abe3a12 100644--- a/server/internal/pluginbundled/catalog.go+++ b/server/internal/pluginbundled/catalog.go@@ -199,7 +199,7 @@ func loadRelease(source fs.FS, verifier plugincontract.ReleaseVerifier, metadata}return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, code)}- compatible, why := compatibleWithV1Host(release.Manifest)+ compatible, why := CompatibleWithV1Host(release.Manifest)return CatalogEntry{Release: release,PublisherType: metadata.PublisherType,@@ -269,7 +269,9 @@ func buildArchive(source fs.FS, releaseDir, signatureFile string) ([]byte, errorreturn buffer.Bytes(), nil}-func compatibleWithV1Host(manifest plugincontract.Manifest) (bool, string) {+// CompatibleWithV1Host applies the V1 host and daemon compatibility contract+// to both bundled and workspace-private releases.+func CompatibleWithV1Host(manifest plugincontract.Manifest) (bool, string) {if manifest.Compatibility.HostAPI != ">=1.0.0 <2.0.0" {return false, "host_api_unsupported"}diff --git a/server/internal/service/plugin.go b/server/internal/service/plugin.goindex 14deb0050e..a44464064a 100644--- a/server/internal/service/plugin.go+++ b/server/internal/service/plugin.go@@ -23,6 +23,13 @@ type PluginService struct {BundledCatalog *pluginbundled.Catalog}+const (+ MaxWorkspacePrivatePluginReleases = int64(100)+ MaxWorkspacePrivatePluginBytes = int64(256 << 20)+ privatePluginPublisherType = "private_dev"+ privatePluginTrustTier = "private_dev"+)+func NewPluginService(queries *db.Queries, txStarter TxStarter) *PluginService {return &PluginService{Queries: queries,@@ -89,6 +96,29 @@ func (s *PluginService) InstallCatalogRelease(ctx context.Context, workspaceID,})}+// InstallPrivateArchive is the authenticated workspace acquisition boundary.+// The Server always revalidates uploaded bytes and derives a privacy-safe+// source reference rather than accepting a developer-machine path.+func (s *PluginService) InstallPrivateArchive(ctx context.Context, workspaceID, actorID pgtype.UUID, archive []byte) (db.PluginInstallation, error) {+ archiveDigest := plugincontract.DigestBytes(archive)+ release, err := plugincontract.ValidateReleaseCandidate(plugincontract.ReleaseCandidate{+ Archive: archive,+ SourceKind: plugincontract.SourcePrivateDev,+ SourceRef: "private://" + archiveDigest,+ }, nil)+ if err != nil {+ return db.PluginInstallation{}, newPluginError(PluginErrorInvalid, "Private Plugin package is invalid", err)+ }+ if compatible, _ := pluginbundled.CompatibleWithV1Host(release.Manifest); !compatible {+ return db.PluginInstallation{}, newPluginError(PluginErrorIncompatible, "Private Plugin release is incompatible with this Multica version", nil)+ }+ return s.InstallPluginRelease(ctx, workspaceID, actorID, PluginReleasePublication{+ Release: release,+ PublisherType: privatePluginPublisherType,+ TrustTier: privatePluginTrustTier,+ })+}+func (s *PluginService) UpgradeCatalogRelease(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, pluginKey, version string) (db.PluginInstallation, error) {entry, ok := s.FindCatalogRelease(pluginKey, version)if !ok {@@ -108,6 +138,9 @@ func (s *PluginService) UpgradeCatalogRelease(ctx context.Context, workspaceID,if err != nil || installation.WorkspaceID != workspaceID {return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)}+ if installation.SourceKind != plugincontract.SourceBundled {+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)+ }identity, err := q.GetPluginIdentity(ctx, installation.PluginID)if err != nil || identity.PluginKey != pluginKey {return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)@@ -119,7 +152,7 @@ func (s *PluginService) UpgradeCatalogRelease(ctx context.Context, workspaceID,if !pluginbundled.IsNewerVersion(entry.Release.Manifest.Metadata.Version, currentRelease.Version) {return db.PluginInstallation{}, newPluginError(PluginErrorConflict, "Target Plugin release is not newer than the installed release", nil)}- _, release, err := ensurePluginRelease(ctx, q, PluginReleasePublication{+ _, release, err := ensurePluginRelease(ctx, q, workspaceID, PluginReleasePublication{Release: entry.Release,PublisherType: entry.PublisherType,TrustTier: entry.TrustTier,@@ -166,17 +199,51 @@ func (s *PluginService) InstallPluginRelease(ctx context.Context, workspaceID, adefer tx.Rollback(ctx) //nolint:errcheckq := s.Queries.WithTx(tx)- identity, release, err := ensurePluginRelease(ctx, q, publication)+ identity, release, err := ensurePluginRelease(ctx, q, workspaceID, publication)if err != nil {return db.PluginInstallation{}, err}- if _, err := q.GetWorkspacePluginInstallation(ctx, db.GetWorkspacePluginInstallationParams{+ existing, existingErr := q.GetWorkspacePluginInstallation(ctx, db.GetWorkspacePluginInstallationParams{WorkspaceID: workspaceID,PluginID: identity.ID,- }); err == nil {- return db.PluginInstallation{}, newPluginError(PluginErrorConflict, "Plugin is already installed", nil)- } else if !errors.Is(err, pgx.ErrNoRows) {- return db.PluginInstallation{}, err+ })+ if existingErr == nil {+ if publication.Release.SourceKind != plugincontract.SourcePrivateDev {+ return db.PluginInstallation{}, newPluginError(PluginErrorConflict, "Plugin is already installed", nil)+ }+ auditAction := "plugin_private_uploaded"+ if existing.DesiredReleaseID != release.ID {+ currentRelease, currentErr := q.GetPluginRelease(ctx, existing.DesiredReleaseID)+ if currentErr != nil {+ return db.PluginInstallation{}, fmt.Errorf("load installed Private Plugin release: %w", currentErr)+ }+ if !pluginbundled.IsNewerVersion(release.Version, currentRelease.Version) {+ return db.PluginInstallation{}, newPluginError(PluginErrorConflict, "Target Private Plugin release is not newer than the installed release; use rollback for an older version", nil)+ }+ existing, err = q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{+ Enabled: existing.Enabled,+ UpdatedBy: actorID,+ WorkspaceID: workspaceID,+ DesiredReleaseID: release.ID,+ ID: existing.ID,+ })+ if err != nil {+ return db.PluginInstallation{}, fmt.Errorf("update private Plugin release: %w", err)+ }+ if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {+ return db.PluginInstallation{}, err+ }+ auditAction = "plugin_private_upgraded"+ }+ if err := createPluginAudit(ctx, q, workspaceID, actorID, auditAction, identity, release, existing); err != nil {+ return db.PluginInstallation{}, err+ }+ if err := tx.Commit(ctx); err != nil {+ return db.PluginInstallation{}, err+ }+ return s.Queries.GetPluginInstallation(ctx, existing.ID)+ } else if !errors.Is(existingErr, pgx.ErrNoRows) {+ return db.PluginInstallation{}, existingErr}installation, err := q.CreatePluginInstallation(ctx, db.CreatePluginInstallationParams{@@ -203,13 +270,18 @@ func (s *PluginService) InstallPluginRelease(ctx context.Context, workspaceID, aif _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {return db.PluginInstallation{}, err}+ if publication.Release.SourceKind == plugincontract.SourcePrivateDev {+ if err := createPluginAudit(ctx, q, workspaceID, actorID, "plugin_private_installed", identity, release, installation); err != nil {+ return db.PluginInstallation{}, err+ }+ }if err := tx.Commit(ctx); err != nil {return db.PluginInstallation{}, err}return s.Queries.GetPluginInstallation(ctx, installation.ID)}-func ensurePluginRelease(ctx context.Context, q *db.Queries, publication PluginReleasePublication) (db.PluginIdentity, db.PluginRelease, error) {+func ensurePluginRelease(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, publication PluginReleasePublication) (db.PluginIdentity, db.PluginRelease, error) {releaseData := publication.Releasemanifest := releaseData.Manifestif publication.PublisherType == "" || publication.TrustTier == "" {@@ -218,18 +290,40 @@ func ensurePluginRelease(ctx context.Context, q *db.Queries, publication PluginRif len(releaseData.Files) == 0 {return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorInvalid, "Plugin release contains no artifact files", nil)}- if err := q.LockPluginRegistryKey(ctx, manifest.Metadata.Key); err != nil {+ privateRelease := releaseData.SourceKind == plugincontract.SourcePrivateDev+ registryLockKey := "official:" + manifest.Metadata.Key+ if privateRelease {+ if publication.PublisherType != privatePluginPublisherType || publication.TrustTier != privatePluginTrustTier {+ return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorInvalid, "Private Plugin trust must be private / unverified", nil)+ }+ registryLockKey = "private:" + util.UUIDToString(workspaceID) + ":" + manifest.Metadata.Key+ }+ if err := q.LockPluginRegistryKey(ctx, registryLockKey); err != nil {return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("lock plugin registry key: %w", err)}- identity, err := q.GetPluginIdentityByKey(ctx, manifest.Metadata.Key)+ var identity db.PluginIdentity+ var err error+ if privateRelease {+ identity, err = q.GetWorkspacePrivatePluginIdentityByKey(ctx, db.GetWorkspacePrivatePluginIdentityByKeyParams{+ WorkspaceID: workspaceID,+ PluginKey: manifest.Metadata.Key,+ })+ } else {+ identity, err = q.GetOfficialPluginIdentityByKey(ctx, manifest.Metadata.Key)+ }if errors.Is(err, pgx.ErrNoRows) {+ ownerWorkspaceID := pgtype.UUID{}+ if privateRelease {+ ownerWorkspaceID = workspaceID+ }identity, err = q.CreatePluginIdentity(ctx, db.CreatePluginIdentityParams{- PluginKey: manifest.Metadata.Key,- DisplayName: manifest.Metadata.Name,- PublisherID: manifest.Metadata.Publisher,- PublisherType: publication.PublisherType,- TrustTier: publication.TrustTier,+ PluginKey: manifest.Metadata.Key,+ DisplayName: manifest.Metadata.Name,+ PublisherID: manifest.Metadata.Publisher,+ PublisherType: publication.PublisherType,+ TrustTier: publication.TrustTier,+ OwnerWorkspaceID: ownerWorkspaceID,})}if err != nil {@@ -239,11 +333,28 @@ func ensurePluginRelease(ctx context.Context, q *db.Queries, publication PluginRreturn db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorConflict, "Plugin publisher conflicts with the registered identity", nil)}- release, err := q.GetPluginReleaseByVersion(ctx, db.GetPluginReleaseByVersionParams{+ release, err := q.GetRegisteredPluginReleaseByVersion(ctx, db.GetRegisteredPluginReleaseByVersionParams{PluginID: identity.ID,Version: manifest.Metadata.Version,})if errors.Is(err, pgx.ErrNoRows) {+ if privateRelease {+ // Different private Plugin keys use different registry locks, so+ // serialize the workspace-wide quota check as well.+ if lockErr := q.LockPluginRegistryKey(ctx, "private-quota:"+util.UUIDToString(workspaceID)); lockErr != nil {+ return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("lock Private Plugin quota: %w", lockErr)+ }+ usage, usageErr := q.GetWorkspacePrivatePluginUsage(ctx, workspaceID)+ if usageErr != nil {+ return db.PluginIdentity{}, db.PluginRelease{}, usageErr+ }+ if usage.ReleaseCount >= MaxWorkspacePrivatePluginReleases {+ return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorConflict, "Workspace Private Plugin release quota exceeded", nil)+ }+ if usage.TotalBytes+releaseData.ArtifactSize > MaxWorkspacePrivatePluginBytes {+ return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorConflict, "Workspace Private Plugin storage quota exceeded", nil)+ }+ }manifestJSON, marshalErr := json.Marshal(manifest)if marshalErr != nil {return db.PluginIdentity{}, db.PluginRelease{}, marshalErr@@ -255,7 +366,7 @@ func ensurePluginRelease(ctx context.Context, q *db.Queries, publication PluginRSourceKind: releaseData.SourceKind,SourceRef: releaseData.SourceRef,ArchiveDigest: releaseData.ArchiveDigest,- ArtifactRef: releaseData.SourceRef,+ ArtifactRef: "artifact://" + releaseData.ArtifactDigest,ArtifactDigest: releaseData.ArtifactDigest,ArtifactSize: releaseData.ArtifactSize,Signature: releaseData.Signature,@@ -302,12 +413,43 @@ func ensurePluginRelease(ctx context.Context, q *db.Queries, publication PluginRif err != nil {return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("ensure plugin release: %w", err)}- if release.ManifestDigest != releaseData.ManifestDigest || release.ArtifactDigest != releaseData.ArtifactDigest || release.ArchiveDigest != releaseData.ArchiveDigest {+ if release.RevocationStatus != "active" {+ return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorConflict, "Plugin release has been revoked and cannot be installed", nil)+ }+ if release.ManifestDigest != releaseData.ManifestDigest ||+ release.ArtifactDigest != releaseData.ArtifactDigest ||+ (!privateRelease && release.ArchiveDigest != releaseData.ArchiveDigest) {return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorConflict, "Plugin release conflicts with immutable registry content", nil)}return identity, release, nil}+func createPluginAudit(ctx context.Context, q *db.Queries, workspaceID, actorID pgtype.UUID, action string, identity db.PluginIdentity, release db.PluginRelease, installation db.PluginInstallation) error {+ details, err := json.Marshal(map[string]any{+ "installation_id": util.UUIDToString(installation.ID),+ "plugin_id": util.UUIDToString(identity.ID),+ "plugin_key": identity.PluginKey,+ "release_id": util.UUIDToString(release.ID),+ "version": release.Version,+ "source_kind": release.SourceKind,+ "artifact_digest": release.ArtifactDigest,+ })+ if err != nil {+ return err+ }+ if _, err := q.CreateActivity(ctx, db.CreateActivityParams{+ WorkspaceID: workspaceID,+ IssueID: pgtype.UUID{},+ ActorType: pgtype.Text{String: "member", Valid: true},+ ActorID: actorID,+ Action: action,+ Details: details,+ }); err != nil {+ return fmt.Errorf("create Plugin audit record: %w", err)+ }+ return nil+}+func (s *PluginService) EnablePlugin(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, scopeType string, scopeID pgtype.UUID) (db.PluginInstallation, error) {return s.setPluginBinding(ctx, workspaceID, installationID, actorID, scopeType, scopeID, true)}@@ -330,6 +472,14 @@ func (s *PluginService) setPluginBinding(ctx context.Context, workspaceID, instaif err != nil || installation.WorkspaceID != workspaceID {return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)}+ identity, err := q.GetPluginIdentity(ctx, installation.PluginID)+ if err != nil {+ return db.PluginInstallation{}, err+ }+ release, err := q.GetPluginRelease(ctx, installation.DesiredReleaseID)+ if err != nil {+ return db.PluginInstallation{}, err+ }if scopeType == "workspace" && scopeID != workspaceID {return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin binding target not found", nil)}@@ -372,6 +522,15 @@ func (s *PluginService) setPluginBinding(ctx context.Context, workspaceID, instaif _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {return db.PluginInstallation{}, err}+ if installation.SourceKind == plugincontract.SourcePrivateDev {+ action := "plugin_private_disabled"+ if enabled {+ action = "plugin_private_enabled"+ }+ if err := createPluginAudit(ctx, q, workspaceID, actorID, action, identity, release, installation); err != nil {+ return db.PluginInstallation{}, err+ }+ }if err := tx.Commit(ctx); err != nil {return db.PluginInstallation{}, err}@@ -393,9 +552,9 @@ func (s *PluginService) RollbackPlugin(ctx context.Context, workspaceID, installif err != nil {return db.PluginInstallation{}, err}- release, err := q.GetPluginReleaseByPluginKeyVersion(ctx, db.GetPluginReleaseByPluginKeyVersionParams{- PluginKey: identity.PluginKey,- Version: version,+ release, err := q.GetPluginReleaseByVersion(ctx, db.GetPluginReleaseByVersionParams{+ PluginID: installation.PluginID,+ Version: version,})if err != nil {return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Rollback release not found", nil)@@ -413,12 +572,59 @@ func (s *PluginService) RollbackPlugin(ctx context.Context, workspaceID, installif _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {return db.PluginInstallation{}, err}+ if installation.SourceKind == plugincontract.SourcePrivateDev {+ if err := createPluginAudit(ctx, q, workspaceID, actorID, "plugin_private_rolled_back", identity, release, installation); err != nil {+ return db.PluginInstallation{}, err+ }+ }if err := tx.Commit(ctx); err != nil {return db.PluginInstallation{}, err}return s.Queries.GetPluginInstallation(ctx, installationID)}+// UninstallPlugin prevents future tasks from seeing an installation while+// retaining immutable releases and artifact files for historical pinned Runs.+func (s *PluginService) UninstallPlugin(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID) error {+ tx, err := s.TxStarter.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx) //nolint:errcheck+ q := s.Queries.WithTx(tx)+ installation, err := q.GetPluginInstallation(ctx, installationID)+ if err != nil || installation.WorkspaceID != workspaceID || installation.UninstalledAt.Valid {+ return newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)+ }+ identity, err := q.GetPluginIdentity(ctx, installation.PluginID)+ if err != nil {+ return err+ }+ release, err := q.GetPluginRelease(ctx, installation.DesiredReleaseID)+ if err != nil {+ return err+ }+ uninstalled, err := q.UninstallPluginInstallation(ctx, db.UninstallPluginInstallationParams{+ UpdatedBy: actorID,+ ID: installationID,+ WorkspaceID: workspaceID,+ })+ if err != nil {+ return newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)+ }+ if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {+ return err+ }+ auditAction := "plugin_uninstalled"+ if installation.SourceKind == plugincontract.SourcePrivateDev {+ auditAction = "plugin_private_uninstalled"+ }+ if err := createPluginAudit(ctx, q, workspaceID, actorID, auditAction, identity, release, uninstalled); err != nil {+ return err+ }+ return tx.Commit(ctx)+}+func (s *PluginService) ReconcileWorkspace(ctx context.Context, workspaceID pgtype.UUID) (db.PluginCapabilitySnapshot, error) {tx, err := s.TxStarter.Begin(ctx)if err != nil {diff --git a/server/internal/service/plugin_integration_test.go b/server/internal/service/plugin_integration_test.goindex 4ef07ae34e..ef438a4326 100644--- a/server/internal/service/plugin_integration_test.go+++ b/server/internal/service/plugin_integration_test.go@@ -1,19 +1,63 @@package serviceimport (+ "archive/zip"+ "bytes""context"+ "encoding/json"+ "errors""fmt"+ "io""os"+ "path/filepath""strings""testing""time"+ "github.com/jackc/pgx/v5/pgtype""github.com/jackc/pgx/v5/pgxpool""github.com/multica-ai/multica/server/internal/testutil/plugintest""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract")+func repackPluginArchive(t *testing.T, archive []byte) []byte {+ t.Helper()+ reader, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive)))+ if err != nil {+ t.Fatalf("open Plugin archive: %v", err)+ }+ var output bytes.Buffer+ writer := zip.NewWriter(&output)+ if err := writer.SetComment("semantically equivalent test package"); err != nil {+ t.Fatalf("set Plugin archive comment: %v", err)+ }+ for _, file := range reader.File {+ source, openErr := file.Open()+ if openErr != nil {+ t.Fatalf("open Plugin archive entry %s: %v", file.Name, openErr)+ }+ header := file.FileHeader+ destination, createErr := writer.CreateHeader(&header)+ if createErr != nil {+ source.Close() //nolint:errcheck+ t.Fatalf("create Plugin archive entry %s: %v", file.Name, createErr)+ }+ if _, copyErr := io.Copy(destination, source); copyErr != nil {+ source.Close() //nolint:errcheck+ t.Fatalf("copy Plugin archive entry %s: %v", file.Name, copyErr)+ }+ if closeErr := source.Close(); closeErr != nil {+ t.Fatalf("close Plugin archive entry %s: %v", file.Name, closeErr)+ }+ }+ if err := writer.Close(); err != nil {+ t.Fatalf("close Plugin archive: %v", err)+ }+ return output.Bytes()+}+func TestReferencePluginInstallEnablePinDisableAndRetry(t *testing.T) {ctx := context.Background()databaseURL := os.Getenv("DATABASE_URL")@@ -31,7 +75,7 @@ func TestReferencePluginInstallEnablePinDisableAndRetry(t *testing.T) {}suffix := time.Now().UnixNano()- var userID, workspaceID, runtimeID, agentID, issueID string+ var userID, workspaceID, isolationWorkspaceID, runtimeID, agentID, issueID stringif err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Plugin E2E', $1) RETURNING id`, fmt.Sprintf("plugin-e2e-%[email protected]", suffix)).Scan(&userID); err != nil {t.Fatal(err)}@@ -61,14 +105,27 @@ func TestReferencePluginInstallEnablePinDisableAndRetry(t *testing.T) {}t.Cleanup(func() {cleanup := context.Background()- pool.Exec(cleanup, `DELETE FROM plugin_execution_manifest WHERE workspace_id = $1`, workspaceID)+ cleanupPluginWorkspace := func(id string) {+ pool.Exec(cleanup, `DELETE FROM plugin_execution_manifest WHERE workspace_id = $1`, id)+ pool.Exec(cleanup, `DELETE FROM plugin_health WHERE workspace_id = $1`, id)+ pool.Exec(cleanup, `DELETE FROM plugin_capability_snapshot WHERE workspace_id = $1`, id)+ pool.Exec(cleanup, `DELETE FROM plugin_workspace_capability_state WHERE workspace_id = $1`, id)+ pool.Exec(cleanup, `DELETE FROM plugin_binding WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, id)+ pool.Exec(cleanup, `DELETE FROM plugin_grant WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, id)+ pool.Exec(cleanup, `DELETE FROM plugin_installation WHERE workspace_id = $1`, id)+ pool.Exec(cleanup, `DELETE FROM plugin_contribution WHERE release_id IN (SELECT id FROM plugin_release WHERE plugin_id IN (SELECT id FROM plugin_identity WHERE owner_workspace_id = $1))`, id)+ pool.Exec(cleanup, `DELETE FROM plugin_artifact_file WHERE release_id IN (SELECT id FROM plugin_release WHERE plugin_id IN (SELECT id FROM plugin_identity WHERE owner_workspace_id = $1))`, id)+ pool.Exec(cleanup, `DELETE FROM plugin_release WHERE plugin_id IN (SELECT id FROM plugin_identity WHERE owner_workspace_id = $1)`, id)+ pool.Exec(cleanup, `DELETE FROM plugin_identity WHERE owner_workspace_id = $1`, id)+ pool.Exec(cleanup, `DELETE FROM activity_log WHERE workspace_id = $1`, id)+ }+ cleanupPluginWorkspace(workspaceID)+ if isolationWorkspaceID != "" {+ cleanupPluginWorkspace(isolationWorkspaceID)+ pool.Exec(cleanup, `DELETE FROM member WHERE workspace_id = $1`, isolationWorkspaceID)+ pool.Exec(cleanup, `DELETE FROM workspace WHERE id = $1`, isolationWorkspaceID)+ }pool.Exec(cleanup, `DELETE FROM agent_task_queue WHERE agent_id = $1`, agentID)- pool.Exec(cleanup, `DELETE FROM plugin_health WHERE workspace_id = $1`, workspaceID)- pool.Exec(cleanup, `DELETE FROM plugin_capability_snapshot WHERE workspace_id = $1`, workspaceID)- pool.Exec(cleanup, `DELETE FROM plugin_workspace_capability_state WHERE workspace_id = $1`, workspaceID)- pool.Exec(cleanup, `DELETE FROM plugin_binding WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, workspaceID)- pool.Exec(cleanup, `DELETE FROM plugin_grant WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, workspaceID)- pool.Exec(cleanup, `DELETE FROM plugin_installation WHERE workspace_id = $1`, workspaceID)pool.Exec(cleanup, `DELETE FROM issue WHERE id = $1`, issueID)pool.Exec(cleanup, `DELETE FROM agent WHERE id = $1`, agentID)pool.Exec(cleanup, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)@@ -165,7 +222,208 @@ func TestReferencePluginInstallEnablePinDisableAndRetry(t *testing.T) {if err != nil || len(retryBundles) != 1 || retryManifest.SnapshotDigest != manifest.SnapshotDigest {t.Fatalf("retry did not inherit pinned manifest: bundles=%d manifest=%+v err=%v", len(retryBundles), retryManifest, err)}+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, retryTaskID); err != nil {+ t.Fatalf("complete retry task: %v", err)+ }if _, err := pluginService.RollbackPlugin(ctx, workspaceUUID, installation.ID, actorUUID, "1.0.0"); err != nil {t.Fatalf("rollback: %v", err)}++ privateSource := filepath.Join("..", "..", "..", "examples", "plugins", "incident-triage")+ if _, err := pluginService.InstallPrivateArchive(ctx, workspaceUUID, actorUUID, []byte("not a Plugin archive")); err == nil {+ t.Fatal("invalid private Plugin archive unexpectedly installed")+ } else {+ var pluginErr *PluginError+ if !errors.As(err, &pluginErr) || pluginErr.Kind != PluginErrorInvalid {+ t.Fatalf("invalid private Plugin error = %v", err)+ }+ }+ privateArchiveV1, _, err := plugincontract.PackDirectory(privateSource)+ if err != nil {+ t.Fatalf("pack private Plugin v1: %v", err)+ }+ privateInstallation, err := pluginService.InstallPrivateArchive(ctx, workspaceUUID, actorUUID, privateArchiveV1)+ if err != nil {+ t.Fatalf("install private Plugin v1: %v", err)+ }+ if privateInstallation.Enabled || privateInstallation.SourceKind != plugincontract.SourcePrivateDev {+ t.Fatalf("private install must be disabled and private: %+v", privateInstallation)+ }+ privateInstallation, err = pluginService.EnablePlugin(ctx, workspaceUUID, privateInstallation.ID, actorUUID, "agent", agentUUID)+ if err != nil {+ t.Fatalf("enable private Plugin: %v", err)+ }+ privateV1TaskID := createTask(nil)+ privateV1Bundles, _, privateV1Manifest, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(privateV1TaskID))+ if err != nil || len(privateV1Bundles) != 1 || privateV1Manifest == nil || !strings.Contains(privateV1Bundles[0].Content, "# Incident triage") {+ t.Fatalf("private v1 Skill missing from real task: bundles=%d manifest=%+v err=%v", len(privateV1Bundles), privateV1Manifest, err)+ }+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, privateV1TaskID); err != nil {+ t.Fatalf("complete private v1 task: %v", err)+ }++ privateV2Source := filepath.Join(t.TempDir(), "incident-triage")+ privateV2SkillDir := filepath.Join(privateV2Source, "skills", "incident-triage")+ if err := os.MkdirAll(privateV2SkillDir, 0o755); err != nil {+ t.Fatal(err)+ }+ manifestBytes, err := os.ReadFile(filepath.Join(privateSource, plugincontract.ManifestFilename))+ if err != nil {+ t.Fatal(err)+ }+ var privateManifest plugincontract.Manifest+ if err := json.Unmarshal(manifestBytes, &privateManifest); err != nil {+ t.Fatal(err)+ }+ privateManifest.Metadata.Version = "0.2.0"+ manifestBytes, err = json.MarshalIndent(privateManifest, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(privateV2Source, plugincontract.ManifestFilename), append(manifestBytes, '\n'), 0o644); err != nil {+ t.Fatal(err)+ }+ v2Skill := "---\nname: incident-triage\ndescription: Structure incident intake, severity assessment, evidence capture, and handoff.\n---\n\n# Incident triage v2\n\nUse the updated private workflow.\n"+ if err := os.WriteFile(filepath.Join(privateV2SkillDir, "SKILL.md"), []byte(v2Skill), 0o644); err != nil {+ t.Fatal(err)+ }+ privateArchiveV2, _, err := plugincontract.PackDirectory(privateV2Source)+ if err != nil {+ t.Fatalf("pack private Plugin v2: %v", err)+ }+ privateInstallation, err = pluginService.InstallPrivateArchive(ctx, workspaceUUID, actorUUID, privateArchiveV2)+ if err != nil {+ t.Fatalf("upgrade private Plugin: %v", err)+ }+ idempotentInstallation, err := pluginService.InstallPrivateArchive(ctx, workspaceUUID, actorUUID, privateArchiveV2)+ if err != nil || idempotentInstallation.ID != privateInstallation.ID {+ t.Fatalf("idempotent private upload: installation=%+v err=%v", idempotentInstallation, err)+ }+ repackedArchive := repackPluginArchive(t, privateArchiveV2)+ if bytes.Equal(repackedArchive, privateArchiveV2) {+ t.Fatal("repacked Private Plugin archive unexpectedly has identical bytes")+ }+ repackedInstallation, err := pluginService.InstallPrivateArchive(ctx, workspaceUUID, actorUUID, repackedArchive)+ if err != nil || repackedInstallation.ID != privateInstallation.ID {+ t.Fatalf("semantically equivalent private upload: installation=%+v err=%v", repackedInstallation, err)+ }+ if _, err := pluginService.InstallPrivateArchive(ctx, workspaceUUID, actorUUID, privateArchiveV1); err == nil {+ t.Fatal("private upload silently downgraded the installed release")+ } else {+ var pluginErr *PluginError+ if !errors.As(err, &pluginErr) || pluginErr.Kind != PluginErrorConflict || !strings.Contains(pluginErr.Message, "rollback") {+ t.Fatalf("private downgrade error = %v", err)+ }+ }+ if err := os.WriteFile(filepath.Join(privateV2SkillDir, "SKILL.md"), []byte(v2Skill+"\nConflicting content.\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ conflictingArchive, _, err := plugincontract.PackDirectory(privateV2Source)+ if err != nil {+ t.Fatalf("pack conflicting private Plugin: %v", err)+ }+ if _, err := pluginService.InstallPrivateArchive(ctx, workspaceUUID, actorUUID, conflictingArchive); err == nil {+ t.Fatal("changed content reused an immutable private Plugin version")+ } else {+ var pluginErr *PluginError+ if !errors.As(err, &pluginErr) || pluginErr.Kind != PluginErrorConflict {+ t.Fatalf("immutable private Plugin conflict error = %v", err)+ }+ }+ privateV2TaskID := createTask(nil)+ privateV2Bundles, _, _, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(privateV2TaskID))+ if err != nil || len(privateV2Bundles) != 1 || !strings.Contains(privateV2Bundles[0].Content, "# Incident triage v2") {+ t.Fatalf("private v2 Skill missing from new task: bundles=%d err=%v", len(privateV2Bundles), err)+ }+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, privateV2TaskID); err != nil {+ t.Fatalf("complete private v2 task: %v", err)+ }+ privateInstallation, err = pluginService.RollbackPlugin(ctx, workspaceUUID, privateInstallation.ID, actorUUID, "0.1.0")+ if err != nil {+ t.Fatalf("rollback private Plugin: %v", err)+ }+ if privateInstallation.SourceKind != plugincontract.SourcePrivateDev {+ t.Fatalf("rollback changed source kind: %+v", privateInstallation)+ }+ privateRollbackTaskID := createTask(nil)+ privateRollbackBundles, _, _, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(privateRollbackTaskID))+ if err != nil || len(privateRollbackBundles) != 1 || strings.Contains(privateRollbackBundles[0].Content, "# Incident triage v2") {+ t.Fatalf("private rollback did not restore v1 for new task: bundles=%d err=%v", len(privateRollbackBundles), err)+ }+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, privateRollbackTaskID); err != nil {+ t.Fatalf("complete private rollback task: %v", err)+ }+ privateV2Release, err := queries.GetPluginReleaseByVersion(ctx, db.GetPluginReleaseByVersionParams{+ PluginID: privateInstallation.PluginID,+ Version: "0.2.0",+ })+ if err != nil {+ t.Fatalf("load private v2 release: %v", err)+ }+ if _, err := queries.RevokePluginRelease(ctx, db.RevokePluginReleaseParams{+ RevocationStatus: "revoked",+ RevocationReason: pgtype.Text{String: "integration test", Valid: true},+ ID: privateV2Release.ID,+ }); err != nil {+ t.Fatalf("revoke private v2 release: %v", err)+ }+ if _, err := pluginService.RollbackPlugin(ctx, workspaceUUID, privateInstallation.ID, actorUUID, "0.2.0"); err == nil {+ t.Fatal("rollback selected a revoked Private Plugin release")+ } else {+ var pluginErr *PluginError+ if !errors.As(err, &pluginErr) || pluginErr.Kind != PluginErrorNotFound {+ t.Fatalf("revoked rollback error = %v", err)+ }+ }+ if _, err := pluginService.InstallPrivateArchive(ctx, workspaceUUID, actorUUID, privateArchiveV2); err == nil {+ t.Fatal("private upload reactivated a revoked release")+ } else {+ var pluginErr *PluginError+ if !errors.As(err, &pluginErr) || pluginErr.Kind != PluginErrorConflict || !strings.Contains(pluginErr.Message, "revoked") {+ t.Fatalf("revoked private upload error = %v", err)+ }+ }++ if err := pool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description, issue_prefix)+ VALUES ('Plugin Isolation', $1, '', 'PI2') RETURNING id+ `, fmt.Sprintf("plugin-isolation-%d", suffix)).Scan(&isolationWorkspaceID); err != nil {+ t.Fatal(err)+ }+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`, isolationWorkspaceID, userID); err != nil {+ t.Fatal(err)+ }+ isolationInstallation, err := pluginService.InstallPrivateArchive(ctx, util.MustParseUUID(isolationWorkspaceID), actorUUID, privateArchiveV1)+ if err != nil {+ t.Fatalf("install same private key in isolated workspace: %v", err)+ }+ if isolationInstallation.PluginID == privateInstallation.PluginID {+ t.Fatal("private Plugin identity leaked across workspaces")+ }+ if _, err := pluginService.EnablePlugin(ctx, util.MustParseUUID(isolationWorkspaceID), privateInstallation.ID, actorUUID, "workspace", util.MustParseUUID(isolationWorkspaceID)); err == nil {+ t.Fatal("cross-workspace installation mutation unexpectedly succeeded")+ }++ if err := pluginService.UninstallPlugin(ctx, workspaceUUID, privateInstallation.ID, actorUUID); err != nil {+ t.Fatalf("uninstall private Plugin: %v", err)+ }+ historicalBundles, _, historicalManifest, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(privateV1TaskID))+ if err != nil || len(historicalBundles) != 1 || historicalManifest.SnapshotDigest != privateV1Manifest.SnapshotDigest {+ t.Fatalf("uninstall changed historical private task: bundles=%d manifest=%+v err=%v", len(historicalBundles), historicalManifest, err)+ }+ afterUninstallTaskID := createTask(nil)+ afterUninstallBundles, _, _, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(afterUninstallTaskID))+ if err != nil || len(afterUninstallBundles) != 0 {+ t.Fatalf("uninstalled private Plugin leaked into new task: bundles=%d err=%v", len(afterUninstallBundles), err)+ }+ var auditCount int+ if err := pool.QueryRow(ctx, `+ SELECT count(*) FROM activity_log+ WHERE workspace_id = $1 AND action LIKE 'plugin_private_%'+ `, workspaceID).Scan(&auditCount); err != nil {+ t.Fatal(err)+ }+ if auditCount < 5 {+ t.Fatalf("private Plugin audit records = %d, want at least 5", auditCount)+ }}diff --git a/server/migrations/310_workspace_private_plugin_identity.down.sql b/server/migrations/310_workspace_private_plugin_identity.down.sqlnew file mode 100644index 0000000000..18223e7149--- /dev/null+++ b/server/migrations/310_workspace_private_plugin_identity.down.sql@@ -0,0 +1,3 @@+ALTER TABLE plugin_identity+ DROP CONSTRAINT IF EXISTS plugin_identity_scope_check,+ DROP COLUMN IF EXISTS owner_workspace_id;diff --git a/server/migrations/310_workspace_private_plugin_identity.up.sql b/server/migrations/310_workspace_private_plugin_identity.up.sqlnew file mode 100644index 0000000000..fb353e9326--- /dev/null+++ b/server/migrations/310_workspace_private_plugin_identity.up.sql@@ -0,0 +1,9 @@+-- Workspace ownership is part of private Plugin identity, while official+-- identities remain global. Relationships stay application-owned: no FK.+ALTER TABLE plugin_identity+ ADD COLUMN owner_workspace_id UUID,+ ADD CONSTRAINT plugin_identity_scope_check CHECK (+ (publisher_type = 'private_dev' AND trust_tier = 'private_dev' AND owner_workspace_id IS NOT NULL)+ OR+ (publisher_type <> 'private_dev' AND trust_tier <> 'private_dev' AND owner_workspace_id IS NULL)+ );diff --git a/server/migrations/311_plugin_identity_scoped_key_index.down.sql b/server/migrations/311_plugin_identity_scoped_key_index.down.sqlnew file mode 100644index 0000000000..893d86fc72--- /dev/null+++ b/server/migrations/311_plugin_identity_scoped_key_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_identity_scoped_key;diff --git a/server/migrations/311_plugin_identity_scoped_key_index.up.sql b/server/migrations/311_plugin_identity_scoped_key_index.up.sqlnew file mode 100644index 0000000000..3f66b20d9e--- /dev/null+++ b/server/migrations/311_plugin_identity_scoped_key_index.up.sql@@ -0,0 +1,2 @@+CREATE UNIQUE INDEX CONCURRENTLY idx_plugin_identity_scoped_key+ ON plugin_identity (COALESCE(owner_workspace_id, '00000000-0000-0000-0000-000000000000'::uuid), plugin_key);diff --git a/server/migrations/312_drop_global_plugin_identity_key_index.down.sql b/server/migrations/312_drop_global_plugin_identity_key_index.down.sqlnew file mode 100644index 0000000000..54c057ed3b--- /dev/null+++ b/server/migrations/312_drop_global_plugin_identity_key_index.down.sql@@ -0,0 +1,2 @@+CREATE UNIQUE INDEX CONCURRENTLY idx_plugin_identity_key+ ON plugin_identity (plugin_key);diff --git a/server/migrations/312_drop_global_plugin_identity_key_index.up.sql b/server/migrations/312_drop_global_plugin_identity_key_index.up.sqlnew file mode 100644index 0000000000..f39d0e378a--- /dev/null+++ b/server/migrations/312_drop_global_plugin_identity_key_index.up.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_identity_key;diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 08a577458c..5c7aca4507 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -981,14 +981,15 @@ type PluginHealth struct {}type PluginIdentity struct {- ID pgtype.UUID `json:"id"`- PluginKey string `json:"plugin_key"`- DisplayName string `json:"display_name"`- PublisherID string `json:"publisher_id"`- PublisherType string `json:"publisher_type"`- TrustTier string `json:"trust_tier"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- RetiredAt pgtype.Timestamptz `json:"retired_at"`+ ID pgtype.UUID `json:"id"`+ PluginKey string `json:"plugin_key"`+ DisplayName string `json:"display_name"`+ PublisherID string `json:"publisher_id"`+ PublisherType string `json:"publisher_type"`+ TrustTier string `json:"trust_tier"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ RetiredAt pgtype.Timestamptz `json:"retired_at"`+ OwnerWorkspaceID pgtype.UUID `json:"owner_workspace_id"`}type PluginInstallation struct {diff --git a/server/pkg/db/generated/plugin.sql.go b/server/pkg/db/generated/plugin.sql.goindex b6ab2e9995..4fb29f33c0 100644--- a/server/pkg/db/generated/plugin.sql.go+++ b/server/pkg/db/generated/plugin.sql.go@@ -454,19 +454,22 @@ func (q *Queries) CreatePluginHealth(ctx context.Context, arg CreatePluginHealthconst createPluginIdentity = `-- name: CreatePluginIdentity :oneINSERT INTO plugin_identity (- plugin_key, display_name, publisher_id, publisher_type, trust_tier+ plugin_key, display_name, publisher_id, publisher_type, trust_tier,+ owner_workspace_id) VALUES (- $1, $2, $3, $4, $5+ $1, $2, $3, $4, $5,+ $6)-RETURNING id, plugin_key, display_name, publisher_id, publisher_type, trust_tier, created_at, retired_at+RETURNING id, plugin_key, display_name, publisher_id, publisher_type, trust_tier, created_at, retired_at, owner_workspace_id`type CreatePluginIdentityParams struct {- PluginKey string `json:"plugin_key"`- DisplayName string `json:"display_name"`- PublisherID string `json:"publisher_id"`- PublisherType string `json:"publisher_type"`- TrustTier string `json:"trust_tier"`+ PluginKey string `json:"plugin_key"`+ DisplayName string `json:"display_name"`+ PublisherID string `json:"publisher_id"`+ PublisherType string `json:"publisher_type"`+ TrustTier string `json:"trust_tier"`+ OwnerWorkspaceID pgtype.UUID `json:"owner_workspace_id"`}func (q *Queries) CreatePluginIdentity(ctx context.Context, arg CreatePluginIdentityParams) (PluginIdentity, error) {@@ -476,6 +479,7 @@ func (q *Queries) CreatePluginIdentity(ctx context.Context, arg CreatePluginIdenarg.PublisherID,arg.PublisherType,arg.TrustTier,+ arg.OwnerWorkspaceID,)var i PluginIdentityerr := row.Scan(@@ -487,6 +491,7 @@ func (q *Queries) CreatePluginIdentity(ctx context.Context, arg CreatePluginIden&i.TrustTier,&i.CreatedAt,&i.RetiredAt,+ &i.OwnerWorkspaceID,)return i, err}@@ -691,6 +696,28 @@ func (q *Queries) GetLatestPluginRelease(ctx context.Context, pluginKey string)return i, err}+const getOfficialPluginIdentityByKey = `-- name: GetOfficialPluginIdentityByKey :one+SELECT id, plugin_key, display_name, publisher_id, publisher_type, trust_tier, created_at, retired_at, owner_workspace_id FROM plugin_identity+WHERE plugin_key = $1 AND owner_workspace_id IS NULL+`++func (q *Queries) GetOfficialPluginIdentityByKey(ctx context.Context, pluginKey string) (PluginIdentity, error) {+ row := q.db.QueryRow(ctx, getOfficialPluginIdentityByKey, pluginKey)+ var i PluginIdentity+ err := row.Scan(+ &i.ID,+ &i.PluginKey,+ &i.DisplayName,+ &i.PublisherID,+ &i.PublisherType,+ &i.TrustTier,+ &i.CreatedAt,+ &i.RetiredAt,+ &i.OwnerWorkspaceID,+ )+ return i, err+}+const getPluginArtifactFile = `-- name: GetPluginArtifactFile :oneSELECT id, release_id, path, digest, size_bytes, content, created_at FROM plugin_artifact_fileWHERE id = $1@@ -767,7 +794,7 @@ func (q *Queries) GetPluginExecutionManifestByTask(ctx context.Context, taskID p}const getPluginIdentity = `-- name: GetPluginIdentity :one-SELECT id, plugin_key, display_name, publisher_id, publisher_type, trust_tier, created_at, retired_at FROM plugin_identity+SELECT id, plugin_key, display_name, publisher_id, publisher_type, trust_tier, created_at, retired_at, owner_workspace_id FROM plugin_identityWHERE id = $1`@@ -783,27 +810,7 @@ func (q *Queries) GetPluginIdentity(ctx context.Context, id pgtype.UUID) (Plugin&i.TrustTier,&i.CreatedAt,&i.RetiredAt,- )- return i, err-}--const getPluginIdentityByKey = `-- name: GetPluginIdentityByKey :one-SELECT id, plugin_key, display_name, publisher_id, publisher_type, trust_tier, created_at, retired_at FROM plugin_identity-WHERE plugin_key = $1-`--func (q *Queries) GetPluginIdentityByKey(ctx context.Context, pluginKey string) (PluginIdentity, error) {- row := q.db.QueryRow(ctx, getPluginIdentityByKey, pluginKey)- var i PluginIdentity- err := row.Scan(- &i.ID,- &i.PluginKey,- &i.DisplayName,- &i.PublisherID,- &i.PublisherType,- &i.TrustTier,- &i.CreatedAt,- &i.RetiredAt,+ &i.OwnerWorkspaceID,)return i, err}@@ -873,6 +880,7 @@ SELECT release.id, release.plugin_id, release.version, release.manifest, releaseFROM plugin_release releaseJOIN plugin_identity identity ON identity.id = release.plugin_idWHERE identity.plugin_key = $1+ AND identity.owner_workspace_id IS NULLAND identity.retired_at IS NULLAND release.version = $2AND release.revocation_status = 'active'@@ -910,7 +918,7 @@ func (q *Queries) GetPluginReleaseByPluginKeyVersion(ctx context.Context, arg Geconst getPluginReleaseByVersion = `-- name: GetPluginReleaseByVersion :oneSELECT id, plugin_id, version, manifest, manifest_digest, source_kind, source_ref, archive_digest, artifact_ref, artifact_digest, artifact_size, signature, signature_key_id, revocation_status, revoked_at, revocation_reason, published_at FROM plugin_release-WHERE plugin_id = $1 AND version = $2+WHERE plugin_id = $1 AND version = $2 AND revocation_status = 'active'`type GetPluginReleaseByVersionParams struct {@@ -962,6 +970,72 @@ func (q *Queries) GetPluginWorkspaceCapabilityStateForUpdate(ctx context.Contextreturn i, err}+const getRegisteredPluginReleaseByVersion = `-- name: GetRegisteredPluginReleaseByVersion :one+SELECT id, plugin_id, version, manifest, manifest_digest, source_kind, source_ref, archive_digest, artifact_ref, artifact_digest, artifact_size, signature, signature_key_id, revocation_status, revoked_at, revocation_reason, published_at FROM plugin_release+WHERE plugin_id = $1 AND version = $2+`++type GetRegisteredPluginReleaseByVersionParams struct {+ PluginID pgtype.UUID `json:"plugin_id"`+ Version string `json:"version"`+}++func (q *Queries) GetRegisteredPluginReleaseByVersion(ctx context.Context, arg GetRegisteredPluginReleaseByVersionParams) (PluginRelease, error) {+ row := q.db.QueryRow(ctx, getRegisteredPluginReleaseByVersion, arg.PluginID, arg.Version)+ var i PluginRelease+ err := row.Scan(+ &i.ID,+ &i.PluginID,+ &i.Version,+ &i.Manifest,+ &i.ManifestDigest,+ &i.SourceKind,+ &i.SourceRef,+ &i.ArchiveDigest,+ &i.ArtifactRef,+ &i.ArtifactDigest,+ &i.ArtifactSize,+ &i.Signature,+ &i.SignatureKeyID,+ &i.RevocationStatus,+ &i.RevokedAt,+ &i.RevocationReason,+ &i.PublishedAt,+ )+ return i, err+}++const getWorkspacePluginHealthByInstallation = `-- name: GetWorkspacePluginHealthByInstallation :one+SELECT id, workspace_id, installation_id, scope_type, scope_id, state, reason_code, safe_detail, observed_generation, last_good_snapshot_id, observed_at FROM plugin_health+WHERE workspace_id = $1 AND installation_id = $2+ORDER BY observed_at DESC, id DESC+LIMIT 1+`++type GetWorkspacePluginHealthByInstallationParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+}++func (q *Queries) GetWorkspacePluginHealthByInstallation(ctx context.Context, arg GetWorkspacePluginHealthByInstallationParams) (PluginHealth, error) {+ row := q.db.QueryRow(ctx, getWorkspacePluginHealthByInstallation, arg.WorkspaceID, arg.InstallationID)+ var i PluginHealth+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.InstallationID,+ &i.ScopeType,+ &i.ScopeID,+ &i.State,+ &i.ReasonCode,+ &i.SafeDetail,+ &i.ObservedGeneration,+ &i.LastGoodSnapshotID,+ &i.ObservedAt,+ )+ return i, err+}+const getWorkspacePluginInstallation = `-- name: GetWorkspacePluginInstallation :oneSELECT id, workspace_id, plugin_id, source_kind, source_ref, desired_release_id, active_release_id, enabled, desired_generation, active_generation, lifecycle_status, installed_by, installed_at, updated_by, updated_at, disabled_at, uninstalled_at FROM plugin_installationWHERE workspace_id = $1 AND plugin_id = $2 AND uninstalled_at IS NULL@@ -997,6 +1071,97 @@ func (q *Queries) GetWorkspacePluginInstallation(ctx context.Context, arg GetWorreturn i, err}+const getWorkspacePrivatePluginIdentityByKey = `-- name: GetWorkspacePrivatePluginIdentityByKey :one+SELECT id, plugin_key, display_name, publisher_id, publisher_type, trust_tier, created_at, retired_at, owner_workspace_id FROM plugin_identity+WHERE owner_workspace_id = $1 AND plugin_key = $2+`++type GetWorkspacePrivatePluginIdentityByKeyParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PluginKey string `json:"plugin_key"`+}++func (q *Queries) GetWorkspacePrivatePluginIdentityByKey(ctx context.Context, arg GetWorkspacePrivatePluginIdentityByKeyParams) (PluginIdentity, error) {+ row := q.db.QueryRow(ctx, getWorkspacePrivatePluginIdentityByKey, arg.WorkspaceID, arg.PluginKey)+ var i PluginIdentity+ err := row.Scan(+ &i.ID,+ &i.PluginKey,+ &i.DisplayName,+ &i.PublisherID,+ &i.PublisherType,+ &i.TrustTier,+ &i.CreatedAt,+ &i.RetiredAt,+ &i.OwnerWorkspaceID,+ )+ return i, err+}++const getWorkspacePrivatePluginInstallationByRef = `-- name: GetWorkspacePrivatePluginInstallationByRef :one+SELECT installation.id, installation.workspace_id, installation.plugin_id, installation.source_kind, installation.source_ref, installation.desired_release_id, installation.active_release_id, installation.enabled, installation.desired_generation, installation.active_generation, installation.lifecycle_status, installation.installed_by, installation.installed_at, installation.updated_by, installation.updated_at, installation.disabled_at, installation.uninstalled_at+FROM plugin_installation installation+JOIN plugin_identity identity ON identity.id = installation.plugin_id+WHERE installation.workspace_id = $1+ AND identity.owner_workspace_id = $1+ AND installation.source_kind = 'private_dev'+ AND installation.uninstalled_at IS NULL+ AND (installation.id::text = $2::text OR identity.plugin_key = $2::text)+LIMIT 1+`++type GetWorkspacePrivatePluginInstallationByRefParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PluginRef string `json:"plugin_ref"`+}++func (q *Queries) GetWorkspacePrivatePluginInstallationByRef(ctx context.Context, arg GetWorkspacePrivatePluginInstallationByRefParams) (PluginInstallation, error) {+ row := q.db.QueryRow(ctx, getWorkspacePrivatePluginInstallationByRef, arg.WorkspaceID, arg.PluginRef)+ var i PluginInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginID,+ &i.SourceKind,+ &i.SourceRef,+ &i.DesiredReleaseID,+ &i.ActiveReleaseID,+ &i.Enabled,+ &i.DesiredGeneration,+ &i.ActiveGeneration,+ &i.LifecycleStatus,+ &i.InstalledBy,+ &i.InstalledAt,+ &i.UpdatedBy,+ &i.UpdatedAt,+ &i.DisabledAt,+ &i.UninstalledAt,+ )+ return i, err+}++const getWorkspacePrivatePluginUsage = `-- name: GetWorkspacePrivatePluginUsage :one+SELECT+ COUNT(release.id)::bigint AS release_count,+ COALESCE(SUM(release.artifact_size), 0)::bigint AS total_bytes+FROM plugin_release release+JOIN plugin_identity identity ON identity.id = release.plugin_id+WHERE identity.owner_workspace_id = $1+ AND release.source_kind = 'private_dev'+`++type GetWorkspacePrivatePluginUsageRow struct {+ ReleaseCount int64 `json:"release_count"`+ TotalBytes int64 `json:"total_bytes"`+}++func (q *Queries) GetWorkspacePrivatePluginUsage(ctx context.Context, workspaceID pgtype.UUID) (GetWorkspacePrivatePluginUsageRow, error) {+ row := q.db.QueryRow(ctx, getWorkspacePrivatePluginUsage, workspaceID)+ var i GetWorkspacePrivatePluginUsageRow+ err := row.Scan(&i.ReleaseCount, &i.TotalBytes)+ return i, err+}+const listLatestPluginBindings = `-- name: ListLatestPluginBindings :manySELECT DISTINCT ON (scope_type, scope_id) id, installation_id, scope_type, scope_id, enabled, binding_revision, created_by, created_atFROM plugin_binding@@ -1300,6 +1465,50 @@ func (q *Queries) ListPluginInstallationsForCompile(ctx context.Context, workspareturn items, nil}+const listPluginReleasesByPlugin = `-- name: ListPluginReleasesByPlugin :many+SELECT id, plugin_id, version, manifest, manifest_digest, source_kind, source_ref, archive_digest, artifact_ref, artifact_digest, artifact_size, signature, signature_key_id, revocation_status, revoked_at, revocation_reason, published_at FROM plugin_release+WHERE plugin_id = $1 AND revocation_status = 'active'+ORDER BY published_at DESC, id DESC+`++func (q *Queries) ListPluginReleasesByPlugin(ctx context.Context, pluginID pgtype.UUID) ([]PluginRelease, error) {+ rows, err := q.db.Query(ctx, listPluginReleasesByPlugin, pluginID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []PluginRelease{}+ for rows.Next() {+ var i PluginRelease+ if err := rows.Scan(+ &i.ID,+ &i.PluginID,+ &i.Version,+ &i.Manifest,+ &i.ManifestDigest,+ &i.SourceKind,+ &i.SourceRef,+ &i.ArchiveDigest,+ &i.ArtifactRef,+ &i.ArtifactDigest,+ &i.ArtifactSize,+ &i.Signature,+ &i.SignatureKeyID,+ &i.RevocationStatus,+ &i.RevokedAt,+ &i.RevocationReason,+ &i.PublishedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listWorkspacePluginHealth = `-- name: ListWorkspacePluginHealth :manySELECT id, workspace_id, installation_id, scope_type, scope_id, state, reason_code, safe_detail, observed_generation, last_good_snapshot_id, observed_at FROM plugin_healthWHERE workspace_id = $1@@ -1382,6 +1591,103 @@ func (q *Queries) ListWorkspacePluginInstallations(ctx context.Context, workspacreturn items, nil}+const listWorkspacePluginReleases = `-- name: ListWorkspacePluginReleases :many+SELECT release.id, release.plugin_id, release.version, release.manifest, release.manifest_digest, release.source_kind, release.source_ref, release.archive_digest, release.artifact_ref, release.artifact_digest, release.artifact_size, release.signature, release.signature_key_id, release.revocation_status, release.revoked_at, release.revocation_reason, release.published_at+FROM plugin_release release+JOIN plugin_installation installation ON installation.plugin_id = release.plugin_id+WHERE installation.workspace_id = $1+ AND installation.uninstalled_at IS NULL+ AND release.revocation_status = 'active'+ORDER BY release.plugin_id, release.published_at DESC, release.id DESC+`++func (q *Queries) ListWorkspacePluginReleases(ctx context.Context, workspaceID pgtype.UUID) ([]PluginRelease, error) {+ rows, err := q.db.Query(ctx, listWorkspacePluginReleases, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []PluginRelease{}+ for rows.Next() {+ var i PluginRelease+ if err := rows.Scan(+ &i.ID,+ &i.PluginID,+ &i.Version,+ &i.Manifest,+ &i.ManifestDigest,+ &i.SourceKind,+ &i.SourceRef,+ &i.ArchiveDigest,+ &i.ArtifactRef,+ &i.ArtifactDigest,+ &i.ArtifactSize,+ &i.Signature,+ &i.SignatureKeyID,+ &i.RevocationStatus,+ &i.RevokedAt,+ &i.RevocationReason,+ &i.PublishedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWorkspacePrivatePluginInstallations = `-- name: ListWorkspacePrivatePluginInstallations :many+SELECT installation.id, installation.workspace_id, installation.plugin_id, installation.source_kind, installation.source_ref, installation.desired_release_id, installation.active_release_id, installation.enabled, installation.desired_generation, installation.active_generation, installation.lifecycle_status, installation.installed_by, installation.installed_at, installation.updated_by, installation.updated_at, installation.disabled_at, installation.uninstalled_at+FROM plugin_installation installation+JOIN plugin_identity identity ON identity.id = installation.plugin_id+WHERE installation.workspace_id = $1+ AND identity.owner_workspace_id = $1+ AND installation.source_kind = 'private_dev'+ AND installation.uninstalled_at IS NULL+ORDER BY installation.installed_at, installation.id+`++func (q *Queries) ListWorkspacePrivatePluginInstallations(ctx context.Context, workspaceID pgtype.UUID) ([]PluginInstallation, error) {+ rows, err := q.db.Query(ctx, listWorkspacePrivatePluginInstallations, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []PluginInstallation{}+ for rows.Next() {+ var i PluginInstallation+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginID,+ &i.SourceKind,+ &i.SourceRef,+ &i.DesiredReleaseID,+ &i.ActiveReleaseID,+ &i.Enabled,+ &i.DesiredGeneration,+ &i.ActiveGeneration,+ &i.LifecycleStatus,+ &i.InstalledBy,+ &i.InstalledAt,+ &i.UpdatedBy,+ &i.UpdatedAt,+ &i.DisabledAt,+ &i.UninstalledAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const lockPluginRegistryKey = `-- name: LockPluginRegistryKey :execSELECT pg_advisory_xact_lock(hashtextextended($1, 0))`@@ -1395,7 +1701,7 @@ const retirePluginIdentity = `-- name: RetirePluginIdentity :oneUPDATE plugin_identitySET retired_at = COALESCE(retired_at, now())WHERE id = $1-RETURNING id, plugin_key, display_name, publisher_id, publisher_type, trust_tier, created_at, retired_at+RETURNING id, plugin_key, display_name, publisher_id, publisher_type, trust_tier, created_at, retired_at, owner_workspace_id`func (q *Queries) RetirePluginIdentity(ctx context.Context, id pgtype.UUID) (PluginIdentity, error) {@@ -1410,6 +1716,7 @@ func (q *Queries) RetirePluginIdentity(ctx context.Context, id pgtype.UUID) (Plu&i.TrustTier,&i.CreatedAt,&i.RetiredAt,+ &i.OwnerWorkspaceID,)return i, err}@@ -1524,3 +1831,58 @@ func (q *Queries) SetPluginInstallationDesiredState(ctx context.Context, arg Set)return i, err}++const uninstallPluginInstallation = `-- name: UninstallPluginInstallation :one+WITH target AS MATERIALIZED (+ SELECT installation.id+ FROM plugin_installation installation+ JOIN workspace ON workspace.id = installation.workspace_id+ WHERE installation.id = $2+ AND installation.workspace_id = $3+ AND installation.uninstalled_at IS NULL+ FOR UPDATE OF installation+ FOR KEY SHARE OF workspace+)+UPDATE plugin_installation installation+SET enabled = FALSE,+ desired_generation = installation.desired_generation + 1,+ lifecycle_status = 'uninstalled',+ updated_by = $1,+ updated_at = now(),+ disabled_at = COALESCE(installation.disabled_at, now()),+ uninstalled_at = now()+FROM target+WHERE installation.id = target.id+RETURNING installation.id, installation.workspace_id, installation.plugin_id, installation.source_kind, installation.source_ref, installation.desired_release_id, installation.active_release_id, installation.enabled, installation.desired_generation, installation.active_generation, installation.lifecycle_status, installation.installed_by, installation.installed_at, installation.updated_by, installation.updated_at, installation.disabled_at, installation.uninstalled_at+`++type UninstallPluginInstallationParams struct {+ UpdatedBy pgtype.UUID `json:"updated_by"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) UninstallPluginInstallation(ctx context.Context, arg UninstallPluginInstallationParams) (PluginInstallation, error) {+ row := q.db.QueryRow(ctx, uninstallPluginInstallation, arg.UpdatedBy, arg.ID, arg.WorkspaceID)+ var i PluginInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginID,+ &i.SourceKind,+ &i.SourceRef,+ &i.DesiredReleaseID,+ &i.ActiveReleaseID,+ &i.Enabled,+ &i.DesiredGeneration,+ &i.ActiveGeneration,+ &i.LifecycleStatus,+ &i.InstalledBy,+ &i.InstalledAt,+ &i.UpdatedBy,+ &i.UpdatedAt,+ &i.DisabledAt,+ &i.UninstalledAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex 30d1490b6d..8b83b9de56 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -461,6 +461,16 @@ WITH installations AS MATERIALIZED (FROM plugin_installationWHERE plugin_installation.workspace_id = $1),+private_identities AS MATERIALIZED (+ SELECT plugin_identity.id+ FROM plugin_identity+ WHERE plugin_identity.owner_workspace_id = $1+),+private_releases AS MATERIALIZED (+ SELECT plugin_release.id+ FROM plugin_release+ WHERE plugin_release.plugin_id IN (SELECT id FROM private_identities)+),deleted_health AS (DELETE FROM plugin_healthWHERE workspace_id = $1@@ -484,14 +494,26 @@ deleted_bindings AS (deleted_grants AS (DELETE FROM plugin_grantWHERE installation_id IN (SELECT id FROM installations)+),+deleted_installations AS (+ DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations)+),+deleted_private_artifacts AS (+ DELETE FROM plugin_artifact_file WHERE release_id IN (SELECT id FROM private_releases)+),+deleted_private_contributions AS (+ DELETE FROM plugin_contribution WHERE release_id IN (SELECT id FROM private_releases)+),+deleted_private_releases AS (+ DELETE FROM plugin_release WHERE id IN (SELECT id FROM private_releases))-DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations)+DELETE FROM plugin_identity WHERE id IN (SELECT id FROM private_identities)`// Plugin relationships have no foreign keys or cascades. Delete the append-only// grant/binding history first, then installation rows. Global identity, release,-// contribution, and artifact rows survive for other workspaces and historical-// execution-manifest attribution.+// contribution, and artifact rows survive. Workspace-owned private registry+// rows are removed after their execution manifests have been removed.func (q *Queries) DeleteWorkspacePluginData(ctx context.Context, workspaceID pgtype.UUID) error {_, err := q.db.Exec(ctx, deleteWorkspacePluginData, workspaceID)return errdiff --git a/server/pkg/db/queries/plugin.sql b/server/pkg/db/queries/plugin.sqlindex 4f31158b63..de1995bf7c 100644--- a/server/pkg/db/queries/plugin.sql+++ b/server/pkg/db/queries/plugin.sql@@ -3,9 +3,11 @@ SELECT pg_advisory_xact_lock(hashtextextended(@plugin_key, 0));-- name: CreatePluginIdentity :oneINSERT INTO plugin_identity (- plugin_key, display_name, publisher_id, publisher_type, trust_tier+ plugin_key, display_name, publisher_id, publisher_type, trust_tier,+ owner_workspace_id) VALUES (- @plugin_key, @display_name, @publisher_id, @publisher_type, @trust_tier+ @plugin_key, @display_name, @publisher_id, @publisher_type, @trust_tier,+ sqlc.narg('owner_workspace_id'))RETURNING *;@@ -13,9 +15,13 @@ RETURNING *;SELECT * FROM plugin_identityWHERE id = $1;--- name: GetPluginIdentityByKey :one+-- name: GetOfficialPluginIdentityByKey :oneSELECT * FROM plugin_identity-WHERE plugin_key = $1;+WHERE plugin_key = $1 AND owner_workspace_id IS NULL;++-- name: GetWorkspacePrivatePluginIdentityByKey :one+SELECT * FROM plugin_identity+WHERE owner_workspace_id = @workspace_id AND plugin_key = @plugin_key;-- name: RetirePluginIdentity :oneUPDATE plugin_identity@@ -50,6 +56,10 @@ WHERE id = $1;-- name: GetPluginReleaseByVersion :oneSELECT * FROM plugin_release+WHERE plugin_id = $1 AND version = $2 AND revocation_status = 'active';++-- name: GetRegisteredPluginReleaseByVersion :one+SELECT * FROM plugin_releaseWHERE plugin_id = $1 AND version = $2;-- name: RevokePluginRelease :one@@ -84,6 +94,11 @@ SELECT * FROM plugin_contributionWHERE release_id = $1ORDER BY ordinal, id;+-- name: ListPluginReleasesByPlugin :many+SELECT * FROM plugin_release+WHERE plugin_id = $1 AND revocation_status = 'active'+ORDER BY published_at DESC, id DESC;+-- name: CreatePluginInstallation :oneWITH parents AS MATERIALIZED (SELECT w.id AS workspace_id, p.id AS plugin_id, r.id AS release_id,@@ -121,6 +136,45 @@ SELECT * FROM plugin_installationWHERE workspace_id = $1 AND uninstalled_at IS NULLORDER BY installed_at, id;+-- name: ListWorkspacePluginReleases :many+SELECT release.*+FROM plugin_release release+JOIN plugin_installation installation ON installation.plugin_id = release.plugin_id+WHERE installation.workspace_id = @workspace_id+ AND installation.uninstalled_at IS NULL+ AND release.revocation_status = 'active'+ORDER BY release.plugin_id, release.published_at DESC, release.id DESC;++-- name: ListWorkspacePrivatePluginInstallations :many+SELECT installation.*+FROM plugin_installation installation+JOIN plugin_identity identity ON identity.id = installation.plugin_id+WHERE installation.workspace_id = @workspace_id+ AND identity.owner_workspace_id = @workspace_id+ AND installation.source_kind = 'private_dev'+ AND installation.uninstalled_at IS NULL+ORDER BY installation.installed_at, installation.id;++-- name: GetWorkspacePrivatePluginInstallationByRef :one+SELECT installation.*+FROM plugin_installation installation+JOIN plugin_identity identity ON identity.id = installation.plugin_id+WHERE installation.workspace_id = @workspace_id+ AND identity.owner_workspace_id = @workspace_id+ AND installation.source_kind = 'private_dev'+ AND installation.uninstalled_at IS NULL+ AND (installation.id::text = @plugin_ref::text OR identity.plugin_key = @plugin_ref::text)+LIMIT 1;++-- name: GetWorkspacePrivatePluginUsage :one+SELECT+ COUNT(release.id)::bigint AS release_count,+ COALESCE(SUM(release.artifact_size), 0)::bigint AS total_bytes+FROM plugin_release release+JOIN plugin_identity identity ON identity.id = release.plugin_id+WHERE identity.owner_workspace_id = @workspace_id+ AND release.source_kind = 'private_dev';+-- name: SetPluginInstallationDesiredState :oneWITH workspace_guard AS MATERIALIZED (SELECT workspace.id@@ -152,6 +206,29 @@ FROM targetWHERE i.id = target.idRETURNING i.*;+-- name: UninstallPluginInstallation :one+WITH target AS MATERIALIZED (+ SELECT installation.id+ FROM plugin_installation installation+ JOIN workspace ON workspace.id = installation.workspace_id+ WHERE installation.id = @id+ AND installation.workspace_id = @workspace_id+ AND installation.uninstalled_at IS NULL+ FOR UPDATE OF installation+ FOR KEY SHARE OF workspace+)+UPDATE plugin_installation installation+SET enabled = FALSE,+ desired_generation = installation.desired_generation + 1,+ lifecycle_status = 'uninstalled',+ updated_by = sqlc.narg('updated_by'),+ updated_at = now(),+ disabled_at = COALESCE(installation.disabled_at, now()),+ uninstalled_at = now()+FROM target+WHERE installation.id = target.id+RETURNING installation.*;+-- name: CreatePluginGrantRevision :oneWITH target AS MATERIALIZED (SELECT i.id@@ -275,6 +352,7 @@ SELECT release.*FROM plugin_release releaseJOIN plugin_identity identity ON identity.id = release.plugin_idWHERE identity.plugin_key = @plugin_key+ AND identity.owner_workspace_id IS NULLAND identity.retired_at IS NULLAND release.version = @versionAND release.revocation_status = 'active';@@ -425,3 +503,9 @@ WHERE task.id = @task_idSELECT * FROM plugin_healthWHERE workspace_id = $1ORDER BY observed_at DESC, id DESC;++-- name: GetWorkspacePluginHealthByInstallation :one+SELECT * FROM plugin_health+WHERE workspace_id = @workspace_id AND installation_id = @installation_id+ORDER BY observed_at DESC, id DESC+LIMIT 1;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 1fdb13f8f5..5c2bd9c70e 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -570,13 +570,23 @@ DELETE FROM skill WHERE skill.workspace_id = $1;-- name: DeleteWorkspacePluginData :exec-- Plugin relationships have no foreign keys or cascades. Delete the append-only-- grant/binding history first, then installation rows. Global identity, release,--- contribution, and artifact rows survive for other workspaces and historical--- execution-manifest attribution.+-- contribution, and artifact rows survive. Workspace-owned private registry+-- rows are removed after their execution manifests have been removed.WITH installations AS MATERIALIZED (SELECT plugin_installation.idFROM plugin_installationWHERE plugin_installation.workspace_id = $1),+private_identities AS MATERIALIZED (+ SELECT plugin_identity.id+ FROM plugin_identity+ WHERE plugin_identity.owner_workspace_id = $1+),+private_releases AS MATERIALIZED (+ SELECT plugin_release.id+ FROM plugin_release+ WHERE plugin_release.plugin_id IN (SELECT id FROM private_identities)+),deleted_health AS (DELETE FROM plugin_healthWHERE workspace_id = $1@@ -600,8 +610,20 @@ deleted_bindings AS (deleted_grants AS (DELETE FROM plugin_grantWHERE installation_id IN (SELECT id FROM installations)+),+deleted_installations AS (+ DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations)+),+deleted_private_artifacts AS (+ DELETE FROM plugin_artifact_file WHERE release_id IN (SELECT id FROM private_releases)+),+deleted_private_contributions AS (+ DELETE FROM plugin_contribution WHERE release_id IN (SELECT id FROM private_releases)+),+deleted_private_releases AS (+ DELETE FROM plugin_release WHERE id IN (SELECT id FROM private_releases))-DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations);+DELETE FROM plugin_identity WHERE id IN (SELECT id FROM private_identities);-- name: DeleteWorkspaceAgents :execDELETE FROM agent WHERE agent.workspace_id = $1;diff --git a/server/pkg/plugincontract/artifact.go b/server/pkg/plugincontract/artifact.goindex 01b38ccd5f..2863ce067f 100644--- a/server/pkg/plugincontract/artifact.go+++ b/server/pkg/plugincontract/artifact.go@@ -65,6 +65,9 @@ func ValidateArtifact(archive []byte) (Artifact, error) {if isDirectory {continue}+ if isInstallHookPath(name) {+ return Artifact{}, fmt.Errorf("plugin archive path %q is an installation or build hook", name)+ }if len(files) >= MaxArtifactFiles {return Artifact{}, fmt.Errorf("plugin artifact exceeds %d files", MaxArtifactFiles)}@@ -162,6 +165,21 @@ func ValidateArtifact(archive []byte) (Artifact, error) {}, nil}+func isInstallHookPath(name string) bool {+ base := strings.ToLower(path.Base(name))+ switch base {+ case "package.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock",+ "install", "install.sh", "install.ps1", "install.cmd", "install.bat",+ "preinstall", "preinstall.sh", "preinstall.ps1", "preinstall.cmd", "preinstall.bat",+ "postinstall", "postinstall.sh", "postinstall.ps1", "postinstall.cmd", "postinstall.bat",+ "prepare", "prepare.sh", "prepare.ps1", "prepare.cmd", "prepare.bat",+ "build", "build.sh", "build.ps1", "build.cmd", "build.bat":+ return true+ default:+ return false+ }+}+func validateArchivePath(name string) (string, bool, error) {if name == "" || strings.ContainsRune(name, '\x00') || strings.Contains(name, "\\") || strings.HasPrefix(name, "/") {return "", false, fmt.Errorf("plugin archive path %q is unsafe", name)diff --git a/server/pkg/plugincontract/artifact_test.go b/server/pkg/plugincontract/artifact_test.goindex 2b14247b8a..3e83b5b966 100644--- a/server/pkg/plugincontract/artifact_test.go+++ b/server/pkg/plugincontract/artifact_test.go@@ -129,3 +129,18 @@ func TestValidateArtifactRejectsMissingDeclaredEntry(t *testing.T) {t.Fatalf("ValidateArtifact missing entry error = %v", err)}}++func TestValidateArtifactRejectsInstallAndBuildHooks(t *testing.T) {+ for _, name := range []string{"package.json", "install.sh", "postinstall", "build", "build.ps1", "pnpm-lock.yaml"} {+ t.Run(name, func(t *testing.T) {+ files := append(referenceArchiveFiles(t), zipFixtureFile{+ name: "skills/review-readiness/" + name,+ content: []byte("declarative-looking but forbidden"),+ })+ _, err := ValidateArtifact(buildArchive(t, files))+ if err == nil || !strings.Contains(err.Error(), "installation or build hook") {+ t.Fatalf("ValidateArtifact error = %v, want install/build hook rejection", err)+ }+ })+ }+}diff --git a/server/pkg/plugincontract/pack.go b/server/pkg/plugincontract/pack.gonew file mode 100644index 0000000000..9c32681dd3--- /dev/null+++ b/server/pkg/plugincontract/pack.go@@ -0,0 +1,101 @@+package plugincontract++import (+ "archive/zip"+ "bytes"+ "fmt"+ "io/fs"+ "os"+ "path/filepath"+ "sort"+ "time"+)++var deterministicZipTime = time.Date(1980, time.January, 1, 0, 0, 0, 0, time.UTC)++// PackDirectory creates a deterministic ZIP from a Plugin source directory and+// validates the resulting artifact with the same contract used by the Server.+func PackDirectory(root string) ([]byte, Artifact, error) {+ root = filepath.Clean(root)+ rootInfo, err := os.Stat(root)+ if err != nil {+ return nil, Artifact{}, fmt.Errorf("open plugin directory: %w", err)+ }+ if !rootInfo.IsDir() {+ return nil, Artifact{}, fmt.Errorf("plugin source %q is not a directory", root)+ }++ type sourceFile struct {+ path string+ content []byte+ }+ files := make([]sourceFile, 0)+ err = filepath.WalkDir(root, func(current string, entry fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ if current == root {+ return nil+ }+ relative, err := filepath.Rel(root, current)+ if err != nil {+ return err+ }+ name := filepath.ToSlash(relative)+ if entry.Type()&os.ModeSymlink != 0 {+ return fmt.Errorf("plugin source path %q is a symlink", name)+ }+ if entry.IsDir() {+ return nil+ }+ info, err := entry.Info()+ if err != nil {+ return err+ }+ if !info.Mode().IsRegular() {+ return fmt.Errorf("plugin source path %q is not a regular file", name)+ }+ if info.Mode().Perm()&0o111 != 0 {+ return fmt.Errorf("plugin source path %q is executable", name)+ }+ if info.Size() > MaxFileSize {+ return fmt.Errorf("plugin source path %q exceeds %d bytes", name, MaxFileSize)+ }+ content, err := os.ReadFile(current)+ if err != nil {+ return err+ }+ files = append(files, sourceFile{path: name, content: content})+ return nil+ })+ if err != nil {+ return nil, Artifact{}, err+ }+ sort.Slice(files, func(i, j int) bool { return files[i].path < files[j].path })++ var buffer bytes.Buffer+ writer := zip.NewWriter(&buffer)+ for _, file := range files {+ header := &zip.FileHeader{Name: file.path, Method: zip.Deflate}+ header.SetMode(0o644)+ header.SetModTime(deterministicZipTime)+ header.Extra = nil+ header.Comment = ""+ part, err := writer.CreateHeader(header)+ if err != nil {+ return nil, Artifact{}, fmt.Errorf("create plugin archive path %q: %w", file.path, err)+ }+ if _, err := part.Write(file.content); err != nil {+ return nil, Artifact{}, fmt.Errorf("write plugin archive path %q: %w", file.path, err)+ }+ }+ if err := writer.Close(); err != nil {+ return nil, Artifact{}, fmt.Errorf("close plugin archive: %w", err)+ }+ archive := buffer.Bytes()+ artifact, err := ValidateArtifact(archive)+ if err != nil {+ return nil, Artifact{}, err+ }+ return append([]byte(nil), archive...), artifact, nil+}diff --git a/server/pkg/plugincontract/pack_test.go b/server/pkg/plugincontract/pack_test.gonew file mode 100644index 0000000000..ab7b60813f--- /dev/null+++ b/server/pkg/plugincontract/pack_test.go@@ -0,0 +1,73 @@+package plugincontract++import (+ "bytes"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func writePackFixture(t *testing.T, root string) {+ t.Helper()+ manifest := manifestJSON(t, validManifest())+ if err := os.WriteFile(filepath.Join(root, ManifestFilename), manifest, 0o644); err != nil {+ t.Fatal(err)+ }+ skillDir := filepath.Join(root, "skills", "review-readiness")+ if err := os.MkdirAll(skillDir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte("---\nname: review-readiness\n---\nReview the evidence.\n"), 0o644); err != nil {+ t.Fatal(err)+ }+}++func TestPackDirectoryIsDeterministic(t *testing.T) {+ root := t.TempDir()+ writePackFixture(t, root)++ firstArchive, firstArtifact, err := PackDirectory(root)+ if err != nil {+ t.Fatalf("PackDirectory first: %v", err)+ }+ if err := os.Chtimes(filepath.Join(root, ManifestFilename), deterministicZipTime.Add(10), deterministicZipTime.Add(20)); err != nil {+ t.Fatal(err)+ }+ secondArchive, secondArtifact, err := PackDirectory(root)+ if err != nil {+ t.Fatalf("PackDirectory second: %v", err)+ }+ if !bytes.Equal(firstArchive, secondArchive) {+ t.Fatal("archive bytes changed across identical packs")+ }+ if firstArtifact.ArchiveDigest != secondArtifact.ArchiveDigest || firstArtifact.ArtifactDigest != secondArtifact.ArtifactDigest {+ t.Fatalf("pack digests changed: first=%+v second=%+v", firstArtifact, secondArtifact)+ }+}++func TestPackDirectoryRejectsExecutableFile(t *testing.T) {+ root := t.TempDir()+ writePackFixture(t, root)+ path := filepath.Join(root, "skills", "review-readiness", "run.sh")+ if err := os.WriteFile(path, []byte("echo no\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ _, _, err := PackDirectory(root)+ if err == nil || !strings.Contains(err.Error(), "executable") {+ t.Fatalf("PackDirectory error = %v, want executable rejection", err)+ }+}++func TestPackDirectoryRejectsSymlink(t *testing.T) {+ root := t.TempDir()+ writePackFixture(t, root)+ link := filepath.Join(root, "skills", "review-readiness", "link")+ if err := os.Symlink("SKILL.md", link); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }+ _, _, err := PackDirectory(root)+ if err == nil || !strings.Contains(err.Error(), "symlink") {+ t.Fatalf("PackDirectory error = %v, want symlink rejection", err)+ }+}