Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6350: rebuild the plugin system (1/4) — cleanup and foundations (#7144)
Jiayuan Zhang6a17c001442d
diff --git a/.env.example b/.env.exampleindex 0c76f9d6e2..28c9d0e6b7 100644--- a/.env.example+++ b/.env.example@@ -424,6 +424,21 @@ GITHUB_APP_PRIVATE_KEY=MULTICA_VCS_INTEGRATION_ENABLED=MULTICA_VCS_SECRET_KEY=+# Plugins (Settings → Plugins). Multica never executes plugin code: a plugin+# runs only inside a sandboxed iframe in the user's browser, or on the plugin+# author's own server. Two optional settings:+# 1. MULTICA_PLUGIN_SECRET_KEY — a base64-encoded 32-byte key that encrypts+# `secret` config values at rest. Without it, saving a secret field fails+# closed rather than storing plaintext. Generate one with:+# openssl rand -base64 32+# 2. MULTICA_PLUGIN_DIR — an absolute path to a directory of plugin folders,+# each containing a multica.plugin.json. A self-hosted operator or plugin+# author can then install with the source URL `local:<folder-name>`+# instead of publishing to a public HTTPS host first. Leave empty to+# accept only public HTTPS manifest URLs.+MULTICA_PLUGIN_SECRET_KEY=+MULTICA_PLUGIN_DIR=+# Lark / Feishu bot integration (Settings → Integrations "Bind to Lark")# Off until MULTICA_LARK_SECRET_KEY is set — a base64-encoded 32-byte key# that encrypts each Bot's app secret at rest. Leave empty to disable.diff --git a/examples/plugins/exa-search/multica.plugin.json b/examples/plugins/exa-search/multica.plugin.jsondeleted file mode 100644index 20f731a59c..0000000000--- a/examples/plugins/exa-search/multica.plugin.json+++ /dev/null@@ -1,66 +0,0 @@-{- "api_version": "multica.plugin/v1",- "kind": "Plugin",- "metadata": {- "key": "dev.multica.exa-search",- "name": "Exa Search",- "description": "Reference Exa Plugin with research guidance and hosted web search tools",- "version": "0.3.0",- "publisher": "multica.examples"- },- "compatibility": {- "host_api": ">=1.0.0 <2.0.0",- "required_daemon_features": [- "execution-manifest-v1",- "agent-skill-v1",- "remote-mcp-v1"- ]- },- "requested_capabilities": [- "agent.skill.contribute",- "tool.remote-mcp.connect"- ],- "contributes": {- "agent_skills": [- {- "key": "exa-research",- "name": "Exa Research Guidance",- "description": "Use Exa for current web research, deep dives, competitive analysis, lead discovery, and source-backed investigation.",- "entry": "skills/exa-research/SKILL.md"- }- ],- "remote_mcp": [- {- "key": "exa-search",- "name": "Exa Search",- "description": "Search the public web and fetch page content through Exa's hosted MCP server",- "transport": "streamable-http",- "protocol_versions": ["2025-03-26", "2024-11-05"],- "endpoint_policy": {- "default_endpoint": "https://mcp.exa.ai/mcp",- "allowed_hosts": ["mcp.exa.ai"]- },- "authentication": {- "preferred": "none",- "supported": ["none", "bearer"]- },- "tool_intent": [- {- "name": "web_search_exa",- "description": "Search the web for a topic and return relevant content",- "risk": "read"- },- {- "name": "web_fetch_exa",- "description": "Fetch webpage content as clean markdown",- "risk": "read"- }- ],- "configuration_schema": {- "type": "object",- "additionalProperties": false- }- }- ]- }-}diff --git a/examples/plugins/exa-search/skills/exa-research/SKILL.md b/examples/plugins/exa-search/skills/exa-research/SKILL.mddeleted file mode 100644index 551994c180..0000000000--- a/examples/plugins/exa-search/skills/exa-research/SKILL.md+++ /dev/null@@ -1,25 +0,0 @@-----name: exa-research-description: "Use Exa for current web research, deep dives, competitive analysis, lead discovery, literature reviews, and source-backed investigation. Trigger on requests to research, search the web, find current information, compare competitors, discover companies or people, or investigate a topic across multiple sources."------# Exa research--Use the approved Exa MCP tools for web research in this workspace.--## Tool choice--- Start with `web_search_exa` when the user needs current facts, sources, companies, people, news, comparisons, or broader discovery.-- Use a semantically rich query that describes the ideal result, not a short keyword list.-- Use `web_fetch_exa` after search when snippets are insufficient, or when the user gives one or more URLs whose full contents must be read.-- Batch URLs into one `web_fetch_exa` call when possible.--## Workflow--1. Clarify the target, time range, filters, and desired output when they materially change the search.-2. Search broadly enough for the requested depth, then discard results that do not meet the user's criteria.-3. Fetch the strongest sources when their full context is needed.-4. Deduplicate repeated URLs and cross-check important claims across independent sources.-5. Answer with linked sources and distinguish sourced facts from inference.--If Exa is unavailable or rate-limited, report the exact failure and the authentication or configuration needed. Do not silently substitute a different search provider when the request or task specifically requires Exa.diff --git a/examples/plugins/incident-triage/multica.plugin.json b/examples/plugins/incident-triage/multica.plugin.jsondeleted file mode 100644index f97e4f535b..0000000000--- a/examples/plugins/incident-triage/multica.plugin.json+++ /dev/null@@ -1,26 +0,0 @@-{- "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.mddeleted file mode 100644index a03e2ff41b..0000000000--- a/examples/plugins/incident-triage/skills/incident-triage/SKILL.md+++ /dev/null@@ -1,16 +0,0 @@-----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/examples/plugins/incident-triage/skills/incident-triage/references/severity-guide.md b/examples/plugins/incident-triage/skills/incident-triage/references/severity-guide.mddeleted file mode 100644index ec2ebdffd1..0000000000--- a/examples/plugins/incident-triage/skills/incident-triage/references/severity-guide.md+++ /dev/null@@ -1,5 +0,0 @@-# Severity guide--- SEV-1: Widespread critical impact with no workaround.-- SEV-2: Significant impact with a partial workaround.-- SEV-3: Limited impact or a complete workaround.diff --git a/examples/plugins/mobbin/multica.plugin.json b/examples/plugins/mobbin/multica.plugin.jsondeleted file mode 100644index be605014ad..0000000000--- a/examples/plugins/mobbin/multica.plugin.json+++ /dev/null@@ -1,61 +0,0 @@-{- "api_version": "multica.plugin/v1",- "kind": "Plugin",- "metadata": {- "key": "dev.multica.mobbin-design-reference",- "name": "Mobbin Design Reference",- "description": "Example Plugin combining Mobbin design-research guidance with Mobbin's OAuth-protected hosted MCP server",- "version": "0.2.0",- "publisher": "multica.examples"- },- "compatibility": {- "host_api": ">=1.0.0 <2.0.0",- "required_daemon_features": [- "execution-manifest-v1",- "agent-skill-v1",- "remote-mcp-v1"- ]- },- "requested_capabilities": [- "agent.skill.contribute",- "tool.remote-mcp.connect"- ],- "contributes": {- "agent_skills": [- {- "key": "mobbin-design-research",- "name": "Mobbin Design Research",- "description": "Research real shipped screens and flows before designing or reviewing product interfaces.",- "entry": "skills/mobbin-design-research/SKILL.md"- }- ],- "remote_mcp": [- {- "key": "mobbin",- "name": "Mobbin",- "description": "Search Mobbin's hosted library of real product screens and flows",- "transport": "streamable-http",- "protocol_versions": ["2025-03-26", "2024-11-05"],- "endpoint_policy": {- "default_endpoint": "https://api.mobbin.com/mcp",- "allowed_hosts": ["api.mobbin.com"]- },- "authentication": {- "preferred": "oauth",- "supported": ["oauth"]- },- "tool_intent": [- {- "name": "*",- "description": "Discover Mobbin's authenticated research tools for explicit administrator review.",- "risk": "write"- }- ],- "configuration_schema": {- "type": "object",- "additionalProperties": false- }- }- ]- }-}diff --git a/examples/plugins/mobbin/skills/mobbin-design-research/SKILL.md b/examples/plugins/mobbin/skills/mobbin-design-research/SKILL.mddeleted file mode 100644index 5a37b5dbc0..0000000000--- a/examples/plugins/mobbin/skills/mobbin-design-research/SKILL.md+++ /dev/null@@ -1,23 +0,0 @@-----name: mobbin-design-research-description: Use Mobbin's approved MCP tools to research real shipped product screens and flows before designing or reviewing interfaces. Trigger for UI/UX pattern research, competitive design comparisons, onboarding, checkout, paywall, permissions, navigation, empty states, error states, and other requests that benefit from concrete app references.------# Mobbin Design Research--Use the Mobbin MCP tools to ground design decisions in real product examples. Treat the returned screens as research inputs, not templates to copy blindly.--## Workflow--1. Translate the request into a concrete pattern, platform, industry, and user state. Preserve the user's constraints and style guide.-2. Search broadly enough to compare several relevant shipped products. Refine the query when results mix unrelated flows.-3. Inspect the strongest examples and identify repeated patterns, meaningful differences, and likely tradeoffs.-4. Synthesize the evidence into recommendations for the user's product. Explain why a pattern fits the current context instead of merely listing screenshots.-5. Attribute examples to the product and platform shown by Mobbin, and distinguish observed details from your inference.--## Guardrails--- Prefer recent and contextually similar examples, but include a contrasting approach when it clarifies the decision.-- Do not imply that popularity proves usability or that a visual pattern is universally correct.-- Do not reproduce a product's branded screen verbatim. Adapt structure and interaction principles to the user's own system.-- If Mobbin is unavailable or requires authorization, report that directly and state what research could not be completed.diff --git a/examples/plugins/mobbin/skills/mobbin-design-research/agents/openai.yaml b/examples/plugins/mobbin/skills/mobbin-design-research/agents/openai.yamldeleted file mode 100644index 193b0de448..0000000000--- a/examples/plugins/mobbin/skills/mobbin-design-research/agents/openai.yaml+++ /dev/null@@ -1,4 +0,0 @@-interface:- display_name: "Mobbin Design Research"- short_description: "Research proven UI patterns with Mobbin"- default_prompt: "Use $mobbin-design-research to research proven product patterns for this interface."diff --git a/examples/plugins/remote-mcp-fixture/multica.plugin.json b/examples/plugins/remote-mcp-fixture/multica.plugin.jsondeleted file mode 100644index 70febc6965..0000000000--- a/examples/plugins/remote-mcp-fixture/multica.plugin.json+++ /dev/null@@ -1,51 +0,0 @@-{- "api_version": "multica.plugin/v1",- "kind": "Plugin",- "metadata": {- "key": "dev.multica.remote-mcp-fixture",- "name": "Remote MCP Fixture",- "description": "Reference Remote MCP Plugin with deterministic read and write tools",- "version": "1.0.0",- "publisher": "multica.dev"- },- "compatibility": {- "host_api": ">=1.0.0 <2.0.0",- "required_daemon_features": [- "execution-manifest-v1",- "remote-mcp-v1"- ]- },- "requested_capabilities": [- "tool.remote-mcp.connect"- ],- "contributes": {- "remote_mcp": [- {- "key": "fixture-tools",- "name": "Fixture Tools",- "description": "Exercises Remote MCP discovery, approval, read, and write paths",- "transport": "streamable-http",- "protocol_versions": ["2025-03-26"],- "endpoint_policy": {- "allowed_hosts": ["mcp-fixture.example.com"]- },- "tool_intent": [- {- "name": "fixture.read",- "description": "Read a deterministic fixture value",- "risk": "read"- },- {- "name": "fixture.write",- "description": "Append a value to the fixture log",- "risk": "write"- }- ],- "configuration_schema": {- "type": "object",- "additionalProperties": false- }- }- ]- }-}diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 3e8a4a4834..ec82d5a7a9 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -1,5 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest";import { ApiClient, ApiError, CHAT_DRAFT_RESTORE_CAPABILITY } from "./client";+import { EMPTY_PLUGIN_PREVIEW } from "./schemas";afterEach(() => {vi.unstubAllGlobals();@@ -69,24 +70,22 @@ describe("ApiClient pull-request response schema", () => {});});-describe("ApiClient Remote MCP OAuth response schema", () => {- it("degrades a malformed start response without inventing a navigation URL", async () => {+describe("ApiClient Plugin preview response schema", () => {+ it("degrades a malformed preview so a blank scope list is never shown as approval", async () => {vi.stubGlobal("fetch",vi.fn().mockResolvedValue(- new Response(JSON.stringify({ authorization_url: 42 }), {+ new Response(JSON.stringify({ scopes: "issues:read" }), {status: 200,headers: { "Content-Type": "application/json" },}),),);- await expect(new ApiClient("https://api.example.test").startPluginRemoteMCPOAuth(+ await expect(new ApiClient("https://api.example.test").previewPlugin("workspace-1",- "installation-1",- "search",- { public_config: {}, failure_policy: "required" },- )).resolves.toEqual({ authorization_url: "" });+ { source_url: "https://example.test/multica.plugin.json" },+ )).resolves.toEqual(EMPTY_PLUGIN_PREVIEW);});});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex d404c45947..f08fadeba5 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -147,15 +147,12 @@ import type {WebhookDelivery,NotificationPreferenceResponse,NotificationPreferences,- PluginBindingRequest,- PluginCatalogResponse,PluginInstallation,PluginInstallationListResponse,- PluginReleaseRequest,- RemoteMCPConfigRequest,- RemoteMCPDiscoveryResponse,- RemoteMCPOAuthStartRequest,- RemoteMCPOAuthStartResponse,+ PluginPreview,+ PluginPreviewRequest,+ PluginInstallRequest,+ PluginConfigRequest,GitHubPullRequest,ListGitHubInstallationsResponse,ListGitHubRepositoriesResponse,@@ -386,16 +383,13 @@ import {IssueViewListSchema,IssueViewPreferenceSchema,EMPTY_ISSUE_VIEW_PREFERENCE,- EMPTY_PLUGIN_CATALOG,EMPTY_PLUGIN_INSTALLATION,EMPTY_WORKSPACE_MCP_SERVER,EMPTY_PLUGIN_INSTALLATION_LIST,- PluginCatalogResponseSchema,+ EMPTY_PLUGIN_PREVIEW,PluginInstallationListResponseSchema,PluginInstallationSchema,- RemoteMCPDiscoveryResponseSchema,- RemoteMCPOAuthStartResponseSchema,- EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE,+ PluginPreviewSchema,WorkspaceMcpServerListSchema,WorkspaceMcpServerSchema,ShareLinkSchema,@@ -2318,19 +2312,6 @@ export class ApiClient {});}- async listPluginCatalog(workspaceId: string): Promise<PluginCatalogResponse> {- let raw: unknown;- try {- raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/catalog`);- } catch (error) {- if (error instanceof ApiError && error.status === 404) return EMPTY_PLUGIN_CATALOG;- throw error;- }- return parseWithFallback(raw, PluginCatalogResponseSchema, EMPTY_PLUGIN_CATALOG, {- endpoint: "GET /api/workspaces/{id}/plugins/catalog",- });- }-async listPluginInstallations(workspaceId: string): Promise<PluginInstallationListResponse> {let raw: unknown;try {@@ -2446,49 +2427,47 @@ export class ApiClient {});}- async installPlugin(workspaceId: string, request: PluginReleaseRequest): Promise<PluginInstallation> {- const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/install`, {+ /**+ * Step one of the two-step install. Nothing is written: the response is what+ * the consent screen shows before an installation exists.+ */+ async previewPlugin(workspaceId: string, request: PluginPreviewRequest): Promise<PluginPreview> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/preview`, {method: "POST",body: JSON.stringify(request),});- return parseWithFallback(raw, PluginInstallationSchema, EMPTY_PLUGIN_INSTALLATION, {- endpoint: "POST /api/workspaces/{id}/plugins/install",+ return parseWithFallback(raw, PluginPreviewSchema, EMPTY_PLUGIN_PREVIEW, {+ endpoint: "POST /api/workspaces/{id}/plugins/preview",});}- async upgradePlugin(workspaceId: string, installationId: string, request: PluginReleaseRequest): Promise<PluginInstallation> {- const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/upgrade`, {+ async installPlugin(workspaceId: string, request: PluginInstallRequest): Promise<PluginInstallation> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins`, {method: "POST",body: JSON.stringify(request),});return parseWithFallback(raw, PluginInstallationSchema, EMPTY_PLUGIN_INSTALLATION, {- endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/upgrade",+ endpoint: "POST /api/workspaces/{id}/plugins",});}- async setPluginEnabled(- workspaceId: string,- installationId: string,- enabled: boolean,- binding: PluginBindingRequest,- ): Promise<PluginInstallation> {- const action = enabled ? "enable" : "disable";- const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/${action}`, {- method: "POST",- body: JSON.stringify(binding),+ async configurePlugin(workspaceId: string, installationId: string, request: PluginConfigRequest): Promise<PluginInstallation> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/config`, {+ method: "PUT",+ body: JSON.stringify(request),});return parseWithFallback(raw, PluginInstallationSchema, EMPTY_PLUGIN_INSTALLATION, {- endpoint: `POST /api/workspaces/{id}/plugins/{installationId}/${action}`,+ endpoint: "PUT /api/workspaces/{id}/plugins/{installationId}/config",});}- async rollbackPlugin(workspaceId: string, installationId: string, version: string): Promise<PluginInstallation> {- const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/rollback`, {+ async setPluginEnabled(workspaceId: string, installationId: string, enabled: boolean): Promise<PluginInstallation> {+ const action = enabled ? "enable" : "disable";+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/${action}`, {method: "POST",- body: JSON.stringify({ version }),});return parseWithFallback(raw, PluginInstallationSchema, EMPTY_PLUGIN_INSTALLATION, {- endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/rollback",+ endpoint: `POST /api/workspaces/{id}/plugins/{installationId}/${action}`,});}@@ -2498,49 +2477,6 @@ export class ApiClient {});}- async configurePluginRemoteMCP(workspaceId: string, installationId: string, contributionKey: string, request: RemoteMCPConfigRequest): Promise<RemoteMCPDiscoveryResponse> {- const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/remote-mcp/${encodeURIComponent(contributionKey)}/config`, {- method: "PUT",- body: JSON.stringify(request),- });- return parseWithFallback(raw, RemoteMCPDiscoveryResponseSchema, { config_revision: 0, discovered_tools: [], discovered_schema_digest: "" }, {- endpoint: "PUT /api/workspaces/{id}/plugins/{installationId}/remote-mcp/{contributionKey}/config",- });- }-- async testPluginRemoteMCP(workspaceId: string, installationId: string, contributionKey: string): Promise<RemoteMCPDiscoveryResponse> {- const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/remote-mcp/${encodeURIComponent(contributionKey)}/test`, {- method: "POST",- body: JSON.stringify({}),- });- return parseWithFallback(raw, RemoteMCPDiscoveryResponseSchema, { config_revision: 0, discovered_tools: [], discovered_schema_digest: "" }, {- endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/remote-mcp/{contributionKey}/test",- });- }-- async startPluginRemoteMCPOAuth(workspaceId: string, installationId: string, contributionKey: string, request: RemoteMCPOAuthStartRequest): Promise<RemoteMCPOAuthStartResponse> {- const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/remote-mcp/${encodeURIComponent(contributionKey)}/oauth/start`, {- method: "POST",- body: JSON.stringify(request),- });- return parseWithFallback(raw, RemoteMCPOAuthStartResponseSchema, EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE, {- endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/remote-mcp/{contributionKey}/oauth/start",- });- }-- async approvePluginRemoteMCPTools(workspaceId: string, installationId: string, contributionKey: string, tools: string[]): Promise<void> {- await this.fetch(`/api/workspaces/${workspaceId}/plugins/${installationId}/remote-mcp/${encodeURIComponent(contributionKey)}/approve`, {- method: "POST",- body: JSON.stringify({ tools }),- });- }-- async revokePluginRemoteMCPCredential(workspaceId: string, installationId: string, contributionKey: string): Promise<void> {- await this.fetch(`/api/workspaces/${workspaceId}/plugins/${installationId}/remote-mcp/${encodeURIComponent(contributionKey)}/credential`, {- 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 c42aed90af..1df38515d0 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -47,12 +47,11 @@ import {SquadSchema,TimelineEntriesSchema,UserSchema,- EMPTY_PLUGIN_CATALOG,- PluginCatalogResponseSchema,PluginInstallationSchema,- RemoteMCPDiscoveryResponseSchema,- RemoteMCPOAuthStartResponseSchema,- EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE,+ PluginInstallationListResponseSchema,+ PluginPreviewSchema,+ EMPTY_PLUGIN_INSTALLATION_LIST,+ EMPTY_PLUGIN_PREVIEW,} from "./schemas";import { IssueViewSchema, IssueViewListSchema } from "./schemas";import {@@ -1403,81 +1402,70 @@ describe("WeCom installation schemas", () => {});});-describe("Plugin catalog schemas", () => {- it("defaults optional release fields without granting trust or compatibility", () => {- const parsed = PluginCatalogResponseSchema.parse({- releases: [{ plugin_key: "ai.multica.software-delivery", version: "1.0.0" }],- });- expect(parsed.supported).toBe(true);- expect(parsed.releases[0]?.compatible).toBe(false);- expect(parsed.releases[0]?.signature_verified).toBe(false);- expect(parsed.releases[0]?.contributions).toEqual([]);- });-- it("defaults missing lifecycle and binding fields to a disabled error state", () => {+describe("Plugin schemas", () => {+ it("defaults every missing installation field to an inert, disabled shape", () => {const parsed = PluginInstallationSchema.parse({ id: "installation-1" });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([]);- expect(parsed.remote_mcp).toEqual([]);+ expect(parsed.granted_scopes).toEqual([]);+ expect(parsed.config_schema).toEqual([]);+ expect(parsed.configured_secrets).toEqual([]);+ expect(parsed.surfaces).toEqual([]);+ expect(parsed.hooks).toEqual([]);+ expect(parsed.resources).toEqual([]);+ });++ it("does not model a secret value even when the server sends one", () => {+ // The API contract is that a secret is write-only. If a future response+ // ever regressed and echoed one, the client must not carry it into typed+ // state where a component could render it.+ const parsed = PluginInstallationSchema.parse({+ id: "installation-1",+ config: { repo: "multica-ai/multica" },+ configured_secrets: ["token"],+ });+ expect(parsed.config).toEqual({ repo: "multica-ai/multica" });+ expect(parsed.configured_secrets).toEqual(["token"]);+ expect(Object.keys(parsed)).not.toContain("secrets");});- it("parses Remote MCP status without accepting secret-shaped response fields", () => {+ it("keeps config field declaration order so the generated form is stable", () => {const parsed = PluginInstallationSchema.parse({id: "installation-1",- remote_mcp: [{- contribution_key: "search",- credential_state: "configured",- credential_hint: "••••1234",- credential: "must-not-be-modeled",- approved_tools: [{- name: "search.read",- input_schema: { type: "object" },- schema_digest: "sha256:fixture",- risk: "read",- }],- reviewed: true,- ready: true,- }],+ config_schema: [+ { key: "repo", type: "string", label: "Repo", required: true },+ { key: "token", type: "secret", label: "Token" },+ ],});- expect(parsed.remote_mcp[0]?.credential_state).toBe("configured");- expect(parsed.remote_mcp[0]?.approved_tools[0]?.name).toBe("search.read");- expect(parsed.remote_mcp[0]?.ready).toBe(true);- expect(parsed.remote_mcp[0]).not.toHaveProperty("credential");+ expect(parsed.config_schema.map((field) => field.key)).toEqual(["repo", "token"]);+ expect(parsed.config_schema[1]?.required).toBe(false);});- it("defaults a malformed Remote MCP discovery response without inventing tools", () => {- const fallback = { config_revision: 0, discovered_tools: [], discovered_schema_digest: "" };- const parsed = parseWithFallback(- { config_revision: "bad", discovered_tools: { name: "search" } },- RemoteMCPDiscoveryResponseSchema,- fallback,- { endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/remote-mcp/{key}/test" },- );- expect(parsed).toEqual(fallback);+ it("degrades a malformed installation list to empty rather than a partial list", () => {+ const parsed = parseWithFallback("not-json", PluginInstallationListResponseSchema, EMPTY_PLUGIN_INSTALLATION_LIST, {+ endpoint: "GET /api/workspaces/{id}/plugins",+ });+ expect(parsed).toEqual(EMPTY_PLUGIN_INSTALLATION_LIST);});- it("rejects a malformed Remote MCP OAuth start response", () => {- expect(parseWithFallback(- { authorization_url: undefined },- RemoteMCPOAuthStartResponseSchema,- EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE,- { endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/remote-mcp/{key}/oauth/start" },- )).toEqual(EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE);- expect(RemoteMCPOAuthStartResponseSchema.parse({- authorization_url: "https://auth.example.test/authorize?state=opaque",- }).authorization_url).toContain("auth.example.test");+ it("degrades a malformed preview so the consent screen cannot show a blank scope list as approval", () => {+ const parsed = parseWithFallback({ scopes: "issues:read" }, PluginPreviewSchema, EMPTY_PLUGIN_PREVIEW, {+ endpoint: "POST /api/workspaces/{id}/plugins/preview",+ });+ expect(parsed).toEqual(EMPTY_PLUGIN_PREVIEW);+ expect(parsed.scopes).toEqual([]);});- it("degrades a malformed catalog response to unsupported and empty", () => {- const parsed = parseWithFallback("not-json", PluginCatalogResponseSchema, EMPTY_PLUGIN_CATALOG, {- endpoint: "GET /api/workspaces/{id}/plugins/catalog",+ it("parses a preview that reports an upgrade adding new scopes", () => {+ const parsed = PluginPreviewSchema.parse({+ manifest: { key: "com.example.hello", name: "Hello", version: "2.0.0", author: { name: "example" } },+ scopes: ["issues:read", "comments:write"],+ installed: true,+ installed_version: "1.0.0",+ added_scopes: ["comments:write"],});- expect(parsed).toEqual(EMPTY_PLUGIN_CATALOG);- expect(parsed.supported).toBe(false);+ expect(parsed.installed).toBe(true);+ expect(parsed.installed_version).toBe("1.0.0");+ expect(parsed.added_scopes).toEqual(["comments:write"]);});});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 7994ada9e1..87b1606fbf 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -61,9 +61,9 @@ import type {IssueStatusEntry,ListIssueStatusesResponse,NotificationPreferenceResponse,- PluginCatalogResponse,PluginInstallation,PluginInstallationListResponse,+ PluginPreview,ResourceLabelsResponse,RuntimeModelListRequest,SearchIssuesResponse,@@ -80,122 +80,74 @@ import type {import type { CloudRuntimeNode } from "../runtimes/cloud-runtime";import type { CreateFeedbackResponse } from "../feedback/types";-export const PluginBindingSchema = z.object({- scope_type: z.string().default("workspace"),- scope_id: z.string().default(""),- enabled: z.boolean().default(false),- revision: z.number().default(0),-}).loose();--export const RemoteMCPToolSchema = z.object({- name: z.string(),+export const PluginConfigFieldSchema = z.object({+ key: z.string(),+ type: z.string().default("string"),+ label: z.string().default(""),description: z.string().optional(),- input_schema: z.record(z.string(), z.unknown()).default({}),- schema_digest: z.string().default(""),- risk: z.string().optional(),-});--export const PluginRemoteMCPConfigSchema = z.object({- contribution_key: z.string(),- default_endpoint: z.string().optional(),- preferred_auth: z.string().optional(),- supported_auth: z.array(z.string()).default([]),- config_revision: z.number().optional(),- endpoint: z.string().optional(),- endpoint_domain: z.string().optional(),- auth_type: z.string().optional(),- auth_header: z.string().optional(),- public_config: z.record(z.string(), z.unknown()).optional(),- connection_scope: z.string().optional(),- connected_by: z.string().optional(),- credential_state: z.string().default("missing"),- credential_hint: z.string().optional(),- failure_policy: z.string().optional(),- approved_tools: z.array(RemoteMCPToolSchema).default([]),- discovered_tools: z.array(RemoteMCPToolSchema).default([]),- discovered_schema_digest: z.string().optional(),- schema_digest: z.string().optional(),- reviewed: z.boolean().default(false),- ready: z.boolean().default(false),-});+ required: z.boolean().default(false),+ options: z.array(z.string()).default([]),+ placeholder: z.string().optional(),+}).loose();-export const RemoteMCPDiscoveryResponseSchema = z.object({- ok: z.boolean().optional(),- config_revision: z.number().default(0),- credential_state: z.string().optional(),- reviewed: z.boolean().optional(),- discovered_tools: z.array(RemoteMCPToolSchema).default([]),- discovered_schema_digest: z.string().default(""),-});+export const PluginSurfaceSchema = z.object({+ key: z.string(),+ type: z.string().default(""),+ name: z.string().default(""),+ entry: z.string().default(""),+ platforms: z.array(z.string()).default([]),+}).loose();-export const RemoteMCPOAuthStartResponseSchema = z.object({- authorization_url: z.string().url(),-});+export const PluginHookSchema = z.object({+ key: z.string(),+ name: z.string().default(""),+ description: z.string().default(""),+ triggers: z.array(z.string()).default([]),+ events: z.array(z.string()).default([]),+ transport: z.string().default(""),+}).loose();-export const EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE = { authorization_url: "" };+export const PluginResourceSchema = z.object({+ type: z.string().default(""),+ key: z.string(),+ entry: z.string().default(""),+}).loose();export const PluginInstallationSchema = z.object({id: z.string(),plugin_key: z.string().default(""),- display_name: z.string().default(""),- desired_version: z.string().default(""),- active_version: z.string().optional(),- enabled: z.boolean().default(false),- desired_generation: z.number().default(0),- active_generation: z.number().default(0),- lifecycle_status: z.string().default("error"),- health_state: z.string().optional(),- health_reason: z.string().optional(),+ name: z.string().default(""),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([]),- remote_mcp: z.array(PluginRemoteMCPConfigSchema).default([]),+ version: z.string().default(""),+ source_url: z.string().default(""),+ enabled: z.boolean().default(false),+ granted_scopes: z.array(z.string()).default([]),+ config_schema: z.array(PluginConfigFieldSchema).default([]),+ config: z.record(z.string(), z.unknown()).default({}),+ configured_secrets: z.array(z.string()).default([]),+ surfaces: z.array(PluginSurfaceSchema).default([]),+ hooks: z.array(PluginHookSchema).default([]),+ resources: z.array(PluginResourceSchema).default([]),+ created_at: z.string().default(""),+ updated_at: z.string().default(""),}).loose();export const EMPTY_PLUGIN_INSTALLATION: PluginInstallation = {id: "",plugin_key: "",- display_name: "",- desired_version: "",+ name: "",+ version: "",+ source_url: "",enabled: false,- 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: [],- remote_mcp: [],+ granted_scopes: [],+ config_schema: [],+ config: {},+ configured_secrets: [],+ surfaces: [],+ hooks: [],+ resources: [],+ created_at: "",+ updated_at: "",};export const PluginInstallationListResponseSchema = z.object({@@ -206,53 +158,32 @@ export const EMPTY_PLUGIN_INSTALLATION_LIST: PluginInstallationListResponse = {plugins: [],};-export const PluginCatalogContributionSchema = z.object({- key: z.string(),- type: z.string().default(""),+export const PluginManifestSummarySchema = z.object({+ key: z.string().default(""),name: z.string().default(""),- description: z.string().default(""),- entry_path: z.string().default(""),- entry_digest: z.string().default(""),+ description: z.string().optional(),+ version: z.string().default(""),+ author: z.object({+ name: z.string().default(""),+ url: z.string().optional(),+ }).loose().default({ name: "" }),}).loose();-export const PluginCatalogReleaseSchema = z.object({- plugin_key: z.string(),- name: z.string().default(""),- description: z.string().default(""),- version: z.string(),- 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(""),- requested_capabilities: z.array(z.string()).default([]),- host_api: z.string().default(""),- required_daemon_features: z.array(z.string()).default([]),- signature_key_id: z.string().default(""),- signature_verified: z.boolean().default(false),- manifest_digest: z.string().default(""),- archive_digest: z.string().default(""),- artifact_digest: z.string().default(""),- compatible: z.boolean().default(false),- compatibility_reason: z.string().optional(),- contributions: z.array(PluginCatalogContributionSchema).default([]),- installation: PluginInstallationSchema.optional(),-}).loose();--export const PluginCatalogResponseSchema = z.object({- releases: z.array(PluginCatalogReleaseSchema).default([]),- diagnostics: z.array(z.object({- source_ref: z.string().default(""),- code: z.string().default("unknown"),- message: z.string().default(""),- }).loose()).default([]),- supported: z.boolean().optional().default(true),-}).loose();--export const EMPTY_PLUGIN_CATALOG: PluginCatalogResponse = {- releases: [],- diagnostics: [],- supported: false,+export const PluginPreviewSchema = z.object({+ manifest: PluginManifestSummarySchema,+ scopes: z.array(z.string()).default([]),+ config_schema: z.array(PluginConfigFieldSchema).default([]),+ installed: z.boolean().default(false),+ installed_version: z.string().optional(),+ added_scopes: z.array(z.string()).default([]),+}).loose();++export const EMPTY_PLUGIN_PREVIEW: PluginPreview = {+ manifest: { key: "", name: "", version: "", author: { name: "" } },+ scopes: [],+ config_schema: [],+ installed: false,+ added_scopes: [],};export const GitHubInstallationSchema = z.object({diff --git a/packages/core/plugins/index.ts b/packages/core/plugins/index.tsindex 7a84634243..868bf87e53 100644--- a/packages/core/plugins/index.ts+++ b/packages/core/plugins/index.ts@@ -1,3 +1,2 @@export * from "./queries";export * from "./mutations";-export * from "./version";diff --git a/packages/core/plugins/mutations.ts b/packages/core/plugins/mutations.tsindex e98c3c5c31..47f7e4ad2f 100644--- a/packages/core/plugins/mutations.ts+++ b/packages/core/plugins/mutations.ts@@ -1,6 +1,6 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { api } from "../api";-import type { PluginBindingRequest, PluginReleaseRequest, RemoteMCPConfigRequest, RemoteMCPOAuthStartRequest } from "../types";+import type { PluginConfigRequest, PluginInstallRequest, PluginPreviewRequest } from "../types";import { pluginKeys } from "./queries";function useInvalidatePlugins(wsId: string) {@@ -8,40 +8,39 @@ function useInvalidatePlugins(wsId: string) {return () => queryClient.invalidateQueries({ queryKey: pluginKeys.all(wsId) });}-export function useInstallPlugin(wsId: string) {- const invalidate = useInvalidatePlugins(wsId);+/**+ * Preview is deliberately a mutation, not a query: it performs an outbound+ * fetch of a URL the administrator just typed, so it must run on an explicit+ * action and never be replayed by a cache refetch.+ */+export function usePreviewPlugin(wsId: string) {return useMutation({- mutationFn: (request: PluginReleaseRequest) => api.installPlugin(wsId, request),- onSettled: invalidate,+ mutationFn: (request: PluginPreviewRequest) => api.previewPlugin(wsId, request),});}-export function useUpgradePlugin(wsId: string) {+export function useInstallPlugin(wsId: string) {const invalidate = useInvalidatePlugins(wsId);return useMutation({- mutationFn: ({ installationId, ...request }: PluginReleaseRequest & { installationId: string }) =>- api.upgradePlugin(wsId, installationId, request),+ mutationFn: (request: PluginInstallRequest) => api.installPlugin(wsId, request),onSettled: invalidate,});}-export function useSetPluginEnabled(wsId: string) {+export function useConfigurePlugin(wsId: string) {const invalidate = useInvalidatePlugins(wsId);return useMutation({- mutationFn: ({ installationId, enabled, binding }: {- installationId: string;- enabled: boolean;- binding: PluginBindingRequest;- }) => api.setPluginEnabled(wsId, installationId, enabled, binding),+ mutationFn: ({ installationId, ...request }: PluginConfigRequest & { installationId: string }) =>+ api.configurePlugin(wsId, installationId, request),onSettled: invalidate,});}-export function useRollbackPlugin(wsId: string) {+export function useSetPluginEnabled(wsId: string) {const invalidate = useInvalidatePlugins(wsId);return useMutation({- mutationFn: ({ installationId, version }: { installationId: string; version: string }) =>- api.rollbackPlugin(wsId, installationId, version),+ mutationFn: ({ installationId, enabled }: { installationId: string; enabled: boolean }) =>+ api.setPluginEnabled(wsId, installationId, enabled),onSettled: invalidate,});}@@ -53,44 +52,3 @@ export function useUninstallPlugin(wsId: string) {onSettled: invalidate,});}--export function useConfigurePluginRemoteMCP(wsId: string) {- const invalidate = useInvalidatePlugins(wsId);- return useMutation({- mutationFn: ({ installationId, contributionKey, request }: { installationId: string; contributionKey: string; request: RemoteMCPConfigRequest }) =>- api.configurePluginRemoteMCP(wsId, installationId, contributionKey, request),- onSettled: invalidate,- });-}--export function useTestPluginRemoteMCP(wsId: string) {- return useMutation({- mutationFn: ({ installationId, contributionKey }: { installationId: string; contributionKey: string }) =>- api.testPluginRemoteMCP(wsId, installationId, contributionKey),- });-}--export function useStartPluginRemoteMCPOAuth(wsId: string) {- return useMutation({- mutationFn: ({ installationId, contributionKey, request }: { installationId: string; contributionKey: string; request: RemoteMCPOAuthStartRequest }) =>- api.startPluginRemoteMCPOAuth(wsId, installationId, contributionKey, request),- });-}--export function useApprovePluginRemoteMCPTools(wsId: string) {- const invalidate = useInvalidatePlugins(wsId);- return useMutation({- mutationFn: ({ installationId, contributionKey, tools }: { installationId: string; contributionKey: string; tools: string[] }) =>- api.approvePluginRemoteMCPTools(wsId, installationId, contributionKey, tools),- onSettled: invalidate,- });-}--export function useRevokePluginRemoteMCPCredential(wsId: string) {- const invalidate = useInvalidatePlugins(wsId);- return useMutation({- mutationFn: ({ installationId, contributionKey }: { installationId: string; contributionKey: string }) =>- api.revokePluginRemoteMCPCredential(wsId, installationId, contributionKey),- onSettled: invalidate,- });-}diff --git a/packages/core/plugins/queries.ts b/packages/core/plugins/queries.tsindex 4a4fbf7a3b..d235ec30e4 100644--- a/packages/core/plugins/queries.ts+++ b/packages/core/plugins/queries.ts@@ -3,18 +3,9 @@ import { api } from "../api";export const pluginKeys = {all: (wsId: string) => ["workspaces", wsId, "plugins"] as const,- catalog: (wsId: string) => [...pluginKeys.all(wsId), "catalog"] as const,installed: (wsId: string) => [...pluginKeys.all(wsId), "installed"] as const,};-export function pluginCatalogOptions(wsId: string) {- return queryOptions({- queryKey: pluginKeys.catalog(wsId),- queryFn: () => api.listPluginCatalog(wsId),- enabled: wsId.length > 0,- });-}-export function pluginInstallationsOptions(wsId: string) {return queryOptions({queryKey: pluginKeys.installed(wsId),diff --git a/packages/core/plugins/version.test.ts b/packages/core/plugins/version.test.tsdeleted file mode 100644index b86c316191..0000000000--- a/packages/core/plugins/version.test.ts+++ /dev/null@@ -1,18 +0,0 @@-import { describe, expect, it } from "vitest";-import { comparePluginVersions } from "./version";--describe("comparePluginVersions", () => {- it.each([- ["1.1.0", "1.0.0", 1],- ["1.0.0", "1.0.0", 0],- ["1.0.0", "1.0.0-rc.1", 1],- ["1.0.0-rc.10", "1.0.0-rc.9", 1],- ["1.0.0-beta.1", "1.0.0-1", 1],- ["1.0.0-rc.1", "1.0.0-rc.1.1", -1],- ["1.2.1+r1", "1.2.0", 1],- ["1.2.1+r2", "1.2.1+r1", 0],- ["100000000000000000000.0.0", "99999999999999999999.0.0", 1],- ])("orders %s against %s", (left, right, expectedSign) => {- expect(Math.sign(comparePluginVersions(left, right))).toBe(expectedSign);- });-});diff --git a/packages/core/plugins/version.ts b/packages/core/plugins/version.tsdeleted file mode 100644index 81571637f1..0000000000--- a/packages/core/plugins/version.ts+++ /dev/null@@ -1,62 +0,0 @@-const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;--interface ParsedVersion {- numeric: [string, string, string];- prerelease: string[];-}--function parseVersion(version: string): ParsedVersion | null {- const match = SEMVER_RE.exec(version);- if (!match) return null;- return {- numeric: [match[1]!, match[2]!, match[3]!],- prerelease: match[4]?.split(".") ?? [],- };-}--function compareNumericIdentifier(left: string, right: string): number {- const normalizedLeft = left.replace(/^0+/, "") || "0";- const normalizedRight = right.replace(/^0+/, "") || "0";- if (normalizedLeft.length !== normalizedRight.length) {- return normalizedLeft.length - normalizedRight.length;- }- return normalizedLeft < normalizedRight ? -1 : normalizedLeft > normalizedRight ? 1 : 0;-}--/** Compare two validated Plugin manifest versions using SemVer precedence. */-export function comparePluginVersions(left: string, right: string): number {- const parsedLeft = parseVersion(left);- const parsedRight = parseVersion(right);- if (!parsedLeft || !parsedRight) {- return left < right ? -1 : left > right ? 1 : 0;- }-- for (let index = 0; index < parsedLeft.numeric.length; index += 1) {- const comparison = compareNumericIdentifier(parsedLeft.numeric[index]!, parsedRight.numeric[index]!);- if (comparison !== 0) return comparison;- }-- const leftPrerelease = parsedLeft.prerelease;- const rightPrerelease = parsedRight.prerelease;- if (leftPrerelease.length === 0 && rightPrerelease.length === 0) return 0;- if (leftPrerelease.length === 0) return 1;- if (rightPrerelease.length === 0) return -1;-- for (let index = 0; index < leftPrerelease.length && index < rightPrerelease.length; index += 1) {- const leftIdentifier = leftPrerelease[index]!;- const rightIdentifier = rightPrerelease[index]!;- const leftIsNumeric = /^\d+$/.test(leftIdentifier);- const rightIsNumeric = /^\d+$/.test(rightIdentifier);- if (leftIsNumeric && rightIsNumeric) {- const comparison = compareNumericIdentifier(leftIdentifier, rightIdentifier);- if (comparison !== 0) return comparison;- } else if (leftIsNumeric) {- return -1;- } else if (rightIsNumeric) {- return 1;- } else if (leftIdentifier !== rightIdentifier) {- return leftIdentifier < rightIdentifier ? -1 : 1;- }- }- return leftPrerelease.length - rightPrerelease.length;-}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 885e2f7d5b..2365ea7c64 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -85,21 +85,20 @@ export type {export { RUNTIME_PROFILE_PROTOCOL_FAMILIES } from "./agent";export type { Workspace, WorkspaceRepo, WorkspaceMcpServer, Member, MemberRole, User, MemberWithUser, Invitation, ShareLink, ShareLinkInfo } from "./workspace";export type {- PluginBinding,PluginInstallation,- PluginCatalogContribution,- PluginCatalogRelease,- PluginCatalogDiagnostic,- PluginCatalogResponse,+ PluginConfigField,+ PluginConfigFieldType,+ PluginSurface,+ PluginSurfaceType,+ PluginHook,+ PluginHookTrigger,+ PluginResource,PluginInstallationListResponse,- PluginReleaseRequest,- PluginBindingRequest,- PluginRemoteMCPConfig,- RemoteMCPConfigRequest,- RemoteMCPDiscoveryResponse,- RemoteMCPOAuthStartRequest,- RemoteMCPOAuthStartResponse,- RemoteMCPTool,+ PluginManifestSummary,+ PluginPreview,+ PluginPreviewRequest,+ PluginInstallRequest,+ PluginConfigRequest,} from "./plugin";export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread } from "./inbox";export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";diff --git a/packages/core/types/plugin.ts b/packages/core/types/plugin.tsindex e25a9e7d01..507184ef82 100644--- a/packages/core/types/plugin.ts+++ b/packages/core/types/plugin.ts@@ -1,163 +1,105 @@-export interface PluginBinding {- scope_type: string;- scope_id: string;- enabled: boolean;- revision: number;-}+/**+ * A plugin relates to Multica in exactly three ways: Action (plugin calls+ * Multica), Hook (Multica calls plugin), and Resource (a static contribution+ * with no call at all). These types mirror the manifest contract the server+ * parses; the client never re-derives them from anything else.+ */-export interface PluginInstallation {- id: string;- plugin_key: string;- display_name: string;- desired_version: string;- active_version?: string;- enabled: boolean;- desired_generation: number;- active_generation: number;- 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[];- remote_mcp: PluginRemoteMCPConfig[];-}+export type PluginConfigFieldType = "string" | "number" | "bool" | "enum" | "secret";-export interface RemoteMCPTool {- name: string;+export interface PluginConfigField {+ key: string;+ type: PluginConfigFieldType | string;+ label: string;description?: string;- input_schema: Record<string, unknown>;- schema_digest: string;- risk?: "read" | "write" | string;+ required: boolean;+ options?: string[];+ placeholder?: string;}-export interface PluginRemoteMCPConfig {- contribution_key: string;- default_endpoint?: string;- preferred_auth?: "none" | "oauth" | "bearer" | "header" | string;- supported_auth?: string[];- config_revision?: number;- endpoint?: string;- endpoint_domain?: string;- auth_type?: "none" | "oauth" | "bearer" | "header" | string;- auth_header?: string;- public_config?: Record<string, unknown>;- connection_scope?: "workspace" | "user" | string;- connected_by?: string;- credential_state: "missing" | "configured" | "revoked" | "not_required" | string;- credential_hint?: string;- failure_policy?: "required" | "optional" | string;- approved_tools: RemoteMCPTool[];- discovered_tools: RemoteMCPTool[];- discovered_schema_digest?: string;- schema_digest?: string;- reviewed: boolean;- ready: boolean;-}--export interface RemoteMCPConfigRequest {- endpoint: string;- public_config: Record<string, unknown>;- auth_type: "none" | "bearer" | "header";- auth_header?: string;- credential?: string;- failure_policy: "required" | "optional";-}--export interface RemoteMCPDiscoveryResponse {- ok?: boolean;- config_revision: number;- credential_state?: string;- reviewed?: boolean;- discovered_tools: RemoteMCPTool[];- discovered_schema_digest: string;-}+export type PluginSurfaceType = "issue_panel" | "sidebar_panel" | "modal";-export interface RemoteMCPOAuthStartRequest {- endpoint?: string;- public_config: Record<string, unknown>;- failure_policy: "required" | "optional";- scope?: string;- client_id?: string;- client_secret?: string;- token_endpoint_auth_method?: "none" | "client_secret_basic" | "client_secret_post";- authorization_endpoint?: string;- token_endpoint?: string;- return_to?: string;+export interface PluginSurface {+ key: string;+ type: PluginSurfaceType | string;+ name: string;+ entry: string;+ platforms?: string[];}-export interface RemoteMCPOAuthStartResponse {- authorization_url: string;-}+export type PluginHookTrigger = "ui" | "manual" | "agent" | "event";-export interface PluginCatalogContribution {+export interface PluginHook {key: string;- type: string;name: string;description: string;- entry_path: string;- entry_digest: string;+ triggers: (PluginHookTrigger | string)[];+ events?: string[];+ transport: string;+}++export interface PluginResource {+ type: string;+ key: string;+ entry: string;}-export interface PluginCatalogRelease {+export interface PluginInstallation {+ id: string;plugin_key: string;name: string;- description: string;+ description?: string;version: string;- publisher: string;- publisher_type: string;- trust_tier: string;- source_kind: string;- source_ref: string;- requested_capabilities: string[];- host_api: string;- required_daemon_features: string[];- signature_key_id: string;- signature_verified: boolean;- manifest_digest: string;- archive_digest: string;- artifact_digest: string;- compatible: boolean;- compatibility_reason?: string;- contributions: PluginCatalogContribution[];- installation?: PluginInstallation;+ source_url: string;+ enabled: boolean;+ granted_scopes: string[];+ config_schema: PluginConfigField[];+ /** Non-secret values only. A secret is never returned by any endpoint. */+ config: Record<string, unknown>;+ /** Names of secret fields that hold a value — never the values themselves. */+ configured_secrets: string[];+ surfaces: PluginSurface[];+ hooks: PluginHook[];+ resources: PluginResource[];+ created_at: string;+ updated_at: string;+}++export interface PluginInstallationListResponse {+ plugins: PluginInstallation[];}-export interface PluginCatalogDiagnostic {- source_ref: string;- code: string;- message: string;+export interface PluginManifestSummary {+ key: string;+ name: string;+ description?: string;+ version: string;+ author: { name: string; url?: string };}-export interface PluginCatalogResponse {- releases: PluginCatalogRelease[];- diagnostics: PluginCatalogDiagnostic[];- supported: boolean;+/**+ * What the consent screen renders. There is no signature and no trust tier in+ * this model: an administrator reading the scope list IS the trust decision.+ */+export interface PluginPreview {+ manifest: PluginManifestSummary;+ scopes: string[];+ config_schema: PluginConfigField[];+ installed: boolean;+ installed_version?: string;+ /** Scopes this install would add on top of what is already granted. */+ added_scopes?: string[];}-export interface PluginInstallationListResponse {- plugins: PluginInstallation[];+export interface PluginPreviewRequest {+ source_url: string;}-export interface PluginReleaseRequest {- plugin_key: string;- version: string;+export interface PluginInstallRequest {+ source_url: string;+ granted_scopes: string[];}-export interface PluginBindingRequest {- scope_type: "workspace" | "agent";- scope_id: string;+export interface PluginConfigRequest {+ values: Record<string, unknown>;}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex ce4faeaf66..447cf79d8c 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -265,126 +265,65 @@},"plugins": {"title": "Plugins",- "description": "Review, install, scope, and manage signed capabilities delivered by Multica.",+ "description": "Install plugins by URL and review exactly what each one is allowed to reach.","loading": "Loading Plugins","load_failed": "Plugins couldn't be loaded",- "load_failed_description": "Try again. Existing enabled Plugins and pinned runs are unaffected.",- "backend_unavailable": "Plugin management isn't available",- "backend_unavailable_description": "This server predates the bundled Plugin catalog. Update the backend to manage Plugins here.",- "catalog_degraded": "Some bundled releases were isolated",- "catalog_degraded_description": "A bundled source failed validation. Healthy signed releases remain available.",+ "load_failed_description": "Try again. Installed Plugins are unaffected.","read_only": "Read-only access",- "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",- "incompatible_description": "This release requires a newer host API or daemon capability and cannot be activated.",- "install_disabled_hint": "Installation is disabled by default. Choose a workspace or agent scope after installing.",- "install": "Install",- "installed_disabled": "Plugin installed and left disabled",- "active_version": "Active version:",- "health": "Health:",- "bindings": "Enabled scopes",- "unknown_agent": "Unknown agent",- "unknown_member": "Unknown member",- "workspace_scope": "Workspace",- "agent_scope": "Agent",- "binding_disabled": "Plugin binding disabled",- "disable_binding": "Disable",- "no_bindings": "No enabled scopes. New runs do not receive this Plugin.",- "enable_scope": "Enable scope",- "enabled": "Plugin scope enabled",- "disable_workspace": "Disable workspace",- "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}}",+ "read_only_description": "Workspace owners and admins can install, configure, and remove Plugins.",+ "empty": "No Plugins are installed yet.","action_failed": "Plugin action failed",- "none": "None",+ "enabled": "Plugin enabled",+ "disabled": "Plugin disabled",+ "enabled_label": "Enable Plugin",+ "uninstall": "Uninstall",+ "uninstalled": "Plugin uninstalled. Its stored data and secrets were removed.",+ "granted_scopes": "Granted access",+ "contributes": "Contributes",+ "version": "v{{version}}",+ "byline": "{{author}} · v{{version}}",+ "source": "Source","states": {- "disabled": "Disabled",- "activating": "Activating",- "healthy": "Healthy",- "degraded": "Degraded",- "failed": "Failed"+ "disabled": "Disabled"},- "review": {- "contributes": "Contributes",- "permissions": "Requested capability",- "compatibility": "Compatibility",- "host_api": "Host API",- "publisher": "Publisher and signing identity",- "none": "None"+ "install": {+ "title": "Install a Plugin",+ "description": "Paste the URL of a plugin manifest. You'll see what it asks for before anything is installed.",+ "placeholder": "https://example.com/multica.plugin.json",+ "review": "Review"},- "remote_mcp": {- "title": "Remote MCP connection",- "endpoint": "HTTPS endpoint",- "endpoint_placeholder": "https://mcp.example.com/mcp",- "auth": "Authentication",- "auth_types": {- "none": "None",- "oauth": "OAuth (recommended)",- "bearer": "Bearer token",- "header": "Custom header"- },- "header_name": "Header name",- "credential": "Credential (stored encrypted)",- "connect": "Connect",- "connected": "Connected",- "ready_to_connect": "Ready to connect",- "complete_before_enabling": "Connect the MCP and approve at least one tool before enabling a scope.",- "advanced": "Advanced configuration",- "oauth_scope": "OAuth scopes (automatic when empty)",- "oauth_client_id": "OAuth client ID (automatic when empty)",- "oauth_client_secret": "OAuth client secret",- "oauth_authorization_endpoint": "Authorization endpoint override",- "oauth_token_endpoint": "Token endpoint override",- "oauth_token_auth_method": "Token endpoint authentication",- "oauth_token_auth_methods": {- "none": "Public client (PKCE)",- "client_secret_basic": "Client secret (HTTP Basic)",- "client_secret_post": "Client secret (request body)"- },- "public_config": "Public configuration (JSON object)",- "invalid_public_config": "Public configuration must be a valid JSON object",- "failure_policy": "Failure policy",- "failure_policies": {- "required": "Required — stop the task",- "optional": "Optional — continue without tools"- },- "configure_and_discover": "Save and discover tools",- "test": "Test connection",- "approve": "Approve selected tools",- "revoke": "Revoke credential",- "credential_states": {- "configured": "Credential configured",- "revoked": "Credential revoked",- "missing": "Credential missing",- "not_required": "No credential required"- },- "reviewed": "Tools approved",- "pending_review": "Approval required",- "approved_tools": "Approved tools",- "no_tools": "The server did not advertise any tools.",- "discovery": "Discovered tools — review access explicitly",- "read": "Read",- "write": "Write",- "configured_success": "Connection saved; review the discovered tools",- "oauth_connected_success": "OAuth connection completed; review the discovered tools",- "oauth_connect_failed": "OAuth connection could not be completed. Try again.",- "test_success": "Connection test succeeded",- "approved_success": "Tool access approved",- "revoked_success": "Credential revoked and the Plugin disabled"+ "installed": {+ "title": "Installed"+ },+ "consent": {+ "title": "This Plugin is asking for the following access",+ "description": "Multica never runs plugin code on its servers. A Plugin can only do what these scopes allow, and never more than the person using it can already do.",+ "cancel": "Cancel",+ "confirm": "Grant and install",+ "confirm_upgrade": "Grant and upgrade",+ "installed": "Plugin installed",+ "upgrade_from": " · upgrading from v{{version}}",+ "new_scope": "New"+ },+ "config": {+ "title": "Configuration",+ "save": "Save",+ "saved": "Configuration saved",+ "secret_set": "Saved — enter a new value to replace it"+ },+ "scopes": {+ "issues_read": "Read issues",+ "issues_write": "Create and edit issues",+ "comments_read": "Read comments",+ "comments_write": "Post comments",+ "tasks_read": "Read agent tasks",+ "tasks_write": "Start and update agent tasks",+ "agents_read": "Read the agent list",+ "members_read": "Read the member list",+ "storage_user": "Store data for each member individually",+ "storage_workspace": "Store data shared by the workspace",+ "net": "Send data to {{domain}}",+ "unknown": "Unrecognized access — do not install"}},"properties": {diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex f993b67816..7db046be6a 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -265,126 +265,65 @@},"plugins": {"title": "Plugins",- "description": "Multica が提供する署名済み機能を確認、インストール、スコープ設定、管理します。",+ "description": "URL から Plugin をインストールし、各 Plugin が何にアクセスできるかを確認します。","loading": "Plugins を読み込み中","load_failed": "Plugins を読み込めませんでした",- "load_failed_description": "再試行してください。有効な Plugins と固定済みの作業には影響しません。",- "backend_unavailable": "Plugin 管理を利用できません",- "backend_unavailable_description": "このサーバーは bundled Plugin catalog に対応していません。バックエンドを更新してください。",- "catalog_degraded": "一部の bundled release を隔離しました",- "catalog_degraded_description": "bundled source の検証に失敗しました。正常な署名済み release は引き続き利用できます。",+ "load_failed_description": "再試行してください。インストール済みの Plugin には影響しません。","read_only": "読み取り専用",- "read_only_description": "ワークスペースの owner と admin が Plugin とバインドを変更できます。",- "empty": "利用可能な bundled Plugins はありません。",- "official": "公式",- "private": "プライベート",- "unverified": "未検証",- "signed": "署名検証済み",- "signature_unverified": "署名未検証",- "incompatible": "互換性のない release",- "incompatible_description": "新しい Host API またはデーモン機能が必要なため、有効化できません。",- "install_disabled_hint": "インストール後は無効です。ワークスペースまたはエージェントのスコープを選択してください。",- "install": "インストール",- "installed_disabled": "Plugin を無効のままインストールしました",- "active_version": "有効なバージョン:",- "health": "状態:",- "bindings": "有効なスコープ",- "unknown_agent": "不明なエージェント",- "unknown_member": "不明なメンバー",- "workspace_scope": "ワークスペース",- "agent_scope": "エージェント",- "binding_disabled": "Plugin バインドを無効にしました",- "disable_binding": "無効化",- "no_bindings": "有効なスコープはありません。新しい作業にはこの Plugin が追加されません。",- "enable_scope": "スコープを有効化",- "enabled": "Plugin スコープを有効にしました",- "disable_workspace": "ワークスペースで無効化",- "disabled": "新しい作業で Plugin を無効にしました",- "upgraded": "Plugin をアップグレードしました",- "rolled_back": "Plugin をロールバックしました",- "source": "ソースとアップロード者",- "private_upload": "ワークスペースへのプライベートアップロード",- "uploaded_by": "アップロード者",- "uninstall": "アンインストール",- "uninstalled": "今後の実行から Plugin をアンインストールしました",- "upgrade_to": "v{{version}} にアップグレード",- "rollback_to": "v{{version}} にロールバック",+ "read_only_description": "ワークスペースの owner と admin が Plugin をインストール、設定、削除できます。",+ "empty": "インストール済みの Plugin はありません。","action_failed": "Plugin 操作に失敗しました",- "none": "なし",+ "enabled": "Plugin を有効にしました",+ "disabled": "Plugin を無効にしました",+ "enabled_label": "Plugin を有効化",+ "uninstall": "アンインストール",+ "uninstalled": "Plugin をアンインストールし、保存データとシークレットも削除しました",+ "granted_scopes": "許可したアクセス",+ "contributes": "提供する機能",+ "version": "v{{version}}",+ "byline": "{{author}} · v{{version}}",+ "source": "ソース","states": {- "disabled": "無効",- "activating": "有効化中",- "healthy": "正常",- "degraded": "低下",- "failed": "失敗"+ "disabled": "無効"},- "review": {- "contributes": "提供内容",- "permissions": "要求する capability",- "compatibility": "互換性",- "host_api": "Host API",- "publisher": "発行元と署名 ID",- "none": "なし"+ "install": {+ "title": "Plugin をインストール",+ "description": "Plugin manifest の URL を貼り付けてください。インストール前に要求される権限を確認できます。",+ "placeholder": "https://example.com/multica.plugin.json",+ "review": "権限を確認"},- "remote_mcp": {- "title": "Remote MCP 接続",- "endpoint": "HTTPS エンドポイント",- "endpoint_placeholder": "https://mcp.example.com/mcp",- "auth": "認証",- "auth_types": {- "none": "なし",- "oauth": "OAuth(推奨)",- "bearer": "Bearer トークン",- "header": "カスタムヘッダー"- },- "header_name": "ヘッダー名",- "credential": "認証情報(暗号化して保存)",- "connect": "接続",- "connected": "接続済み",- "ready_to_connect": "接続できます",- "complete_before_enabling": "スコープを有効にする前に MCP に接続し、少なくとも 1 つのツールを承認してください。",- "advanced": "詳細設定",- "oauth_scope": "OAuth スコープ(空欄は自動)",- "oauth_client_id": "OAuth クライアント ID(空欄は自動)",- "oauth_client_secret": "OAuth クライアントシークレット",- "oauth_authorization_endpoint": "認可エンドポイントの上書き",- "oauth_token_endpoint": "トークンエンドポイントの上書き",- "oauth_token_auth_method": "トークンエンドポイント認証",- "oauth_token_auth_methods": {- "none": "パブリッククライアント(PKCE)",- "client_secret_basic": "クライアントシークレット(HTTP Basic)",- "client_secret_post": "クライアントシークレット(リクエスト本文)"- },- "public_config": "公開設定(JSON オブジェクト)",- "invalid_public_config": "公開設定には有効な JSON オブジェクトを指定してください",- "failure_policy": "障害ポリシー",- "failure_policies": {- "required": "必須 — タスクを停止",- "optional": "任意 — ツールなしで続行"- },- "configure_and_discover": "保存してツールを検出",- "test": "接続をテスト",- "approve": "選択したツールを承認",- "revoke": "認証情報を失効",- "credential_states": {- "configured": "認証情報を設定済み",- "revoked": "認証情報を失効済み",- "missing": "認証情報がありません",- "not_required": "認証情報は不要"- },- "reviewed": "ツールを承認済み",- "pending_review": "承認が必要",- "approved_tools": "承認済みツール",- "no_tools": "サーバーからツールが通知されませんでした。",- "discovery": "検出されたツール — アクセスを明示的に確認してください",- "read": "読み取り",- "write": "書き込み",- "configured_success": "接続を保存しました。検出されたツールを確認してください",- "oauth_connected_success": "OAuth 接続が完了しました。検出されたツールを確認してください",- "oauth_connect_failed": "OAuth 接続を完了できませんでした。もう一度お試しください。",- "test_success": "接続テストに成功しました",- "approved_success": "ツールへのアクセスを承認しました",- "revoked_success": "認証情報を失効し、Plugin を無効にしました"+ "installed": {+ "title": "インストール済み"+ },+ "consent": {+ "title": "この Plugin は次のアクセスを要求しています",+ "description": "Multica はサーバー上で Plugin のコードを実行しません。Plugin はこれらの権限の範囲内でのみ動作し、利用者本人の権限を超えることはありません。",+ "cancel": "キャンセル",+ "confirm": "許可してインストール",+ "confirm_upgrade": "許可してアップグレード",+ "installed": "Plugin をインストールしました",+ "upgrade_from": " · v{{version}} からアップグレード",+ "new_scope": "新規"+ },+ "config": {+ "title": "設定",+ "save": "保存",+ "saved": "設定を保存しました",+ "secret_set": "保存済み — 新しい値を入力すると置き換わります"+ },+ "scopes": {+ "issues_read": "issue を読み取る",+ "issues_write": "issue を作成・編集する",+ "comments_read": "コメントを読み取る",+ "comments_write": "コメントを投稿する",+ "tasks_read": "agent task を読み取る",+ "tasks_write": "agent task を開始・更新する",+ "agents_read": "agent 一覧を読み取る",+ "members_read": "メンバー一覧を読み取る",+ "storage_user": "メンバーごとにデータを保存する",+ "storage_workspace": "ワークスペース共有のデータを保存する",+ "net": "{{domain}} にデータを送信する",+ "unknown": "認識できない権限です — インストールしないでください"}},"properties": {diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex f3c309eb3e..7fdaec28e7 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -265,126 +265,65 @@},"plugins": {"title": "Plugins",- "description": "Multica가 제공하는 서명된 기능을 검토, 설치, 범위 지정 및 관리합니다.",+ "description": "URL로 Plugin을 설치하고 각 Plugin이 무엇에 접근할 수 있는지 확인합니다.","loading": "Plugins 불러오는 중",- "load_failed": "Plugins를 불러오지 못했습니다",- "load_failed_description": "다시 시도하세요. 활성 Plugins와 고정된 작업에는 영향이 없습니다.",- "backend_unavailable": "Plugin 관리를 사용할 수 없습니다",- "backend_unavailable_description": "이 서버는 bundled Plugin catalog를 지원하지 않습니다. 백엔드를 업데이트하세요.",- "catalog_degraded": "일부 bundled release가 격리되었습니다",- "catalog_degraded_description": "bundled source 검증에 실패했습니다. 정상적인 서명 release는 계속 사용할 수 있습니다.",+ "load_failed": "Plugins를 불러올 수 없습니다",+ "load_failed_description": "다시 시도하세요. 설치된 Plugin에는 영향이 없습니다.","read_only": "읽기 전용",- "read_only_description": "워크스페이스 owner와 admin이 Plugin 및 바인딩을 변경할 수 있습니다.",- "empty": "사용 가능한 bundled Plugins가 없습니다.",- "official": "공식",- "private": "비공개",- "unverified": "확인되지 않음",- "signed": "서명 확인됨",- "signature_unverified": "서명 미확인",- "incompatible": "호환되지 않는 release",- "incompatible_description": "최신 Host API 또는 데몬 기능이 필요하여 활성화할 수 없습니다.",- "install_disabled_hint": "설치 후 기본적으로 비활성화됩니다. 워크스페이스 또는 에이전트 범위를 선택하세요.",- "install": "설치",- "installed_disabled": "Plugin을 비활성 상태로 설치했습니다",- "active_version": "활성 버전:",- "health": "상태:",- "bindings": "활성 범위",- "unknown_agent": "알 수 없는 에이전트",- "unknown_member": "알 수 없는 멤버",- "workspace_scope": "워크스페이스",- "agent_scope": "에이전트",- "binding_disabled": "Plugin 바인딩을 비활성화했습니다",- "disable_binding": "비활성화",- "no_bindings": "활성 범위가 없습니다. 새 작업에 이 Plugin이 추가되지 않습니다.",- "enable_scope": "범위 활성화",- "enabled": "Plugin 범위를 활성화했습니다",- "disable_workspace": "워크스페이스 비활성화",- "disabled": "새 작업에서 Plugin을 비활성화했습니다",- "upgraded": "Plugin을 업그레이드했습니다",- "rolled_back": "Plugin을 롤백했습니다",- "source": "소스 및 업로더",- "private_upload": "워크스페이스 비공개 업로드",- "uploaded_by": "업로드한 사용자",- "uninstall": "제거",- "uninstalled": "향후 실행에서 Plugin을 제거했습니다",- "upgrade_to": "v{{version}}로 업그레이드",- "rollback_to": "v{{version}}로 롤백",+ "read_only_description": "워크스페이스 owner와 admin이 Plugin을 설치, 설정, 제거할 수 있습니다.",+ "empty": "설치된 Plugin이 없습니다.","action_failed": "Plugin 작업에 실패했습니다",- "none": "없음",+ "enabled": "Plugin을 활성화했습니다",+ "disabled": "Plugin을 비활성화했습니다",+ "enabled_label": "Plugin 활성화",+ "uninstall": "제거",+ "uninstalled": "Plugin을 제거했고 저장된 데이터와 시크릿도 함께 삭제했습니다",+ "granted_scopes": "허용한 접근 권한",+ "contributes": "제공 기능",+ "version": "v{{version}}",+ "byline": "{{author}} · v{{version}}",+ "source": "출처","states": {- "disabled": "비활성",- "activating": "활성화 중",- "healthy": "정상",- "degraded": "성능 저하",- "failed": "실패"+ "disabled": "비활성"},- "review": {- "contributes": "제공 항목",- "permissions": "요청 capability",- "compatibility": "호환성",- "host_api": "Host API",- "publisher": "게시자 및 서명 ID",- "none": "없음"+ "install": {+ "title": "Plugin 설치",+ "description": "Plugin manifest의 URL을 붙여넣으세요. 설치 전에 요청하는 권한을 확인할 수 있습니다.",+ "placeholder": "https://example.com/multica.plugin.json",+ "review": "권한 확인"},- "remote_mcp": {- "title": "Remote MCP 연결",- "endpoint": "HTTPS 엔드포인트",- "endpoint_placeholder": "https://mcp.example.com/mcp",- "auth": "인증",- "auth_types": {- "none": "없음",- "oauth": "OAuth(권장)",- "bearer": "Bearer 토큰",- "header": "사용자 지정 헤더"- },- "header_name": "헤더 이름",- "credential": "인증 정보(암호화 저장)",- "connect": "연결",- "connected": "연결됨",- "ready_to_connect": "연결할 수 있음",- "complete_before_enabling": "범위를 활성화하기 전에 MCP를 연결하고 도구를 하나 이상 승인하세요.",- "advanced": "고급 구성",- "oauth_scope": "OAuth 범위(비워두면 자동)",- "oauth_client_id": "OAuth 클라이언트 ID(비워두면 자동)",- "oauth_client_secret": "OAuth 클라이언트 보안 비밀",- "oauth_authorization_endpoint": "인증 엔드포인트 재정의",- "oauth_token_endpoint": "토큰 엔드포인트 재정의",- "oauth_token_auth_method": "토큰 엔드포인트 인증",- "oauth_token_auth_methods": {- "none": "공개 클라이언트(PKCE)",- "client_secret_basic": "클라이언트 시크릿(HTTP Basic)",- "client_secret_post": "클라이언트 시크릿(요청 본문)"- },- "public_config": "공개 설정(JSON 객체)",- "invalid_public_config": "공개 설정은 유효한 JSON 객체여야 합니다",- "failure_policy": "실패 정책",- "failure_policies": {- "required": "필수 — 태스크 중지",- "optional": "선택 — 도구 없이 계속"- },- "configure_and_discover": "저장하고 도구 검색",- "test": "연결 테스트",- "approve": "선택한 도구 승인",- "revoke": "인증 정보 폐기",- "credential_states": {- "configured": "인증 정보 설정됨",- "revoked": "인증 정보 폐기됨",- "missing": "인증 정보 없음",- "not_required": "인증 정보 필요 없음"- },- "reviewed": "도구 승인됨",- "pending_review": "승인 필요",- "approved_tools": "승인된 도구",- "no_tools": "서버에서 알린 도구가 없습니다.",- "discovery": "검색된 도구 — 접근 권한을 명시적으로 검토하세요",- "read": "읽기",- "write": "쓰기",- "configured_success": "연결을 저장했습니다. 검색된 도구를 검토하세요",- "oauth_connected_success": "OAuth 연결이 완료되었습니다. 검색된 도구를 검토하세요",- "oauth_connect_failed": "OAuth 연결을 완료하지 못했습니다. 다시 시도하세요.",- "test_success": "연결 테스트에 성공했습니다",- "approved_success": "도구 접근을 승인했습니다",- "revoked_success": "인증 정보를 폐기하고 Plugin을 비활성화했습니다"+ "installed": {+ "title": "설치됨"+ },+ "consent": {+ "title": "이 Plugin이 요청하는 접근 권한",+ "description": "Multica는 서버에서 Plugin 코드를 실행하지 않습니다. Plugin은 이 권한 범위 안에서만 동작하며, 사용자 본인의 권한을 넘어설 수 없습니다.",+ "cancel": "취소",+ "confirm": "허용하고 설치",+ "confirm_upgrade": "허용하고 업그레이드",+ "installed": "Plugin을 설치했습니다",+ "upgrade_from": " · v{{version}}에서 업그레이드",+ "new_scope": "신규"+ },+ "config": {+ "title": "설정",+ "save": "저장",+ "saved": "설정을 저장했습니다",+ "secret_set": "저장됨 — 새 값을 입력하면 교체됩니다"+ },+ "scopes": {+ "issues_read": "issue 읽기",+ "issues_write": "issue 생성 및 수정",+ "comments_read": "댓글 읽기",+ "comments_write": "댓글 작성",+ "tasks_read": "agent task 읽기",+ "tasks_write": "agent task 시작 및 업데이트",+ "agents_read": "agent 목록 읽기",+ "members_read": "멤버 목록 읽기",+ "storage_user": "멤버별로 데이터 저장",+ "storage_workspace": "워크스페이스 공유 데이터 저장",+ "net": "{{domain}}(으)로 데이터 전송",+ "unknown": "알 수 없는 권한 — 설치하지 마세요"}},"properties": {diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex e7f51980d4..c87623ece8 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -265,126 +265,65 @@},"plugins": {"title": "Plugins",- "description": "审查、安装、设置作用范围并管理由 Multica 交付的签名能力。",+ "description": "通过 URL 安装 Plugin,并逐条查看它能访问什么。","loading": "正在加载 Plugins","load_failed": "无法加载 Plugins",- "load_failed_description": "请重试。已启用的 Plugins 和已固定的 task 不受影响。",- "backend_unavailable": "Plugin 管理不可用",- "backend_unavailable_description": "当前服务端版本不支持 bundled Plugin catalog。请更新后端后再在此管理。",- "catalog_degraded": "部分 bundled release 已隔离",- "catalog_degraded_description": "有 bundled source 未通过校验。其余已签名的健康 release 仍可使用。",+ "load_failed_description": "请重试。已安装的 Plugin 不受影响。","read_only": "只读访问",- "read_only_description": "工作区 owner 和 admin 可以安装 Plugin 或更改绑定。",- "empty": "没有可用的 bundled Plugins。",- "official": "官方",- "private": "私有",- "unverified": "未验证",- "signed": "签名已验证",- "signature_unverified": "签名未验证",- "incompatible": "Release 不兼容",- "incompatible_description": "此 release 需要更新的 Host API 或守护进程能力,无法激活。",- "install_disabled_hint": "安装后默认停用。安装完成后再选择工作区或智能体作用范围。",- "install": "安装",- "installed_disabled": "Plugin 已安装并保持停用",- "active_version": "当前版本:",- "health": "健康状态:",- "bindings": "已启用的作用范围",- "unknown_agent": "未知智能体",- "unknown_member": "未知成员",- "workspace_scope": "工作区",- "agent_scope": "智能体",- "binding_disabled": "Plugin 绑定已停用",- "disable_binding": "停用",- "no_bindings": "没有已启用的作用范围。新 task 不会获得此 Plugin。",- "enable_scope": "启用此范围",- "enabled": "Plugin 作用范围已启用",- "disable_workspace": "停用工作区",- "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}}",+ "read_only_description": "工作区 owner 和 admin 可以安装、配置和移除 Plugin。",+ "empty": "还没有安装任何 Plugin。","action_failed": "Plugin 操作失败",- "none": "无",+ "enabled": "Plugin 已启用",+ "disabled": "Plugin 已停用",+ "enabled_label": "启用 Plugin",+ "uninstall": "卸载",+ "uninstalled": "Plugin 已卸载,其存储数据与密钥一并删除",+ "granted_scopes": "已授予的访问权限",+ "contributes": "提供的能力",+ "version": "v{{version}}",+ "byline": "{{author}} · v{{version}}",+ "source": "来源","states": {- "disabled": "已停用",- "activating": "正在激活",- "healthy": "健康",- "degraded": "已降级",- "failed": "失败"+ "disabled": "已停用"},- "review": {- "contributes": "贡献内容",- "permissions": "请求的 capability",- "compatibility": "兼容性",- "host_api": "Host API",- "publisher": "发布者与签名身份",- "none": "无"+ "install": {+ "title": "安装 Plugin",+ "description": "粘贴 Plugin manifest 的 URL。安装前你会先看到它请求的全部权限。",+ "placeholder": "https://example.com/multica.plugin.json",+ "review": "查看权限"},- "remote_mcp": {- "title": "Remote MCP 连接",- "endpoint": "HTTPS 端点",- "endpoint_placeholder": "https://mcp.example.com/mcp",- "auth": "身份验证",- "auth_types": {- "none": "无",- "oauth": "OAuth(推荐)",- "bearer": "Bearer 令牌",- "header": "自定义请求头"- },- "header_name": "请求头名称",- "credential": "凭证(加密存储)",- "connect": "连接",- "connected": "已连接",- "ready_to_connect": "可以连接",- "complete_before_enabling": "请先连接 MCP 并批准至少一个工具,再启用作用范围。",- "advanced": "高级配置",- "oauth_scope": "OAuth scopes(留空自动获取)",- "oauth_client_id": "OAuth client ID(留空自动注册)",- "oauth_client_secret": "OAuth client secret",- "oauth_authorization_endpoint": "Authorization endpoint 覆盖值",- "oauth_token_endpoint": "Token endpoint 覆盖值",- "oauth_token_auth_method": "Token endpoint 认证方式",- "oauth_token_auth_methods": {- "none": "公开客户端(PKCE)",- "client_secret_basic": "Client secret(HTTP Basic)",- "client_secret_post": "Client secret(请求体)"- },- "public_config": "公开配置(JSON 对象)",- "invalid_public_config": "公开配置必须是有效的 JSON 对象",- "failure_policy": "失败策略",- "failure_policies": {- "required": "必需 — 停止任务",- "optional": "可选 — 不使用工具并继续"- },- "configure_and_discover": "保存并发现工具",- "test": "测试连接",- "approve": "批准所选工具",- "revoke": "吊销凭证",- "credential_states": {- "configured": "已配置凭证",- "revoked": "凭证已吊销",- "missing": "缺少凭证",- "not_required": "无需凭证"- },- "reviewed": "工具已批准",- "pending_review": "需要批准",- "approved_tools": "已批准的工具",- "no_tools": "服务器未公布任何工具。",- "discovery": "已发现的工具 — 请明确审核访问权限",- "read": "读取",- "write": "写入",- "configured_success": "连接已保存;请审核已发现的工具",- "oauth_connected_success": "OAuth 连接已完成;请审核已发现的工具",- "oauth_connect_failed": "OAuth 连接未能完成,请重试。",- "test_success": "连接测试成功",- "approved_success": "工具访问权限已批准",- "revoked_success": "凭证已吊销,Plugin 已禁用"+ "installed": {+ "title": "已安装"+ },+ "consent": {+ "title": "该 Plugin 请求以下访问权限",+ "description": "Multica 从不在服务器上运行 Plugin 代码。Plugin 只能做这些权限允许的事,且永远不会超过使用者本人的权限。",+ "cancel": "取消",+ "confirm": "授权并安装",+ "confirm_upgrade": "授权并升级",+ "installed": "Plugin 已安装",+ "upgrade_from": " · 从 v{{version}} 升级",+ "new_scope": "新增"+ },+ "config": {+ "title": "配置",+ "save": "保存",+ "saved": "配置已保存",+ "secret_set": "已保存 — 输入新值可替换"+ },+ "scopes": {+ "issues_read": "读取 issue",+ "issues_write": "创建和修改 issue",+ "comments_read": "读取评论",+ "comments_write": "发表评论",+ "tasks_read": "读取 agent task",+ "tasks_write": "启动和更新 agent task",+ "agents_read": "读取 agent 列表",+ "members_read": "读取成员列表",+ "storage_user": "为每位成员单独存储数据",+ "storage_workspace": "存储工作区共享数据",+ "net": "向 {{domain}} 发送数据",+ "unknown": "无法识别的权限 — 请勿安装"}},"properties": {diff --git a/packages/views/settings/components/plugins-tab.test.tsx b/packages/views/settings/components/plugins-tab.test.tsxindex 704d98de59..139ce90d9e 100644--- a/packages/views/settings/components/plugins-tab.test.tsx+++ b/packages/views/settings/components/plugins-tab.test.tsx@@ -6,90 +6,28 @@ import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../locales/en/common.json";import enSettings from "../../locales/en/settings.json";+const mockPreview = vi.hoisted(() => vi.fn());const mockInstall = vi.hoisted(() => vi.fn());+const mockConfigure = 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 mockConfigureRemoteMCP = vi.hoisted(() => vi.fn());-const mockTestRemoteMCP = vi.hoisted(() => vi.fn());-const mockApproveRemoteMCP = vi.hoisted(() => vi.fn());-const mockRevokeRemoteMCP = vi.hoisted(() => vi.fn());-const mockStartRemoteMCPOAuth = vi.hoisted(() => vi.fn());-const mockOpenExternal = vi.hoisted(() => vi.fn());-const mockRefetch = vi.hoisted(() => vi.fn());const data = vi.hoisted(() => ({- catalog: {- supported: true,- diagnostics: [],- releases: [{- plugin_key: "ai.multica.software-delivery",- name: "Software Delivery",- description: "Official Multica software-delivery workflow skills.",- version: "1.1.0",- publisher: "multica",- publisher_type: "official",- trust_tier: "official",- source_kind: "bundled",- source_ref: "bundled://ai.multica.software-delivery/1.1.0",- requested_capabilities: ["agent.skill.contribute"],- host_api: ">=1.0.0 <2.0.0",- required_daemon_features: ["execution-manifest-v1", "agent-skill-v1"],- signature_key_id: "multica-plugin-release-2026-01",- signature_verified: true,- manifest_digest: "sha256:manifest",- archive_digest: "sha256:archive",- artifact_digest: "sha256:artifact",- compatible: true,- contributions: [{- key: "review-readiness",- type: "agent.skill.v1",- name: "review-readiness",- description: "Verify that a software change is ready for review and handoff.",- entry_path: "skills/review-readiness/SKILL.md",- entry_digest: "sha256:entry",- }],- }],- },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",}));vi.mock("@tanstack/react-query", () => ({- useQuery: (options: { queryKey?: readonly string[] }) => {- const key = options.queryKey?.join(":") ?? "";- if (key.includes("catalog")) return { data: data.catalog, isPending: false, isError: false, refetch: mockRefetch };- if (key.includes("installed")) return { data: data.installed, isPending: false, isError: false, refetch: mockRefetch };- if (key.includes("members")) return { data: data.members, isPending: false, isError: false, refetch: mockRefetch };- return { data: data.agents, isPending: false, isError: false, refetch: mockRefetch };- },+ useQuery: () => ({ data: data.installed, isLoading: false, isError: false }),}));vi.mock("@multica/core/plugins", () => ({- comparePluginVersions: (left: string, right: string) => left.localeCompare(right),- pluginCatalogOptions: () => ({ queryKey: ["plugins", "catalog"] }),pluginInstallationsOptions: () => ({ queryKey: ["plugins", "installed"] }),+ usePreviewPlugin: () => ({ mutateAsync: mockPreview, isPending: false }),useInstallPlugin: () => ({ mutateAsync: mockInstall, isPending: false }),+ useConfigurePlugin: () => ({ mutateAsync: mockConfigure, isPending: false }),useSetPluginEnabled: () => ({ mutateAsync: mockSetEnabled, isPending: false }),- useUpgradePlugin: () => ({ mutateAsync: mockUpgrade, isPending: false }),- useRollbackPlugin: () => ({ mutateAsync: mockRollback, isPending: false }),useUninstallPlugin: () => ({ mutateAsync: mockUninstall, isPending: false }),- useConfigurePluginRemoteMCP: () => ({ mutateAsync: mockConfigureRemoteMCP, isPending: false }),- useTestPluginRemoteMCP: () => ({ mutateAsync: mockTestRemoteMCP, isPending: false }),- useApprovePluginRemoteMCPTools: () => ({ mutateAsync: mockApproveRemoteMCP, isPending: false }),- useRevokePluginRemoteMCPCredential: () => ({ mutateAsync: mockRevokeRemoteMCP, isPending: false }),- useStartPluginRemoteMCPOAuth: () => ({ mutateAsync: mockStartRemoteMCPOAuth, isPending: false }),-}));--vi.mock("../../platform/open-external", () => ({ openExternal: mockOpenExternal }));-vi.mock("../../platform/local-directory", () => ({ isDesktopShell: () => true }));--vi.mock("@multica/core/workspace/queries", () => ({- agentListOptions: () => ({ queryKey: ["agents"] }),- memberListOptions: () => ({ queryKey: ["members"] }),}));vi.mock("@multica/core/paths", () => ({@@ -110,194 +48,134 @@ function Wrapper({ children }: { children: ReactNode }) {return <I18nProvider locale="en" resources={TEST_RESOURCES}>{children}</I18nProvider>;}+const INSTALLATION = {+ id: "installation-1",+ plugin_key: "com.example.hello",+ name: "Hello Panel",+ description: "A greeting panel.",+ version: "1.0.0",+ source_url: "https://example.com/multica.plugin.json",+ enabled: true,+ granted_scopes: ["issues:read", "comments:write", "net:example.com"],+ config_schema: [+ { key: "repo", type: "string", label: "Repo", required: true, options: [] },+ { key: "token", type: "secret", label: "Token", required: true, options: [] },+ ],+ config: { repo: "multica-ai/multica" },+ configured_secrets: ["token"],+ surfaces: [{ key: "hello", type: "issue_panel", name: "Hello", entry: "ui/main.js", platforms: [] }],+ hooks: [],+ resources: [],+ created_at: "2026-08-18T00:00:00Z",+ updated_at: "2026-08-18T00:00:00Z",+};++const PREVIEW = {+ manifest: {+ key: "com.example.hello",+ name: "Hello Panel",+ description: "A greeting panel.",+ version: "1.0.0",+ author: { name: "example" },+ },+ scopes: ["issues:read", "comments:write", "net:example.com"],+ config_schema: [],+ installed: false,+ added_scopes: [],+};+describe("PluginsTab", () => {beforeEach(() => {vi.clearAllMocks();- window.history.replaceState({}, "", "/");data.role = "owner";- data.catalog.releases[0]!.compatible = true;- data.catalog.releases[0]!.signature_verified = true;data.installed.plugins = [];- mockInstall.mockResolvedValue({});- mockSetEnabled.mockResolvedValue({});- mockUninstall.mockResolvedValue({});- mockStartRemoteMCPOAuth.mockResolvedValue({ authorization_url: "https://auth.example.test/authorize" });+ mockPreview.mockResolvedValue(PREVIEW);+ mockInstall.mockResolvedValue(INSTALLATION);+ mockConfigure.mockResolvedValue(INSTALLATION);+ mockSetEnabled.mockResolvedValue(INSTALLATION);+ mockUninstall.mockResolvedValue(undefined);});- it("renders the install review and keeps installation disabled by default", async () => {+ it("shows the scope consent screen before anything is installed", async () => {const user = userEvent.setup();render(<PluginsTab />, { wrapper: Wrapper });- expect(screen.getByText("review-readiness")).toBeInTheDocument();- expect(screen.getByText("agent.skill.contribute")).toBeInTheDocument();- expect(screen.getByText("Signature verified")).toBeInTheDocument();- expect(screen.getByText(/Installation is disabled by default/)).toBeInTheDocument();-- await user.click(screen.getByRole("button", { name: "Install" }));+ await user.type(+ screen.getByPlaceholderText("https://example.com/multica.plugin.json"),+ "https://example.com/multica.plugin.json",+ );+ await user.click(screen.getByRole("button", { name: "Review" }));++ // The raw scope strings are the trust model, so they must be on screen+ // verbatim alongside their plain-language meaning.+ await screen.findByText("This Plugin is asking for the following access");+ expect(screen.getByText("issues:read")).toBeInTheDocument();+ expect(screen.getByText("comments:write")).toBeInTheDocument();+ expect(screen.getByText("net:example.com")).toBeInTheDocument();+ expect(screen.getByText("Send data to example.com")).toBeInTheDocument();+ expect(mockInstall).not.toHaveBeenCalled();++ await user.click(screen.getByRole("button", { name: "Grant and install" }));await waitFor(() => expect(mockInstall).toHaveBeenCalledWith({- plugin_key: "ai.multica.software-delivery",- version: "1.1.0",+ source_url: "https://example.com/multica.plugin.json",+ granted_scopes: ["issues:read", "comments:write", "net:example.com"],}));});- it("enables an installed Plugin for the workspace through a generic binding", async () => {+ it("renders the configuration form from the manifest and never shows a stored secret", async () => {+ data.installed.plugins = [INSTALLATION];const user = userEvent.setup();- data.installed.plugins = [{- id: "installation-1",- plugin_key: "ai.multica.software-delivery",- display_name: "Software Delivery",- desired_version: "1.1.0",- active_version: "1.1.0",- enabled: false,- desired_generation: 1,- active_generation: 1,- lifecycle_status: "installed",- contributions: ["review-readiness"],- bindings: [],- remote_mcp: [],- }];render(<PluginsTab />, { wrapper: Wrapper });- expect(screen.getByText("Disabled")).toBeInTheDocument();- await user.click(screen.getByRole("button", { name: "Enable scope" }));- await waitFor(() => expect(mockSetEnabled).toHaveBeenCalledWith({- installationId: "installation-1",- enabled: true,- binding: { scope_type: "workspace", scope_id: "workspace-1" },- }));- });+ const repo = screen.getByDisplayValue("multica-ai/multica");+ expect(repo).toBeInTheDocument();- it("fails closed when compatibility or signature evidence is absent", () => {- data.catalog.releases[0]!.compatible = false;- data.catalog.releases[0]!.signature_verified = false;- render(<PluginsTab />, { wrapper: Wrapper });+ const secret = screen.getByPlaceholderText("Saved — enter a new value to replace it");+ expect(secret).toHaveAttribute("type", "password");+ expect(secret).toHaveValue("");- expect(screen.getByText("Incompatible release")).toBeInTheDocument();- expect(screen.getByRole("button", { name: "Install" })).toBeDisabled();- });-- it("keeps the catalog visible but actions read-only for members", () => {- data.role = "member";- render(<PluginsTab />, { wrapper: Wrapper });+ // Saving without retyping the secret must not send an empty value: that+ // would clear a stored secret as a side effect of an unrelated edit.+ await user.click(screen.getByRole("button", { name: "Save" }));+ await waitFor(() => expect(mockConfigure).toHaveBeenCalledWith({+ installationId: "installation-1",+ values: { repo: "multica-ai/multica" },+ }));- expect(screen.getByText("Read-only access")).toBeInTheDocument();- expect(screen.getByText("review-readiness")).toBeInTheDocument();- expect(screen.getByRole("button", { name: "Install" })).toBeDisabled();+ mockConfigure.mockClear();+ await user.type(secret, "new-token");+ await user.click(screen.getByRole("button", { name: "Save" }));+ await waitFor(() => expect(mockConfigure).toHaveBeenCalledWith({+ installationId: "installation-1",+ values: { repo: "multica-ai/multica", token: "new-token" },+ }));});- it("shows a private unverified installation outside the official catalog", async () => {+ it("disables and uninstalls an installed Plugin", async () => {+ data.installed.plugins = [INSTALLATION];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: [],- remote_mcp: [],- }];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"));- });-- it("opens OAuth in the platform browser and restores saved advanced configuration", async () => {- const user = userEvent.setup();- data.installed.plugins = [{- id: "private-remote-1",- plugin_key: "dev.acme.search",- display_name: "Search",- desired_version: "0.1.0",- active_version: "0.1.0",+ await user.click(screen.getByRole("switch", { name: "Enable Plugin" }));+ await waitFor(() => expect(mockSetEnabled).toHaveBeenCalledWith({+ installationId: "installation-1",enabled: false,- desired_generation: 1,- active_generation: 1,- lifecycle_status: "installed",- publisher: "acme.internal",- publisher_type: "private_dev",- trust_tier: "private_dev",- source_kind: "private_dev",- source_ref: "private://sha256:search",- signature_verified: false,- requested_capabilities: ["tool.remote-mcp.connect"],- available_versions: ["0.1.0"],- contributions: ["search"],- contribution_details: [],- bindings: [],- remote_mcp: [{- contribution_key: "search",- default_endpoint: "https://default.example.test/mcp",- preferred_auth: "oauth",- supported_auth: ["oauth"],- endpoint: "https://saved.example.test/mcp",- auth_type: "oauth",- public_config: { locale: "en" },- failure_policy: "optional",- credential_state: "missing",- approved_tools: [],- discovered_tools: [],- reviewed: false,- ready: false,- }],- }];- render(<PluginsTab />, { wrapper: Wrapper });-- await user.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => expect(mockStartRemoteMCPOAuth).toHaveBeenCalledWith(expect.objectContaining({- installationId: "private-remote-1",- contributionKey: "search",- request: expect.objectContaining({- endpoint: "https://saved.example.test/mcp",- public_config: { locale: "en" },- failure_policy: "optional",- }),- })));- expect(mockOpenExternal).toHaveBeenCalledWith("https://auth.example.test/authorize");+ }));- await user.click(screen.getByText("Advanced configuration"));- expect(screen.getByLabelText("HTTPS endpoint")).toHaveValue("https://saved.example.test/mcp");- expect(screen.getByLabelText("Public configuration (JSON object)")).toHaveValue('{\n "locale": "en"\n}');+ await user.click(screen.getByRole("button", { name: "Uninstall" }));+ await waitFor(() => expect(mockUninstall).toHaveBeenCalledWith("installation-1"));});- it("consumes a successful OAuth callback and refreshes installation state", async () => {- window.history.replaceState({}, "", "/settings?tab=plugins&remote_mcp_connected=1#plugins");-+ it("blocks management for a non-admin member", () => {+ data.role = "member";+ data.installed.plugins = [INSTALLATION];render(<PluginsTab />, { wrapper: Wrapper });- await waitFor(() => expect(mockRefetch).toHaveBeenCalled());- expect(window.location.search).toBe("?tab=plugins");- expect(window.location.hash).toBe("#plugins");+ expect(screen.getByText("Read-only access")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Review" })).not.toBeInTheDocument();+ // Base UI's Switch marks the disabled state with aria-disabled rather than+ // the native attribute, so assert what a screen reader actually sees.+ expect(screen.getByRole("switch", { name: "Enable Plugin" })).toHaveAttribute("aria-disabled", "true");+ expect(screen.getByRole("button", { name: "Uninstall" })).toBeDisabled();});});diff --git a/packages/views/settings/components/plugins-tab.tsx b/packages/views/settings/components/plugins-tab.tsxindex 02ef690775..aa23d4a5a4 100644--- a/packages/views/settings/components/plugins-tab.tsx+++ b/packages/views/settings/components/plugins-tab.tsx@@ -1,37 +1,23 @@"use client";-import { useEffect, useMemo, useState } from "react";+import { useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";-import { AlertCircle, CheckCircle2, Loader2, PackageCheck, ShieldCheck, Trash2 } from "lucide-react";+import { AlertCircle, Loader2, Trash2 } from "lucide-react";import { toast } from "sonner";-import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";import { useCurrentMember } from "@multica/core/permissions";import {- comparePluginVersions,- pluginCatalogOptions,pluginInstallationsOptions,- useApprovePluginRemoteMCPTools,- useConfigurePluginRemoteMCP,+ useConfigurePlugin,useInstallPlugin,- useRevokePluginRemoteMCPCredential,- useRollbackPlugin,+ usePreviewPlugin,useSetPluginEnabled,- useTestPluginRemoteMCP,- useStartPluginRemoteMCPOAuth,useUninstallPlugin,- useUpgradePlugin,} from "@multica/core/plugins";import { useCurrentWorkspace } from "@multica/core/paths";-import type {- PluginCatalogRelease,- PluginInstallation,- PluginRemoteMCPConfig,- RemoteMCPDiscoveryResponse,-} from "@multica/core/types";+import type { PluginConfigField, PluginInstallation, PluginPreview } from "@multica/core/types";import { Alert, AlertDescription, AlertTitle } from "@multica/ui/components/ui/alert";import { Badge } from "@multica/ui/components/ui/badge";import { Button } from "@multica/ui/components/ui/button";-import { Checkbox } from "@multica/ui/components/ui/checkbox";import { Input } from "@multica/ui/components/ui/input";import {Select,@@ -41,968 +27,438 @@ import {SelectValue,} from "@multica/ui/components/ui/select";import { Skeleton } from "@multica/ui/components/ui/skeleton";-import { Textarea } from "@multica/ui/components/ui/textarea";+import { Switch } from "@multica/ui/components/ui/switch";import { useT } from "../../i18n";-import { isDesktopShell } from "../../platform/local-directory";-import { openExternal } from "../../platform/open-external";import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";-type BindingScope = "workspace" | "agent";+/**+ * The scope list is the entire trust model: there is no signature, no+ * publisher verification, and no trust tier. So the consent screen shows the+ * raw scope strings alongside a plain-language line, and never summarizes them+ * away.+ */+function ScopeList({ scopes, highlighted }: { scopes: string[]; highlighted?: string[] }) {+ const { t } = useT("settings");+ const added = new Set(highlighted ?? []);+ return (+ <ul className="space-y-1.5">+ {scopes.map((scope) => (+ <li key={scope} className="flex items-baseline gap-2 text-caption">+ <code className="shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono">{scope}</code>+ <span className="text-muted-foreground">{scopeDescription(scope, t)}</span>+ {added.has(scope) ? (+ <Badge variant="secondary">{t(($) => $.plugins.consent.new_scope)}</Badge>+ ) : null}+ </li>+ ))}+ </ul>+ );+}-type RemoteMCPAuthType = "none" | "oauth" | "bearer" | "header";+type Translate = ReturnType<typeof useT<"settings">>["t"];-function RemoteMCPConfiguration({- wsId,- installationId,- config,+function scopeDescription(scope: string, t: Translate): string {+ if (scope.startsWith("net:")) {+ return t(($) => $.plugins.scopes.net, { domain: scope.slice("net:".length) });+ }+ switch (scope) {+ case "issues:read": return t(($) => $.plugins.scopes.issues_read);+ case "issues:write": return t(($) => $.plugins.scopes.issues_write);+ case "comments:read": return t(($) => $.plugins.scopes.comments_read);+ case "comments:write": return t(($) => $.plugins.scopes.comments_write);+ case "tasks:read": return t(($) => $.plugins.scopes.tasks_read);+ case "tasks:write": return t(($) => $.plugins.scopes.tasks_write);+ case "agents:read": return t(($) => $.plugins.scopes.agents_read);+ case "members:read": return t(($) => $.plugins.scopes.members_read);+ case "storage:user": return t(($) => $.plugins.scopes.storage_user);+ case "storage:workspace": return t(($) => $.plugins.scopes.storage_workspace);+ default: return t(($) => $.plugins.scopes.unknown);+ }+}++/**+ * The configuration form is generated from the manifest, not supplied by the+ * plugin: rendering plugin-authored form markup in the host would put plugin+ * code on our origin.+ */+function ConfigForm({+ installation,canManage,+ wsId,}: {- wsId: string;- installationId: string;- config: PluginRemoteMCPConfig;+ installation: PluginInstallation;canManage: boolean;+ wsId: string;}) {const { t } = useT("settings");- const configureMutation = useConfigurePluginRemoteMCP(wsId);- const testMutation = useTestPluginRemoteMCP(wsId);- const approveMutation = useApprovePluginRemoteMCPTools(wsId);- const revokeMutation = useRevokePluginRemoteMCPCredential(wsId);- const oauthMutation = useStartPluginRemoteMCPOAuth(wsId);- const [endpoint, setEndpoint] = useState(config.endpoint ?? config.default_endpoint ?? "");- const [authType, setAuthType] = useState<RemoteMCPAuthType>(- config.auth_type === "oauth" || config.auth_type === "bearer" || config.auth_type === "header" || config.auth_type === "none"- ? config.auth_type- : config.preferred_auth === "oauth" ? "oauth" : "none",- );- const [authHeader, setAuthHeader] = useState(config.auth_header ?? "Authorization");- const [credential, setCredential] = useState("");- const [oauthScope, setOAuthScope] = useState("");- const [oauthClientId, setOAuthClientId] = useState("");- const [oauthClientSecret, setOAuthClientSecret] = useState("");- const [oauthAuthorizationEndpoint, setOAuthAuthorizationEndpoint] = useState("");- const [oauthTokenEndpoint, setOAuthTokenEndpoint] = useState("");- const [oauthTokenAuthMethod, setOAuthTokenAuthMethod] = useState<"none" | "client_secret_basic" | "client_secret_post">("none");- const [publicConfig, setPublicConfig] = useState(() => JSON.stringify(config.public_config ?? {}, null, 2));- const [failurePolicy, setFailurePolicy] = useState<"required" | "optional">(- config.failure_policy === "optional" ? "optional" : "required",- );- const [discovery, setDiscovery] = useState<RemoteMCPDiscoveryResponse | null>(() =>- !config.reviewed && config.discovered_tools.length > 0- ? {- config_revision: config.config_revision ?? 0,- discovered_tools: config.discovered_tools,- discovered_schema_digest: config.discovered_schema_digest ?? "",- }- : null,- );- const [approvedTools, setApprovedTools] = useState<string[]>(() =>- !config.reviewed ? config.discovered_tools.map((tool) => tool.name) : [],- );- const isPending = configureMutation.isPending || testMutation.isPending- || approveMutation.isPending || revokeMutation.isPending || oauthMutation.isPending;- const isConnected = Boolean(config.config_revision)- && (config.credential_state === "configured" || config.credential_state === "not_required");+ const configureMutation = useConfigurePlugin(wsId);+ const [values, setValues] = useState<Record<string, unknown>>(() => ({ ...installation.config }));+ const [secrets, setSecrets] = useState<Record<string, string>>({});- const reportError = (error: unknown) => {- toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));- };- const rememberDiscovery = (result: RemoteMCPDiscoveryResponse) => {- setDiscovery(result);- setApprovedTools(result.discovered_tools.map((tool) => tool.name));- };- const credentialStateLabel = config.credential_state === "configured"- ? t(($) => $.plugins.remote_mcp.credential_states.configured)- : config.credential_state === "revoked"- ? t(($) => $.plugins.remote_mcp.credential_states.revoked)- : config.credential_state === "not_required"- ? t(($) => $.plugins.remote_mcp.credential_states.not_required)- : t(($) => $.plugins.remote_mcp.credential_states.missing);- const configure = async (requestedAuth: RemoteMCPAuthType = authType) => {- let parsedPublicConfig: Record<string, unknown>;- try {- const parsed: unknown = JSON.parse(publicConfig);- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();- parsedPublicConfig = parsed as Record<string, unknown>;- } catch {- toast.error(t(($) => $.plugins.remote_mcp.invalid_public_config));- return;+ if (installation.config_schema.length === 0) return null;++ const setValue = (key: string, value: unknown) => setValues((current) => ({ ...current, [key]: value }));+ const configuredSecrets = new Set(installation.configured_secrets);++ const submit = async () => {+ const payload: Record<string, unknown> = { ...values };+ // Only send a secret the admin actually typed. Sending "" would clear a+ // stored secret every time an unrelated field is saved.+ for (const [key, value] of Object.entries(secrets)) {+ if (value.length > 0) payload[key] = value;}try {- if (requestedAuth === "oauth") {- const result = await oauthMutation.mutateAsync({- installationId,- contributionKey: config.contribution_key,- request: {- endpoint: endpoint.trim() || config.default_endpoint,- public_config: parsedPublicConfig,- failure_policy: failurePolicy,- scope: oauthScope.trim() || undefined,- client_id: oauthClientId.trim() || undefined,- client_secret: oauthClientSecret || undefined,- token_endpoint_auth_method: oauthClientId.trim() ? oauthTokenAuthMethod : undefined,- authorization_endpoint: oauthAuthorizationEndpoint.trim() || undefined,- token_endpoint: oauthTokenEndpoint.trim() || undefined,- return_to: `${window.location.pathname}${window.location.search}`,- },- });- if (!result.authorization_url) {- throw new Error(t(($) => $.plugins.remote_mcp.oauth_connect_failed));- }- if (isDesktopShell()) {- openExternal(result.authorization_url);- } else {- window.location.assign(result.authorization_url);- }- return;- }- const result = await configureMutation.mutateAsync({- installationId,- contributionKey: config.contribution_key,- request: {- endpoint: endpoint.trim(),- public_config: parsedPublicConfig,- auth_type: requestedAuth,- auth_header: requestedAuth === "header" ? authHeader.trim() : undefined,- credential: requestedAuth === "none" ? undefined : credential,- failure_policy: failurePolicy,- },- });- setCredential("");- rememberDiscovery(result);- toast.success(t(($) => $.plugins.remote_mcp.configured_success));+ await configureMutation.mutateAsync({ installationId: installation.id, values: payload });+ setSecrets({});+ toast.success(t(($) => $.plugins.config.saved));} catch (error) {- reportError(error);+ toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));}};return (- <div className="space-y-4 rounded-xl border border-surface-border bg-muted/30 p-4">- <div className="flex flex-wrap items-start justify-between gap-2">- <div>- <div className="text-body font-medium">{t(($) => $.plugins.remote_mcp.title)} · {config.contribution_key}</div>- <div className="mt-1 flex flex-wrap items-center gap-2 text-caption text-muted-foreground">- {config.endpoint_domain ? <span>{config.endpoint_domain}</span> : null}- <Badge variant={config.credential_state === "revoked" || config.credential_state === "missing" ? "destructive" : "secondary"}>- {credentialStateLabel}- </Badge>- <Badge variant={config.reviewed ? "default" : "secondary"}>- {config.reviewed ? t(($) => $.plugins.remote_mcp.reviewed) : t(($) => $.plugins.remote_mcp.pending_review)}- </Badge>- {config.credential_hint ? <span>{config.credential_hint}</span> : null}- </div>- </div>- {config.credential_state !== "not_required" ? (- <Button- size="xs"- variant="ghost"- disabled={!canManage || isPending || config.credential_state !== "configured"}- onClick={() => revokeMutation.mutateAsync({ installationId, contributionKey: config.contribution_key })- .then(() => toast.success(t(($) => $.plugins.remote_mcp.revoked_success)))- .catch(reportError)}- >- {t(($) => $.plugins.remote_mcp.revoke)}- </Button>- ) : null}+ <div className="space-y-4 border-t border-surface-border px-4 py-4">+ <div className="text-caption font-medium">{t(($) => $.plugins.config.title)}</div>+ {installation.config_schema.map((field) => (+ <ConfigField+ key={field.key}+ field={field}+ value={values[field.key]}+ secretValue={secrets[field.key] ?? ""}+ secretConfigured={configuredSecrets.has(field.key)}+ disabled={!canManage || configureMutation.isPending}+ onValueChange={(value) => setValue(field.key, value)}+ onSecretChange={(value) => setSecrets((current) => ({ ...current, [field.key]: value }))}+ />+ ))}+ <div className="flex justify-end">+ <Button size="sm" disabled={!canManage || configureMutation.isPending} onClick={submit}>+ {configureMutation.isPending ? <Loader2 className="animate-spin" /> : null}+ {t(($) => $.plugins.config.save)}+ </Button></div>+ </div>+ );+}- {config.default_endpoint && (config.preferred_auth === "oauth" || config.preferred_auth === "none") ? (- <div className="flex flex-wrap items-center gap-3 rounded-lg border border-surface-border bg-background p-3">- <div className="min-w-0 flex-1">- <div className="text-caption font-medium">- {isConnected ? t(($) => $.plugins.remote_mcp.connected) : t(($) => $.plugins.remote_mcp.ready_to_connect)}- </div>- <div className="mt-0.5 truncate text-caption text-muted-foreground">{config.default_endpoint}</div>- </div>- <Button- size="sm"- disabled={!canManage || isPending || isConnected}- onClick={() => configure(config.preferred_auth as RemoteMCPAuthType)}- >- {oauthMutation.isPending || configureMutation.isPending ? <Loader2 className="animate-spin" /> : null}- {isConnected ? t(($) => $.plugins.remote_mcp.connected) : t(($) => $.plugins.remote_mcp.connect)}- </Button>- </div>+function ConfigField({+ field,+ value,+ secretValue,+ secretConfigured,+ disabled,+ onValueChange,+ onSecretChange,+}: {+ field: PluginConfigField;+ value: unknown;+ secretValue: string;+ secretConfigured: boolean;+ disabled: boolean;+ onValueChange: (value: unknown) => void;+ onSecretChange: (value: string) => void;+}) {+ const { t } = useT("settings");+ const label = (+ <div className="min-w-0">+ <div className="text-caption font-medium">+ {field.label}+ {field.required ? <span className="ml-1 text-destructive">*</span> : null}+ </div>+ {field.description ? (+ <p className="mt-0.5 text-caption text-muted-foreground">{field.description}</p>) : null}+ </div>+ );- <details className="group rounded-lg border border-surface-border bg-background">- <summary className="cursor-pointer select-none px-3 py-2 text-caption font-medium">- {t(($) => $.plugins.remote_mcp.advanced)}- </summary>- <div className="grid gap-3 border-t border-surface-border p-3 sm:grid-cols-2">- <label className="space-y-1 text-caption sm:col-span-2">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.endpoint)}</span>+ return (+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ {label}+ <div className="w-full sm:w-96">+ {field.type === "secret" ? (<Input- value={endpoint}- onChange={(event) => setEndpoint(event.target.value)}- placeholder={t(($) => $.plugins.remote_mcp.endpoint_placeholder)}- disabled={!canManage || isPending}+ type="password"+ autoComplete="off"+ disabled={disabled}+ value={secretValue}+ placeholder={secretConfigured+ ? t(($) => $.plugins.config.secret_set)+ : field.placeholder ?? ""}+ onChange={(event) => onSecretChange(event.target.value)}/>- </label>- <label className="space-y-1 text-caption">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.auth)}</span>- <Select- items={(["none", "oauth", "bearer", "header"] as const).map((value) => ({- value,- label: t(($) => $.plugins.remote_mcp.auth_types[value]),- }))}- value={authType}- onValueChange={(value) => value && setAuthType(value as RemoteMCPAuthType)}- disabled={!canManage || isPending}- >- <SelectTrigger><SelectValue /></SelectTrigger>- <SelectContent>- <SelectItem value="none">{t(($) => $.plugins.remote_mcp.auth_types.none)}</SelectItem>- <SelectItem value="oauth">{t(($) => $.plugins.remote_mcp.auth_types.oauth)}</SelectItem>- <SelectItem value="bearer">{t(($) => $.plugins.remote_mcp.auth_types.bearer)}</SelectItem>- <SelectItem value="header">{t(($) => $.plugins.remote_mcp.auth_types.header)}</SelectItem>- </SelectContent>- </Select>- </label>- <label className="space-y-1 text-caption">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.failure_policy)}</span>+ ) : field.type === "bool" ? (+ <Switch+ disabled={disabled}+ checked={value === true}+ onCheckedChange={(checked) => onValueChange(checked === true)}+ />+ ) : field.type === "enum" ? (<Select- items={(["required", "optional"] as const).map((value) => ({- value,- label: t(($) => $.plugins.remote_mcp.failure_policies[value]),- }))}- value={failurePolicy}- onValueChange={(value) => value && setFailurePolicy(value as "required" | "optional")}- disabled={!canManage || isPending}+ items={(field.options ?? []).map((option) => ({ value: option, label: option }))}+ value={typeof value === "string" ? value : ""}+ onValueChange={(next) => next && onValueChange(next)}>- <SelectTrigger><SelectValue /></SelectTrigger>+ <SelectTrigger disabled={disabled}><SelectValue /></SelectTrigger><SelectContent>- <SelectItem value="required">{t(($) => $.plugins.remote_mcp.failure_policies.required)}</SelectItem>- <SelectItem value="optional">{t(($) => $.plugins.remote_mcp.failure_policies.optional)}</SelectItem>+ {(field.options ?? []).map((option) => (+ <SelectItem key={option} value={option}>{option}</SelectItem>+ ))}</SelectContent></Select>- </label>- {authType === "header" ? (- <label className="space-y-1 text-caption">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.header_name)}</span>- <Input value={authHeader} onChange={(event) => setAuthHeader(event.target.value)} disabled={!canManage || isPending} />- </label>- ) : null}- {authType === "bearer" || authType === "header" ? (- <label className="space-y-1 text-caption">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.credential)}</span>- <Input- type="password"- autoComplete="new-password"- value={credential}- onChange={(event) => setCredential(event.target.value)}- disabled={!canManage || isPending}- />- </label>- ) : null}- {authType === "oauth" ? (- <>- <label className="space-y-1 text-caption sm:col-span-2">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_scope)}</span>- <Input value={oauthScope} onChange={(event) => setOAuthScope(event.target.value)} disabled={!canManage || isPending} />- </label>- <label className="space-y-1 text-caption">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_client_id)}</span>- <Input value={oauthClientId} onChange={(event) => setOAuthClientId(event.target.value)} disabled={!canManage || isPending} />- </label>- <label className="space-y-1 text-caption">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_client_secret)}</span>- <Input type="password" autoComplete="new-password" value={oauthClientSecret} onChange={(event) => setOAuthClientSecret(event.target.value)} disabled={!canManage || isPending} />- </label>- <label className="space-y-1 text-caption">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_authorization_endpoint)}</span>- <Input value={oauthAuthorizationEndpoint} onChange={(event) => setOAuthAuthorizationEndpoint(event.target.value)} disabled={!canManage || isPending} />- </label>- <label className="space-y-1 text-caption">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_token_endpoint)}</span>- <Input value={oauthTokenEndpoint} onChange={(event) => setOAuthTokenEndpoint(event.target.value)} disabled={!canManage || isPending} />- </label>- {oauthClientSecret ? (- <label className="space-y-1 text-caption sm:col-span-2">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_token_auth_method)}</span>- <Select- items={(["none", "client_secret_basic", "client_secret_post"] as const).map((value) => ({ value, label: value }))}- value={oauthTokenAuthMethod}- onValueChange={(value) => value && setOAuthTokenAuthMethod(value as typeof oauthTokenAuthMethod)}- disabled={!canManage || isPending}- >- <SelectTrigger><SelectValue /></SelectTrigger>- <SelectContent>- <SelectItem value="none">{t(($) => $.plugins.remote_mcp.oauth_token_auth_methods.none)}</SelectItem>- <SelectItem value="client_secret_basic">{t(($) => $.plugins.remote_mcp.oauth_token_auth_methods.client_secret_basic)}</SelectItem>- <SelectItem value="client_secret_post">{t(($) => $.plugins.remote_mcp.oauth_token_auth_methods.client_secret_post)}</SelectItem>- </SelectContent>- </Select>- </label>- ) : null}- </>- ) : null}- <label className="space-y-1 text-caption sm:col-span-2">- <span className="font-medium">{t(($) => $.plugins.remote_mcp.public_config)}</span>- <Textarea- className="font-mono"- value={publicConfig}- onChange={(event) => setPublicConfig(event.target.value)}- disabled={!canManage || isPending}+ ) : field.type === "number" ? (+ <Input+ type="number"+ disabled={disabled}+ value={typeof value === "number" ? String(value) : ""}+ placeholder={field.placeholder ?? ""}+ onChange={(event) => {+ const parsed = Number(event.target.value);+ onValueChange(event.target.value === "" || Number.isNaN(parsed) ? undefined : parsed);+ }}/>- </label>- </div>+ ) : (+ <Input+ disabled={disabled}+ value={typeof value === "string" ? value : ""}+ placeholder={field.placeholder ?? ""}+ onChange={(event) => onValueChange(event.target.value)}+ />+ )}+ </div>+ </div>+ );+}- <div className="flex flex-wrap gap-2 border-t border-surface-border p-3">- <Button- size="sm"- disabled={!canManage || isPending || endpoint.trim() === "" || ((authType === "bearer" || authType === "header") && credential === "")}- onClick={() => configure()}- >- {configureMutation.isPending || oauthMutation.isPending ? <Loader2 className="animate-spin" /> : null}- {t(($) => $.plugins.remote_mcp.configure_and_discover)}- </Button>- <Button- size="sm"- variant="outline"- disabled={!canManage || isPending || !config.config_revision}- onClick={() => testMutation.mutateAsync({ installationId, contributionKey: config.contribution_key })- .then((result) => {- rememberDiscovery(result);- toast.success(t(($) => $.plugins.remote_mcp.test_success));- }).catch(reportError)}- >- {testMutation.isPending ? <Loader2 className="animate-spin" /> : null}- {t(($) => $.plugins.remote_mcp.test)}- </Button>- </div>- </details>-- {discovery ? (- <div className="space-y-3 border-t border-surface-border pt-3">- <div className="text-caption font-medium">{t(($) => $.plugins.remote_mcp.discovery)}</div>- {discovery.discovered_tools.length > 0 ? discovery.discovered_tools.map((tool) => (- <label key={tool.name} className="flex items-start gap-2 rounded-lg bg-background px-3 py-2 text-caption">- <Checkbox- checked={approvedTools.includes(tool.name)}- disabled={!canManage || isPending}- onCheckedChange={() => setApprovedTools((current) => current.includes(tool.name)- ? current.filter((name) => name !== tool.name)- : [...current, tool.name])}- />- <span className="min-w-0">- <span className="font-medium">{tool.name}</span>- <Badge className="ml-2" variant={tool.risk === "write" ? "destructive" : "secondary"}>- {tool.risk === "write" ? t(($) => $.plugins.remote_mcp.write) : t(($) => $.plugins.remote_mcp.read)}- </Badge>- {tool.description ? <span className="mt-0.5 block text-muted-foreground">{tool.description}</span> : null}- </span>- </label>- )) : <p className="text-caption text-muted-foreground">{t(($) => $.plugins.remote_mcp.no_tools)}</p>}+function InstallFlow({ wsId, canManage }: { wsId: string; canManage: boolean }) {+ const { t } = useT("settings");+ const previewMutation = usePreviewPlugin(wsId);+ const installMutation = useInstallPlugin(wsId);+ const [sourceUrl, setSourceUrl] = useState("");+ const [preview, setPreview] = useState<PluginPreview | null>(null);++ const runPreview = async () => {+ try {+ const result = await previewMutation.mutateAsync({ source_url: sourceUrl.trim() });+ setPreview(result);+ } catch (error) {+ setPreview(null);+ toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));+ }+ };++ const confirmInstall = async () => {+ if (!preview) return;+ try {+ await installMutation.mutateAsync({ source_url: sourceUrl.trim(), granted_scopes: preview.scopes });+ setPreview(null);+ setSourceUrl("");+ toast.success(t(($) => $.plugins.consent.installed));+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));+ }+ };++ return (+ <SettingsSection title={t(($) => $.plugins.install.title)} description={t(($) => $.plugins.install.description)}>+ <SettingsCard>+ <div className="flex flex-col gap-2 px-4 py-4 sm:flex-row sm:items-center">+ <Input+ className="sm:flex-1"+ disabled={!canManage || previewMutation.isPending}+ value={sourceUrl}+ placeholder={t(($) => $.plugins.install.placeholder)}+ onChange={(event) => setSourceUrl(event.target.value)}+ /><Button- size="sm"- disabled={!canManage || isPending || approvedTools.length === 0}- onClick={() => approveMutation.mutateAsync({- installationId,- contributionKey: config.contribution_key,- tools: approvedTools,- }).then(() => {- setDiscovery(null);- toast.success(t(($) => $.plugins.remote_mcp.approved_success));- }).catch(reportError)}+ disabled={!canManage || previewMutation.isPending || sourceUrl.trim().length === 0}+ onClick={runPreview}>- {approveMutation.isPending ? <Loader2 className="animate-spin" /> : <ShieldCheck />}- {t(($) => $.plugins.remote_mcp.approve)}+ {previewMutation.isPending ? <Loader2 className="animate-spin" /> : null}+ {t(($) => $.plugins.install.review)}</Button></div>- ) : config.approved_tools.length > 0 ? (- <div className="text-caption text-muted-foreground">- {t(($) => $.plugins.remote_mcp.approved_tools)}: {config.approved_tools.map((tool) => tool.name).join(", ")}- </div>- ) : null}- </div>- );-}-function installationState(installation: PluginInstallation): "disabled" | "activating" | "healthy" | "degraded" | "failed" {- if (installation.enabled !== true) return "disabled";- if (installation.lifecycle_status === "activating") return "activating";- if (installation.health_state === "error" || installation.lifecycle_status === "error") return "failed";- if (installation.health_state === "degraded" || installation.lifecycle_status === "degraded") return "degraded";- return "healthy";+ {preview ? (+ <div className="space-y-4 border-t border-surface-border px-4 py-4">+ <div>+ <div className="text-body font-semibold">{preview.manifest.name}</div>+ <p className="text-caption text-muted-foreground">+ {t(($) => $.plugins.byline, {+ author: preview.manifest.author.name,+ version: preview.manifest.version,+ })}+ {preview.installed+ ? t(($) => $.plugins.consent.upgrade_from, { version: preview.installed_version ?? "" })+ : ""}+ </p>+ {preview.manifest.description ? (+ <p className="mt-2 text-caption">{preview.manifest.description}</p>+ ) : null}+ </div>++ <Alert>+ <AlertCircle />+ <AlertTitle>{t(($) => $.plugins.consent.title)}</AlertTitle>+ <AlertDescription>{t(($) => $.plugins.consent.description)}</AlertDescription>+ </Alert>++ <ScopeList scopes={preview.scopes} highlighted={preview.added_scopes} />++ <div className="flex justify-end gap-2">+ <Button variant="ghost" onClick={() => setPreview(null)}>+ {t(($) => $.plugins.consent.cancel)}+ </Button>+ <Button disabled={!canManage || installMutation.isPending} onClick={confirmInstall}>+ {installMutation.isPending ? <Loader2 className="animate-spin" /> : null}+ {preview.installed+ ? t(($) => $.plugins.consent.confirm_upgrade)+ : t(($) => $.plugins.consent.confirm)}+ </Button>+ </div>+ </div>+ ) : null}+ </SettingsCard>+ </SettingsSection>+ );}-export function PluginsTab() {+function InstalledPlugin({+ installation,+ wsId,+ canManage,+}: {+ installation: PluginInstallation;+ wsId: string;+ canManage: boolean;+}) {const { t } = useT("settings");- const workspace = useCurrentWorkspace();- const wsId = workspace?.id ?? "";- const currentMember = useCurrentMember(wsId);- const canManage = currentMember.role === "owner" || currentMember.role === "admin";- const catalogQuery = useQuery(pluginCatalogOptions(wsId));- const installationsQuery = useQuery(pluginInstallationsOptions(wsId));- const refetchInstallations = installationsQuery.refetch;- 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>>({});-- useEffect(() => {- const search = new URLSearchParams(window.location.search);- const connected = search.get("remote_mcp_connected") === "1";- const failed = search.has("remote_mcp_error");- if (!connected && !failed) return;-- if (connected) {- toast.success(t(($) => $.plugins.remote_mcp.oauth_connected_success));- void refetchInstallations();- } else {- toast.error(t(($) => $.plugins.remote_mcp.oauth_connect_failed));- }- search.delete("remote_mcp_connected");- search.delete("remote_mcp_error");- const query = search.toString();- window.history.replaceState(window.history.state, "", `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`);- }, [refetchInstallations, t]);-- const releasesByPlugin = useMemo(() => {- const grouped = new Map<string, PluginCatalogRelease[]>();- for (const release of catalogQuery.data?.releases ?? []) {- const versions = grouped.get(release.plugin_key) ?? [];- versions.push(release);- grouped.set(release.plugin_key, versions);- }- for (const versions of grouped.values()) {- versions.sort((left, right) => comparePluginVersions(right.version, left.version));- }- return [...grouped.entries()];- }, [catalogQuery.data?.releases]);-- 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 members = membersQuery.data ?? [];- const isMutating = installMutation.isPending || upgradeMutation.isPending || enabledMutation.isPending- || rollbackMutation.isPending || uninstallMutation.isPending;+ const isMutating = enabledMutation.isPending || uninstallMutation.isPending;const reportError = (error: unknown) => {toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));};- if (catalogQuery.isPending || installationsQuery.isPending) {- return (- <SettingsTab title={t(($) => $.plugins.title)} description={t(($) => $.plugins.description)}>- <SettingsCard>- <div className="space-y-3 p-4" aria-label={t(($) => $.plugins.loading)}>- <Skeleton className="h-5 w-48" />- <Skeleton className="h-4 w-full" />- <Skeleton className="h-8 w-28" />+ const contributions = [+ ...installation.surfaces.map((surface) => `${surface.name} (${surface.type})`),+ ...installation.hooks.map((hook) => `${hook.name} (${hook.triggers.join(", ")})`),+ ...installation.resources.map((resource) => `${resource.key} (${resource.type})`),+ ];++ return (+ <SettingsCard>+ <div className="space-y-4 px-4 py-4">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-body font-semibold">{installation.name}</span>+ <Badge variant="secondary">{t(($) => $.plugins.version, { version: installation.version })}</Badge>+ {!installation.enabled ? (+ <Badge variant="outline">{t(($) => $.plugins.states.disabled)}</Badge>+ ) : null}+ </div>+ <p className="text-caption text-muted-foreground">{installation.plugin_key}</p>+ {installation.description ? (+ <p className="mt-2 max-w-2xl text-caption">{installation.description}</p>+ ) : null}</div>- </SettingsCard>- </SettingsTab>- );- }+ <div className="flex items-center gap-2">+ <Switch+ aria-label={t(($) => $.plugins.enabled_label)}+ disabled={!canManage || isMutating}+ checked={installation.enabled}+ onCheckedChange={(checked) => enabledMutation+ .mutateAsync({ installationId: installation.id, enabled: checked === true })+ .then(() => toast.success(checked+ ? t(($) => $.plugins.enabled)+ : t(($) => $.plugins.disabled)))+ .catch(reportError)}+ />+ <Button+ size="icon"+ variant="ghost"+ aria-label={t(($) => $.plugins.uninstall)}+ disabled={!canManage || isMutating}+ onClick={() => uninstallMutation.mutateAsync(installation.id)+ .then(() => toast.success(t(($) => $.plugins.uninstalled)))+ .catch(reportError)}+ >+ {uninstallMutation.isPending ? <Loader2 className="animate-spin" /> : <Trash2 />}+ </Button>+ </div>+ </div>- if (catalogQuery.isError || installationsQuery.isError) {- return (- <SettingsTab title={t(($) => $.plugins.title)} description={t(($) => $.plugins.description)}>- <Alert variant="destructive">- <AlertCircle />- <AlertTitle>{t(($) => $.plugins.load_failed)}</AlertTitle>- <AlertDescription>{t(($) => $.plugins.load_failed_description)}</AlertDescription>- </Alert>- </SettingsTab>- );- }+ <div className="space-y-2">+ <div className="text-caption font-medium">{t(($) => $.plugins.granted_scopes)}</div>+ <ScopeList scopes={installation.granted_scopes} />+ </div>- if (catalogQuery.data?.supported !== true) {- return (- <SettingsTab title={t(($) => $.plugins.title)} description={t(($) => $.plugins.description)}>- <Alert>- <AlertCircle />- <AlertTitle>{t(($) => $.plugins.backend_unavailable)}</AlertTitle>- <AlertDescription>{t(($) => $.plugins.backend_unavailable_description)}</AlertDescription>- </Alert>- </SettingsTab>- );- }+ {contributions.length > 0 ? (+ <div className="space-y-1">+ <div className="text-caption font-medium">{t(($) => $.plugins.contributes)}</div>+ <p className="text-caption text-muted-foreground">{contributions.join(" · ")}</p>+ </div>+ ) : null}++ <p className="text-caption text-muted-foreground">+ {t(($) => $.plugins.source)}: <span className="font-mono break-all">{installation.source_url}</span>+ </p>+ </div>++ <ConfigForm installation={installation} canManage={canManage} wsId={wsId} />+ </SettingsCard>+ );+}++export function PluginsTab() {+ const { t } = useT("settings");+ const workspace = useCurrentWorkspace();+ const wsId = workspace?.id ?? "";+ const { role } = useCurrentMember(wsId);+ const canManage = role === "owner" || role === "admin";++ const { data, isLoading, isError } = useQuery(pluginInstallationsOptions(wsId));+ const installations = useMemo(() => data?.plugins ?? [], [data]);return (<SettingsTab title={t(($) => $.plugins.title)} description={t(($) => $.plugins.description)}>- {catalogQuery.data.diagnostics.length > 0 ? (- <Alert variant="destructive">- <AlertCircle />- <AlertTitle>{t(($) => $.plugins.catalog_degraded)}</AlertTitle>- <AlertDescription>{t(($) => $.plugins.catalog_degraded_description)}</AlertDescription>- </Alert>- ) : null}-- {!canManage && !currentMember.isLoading ? (+ {!canManage ? (<Alert>- <ShieldCheck />+ <AlertCircle /><AlertTitle>{t(($) => $.plugins.read_only)}</AlertTitle><AlertDescription>{t(($) => $.plugins.read_only_description)}</AlertDescription></Alert>) : null}- {releasesByPlugin.length === 0 && privateInstallations.length === 0 ? (- <SettingsCard>- <div className="p-6 text-center text-body text-muted-foreground">- {t(($) => $.plugins.empty)}+ {canManage ? <InstallFlow wsId={wsId} canManage={canManage} /> : null}++ <SettingsSection title={t(($) => $.plugins.installed.title)}>+ {isLoading ? (+ <Skeleton className="h-24 w-full" aria-label={t(($) => $.plugins.loading)} />+ ) : isError ? (+ <Alert variant="destructive">+ <AlertCircle />+ <AlertTitle>{t(($) => $.plugins.load_failed)}</AlertTitle>+ <AlertDescription>{t(($) => $.plugins.load_failed_description)}</AlertDescription>+ </Alert>+ ) : installations.length === 0 ? (+ <SettingsCard>+ <p className="px-4 py-6 text-caption text-muted-foreground">{t(($) => $.plugins.empty)}</p>+ </SettingsCard>+ ) : (+ <div className="space-y-4">+ {installations.map((installation) => (+ <InstalledPlugin+ key={installation.id}+ installation={installation}+ wsId={wsId}+ canManage={canManage}+ />+ ))}</div>- </SettingsCard>- ) : null}-- {releasesByPlugin.map(([pluginKey, versions]) => {- const latest = versions[0];- if (!latest) return null;- 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;- const rollback = installation- ? versions.find((release) => comparePluginVersions(release.version, installation.desired_version) < 0)- : null;- const scope = installation ? selectedScopes[installation.id] ?? "workspace" : "workspace";- const selectedAgent = installation ? selectedAgents[installation.id] ?? agents[0]?.id ?? "" : "";- const state = installation ? installationState(installation) : null;- const activeBindings = installation?.bindings.filter((binding) => binding.enabled === true) ?? [];- const workspaceBindingActive = activeBindings.some((binding) => binding.scope_type === "workspace");- const remoteMCPReady = installation?.remote_mcp.every((config) => config.ready) ?? true;-- return (- <SettingsSection key={pluginKey}>- <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">{latest.name}</h3>- <Badge variant="outline">{t(($) => $.plugins.official)}</Badge>- {latest.signature_verified === true ? (- <Badge variant="secondary"><ShieldCheck />{t(($) => $.plugins.signed)}</Badge>- ) : (- <Badge variant="destructive">{t(($) => $.plugins.signature_unverified)}</Badge>- )}- {state ? (- <Badge variant={state === "failed" ? "destructive" : state === "healthy" ? "default" : "secondary"}>- {state === "activating" ? <Loader2 className="animate-spin" /> : null}- {t(($) => $.plugins.states[state])}- </Badge>- ) : null}- </div>- <p className="mt-1 text-body text-muted-foreground">{latest.description}</p>- <p className="mt-1 break-all font-mono text-caption text-muted-foreground">{pluginKey}</p>- </div>- <Badge variant="outline">{installation?.desired_version ?? selectedRelease.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">- {selectedRelease.contributions.map((contribution) => (- <li key={contribution.key}>- <span className="font-medium text-foreground">{contribution.name}</span>- {" · "}{contribution.type}{" — "}{contribution.description}- </li>- ))}- </ul>- </div>- <div>- <div className="font-medium text-foreground">{t(($) => $.plugins.review.permissions)}</div>- <p className="mt-1 text-muted-foreground">- {selectedRelease.requested_capabilities.join(", ") || t(($) => $.plugins.review.none)}- </p>- </div>- <div>- <div className="font-medium text-foreground">{t(($) => $.plugins.review.compatibility)}</div>- <p className="mt-1 text-muted-foreground">- {t(($) => $.plugins.review.host_api)} {selectedRelease.host_api}{" · "}- {selectedRelease.required_daemon_features.join(", ")}- </p>- </div>- <div>- <div className="font-medium text-foreground">{t(($) => $.plugins.review.publisher)}</div>- <p className="mt-1 break-all text-muted-foreground">- {selectedRelease.publisher}{" · "}{selectedRelease.signature_key_id}- </p>- </div>- </div>-- {selectedRelease.compatible !== true ? (- <Alert variant="destructive">- <AlertCircle />- <AlertTitle>{t(($) => $.plugins.incompatible)}</AlertTitle>- <AlertDescription>{t(($) => $.plugins.incompatible_description)}</AlertDescription>- </Alert>- ) : null}-- {!installation ? (- <div className="flex flex-col gap-2 border-t border-surface-border pt-4 sm:flex-row sm:items-center sm:justify-between">- <p className="text-caption text-muted-foreground">{t(($) => $.plugins.install_disabled_hint)}</p>- <div className="flex items-center gap-2">- <Select- items={versions.map((release) => ({ value: release.version, label: release.version }))}- value={selectedVersion}- onValueChange={(value) => value && setSelectedVersions((current) => ({ ...current, [pluginKey]: value }))}- >- <SelectTrigger><SelectValue /></SelectTrigger>- <SelectContent>- {versions.map((release) => <SelectItem key={release.version} value={release.version}>{release.version}</SelectItem>)}- </SelectContent>- </Select>- <Button- disabled={!canManage || isMutating || selectedRelease.compatible !== true || selectedRelease.signature_verified !== true}- onClick={() => installMutation.mutateAsync({ plugin_key: pluginKey, version: selectedRelease.version })- .then(() => toast.success(t(($) => $.plugins.installed_disabled)))- .catch(reportError)}- >- {installMutation.isPending ? <Loader2 className="animate-spin" /> : null}- {t(($) => $.plugins.install)}- </Button>- </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>-- {installation.remote_mcp.map((config) => (- <RemoteMCPConfiguration- key={config.contribution_key}- wsId={wsId}- installationId={installation.id}- config={config}- canManage={canManage}- />- ))}-- {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>- )}-- {!remoteMCPReady ? (- <p className="text-caption text-muted-foreground">- {t(($) => $.plugins.remote_mcp.complete_before_enabling)}- </p>- ) : null}-- <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 || !remoteMCPReady || (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>- <Button- variant="outline"- disabled={!canManage || isMutating || !workspaceBindingActive}- onClick={() => enabledMutation.mutateAsync({- installationId: installation.id,- enabled: false,- binding: { scope_type: "workspace", scope_id: wsId },- }).then(() => toast.success(t(($) => $.plugins.disabled))).catch(reportError)}- >- {t(($) => $.plugins.disable_workspace)}- </Button>- </div>-- <div className="flex flex-wrap gap-2">- {upgrade ? (- <Button- variant="outline"- disabled={!canManage || isMutating || upgrade.compatible !== true}- onClick={() => upgradeMutation.mutateAsync({- installationId: installation.id,- plugin_key: pluginKey,- version: upgrade.version,- }).then(() => toast.success(t(($) => $.plugins.upgraded))).catch(reportError)}- >- {upgradeMutation.isPending ? <Loader2 className="animate-spin" /> : null}- {t(($) => $.plugins.upgrade_to, { version: upgrade.version })}- </Button>- ) : null}- {rollback ? (- <Button- variant="outline"- disabled={!canManage || isMutating}- onClick={() => rollbackMutation.mutateAsync({ installationId: installation.id, version: rollback.version })- .then(() => toast.success(t(($) => $.plugins.rolled_back)))- .catch(reportError)}- >- {rollbackMutation.isPending ? <Loader2 className="animate-spin" /> : null}- {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>- )}- </div>- </SettingsCard>- </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 remoteMCPReady = installation.remote_mcp.every((config) => config.ready);- 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>-- {installation.remote_mcp.map((config) => (- <RemoteMCPConfiguration- key={config.contribution_key}- wsId={wsId}- installationId={installation.id}- config={config}- canManage={canManage}- />- ))}-- {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>}-- {!remoteMCPReady ? (- <p className="text-caption text-muted-foreground">- {t(($) => $.plugins.remote_mcp.complete_before_enabling)}- </p>- ) : null}-- <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 || !remoteMCPReady || (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>- );- })}+ )}+ </SettingsSection></SettingsTab>);}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 095484f889..7006854476 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -195,6 +195,9 @@ var concurrentIndexCleanups = map[string]string{"335_issue_status_workspace_key_index": "idx_issue_status_workspace_key","336_issue_status_workspace_name_index": "idx_issue_status_workspace_name_active","343_comment_delegated_failure_pending_index": "idx_comment_delegated_failure_pending",+ "345_plugin_installation_workspace_key_index": "idx_plugin_installation_workspace_key",+ "346_plugin_storage_scope_key_index": "idx_plugin_storage_scope_key",+ "347_plugin_secret_installation_key_index": "idx_plugin_secret_installation_key",}// concurrentDownIndexCleanups covers every migration whose down directiondiff --git a/server/cmd/multica/cmd_plugin.go b/server/cmd/multica/cmd_plugin.godeleted file mode 100644index cc1be8a96a..0000000000--- a/server/cmd/multica/cmd_plugin.go+++ /dev/null@@ -1,490 +0,0 @@-package main--import (- "context"- "encoding/json"- "fmt"- "io"- "net/url"- "os"- "path/filepath"- "strings"- "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,-}--var pluginRemoteMCPCmd = &cobra.Command{Use: "remote-mcp", Short: "Configure and review Remote MCP contributions"}--var pluginRemoteMCPConfigureCmd = &cobra.Command{- Use: "configure <installation-id> <contribution-key>", Short: "Configure and test a Remote MCP endpoint", Args: exactArgs(2), RunE: runPluginRemoteMCPConfigure,-}-var pluginRemoteMCPTestCmd = &cobra.Command{- Use: "test <installation-id> <contribution-key>", Short: "Test and discover a configured Remote MCP endpoint", Args: exactArgs(2), RunE: runPluginRemoteMCPTest,-}-var pluginRemoteMCPApproveCmd = &cobra.Command{- Use: "approve <installation-id> <contribution-key>", Short: "Approve an explicit Remote MCP tool allowlist", Args: exactArgs(2), RunE: runPluginRemoteMCPApprove,-}-var pluginRemoteMCPRevokeCmd = &cobra.Command{- Use: "revoke <installation-id> <contribution-key>", Short: "Revoke the Remote MCP credential and disable the Plugin", Args: exactArgs(2), RunE: runPluginRemoteMCPRevoke,-}--func init() {- pluginCmd.AddCommand(pluginInitCmd, pluginValidateCmd, pluginPackCmd, pluginInstallCmd, pluginListCmd, pluginStatusCmd, pluginRemoteMCPCmd)- pluginRemoteMCPCmd.AddCommand(pluginRemoteMCPConfigureCmd, pluginRemoteMCPTestCmd, pluginRemoteMCPApproveCmd, pluginRemoteMCPRevokeCmd)- 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")- pluginInitCmd.Flags().String("contribution", "skill", "Contribution template: skill or remote-mcp")- pluginInitCmd.Flags().String("endpoint-host", "mcp.example.com", "Allowed Remote MCP endpoint host for the remote-mcp template")- 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")- for _, command := range []*cobra.Command{pluginRemoteMCPConfigureCmd, pluginRemoteMCPTestCmd, pluginRemoteMCPApproveCmd, pluginRemoteMCPRevokeCmd} {- command.Flags().String("workspace", "", "Workspace ID, slug, or ID prefix")- command.Flags().String("output", "json", "Output format: json")- }- pluginRemoteMCPConfigureCmd.Flags().String("endpoint", "", "Public HTTPS MCP endpoint (required)")- pluginRemoteMCPConfigureCmd.Flags().String("auth-type", "none", "Authentication: none, bearer, or header")- pluginRemoteMCPConfigureCmd.Flags().String("auth-header", "", "Header name when --auth-type=header")- pluginRemoteMCPConfigureCmd.Flags().Bool("credential-stdin", false, "Read the credential from stdin; keeps it out of shell history and ps")- pluginRemoteMCPConfigureCmd.Flags().String("credential-file", "", "Read the credential from a file (suggested mode: 0600)")- pluginRemoteMCPConfigureCmd.Flags().String("public-config-file", "", "Read non-secret public configuration JSON from a file")- pluginRemoteMCPConfigureCmd.Flags().String("failure-policy", "required", "Failure policy: required or optional")- pluginRemoteMCPApproveCmd.Flags().StringSlice("tool", nil, "Tool name to approve (repeatable or comma-separated; required)")-}--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")- contributionType, _ := cmd.Flags().GetString("contribution")- endpointHost, _ := cmd.Flags().GetString("endpoint-host")- if contributionType == "" {- contributionType = "skill"- }- if endpointHost == "" {- endpointHost = "mcp.example.com"- }- 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"},- }- switch contributionType {- case "skill":- manifest.Compatibility.RequiredDaemonFeatures = []string{plugincontract.DaemonFeatureExecutionManifestV1, plugincontract.DaemonFeatureAgentSkillV1}- manifest.RequestedCapabilities = []string{plugincontract.CapabilityAgentSkillContribute}- manifest.Contributes.AgentSkills = []plugincontract.AgentSkillContribution{{- Key: "example-skill", Name: name, Description: "Explain when and how this Skill should be used.", Entry: "skills/example-skill/SKILL.md",- }}- case "remote-mcp":- manifest.Metadata.Description = "A workspace-private declarative Remote MCP Plugin."- manifest.Compatibility.RequiredDaemonFeatures = []string{plugincontract.DaemonFeatureExecutionManifestV1, plugincontract.DaemonFeatureRemoteMCPV1}- manifest.RequestedCapabilities = []string{plugincontract.CapabilityRemoteMCPConnect}- manifest.Contributes.RemoteMCP = []plugincontract.RemoteMCPContribution{{- Key: "example-tools", Name: name, Description: "Expose explicitly reviewed remote tools.",- Transport: "streamable-http", ProtocolVersions: []string{"2025-03-26", "2024-11-05"},- EndpointPolicy: plugincontract.RemoteMCPEndpointPolicy{- DefaultEndpoint: "https://" + endpointHost + "/mcp", AllowedHosts: []string{endpointHost},- },- Authentication: plugincontract.RemoteMCPAuthentication{- Preferred: "oauth", Supported: []string{"oauth", "bearer", "header", "none"},- },- ToolIntent: []plugincontract.RemoteMCPToolIntent{{Name: "example.read", Description: "Read an example value.", Risk: "read"}},- ConfigurationSchema: json.RawMessage(`{"type":"object","additionalProperties":false}`),- }}- default:- return fmt.Errorf("--contribution must be skill or remote-mcp")- }- 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(dir, 0o755); err != nil {- return err- }- if err := os.WriteFile(filepath.Join(dir, plugincontract.ManifestFilename), manifestBytes, 0o644); err != nil {- return err- }- if contributionType == "skill" {- if err := os.MkdirAll(filepath.Join(dir, "skills", "example-skill"), 0o755); 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)-}--func remoteMCPAPI(cmd *cobra.Command, args []string, suffix string, method string, body any) error {- if err := requireHumanLocalCommand("plugin remote-mcp " + method); err != nil {- return err- }- workspaceID, err := pluginWorkspaceID(cmd)- if err != nil {- return err- }- client, err := newAPIClient(cmd)- if err != nil {- return err- }- client.WorkspaceID = workspaceID- path := "/api/workspaces/" + workspaceID + "/plugins/" + url.PathEscape(args[0]) + "/remote-mcp/" + url.PathEscape(args[1]) + suffix- ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(time.Minute))- defer cancel()- if method == "revoke" {- if err := client.DeleteJSON(ctx, path); err != nil {- return err- }- return cli.PrintJSON(cmd.OutOrStdout(), map[string]any{"revoked": true, "plugin_disabled": true})- }- var result map[string]any- if suffix == "/config" {- err = client.PutJSON(ctx, path, body, &result)- } else {- err = client.PostJSON(ctx, path, body, &result)- }- if err != nil {- return err- }- return cli.PrintJSON(cmd.OutOrStdout(), result)-}--func runPluginRemoteMCPConfigure(cmd *cobra.Command, args []string) error {- endpoint, _ := cmd.Flags().GetString("endpoint")- if endpoint == "" {- return fmt.Errorf("--endpoint is required")- }- credential, err := readRemoteMCPCredential(cmd)- if err != nil {- return err- }- publicConfig := json.RawMessage(`{}`)- if configPath, _ := cmd.Flags().GetString("public-config-file"); configPath != "" {- raw, err := os.ReadFile(filepath.Clean(configPath))- if err != nil {- return fmt.Errorf("read --public-config-file: %w", err)- }- publicConfig = raw- }- authType, _ := cmd.Flags().GetString("auth-type")- authHeader, _ := cmd.Flags().GetString("auth-header")- failurePolicy, _ := cmd.Flags().GetString("failure-policy")- return remoteMCPAPI(cmd, args, "/config", "configure", map[string]any{- "endpoint": endpoint, "public_config": publicConfig, "auth_type": authType,- "auth_header": authHeader, "credential": credential, "failure_policy": failurePolicy,- })-}--func runPluginRemoteMCPTest(cmd *cobra.Command, args []string) error {- return remoteMCPAPI(cmd, args, "/test", "test", map[string]any{})-}--func runPluginRemoteMCPApprove(cmd *cobra.Command, args []string) error {- tools, _ := cmd.Flags().GetStringSlice("tool")- if len(tools) == 0 {- return fmt.Errorf("at least one --tool is required")- }- return remoteMCPAPI(cmd, args, "/approve", "approve", map[string]any{"tools": tools})-}--func runPluginRemoteMCPRevoke(cmd *cobra.Command, args []string) error {- return remoteMCPAPI(cmd, args, "/credential", "revoke", nil)-}--func readRemoteMCPCredential(cmd *cobra.Command) (string, error) {- fromStdin, _ := cmd.Flags().GetBool("credential-stdin")- fromFile, _ := cmd.Flags().GetString("credential-file")- if fromStdin && fromFile != "" {- return "", fmt.Errorf("--credential-stdin and --credential-file are mutually exclusive")- }- if !fromStdin && fromFile == "" {- return "", nil- }- var raw []byte- var err error- if fromStdin {- raw, err = io.ReadAll(cmd.InOrStdin())- } else {- raw, err = os.ReadFile(filepath.Clean(fromFile))- }- if err != nil {- return "", fmt.Errorf("read Remote MCP credential: %w", err)- }- credential := strings.TrimSpace(string(raw))- if credential == "" {- return "", fmt.Errorf("Remote MCP credential input is empty")- }- return credential, nil-}diff --git a/server/cmd/multica/cmd_plugin_test.go b/server/cmd/multica/cmd_plugin_test.godeleted file mode 100644index 1da91cf7ab..0000000000--- a/server/cmd/multica/cmd_plugin_test.go+++ /dev/null@@ -1,97 +0,0 @@-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")- }-}--func TestPluginInitRemoteMCPTemplate(t *testing.T) {- root := filepath.Join(t.TempDir(), "plugin")- cmd := pluginInitTestCommand(&bytes.Buffer{})- cmd.Flags().String("contribution", "remote-mcp", "")- cmd.Flags().String("endpoint-host", "tools.example.com", "")- if err := runPluginInit(cmd, []string{root}); err != nil {- t.Fatalf("plugin init remote-mcp: %v", err)- }- _, artifact, err := loadPluginSource(root)- if err != nil {- t.Fatalf("load remote-mcp template: %v", err)- }- if len(artifact.Manifest.Contributes.RemoteMCP) != 1 || len(artifact.Files) != 1 {- t.Fatalf("remote-mcp template = %+v", artifact.Manifest.Contributes)- }-}diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.goindex 8538a7f485..81d14b6c0c 100644--- a/server/cmd/multica/main.go+++ b/server/cmd/multica/main.go@@ -54,7 +54,6 @@ func init() {workspaceCmd.GroupID = groupCorerepoCmd.GroupID = groupCoreskillCmd.GroupID = groupCore- pluginCmd.GroupID = groupCoresquadCmd.GroupID = groupCorechatCmd.GroupID = groupCore@@ -81,7 +80,6 @@ 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 68ae30249c..99c83bef37 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -991,19 +991,20 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busslog.Info("vcs integration disabled (MULTICA_VCS_SECRET_KEY not set)")}- // Remote MCP Plugin credentials use a dedicated deployment key. Keeping- // this separate from VCS and channel secrets gives operators an isolated- // rotation and blast radius; without it configuration endpoints fail closed.+ // Plugin secrets use a dedicated deployment key. Keeping this separate from+ // VCS and channel secrets gives operators an isolated rotation and blast+ // radius; without it, saving a `secret` config field fails closed rather+ // than storing plaintext.if pluginKey, err := secretbox.LoadKey("MULTICA_PLUGIN_SECRET_KEY"); err == nil {box, err := secretbox.New(pluginKey)if err != nil {- slog.Error("plugins: secretbox.New failed; Remote MCP credentials disabled", "error", err)+ slog.Error("plugins: secretbox.New failed; Plugin secrets disabled", "error", err)} else if h.PluginService != nil {- h.PluginService.RemoteMCPSecrets = box- slog.Info("Remote MCP Plugin credential encryption enabled")+ h.PluginService.Secrets = box+ slog.Info("Plugin secret encryption enabled")}} else {- slog.Info("Remote MCP Plugin credentials disabled (MULTICA_PLUGIN_SECRET_KEY not set)")+ slog.Info("Plugin secrets disabled (MULTICA_PLUGIN_SECRET_KEY not set)")}if opts.HeartbeatScheduler != nil {@@ -1188,9 +1189,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Auth group made a missing cookie a hard 401, breaking the flow for exactly// the browsers above; the other four composio endpoints stay session-gated.r.Get("/api/integrations/composio/callback", h.ComposioCallback)- // Generic hosted Remote MCP OAuth callback. Identity and installation scope- // come exclusively from the encrypted, single-use state record.- r.With(authVerifyRL).Get("/api/plugins/remote-mcp/oauth/callback", h.CompletePluginRemoteMCPOAuth)// Daemon API routes (require daemon token or valid user token)r.Route("/api/daemon", func(r chi.Router) {@@ -1219,7 +1217,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/runtimes/{runtimeId}/local-skills/import/{requestId}/result", h.ReportLocalSkillImportResult)r.Get("/tasks/{taskId}/status", h.GetTaskStatus)- r.Get("/tasks/{taskId}/remote-mcp/{contributionId}/credential", h.ResolveTaskRemoteMCPCredential)r.Post("/tasks/{taskId}/start", h.StartTask)r.Post("/tasks/{taskId}/wait-local-directory", h.MarkTaskWaitingLocalDirectory)r.Post("/tasks/{taskId}/progress", h.ReportTaskProgress)@@ -1314,11 +1311,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// The payload is names and transports only; the stored// entries are write-only.r.Get("/mcp-servers", h.ListWorkspaceMcpServers)+ // Installed Plugins are member-visible so a member can+ // see what is mounted in their workspace and which scopes+ // it holds; install / configure / remove stay admin-only.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)})// Admin-level accessr.Group(func(r chi.Router) {@@ -1345,17 +1341,15 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Patch("/runtime-profiles/{profileId}", h.UpdateRuntimeProfile)r.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)+ // Installing a Plugin is two steps on purpose: preview+ // parses the manifest and returns the scope list without+ // writing anything, so the consent screen has something to+ // show before an installation exists.+ r.Post("/plugins/preview", h.PreviewPlugin)+ r.Post("/plugins", h.InstallPlugin)+ r.Put("/plugins/{installationId}/config", h.ConfigurePlugin)r.Post("/plugins/{installationId}/enable", h.EnablePlugin)r.Post("/plugins/{installationId}/disable", h.DisablePlugin)- r.Put("/plugins/{installationId}/remote-mcp/{contributionKey}/config", h.ConfigurePluginRemoteMCP)- r.Post("/plugins/{installationId}/remote-mcp/{contributionKey}/oauth/start", h.StartPluginRemoteMCPOAuth)- r.Post("/plugins/{installationId}/remote-mcp/{contributionKey}/test", h.TestPluginRemoteMCP)- r.Post("/plugins/{installationId}/remote-mcp/{contributionKey}/approve", h.ReviewPluginRemoteMCPTools)- r.Delete("/plugins/{installationId}/remote-mcp/{contributionKey}/credential", h.RevokePluginRemoteMCPCredential)- r.Post("/plugins/{installationId}/rollback", h.RollbackPlugin)r.Delete("/plugins/{installationId}", h.UninstallPlugin)})// Owner-only accessdiff --git a/server/internal/daemon/remote_mcp_broker.go b/server/internal/daemon/remote_mcp_broker.goindex 2929361069..7e92ca0e06 100644--- a/server/internal/daemon/remote_mcp_broker.go+++ b/server/internal/daemon/remote_mcp_broker.go@@ -19,8 +19,6 @@ import ("sync/atomic""time"- "github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/pluginruntime""github.com/multica-ai/multica/server/pkg/remotemcp")@@ -54,7 +52,7 @@ func (set *remoteMCPBrokerSet) Close() {})}-func startTaskRemoteMCPBrokers(setupCtx, lifetimeCtx context.Context, taskID, provider string, connections []pluginruntime.RemoteMCPConnection, resolveCredential remoteMCPCredentialResolver, logger *slog.Logger) (json.RawMessage, []string, *remoteMCPBrokerSet, error) {+func startTaskRemoteMCPBrokers(setupCtx, lifetimeCtx context.Context, taskID, provider string, connections []remotemcp.Connection, resolveCredential remoteMCPCredentialResolver, logger *slog.Logger) (json.RawMessage, []string, *remoteMCPBrokerSet, error) {if len(connections) == 0 {return nil, nil, nil, nil}@@ -167,8 +165,8 @@ func providerSupportsRemoteMCPBroker(provider string) bool {}}-func validatePinnedRemoteMCPTools(approved, discovered []pluginruntime.RemoteMCPTool) error {- available := make(map[string]pluginruntime.RemoteMCPTool, len(discovered))+func validatePinnedRemoteMCPTools(approved, discovered []remotemcp.Tool) error {+ available := make(map[string]remotemcp.Tool, len(discovered))for _, tool := range discovered {available[tool.Name] = tool}@@ -192,7 +190,7 @@ func randomBrokerToken() (string, error) {return hex.EncodeToString(value), nil}-func remoteMCPServerName(connection pluginruntime.RemoteMCPConnection) string {+func remoteMCPServerName(connection remotemcp.Connection) string {name := strings.Map(func(r rune) rune {if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {return r@@ -208,7 +206,7 @@ func remoteMCPServerName(connection pluginruntime.RemoteMCPConnection) string {type remoteMCPProxy struct {taskID string- connection pluginruntime.RemoteMCPConnection+ connection remotemcp.Connectionendpoint *url.URLclient *http.ClientcredentialHeaders http.Header@@ -410,12 +408,12 @@ func (proxy *remoteMCPProxy) filterToolsListResponse(raw []byte) ([]byte, error)}byName[tool.Name] = canonical}- pinned := append([]pluginruntime.RemoteMCPTool(nil), proxy.connection.ApprovedTools...)+ pinned := append([]remotemcp.Tool(nil), proxy.connection.ApprovedTools...)sort.Slice(pinned, func(i, j int) bool { return pinned[i].Name < pinned[j].Name })filtered := make([]map[string]any, 0, len(pinned))for _, tool := range pinned {current, ok := byName[tool.Name]- if !ok || plugincontract.DigestBytes(current) != tool.SchemaDigest {+ if !ok || remotemcp.DigestBytes(current) != tool.SchemaDigest {return nil, errors.New("tool schema drift")}filtered = append(filtered, map[string]any{diff --git a/server/internal/daemon/remote_mcp_broker_test.go b/server/internal/daemon/remote_mcp_broker_test.goindex 035453d17d..056179268e 100644--- a/server/internal/daemon/remote_mcp_broker_test.go+++ b/server/internal/daemon/remote_mcp_broker_test.go@@ -13,8 +13,7 @@ import ("strings""testing"- "github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/pluginruntime"+ "github.com/multica-ai/multica/server/pkg/remotemcp""github.com/multica-ai/multica/server/pkg/remotemcp/remotemcptest")@@ -31,11 +30,11 @@ func TestRemoteMCPProxyFiltersToolsAndInjectsCredential(t *testing.T) {taskID: "task", endpoint: endpoint, client: fixture.Client(), path: "/capability",credentialHeaders: http.Header{"Authorization": []string{"Bearer " + remotemcptest.Credential}},semaphore: make(chan struct{}, remoteMCPMaxConcurrency), logger: slog.New(slog.NewTextHandler(io.Discard, nil)),- connection: pluginruntime.RemoteMCPConnection{+ connection: remotemcp.Connection{InstallationID: "installation", ContributionKey: "fixture",- ApprovedTools: []pluginruntime.RemoteMCPTool{{+ ApprovedTools: []remotemcp.Tool{{Name: "fixture.read", Description: "pinned", InputSchema: canonical,- SchemaDigest: plugincontract.DigestBytes(canonical), Risk: "read",+ SchemaDigest: remotemcp.DigestBytes(canonical), Risk: "read",}},},}@@ -61,8 +60,8 @@ func TestRemoteMCPProxyFiltersToolsAndInjectsCredential(t *testing.T) {if err != nil {t.Fatal(err)}- proxy.connection.ApprovedTools = append(proxy.connection.ApprovedTools, pluginruntime.RemoteMCPTool{- Name: "fixture.write", InputSchema: writeSchema, SchemaDigest: plugincontract.DigestBytes(writeSchema), Risk: "write",+ proxy.connection.ApprovedTools = append(proxy.connection.ApprovedTools, remotemcp.Tool{+ Name: "fixture.write", InputSchema: writeSchema, SchemaDigest: remotemcp.DigestBytes(writeSchema), Risk: "write",})writeRequest := httptest.NewRequest(http.MethodPost, "/capability", strings.NewReader(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"fixture.write","arguments":{"value":"broker-write"}}}`))writeResponse := httptest.NewRecorder()@@ -80,7 +79,7 @@ func TestRemoteMCPProxyRejectsUnapprovedToolWithoutCallingUpstream(t *testing.T)proxy := &remoteMCPProxy{endpoint: endpoint, client: upstream.Client(), path: "/capability",semaphore: make(chan struct{}, remoteMCPMaxConcurrency),- connection: pluginruntime.RemoteMCPConnection{ApprovedTools: []pluginruntime.RemoteMCPTool{{Name: "allowed"}}},+ connection: remotemcp.Connection{ApprovedTools: []remotemcp.Tool{{Name: "allowed"}}},}request := httptest.NewRequest(http.MethodPost, "/capability", bytes.NewBufferString(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"denied","arguments":{"secret":"not logged"}}}`))response := httptest.NewRecorder()@@ -125,9 +124,9 @@ func TestRemoteMCPProxyRechecksCredentialBeforeUpstreamCall(t *testing.T) {proxy := &remoteMCPProxy{endpoint: endpoint, client: upstream.Client(), path: "/capability",semaphore: make(chan struct{}, remoteMCPMaxConcurrency),- connection: pluginruntime.RemoteMCPConnection{+ connection: remotemcp.Connection{ContributionID: "contribution", CredentialHeader: "Authorization",- ApprovedTools: []pluginruntime.RemoteMCPTool{{Name: "allowed"}},+ ApprovedTools: []remotemcp.Tool{{Name: "allowed"}},},resolveCredential: func(context.Context, string) (http.Header, error) {return nil, errors.New("revoked")diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex b2f9d80f2c..b21f04cf68 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -4,7 +4,7 @@ import ("encoding/json""github.com/multica-ai/multica/server/internal/runtimeapps"- "github.com/multica-ai/multica/server/pkg/pluginruntime"+ "github.com/multica-ai/multica/server/pkg/remotemcp")// AgentEntry describes a single available agent CLI.@@ -71,13 +71,12 @@ type ActiveSiblingRunData struct {// Task represents a claimed task from the server.// Agent data (name, skills) is populated by the claim endpoint.type Task struct {- ID string `json:"id"`- AgentID string `json:"agent_id"`- RuntimeID string `json:"runtime_id"`- IssueID string `json:"issue_id"`- WorkspaceID string `json:"workspace_id"`- PluginExecutionManifest *PluginExecutionManifestData `json:"plugin_execution_manifest,omitempty"`- RemoteMCPConnections []pluginruntime.RemoteMCPConnection `json:"remote_mcp_connections,omitempty"`+ ID string `json:"id"`+ AgentID string `json:"agent_id"`+ RuntimeID string `json:"runtime_id"`+ IssueID string `json:"issue_id"`+ WorkspaceID string `json:"workspace_id"`+ RemoteMCPConnections []remotemcp.Connection `json:"remote_mcp_connections,omitempty"`// RemoteMCPDaemonToken stays inside the daemon and authenticates the local// broker's credential-resolution calls. It must never enter agent env/config.RemoteMCPDaemonToken string `json:"remote_mcp_daemon_token,omitempty"`@@ -165,21 +164,6 @@ type Task struct {AuthToken string `json:"auth_token,omitempty"`}-// PluginExecutionManifestData mirrors the immutable enqueue-time plugin pin-// returned by the server. The daemon materializes its skill refs through the-// normal content-addressed cache; this record is retained on the task for run-// attribution and diagnostics.-type PluginExecutionManifestData struct {- ID string `json:"id"`- SnapshotID string `json:"snapshot_id,omitempty"`- SnapshotRevision int64 `json:"snapshot_revision"`- SnapshotDigest string `json:"snapshot_digest,omitempty"`- ComposerVersion string `json:"composer_version"`- SchemaVersion int32 `json:"schema_version"`- OrderedContributions json.RawMessage `json:"ordered_contributions"`- Diagnostics []string `json:"diagnostics,omitempty"`-}-// ChatAttachmentMeta is the structured attachment metadata the daemon// hands to the agent for chat tasks. We pass id + filename + content_type// so the chat prompt can list them explicitly and instruct the agent todiff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 7c6795c169..6e5617ce4e 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -25,8 +25,8 @@ import ("github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/pkg/agent"db "github.com/multica-ai/multica/server/pkg/db/generated"- "github.com/multica-ai/multica/server/pkg/pluginruntime""github.com/multica-ai/multica/server/pkg/protocol"+ "github.com/multica-ai/multica/server/pkg/remotemcp")// Mirrors AGENT_DESCRIPTION_MAX_LENGTH in packages/core/agents/constants.ts@@ -309,13 +309,12 @@ type ActiveSiblingRunData struct {}type AgentTaskResponse struct {- ID string `json:"id"`- AgentID string `json:"agent_id"`- RuntimeID string `json:"runtime_id"`- IssueID string `json:"issue_id"`- WorkspaceID string `json:"workspace_id"`- PluginExecutionManifest *service.PluginExecutionManifestData `json:"plugin_execution_manifest,omitempty"`- RemoteMCPConnections []pluginruntime.RemoteMCPConnection `json:"remote_mcp_connections,omitempty"`+ ID string `json:"id"`+ AgentID string `json:"agent_id"`+ RuntimeID string `json:"runtime_id"`+ IssueID string `json:"issue_id"`+ WorkspaceID string `json:"workspace_id"`+ RemoteMCPConnections []remotemcp.Connection `json:"remote_mcp_connections,omitempty"`// RemoteMCPDaemonToken is a short-lived, workspace-and-daemon scoped// credential used only by the local daemon's write-only Remote MCP broker.// It is never injected into the agent process.diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 8306de08ae..789c4dcfc4 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1880,73 +1880,6 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQuif composioMCPEnabled {resp.ConnectedApps = parseRuntimeConnectedAppsForClaim(task.RuntimeConnectedApps, task.ID)}- _, pluginSkillRefs, pluginManifest, pluginErr := h.TaskService.LoadTaskPluginSkillBundles(r.Context(), task.ID)- if pluginErr != nil {- slog.Error("daemon claim: load pinned plugin contributions failed", "task_id", uuidToString(task.ID), "error", pluginErr)- failure := h.failClaimedTaskBeforeLaunch(- r.Context(),- task,- "This task could not start because its pinned Plugin contributions are unavailable. Retry the task; if it fails again, reinstall or re-enable the Plugin.",- taskfailure.ReasonSkillBundleUnavailable,- "error_plugin_contributions",- http.StatusInternalServerError,- "pinned plugin contributions are unavailable",- )- return resp, deliveredCommentIDs, 0, 0, failure- }- resp.PluginExecutionManifest = pluginManifest- remoteConnections, remoteDiagnostics, remoteErr := h.PluginService.ResolveTaskRemoteMCPConnections(r.Context(), task.ID)- if remoteErr != nil {- slog.Error("daemon claim: resolve pinned Remote MCP contribution failed", "task_id", uuidToString(task.ID), "error", remoteErr)- failure := h.failClaimedTaskBeforeLaunch(- r.Context(),- task,- "This task could not start because a required Remote MCP contribution is unavailable. Test the Plugin connection or update its configuration, then retry.",- taskfailure.ReasonAgentMissingConfig,- "error_required_remote_mcp",- http.StatusConflict,- "required Remote MCP contribution is unavailable",- )- return resp, deliveredCommentIDs, 0, 0, failure- }- if pluginManifest != nil && len(remoteDiagnostics) > 0 {- pluginManifest.Diagnostics = append(pluginManifest.Diagnostics, remoteDiagnostics...)- }- if len(remoteConnections) > 0 && !requestHasClientCapability(r, protocol.DaemonCapabilityRemoteMCPV1) {- for _, connection := range remoteConnections {- if connection.FailurePolicy == "required" {- failure := h.failClaimedTaskBeforeLaunch(- r.Context(),- task,- "This task could not start because its runtime does not support the required Remote MCP contribution. Update the runtime, then retry.",- taskfailure.ReasonAgentRuntimeVersionUnsupported,- "error_remote_mcp_runtime_incompatible",- http.StatusConflict,- "runtime does not support this task's required Remote MCP contribution",- )- return resp, deliveredCommentIDs, 0, 0, failure- }- }- if pluginManifest != nil {- pluginManifest.Diagnostics = append(pluginManifest.Diagnostics, "optional Remote MCP contributions omitted because the runtime is incompatible")- }- remoteConnections = nil- }- resp.RemoteMCPConnections = remoteConnections- if len(pluginSkillRefs) > 0 && (!requestHasClientCapability(r, protocol.DaemonCapabilitySkillBundlesV1) ||- !requestHasClientCapability(r, protocol.DaemonCapabilityExecutionManifestV1) ||- !requestHasClientCapability(r, protocol.DaemonCapabilityAgentSkillV1)) {- failure := h.failClaimedTaskBeforeLaunch(- r.Context(),- task,- "This task could not start because its runtime does not support the Plugin's Skill contribution. Update the runtime, then retry.",- taskfailure.ReasonAgentRuntimeVersionUnsupported,- "error_plugin_skill_runtime_incompatible",- http.StatusConflict,- "runtime does not support this task's plugin execution manifest",- )- return resp, deliveredCommentIDs, 0, 0, failure- }if agent, err := h.Queries.GetAgent(r.Context(), task.AgentID); err == nil {useSkillRefs := requestHasClientCapability(r, protocol.DaemonCapabilitySkillBundlesV1)var customEnv map[string]string@@ -2035,7 +1968,6 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu}if useSkillRefs {_, skillRefs := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)- skillRefs = append(skillRefs, pluginSkillRefs...)agentSkillCount = len(skillRefs)resp.Agent.SkillRefs = skillRefs} else {@@ -3266,12 +3198,6 @@ func (h *Handler) ResolveTaskSkillBundles(w http.ResponseWriter, r *http.Request}bundles, _ := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)- pluginBundles, _, _, err := h.TaskService.LoadTaskPluginSkillBundles(r.Context(), task.ID)- if err != nil {- writeError(w, http.StatusInternalServerError, "pinned plugin contributions are unavailable")- return- }- bundles = append(bundles, pluginBundles...)allowed := make(map[string]service.AgentSkillData, len(bundles))for _, bundle := range bundles {allowed[bundle.Source+"\x00"+bundle.ID] = bundlediff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 2da7a3561b..f872877e39 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -21,8 +21,8 @@ import ("github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated"- "github.com/multica-ai/multica/server/pkg/pluginruntime""github.com/multica-ai/multica/server/pkg/protocol"+ "github.com/multica-ai/multica/server/pkg/remotemcp")func TestLogClaimEndpointSlowIncludesPayloadFields(t *testing.T) {@@ -127,7 +127,7 @@ func TestRemoteMCPDaemonTokenForClaim(t *testing.T) {DaemonID: strToText("daemon-remote-mcp"),}raw, params, err := remoteMCPDaemonTokenForClaim(AgentTaskResponse{- RemoteMCPConnections: []pluginruntime.RemoteMCPConnection{{ContributionKey: "mobbin"}},+ RemoteMCPConnections: []remotemcp.Connection{{ContributionKey: "mobbin"}},}, runtime)if err != nil {t.Fatalf("remoteMCPDaemonTokenForClaim: %v", err)diff --git a/server/internal/handler/plugin.go b/server/internal/handler/plugin.goindex 25439e7a77..1d2fcd5e9d 100644--- a/server/internal/handler/plugin.go+++ b/server/internal/handler/plugin.go@@ -4,23 +4,13 @@ import ("context""encoding/json""errors"- "io"- "log/slog""net/http"- "net/url"- "strings""github.com/go-chi/chi/v5"- "github.com/jackc/pgx/v5"- "github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/featureflags"- "github.com/multica-ai/multica/server/internal/middleware"- "github.com/multica-ai/multica/server/internal/pluginbundled""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"- "github.com/multica-ai/multica/server/pkg/pluginruntime")func (h *Handler) pluginsV1Enabled(ctx context.Context) bool {@@ -35,242 +25,134 @@ func (h *Handler) requirePluginsV1(w http.ResponseWriter, r *http.Request) boolreturn false}-type pluginBindingResponse struct {- ScopeType string `json:"scope_type"`- ScopeID string `json:"scope_id"`- Enabled bool `json:"enabled"`- 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 pluginRemoteMCPConfigResponse struct {- ContributionKey string `json:"contribution_key"`- DefaultEndpoint string `json:"default_endpoint,omitempty"`- PreferredAuth string `json:"preferred_auth,omitempty"`- SupportedAuth []string `json:"supported_auth,omitempty"`- ConfigRevision int64 `json:"config_revision,omitempty"`- Endpoint string `json:"endpoint,omitempty"`- EndpointDomain string `json:"endpoint_domain,omitempty"`- AuthType string `json:"auth_type,omitempty"`- AuthHeader string `json:"auth_header,omitempty"`- PublicConfig json.RawMessage `json:"public_config,omitempty"`- ConnectionScope string `json:"connection_scope,omitempty"`- ConnectedBy string `json:"connected_by,omitempty"`- CredentialState string `json:"credential_state"`- CredentialHint string `json:"credential_hint,omitempty"`- FailurePolicy string `json:"failure_policy,omitempty"`- ApprovedTools []pluginruntime.RemoteMCPTool `json:"approved_tools"`- DiscoveredTools []pluginruntime.RemoteMCPTool `json:"discovered_tools"`- DiscoveredDigest string `json:"discovered_schema_digest,omitempty"`- SchemaDigest string `json:"schema_digest,omitempty"`- Reviewed bool `json:"reviewed"`- Ready bool `json:"ready"`-}--func remoteMCPConfigResponseReady(config pluginRemoteMCPConfigResponse) bool {- credentialReady := config.CredentialState == "configured" || config.CredentialState == "not_required"- return config.ConfigRevision > 0 && config.Reviewed && len(config.ApprovedTools) > 0 && config.SchemaDigest != "" && credentialReady+// writePluginError maps a service error onto a status. Kinds exist so the+// handler never has to string-match a message to pick a status code.+func writePluginError(w http.ResponseWriter, err error, fallback string) {+ var pluginErr *service.PluginError+ if !errors.As(err, &pluginErr) {+ writeError(w, http.StatusInternalServerError, fallback)+ return+ }+ switch pluginErr.Kind {+ case service.PluginErrorInvalid:+ writeError(w, http.StatusBadRequest, pluginErr.Message)+ case service.PluginErrorNotFound:+ writeError(w, http.StatusNotFound, pluginErr.Message)+ case service.PluginErrorConflict:+ writeError(w, http.StatusConflict, pluginErr.Message)+ case service.PluginErrorIncompatible:+ writeError(w, http.StatusUnprocessableEntity, pluginErr.Message)+ case service.PluginErrorQuota:+ writeError(w, http.StatusInsufficientStorage, pluginErr.Message)+ default:+ writeError(w, http.StatusBadGateway, pluginErr.Message)+ }}+// pluginInstallationResponse never carries a secret value. `config` holds only+// non-secret fields by construction (SetConfig routes secrets to their own+// encrypted table), and configured secrets appear as names in+// `configured_secrets`.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"`- 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"`- RemoteMCP []pluginRemoteMCPConfigResponse `json:"remote_mcp"`-}--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)+ ID string `json:"id"`+ PluginKey string `json:"plugin_key"`+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ Version string `json:"version"`+ SourceURL string `json:"source_url"`+ Enabled bool `json:"enabled"`+ GrantedScopes []string `json:"granted_scopes"`+ ConfigSchema []service.PluginConfigField `json:"config_schema"`+ Config map[string]any `json:"config"`+ ConfiguredSecrets []string `json:"configured_secrets"`+ Surfaces []plugincontract.Surface `json:"surfaces"`+ Hooks []pluginHookResponse `json:"hooks"`+ Resources []plugincontract.Resource `json:"resources"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++// pluginHookResponse omits input_schema: the settings page lists what a hook is+// and who may call it, and the raw JSON Schema is noise there.+type pluginHookResponse struct {+ Key string `json:"key"`+ Name string `json:"name"`+ Description string `json:"description"`+ Triggers []string `json:"triggers"`+ Events []string `json:"events,omitempty"`+ Transport string `json:"transport"`+}++func (h *Handler) pluginInstallationPayload(ctx context.Context, installation db.PluginInstallation) (pluginInstallationResponse, error) {+ manifest, err := service.ParseInstallationManifest(installation)if err != nil {return pluginInstallationResponse{}, err}- desired, err := h.Queries.GetPluginRelease(r.Context(), installation.DesiredReleaseID)+ secrets, err := h.PluginService.ConfiguredSecretKeys(ctx, installation.ID)if 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,- DisplayName: identity.DisplayName,- DesiredVersion: desired.Version,- Enabled: installation.Enabled,- DesiredGeneration: 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{},- RemoteMCP: []pluginRemoteMCPConfigResponse{},- }- 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)++ config := map[string]any{}+ if len(installation.Config) > 0 {+ _ = json.Unmarshal(installation.Config, &config)}- contributions, err := h.Queries.ListPluginContributionsByRelease(r.Context(), desired.ID)- if err != nil {- return pluginInstallationResponse{}, err+ var granted []string+ if len(installation.GrantedScopes) > 0 {+ _ = json.Unmarshal(installation.GrantedScopes, &granted)}- 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,- })- if contribution.Type == plugincontract.ContributionRemoteMCPV1 {- remote := pluginRemoteMCPConfigResponse{- ContributionKey: contribution.ContributionKey,- CredentialState: "missing",- ApprovedTools: []pluginruntime.RemoteMCPTool{},- DiscoveredTools: []pluginruntime.RemoteMCPTool{},- }- for _, declaration := range manifest.Contributes.RemoteMCP {- if declaration.Key == contribution.ContributionKey {- remote.DefaultEndpoint = declaration.EndpointPolicy.DefaultEndpoint- remote.PreferredAuth = declaration.Authentication.Preferred- remote.SupportedAuth = append([]string(nil), declaration.Authentication.Supported...)- break- }- }- config, configErr := h.Queries.GetLatestPluginInstallationConfig(r.Context(), db.GetLatestPluginInstallationConfigParams{- WorkspaceID: installation.WorkspaceID, InstallationID: installation.ID, ContributionID: contribution.ID,- })- if configErr == nil {- remote.ConfigRevision = config.Revision- remote.Endpoint = config.Endpoint- remote.AuthType = config.AuthType- remote.AuthHeader = config.AuthHeader- remote.PublicConfig = append(json.RawMessage(nil), config.PublicConfig...)- remote.FailurePolicy = config.FailurePolicy- remote.SchemaDigest = config.SchemaDigest.String- remote.DiscoveredDigest = config.DiscoveredSchemaDigest.String- remote.Reviewed = config.ReviewedAt.Valid- if endpoint, parseErr := url.Parse(config.Endpoint); parseErr == nil {- remote.EndpointDomain = endpoint.Hostname()- }- _ = json.Unmarshal(config.ApprovedTools, &remote.ApprovedTools)- _ = json.Unmarshal(config.DiscoveredTools, &remote.DiscoveredTools)- if config.AuthType == "none" {- remote.CredentialState = "not_required"- } else if config.SecretRef.Valid {- secret, secretErr := h.Queries.GetActivePluginRemoteMCPSecret(r.Context(), db.GetActivePluginRemoteMCPSecretParams{- ID: config.SecretRef, WorkspaceID: installation.WorkspaceID,- InstallationID: installation.ID, ContributionID: contribution.ID,- })- if secretErr == nil {- remote.CredentialState = "configured"- remote.CredentialHint = secret.Hint- remote.ConnectedBy = uuidToString(secret.CreatedBy)- // V1 execution configs are workspace-pinned. Recording the- // connecting user now keeps the wire contract ready for a- // future per-user connection selector without exposing tokens.- remote.ConnectionScope = "workspace"- } else if errors.Is(secretErr, pgx.ErrNoRows) {- remote.CredentialState = "revoked"- }- }- } else if !errors.Is(configErr, pgx.ErrNoRows) {- return pluginInstallationResponse{}, configErr- }- remote.Ready = remoteMCPConfigResponseReady(remote)- response.RemoteMCP = append(response.RemoteMCP, remote)- }+ if granted == nil {+ granted = []string{}}- bindings, err := h.Queries.ListLatestPluginBindings(r.Context(), installation.ID)- if err != nil {- return pluginInstallationResponse{}, err- }- for _, binding := range bindings {- response.Bindings = append(response.Bindings, pluginBindingResponse{- ScopeType: binding.ScopeType,- ScopeID: uuidToString(binding.ScopeID),- Enabled: binding.Enabled,- Revision: binding.BindingRevision,++ hooks := make([]pluginHookResponse, 0, len(manifest.Contributes.Hooks))+ for _, hook := range manifest.Contributes.Hooks {+ hooks = append(hooks, pluginHookResponse{+ Key: hook.Key,+ Name: hook.Name,+ Description: hook.Description,+ Triggers: hook.Triggers,+ Events: hook.Events,+ Transport: hook.Transport.Type,})}- if installation.ActiveReleaseID.Valid {- active, err := h.Queries.GetPluginRelease(r.Context(), installation.ActiveReleaseID)- if err != nil {- return pluginInstallationResponse{}, err- }- response.ActiveVersion = active.Version+ surfaces := manifest.Contributes.Surfaces+ if surfaces == nil {+ surfaces = []plugincontract.Surface{}}- if health != nil {- response.HealthState = health.State- response.HealthReason = health.ReasonCode+ resources := manifest.Contributes.Resources+ if resources == nil {+ resources = []plugincontract.Resource{}}- return response, nil++ return pluginInstallationResponse{+ ID: uuidToString(installation.ID),+ PluginKey: installation.PluginKey,+ Name: manifest.Name,+ Description: manifest.Description,+ Version: installation.Version,+ SourceURL: installation.SourceUrl,+ Enabled: installation.Enabled,+ GrantedScopes: granted,+ ConfigSchema: service.ConfigFieldsForManifest(manifest),+ Config: config,+ ConfiguredSecrets: secrets,+ Surfaces: surfaces,+ Hooks: hooks,+ Resources: resources,+ CreatedAt: installation.CreatedAt.Time.UTC().Format(timeFormatRFC3339),+ UpdatedAt: installation.UpdatedAt.Time.UTC().Format(timeFormatRFC3339),+ }, nil}+const timeFormatRFC3339 = "2006-01-02T15:04:05Z07:00"++// ListPlugins — GET /api/workspaces/{id}/pluginsfunc (h *Handler) ListPlugins(w http.ResponseWriter, r *http.Request) {if !h.requirePluginsV1(w, r) {return}- workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")+ workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")if !ok {return}@@ -279,753 +161,165 @@ 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.requirePluginsV1(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.requirePluginsV1(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 {- key := uuidToString(health.InstallationID)- if _, exists := healthByInstallation[key]; !exists {- 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))+ payloads := make([]pluginInstallationResponse, 0, len(installations))for _, installation := range installations {- health, hasHealth := healthByInstallation[uuidToString(installation.ID)]- var healthPtr *db.PluginHealth- if hasHealth {- healthPtr = &health- }- releases := releasesByPlugin[uuidToString(installation.PluginID)]- response, err := h.pluginInstallationResponseWithReleases(r, installation, healthPtr, &releases)+ payload, err := h.pluginInstallationPayload(r.Context(), installation)if err != nil {- writeError(w, http.StatusInternalServerError, "failed to load Plugin")+ writeError(w, http.StatusInternalServerError, "failed to list Plugins")return}- responses = append(responses, response)- }- writeJSON(w, http.StatusOK, map[string]any{"plugins": responses})-}--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 []pluginContributionResponse `json:"contributions"`- Installation *pluginInstallationResponse `json:"installation,omitempty"`-}--func (h *Handler) catalogReleaseResponse(r *http.Request, workspaceID pgtype.UUID, entry pluginbundled.CatalogEntry) (pluginCatalogReleaseResponse, error) {- manifest := entry.Release.Manifest- response := pluginCatalogReleaseResponse{- PluginKey: manifest.Metadata.Key,- Name: manifest.Metadata.Name,- Description: manifest.Metadata.Description,- Version: manifest.Metadata.Version,- Publisher: manifest.Metadata.Publisher,- PublisherType: entry.PublisherType,- TrustTier: entry.TrustTier,- SourceKind: entry.Release.SourceKind,- SourceRef: entry.Release.SourceRef,- RequestedCapabilities: append([]string(nil), manifest.RequestedCapabilities...),- HostAPI: manifest.Compatibility.HostAPI,- RequiredDaemonFeatures: append([]string(nil), manifest.Compatibility.RequiredDaemonFeatures...),- SignatureKeyID: entry.Release.SignatureKeyID,- SignatureVerified: true,- ManifestDigest: entry.Release.ManifestDigest,- ArchiveDigest: entry.Release.ArchiveDigest,- ArtifactDigest: entry.Release.ArtifactDigest,- Compatible: entry.Compatible,- CompatibilityReason: entry.CompatibilityWhy,- Contributions: make([]pluginContributionResponse, 0, len(entry.Release.Contributions)),- }- for _, contribution := range entry.Release.Contributions {- response.Contributions = append(response.Contributions, pluginContributionResponse{- Key: contribution.Key,- Type: contribution.Type,- Name: contribution.DisplayName,- Description: contribution.Description,- EntryPath: contribution.EntryPath,- EntryDigest: contribution.EntryDigest,- })- }- identity, err := h.Queries.GetOfficialPluginIdentityByKey(r.Context(), manifest.Metadata.Key)- if errors.Is(err, pgx.ErrNoRows) {- return response, nil- }- if err != nil {- return pluginCatalogReleaseResponse{}, err- }- installation, err := h.Queries.GetWorkspacePluginInstallation(r.Context(), db.GetWorkspacePluginInstallationParams{- WorkspaceID: workspaceID,- PluginID: identity.ID,- })- if errors.Is(err, pgx.ErrNoRows) {- return response, nil- }- if err != nil {- return pluginCatalogReleaseResponse{}, err- }- installed, err := h.pluginInstallationResponse(r, installation, nil)- if err != nil {- return pluginCatalogReleaseResponse{}, err+ payloads = append(payloads, payload)}- response.Installation = &installed- return response, nil+ writeJSON(w, http.StatusOK, map[string]any{"plugins": payloads})}-func (h *Handler) ListPluginCatalog(w http.ResponseWriter, r *http.Request) {- if !h.requirePluginsV1(w, r) {- return- }- workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")- if !ok {- return- }- entries := h.PluginService.CatalogEntries()- responses := make([]pluginCatalogReleaseResponse, 0, len(entries))- for _, entry := range entries {- response, err := h.catalogReleaseResponse(r, workspaceID, entry)- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to load Plugin catalog")- return- }- responses = append(responses, response)- }- diagnostics := h.PluginService.CatalogDiagnostics()- if diagnostics == nil {- diagnostics = []pluginbundled.Diagnostic{}- }- writeJSON(w, http.StatusOK, map[string]any{- "releases": responses,- "diagnostics": diagnostics,- })+type previewPluginRequest struct {+ SourceURL string `json:"source_url"`}-func (h *Handler) GetPluginCatalogRelease(w http.ResponseWriter, r *http.Request) {+// PreviewPlugin — POST /api/workspaces/{id}/plugins/preview+//+// Step one of the two-step install. Nothing is written: the response exists so+// the administrator can read the scope list before consenting.+func (h *Handler) PreviewPlugin(w http.ResponseWriter, r *http.Request) {if !h.requirePluginsV1(w, r) {return}- workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")+ workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")if !ok {return}- entry, found := h.PluginService.FindCatalogRelease(chi.URLParam(r, "pluginKey"), r.URL.Query().Get("version"))- if !found {- writeError(w, http.StatusNotFound, "Plugin release not found")+ var req previewPluginRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")return}- response, err := h.catalogReleaseResponse(r, workspaceID, entry)+ preview, err := h.PluginService.PreviewPlugin(r.Context(), workspaceID, req.SourceURL)if err != nil {- writeError(w, http.StatusInternalServerError, "failed to load Plugin catalog")+ writePluginError(w, err, "failed to read the Plugin manifest")return}- writeJSON(w, http.StatusOK, response)+ writeJSON(w, http.StatusOK, preview)}-type pluginReleaseRequest struct {- PluginKey string `json:"plugin_key"`- Version string `json:"version"`+type installPluginRequest struct {+ SourceURL string `json:"source_url"`+ GrantedScopes []string `json:"granted_scopes"`}+// InstallPlugin — POST /api/workspaces/{id}/pluginsfunc (h *Handler) InstallPlugin(w http.ResponseWriter, r *http.Request) {if !h.requirePluginsV1(w, r) {return}- workspaceID, actorID, ok := pluginRequestIDs(w, r)+ workspaceIDString := workspaceIDFromURL(r, "id")+ workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDString, "workspace_id")if !ok {return}- var request pluginReleaseRequest- if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.PluginKey == "" || request.Version == "" {- writeError(w, http.StatusBadRequest, "plugin_key and version are required")- return- }- installation, err := h.PluginService.InstallCatalogRelease(r.Context(), workspaceID, actorID, request.PluginKey, request.Version)- 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 Plugin")- return- }- writeJSON(w, http.StatusCreated, response)-}--func (h *Handler) InstallPrivatePlugin(w http.ResponseWriter, r *http.Request) {- if !h.requirePluginsV1(w, r) {- return- }- workspaceID, actorID, ok := pluginRequestIDs(w, r)+ member, ok := h.workspaceMember(w, r, workspaceIDString)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- }- if _, validateErr := plugincontract.ValidateArtifact(archive); validateErr != nil {- writeError(w, http.StatusBadRequest, "Private Plugin package is invalid")+ var req installPluginRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")return}- installation, err := h.PluginService.InstallPrivateArchive(r.Context(), workspaceID, actorID, archive)+ installation, err := h.PluginService.InstallPlugin(r.Context(), workspaceID, member.UserID, req.SourceURL, req.GrantedScopes)if err != nil {- writePluginError(w, r, err)+ writePluginError(w, err, "failed to install the Plugin")return}- response, err := h.pluginInstallationResponse(r, installation, nil)+ payload, err := h.pluginInstallationPayload(r.Context(), installation)if err != nil {- writeError(w, http.StatusInternalServerError, "failed to load Private Plugin")+ writeError(w, http.StatusInternalServerError, "failed to install the Plugin")return}- writeJSON(w, http.StatusCreated, response)+ writeJSON(w, http.StatusCreated, payload)}-func (h *Handler) UpgradePlugin(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")+type configurePluginRequest struct {+ Values map[string]any `json:"values"`+}++// ConfigurePlugin — PUT /api/workspaces/{id}/plugins/{installationId}/config+func (h *Handler) ConfigurePlugin(w http.ResponseWriter, r *http.Request) {+ installation, ok := h.pluginInstallationFromURL(w, r)if !ok {return}- if !h.requirePluginInstallation(w, r, workspaceID, installationID) {- return- }- var request pluginReleaseRequest- if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.PluginKey == "" || request.Version == "" {- writeError(w, http.StatusBadRequest, "plugin_key and version are required")+ var req configurePluginRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")return}- installation, err := h.PluginService.UpgradeCatalogRelease(r.Context(), workspaceID, installationID, actorID, request.PluginKey, request.Version)+ updated, err := h.PluginService.SetConfig(r.Context(), installation, req.Values)if err != nil {- writePluginError(w, r, err)+ writePluginError(w, err, "failed to configure the Plugin")return}- response, err := h.pluginInstallationResponse(r, installation, nil)+ payload, err := h.pluginInstallationPayload(r.Context(), updated)if err != nil {- writeError(w, http.StatusInternalServerError, "failed to load Plugin")+ writeError(w, http.StatusInternalServerError, "failed to configure the Plugin")return}- writeJSON(w, http.StatusOK, response)-}--type pluginBindingRequest struct {- ScopeType string `json:"scope_type"`- ScopeID string `json:"scope_id"`+ writeJSON(w, http.StatusOK, payload)}+// EnablePlugin — POST /api/workspaces/{id}/plugins/{installationId}/enablefunc (h *Handler) EnablePlugin(w http.ResponseWriter, r *http.Request) {- if !h.requirePluginsV1(w, r) {- return- }h.setPluginEnabled(w, r, true)}+// DisablePlugin — POST /api/workspaces/{id}/plugins/{installationId}/disablefunc (h *Handler) DisablePlugin(w http.ResponseWriter, r *http.Request) {- if !h.requirePluginsV1(w, r) {- return- }h.setPluginEnabled(w, r, false)}func (h *Handler) setPluginEnabled(w http.ResponseWriter, r *http.Request, enabled bool) {- workspaceID, actorID, ok := pluginRequestIDs(w, r)- if !ok {- return- }- installationID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation_id")+ installation, ok := h.pluginInstallationFromURL(w, r)if !ok {return}- if !h.requirePluginInstallation(w, r, workspaceID, installationID) {- 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 {- writeError(w, http.StatusBadRequest, "invalid request body")- return- }- }- if request.ScopeType == "workspace" && request.ScopeID == "" {- request.ScopeID = uuidToString(workspaceID)- }- scopeID, ok := parseUUIDOrBadRequest(w, request.ScopeID, "scope_id")- if !ok {- return- }- var installation db.PluginInstallation- var err error- if enabled {- installation, err = h.PluginService.EnablePlugin(r.Context(), workspaceID, installationID, actorID, request.ScopeType, scopeID)- } else {- installation, err = h.PluginService.DisablePlugin(r.Context(), workspaceID, installationID, actorID, request.ScopeType, scopeID)- }- 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 Plugin")- return- }- writeJSON(w, http.StatusOK, response)-}--func (h *Handler) RollbackPlugin(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.requirePluginInstallation(w, r, workspaceID, installationID) {- return- }- var request struct {- Version string `json:"version"`- }- if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.Version == "" {- writeError(w, http.StatusBadRequest, "version is required")- return- }- installation, err := h.PluginService.RollbackPlugin(r.Context(), workspaceID, installationID, actorID, request.Version)+ updated, err := h.PluginService.SetEnabled(r.Context(), installation, enabled)if err != nil {- writePluginError(w, r, err)+ writePluginError(w, err, "failed to update the Plugin")return}- response, err := h.pluginInstallationResponse(r, installation, nil)+ payload, err := h.pluginInstallationPayload(r.Context(), updated)if err != nil {- writeError(w, http.StatusInternalServerError, "failed to load Plugin")+ writeError(w, http.StatusInternalServerError, "failed to update the Plugin")return}- writeJSON(w, http.StatusOK, response)+ writeJSON(w, http.StatusOK, payload)}+// UninstallPlugin — DELETE /api/workspaces/{id}/plugins/{installationId}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.requirePluginInstallation(w, r, workspaceID, installationID) {- return- }- if err := h.PluginService.UninstallPlugin(r.Context(), workspaceID, installationID, actorID); err != nil {- writePluginError(w, r, err)- return- }- w.WriteHeader(http.StatusNoContent)-}--type remoteMCPConfigRequest struct {- Endpoint string `json:"endpoint"`- PublicConfig json.RawMessage `json:"public_config"`- AuthType string `json:"auth_type"`- AuthHeader string `json:"auth_header"`- Credential string `json:"credential"`- FailurePolicy string `json:"failure_policy"`-}--type remoteMCPOAuthStartRequest struct {- Endpoint string `json:"endpoint"`- PublicConfig json.RawMessage `json:"public_config"`- FailurePolicy string `json:"failure_policy"`- Scope string `json:"scope"`- ClientID string `json:"client_id"`- ClientSecret string `json:"client_secret"`- TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`- AuthorizationEndpoint string `json:"authorization_endpoint"`- TokenEndpoint string `json:"token_endpoint"`- ReturnTo string `json:"return_to"`-}--const remoteMCPOAuthCallbackPath = "/api/plugins/remote-mcp/oauth/callback"--func (h *Handler) StartPluginRemoteMCPOAuth(w http.ResponseWriter, r *http.Request) {- workspaceID, actorID, installationID, ok := h.remoteMCPRequestIDs(w, r)- if !ok {- return- }- var request remoteMCPOAuthStartRequest- if err := json.NewDecoder(r.Body).Decode(&request); err != nil {- writeError(w, http.StatusBadRequest, "invalid request body")- return- }- callbackBase := strings.TrimRight(h.cfg.PublicURL, "/")- if callbackBase == "" {- writeError(w, http.StatusServiceUnavailable, "MULTICA_PUBLIC_URL is required for Remote MCP OAuth")- return- }- result, err := h.PluginService.BeginRemoteMCPOAuth(r.Context(), workspaceID, installationID, actorID, chi.URLParam(r, "contributionKey"), service.RemoteMCPOAuthStartInput{- Endpoint: request.Endpoint, PublicConfig: request.PublicConfig, FailurePolicy: request.FailurePolicy,- Scope: request.Scope, ClientID: request.ClientID, ClientSecret: request.ClientSecret,- TokenEndpointAuthMethod: request.TokenEndpointAuthMethod,- AuthorizationEndpoint: request.AuthorizationEndpoint, TokenEndpoint: request.TokenEndpoint,- RedirectURI: callbackBase + remoteMCPOAuthCallbackPath, ReturnTo: request.ReturnTo,- })- if err != nil {- writePluginError(w, r, err)- return- }- writeJSON(w, http.StatusOK, map[string]string{"authorization_url": result.AuthorizationURL})-}--// CompletePluginRemoteMCPOAuth is intentionally public. The single-use,-// short-lived state hash carries the installation and actor identity; browser-// cookies are neither required nor trusted on this cross-site callback.-func (h *Handler) CompletePluginRemoteMCPOAuth(w http.ResponseWriter, r *http.Request) {- if !h.requirePluginsV1(w, r) {- return- }- result, err := h.PluginService.CompleteRemoteMCPOAuth(r.Context(), r.URL.Query().Get("state"), r.URL.Query().Get("code"))- if err != nil {- providerError := strings.TrimSpace(r.URL.Query().Get("error"))- if len(providerError) > 128 {- providerError = providerError[:128]- }- errorKind := "internal"- errorMessage := "Remote MCP OAuth callback failed"- var pluginErr *service.PluginError- if errors.As(err, &pluginErr) {- errorKind = string(pluginErr.Kind)- errorMessage = pluginErr.Message- }- slog.Warn("Remote MCP OAuth callback failed",- "error_kind", errorKind,- "error_message", errorMessage,- "provider_error", providerError,- "has_state", r.URL.Query().Get("state") != "",- "has_code", r.URL.Query().Get("code") != "",- )- }- returnTo := result.ReturnTo- if returnTo == "" {- returnTo = "/"- }- parsed, parseErr := url.Parse(returnTo)- if parseErr != nil || parsed.IsAbs() || parsed.Host != "" || !strings.HasPrefix(parsed.Path, "/") || strings.HasPrefix(parsed.Path, "//") {- parsed = &url.URL{Path: "/"}- }- query := parsed.Query()- if err == nil {- query.Set("remote_mcp_connected", "1")- } else {- query.Set("remote_mcp_error", "connect_failed")- }- parsed.RawQuery = query.Encode()- destination := parsed.String()- if appURL := resolveFrontendAppURL(); appURL != "" {- destination = strings.TrimRight(appURL, "/") + destination- }- http.Redirect(w, r, destination, http.StatusFound)-}--func (h *Handler) ConfigurePluginRemoteMCP(w http.ResponseWriter, r *http.Request) {- workspaceID, actorID, installationID, ok := h.remoteMCPRequestIDs(w, r)- if !ok {- return- }- var request remoteMCPConfigRequest- if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.Endpoint == "" {- writeError(w, http.StatusBadRequest, "endpoint is required")- return- }- result, err := h.PluginService.ConfigureRemoteMCP(r.Context(), workspaceID, installationID, actorID, chi.URLParam(r, "contributionKey"), service.RemoteMCPConfigInput{- Endpoint: request.Endpoint, PublicConfig: request.PublicConfig, AuthType: request.AuthType,- AuthHeader: request.AuthHeader, Credential: request.Credential, FailurePolicy: request.FailurePolicy,- })- if err != nil {- writePluginError(w, r, err)- return- }- writeJSON(w, http.StatusOK, map[string]any{- "config_revision": result.Config.Revision,- "credential_state": credentialState(result.Config),- "reviewed": false,- "discovered_tools": result.DiscoveredTools,- "discovered_schema_digest": result.SchemaDigest,- })-}--func (h *Handler) TestPluginRemoteMCP(w http.ResponseWriter, r *http.Request) {- workspaceID, _, installationID, ok := h.remoteMCPRequestIDs(w, r)- if !ok {- return- }- result, err := h.PluginService.TestRemoteMCP(r.Context(), workspaceID, installationID, chi.URLParam(r, "contributionKey"))- if err != nil {- writePluginError(w, r, err)- return- }- writeJSON(w, http.StatusOK, map[string]any{- "ok": true, "config_revision": result.Config.Revision,- "discovered_tools": result.DiscoveredTools, "discovered_schema_digest": result.SchemaDigest,- })-}--func (h *Handler) ReviewPluginRemoteMCPTools(w http.ResponseWriter, r *http.Request) {- workspaceID, actorID, installationID, ok := h.remoteMCPRequestIDs(w, r)+ installation, ok := h.pluginInstallationFromURL(w, r)if !ok {return}- var request struct {- Tools []string `json:"tools"`- }- if err := json.NewDecoder(r.Body).Decode(&request); err != nil {- writeError(w, http.StatusBadRequest, "tools are required")- return- }- result, err := h.PluginService.ReviewRemoteMCPTools(r.Context(), workspaceID, installationID, actorID, chi.URLParam(r, "contributionKey"), request.Tools)- if err != nil {- writePluginError(w, r, err)- return- }- writeJSON(w, http.StatusOK, map[string]any{- "config_revision": result.Config.Revision, "reviewed": true,- "approved_tools": request.Tools, "schema_digest": result.SchemaDigest,- })-}--func (h *Handler) RevokePluginRemoteMCPCredential(w http.ResponseWriter, r *http.Request) {- workspaceID, actorID, installationID, ok := h.remoteMCPRequestIDs(w, r)- if !ok {- return- }- if err := h.PluginService.RevokeRemoteMCPCredential(r.Context(), workspaceID, installationID, actorID, chi.URLParam(r, "contributionKey")); err != nil {- writePluginError(w, r, err)+ if err := h.PluginService.Uninstall(r.Context(), installation); err != nil {+ writePluginError(w, err, "failed to uninstall the Plugin")return}w.WriteHeader(http.StatusNoContent)}-// ResolveTaskRemoteMCPCredential is daemon-only and intentionally returns-// write-only credential material. Management APIs and provider configuration-// never call this route. Every request re-checks the active scoped secret so-// revocation takes effect for running brokers before their next upstream call.-func (h *Handler) ResolveTaskRemoteMCPCredential(w http.ResponseWriter, r *http.Request) {- // DaemonAuth also accepts user PATs/JWTs for legacy daemon routes. This- // endpoint returns secret material, so it deliberately requires the- // workspace-scoped daemon-token path instead of that compatibility fallback.- if middleware.DaemonAuthPathFromContext(r.Context()) != middleware.DaemonAuthPathDaemonToken {- writeError(w, http.StatusForbidden, "daemon token required")- return- }- task, ok := h.requireDaemonTaskAccess(w, r, chi.URLParam(r, "taskId"))- if !ok {- return- }- // A daemon token is workspace scoped, but the credential belongs to the- // concrete machine executing this task. Do not let another daemon in the- // same workspace use its own token to resolve this task's secret.- runtime, err := h.Queries.GetAgentRuntime(r.Context(), task.RuntimeID)- if err != nil {- if !isNotFound(err) {- slog.Warn("load Remote MCP task runtime failed", "task_id", uuidToString(task.ID), "error", err)- writeError(w, http.StatusInternalServerError, "failed to load task runtime")- return- }- writeError(w, http.StatusNotFound, "task not found")- return- }- if !runtime.DaemonID.Valid || runtime.DaemonID.String != middleware.DaemonIDFromContext(r.Context()) {- writeError(w, http.StatusNotFound, "task not found")- return- }- header, credential, err := h.PluginService.ResolveTaskRemoteMCPCredential(r.Context(), task.ID, chi.URLParam(r, "contributionId"))- if err != nil {- writePluginError(w, r, err)- return- }- w.Header().Set("Cache-Control", "no-store")- writeJSON(w, http.StatusOK, map[string]string{"credential_header": header, "credential": credential})-}--func (h *Handler) remoteMCPRequestIDs(w http.ResponseWriter, r *http.Request) (pgtype.UUID, pgtype.UUID, pgtype.UUID, bool) {+func (h *Handler) pluginInstallationFromURL(w http.ResponseWriter, r *http.Request) (db.PluginInstallation, bool) {if !h.requirePluginsV1(w, r) {- return pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, false- }- workspaceID, actorID, ok := pluginRequestIDs(w, r)- if !ok {- return pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, false- }- installationID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation_id")- if !ok {- return pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, false- }- if !h.requirePluginInstallation(w, r, workspaceID, installationID) {- return pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, false- }- return workspaceID, actorID, installationID, true-}--func credentialState(config db.PluginInstallationConfig) string {- if config.AuthType == "none" {- return "not_required"+ return db.PluginInstallation{}, false}- return "configured"-}--func (h *Handler) requirePluginInstallation(w http.ResponseWriter, r *http.Request, workspaceID, installationID pgtype.UUID) 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- }- return true-}--func writePluginError(w http.ResponseWriter, r *http.Request, err error) {- var pluginErr *service.PluginError- if !errors.As(err, &pluginErr) {- slog.Error("Plugin request failed", "method", r.Method, "path", r.URL.Path, "error", err)- writeError(w, http.StatusInternalServerError, "Plugin operation failed")- return- }- status := http.StatusInternalServerError- switch pluginErr.Kind {- case service.PluginErrorInvalid:- status = http.StatusBadRequest- case service.PluginErrorNotFound:- status = http.StatusNotFound- case service.PluginErrorConflict:- status = http.StatusConflict- case service.PluginErrorIncompatible:- status = http.StatusUnprocessableEntity- default:- slog.Error("Plugin request returned unknown classified error", "error", err)- writeError(w, http.StatusInternalServerError, "Plugin operation failed")- return- }- writeError(w, status, pluginErr.Message)-}--func pluginRequestIDs(w http.ResponseWriter, r *http.Request) (pgtype.UUID, pgtype.UUID, bool) {- workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")+ workspaceID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace_id")if !ok {- return pgtype.UUID{}, pgtype.UUID{}, false+ return db.PluginInstallation{}, false}- actorID, err := util.ParseUUID(requestUserID(r))+ installation, err := h.PluginService.InstallationForWorkspace(r.Context(), workspaceID, chi.URLParam(r, "installationId"))if err != nil {- writeError(w, http.StatusUnauthorized, "authentication required")- return pgtype.UUID{}, pgtype.UUID{}, false+ writePluginError(w, err, "failed to load the Plugin")+ return db.PluginInstallation{}, false}- return workspaceID, actorID, true+ return installation, true}diff --git a/server/internal/handler/plugin_test.go b/server/internal/handler/plugin_test.goindex 1784e86ac7..a821ff675f 100644--- a/server/internal/handler/plugin_test.go+++ b/server/internal/handler/plugin_test.go@@ -4,52 +4,39 @@ import ("bytes""context""encoding/json"- "errors"- "mime/multipart""net/http""net/http/httptest"+ "os""path/filepath""strings""testing""github.com/go-chi/chi/v5"- "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/internal/middleware"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/util/secretbox""github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/pluginruntime")-type failPluginDetailQueryDB struct {- db.DBTX- queryFragment string- queryRowFragment string- failQueryRowAtMatch int- queryRowMatches int-}--func (database *failPluginDetailQueryDB) Query(ctx context.Context, query string, args ...any) (pgx.Rows, error) {- if database.queryFragment != "" && strings.Contains(query, database.queryFragment) {- return nil, errors.New("forced Plugin detail query failure")- }- return database.DBTX.Query(ctx, query, args...)-}--type pluginDetailErrorRow struct{}--func (pluginDetailErrorRow) Scan(...any) error {- return errors.New("forced Plugin detail query failure")-}--func (database *failPluginDetailQueryDB) QueryRow(ctx context.Context, query string, args ...any) pgx.Row {- if database.queryRowFragment != "" && strings.Contains(query, database.queryRowFragment) {- database.queryRowMatches++- if database.queryRowMatches == database.failQueryRowAtMatch {- return pluginDetailErrorRow{}- }- }- return database.DBTX.QueryRow(ctx, query, args...)-}+// The reference manifest for handler tests declares only capabilities this+// build ships. Contribution kinds that are still gated are covered by the+// capability matrix in pkg/plugincontract; repeating them here would just+// re-run that matrix through HTTP.+const handlerTestManifest = `{+ "manifest_version": 1,+ "key": "com.example.hello",+ "name": "Hello Panel",+ "version": "1.0.0",+ "author": { "name": "example" },+ "scopes": ["issues:read", "comments:write", "storage:user"],+ "config": {+ "repo": { "type": "string", "label": "Repo", "required": true },+ "token": { "type": "secret", "label": "Token" }+ },+ "contributes": {+ "surfaces": [{ "key": "hello", "type": "issue_panel", "name": "Hello", "entry": "ui/main.js" }]+ }+}`func pluginHandlerRequest(method, path string, body []byte, params map[string]string) *http.Request {request := httptest.NewRequest(method, path, bytes.NewReader(body))@@ -62,385 +49,406 @@ func pluginHandlerRequest(method, path string, body []byte, params map[string]streturn request.WithContext(context.WithValue(request.Context(), chi.RouteCtxKey, routeContext))}-func TestRemoteMCPConfigResponseReady(t *testing.T) {- ready := pluginRemoteMCPConfigResponse{- ConfigRevision: 1, CredentialState: "configured", Reviewed: true,- ApprovedTools: []pluginruntime.RemoteMCPTool{{Name: "search"}}, SchemaDigest: "sha256:test",+func writeLocalPluginManifest(t *testing.T, root, manifest string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Join(root, "hello"), 0o755); err != nil {+ t.Fatalf("create local plugin dir: %v", err)+ }+ if err := os.WriteFile(filepath.Join(root, "hello", plugincontract.ManifestFilename), []byte(manifest), 0o644); err != nil {+ t.Fatalf("write local manifest: %v", err)}- if !remoteMCPConfigResponseReady(ready) {- t.Fatal("complete Remote MCP configuration was not ready")+}++// withLocalPluginSource points the service at a temp MULTICA_PLUGIN_DIR and+// enables every capability, so these tests exercise the HTTP surface rather+// than the staged-rollout gate.+func withLocalPluginSource(t *testing.T, manifest string) string {+ t.Helper()+ return withLocalPluginSourceIn(t, t.TempDir(), manifest)+}++// withLocalPluginSourceIn takes the root explicitly so an upgrade test can+// rewrite the manifest in place and install again from the same source URL.+func withLocalPluginSourceIn(t *testing.T, root string, manifest string) string {+ t.Helper()+ writeLocalPluginManifest(t, root, manifest)++ previousDir := testHandler.PluginService.LocalDir+ previousHost := testHandler.PluginService.Host+ previousSecrets := testHandler.PluginService.Secrets+ testHandler.PluginService.LocalDir = root+ testHandler.PluginService.Host = plugincontract.Capabilities{+ SurfaceTypes: map[string]bool{plugincontract.SurfaceIssuePanel: true, plugincontract.SurfaceSidebarPanel: true, plugincontract.SurfaceModal: true},+ HookTriggers: map[string]bool{plugincontract.TriggerUI: true, plugincontract.TriggerManual: true, plugincontract.TriggerAgent: true, plugincontract.TriggerEvent: true},+ HookTransport: map[string]bool{plugincontract.TransportHTTP: true, plugincontract.TransportMCP: true},+ ResourceTypes: map[string]bool{plugincontract.ResourceSkill: true},+ }+ box, err := secretbox.New(bytes.Repeat([]byte{7}, 32))+ if err != nil {+ t.Fatalf("secretbox.New: %v", err)+ }+ testHandler.PluginService.Secrets = box+ t.Cleanup(func() {+ testHandler.PluginService.LocalDir = previousDir+ testHandler.PluginService.Host = previousHost+ testHandler.PluginService.Secrets = previousSecrets+ })+ return service.LocalSourcePrefix + "hello"+}++func cleanupPluginInstallations(t *testing.T) {+ t.Helper()+ remove := func() {+ ctx := context.Background()+ testPool.Exec(ctx, `DELETE FROM plugin_storage WHERE installation_id IN (SELECT id FROM plugin_installation WHERE workspace_id = $1)`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM plugin_secret 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)}- for name, edit := range map[string]func(*pluginRemoteMCPConfigResponse){- "missing config": func(config *pluginRemoteMCPConfigResponse) { config.ConfigRevision = 0 },- "missing credential": func(config *pluginRemoteMCPConfigResponse) { config.CredentialState = "missing" },- "unreviewed": func(config *pluginRemoteMCPConfigResponse) { config.Reviewed = false },- "no approved tools": func(config *pluginRemoteMCPConfigResponse) { config.ApprovedTools = nil },- "missing digest": func(config *pluginRemoteMCPConfigResponse) { config.SchemaDigest = "" },+ remove()+ t.Cleanup(remove)+}++func TestPluginManagementRequiresPluginsV1(t *testing.T) {+ withPluginsV1Flag(t, testHandler, false)+ for name, handler := range map[string]http.HandlerFunc{+ "list": testHandler.ListPlugins,+ "preview": testHandler.PreviewPlugin,+ "install": testHandler.InstallPlugin,+ "configure": testHandler.ConfigurePlugin,+ "enable": testHandler.EnablePlugin,+ "disable": testHandler.DisablePlugin,+ "uninstall": testHandler.UninstallPlugin,} {t.Run(name, func(t *testing.T) {- config := ready- edit(&config)- if remoteMCPConfigResponseReady(config) {- t.Fatal("incomplete Remote MCP configuration was ready")+ recorder := httptest.NewRecorder()+ handler(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", []byte(`{}`), map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusServiceUnavailable {+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())}})}}-func TestPluginHTTPLifecycleForInstalledReferenceRelease(t *testing.T) {+func TestPluginPreviewShowsScopesWithoutInstalling(t *testing.T) {withPluginsV1Flag(t, testHandler, 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 activity_log WHERE workspace_id = $1 AND action = 'plugin_uninstalled'`, testWorkspaceID)- }- cleanup()- t.Cleanup(cleanup)+ cleanupPluginInstallations(t)+ source := withLocalPluginSource(t, handlerTestManifest)recorder := httptest.NewRecorder()- testHandler.ListPluginCatalog(recorder, pluginHandlerRequest(http.MethodGet, "/plugins/catalog", nil, map[string]string{"id": testWorkspaceID}))- if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte(`"signature_verified":true`)) || !bytes.Contains(recorder.Body.Bytes(), []byte(plugintest.ReviewReadinessPluginKey)) {- t.Fatalf("catalog status=%d body=%s", recorder.Code, recorder.Body.String())+ body, _ := json.Marshal(map[string]string{"source_url": source})+ testHandler.PreviewPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/preview", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusOK {+ t.Fatalf("preview status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ var preview service.PluginPreview+ if err := json.Unmarshal(recorder.Body.Bytes(), &preview); err != nil {+ t.Fatalf("decode preview: %v", err)+ }+ if len(preview.Scopes) != 3 || preview.Installed {+ t.Fatalf("unexpected preview: %+v", preview)+ }+ if len(preview.ConfigSchema) != 2 || preview.ConfigSchema[0].Key != "repo" || preview.ConfigSchema[1].Type != plugincontract.ConfigSecret {+ t.Fatalf("unexpected config schema: %+v", preview.ConfigSchema)}- var catalogPayload struct {- Diagnostics json.RawMessage `json:"diagnostics"`++ // Preview must be side-effect free: the consent screen has to be able to+ // show scopes before anything exists to revoke.+ listRecorder := httptest.NewRecorder()+ testHandler.ListPlugins(listRecorder, pluginHandlerRequest(http.MethodGet, "/plugins", nil, map[string]string{"id": testWorkspaceID}))+ if listRecorder.Code != http.StatusOK {+ t.Fatalf("list status=%d body=%s", listRecorder.Code, listRecorder.Body.String())+ }+ var list struct {+ Plugins []map[string]any `json:"plugins"`}- if err := json.Unmarshal(recorder.Body.Bytes(), &catalogPayload); err != nil {- t.Fatalf("decode catalog: %v", err)+ if err := json.Unmarshal(listRecorder.Body.Bytes(), &list); err != nil {+ t.Fatalf("decode list: %v", err)}- if !bytes.Equal(catalogPayload.Diagnostics, []byte(`[]`)) {- t.Fatalf("empty catalog diagnostics must be an array, got %s", catalogPayload.Diagnostics)+ if len(list.Plugins) != 0 {+ t.Fatalf("preview created an installation: %v", list.Plugins)}+}++func TestPluginInstallRequiresExactConsent(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ source := withLocalPluginSource(t, handlerTestManifest)+ partial, _ := json.Marshal(map[string]any{"source_url": source, "granted_scopes": []string{"issues:read"}})+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", partial, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusConflict {+ t.Fatalf("partial consent status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ extra, _ := json.Marshal(map[string]any{+ "source_url": source,+ "granted_scopes": []string{"issues:read", "comments:write", "storage:user", "issues:write"},+ })recorder = httptest.NewRecorder()- testHandler.InstallPlugin(recorder, pluginHandlerRequest(- http.MethodPost,- "/plugins/install",- []byte(`{"plugin_key":"ai.multica.software-delivery","version":"1.0.0"}`),- map[string]string{"id": testWorkspaceID},- ))+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", extra, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusConflict {+ t.Fatalf("over-consent status=%d body=%s", recorder.Code, recorder.Body.String())+ }+}++func TestPluginInstallConfigureAndUninstall(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ source := withLocalPluginSource(t, handlerTestManifest)++ install, _ := json.Marshal(map[string]any{+ "source_url": source,+ "granted_scopes": []string{"issues:read", "comments:write", "storage:user"},+ })+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", install, map[string]string{"id": testWorkspaceID}))if recorder.Code != http.StatusCreated {t.Fatalf("install status=%d body=%s", recorder.Code, recorder.Body.String())}- var installed pluginInstallationResponse+ var installed struct {+ ID string `json:"id"`+ PluginKey string `json:"plugin_key"`+ Enabled bool `json:"enabled"`+ Config map[string]any `json:"config"`+ ConfiguredSecrets []string `json:"configured_secrets"`+ }if err := json.Unmarshal(recorder.Body.Bytes(), &installed); err != nil {t.Fatalf("decode installation: %v", err)}- if installed.Enabled || installed.LifecycleStatus != "installed" {- t.Fatalf("install must remain disabled: %+v", installed)+ if installed.ID == "" || installed.PluginKey != "com.example.hello" || !installed.Enabled {+ t.Fatalf("unexpected installation: %+v", installed)}params := map[string]string{"id": testWorkspaceID, "installationId": installed.ID}+ configure, _ := json.Marshal(map[string]any{"values": map[string]any{"repo": "multica-ai/multica", "token": "sk-super-secret"}})recorder = httptest.NewRecorder()- testHandler.EnablePlugin(recorder, pluginHandlerRequest(- http.MethodPost,- "/plugins/enable",- []byte(`{"scope_type":"workspace","scope_id":"00000000-0000-0000-0000-000000000001"}`),- params,- ))- if recorder.Code != http.StatusNotFound || bytes.Contains(recorder.Body.Bytes(), []byte("no rows")) {- t.Fatalf("cross-workspace binding status=%d body=%s", recorder.Code, recorder.Body.String())- }-- recorder = httptest.NewRecorder()- testHandler.EnablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/enable", nil, params))+ testHandler.ConfigurePlugin(recorder, pluginHandlerRequest(http.MethodPut, "/plugins/config", configure, params))if recorder.Code != http.StatusOK {- t.Fatalf("enable status=%d body=%s", recorder.Code, recorder.Body.String())+ t.Fatalf("configure status=%d body=%s", recorder.Code, recorder.Body.String())}-- 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(plugintest.ReviewReadinessPluginKey)) {- t.Fatalf("list status=%d body=%s", recorder.Code, recorder.Body.String())- }- for _, test := range []struct {- name string- queryFragment string- queryRowFragment string- failQueryRowAtMatch int- }{- {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) {- failingHandler := *testHandler- failingHandler.Queries = db.New(&failPluginDetailQueryDB{- DBTX: testPool,- queryFragment: test.queryFragment,- queryRowFragment: test.queryRowFragment,- failQueryRowAtMatch: test.failQueryRowAtMatch,- })- recorder := httptest.NewRecorder()- failingHandler.ListPlugins(recorder, pluginHandlerRequest(http.MethodGet, "/plugins", nil, map[string]string{"id": testWorkspaceID}))- if recorder.Code != http.StatusInternalServerError {- t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())- }- })+ // The secret must not come back in any form: not in `config`, not masked,+ // not anywhere else in the payload.+ if strings.Contains(recorder.Body.String(), "sk-super-secret") {+ t.Fatalf("configure response leaked the secret value: %s", recorder.Body.String())+ }+ var configured struct {+ Config map[string]any `json:"config"`+ ConfiguredSecrets []string `json:"configured_secrets"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &configured); err != nil {+ t.Fatalf("decode configured installation: %v", err)+ }+ if configured.Config["repo"] != "multica-ai/multica" {+ t.Fatalf("plain config value was not stored: %v", configured.Config)+ }+ if _, present := configured.Config["token"]; present {+ t.Fatalf("secret value was stored in config: %v", configured.Config)+ }+ if len(configured.ConfiguredSecrets) != 1 || configured.ConfiguredSecrets[0] != "token" {+ t.Fatalf("configured secrets = %v, want [token]", configured.ConfiguredSecrets)}recorder = httptest.NewRecorder()- testHandler.UpgradePlugin(recorder, pluginHandlerRequest(- http.MethodPost,- "/plugins/upgrade",- []byte(`{"plugin_key":"ai.multica.software-delivery","version":"1.1.0"}`),- params,- ))- if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte(`"desired_version":"1.1.0"`)) {- t.Fatalf("upgrade status=%d body=%s", recorder.Code, recorder.Body.String())+ testHandler.ListPlugins(recorder, pluginHandlerRequest(http.MethodGet, "/plugins", nil, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusOK || strings.Contains(recorder.Body.String(), "sk-super-secret") {+ t.Fatalf("list leaked the secret or failed: status=%d body=%s", recorder.Code, recorder.Body.String())}+ unknown, _ := json.Marshal(map[string]any{"values": map[string]any{"nope": "x"}})recorder = httptest.NewRecorder()- testHandler.UpgradePlugin(recorder, pluginHandlerRequest(- http.MethodPost,- "/plugins/upgrade",- []byte(`{"plugin_key":"ai.multica.software-delivery","version":"1.0.0"}`),- params,- ))- if recorder.Code != http.StatusConflict || !bytes.Contains(recorder.Body.Bytes(), []byte("not newer")) {- t.Fatalf("downgrade through upgrade status=%d body=%s", recorder.Code, recorder.Body.String())+ testHandler.ConfigurePlugin(recorder, pluginHandlerRequest(http.MethodPut, "/plugins/config", unknown, params))+ if recorder.Code != http.StatusBadRequest {+ t.Fatalf("unknown config field 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 {+ if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), `"enabled":false`) {t.Fatalf("disable status=%d body=%s", recorder.Code, recorder.Body.String())}recorder = httptest.NewRecorder()- testHandler.RollbackPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/rollback", []byte(`{"version":"1.0.0"}`), params))- if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte(`"desired_version":"1.0.0"`)) {- t.Fatalf("rollback status=%d body=%s", recorder.Code, recorder.Body.String())+ testHandler.UninstallPlugin(recorder, pluginHandlerRequest(http.MethodDelete, "/plugins", nil, params))+ if recorder.Code != http.StatusNoContent {+ t.Fatalf("uninstall status=%d body=%s", recorder.Code, recorder.Body.String())}- recorder = httptest.NewRecorder()- testHandler.RollbackPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/rollback", []byte(`{"version":"9.9.9"}`), params))- 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())+ // Uninstall must take the plugin's own state with it, or a reinstall would+ // silently inherit rows nobody can audit.+ var remaining int+ if err := testPool.QueryRow(context.Background(),+ `SELECT (SELECT COUNT(*) FROM plugin_secret WHERE installation_id = $1)+ + (SELECT COUNT(*) FROM plugin_storage WHERE installation_id = $1)`,+ installed.ID).Scan(&remaining); err != nil {+ t.Fatalf("count leftover plugin rows: %v", err)}+ if remaining != 0 {+ t.Fatalf("uninstall left %d plugin-owned rows behind", remaining)+ }+}- 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())+func TestPluginInstallRejectsMalformedManifest(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ source := withLocalPluginSource(t, `{"manifest_version":1,"key":"com.example.hello","surprise":true}`)++ body, _ := json.Marshal(map[string]any{"source_url": source, "granted_scopes": []string{}})+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusBadRequest {+ t.Fatalf("malformed manifest 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)+ if !strings.Contains(recorder.Body.String(), "manifest") {+ t.Fatalf("malformed manifest error is not actionable: %s", recorder.Body.String())}}-func TestPluginManagementUnavailableWhenFlagDisabled(t *testing.T) {- h := &Handler{}- request := func() *http.Request {- return pluginHandlerRequest(http.MethodGet, "/plugins", nil, map[string]string{- "id": testWorkspaceID,- "installationId": "00000000-0000-0000-0000-000000000001",- "pluginKey": plugintest.ReviewReadinessPluginKey,- "pluginRef": plugintest.ReviewReadinessPluginKey,- })+func TestPluginInstallRejectsUnshippedCapabilities(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ source := withLocalPluginSource(t, handlerTestManifest)+ // A declared-but-unshipped contribution must fail the install outright: a+ // silently dropped surface would look installed and never render.+ testHandler.PluginService.Host = plugincontract.HostCapabilities()++ body, _ := json.Marshal(map[string]any{+ "source_url": source,+ "granted_scopes": []string{"issues:read", "comments:write", "storage:user"},+ })+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusUnprocessableEntity {+ t.Fatalf("unshipped capability status=%d body=%s", recorder.Code, recorder.Body.String())}-- 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,- "private list": h.ListPrivatePlugins,- "private status": h.GetPrivatePluginStatus,- "private install": h.InstallPrivatePlugin,- "uninstall": h.UninstallPlugin,- "remote oauth start": h.StartPluginRemoteMCPOAuth,- "remote oauth callback": h.CompletePluginRemoteMCPOAuth,- "remote configure": h.ConfigurePluginRemoteMCP,- "remote test": h.TestPluginRemoteMCP,- "remote review": h.ReviewPluginRemoteMCPTools,- "remote revoke": h.RevokePluginRemoteMCPCredential,- } {- t.Run(name, func(t *testing.T) {- recorder := httptest.NewRecorder()- handler(recorder, request())- if recorder.Code != http.StatusServiceUnavailable {- t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())- }- if bytes.Contains(recorder.Body.Bytes(), []byte(plugintest.ReviewReadinessPluginKey)) {- t.Fatalf("disabled response leaked catalog data: %s", recorder.Body.String())- }- })+ if !strings.Contains(recorder.Body.String(), "issue_panel") {+ t.Fatalf("error does not name the missing capability: %s", recorder.Body.String())}}-func TestPrivatePluginManagementRequiresPluginsV1(t *testing.T) {- h := &Handler{}- withPluginsV1Flag(t, h, false)- 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 TestPluginInstallationFromAnotherWorkspaceIsNotFound(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ recorder := httptest.NewRecorder()+ testHandler.EnablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/enable", nil, map[string]string{+ "id": testWorkspaceID,+ "installationId": "11111111-1111-1111-1111-111111111111",+ }))+ if recorder.Code != http.StatusNotFound {+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())}}-func TestPrivatePluginHTTPUploadListAndUninstall(t *testing.T) {+func TestPluginUpgradePrunesSecretsTheNewManifestDropped(t *testing.T) {withPluginsV1Flag(t, testHandler, 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)+ cleanupPluginInstallations(t)+ root := t.TempDir()+ source := withLocalPluginSourceIn(t, root, handlerTestManifest)- 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())+ install, _ := json.Marshal(map[string]any{+ "source_url": source,+ "granted_scopes": []string{"issues:read", "comments:write", "storage:user"},+ })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())+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", install, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("install 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())+ var installed struct {+ ID string `json:"id"`}+ json.Unmarshal(recorder.Body.Bytes(), &installed)params := map[string]string{"id": testWorkspaceID, "installationId": installed.ID}+ configure, _ := json.Marshal(map[string]any{"values": map[string]any{"token": "sk-old-secret"}})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())+ testHandler.ConfigurePlugin(recorder, pluginHandlerRequest(http.MethodPut, "/plugins/config", configure, params))+ if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), `"configured_secrets":["token"]`) {+ t.Fatalf("configure status=%d body=%s", recorder.Code, recorder.Body.String())}- withPluginsV1Flag(t, testHandler, false)- recorder = httptest.NewRecorder()- testHandler.ListPlugins(recorder, pluginHandlerRequest(http.MethodGet, "/plugins", nil, map[string]string{"id": testWorkspaceID}))- if recorder.Code != http.StatusServiceUnavailable {- t.Fatalf("Plugin list with plugins_v1 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("Plugin enable with plugins_v1 off status=%d body=%s", recorder.Code, recorder.Body.String())- }+ // v2 drops the `token` secret field entirely. Its ciphertext must go with+ // it: nothing can reach a secret whose field no longer exists, and leaving+ // it means an uninstall is the only thing that ever removes it.+ upgraded := strings.Replace(handlerTestManifest, `"version": "1.0.0"`, `"version": "2.0.0"`, 1)+ upgraded = strings.Replace(upgraded, `,+ "token": { "type": "secret", "label": "Token" }`, "", 1)+ writeLocalPluginManifest(t, root, upgraded)+recorder = httptest.NewRecorder()- testHandler.DisablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/disable", nil, params))- if recorder.Code != http.StatusServiceUnavailable {- t.Fatalf("Plugin disable with plugins_v1 off status=%d body=%s", recorder.Code, recorder.Body.String())+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", install, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("upgrade 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.StatusServiceUnavailable {- t.Fatalf("Plugin uninstall with plugins_v1 off status=%d body=%s", recorder.Code, recorder.Body.String())+ if !strings.Contains(recorder.Body.String(), `"configured_secrets":[]`) {+ t.Fatalf("upgrade left an unreachable secret: %s", recorder.Body.String())}- withPluginsV1Flag(t, testHandler, true)- 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())+ var remaining int+ if err := testPool.QueryRow(context.Background(),+ `SELECT COUNT(*) FROM plugin_secret WHERE installation_id = $1`, installed.ID).Scan(&remaining); err != nil {+ t.Fatalf("count secrets: %v", err)}- 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())+ if remaining != 0 {+ t.Fatalf("upgrade left %d secret rows behind", remaining)}}-func TestResolveTaskRemoteMCPCredentialRejectsNonDaemonAuth(t *testing.T) {- h := &Handler{}- recorder := httptest.NewRecorder()- request := pluginHandlerRequest(http.MethodGet, "/api/daemon/tasks/task-id/remote-mcp/contribution-id/credential", nil, map[string]string{- "taskId": "task-id",- "contributionId": "contribution-id",+// TestPluginRoutesRequireWorkspaceAdmin pins the gate that actually protects+// these endpoints. Every other handler test calls the handler directly, which+// bypasses middleware entirely — so without this, "install/configure/uninstall+// are admin-only" rests on where the routes sit in router.go and nothing would+// fail if one moved into the member group.+func TestPluginRoutesRequireWorkspaceAdmin(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ memberID := createTestUserAndMember(t, "member")++ router := chi.NewRouter()+ router.Route("/api/workspaces/{id}", func(r chi.Router) {+ r.Group(func(r chi.Router) {+ r.Use(middleware.RequireWorkspaceRoleFromURL(testHandler.Queries, "id", "owner", "admin"))+ r.Post("/plugins/preview", testHandler.PreviewPlugin)+ r.Post("/plugins", testHandler.InstallPlugin)+ r.Put("/plugins/{installationId}/config", testHandler.ConfigurePlugin)+ r.Post("/plugins/{installationId}/enable", testHandler.EnablePlugin)+ r.Post("/plugins/{installationId}/disable", testHandler.DisablePlugin)+ r.Delete("/plugins/{installationId}", testHandler.UninstallPlugin)+ })+ // Listing is member-visible on purpose: a member should be able to see+ // what is mounted in their workspace and which scopes it holds.+ r.Get("/plugins", testHandler.ListPlugins)})- h.ResolveTaskRemoteMCPCredential(recorder, request)-- if recorder.Code != http.StatusForbidden {- t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())- }-}--func TestResolveTaskRemoteMCPCredentialRejectsDifferentDaemonInWorkspace(t *testing.T) {- if testHandler == nil || testPool == nil {- t.Skip("database not available")+ base := "/api/workspaces/" + testWorkspaceID+ adminOnly := []struct {+ method string+ path string+ }{+ {http.MethodPost, base + "/plugins/preview"},+ {http.MethodPost, base + "/plugins"},+ {http.MethodPut, base + "/plugins/11111111-1111-1111-1111-111111111111/config"},+ {http.MethodPost, base + "/plugins/11111111-1111-1111-1111-111111111111/enable"},+ {http.MethodPost, base + "/plugins/11111111-1111-1111-1111-111111111111/disable"},+ {http.MethodDelete, base + "/plugins/11111111-1111-1111-1111-111111111111"},+ }+ for _, route := range adminOnly {+ t.Run(route.method+" "+route.path, func(t *testing.T) {+ request := newRequest(route.method, route.path, map[string]any{})+ request.Header.Set("X-User-ID", memberID)+ recorder := httptest.NewRecorder()+ router.ServeHTTP(recorder, request)+ if recorder.Code != http.StatusForbidden {+ t.Fatalf("plain member reached an admin route: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ })}- fixture := createCommentDeliveryFixture(t, "Remote MCP daemon isolation")- request := newDaemonTokenRequest(http.MethodGet,- "/api/daemon/tasks/"+fixture.taskID+"/remote-mcp/contribution-id/credential",- nil, testWorkspaceID, "different-daemon")- routeCtx := chi.NewRouteContext()- routeCtx.URLParams.Add("taskId", fixture.taskID)- routeCtx.URLParams.Add("contributionId", "contribution-id")- request = request.WithContext(context.WithValue(request.Context(), chi.RouteCtxKey, routeCtx))+ request := newRequest(http.MethodGet, base+"/plugins", nil)+ request.Header.Set("X-User-ID", memberID)recorder := httptest.NewRecorder()- testHandler.ResolveTaskRemoteMCPCredential(recorder, request)-- if recorder.Code != http.StatusNotFound {- t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())+ router.ServeHTTP(recorder, request)+ if recorder.Code != http.StatusOK {+ t.Fatalf("plain member could not list Plugins: status=%d body=%s", recorder.Code, recorder.Body.String())}}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 8cb5e7192c..8f42ae2ee5 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -19,114 +19,103 @@ const (// teardown. Adding a table requires an explicit ownership decision here; the// handler deletion graph must then implement that decision before CI passes.var workspaceDeletionManifest = map[string]workspaceDeleteAction{- "activity_log": workspaceDelete,- "agent": workspaceDelete,- "agent_builder_draft": workspaceDelete,- "agent_invocation_target": workspaceDelete,- "agent_runtime": workspaceDelete,- "agent_skill": workspaceDelete,- "agent_task_queue": workspaceDelete,- "agent_to_label": workspaceDelete,- "attachment": workspaceDelete,- "autopilot": workspaceDelete,- "autopilot_collaborator": workspaceDelete,- "autopilot_rule_version": workspaceDelete,- "autopilot_run": workspaceDelete,- "autopilot_subscriber": workspaceDelete,- "autopilot_trigger": workspaceDelete,- "channel_binding_token": workspaceDelete,- "channel_chat_session_binding": workspaceDelete,- "channel_inbound_audit": workspaceDelete,- "channel_inbound_message_dedup": workspaceDelete,- "channel_installation": workspaceDelete,- "channel_media_pending_object": workspaceDeleteSettle,- "channel_outbound_card_message": workspaceDelete,- "channel_user_binding": workspaceDelete,- "chat_draft_restore": workspaceDelete,- "chat_message": workspaceDelete,- "chat_pinned_agent": workspaceDelete,- "chat_session": workspaceDelete,- "client_usage_daily": workspaceDeleteDetach,- "comment": workspaceDelete,- "comment_reaction": workspaceDelete,- "contact_sales_inquiry": workspaceDeleteKeep,- "daemon_connection": workspaceDelete,- "daemon_token": workspaceDelete,- "dingtalk_group_route": workspaceDelete,- "feedback": workspaceDeleteDetach,- "github_installation": workspaceDelete,- "github_pending_check_suite": workspaceDelete,- "github_pending_installation": workspaceDeleteKeep,- "github_pull_request": workspaceDelete,- "github_pull_request_check_run": workspaceDelete,- "github_pull_request_check_suite": workspaceDelete,- "inbox_item": workspaceDelete,- "issue": workspaceDelete,- "issue_view": workspaceDelete,- "issue_view_preference": workspaceDelete,- "issue_dependency": workspaceDelete,- "issue_label": workspaceDelete,- "issue_property": workspaceDelete,- "issue_pull_request": workspaceDelete,- "issue_reaction": workspaceDelete,- "issue_status": workspaceDelete,- "issue_subscriber": workspaceDelete,- "issue_to_label": workspaceDelete,- "issue_vcs_pull_request": workspaceDelete,- "lark_binding_token": workspaceDelete,- "lark_chat_session_binding": workspaceDelete,- "lark_inbound_audit": workspaceDelete,- "lark_inbound_message_dedup": workspaceDelete,- "lark_installation": workspaceDelete,- "lark_outbound_card_message": workspaceDelete,- "lark_user_binding": workspaceDelete,- "member": workspaceDelete,- "agent_mcp_server": workspaceDelete,- "workspace_mcp_server": workspaceDelete,- "notification_preference": workspaceDelete,- "personal_access_token": workspaceDeleteKeep,- "pinned_item": workspaceDelete,- "plugin_binding": workspaceDelete,- "plugin_artifact_file": workspaceDeleteKeep,- "plugin_capability_snapshot": workspaceDelete,- "plugin_contribution": workspaceDeleteKeep,- "plugin_execution_manifest": workspaceDelete,- "plugin_grant": workspaceDelete,- "plugin_health": workspaceDelete,- "plugin_identity": workspaceDeleteKeep,- "plugin_installation_config": workspaceDelete,- "plugin_installation": workspaceDelete,- "plugin_remote_mcp_oauth_state": workspaceDelete,- "plugin_remote_mcp_secret": workspaceDelete,- "plugin_release": workspaceDeleteKeep,- "plugin_workspace_capability_state": workspaceDelete,- "project": workspaceDelete,- "project_resource": workspaceDelete,- "quick_action": workspaceDelete,- "runtime_profile": workspaceDelete,- "schema_migrations": workspaceDeleteKeep,- "skill": workspaceDelete,- "skill_file": workspaceDelete,- "skill_to_label": workspaceDelete,- "squad": workspaceDelete,- "squad_member": workspaceDelete,- "sys_cron_executions": workspaceDeleteKeep,- "task_message": workspaceDelete,- "task_token": workspaceDelete,- "task_usage": workspaceDelete,- "task_usage_hourly": workspaceDelete,- "task_usage_hourly_dirty": workspaceDelete,- "task_usage_hourly_rollup_state": workspaceDeleteKeep,- "user": workspaceDeleteKeep,- "user_composio_connection": workspaceDeleteKeep,- "vcs_commit_status": workspaceDelete,- "vcs_connection": workspaceDelete,- "vcs_pull_request": workspaceDelete,- "verification_code": workspaceDeleteKeep,- "webhook_delivery": workspaceDelete,- "workspace": workspaceDelete,- "workspace_invitation": workspaceDelete,- "workspace_share_link": workspaceDelete,+ "activity_log": workspaceDelete,+ "agent": workspaceDelete,+ "agent_builder_draft": workspaceDelete,+ "agent_invocation_target": workspaceDelete,+ "agent_runtime": workspaceDelete,+ "agent_skill": workspaceDelete,+ "agent_task_queue": workspaceDelete,+ "agent_to_label": workspaceDelete,+ "attachment": workspaceDelete,+ "autopilot": workspaceDelete,+ "autopilot_collaborator": workspaceDelete,+ "autopilot_rule_version": workspaceDelete,+ "autopilot_run": workspaceDelete,+ "autopilot_subscriber": workspaceDelete,+ "autopilot_trigger": workspaceDelete,+ "channel_binding_token": workspaceDelete,+ "channel_chat_session_binding": workspaceDelete,+ "channel_inbound_audit": workspaceDelete,+ "channel_inbound_message_dedup": workspaceDelete,+ "channel_installation": workspaceDelete,+ "channel_media_pending_object": workspaceDeleteSettle,+ "channel_outbound_card_message": workspaceDelete,+ "channel_user_binding": workspaceDelete,+ "chat_draft_restore": workspaceDelete,+ "chat_message": workspaceDelete,+ "chat_pinned_agent": workspaceDelete,+ "chat_session": workspaceDelete,+ "client_usage_daily": workspaceDeleteDetach,+ "comment": workspaceDelete,+ "comment_reaction": workspaceDelete,+ "contact_sales_inquiry": workspaceDeleteKeep,+ "daemon_connection": workspaceDelete,+ "daemon_token": workspaceDelete,+ "dingtalk_group_route": workspaceDelete,+ "feedback": workspaceDeleteDetach,+ "github_installation": workspaceDelete,+ "github_pending_check_suite": workspaceDelete,+ "github_pending_installation": workspaceDeleteKeep,+ "github_pull_request": workspaceDelete,+ "github_pull_request_check_run": workspaceDelete,+ "github_pull_request_check_suite": workspaceDelete,+ "inbox_item": workspaceDelete,+ "issue": workspaceDelete,+ "issue_view": workspaceDelete,+ "issue_view_preference": workspaceDelete,+ "issue_dependency": workspaceDelete,+ "issue_label": workspaceDelete,+ "issue_property": workspaceDelete,+ "issue_pull_request": workspaceDelete,+ "issue_reaction": workspaceDelete,+ "issue_status": workspaceDelete,+ "issue_subscriber": workspaceDelete,+ "issue_to_label": workspaceDelete,+ "issue_vcs_pull_request": workspaceDelete,+ "lark_binding_token": workspaceDelete,+ "lark_chat_session_binding": workspaceDelete,+ "lark_inbound_audit": workspaceDelete,+ "lark_inbound_message_dedup": workspaceDelete,+ "lark_installation": workspaceDelete,+ "lark_outbound_card_message": workspaceDelete,+ "lark_user_binding": workspaceDelete,+ "member": workspaceDelete,+ "agent_mcp_server": workspaceDelete,+ "workspace_mcp_server": workspaceDelete,+ "notification_preference": workspaceDelete,+ "personal_access_token": workspaceDeleteKeep,+ "pinned_item": workspaceDelete,+ "plugin_installation": workspaceDelete,+ "plugin_storage": workspaceDelete,+ "plugin_secret": workspaceDelete,+ "project": workspaceDelete,+ "project_resource": workspaceDelete,+ "quick_action": workspaceDelete,+ "runtime_profile": workspaceDelete,+ "schema_migrations": workspaceDeleteKeep,+ "skill": workspaceDelete,+ "skill_file": workspaceDelete,+ "skill_to_label": workspaceDelete,+ "squad": workspaceDelete,+ "squad_member": workspaceDelete,+ "sys_cron_executions": workspaceDeleteKeep,+ "task_message": workspaceDelete,+ "task_token": workspaceDelete,+ "task_usage": workspaceDelete,+ "task_usage_hourly": workspaceDelete,+ "task_usage_hourly_dirty": workspaceDelete,+ "task_usage_hourly_rollup_state": workspaceDeleteKeep,+ "user": workspaceDeleteKeep,+ "user_composio_connection": workspaceDeleteKeep,+ "vcs_commit_status": workspaceDelete,+ "vcs_connection": workspaceDelete,+ "vcs_pull_request": workspaceDelete,+ "verification_code": workspaceDeleteKeep,+ "webhook_delivery": workspaceDelete,+ "workspace": workspaceDelete,+ "workspace_invitation": workspaceDelete,+ "workspace_share_link": workspaceDelete,}func TestWorkspaceDeletionManifestCoversPublicSchema(t *testing.T) {diff --git a/server/internal/pluginbundled/README.md b/server/internal/pluginbundled/README.mddeleted file mode 100644index edee91b1b6..0000000000--- a/server/internal/pluginbundled/README.md+++ /dev/null@@ -1,27 +0,0 @@-# Bundled Plugin release catalog--This package is the production acquisition boundary for official Plugins that-ship with the Multica server. It discovers release directories generically,-rebuilds their ZIP archives deterministically, validates the manifest and-artifact, and verifies the detached Ed25519 signature against-`trust_roots.json` before exposing a release to the catalog.--Each release directory contains:--- `release.json`: source and publisher metadata plus the signing-key ID.-- `release.sig`: a detached base64 Ed25519 signature.-- `multica.plugin.json` and the static contribution payloads that form the ZIP.--The signing private key is intentionally not stored in this repository or the-server binary. Release automation must build the same deterministic ZIP, sign-the Plugin release envelope offline, and commit only the detached signature.-Run the reproducibility and trust-boundary checks from `server/`:--```sh-go test ./internal/pluginbundled -count=1-```--A malformed, tampered, or unknown-key release is isolated as a safe catalog-diagnostic. It does not prevent other releases or the server from starting.-The public API admits only this bundled source in V1; no `private_dev` upload or-server-file-path acquisition route is exposed.diff --git a/server/internal/pluginbundled/catalog.go b/server/internal/pluginbundled/catalog.godeleted file mode 100644index 38ec92dd6c..0000000000--- a/server/internal/pluginbundled/catalog.go+++ /dev/null@@ -1,439 +0,0 @@-// Package pluginbundled discovers and validates immutable Plugin releases-// shipped with the Multica server binary.-package pluginbundled--import (- "archive/zip"- "bytes"- "crypto/ed25519"- "embed"- "encoding/base64"- "encoding/json"- "errors"- "fmt"- "io/fs"- "path"- "sort"- "strings"- "time"-- "github.com/multica-ai/multica/server/pkg/plugincontract"-)--const (- PublisherTypeOfficial = "official"- TrustTierOfficial = "official"-)--//go:embed trust_roots.json releases-var bundledFS embed.FS--// CatalogEntry is a validated bundled release plus the acquisition-boundary-// trust decision used when it is installed into a workspace.-type CatalogEntry struct {- Release plugincontract.ValidatedRelease- PublisherType string- TrustTier string- Compatible bool- CompatibilityWhy string-}--// Diagnostic reports a release that could not be admitted without preventing-// healthy releases, or the server, from loading.-type Diagnostic struct {- SourceRef string `json:"source_ref"`- Code string `json:"code"`- Message string `json:"message"`-}--// Catalog is immutable after construction and safe for concurrent reads.-type Catalog struct {- entries map[string]map[string]CatalogEntry- diagnostics []Diagnostic-}--type trustRootFile struct {- Keys []struct {- ID string `json:"id"`- PublicKey string `json:"public_key"`- } `json:"keys"`-}--type releaseMetadata struct {- SourceRef string `json:"source_ref"`- SignatureKeyID string `json:"signature_key_id"`- SignatureFile string `json:"signature_file"`- PublisherType string `json:"publisher_type"`- TrustTier string `json:"trust_tier"`-}--// Load discovers the releases embedded in the production server. A bad trust-// root or release becomes a catalog diagnostic; it never blocks Kernel startup.-func Load() *Catalog {- return LoadFromFS(bundledFS)-}--// LoadFromFS is the testable discovery boundary for bundled sources.-func LoadFromFS(source fs.FS) *Catalog {- catalog := &Catalog{entries: make(map[string]map[string]CatalogEntry)}- verifier, err := loadTrustStore(source)- if err != nil {- catalog.diagnostics = append(catalog.diagnostics, Diagnostic{- SourceRef: "bundled://trust-roots",- Code: "trust_roots_invalid",- Message: "Bundled Plugin trust roots could not be loaded.",- })- return catalog- }-- var metadataFiles []string- if err := fs.WalkDir(source, "releases", func(name string, entry fs.DirEntry, walkErr error) error {- if walkErr != nil {- catalog.diagnostics = append(catalog.diagnostics, Diagnostic{- SourceRef: "bundled://" + name,- Code: "source_unreadable",- Message: "A bundled Plugin source could not be read.",- })- return fs.SkipDir- }- if !entry.IsDir() && path.Base(name) == "release.json" {- metadataFiles = append(metadataFiles, name)- }- return nil- }); err != nil {- catalog.diagnostics = append(catalog.diagnostics, Diagnostic{- SourceRef: "bundled://releases",- Code: "source_unreadable",- Message: "Bundled Plugin releases could not be discovered.",- })- return catalog- }- sort.Strings(metadataFiles)- for _, metadataFile := range metadataFiles {- entry, diagnostic := loadRelease(source, verifier, metadataFile)- if diagnostic != nil {- catalog.diagnostics = append(catalog.diagnostics, *diagnostic)- continue- }- key := entry.Release.Manifest.Metadata.Key- version := entry.Release.Manifest.Metadata.Version- if catalog.entries[key] == nil {- catalog.entries[key] = make(map[string]CatalogEntry)- }- if _, duplicate := catalog.entries[key][version]; duplicate {- catalog.diagnostics = append(catalog.diagnostics, Diagnostic{- SourceRef: entry.Release.SourceRef,- Code: "duplicate_release",- Message: "A duplicate bundled Plugin release was ignored.",- })- continue- }- catalog.entries[key][version] = entry- }- return catalog-}--func loadTrustStore(source fs.FS) (*plugincontract.Ed25519TrustStore, error) {- raw, err := fs.ReadFile(source, "trust_roots.json")- if err != nil {- return nil, err- }- decoder := json.NewDecoder(bytes.NewReader(raw))- decoder.DisallowUnknownFields()- var roots trustRootFile- if err := decoder.Decode(&roots); err != nil {- return nil, err- }- keys := make(map[string]ed25519.PublicKey, len(roots.Keys))- for _, root := range roots.Keys {- decoded, err := base64.StdEncoding.DecodeString(root.PublicKey)- if err != nil {- return nil, err- }- keys[root.ID] = ed25519.PublicKey(decoded)- }- if len(keys) == 0 {- return nil, errors.New("bundled Plugin trust store is empty")- }- return plugincontract.NewEd25519TrustStore(keys)-}--func loadRelease(source fs.FS, verifier plugincontract.ReleaseVerifier, metadataFile string) (CatalogEntry, *Diagnostic) {- releaseDir := path.Dir(metadataFile)- metadataRaw, err := fs.ReadFile(source, metadataFile)- if err != nil {- return CatalogEntry{}, releaseDiagnostic(releaseDir, "release_metadata_invalid")- }- decoder := json.NewDecoder(bytes.NewReader(metadataRaw))- decoder.DisallowUnknownFields()- var metadata releaseMetadata- if err := decoder.Decode(&metadata); err != nil || metadata.SourceRef == "" || metadata.SignatureKeyID == "" || metadata.SignatureFile == "" {- return CatalogEntry{}, releaseDiagnostic(releaseDir, "release_metadata_invalid")- }- if metadata.PublisherType != PublisherTypeOfficial || metadata.TrustTier != TrustTierOfficial {- return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, "publisher_not_official")- }- archive, err := buildArchive(source, releaseDir, metadata.SignatureFile)- if err != nil {- return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, "artifact_invalid")- }- signatureRaw, err := fs.ReadFile(source, path.Join(releaseDir, metadata.SignatureFile))- if err != nil {- return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, "signature_missing")- }- signature, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(signatureRaw)))- if err != nil {- return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, "signature_invalid")- }- release, err := plugincontract.ValidateReleaseCandidate(plugincontract.ReleaseCandidate{- Archive: archive,- SourceKind: plugincontract.SourceBundled,- SourceRef: metadata.SourceRef,- SignatureKeyID: metadata.SignatureKeyID,- Signature: signature,- }, verifier)- if err != nil {- code := "artifact_invalid"- if errors.Is(err, plugincontract.ErrInvalidSignature) || errors.Is(err, plugincontract.ErrUnknownSigningKey) {- code = "signature_invalid"- }- return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, code)- }- compatible, why := CompatibleWithV1Host(release.Manifest)- return CatalogEntry{- Release: release,- PublisherType: metadata.PublisherType,- TrustTier: metadata.TrustTier,- Compatible: compatible,- CompatibilityWhy: why,- }, nil-}--func releaseDiagnostic(sourceRef, code string) *Diagnostic {- if !strings.HasPrefix(sourceRef, "bundled://") {- sourceRef = "bundled://" + strings.TrimPrefix(sourceRef, "releases/")- }- return &Diagnostic{- SourceRef: sourceRef,- Code: code,- Message: "A bundled Plugin release failed validation and was isolated.",- }-}--func buildArchive(source fs.FS, releaseDir, signatureFile string) ([]byte, error) {- var files []string- if err := fs.WalkDir(source, releaseDir, func(name string, entry fs.DirEntry, err error) error {- if err != nil {- return err- }- if entry.IsDir() {- return nil- }- relative := strings.TrimPrefix(name, releaseDir+"/")- if relative == "release.json" || relative == signatureFile {- return nil- }- files = append(files, name)- return nil- }); err != nil {- return nil, err- }- if len(files) == 0 {- return nil, errors.New("bundled Plugin release has no artifact files")- }- sort.Strings(files)- var buffer bytes.Buffer- writer := zip.NewWriter(&buffer)- for _, name := range files {- content, err := fs.ReadFile(source, name)- if err != nil {- return nil, err- }- header := &zip.FileHeader{- Name: strings.TrimPrefix(name, releaseDir+"/"),- Method: zip.Store,- }- header.SetMode(0o600)- header.SetModTime(time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC))- entry, err := writer.CreateHeader(header)- if err != nil {- return nil, err- }- if _, err := entry.Write(content); err != nil {- return nil, err- }- }- if err := writer.Close(); err != nil {- return nil, err- }- return buffer.Bytes(), nil-}--// 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"- }- supported := map[string]bool{- plugincontract.DaemonFeatureExecutionManifestV1: true,- plugincontract.DaemonFeatureAgentSkillV1: true,- plugincontract.DaemonFeatureRemoteMCPV1: true,- }- for _, feature := range manifest.Compatibility.RequiredDaemonFeatures {- if !supported[feature] {- return false, "daemon_feature_unsupported"- }- }- return true, ""-}--// List returns every admitted release in stable plugin/version order.-func (c *Catalog) List() []CatalogEntry {- if c == nil {- return nil- }- var entries []CatalogEntry- for _, versions := range c.entries {- for _, entry := range versions {- entries = append(entries, entry)- }- }- sort.Slice(entries, func(i, j int) bool {- left := entries[i].Release.Manifest.Metadata- right := entries[j].Release.Manifest.Metadata- if left.Key != right.Key {- return left.Key < right.Key- }- return compareSemver(left.Version, right.Version) > 0- })- return entries-}--// Find resolves an exact immutable bundled release.-func (c *Catalog) Find(pluginKey, version string) (CatalogEntry, bool) {- if c == nil || c.entries[pluginKey] == nil {- return CatalogEntry{}, false- }- entry, ok := c.entries[pluginKey][version]- return entry, ok-}--// Latest resolves the highest semantic version for a Plugin.-func (c *Catalog) Latest(pluginKey string) (CatalogEntry, bool) {- versions := c.entries[pluginKey]- var latest CatalogEntry- found := false- for _, entry := range versions {- if !found || compareSemver(entry.Release.Manifest.Metadata.Version, latest.Release.Manifest.Metadata.Version) > 0 {- latest = entry- found = true- }- }- return latest, found-}--func (c *Catalog) Diagnostics() []Diagnostic {- if c == nil {- return nil- }- return append([]Diagnostic(nil), c.diagnostics...)-}--// IsNewerVersion reports whether candidate is strictly newer than current.-// Both inputs have already passed the Plugin manifest's semantic-version-// validation before reaching the bundled catalog.-func IsNewerVersion(candidate, current string) bool {- return compareSemver(candidate, current) > 0-}--func compareSemver(left, right string) int {- parse := func(value string) ([3]string, []string) {- var numeric [3]string- withoutBuild, _, _ := strings.Cut(value, "+")- main, prerelease, _ := strings.Cut(withoutBuild, "-")- copy(numeric[:], strings.Split(main, "."))- if prerelease == "" {- return numeric, nil- }- return numeric, strings.Split(prerelease, ".")- }- leftNumeric, leftPrerelease := parse(left)- rightNumeric, rightPrerelease := parse(right)- for index := range leftNumeric {- if comparison := compareNumericIdentifier(leftNumeric[index], rightNumeric[index]); comparison != 0 {- return comparison- }- }- if len(leftPrerelease) == 0 && len(rightPrerelease) == 0 {- return 0- }- if len(leftPrerelease) == 0 {- return 1- }- if len(rightPrerelease) == 0 {- return -1- }- for index := 0; index < len(leftPrerelease) && index < len(rightPrerelease); index++ {- leftIdentifier := leftPrerelease[index]- rightIdentifier := rightPrerelease[index]- leftNumber := isNumericIdentifier(leftIdentifier)- rightNumber := isNumericIdentifier(rightIdentifier)- switch {- case leftNumber && rightNumber:- if comparison := compareNumericIdentifier(leftIdentifier, rightIdentifier); comparison != 0 {- return comparison- }- case leftNumber:- return -1- case rightNumber:- return 1- default:- if comparison := strings.Compare(leftIdentifier, rightIdentifier); comparison != 0 {- return comparison- }- }- }- return len(leftPrerelease) - len(rightPrerelease)-}--func compareNumericIdentifier(left, right string) int {- left = strings.TrimLeft(left, "0")- right = strings.TrimLeft(right, "0")- if left == "" {- left = "0"- }- if right == "" {- right = "0"- }- if len(left) != len(right) {- return len(left) - len(right)- }- return strings.Compare(left, right)-}--func isNumericIdentifier(value string) bool {- if value == "" {- return false- }- for _, character := range value {- if character < '0' || character > '9' {- return false- }- }- return true-}--// VerifyReproducibleRelease rebuilds a source release and returns the exact-// immutable identities used by release automation and repository tests.-func VerifyReproducibleRelease(source fs.FS, releaseDir, signatureFile string) (plugincontract.Artifact, error) {- archive, err := buildArchive(source, releaseDir, signatureFile)- if err != nil {- return plugincontract.Artifact{}, err- }- artifact, err := plugincontract.ValidateArtifact(archive)- if err != nil {- return plugincontract.Artifact{}, fmt.Errorf("validate reproducible bundled artifact: %w", err)- }- return artifact, nil-}diff --git a/server/internal/pluginbundled/catalog_test.go b/server/internal/pluginbundled/catalog_test.godeleted file mode 100644index bd137ada2e..0000000000--- a/server/internal/pluginbundled/catalog_test.go+++ /dev/null@@ -1,101 +0,0 @@-package pluginbundled--import (- "io/fs"- "testing"- "testing/fstest"-- "github.com/multica-ai/multica/server/pkg/plugincontract"-)--func TestV1HostSupportsRemoteMCPDaemonFeature(t *testing.T) {- manifest := plugincontract.Manifest{Compatibility: plugincontract.Compatibility{- HostAPI: ">=1.0.0 <2.0.0",- RequiredDaemonFeatures: []string{- plugincontract.DaemonFeatureExecutionManifestV1,- plugincontract.DaemonFeatureRemoteMCPV1,- },- }}- if compatible, why := CompatibleWithV1Host(manifest); !compatible {- t.Fatalf("Remote MCP V1 compatibility = false, %s", why)- }-}--func TestBundledCatalogLoadsSignedOfficialReleases(t *testing.T) {- catalog := Load()- if diagnostics := catalog.Diagnostics(); len(diagnostics) != 0 {- t.Fatalf("diagnostics = %+v", diagnostics)- }- entries := catalog.List()- if len(entries) != 2 {- t.Fatalf("entries = %d, want 2", len(entries))- }- latest, ok := catalog.Latest("ai.multica.software-delivery")- if !ok || latest.Release.Manifest.Metadata.Version != "1.1.0" {- t.Fatalf("latest = %+v, %v", latest.Release.Manifest.Metadata, ok)- }- if !latest.Compatible || latest.PublisherType != PublisherTypeOfficial || latest.TrustTier != TrustTierOfficial {- t.Fatalf("unexpected admission = %+v", latest)- }- if latest.Release.ArtifactDigest != "sha256:c0064980c253c567f9df90999b158c670989bb60d213289d2f3c36b9a8b591ff" {- t.Fatalf("artifact digest = %s", latest.Release.ArtifactDigest)- }- if len(latest.Release.Contributions) != 1 || latest.Release.Contributions[0].Key != "review-readiness" {- t.Fatalf("contributions = %+v", latest.Release.Contributions)- }-}--func TestBundledCatalogIsolatesTamperedRelease(t *testing.T) {- copyFS := make(fstest.MapFS)- if err := fs.WalkDir(bundledFS, ".", func(name string, entry fs.DirEntry, err error) error {- if err != nil || entry.IsDir() {- return err- }- content, readErr := fs.ReadFile(bundledFS, name)- if readErr != nil {- return readErr- }- copyFS[name] = &fstest.MapFile{Data: append([]byte(nil), content...), Mode: 0o600}- return nil- }); err != nil {- t.Fatal(err)- }- tampered := "releases/ai.multica.software-delivery/1.1.0/skills/review-readiness/SKILL.md"- copyFS[tampered].Data = append(copyFS[tampered].Data, []byte("\ntampered")...)-- catalog := LoadFromFS(copyFS)- if len(catalog.List()) != 1 {- t.Fatalf("healthy releases = %d, want 1", len(catalog.List()))- }- if _, ok := catalog.Find("ai.multica.software-delivery", "1.1.0"); ok {- t.Fatal("tampered release was admitted")- }- if diagnostics := catalog.Diagnostics(); len(diagnostics) != 1 || diagnostics[0].Code != "signature_invalid" {- t.Fatalf("diagnostics = %+v", diagnostics)- }-}--func TestIsNewerVersion(t *testing.T) {- tests := []struct {- candidate string- current string- want bool- }{- {candidate: "1.1.0", current: "1.0.0", want: true},- {candidate: "2.0.0", current: "1.9.9", want: true},- {candidate: "1.0.0", current: "1.0.0", want: false},- {candidate: "1.0.0", current: "1.1.0", want: false},- {candidate: "1.0.0", current: "1.0.0-rc.1", want: true},- {candidate: "1.0.0-rc.10", current: "1.0.0-rc.9", want: true},- {candidate: "1.0.0-beta.1", current: "1.0.0-1", want: true},- {candidate: "1.0.0-rc.1", current: "1.0.0-rc.1.1", want: false},- {candidate: "1.2.1+r1", current: "1.2.0", want: true},- {candidate: "1.2.1+r2", current: "1.2.1+r1", want: false},- {candidate: "100000000000000000000.0.0", current: "99999999999999999999.0.0", want: true},- }- for _, test := range tests {- if got := IsNewerVersion(test.candidate, test.current); got != test.want {- t.Errorf("IsNewerVersion(%q, %q) = %v, want %v", test.candidate, test.current, got, test.want)- }- }-}diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/multica.plugin.json b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/multica.plugin.jsondeleted file mode 100644index 76df21cb67..0000000000--- a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/multica.plugin.json+++ /dev/null@@ -1,26 +0,0 @@-{- "api_version": "multica.plugin/v1",- "kind": "Plugin",- "metadata": {- "key": "ai.multica.software-delivery",- "name": "Software Delivery",- "description": "Official Multica software-delivery workflow skills.",- "version": "1.0.0",- "publisher": "multica"- },- "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": "review-readiness",- "name": "review-readiness",- "description": "Verify that a software change is ready for review and handoff.",- "entry": "skills/review-readiness/SKILL.md"- }- ]- }-}diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.json b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.jsondeleted file mode 100644index b74acf9d20..0000000000--- a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.json+++ /dev/null@@ -1,7 +0,0 @@-{- "source_ref": "bundled://ai.multica.software-delivery/1.0.0",- "signature_key_id": "multica-plugin-release-2026-01",- "signature_file": "release.sig",- "publisher_type": "official",- "trust_tier": "official"-}diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.sig b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.sigdeleted file mode 100644index fa076516f8..0000000000--- a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.sig+++ /dev/null@@ -1 +0,0 @@-QvywEh5534Pkh1pXl6D16upCwUo44Dq9T4MB6wHl2Tcfvu+cPqdiWMZ0RFkTcfcO1pre9D3ItjhrrFjWzANuDA==diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/skills/review-readiness/SKILL.md b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/skills/review-readiness/SKILL.mddeleted file mode 100644index 9680fe6878..0000000000--- a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/skills/review-readiness/SKILL.md+++ /dev/null@@ -1,29 +0,0 @@-----name: review-readiness-description: Verify that a software change has enough evidence, rollout planning, and review context to be safely reviewed.------# Review readiness--Use this skill when preparing a software change for review or deciding whether it is ready to hand off.--## Check the change--1. State the user-visible or operational outcome in one sentence.-2. Confirm the diff is scoped to that outcome and call out intentional exclusions.-3. Record the tests or other evidence that directly exercise the changed behavior.-4. Identify data migrations, compatibility constraints, rollout steps, and rollback steps.-5. Surface unresolved risks or decisions instead of hiding them in implementation detail.--## Produce the handoff--Return a compact review brief with:--- outcome and scope;-- key architectural choices;-- evidence run and its result;-- rollout and rollback notes;-- open risks or decisions;-- exact files or interfaces where reviewers should focus.--Do not claim readiness when required evidence is missing. Say what is missing and the smallest next action that would provide it.diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/multica.plugin.json b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/multica.plugin.jsondeleted file mode 100644index a732ecf32b..0000000000--- a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/multica.plugin.json+++ /dev/null@@ -1,26 +0,0 @@-{- "api_version": "multica.plugin/v1",- "kind": "Plugin",- "metadata": {- "key": "ai.multica.software-delivery",- "name": "Software Delivery",- "description": "Official Multica software-delivery workflow skills.",- "version": "1.1.0",- "publisher": "multica"- },- "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": "review-readiness",- "name": "review-readiness",- "description": "Verify that a software change is ready for review and handoff.",- "entry": "skills/review-readiness/SKILL.md"- }- ]- }-}diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.json b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.jsondeleted file mode 100644index 83afb07c84..0000000000--- a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.json+++ /dev/null@@ -1,7 +0,0 @@-{- "source_ref": "bundled://ai.multica.software-delivery/1.1.0",- "signature_key_id": "multica-plugin-release-2026-01",- "signature_file": "release.sig",- "publisher_type": "official",- "trust_tier": "official"-}diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.sig b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.sigdeleted file mode 100644index 684724caa9..0000000000--- a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.sig+++ /dev/null@@ -1 +0,0 @@-+Yl4EQvwqHlH5mZFkaD2v25Tes8O4LJ1rrRHTnb9K5dtNBePWjka9ZkWKXJs8FZL8H4r1Z/NhZr9MflV9CjxDA==diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/skills/review-readiness/SKILL.md b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/skills/review-readiness/SKILL.mddeleted file mode 100644index 67a622fd4a..0000000000--- a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/skills/review-readiness/SKILL.md+++ /dev/null@@ -1,29 +0,0 @@-----name: review-readiness-description: Verify that a software change has enough evidence, rollout planning, and review context to be safely reviewed.------# Review readiness--Use this skill when preparing a software change for review or deciding whether it is ready to hand off.--## Check the change--1. State the user-visible or operational outcome in one sentence.-2. Confirm the diff is scoped to that outcome and call out intentional exclusions.-3. Record the tests or other evidence that directly exercise the changed behavior, including failure paths.-4. Identify migrations, compatibility constraints, rollout steps, observability, and rollback steps.-5. Surface unresolved risks or decisions instead of hiding them in implementation detail.--## Produce the handoff--Return a compact review brief with:--- outcome and scope;-- key architectural choices;-- evidence run and its result;-- rollout, observability, and rollback notes;-- open risks or decisions;-- exact files or interfaces where reviewers should focus.--Do not claim readiness when required evidence is missing. Say what is missing and the smallest next action that would provide it.diff --git a/server/internal/pluginbundled/trust_roots.json b/server/internal/pluginbundled/trust_roots.jsondeleted file mode 100644index f30a695933..0000000000--- a/server/internal/pluginbundled/trust_roots.json+++ /dev/null@@ -1,8 +0,0 @@-{- "keys": [- {- "id": "multica-plugin-release-2026-01",- "public_key": "40uevCZru/bYuAhZpoNzowNemnBUfGsvdWvFAQGMyyY="- }- ]-}diff --git a/server/internal/service/plugin.go b/server/internal/service/plugin.goindex 0d8e832e5b..15c54dddd2 100644--- a/server/internal/service/plugin.go+++ b/server/internal/service/plugin.go@@ -5,39 +5,48 @@ import ("encoding/json""errors""fmt"- "sort"+ "io"+ "net/http"+ "os"+ "path/filepath"+ "strings""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype"- "github.com/multica-ai/multica/server/internal/pluginbundled""github.com/multica-ai/multica/server/internal/util"+ "github.com/multica-ai/multica/server/internal/util/secretbox"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/pluginruntime"- "github.com/multica-ai/multica/server/pkg/skillbundle"- "golang.org/x/sync/singleflight"+ "github.com/multica-ai/multica/server/pkg/remotemcp")+// LocalSourcePrefix installs from MULTICA_PLUGIN_DIR instead of the network.+// Self-hosted operators and plugin authors need a loop that does not require+// publishing to a public HTTPS host first.+const LocalSourcePrefix = "local:"++// PluginService owns plugin installation, configuration, and plugin-owned+// state. It never executes plugin code: a plugin runs only in the user's+// browser inside a sandboxed iframe, or on the author's own server.type PluginService struct {- Queries *db.Queries- TxStarter TxStarter- BundledCatalog *pluginbundled.Catalog- RemoteMCPSecrets RemoteMCPSecretBox- remoteMCPOAuthRefresh singleflight.Group+ Queries *db.Queries+ TxStarter TxStarter+ // Secrets encrypts `secret` config values. Nil disables secret writes so a+ // misconfigured deployment fails closed instead of storing plaintext.+ Secrets *secretbox.Box+ // LocalDir is MULTICA_PLUGIN_DIR. Empty disables local sources.+ LocalDir string+ // Host gates which declared contributions this build can actually run.+ Host plugincontract.Capabilities}-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,- TxStarter: txStarter,- BundledCatalog: pluginbundled.Load(),+ Queries: queries,+ TxStarter: txStarter,+ LocalDir: strings.TrimSpace(os.Getenv("MULTICA_PLUGIN_DIR")),+ Host: plugincontract.HostCapabilities(),}}@@ -48,6 +57,8 @@ const (PluginErrorNotFound PluginErrorKind = "not_found"PluginErrorConflict PluginErrorKind = "conflict"PluginErrorIncompatible PluginErrorKind = "incompatible"+ PluginErrorQuota PluginErrorKind = "quota"+ PluginErrorUnavailable PluginErrorKind = "unavailable")type PluginError struct {@@ -65,912 +76,563 @@ func (e *PluginError) Error() string {func (e *PluginError) Unwrap() error { return e.Err }-func newPluginError(kind PluginErrorKind, message string, err error) error {- return &PluginError{Kind: kind, Message: message, Err: err}+func pluginErrf(kind PluginErrorKind, format string, args ...any) *PluginError {+ return &PluginError{Kind: kind, Message: fmt.Sprintf(format, args...)}}-func (s *PluginService) CatalogEntries() []pluginbundled.CatalogEntry {- return s.BundledCatalog.List()+// PluginPreview is what the consent screen renders. It is deliberately the raw+// manifest text plus the scope list: there is no signature, no trust tier, and+// no publisher verification in this model, so the administrator reading the+// scopes IS the trust decision.+type PluginPreview struct {+ Manifest plugincontract.Manifest `json:"manifest"`+ Scopes []string `json:"scopes"`+ ConfigSchema []PluginConfigField `json:"config_schema"`+ // Upgrade describes what changes if this replaces an existing install.+ Installed bool `json:"installed"`+ InstalledVersion string `json:"installed_version,omitempty"`+ AddedScopes []string `json:"added_scopes,omitempty"`}-func (s *PluginService) CatalogDiagnostics() []pluginbundled.Diagnostic {- return s.BundledCatalog.Diagnostics()+// PluginConfigField is one host-rendered configuration input.+type PluginConfigField struct {+ Key string `json:"key"`+ Type string `json:"type"`+ Label string `json:"label"`+ Description string `json:"description,omitempty"`+ Required bool `json:"required"`+ Options []string `json:"options,omitempty"`+ Placeholder string `json:"placeholder,omitempty"`}-func (s *PluginService) FindCatalogRelease(pluginKey, version string) (pluginbundled.CatalogEntry, bool) {- if version == "" {- return s.BundledCatalog.Latest(pluginKey)+// ConfigFieldsForManifest flattens the manifest config schema into declaration+// order so the client renders the same form the server validates against.+func ConfigFieldsForManifest(manifest plugincontract.Manifest) []PluginConfigField {+ fields := make([]PluginConfigField, 0, manifest.Config.Len())+ for _, field := range manifest.Config.Fields {+ fields = append(fields, PluginConfigField{+ Key: field.Key,+ Type: field.Type,+ Label: field.Label,+ Description: field.Description,+ Required: field.Required,+ Options: field.Options,+ Placeholder: field.Placeholder,+ })}- return s.BundledCatalog.Find(pluginKey, version)+ return fields}-func (s *PluginService) InstallCatalogRelease(ctx context.Context, workspaceID, actorID pgtype.UUID, pluginKey, version string) (db.PluginInstallation, error) {- entry, ok := s.FindCatalogRelease(pluginKey, version)- if !ok {- return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin release not found", nil)+// FetchManifest resolves a source URL to a parsed manifest.+//+// Network sources reuse the Remote MCP endpoint guard: public HTTPS only, no+// userinfo/query/fragment, private and metadata address ranges refused, and the+// dialer re-checks the resolved address so a DNS rebind between validation and+// connection cannot reach an internal host.+func (s *PluginService) FetchManifest(ctx context.Context, sourceURL string) (plugincontract.Manifest, []byte, error) {+ sourceURL = strings.TrimSpace(sourceURL)+ if sourceURL == "" {+ return plugincontract.Manifest{}, nil, pluginErrf(PluginErrorInvalid, "source_url is required")}- if !entry.Compatible {- return db.PluginInstallation{}, newPluginError(PluginErrorIncompatible, "Plugin release is incompatible with this Multica version", nil)+ if len(sourceURL) > 2048 {+ return plugincontract.Manifest{}, nil, pluginErrf(PluginErrorInvalid, "source_url is too long")}- return s.InstallPluginRelease(ctx, workspaceID, actorID, PluginReleasePublication{- Release: entry.Release,- PublisherType: entry.PublisherType,- TrustTier: entry.TrustTier,- })-}-// 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)+ var raw []byte+ var err error+ if strings.HasPrefix(sourceURL, LocalSourcePrefix) {+ raw, err = s.readLocalManifest(strings.TrimPrefix(sourceURL, LocalSourcePrefix))+ } else {+ raw, err = fetchRemoteManifest(ctx, sourceURL)+ }if err != nil {- return db.PluginInstallation{}, newPluginError(PluginErrorInvalid, "Private Plugin package is invalid", err)+ return plugincontract.Manifest{}, nil, err}- if compatible, _ := pluginbundled.CompatibleWithV1Host(release.Manifest); !compatible {- return db.PluginInstallation{}, newPluginError(PluginErrorIncompatible, "Private Plugin release is incompatible with this Multica version", nil)++ manifest, canonical, parseErr := plugincontract.ParseManifest(raw)+ if parseErr != nil {+ return plugincontract.Manifest{}, nil, &PluginError{Kind: PluginErrorInvalid, Message: "plugin manifest is invalid", Err: parseErr}}- return s.InstallPluginRelease(ctx, workspaceID, actorID, PluginReleasePublication{- Release: release,- PublisherType: privatePluginPublisherType,- TrustTier: privatePluginTrustTier,- })+ return manifest, canonical, nil}-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 {- return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin release not found", nil)+func (s *PluginService) readLocalManifest(name string) ([]byte, error) {+ if s.LocalDir == "" {+ return nil, pluginErrf(PluginErrorInvalid, "local plugin sources require MULTICA_PLUGIN_DIR")}- if !entry.Compatible {- return db.PluginInstallation{}, newPluginError(PluginErrorIncompatible, "Plugin release is incompatible with this Multica version", nil)+ // The name indexes a directory the operator already controls, but it still+ // arrives over the API, so it must not be able to escape the configured+ // root or name a dotfile path.+ if name == "" || strings.ContainsAny(name, `/\`) || strings.HasPrefix(name, ".") {+ return nil, pluginErrf(PluginErrorInvalid, "local plugin source must be a single directory name under MULTICA_PLUGIN_DIR")}-- tx, err := s.TxStarter.Begin(ctx)- if err != nil {- return db.PluginInstallation{}, err+ path := filepath.Join(s.LocalDir, name, plugincontract.ManifestFilename)+ raw, err := os.ReadFile(path)+ if errors.Is(err, os.ErrNotExist) {+ return nil, pluginErrf(PluginErrorNotFound, "no %s found for local plugin %q", plugincontract.ManifestFilename, name)}- defer tx.Rollback(ctx) //nolint:errcheck- q := s.Queries.WithTx(tx)- installation, err := q.GetPluginInstallation(ctx, installationID)- 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)- }- currentRelease, err := q.GetPluginRelease(ctx, installation.DesiredReleaseID)if err != nil {- return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation release not found", nil)+ return nil, &PluginError{Kind: PluginErrorInvalid, Message: "read local plugin manifest", Err: err}}- 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)+ return raw, nil+}++func fetchRemoteManifest(ctx context.Context, sourceURL string) ([]byte, error) {+ endpoint, err := remotemcp.ValidatePublicHTTPSEndpoint(ctx, sourceURL, nil, nil)+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorInvalid, Message: "source_url must be a plain public HTTPS URL", Err: err}}- _, release, err := ensurePluginRelease(ctx, q, workspaceID, PluginReleasePublication{- Release: entry.Release,- PublisherType: entry.PublisherType,- TrustTier: entry.TrustTier,- })+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)if err != nil {- return db.PluginInstallation{}, err+ return nil, &PluginError{Kind: PluginErrorInvalid, Message: "build manifest request", Err: err}}- installation, err = q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{- Enabled: installation.Enabled,- UpdatedBy: actorID,- WorkspaceID: workspaceID,- DesiredReleaseID: release.ID,- ID: installationID,- })+ request.Header.Set("Accept", "application/json")+ response, err := remotemcp.NewSecureHTTPClient(endpoint).Do(request)if err != nil {- return db.PluginInstallation{}, fmt.Errorf("set Plugin desired release: %w", err)+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "fetch plugin manifest", Err: err}}- if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {- return db.PluginInstallation{}, err+ defer response.Body.Close()+ if response.StatusCode != http.StatusOK {+ return nil, pluginErrf(PluginErrorUnavailable, "plugin manifest request returned HTTP %d", response.StatusCode)}- if err := tx.Commit(ctx); err != nil {- return db.PluginInstallation{}, err+ raw, err := io.ReadAll(io.LimitReader(response.Body, plugincontract.MaxManifestSize+1))+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "read plugin manifest", Err: err}}- return s.Queries.GetPluginInstallation(ctx, installationID)-}--// PluginReleasePublication carries the trust decision made by the acquisition-// boundary alongside a release already validated by plugincontract.-type PluginReleasePublication struct {- Release plugincontract.ValidatedRelease- PublisherType string- TrustTier string+ if len(raw) > plugincontract.MaxManifestSize {+ return nil, pluginErrf(PluginErrorInvalid, "plugin manifest exceeds %d bytes", plugincontract.MaxManifestSize)+ }+ return raw, nil}-// InstallPluginRelease publishes an already validated release into the-// immutable registry (idempotently), installs it disabled, and activates an-// empty snapshot. Acquisition, signature trust roots, and user-facing catalogs-// intentionally live outside the lifecycle foundation.-func (s *PluginService) InstallPluginRelease(ctx context.Context, workspaceID, actorID pgtype.UUID, publication PluginReleasePublication) (db.PluginInstallation, error) {- tx, err := s.TxStarter.Begin(ctx)+// PreviewPlugin fetches and parses a manifest without writing anything. It is+// the first half of the two-step install: the administrator must see the scopes+// before an installation row exists.+func (s *PluginService) PreviewPlugin(ctx context.Context, workspaceID pgtype.UUID, sourceURL string) (*PluginPreview, error) {+ manifest, _, err := s.FetchManifest(ctx, sourceURL)if err != nil {- return db.PluginInstallation{}, err+ return nil, err+ }+ if err := manifest.CheckCapabilities(s.Host); err != nil {+ return nil, &PluginError{Kind: PluginErrorIncompatible, Message: capabilityMessage(err), Err: err}}- defer tx.Rollback(ctx) //nolint:errcheck- q := s.Queries.WithTx(tx)- identity, release, err := ensurePluginRelease(ctx, q, workspaceID, publication)- if err != nil {- return db.PluginInstallation{}, err+ preview := &PluginPreview{+ Manifest: manifest,+ Scopes: manifest.Scopes,+ ConfigSchema: ConfigFieldsForManifest(manifest),}- existing, existingErr := q.GetWorkspacePluginInstallation(ctx, db.GetWorkspacePluginInstallationParams{+ existing, err := s.Queries.GetWorkspacePluginInstallationByKey(ctx, db.GetWorkspacePluginInstallationByKeyParams{WorkspaceID: workspaceID,- PluginID: identity.ID,+ PluginKey: manifest.Key,})- if existingErr == nil {- if publication.Release.SourceKind != plugincontract.SourcePrivateDev {- return db.PluginInstallation{}, newPluginError(PluginErrorConflict, "Plugin is already installed", nil)- }- auditAction := "plugin_private_uploaded"- needsReconcile := false- 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)- }- needsReconcile = true- auditAction = "plugin_private_upgraded"- }- // Private Plugin uploads are the capability-approval surface: a fresh- // install grants every requested capability below. Keep upgrades- // consistent by granting capabilities newly introduced by the release.- // Existing denied grants remain denied; an upload must not silently- // override an explicit revocation. This also repairs installations made- // by older servers that activated the contribution metadata but omitted- // its new grant, leaving the Skill visible in status yet absent at run- // time.- grantsChanged, err := grantMissingPrivatePluginCapabilities(- ctx,- q,- workspaceID,- existing.ID,- actorID,- publication.Release.Manifest.RequestedCapabilities,- )- if err != nil {- return db.PluginInstallation{}, err- }- if needsReconcile || grantsChanged {- if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {- return db.PluginInstallation{}, err- }- }- 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- }+ if err == nil {+ preview.Installed = true+ preview.InstalledVersion = existing.Version+ preview.AddedScopes = addedScopes(decodeScopes(existing.GrantedScopes), manifest.Scopes)+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "load existing installation", Err: err}+ }+ return preview, nil+}- installation, err := q.CreatePluginInstallation(ctx, db.CreatePluginInstallationParams{- InstalledBy: actorID,- PluginID: identity.ID,- ReleaseID: release.ID,- WorkspaceID: workspaceID,- })- if err != nil {- return db.PluginInstallation{}, fmt.Errorf("create plugin installation: %w", err)- }- for _, capability := range publication.Release.Manifest.RequestedCapabilities {- if _, err := q.CreatePluginGrantRevision(ctx, db.CreatePluginGrantRevisionParams{- Capability: capability,- Decision: "granted",- Limits: []byte(`{}`),- ApprovedBy: actorID,- InstallationID: installation.ID,- WorkspaceID: workspaceID,- }); err != nil {- return db.PluginInstallation{}, fmt.Errorf("create plugin grant: %w", err)- }- }- if _, 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+func capabilityMessage(err error) string {+ var unavailable *plugincontract.ErrCapabilityUnavailable+ if errors.As(err, &unavailable) {+ return "This plugin declares capabilities that are not enabled yet: " + strings.Join(unavailable.Missing, ", ")}- return s.Queries.GetPluginInstallation(ctx, installation.ID)+ return "This plugin declares capabilities that are not enabled yet"}-func grantMissingPrivatePluginCapabilities(- ctx context.Context,- q *db.Queries,- workspaceID, installationID, actorID pgtype.UUID,- requested []string,-) (bool, error) {- latest, err := q.ListLatestPluginGrants(ctx, installationID)- if err != nil {- return false, fmt.Errorf("list private Plugin grants: %w", err)+func addedScopes(granted []string, wanted []string) []string {+ have := make(map[string]bool, len(granted))+ for _, scope := range granted {+ have[scope] = true}- existing := make(map[string]struct{}, len(latest))- for _, grant := range latest {- existing[grant.Capability] = struct{}{}- }- changed := false- for _, capability := range requested {- if _, ok := existing[capability]; ok {- continue+ added := make([]string, 0)+ for _, scope := range wanted {+ if !have[scope] {+ added = append(added, scope)}- if _, err := q.CreatePluginGrantRevision(ctx, db.CreatePluginGrantRevisionParams{- Capability: capability,- Decision: "granted",- Limits: []byte(`{}`),- ApprovedBy: actorID,- InstallationID: installationID,- WorkspaceID: workspaceID,- }); err != nil {- return false, fmt.Errorf("grant upgraded private Plugin capability %s: %w", capability, err)- }- existing[capability] = struct{}{}- changed = true}- return changed, nil+ return added}-func ensurePluginRelease(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, publication PluginReleasePublication) (db.PluginIdentity, db.PluginRelease, error) {- releaseData := publication.Release- manifest := releaseData.Manifest- if publication.PublisherType == "" || publication.TrustTier == "" {- return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorInvalid, "Plugin publisher trust is required", nil)- }- if len(releaseData.Files) == 0 {- return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorInvalid, "Plugin release contains no artifact files", 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+func decodeScopes(raw []byte) []string {+ var scopes []string+ if len(raw) == 0 {+ return nil}- if err := q.LockPluginRegistryKey(ctx, registryLockKey); err != nil {- return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("lock plugin registry key: %w", err)+ if err := json.Unmarshal(raw, &scopes); err != nil {+ return nil}+ return scopes+}- 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)+// InstallPlugin is the second half of the install. grantedScopes must match the+// manifest exactly: partial consent would leave the plugin silently broken, and+// consenting to a scope the manifest does not request would grant access the+// administrator was never shown a reason for.+func (s *PluginService) InstallPlugin(ctx context.Context, workspaceID, userID pgtype.UUID, sourceURL string, grantedScopes []string) (db.PluginInstallation, error) {+ manifest, canonical, err := s.FetchManifest(ctx, sourceURL)+ if err != nil {+ return db.PluginInstallation{}, err}- 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,- OwnerWorkspaceID: ownerWorkspaceID,- })+ if err := manifest.CheckCapabilities(s.Host); err != nil {+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorIncompatible, Message: capabilityMessage(err), Err: err}}- if err != nil {- return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("ensure plugin identity: %w", err)+ if err := requireExactScopes(manifest.Scopes, grantedScopes); err != nil {+ return db.PluginInstallation{}, err}- if identity.PublisherID != manifest.Metadata.Publisher || identity.PublisherType != publication.PublisherType || identity.TrustTier != publication.TrustTier {- return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorConflict, "Plugin publisher conflicts with the registered identity", nil)+ scopesJSON, err := json.Marshal(manifest.Scopes)+ if err != nil {+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorInvalid, Message: "encode granted scopes", Err: err}}- release, err := q.GetRegisteredPluginReleaseByVersion(ctx, db.GetRegisteredPluginReleaseByVersionParams{- PluginID: identity.ID,- Version: manifest.Metadata.Version,+ existing, err := s.Queries.GetWorkspacePluginInstallationByKey(ctx, db.GetWorkspacePluginInstallationByKeyParams{+ WorkspaceID: workspaceID,+ PluginKey: manifest.Key,})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- }- release, err = q.CreatePluginRelease(ctx, db.CreatePluginReleaseParams{- Version: manifest.Metadata.Version,- Manifest: manifestJSON,- ManifestDigest: releaseData.ManifestDigest,- SourceKind: releaseData.SourceKind,- SourceRef: releaseData.SourceRef,- ArchiveDigest: releaseData.ArchiveDigest,- ArtifactRef: "artifact://" + releaseData.ArtifactDigest,- ArtifactDigest: releaseData.ArtifactDigest,- ArtifactSize: releaseData.ArtifactSize,- Signature: releaseData.Signature,- SignatureKeyID: pgtype.Text{String: releaseData.SignatureKeyID, Valid: releaseData.SignatureKeyID != ""},- PluginID: identity.ID,+ installation, createErr := s.Queries.CreatePluginInstallation(ctx, db.CreatePluginInstallationParams{+ WorkspaceID: workspaceID,+ PluginKey: manifest.Key,+ SourceUrl: sourceURL,+ Version: manifest.Version,+ Manifest: canonical,+ GrantedScopes: scopesJSON,+ InstalledBy: userID,})- if err == nil {- for _, contribution := range releaseData.Contributions {- features, marshalErr := json.Marshal(contribution.RequiredDaemonFeatures)- if marshalErr != nil {- return db.PluginIdentity{}, db.PluginRelease{}, marshalErr- }- if _, err = q.CreatePluginContribution(ctx, db.CreatePluginContributionParams{- ContributionKey: contribution.Key,- Type: contribution.Type,- SchemaVersion: contribution.SchemaVersion,- DisplayName: contribution.DisplayName,- Description: contribution.Description,- EntryPath: contribution.EntryPath,- EntryDigest: contribution.EntryDigest,- RequiredDaemonFeatures: features,- Ordinal: contribution.Ordinal,- ReleaseID: release.ID,- }); err != nil {- break- }- }- }- if err == nil {- for _, file := range releaseData.Files {- _, err = q.CreatePluginArtifactFile(ctx, db.CreatePluginArtifactFileParams{- Path: file.Path,- Digest: file.Digest,- SizeBytes: file.SizeBytes,- Content: string(file.Content),- ReleaseID: release.ID,- })- if err != nil {- break- }+ if createErr != nil {+ // Two admins installing the same plugin at once: one loses the+ // unique index. That is a conflict to retry, not a broken backend.+ if isUniqueViolation(createErr) {+ return db.PluginInstallation{}, pluginErrf(PluginErrorConflict, "this plugin is already installed in this workspace")}+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "install plugin", Err: createErr}}+ return installation, nil}if err != nil {- return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("ensure plugin release: %w", err)- }- if release.RevocationStatus != "active" {- return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorConflict, "Plugin release has been revoked and cannot be installed", nil)+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "load existing installation", Err: err}}- 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,- })+ // Upgrade in place. Values whose fields the new manifest dropped are pruned+ // rather than left as state nothing can reach — and that applies to secrets+ // too, which is the case where unreachable residue is ciphertext. The whole+ // upgrade is one transaction so a snapshot can never land with the previous+ // version's secrets still attached.+ config := pruneConfig(existing.Config, manifest)+ orphanedSecrets, err := s.orphanedSecretKeys(ctx, existing.ID, manifest)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 db.PluginInstallation{}, 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)-}--func (s *PluginService) DisablePlugin(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, false)-}-func (s *PluginService) setPluginBinding(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, scopeType string, scopeID pgtype.UUID, enabled bool) (db.PluginInstallation, error) {- if scopeType != "workspace" && scopeType != "agent" {- return db.PluginInstallation{}, newPluginError(PluginErrorInvalid, "scope_type must be workspace or agent", nil)- }tx, err := s.TxStarter.Begin(ctx)if err != nil {- return db.PluginInstallation{}, err- }- defer tx.Rollback(ctx) //nolint:errcheck- q := s.Queries.WithTx(tx)- installation, err := q.GetPluginInstallation(ctx, installationID)- if 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 enabled {- if err := validateRemoteMCPInstallationReady(ctx, q, workspaceID, installation, release); err != nil {- return db.PluginInstallation{}, err- }- }- if scopeType == "workspace" && scopeID != workspaceID {- return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin binding target not found", nil)- }- if scopeType == "agent" {- if _, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: scopeID, WorkspaceID: workspaceID}); err != nil {- return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin binding target not found", nil)- }+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "begin upgrade", Err: err}}- if _, err := q.CreatePluginBindingRevision(ctx, db.CreatePluginBindingRevisionParams{- ScopeType: scopeType,- ScopeID: scopeID,- Enabled: enabled,- CreatedBy: actorID,- InstallationID: installationID,- WorkspaceID: workspaceID,- }); err != nil {- return db.PluginInstallation{}, fmt.Errorf("create plugin binding: %w", err)- }- bindings, err := q.ListLatestPluginBindings(ctx, installationID)- if err != nil {- return db.PluginInstallation{}, fmt.Errorf("list plugin bindings: %w", err)- }- globalEnabled := false- for _, binding := range bindings {- if binding.Enabled {- globalEnabled = true- break+ defer func() { _ = tx.Rollback(ctx) }()+ queries := s.Queries.WithTx(tx)++ for _, key := range orphanedSecrets {+ if _, err := queries.DeletePluginSecret(ctx, db.DeletePluginSecretParams{InstallationID: existing.ID, Key: key}); err != nil {+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "prune plugin secret", Err: err}}}- installation, err = q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{- Enabled: globalEnabled,- UpdatedBy: actorID,- WorkspaceID: workspaceID,- DesiredReleaseID: installation.DesiredReleaseID,- ID: installationID,+ updated, err := queries.UpdatePluginInstallationManifest(ctx, db.UpdatePluginInstallationManifestParams{+ ID: existing.ID,+ SourceUrl: sourceURL,+ Version: manifest.Version,+ Manifest: canonical,+ GrantedScopes: scopesJSON,+ Config: config,})if err != nil {- return db.PluginInstallation{}, fmt.Errorf("set plugin desired state: %w", err)- }- if _, 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- }+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "upgrade plugin", Err: err}}if err := tx.Commit(ctx); err != nil {- return db.PluginInstallation{}, err+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "commit upgrade", Err: err}}- return s.Queries.GetPluginInstallation(ctx, installationID)+ return updated, nil}-func validateRemoteMCPInstallationReady(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, installation db.PluginInstallation, release db.PluginRelease) error {- contributions, err := q.ListPluginContributionsByRelease(ctx, release.ID)+// orphanedSecretKeys returns stored secrets the new manifest no longer declares+// as a secret field — including a field that changed type away from secret.+func (s *PluginService) orphanedSecretKeys(ctx context.Context, installationID pgtype.UUID, manifest plugincontract.Manifest) ([]string, error) {+ stored, err := s.Queries.ListPluginSecretKeys(ctx, installationID)if err != nil {- return err+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "list plugin secrets", Err: err}}- configs, err := q.ListLatestPluginInstallationConfigs(ctx, db.ListLatestPluginInstallationConfigsParams{- WorkspaceID: workspaceID, InstallationID: installation.ID,- })- if err != nil {- return err+ orphaned := make([]string, 0)+ for _, row := range stored {+ field, ok := manifest.Config.Field(row.Key)+ if !ok || field.Type != plugincontract.ConfigSecret {+ orphaned = append(orphaned, row.Key)+ }}- byContribution := make(map[string]db.PluginInstallationConfig, len(configs))- for _, config := range configs {- byContribution[util.UUIDToString(config.ContributionID)] = config+ return orphaned, nil+}++func requireExactScopes(manifestScopes, grantedScopes []string) error {+ if len(manifestScopes) != len(grantedScopes) {+ return pluginErrf(PluginErrorConflict, "granted_scopes must match the manifest scopes exactly")}- for _, contribution := range contributions {- if contribution.Type != plugincontract.ContributionRemoteMCPV1 {- continue- }- config, ok := byContribution[util.UUIDToString(contribution.ID)]- var approved []pluginruntime.RemoteMCPTool- if ok {- _ = json.Unmarshal(config.ApprovedTools, &approved)- }- if !ok || !config.ReviewedAt.Valid || len(approved) == 0 || !config.SchemaDigest.Valid {- return newPluginError(PluginErrorConflict, "Remote MCP configuration and tool review must be complete before enabling", nil)- }- if config.AuthType != "none" {- if !config.SecretRef.Valid {- return newPluginError(PluginErrorConflict, "Remote MCP credential must be configured before enabling", nil)- }- if _, err := q.GetActivePluginRemoteMCPSecret(ctx, db.GetActivePluginRemoteMCPSecretParams{- ID: config.SecretRef, WorkspaceID: workspaceID, InstallationID: installation.ID, ContributionID: contribution.ID,- }); err != nil {- return newPluginError(PluginErrorConflict, "Remote MCP credential must be configured before enabling", nil)- }+ wanted := make(map[string]bool, len(manifestScopes))+ for _, scope := range manifestScopes {+ wanted[scope] = true+ }+ for _, scope := range grantedScopes {+ if !wanted[scope] {+ return pluginErrf(PluginErrorConflict, "granted_scopes contains %q, which the manifest does not request", scope)}}return nil}-func (s *PluginService) RollbackPlugin(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, version string) (db.PluginInstallation, error) {- tx, err := s.TxStarter.Begin(ctx)- if err != nil {- return db.PluginInstallation{}, err- }- defer tx.Rollback(ctx) //nolint:errcheck- q := s.Queries.WithTx(tx)- installation, err := q.GetPluginInstallation(ctx, installationID)- if err != nil || installation.WorkspaceID != workspaceID {- return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)+func pruneConfig(raw []byte, manifest plugincontract.Manifest) []byte {+ var values map[string]any+ if len(raw) == 0 || json.Unmarshal(raw, &values) != nil {+ return []byte("{}")}- identity, err := q.GetPluginIdentity(ctx, installation.PluginID)- if err != nil {- return db.PluginInstallation{}, err+ for key := range values {+ if _, ok := manifest.Config.Field(key); !ok {+ delete(values, key)+ }}- 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)- }- installation, err = q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{- Enabled: installation.Enabled,- UpdatedBy: actorID,- WorkspaceID: workspaceID,- DesiredReleaseID: release.ID,- ID: installationID,- })+ encoded, err := json.Marshal(values)if err != nil {- return db.PluginInstallation{}, err- }- if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {- return db.PluginInstallation{}, err+ return []byte("{}")}- 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 encoded+}++// ParseInstallationManifest reads back the consented snapshot. Callers must use+// this, never a freshly fetched manifest: what the source URL serves today is+// not what the administrator approved.+func ParseInstallationManifest(installation db.PluginInstallation) (plugincontract.Manifest, error) {+ var manifest plugincontract.Manifest+ if err := json.Unmarshal(installation.Manifest, &manifest); err != nil {+ return plugincontract.Manifest{}, fmt.Errorf("decode stored plugin manifest: %w", err)}- return s.Queries.GetPluginInstallation(ctx, installationID)+ return manifest, nil}-// 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)+// SetConfig validates values against the stored manifest schema and splits them+// by destination: plain values go on the installation row, secrets go to the+// encrypted table. A secret value never lands in `config`.+func (s *PluginService) SetConfig(ctx context.Context, installation db.PluginInstallation, values map[string]any) (db.PluginInstallation, error) {+ manifest, err := ParseInstallationManifest(installation)if err != nil {- return err+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorInvalid, Message: "stored plugin manifest is unreadable", Err: 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)++ plain := map[string]any{}+ secrets := map[string]string{}+ for key, value := range values {+ field, ok := manifest.Config.Field(key)+ if !ok {+ return db.PluginInstallation{}, pluginErrf(PluginErrorInvalid, "unknown config field %q", key)+ }+ if field.Type == plugincontract.ConfigSecret {+ text, ok := value.(string)+ if !ok {+ return db.PluginInstallation{}, pluginErrf(PluginErrorInvalid, "config field %q must be a string", key)+ }+ if len(text) > MaxPluginSecretBytes {+ return db.PluginInstallation{}, pluginErrf(PluginErrorInvalid, "config field %q exceeds %d bytes", key, MaxPluginSecretBytes)+ }+ secrets[key] = text+ continue+ }+ normalized, err := normalizeConfigValue(field, value)+ if err != nil {+ return db.PluginInstallation{}, err+ }+ plain[key] = normalized}- identity, err := q.GetPluginIdentity(ctx, installation.PluginID)- if err != nil {- return err++ // Merge over the stored values so a partial update does not silently clear+ // fields the form did not submit.+ merged := map[string]any{}+ if len(installation.Config) > 0 {+ _ = json.Unmarshal(installation.Config, &merged)}- release, err := q.GetPluginRelease(ctx, installation.DesiredReleaseID)- if err != nil {- return err+ for key, value := range plain {+ merged[key] = value}- uninstalled, err := q.UninstallPluginInstallation(ctx, db.UninstallPluginInstallationParams{- UpdatedBy: actorID,- ID: installationID,- WorkspaceID: workspaceID,- })+ encoded, err := json.Marshal(merged)if err != nil {- return newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)- }- if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {- return err+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorInvalid, Message: "encode plugin config", Err: 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++ if len(secrets) > 0 && s.Secrets == nil {+ return db.PluginInstallation{}, pluginErrf(PluginErrorUnavailable, "plugin secrets are disabled: MULTICA_PLUGIN_SECRET_KEY is not configured")}- return tx.Commit(ctx)-}-func (s *PluginService) ReconcileWorkspace(ctx context.Context, workspaceID pgtype.UUID) (db.PluginCapabilitySnapshot, error) {+ // Secrets and plain values are two tables with no foreign key between them,+ // so one transaction is what keeps a saved form from landing half-applied.tx, err := s.TxStarter.Begin(ctx)if err != nil {- return db.PluginCapabilitySnapshot{}, err+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "begin configure", Err: err}}- defer tx.Rollback(ctx) //nolint:errcheck- snapshot, err := s.reconcileWorkspaceTx(ctx, s.Queries.WithTx(tx), workspaceID)+ defer func() { _ = tx.Rollback(ctx) }()+ queries := s.Queries.WithTx(tx)++ for key, text := range secrets {+ // An empty submission clears the secret rather than storing "".+ if text == "" {+ if _, err := queries.DeletePluginSecret(ctx, db.DeletePluginSecretParams{InstallationID: installation.ID, Key: key}); err != nil {+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "clear plugin secret", Err: err}+ }+ continue+ }+ ciphertext, sealErr := s.Secrets.Seal([]byte(text))+ if sealErr != nil {+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "encrypt plugin secret", Err: sealErr}+ }+ if err := queries.UpsertPluginSecret(ctx, db.UpsertPluginSecretParams{+ InstallationID: installation.ID,+ Key: key,+ Ciphertext: ciphertext,+ }); err != nil {+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "store plugin secret", Err: err}+ }+ }++ updated, err := queries.UpdatePluginInstallationConfig(ctx, db.UpdatePluginInstallationConfigParams{+ ID: installation.ID,+ Config: encoded,+ })if err != nil {- return db.PluginCapabilitySnapshot{}, err+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "store plugin config", Err: err}}if err := tx.Commit(ctx); err != nil {- return db.PluginCapabilitySnapshot{}, err+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "commit configure", Err: err}}- return snapshot, nil+ return updated, nil}-type compilationKey struct {- installationID string- contributionID string+// isUniqueViolation reports a Postgres 23505, the only class of write conflict+// the plugin surface can produce.+func isUniqueViolation(err error) bool {+ var pgErr *pgconn.PgError+ return errors.As(err, &pgErr) && pgErr.Code == "23505"}-func (s *PluginService) reconcileWorkspaceTx(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID) (db.PluginCapabilitySnapshot, error) {- if _, err := q.EnsurePluginWorkspaceCapabilityState(ctx, workspaceID); err != nil {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("ensure plugin capability state: %w", err)+// MaxPluginSecretBytes bounds one secret value before encryption.+const MaxPluginSecretBytes = 8192++func normalizeConfigValue(field plugincontract.ConfigField, value any) (any, error) {+ label := fmt.Sprintf("config field %q", field.Key)+ switch field.Type {+ case plugincontract.ConfigString:+ text, ok := value.(string)+ if !ok {+ return nil, pluginErrf(PluginErrorInvalid, "%s must be a string", label)+ }+ if len(text) > 4096 {+ return nil, pluginErrf(PluginErrorInvalid, "%s exceeds 4096 bytes", label)+ }+ return text, nil+ case plugincontract.ConfigNumber:+ number, ok := value.(float64)+ if !ok {+ return nil, pluginErrf(PluginErrorInvalid, "%s must be a number", label)+ }+ return number, nil+ case plugincontract.ConfigBool:+ flag, ok := value.(bool)+ if !ok {+ return nil, pluginErrf(PluginErrorInvalid, "%s must be a boolean", label)+ }+ return flag, nil+ case plugincontract.ConfigEnum:+ text, ok := value.(string)+ if !ok {+ return nil, pluginErrf(PluginErrorInvalid, "%s must be a string", label)+ }+ for _, option := range field.Options {+ if option == text {+ return text, nil+ }+ }+ return nil, pluginErrf(PluginErrorInvalid, "%s must be one of the declared options", label)+ default:+ return nil, pluginErrf(PluginErrorInvalid, "%s has an unsupported type", label)}- state, err := q.GetPluginWorkspaceCapabilityStateForUpdate(ctx, workspaceID)+}++// ConfiguredSecretKeys reports which secret fields hold a value. It returns+// names only — no endpoint ever returns a secret value, not even masked.+func (s *PluginService) ConfiguredSecretKeys(ctx context.Context, installationID pgtype.UUID) ([]string, error) {+ rows, err := s.Queries.ListPluginSecretKeys(ctx, installationID)if err != nil {- return db.PluginCapabilitySnapshot{}, err+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "list plugin secrets", Err: err}}- installations, err := q.ListPluginInstallationsForCompile(ctx, workspaceID)+ keys := make([]string, 0, len(rows))+ for _, row := range rows {+ keys = append(keys, row.Key)+ }+ return keys, nil+}++// SetEnabled toggles an installation. Disabling hides every contribution+// immediately but keeps storage and secrets, so re-enabling is not a reinstall.+func (s *PluginService) SetEnabled(ctx context.Context, installation db.PluginInstallation, enabled bool) (db.PluginInstallation, error) {+ updated, err := s.Queries.SetPluginInstallationEnabled(ctx, db.SetPluginInstallationEnabledParams{+ ID: installation.ID,+ Enabled: enabled,+ })if err != nil {- return db.PluginCapabilitySnapshot{}, err+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "update plugin state", Err: err}}- rows, err := q.ListPluginCompilationContributions(ctx, workspaceID)+ return updated, nil+}++// Uninstall removes the installation with its storage and secrets. There are no+// foreign keys or cascades by repository policy, so the three deletes share one+// transaction: a partial uninstall would strand plugin-owned rows nothing can+// reach or clean up later.+func (s *PluginService) Uninstall(ctx context.Context, installation db.PluginInstallation) error {+ tx, err := s.TxStarter.Begin(ctx)if err != nil {- return db.PluginCapabilitySnapshot{}, err+ return &PluginError{Kind: PluginErrorUnavailable, Message: "begin uninstall", Err: err}}+ defer func() { _ = tx.Rollback(ctx) }()- sourceGenerations := make(map[string]int64, len(installations))- for _, installation := range installations {- sourceGenerations[util.UUIDToString(installation.ID)] = installation.DesiredGeneration+ queries := s.Queries.WithTx(tx)+ if err := queries.DeletePluginStorageByInstallation(ctx, installation.ID); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin storage", Err: err}}- grouped := make(map[compilationKey][]db.ListPluginCompilationContributionsRow)- keys := make([]compilationKey, 0)- for _, row := range rows {- key := compilationKey{util.UUIDToString(row.InstallationID), util.UUIDToString(row.ContributionID)}- if _, exists := grouped[key]; !exists {- keys = append(keys, key)- }- grouped[key] = append(grouped[key], row)+ if err := queries.DeletePluginSecretsByInstallation(ctx, installation.ID); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin secrets", Err: err}}- sort.Slice(keys, func(i, j int) bool {- if keys[i].installationID != keys[j].installationID {- return keys[i].installationID < keys[j].installationID- }- return keys[i].contributionID < keys[j].contributionID- })-- entries := make([]pluginruntime.CompiledEntry, 0, len(rows))- releaseFiles := make(map[string][]db.PluginArtifactFile)- for _, key := range keys {- contributionRows := grouped[key]- row := contributionRows[0]- if plugincontract.DigestBytes([]byte(row.EntryContent)) != row.EntryDigest {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("plugin contribution %s failed digest validation", row.ContributionKey)- }- var features []string- if err := json.Unmarshal(row.RequiredDaemonFeatures, &features); err != nil {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("decode daemon features: %w", err)- }- base := pluginruntime.CompiledEntry{- PluginID: util.UUIDToString(row.PluginID),- PluginKey: row.PluginKey,- InstallationID: util.UUIDToString(row.InstallationID),- ReleaseID: util.UUIDToString(row.ReleaseID),- ReleaseVersion: row.ReleaseVersion,- ContributionID: util.UUIDToString(row.ContributionID),- ContributionKey: row.ContributionKey,- ContributionType: row.ContributionType,- DisplayName: row.DisplayName,- Description: row.Description,- SourceKind: row.SourceKind,- ArtifactFileID: util.UUIDToString(row.ArtifactFileID),- ArtifactRef: row.ArtifactRef,- ArtifactDigest: row.ArtifactDigest,- EntryPath: row.EntryPath,- EntryDigest: row.EntryDigest,- RequiredDaemonFeatures: features,- Ordinal: row.Ordinal,- }- switch row.ContributionType {- case plugincontract.ContributionAgentSkillV1:- releaseKey := util.UUIDToString(row.ReleaseID)- artifactFiles, ok := releaseFiles[releaseKey]- if !ok {- artifactFiles, err = q.ListPluginArtifactFilesByRelease(ctx, row.ReleaseID)- if err != nil {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("load plugin Skill artifacts: %w", err)- }- releaseFiles[releaseKey] = artifactFiles- }- pinnedFiles, bundleFiles, err := compilePluginSkillFiles(row.ReleaseID, row.ContributionKey, row.EntryPath, artifactFiles)- if err != nil {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("compile plugin Skill %s: %w", row.ContributionKey, err)- }- bundleManifest := skillbundle.BuildManifest(skillbundle.Skill{- ID: "plugin:" + util.UUIDToString(row.ContributionID),- Source: skillbundle.SourcePlugin,- Name: row.ContributionKey,- Description: row.Description,- Content: row.EntryContent,- Files: bundleFiles,- })- base.SkillBundleHash = bundleManifest.Hash- base.SkillSizeBytes = bundleManifest.SizeBytes- base.SkillFileCount = bundleManifest.FileCount- base.SkillFiles = pinnedFiles- case plugincontract.ContributionRemoteMCPV1:- if !row.ConfigID.Valid || !row.ConfigRevision.Valid || !row.Endpoint.Valid || !row.AuthType.Valid || !row.FailurePolicy.Valid || !row.SchemaDigest.Valid {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("remote MCP contribution %s has incomplete reviewed configuration", row.ContributionKey)- }- var tools []pluginruntime.RemoteMCPTool- if err := json.Unmarshal(row.ApprovedTools, &tools); err != nil || len(tools) == 0 {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("remote MCP contribution %s has invalid approved tools", row.ContributionKey)- }- base.ConfigID = util.UUIDToString(row.ConfigID)- base.ConfigRevision = row.ConfigRevision.Int64- base.Endpoint = row.Endpoint.String- base.PublicConfig = append(json.RawMessage(nil), row.PublicConfig...)- base.SecretRef = util.UUIDToString(row.SecretRef)- base.AuthType = row.AuthType.String- base.AuthHeader = row.AuthHeader.String- base.ApprovedTools = tools- base.ToolSchemaDigest = row.SchemaDigest.String- base.FailurePolicy = row.FailurePolicy.String- var manifest plugincontract.Manifest- if err := json.Unmarshal([]byte(row.EntryContent), &manifest); err != nil {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("remote MCP contribution %s has invalid manifest entry", row.ContributionKey)- }- foundDeclaration := false- for _, declaration := range manifest.Contributes.RemoteMCP {- if declaration.Key == row.ContributionKey {- base.Transport = declaration.Transport- base.ProtocolVersions = append([]string(nil), declaration.ProtocolVersions...)- base.EndpointAllowedHosts = append([]string(nil), declaration.EndpointPolicy.AllowedHosts...)- foundDeclaration = true- break- }- }- if !foundDeclaration {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("remote MCP contribution %s is absent from its manifest entry", row.ContributionKey)- }- default:- return db.PluginCapabilitySnapshot{}, fmt.Errorf("unsupported plugin contribution type %q", row.ContributionType)- }-- var workspaceBinding *db.ListPluginCompilationContributionsRow- agentBindings := make([]db.ListPluginCompilationContributionsRow, 0)- for i := range contributionRows {- binding := contributionRows[i]- if !binding.ScopeType.Valid || !binding.ScopeID.Valid || !binding.BindingEnabled.Valid {- continue- }- if binding.ScopeType.String == "workspace" {- copy := binding- workspaceBinding = ©- } else if binding.ScopeType.String == "agent" {- agentBindings = append(agentBindings, binding)- }- }- if workspaceBinding != nil && workspaceBinding.BindingEnabled.Bool {- workspaceEntry := base- workspaceEntry.ScopeType = "workspace"- workspaceEntry.ScopeID = util.UUIDToString(workspaceID)- for _, binding := range agentBindings {- workspaceEntry.ExcludedAgentIDs = append(workspaceEntry.ExcludedAgentIDs, util.UUIDToString(binding.ScopeID))- }- entries = append(entries, workspaceEntry)- }- for _, binding := range agentBindings {- if !binding.BindingEnabled.Bool {- continue- }- agentEntry := base- agentEntry.ScopeType = "agent"- agentEntry.ScopeID = util.UUIDToString(binding.ScopeID)- entries = append(entries, agentEntry)- }+ if err := queries.DeletePluginInstallation(ctx, installation.ID); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin installation", Err: err}+ }+ if err := tx.Commit(ctx); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "commit uninstall", Err: err}}+ return nil+}- digest, err := pluginruntime.SnapshotDigest(sourceGenerations, entries)- if err != nil {- return db.PluginCapabilitySnapshot{}, err- }- sourceJSON, _ := json.Marshal(sourceGenerations)- entriesJSON, _ := json.Marshal(entries)- snapshot, err := q.CreatePluginCapabilitySnapshot(ctx, db.CreatePluginCapabilitySnapshotParams{- WorkspaceID: workspaceID,- Revision: state.NextRevision,- SourceGenerations: sourceJSON,- CompilerVersion: pluginruntime.CompilerVersion,- SchemaVersion: pluginruntime.SchemaVersion,- SnapshotDigest: digest,- CompiledEntries: entriesJSON,- Diagnostics: []byte(`[]`),- })+// InstallationForWorkspace loads an installation and confirms it belongs to the+// workspace in the URL, so an id from another workspace cannot be operated on.+func (s *PluginService) InstallationForWorkspace(ctx context.Context, workspaceID pgtype.UUID, installationID string) (db.PluginInstallation, error) {+ parsed, err := util.ParseUUID(installationID)if err != nil {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("create plugin capability snapshot: %w", err)+ return db.PluginInstallation{}, pluginErrf(PluginErrorNotFound, "plugin installation not found")}- if _, err := q.ActivatePluginWorkspaceCapabilitySnapshot(ctx, db.ActivatePluginWorkspaceCapabilitySnapshotParams{- ActiveSnapshotID: snapshot.ID,- ActiveRevision: snapshot.Revision,- NextRevision: snapshot.Revision + 1,- WorkspaceID: workspaceID,- }); err != nil {- return db.PluginCapabilitySnapshot{}, fmt.Errorf("activate plugin capability snapshot: %w", err)+ installation, err := s.Queries.GetWorkspacePluginInstallation(ctx, db.GetWorkspacePluginInstallationParams{+ WorkspaceID: workspaceID,+ ID: parsed,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return db.PluginInstallation{}, pluginErrf(PluginErrorNotFound, "plugin installation not found")}- activated, err := q.ActivatePluginInstallations(ctx, workspaceID)if err != nil {- return db.PluginCapabilitySnapshot{}, err- }- for _, installation := range activated {- stateName, reason := "healthy", "snapshot_activated"- if !installation.Enabled {- stateName, reason = "disabled", "installation_disabled"- }- if _, err := q.CreatePluginHealth(ctx, db.CreatePluginHealthParams{- WorkspaceID: workspaceID,- InstallationID: installation.ID,- ScopeType: "workspace",- ScopeID: workspaceID,- State: stateName,- ReasonCode: reason,- SafeDetail: "",- ObservedGeneration: installation.ActiveGeneration,- LastGoodSnapshotID: snapshot.ID,- }); err != nil {- return db.PluginCapabilitySnapshot{}, err- }+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "load plugin installation", Err: err}}- return snapshot, nil+ return installation, nil}diff --git a/server/internal/service/plugin_integration_test.go b/server/internal/service/plugin_integration_test.godeleted file mode 100644index 60bab13f49..0000000000--- a/server/internal/service/plugin_integration_test.go+++ /dev/null@@ -1,456 +0,0 @@-package service--import (- "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")- if databaseURL == "" {- databaseURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"- }- pool, err := pgxpool.New(ctx, databaseURL)- if err != nil {- t.Skipf("database unavailable: %v", err)- }- defer pool.Close()- var pluginTablesExist bool- if err := pool.QueryRow(ctx, `SELECT to_regclass('plugin_capability_snapshot') IS NOT NULL`).Scan(&pluginTablesExist); err != nil || !pluginTablesExist {- t.Skip("plugin migrations are not applied")- }-- suffix := time.Now().UnixNano()- var userID, workspaceID, isolationWorkspaceID, runtimeID, agentID, issueID string- if 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)- }- if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug, description, issue_prefix) VALUES ('Plugin E2E', $1, '', 'PE2') RETURNING id`, fmt.Sprintf("plugin-e2e-%d", suffix)).Scan(&workspaceID); err != nil {- t.Fatal(err)- }- if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`, workspaceID, userID); err != nil {- t.Fatal(err)- }- if err := pool.QueryRow(ctx, `- INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, visibility, owner_id)- VALUES ($1, 'Plugin E2E', 'cloud', 'plugin_e2e', 'online', 'test', '{}'::jsonb, now(), 'private', $2) RETURNING id- `, workspaceID, userID).Scan(&runtimeID); err != nil {- t.Fatal(err)- }- if err := pool.QueryRow(ctx, `- INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id)- VALUES ($1, 'Plugin E2E', '', 'cloud', '{}'::jsonb, $2, 'private', 1, $3) RETURNING id- `, workspaceID, runtimeID, userID).Scan(&agentID); err != nil {- t.Fatal(err)- }- if err := pool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'Plugin E2E', 'in_progress', 'none', $2, 'member', $3, 0) RETURNING id- `, workspaceID, userID, suffix%100000000).Scan(&issueID); err != nil {- t.Fatal(err)- }- t.Cleanup(func() {- cleanup := context.Background()- 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 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)- pool.Exec(cleanup, `DELETE FROM member WHERE workspace_id = $1`, workspaceID)- pool.Exec(cleanup, `DELETE FROM workspace WHERE id = $1`, workspaceID)- pool.Exec(cleanup, `DELETE FROM "user" WHERE id = $1`, userID)- })-- queries := db.New(pool)- pluginService := NewPluginService(queries, pool)- taskService := NewTaskService(queries, pool, nil, nil)- workspaceUUID := util.MustParseUUID(workspaceID)- actorUUID := util.MustParseUUID(userID)- release, err := plugintest.ReviewReadinessRelease()- if err != nil {- t.Fatalf("reference release: %v", err)- }- installation, err := pluginService.InstallPluginRelease(ctx, workspaceUUID, actorUUID, PluginReleasePublication{- Release: release,- PublisherType: "official",- TrustTier: "official",- })- if err != nil {- t.Fatalf("install: %v", err)- }- if installation.Enabled {- t.Fatal("install must not implicitly enable plugin")- }- installation, err = pluginService.EnablePlugin(ctx, workspaceUUID, installation.ID, actorUUID, "workspace", workspaceUUID)- if err != nil {- t.Fatalf("enable: %v", err)- }- if !installation.Enabled || installation.ActiveGeneration != installation.DesiredGeneration {- t.Fatalf("installation not active: %+v", installation)- }-- createTask := func(retryOf any) string {- var taskID string- err := pool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, status, priority, context, runtime_id, retry_of_task_id)- VALUES ($1, $2, 'queued', 0, '{}'::jsonb, $3, $4) RETURNING id- `, agentID, issueID, runtimeID, retryOf).Scan(&taskID)- if err != nil {- t.Fatalf("create task: %v", err)- }- return taskID- }- firstTaskID := createTask(nil)- bundles, refs, manifest, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(firstTaskID))- if err != nil {- t.Fatalf("load pinned bundles: %v", err)- }- if len(bundles) != 1 || len(refs) != 1 || manifest == nil || !strings.Contains(bundles[0].Content, "# Review readiness") {- t.Fatalf("unexpected enabled task plugin payload: bundles=%d refs=%d manifest=%+v", len(bundles), len(refs), manifest)- }- if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, firstTaskID); err != nil {- t.Fatalf("complete first task: %v", err)- }-- if _, err := pluginService.DisablePlugin(ctx, workspaceUUID, installation.ID, actorUUID, "workspace", workspaceUUID); err != nil {- t.Fatalf("disable: %v", err)- }- oldBundles, _, _, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(firstTaskID))- if err != nil || len(oldBundles) != 1 {- t.Fatalf("disable changed pinned task: bundles=%d err=%v", len(oldBundles), err)- }- newTaskID := createTask(nil)- newBundles, _, _, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(newTaskID))- if err != nil || len(newBundles) != 0 {- t.Fatalf("disabled plugin leaked into new task: bundles=%d err=%v", len(newBundles), err)- }- if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, newTaskID); err != nil {- t.Fatalf("complete disabled task: %v", err)- }- agentUUID := util.MustParseUUID(agentID)- installation, err = pluginService.EnablePlugin(ctx, workspaceUUID, installation.ID, actorUUID, "agent", agentUUID)- if err != nil || !installation.Enabled {- t.Fatalf("enable agent scope: installation=%+v err=%v", installation, err)- }- agentTaskID := createTask(nil)- agentBundles, _, _, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(agentTaskID))- if err != nil || len(agentBundles) != 1 {- t.Fatalf("agent-scoped Plugin missing from task: bundles=%d err=%v", len(agentBundles), err)- }- if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, agentTaskID); err != nil {- t.Fatalf("complete agent-scoped task: %v", err)- }- installation, err = pluginService.DisablePlugin(ctx, workspaceUUID, installation.ID, actorUUID, "agent", agentUUID)- if err != nil || installation.Enabled {- t.Fatalf("disable last active binding: installation=%+v err=%v", installation, err)- }- retryTaskID := createTask(firstTaskID)- retryBundles, _, retryManifest, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(retryTaskID))- 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 len(privateV1Bundles[0].Files) != 1 || privateV1Bundles[0].Files[0].Path != "references/severity-guide.md" || !strings.Contains(privateV1Bundles[0].Files[0].Content, "SEV-1") {- t.Fatalf("private v1 Skill companion files = %#v", privateV1Bundles[0].Files)- }- if len(privateV1Manifest.OrderedContributions) != 1 || len(privateV1Manifest.OrderedContributions[0].SkillFiles) != 1 || privateV1Manifest.OrderedContributions[0].SkillFileCount != 1 {- t.Fatalf("private v1 execution manifest did not pin companion files: %+v", privateV1Manifest.OrderedContributions)- }- 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)- }- // Simulate an installation upgraded by an older server that retained only- // the release metadata and missed a newly requested capability grant. An- // idempotent upload must repair the missing grant and recompile the active- // snapshot so the contribution reaches the next task.- if _, err := pool.Exec(ctx, `- DELETE FROM plugin_grant- WHERE installation_id = $1 AND capability = 'agent.skill.contribute'- `, privateInstallation.ID); err != nil {- t.Fatalf("remove private Plugin grant: %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)- }- var repairedGrant string- if err := pool.QueryRow(ctx, `- SELECT decision FROM plugin_grant- WHERE installation_id = $1 AND capability = 'agent.skill.contribute'- ORDER BY grant_revision DESC LIMIT 1- `, privateInstallation.ID).Scan(&repairedGrant); err != nil || repairedGrant != "granted" {- t.Fatalf("private Plugin grant was not repaired: decision=%q err=%v", repairedGrant, 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)- }- if len(historicalBundles[0].Files) != 1 || historicalBundles[0].Files[0].Path != "references/severity-guide.md" {- t.Fatalf("uninstall changed historical private Skill companion files: %#v", historicalBundles[0].Files)- }- 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/internal/service/plugin_remote_mcp.go b/server/internal/service/plugin_remote_mcp.godeleted file mode 100644index 425871fd20..0000000000--- a/server/internal/service/plugin_remote_mcp.go+++ /dev/null@@ -1,690 +0,0 @@-package service--import (- "context"- "encoding/json"- "errors"- "fmt"- "net/http"- "regexp"- "strings"-- "github.com/jackc/pgx/v5"- "github.com/jackc/pgx/v5/pgtype"- db "github.com/multica-ai/multica/server/pkg/db/generated"- "github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/pluginruntime"- "github.com/multica-ai/multica/server/pkg/remotemcp"-)--type RemoteMCPSecretBox interface {- Seal([]byte) ([]byte, error)- Open([]byte) ([]byte, error)-}--type RemoteMCPConfigInput struct {- Endpoint string- PublicConfig json.RawMessage- AuthType string- AuthHeader string- Credential string- FailurePolicy string-}--type RemoteMCPConfigResult struct {- Config db.PluginInstallationConfig- DiscoveredTools []pluginruntime.RemoteMCPTool- SchemaDigest string-}--func (s *PluginService) TestRemoteMCP(ctx context.Context, workspaceID, installationID pgtype.UUID, contributionKey string) (RemoteMCPConfigResult, error) {- contribution, declaration, err := s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, contributionKey)- if err != nil {- return RemoteMCPConfigResult{}, err- }- latest, err := s.Queries.GetLatestPluginInstallationConfig(ctx, db.GetLatestPluginInstallationConfigParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,- })- if err != nil {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorConflict, "Remote MCP is not configured", err)- }- headers, err := s.remoteMCPHeaders(ctx, workspaceID, installationID, contribution.ID, latest.AuthType, latest.AuthHeader, "", latest.SecretRef)- if err != nil {- return RemoteMCPConfigResult{}, err- }- tools, digest, err := remotemcp.Discover(ctx, latest.Endpoint, declaration.EndpointPolicy.AllowedHosts, declaration.ProtocolVersions, headers)- if err != nil {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP connection test failed", err)- }- applyDeclaredRisk(tools, declaration)- return RemoteMCPConfigResult{Config: latest, DiscoveredTools: tools, SchemaDigest: digest}, nil-}--var remoteMCPHeaderPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9-]{0,127}$`)--func (s *PluginService) ConfigureRemoteMCP(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, contributionKey string, input RemoteMCPConfigInput) (RemoteMCPConfigResult, error) {- contribution, declaration, err := s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, contributionKey)- if err != nil {- return RemoteMCPConfigResult{}, err- }- if _, err := remotemcp.ValidatePublicHTTPSEndpoint(ctx, input.Endpoint, declaration.EndpointPolicy.AllowedHosts, nil); err != nil {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP endpoint is not allowed", err)- }- publicConfig, err := validateRemoteMCPPublicConfig(input.PublicConfig, declaration.ConfigurationSchema)- if err != nil {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP public configuration is invalid", err)- }- input.AuthType = strings.TrimSpace(input.AuthType)- input.AuthHeader = strings.TrimSpace(input.AuthHeader)- input.FailurePolicy = strings.TrimSpace(input.FailurePolicy)- if input.FailurePolicy == "" {- input.FailurePolicy = "required"- }- if input.FailurePolicy != "required" && input.FailurePolicy != "optional" {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "failure_policy must be required or optional", nil)- }- if input.AuthType != "none" && input.AuthType != "bearer" && input.AuthType != "header" {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "auth_type must be none, bearer, or header", nil)- }- if input.AuthType == "bearer" {- input.AuthHeader = "Authorization"- }- if input.AuthType == "header" && !validRemoteMCPAuthHeader(input.AuthHeader) {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "auth_header is invalid", nil)- }- if input.AuthType == "none" && input.Credential != "" {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "credential is not allowed with auth_type none", nil)- }-- var existingSecret pgtype.UUID- if input.AuthType != "none" && input.Credential == "" {- latest, latestErr := s.Queries.GetLatestPluginInstallationConfig(ctx, db.GetLatestPluginInstallationConfigParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,- })- if latestErr != nil || !latest.SecretRef.Valid || latest.AuthType != input.AuthType || latest.AuthHeader != input.AuthHeader {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "credential is required", nil)- }- existingSecret = latest.SecretRef- }- headers, err := s.remoteMCPHeaders(ctx, workspaceID, installationID, contribution.ID, input.AuthType, input.AuthHeader, input.Credential, existingSecret)- if err != nil {- return RemoteMCPConfigResult{}, err- }- discovered, digest, err := remotemcp.Discover(ctx, input.Endpoint, declaration.EndpointPolicy.AllowedHosts, declaration.ProtocolVersions, headers)- if err != nil {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP connection test failed", err)- }- applyDeclaredRisk(discovered, declaration)- discoveredJSON, _ := json.Marshal(discovered)-- tx, err := s.TxStarter.Begin(ctx)- if err != nil {- return RemoteMCPConfigResult{}, err- }- defer tx.Rollback(ctx) //nolint:errcheck- q := s.Queries.WithTx(tx)- secretRef := existingSecret- if input.AuthType != "none" && input.Credential != "" {- if _, lockErr := q.LockPluginRemoteMCPInstallation(ctx, db.LockPluginRemoteMCPInstallationParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,- }); lockErr != nil {- return RemoteMCPConfigResult{}, lockErr- }- if s.RemoteMCPSecrets == nil {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorIncompatible, "Remote MCP credential encryption is not configured", nil)- }- sealed, sealErr := s.RemoteMCPSecrets.Seal([]byte(input.Credential))- if sealErr != nil {- return RemoteMCPConfigResult{}, fmt.Errorf("encrypt Remote MCP credential: %w", sealErr)- }- if _, revokeErr := q.RevokePluginRemoteMCPSecrets(ctx, db.RevokePluginRemoteMCPSecretsParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,- }); revokeErr != nil {- return RemoteMCPConfigResult{}, revokeErr- }- secret, createErr := q.CreatePluginRemoteMCPSecret(ctx, db.CreatePluginRemoteMCPSecretParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,- Ciphertext: sealed, Hint: secretHint(input.Credential), CreatedBy: actorID,- })- if createErr != nil {- return RemoteMCPConfigResult{}, createErr- }- secretRef = secret.ID- }- config, err := q.CreatePluginInstallationConfig(ctx, db.CreatePluginInstallationConfigParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,- Endpoint: input.Endpoint, PublicConfig: publicConfig, AuthType: input.AuthType, AuthHeader: input.AuthHeader,- SecretRef: secretRef, DiscoveredTools: discoveredJSON,- DiscoveredSchemaDigest: pgtype.Text{String: digest, Valid: true},- ApprovedTools: []byte(`[]`), FailurePolicy: input.FailurePolicy, CreatedBy: actorID,- })- if err != nil {- return RemoteMCPConfigResult{}, err- }- if _, err := s.bumpPluginConfigurationGeneration(ctx, q, workspaceID, installationID, actorID); err != nil {- return RemoteMCPConfigResult{}, err- }- if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {- return RemoteMCPConfigResult{}, err- }- if err := tx.Commit(ctx); err != nil {- return RemoteMCPConfigResult{}, err- }- return RemoteMCPConfigResult{Config: config, DiscoveredTools: discovered, SchemaDigest: digest}, nil-}--func validRemoteMCPAuthHeader(header string) bool {- if !remoteMCPHeaderPattern.MatchString(header) {- return false- }- for _, forbidden := range []string{- "Host", "Connection", "Content-Length", "Content-Type", "Accept",- "Transfer-Encoding", "Trailer", "Upgrade", "Proxy-Authorization",- "Mcp-Session-Id", "Mcp-Protocol-Version", "Last-Event-ID",- } {- if strings.EqualFold(header, forbidden) {- return false- }- }- return true-}--func (s *PluginService) ReviewRemoteMCPTools(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, contributionKey string, approvedNames []string) (RemoteMCPConfigResult, error) {- contribution, declaration, err := s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, contributionKey)- if err != nil {- return RemoteMCPConfigResult{}, err- }- latest, err := s.Queries.GetLatestPluginInstallationConfig(ctx, db.GetLatestPluginInstallationConfigParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,- })- if err != nil {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorConflict, "Remote MCP must be configured before tool review", err)- }- headers, err := s.remoteMCPHeaders(ctx, workspaceID, installationID, contribution.ID, latest.AuthType, latest.AuthHeader, "", latest.SecretRef)- if err != nil {- return RemoteMCPConfigResult{}, err- }- discovered, discoveredDigest, err := remotemcp.Discover(ctx, latest.Endpoint, declaration.EndpointPolicy.AllowedHosts, declaration.ProtocolVersions, headers)- if err != nil {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP tool discovery failed", err)- }- applyDeclaredRisk(discovered, declaration)- approved, err := selectApprovedRemoteMCPTools(discovered, declaration, approvedNames)- if err != nil {- return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP tool approval is invalid", err)- }- digest, err := remotemcp.ToolSetDigest(approved)- if err != nil {- return RemoteMCPConfigResult{}, err- }- approvedJSON, _ := json.Marshal(approved)- discoveredJSON, _ := json.Marshal(discovered)-- tx, err := s.TxStarter.Begin(ctx)- if err != nil {- return RemoteMCPConfigResult{}, err- }- defer tx.Rollback(ctx) //nolint:errcheck- q := s.Queries.WithTx(tx)- config, err := q.CreatePluginInstallationConfig(ctx, db.CreatePluginInstallationConfigParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,- Endpoint: latest.Endpoint, PublicConfig: latest.PublicConfig, AuthType: latest.AuthType, AuthHeader: latest.AuthHeader,- SecretRef: latest.SecretRef, DiscoveredTools: discoveredJSON,- DiscoveredSchemaDigest: pgtype.Text{String: discoveredDigest, Valid: true}, ApprovedTools: approvedJSON,- SchemaDigest: pgtype.Text{String: digest, Valid: true}, FailurePolicy: latest.FailurePolicy,- ReviewedBy: actorID, CreatedBy: actorID,- })- if err != nil {- return RemoteMCPConfigResult{}, err- }- if _, err := s.bumpPluginConfigurationGeneration(ctx, q, workspaceID, installationID, actorID); err != nil {- return RemoteMCPConfigResult{}, err- }- if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {- return RemoteMCPConfigResult{}, err- }- if err := tx.Commit(ctx); err != nil {- return RemoteMCPConfigResult{}, err- }- return RemoteMCPConfigResult{Config: config, DiscoveredTools: discovered, SchemaDigest: digest}, nil-}--func (s *PluginService) RevokeRemoteMCPCredential(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, contributionKey string) error {- contribution, _, err := s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, contributionKey)- if err != nil {- return err- }- tx, err := s.TxStarter.Begin(ctx)- if err != nil {- return err- }- defer tx.Rollback(ctx) //nolint:errcheck- q := s.Queries.WithTx(tx)- if _, err := q.LockPluginRemoteMCPInstallation(ctx, db.LockPluginRemoteMCPInstallationParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,- }); err != nil {- return err- }- if _, err := q.RevokePluginRemoteMCPSecrets(ctx, db.RevokePluginRemoteMCPSecretsParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,- }); err != nil {- return err- }- installation, err := q.GetPluginInstallation(ctx, installationID)- if err != nil {- return err- }- if _, err := q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{- Enabled: false, UpdatedBy: actorID, WorkspaceID: workspaceID,- DesiredReleaseID: installation.DesiredReleaseID, ID: installationID,- }); err != nil {- return err- }- if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {- return err- }- return tx.Commit(ctx)-}--// ResolveTaskRemoteMCPConnections returns only pinned connection metadata.-// Credentials stay server-side and are resolved by the daemon broker's-// authenticated, task-scoped endpoint immediately before an upstream call.-func (s *PluginService) ResolveTaskRemoteMCPConnections(ctx context.Context, taskID pgtype.UUID) ([]pluginruntime.RemoteMCPConnection, []string, error) {- manifest, err := s.Queries.GetPluginExecutionManifestByTask(ctx, taskID)- if errors.Is(err, pgx.ErrNoRows) {- return nil, nil, nil- }- if err != nil {- return nil, nil, err- }- entries, err := pluginruntime.ParseEntries(manifest.OrderedContributions)- if err != nil {- return nil, nil, err- }- connections := make([]pluginruntime.RemoteMCPConnection, 0)- diagnostics := make([]string, 0)- for _, entry := range entries {- if entry.ContributionType != plugincontract.ContributionRemoteMCPV1 {- continue- }- connection, _, resolveErr := s.resolveTaskRemoteMCPEntry(ctx, manifest.WorkspaceID, entry, false)- if resolveErr != nil {- if entry.FailurePolicy == "optional" {- diagnostics = append(diagnostics, fmt.Sprintf("optional Remote MCP %s unavailable", entry.ContributionKey))- continue- }- return nil, diagnostics, fmt.Errorf("required Remote MCP %s is unavailable: %w", entry.ContributionKey, resolveErr)- }- connections = append(connections, connection)- }- return connections, diagnostics, nil-}--// ResolveTaskRemoteMCPCredential re-checks the active secret row for every-// broker call. This is the revocation boundary for already-running tasks: a-// revoked or rotated pinned credential becomes unusable before another-// upstream request is made.-func (s *PluginService) ResolveTaskRemoteMCPCredential(ctx context.Context, taskID pgtype.UUID, contributionID string) (string, string, error) {- manifest, err := s.Queries.GetPluginExecutionManifestByTask(ctx, taskID)- if err != nil {- return "", "", newPluginError(PluginErrorNotFound, "Remote MCP task credential not found", err)- }- entries, err := pluginruntime.ParseEntries(manifest.OrderedContributions)- if err != nil {- return "", "", err- }- for _, entry := range entries {- if entry.ContributionType != plugincontract.ContributionRemoteMCPV1 || entry.ContributionID != contributionID {- continue- }- connection, credential, err := s.resolveTaskRemoteMCPEntry(ctx, manifest.WorkspaceID, entry, true)- if err != nil {- return "", "", newPluginError(PluginErrorConflict, "Remote MCP credential is revoked or unavailable", err)- }- return connection.CredentialHeader, credential, nil- }- return "", "", newPluginError(PluginErrorNotFound, "Remote MCP task contribution not found", nil)-}--func (s *PluginService) resolveTaskRemoteMCPEntry(ctx context.Context, workspaceID pgtype.UUID, entry pluginruntime.CompiledEntry, resolveCredential bool) (pluginruntime.RemoteMCPConnection, string, error) {- installationID, err := parsePluginRuntimeUUID(entry.InstallationID, "installation")- if err != nil {- return pluginruntime.RemoteMCPConnection{}, "", err- }- contributionID, err := parsePluginRuntimeUUID(entry.ContributionID, "contribution")- if err != nil {- return pluginruntime.RemoteMCPConnection{}, "", err- }- if entry.ConfigID == "" || entry.ConfigRevision <= 0 || entry.Endpoint == "" || entry.Transport != "streamable-http" || len(entry.ApprovedTools) == 0 {- return pluginruntime.RemoteMCPConnection{}, "", errors.New("pinned configuration is incomplete")- }- if _, err := remotemcp.ValidatePublicHTTPSEndpoint(ctx, entry.Endpoint, entry.EndpointAllowedHosts, nil); err != nil {- return pluginruntime.RemoteMCPConnection{}, "", err- }- digest, err := remotemcp.ToolSetDigest(entry.ApprovedTools)- if err != nil || digest != entry.ToolSchemaDigest {- return pluginruntime.RemoteMCPConnection{}, "", errors.New("pinned tool schema digest is invalid")- }- credentialHeader := ""- credential := ""- if entry.AuthType != "none" {- secretID, err := parsePluginRuntimeUUID(entry.SecretRef, "credential")- if err != nil || s.RemoteMCPSecrets == nil {- return pluginruntime.RemoteMCPConnection{}, "", errors.New("credential is unavailable")- }- credentialHeader = entry.AuthHeader- if entry.AuthType == "oauth" {- credentialHeader = "Authorization"- if resolveCredential {- accessToken, err := s.remoteMCPOAuthAccessToken(ctx, workspaceID, installationID, contributionID, secretID)- if err != nil {- return pluginruntime.RemoteMCPConnection{}, "", errors.New("OAuth connection is expired or unavailable")- }- credential = "Bearer " + accessToken- } else if _, err := s.Queries.GetActivePluginRemoteMCPSecret(ctx, db.GetActivePluginRemoteMCPSecretParams{- ID: secretID, WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,- }); err != nil {- return pluginruntime.RemoteMCPConnection{}, "", errors.New("credential is revoked or outside task scope")- }- } else {- secret, err := s.Queries.GetActivePluginRemoteMCPSecret(ctx, db.GetActivePluginRemoteMCPSecretParams{- ID: secretID, WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,- })- if err != nil {- return pluginruntime.RemoteMCPConnection{}, "", errors.New("credential is revoked or outside task scope")- }- if resolveCredential {- opened, err := s.RemoteMCPSecrets.Open(secret.Ciphertext)- if err != nil {- return pluginruntime.RemoteMCPConnection{}, "", errors.New("credential cannot be decrypted")- }- credential = string(opened)- }- }- if resolveCredential && entry.AuthType == "bearer" {- credentialHeader = "Authorization"- credential = "Bearer " + credential- }- }- return pluginruntime.RemoteMCPConnection{- InstallationID: entry.InstallationID, ContributionID: entry.ContributionID,- ContributionKey: entry.ContributionKey, ConfigID: entry.ConfigID, ConfigRevision: entry.ConfigRevision,- Endpoint: entry.Endpoint, PublicConfig: append(json.RawMessage(nil), entry.PublicConfig...),- Transport: entry.Transport, ProtocolVersions: append([]string(nil), entry.ProtocolVersions...),- EndpointAllowedHosts: append([]string(nil), entry.EndpointAllowedHosts...),- CredentialHeader: credentialHeader,- ApprovedTools: append([]pluginruntime.RemoteMCPTool(nil), entry.ApprovedTools...),- ToolSchemaDigest: entry.ToolSchemaDigest, FailurePolicy: entry.FailurePolicy,- }, credential, nil-}--func parsePluginRuntimeUUID(value, field string) (pgtype.UUID, error) {- var id pgtype.UUID- if err := id.Scan(value); err != nil || !id.Valid {- return pgtype.UUID{}, fmt.Errorf("invalid %s id", field)- }- return id, nil-}--func (s *PluginService) loadRemoteMCPDeclaration(ctx context.Context, q *db.Queries, workspaceID, installationID pgtype.UUID, contributionKey string) (db.GetInstallationRemoteMCPContributionRow, plugincontract.RemoteMCPContribution, error) {- row, err := q.GetInstallationRemoteMCPContribution(ctx, db.GetInstallationRemoteMCPContributionParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionKey: contributionKey,- })- if errors.Is(err, pgx.ErrNoRows) {- return row, plugincontract.RemoteMCPContribution{}, newPluginError(PluginErrorNotFound, "Remote MCP contribution not found", nil)- }- if err != nil {- return row, plugincontract.RemoteMCPContribution{}, err- }- var manifest plugincontract.Manifest- if err := json.Unmarshal(row.Manifest, &manifest); err != nil {- return row, plugincontract.RemoteMCPContribution{}, err- }- for _, declaration := range manifest.Contributes.RemoteMCP {- if declaration.Key == contributionKey {- return row, declaration, nil- }- }- return row, plugincontract.RemoteMCPContribution{}, newPluginError(PluginErrorNotFound, "Remote MCP contribution not found", nil)-}--func (s *PluginService) remoteMCPHeaders(ctx context.Context, workspaceID, installationID, contributionID pgtype.UUID, authType, authHeader, plaintext string, secretRef pgtype.UUID) (http.Header, error) {- headers := make(http.Header)- if authType == "none" {- return headers, nil- }- if authType == "oauth" {- if !secretRef.Valid {- return nil, newPluginError(PluginErrorConflict, "Remote MCP OAuth connection is unavailable", nil)- }- accessToken, err := s.remoteMCPOAuthAccessToken(ctx, workspaceID, installationID, contributionID, secretRef)- if err != nil {- return nil, newPluginError(PluginErrorConflict, "Remote MCP OAuth connection is unavailable", err)- }- headers.Set("Authorization", "Bearer "+accessToken)- return headers, nil- }- if plaintext == "" {- if s.RemoteMCPSecrets == nil || !secretRef.Valid {- return nil, newPluginError(PluginErrorConflict, "Remote MCP credential is unavailable", nil)- }- secret, err := s.Queries.GetActivePluginRemoteMCPSecret(ctx, db.GetActivePluginRemoteMCPSecretParams{- ID: secretRef, WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,- })- if err != nil {- return nil, newPluginError(PluginErrorConflict, "Remote MCP credential is unavailable", err)- }- opened, err := s.RemoteMCPSecrets.Open(secret.Ciphertext)- if err != nil {- return nil, newPluginError(PluginErrorConflict, "Remote MCP credential is unavailable", err)- }- plaintext = string(opened)- }- if authType == "bearer" {- headers.Set("Authorization", "Bearer "+plaintext)- } else {- headers.Set(authHeader, plaintext)- }- return headers, nil-}--func (s *PluginService) bumpPluginConfigurationGeneration(ctx context.Context, q *db.Queries, workspaceID, installationID, actorID pgtype.UUID) (db.PluginInstallation, error) {- installation, err := q.GetPluginInstallation(ctx, installationID)- if err != nil || installation.WorkspaceID != workspaceID {- return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)- }- return q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{- Enabled: installation.Enabled, UpdatedBy: actorID, WorkspaceID: workspaceID,- DesiredReleaseID: installation.DesiredReleaseID, ID: installationID,- })-}--func validateRemoteMCPPublicConfig(raw, rawSchema json.RawMessage) ([]byte, error) {- if len(raw) == 0 {- raw = json.RawMessage(`{}`)- }- var config map[string]any- if err := json.Unmarshal(raw, &config); err != nil {- return nil, err- }- if err := rejectRemoteMCPSecretKeys(config, ""); err != nil {- return nil, err- }- if len(rawSchema) > 0 {- var schema map[string]any- if err := json.Unmarshal(rawSchema, &schema); err != nil {- return nil, err- }- if err := validateRemoteMCPConfigValue(config, schema, "configuration"); err != nil {- return nil, err- }- }- return json.Marshal(config)-}--func rejectRemoteMCPSecretKeys(value any, path string) error {- switch typed := value.(type) {- case map[string]any:- for key, child := range typed {- childPath := key- if path != "" {- childPath = path + "." + key- }- normalized := strings.ToLower(strings.ReplaceAll(key, "-", "_"))- if strings.Contains(normalized, "secret") || strings.Contains(normalized, "token") || strings.Contains(normalized, "password") || strings.Contains(normalized, "authorization") || strings.Contains(normalized, "api_key") {- return fmt.Errorf("public configuration key %q may contain a secret", childPath)- }- if err := rejectRemoteMCPSecretKeys(child, childPath); err != nil {- return err- }- }- case []any:- for index, child := range typed {- if err := rejectRemoteMCPSecretKeys(child, fmt.Sprintf("%s[%d]", path, index)); err != nil {- return err- }- }- }- return nil-}--// validateRemoteMCPConfigValue intentionally implements the safe structural-// subset accepted by the V1 manifest contract. Publishers can constrain object-// properties, required fields, arrays, primitive types, and enums; unsupported-// JSON Schema keywords remain annotations and never broaden this validation.-func validateRemoteMCPConfigValue(value any, schema map[string]any, path string) error {- if choices, ok := schema["enum"].([]any); ok {- matched := false- for _, choice := range choices {- left, _ := json.Marshal(value)- right, _ := json.Marshal(choice)- if string(left) == string(right) {- matched = true- break- }- }- if !matched {- return fmt.Errorf("%s is outside the configured enum", path)- }- }- typeName, _ := schema["type"].(string)- switch typeName {- case "", "object":- object, ok := value.(map[string]any)- if !ok {- return fmt.Errorf("%s must be an object", path)- }- properties, _ := schema["properties"].(map[string]any)- required, _ := schema["required"].([]any)- for _, rawName := range required {- name, _ := rawName.(string)- if _, exists := object[name]; name != "" && !exists {- return fmt.Errorf("%s.%s is required", path, name)- }- }- additional, hasAdditional := schema["additionalProperties"].(bool)- for name, child := range object {- rawChildSchema, exists := properties[name]- if !exists {- if hasAdditional && !additional {- return fmt.Errorf("%s.%s is not allowed", path, name)- }- continue- }- childSchema, ok := rawChildSchema.(map[string]any)- if !ok {- return fmt.Errorf("%s.%s has an invalid schema", path, name)- }- if err := validateRemoteMCPConfigValue(child, childSchema, path+"."+name); err != nil {- return err- }- }- case "array":- items, ok := value.([]any)- if !ok {- return fmt.Errorf("%s must be an array", path)- }- itemSchema, _ := schema["items"].(map[string]any)- for index, item := range items {- if itemSchema != nil {- if err := validateRemoteMCPConfigValue(item, itemSchema, fmt.Sprintf("%s[%d]", path, index)); err != nil {- return err- }- }- }- case "string":- if _, ok := value.(string); !ok {- return fmt.Errorf("%s must be a string", path)- }- case "boolean":- if _, ok := value.(bool); !ok {- return fmt.Errorf("%s must be a boolean", path)- }- case "number":- if _, ok := value.(float64); !ok {- return fmt.Errorf("%s must be a number", path)- }- case "integer":- number, ok := value.(float64)- if !ok || number != float64(int64(number)) {- return fmt.Errorf("%s must be an integer", path)- }- case "null":- if value != nil {- return fmt.Errorf("%s must be null", path)- }- default:- return fmt.Errorf("%s uses unsupported schema type %q", path, typeName)- }- return nil-}--func applyDeclaredRisk(tools []pluginruntime.RemoteMCPTool, declaration plugincontract.RemoteMCPContribution) {- risks := make(map[string]string, len(declaration.ToolIntent))- for _, intent := range declaration.ToolIntent {- risks[intent.Name] = intent.Risk- }- for index := range tools {- risk := risks[tools[index].Name]- if risk == "" {- risk = risks[plugincontract.RemoteMCPAnyToolIntent]- }- tools[index].Risk = risk- }-}--func selectApprovedRemoteMCPTools(discovered []pluginruntime.RemoteMCPTool, declaration plugincontract.RemoteMCPContribution, names []string) ([]pluginruntime.RemoteMCPTool, error) {- if len(names) == 0 {- return nil, errors.New("at least one tool must be approved")- }- intended := make(map[string]bool, len(declaration.ToolIntent))- for _, tool := range declaration.ToolIntent {- intended[tool.Name] = true- }- allowDiscovered := intended[plugincontract.RemoteMCPAnyToolIntent]- available := make(map[string]pluginruntime.RemoteMCPTool, len(discovered))- for _, tool := range discovered {- available[tool.Name] = tool- }- approved := make([]pluginruntime.RemoteMCPTool, 0, len(names))- seen := map[string]bool{}- for _, name := range names {- if seen[name] || (!allowDiscovered && !intended[name]) {- return nil, fmt.Errorf("tool %q is duplicate or outside declared intent", name)- }- tool, ok := available[name]- if !ok {- return nil, fmt.Errorf("tool %q was not discovered", name)- }- seen[name] = true- approved = append(approved, tool)- }- return approved, nil-}--func secretHint(secret string) string {- if len(secret) <= 4 {- return "••••"- }- return "••••" + secret[len(secret)-4:]-}diff --git a/server/internal/service/plugin_remote_mcp_oauth.go b/server/internal/service/plugin_remote_mcp_oauth.godeleted file mode 100644index 49739f44ef..0000000000--- a/server/internal/service/plugin_remote_mcp_oauth.go+++ /dev/null@@ -1,447 +0,0 @@-package service--import (- "bytes"- "context"- "crypto/rand"- "crypto/sha256"- "encoding/base64"- "encoding/json"- "errors"- "fmt"- "strings"- "time"-- "github.com/jackc/pgx/v5"- "github.com/jackc/pgx/v5/pgtype"- db "github.com/multica-ai/multica/server/pkg/db/generated"- "github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/remotemcp"-)--const remoteMCPOAuthStateTTL = 10 * time.Minute-const remoteMCPOAuthRefreshTimeout = 10 * time.Second--type RemoteMCPOAuthStartInput struct {- Endpoint string- PublicConfig json.RawMessage- FailurePolicy string- Scope string- ClientID string- ClientSecret string- TokenEndpointAuthMethod string- AuthorizationEndpoint string- TokenEndpoint string- RedirectURI string- ReturnTo string-}--type RemoteMCPOAuthStartResult struct {- AuthorizationURL string-}--type RemoteMCPOAuthCallbackResult struct {- ReturnTo string-}--type remoteMCPOAuthStateSecret struct {- Verifier string `json:"verifier"`- ClientSecret string `json:"client_secret,omitempty"`- TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`-}--// remoteMCPOAuthTokenSecret is the encrypted connection record. Keeping the-// refresh metadata beside the token means neither the Plugin artifact nor the-// execution manifest ever receives reusable OAuth material.-type remoteMCPOAuthTokenSecret struct {- AccessToken string `json:"access_token"`- RefreshToken string `json:"refresh_token,omitempty"`- ExpiresAt time.Time `json:"expires_at,omitempty"`- Scope string `json:"scope,omitempty"`- Resource string `json:"resource"`- TokenEndpoint string `json:"token_endpoint"`- ClientID string `json:"client_id"`- ClientSecret string `json:"client_secret,omitempty"`- TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`-}--func (s *PluginService) BeginRemoteMCPOAuth(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, contributionKey string, input RemoteMCPOAuthStartInput) (RemoteMCPOAuthStartResult, error) {- if s.RemoteMCPSecrets == nil {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorIncompatible, "Remote MCP credential encryption is not configured", nil)- }- if strings.TrimSpace(input.RedirectURI) == "" {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorIncompatible, "Remote MCP OAuth callback URL is not configured", nil)- }- contribution, declaration, err := s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, contributionKey)- if err != nil {- return RemoteMCPOAuthStartResult{}, err- }- input.Endpoint = strings.TrimSpace(input.Endpoint)- if input.Endpoint == "" {- input.Endpoint = declaration.EndpointPolicy.DefaultEndpoint- }- if _, err := remotemcp.ValidatePublicHTTPSEndpoint(ctx, input.Endpoint, declaration.EndpointPolicy.AllowedHosts, nil); err != nil {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "Remote MCP endpoint is not allowed", err)- }- publicConfig, err := validateRemoteMCPPublicConfig(input.PublicConfig, declaration.ConfigurationSchema)- if err != nil {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "Remote MCP public configuration is invalid", err)- }- input.FailurePolicy = strings.TrimSpace(input.FailurePolicy)- if input.FailurePolicy == "" {- input.FailurePolicy = "required"- }- if input.FailurePolicy != "required" && input.FailurePolicy != "optional" {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "failure_policy must be required or optional", nil)- }-- metadata, err := remotemcp.DiscoverOAuth(ctx, input.Endpoint, declaration.EndpointPolicy.AllowedHosts)- if err != nil {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "Remote MCP OAuth discovery failed", err)- }- if strings.TrimSpace(input.AuthorizationEndpoint) != "" || strings.TrimSpace(input.TokenEndpoint) != "" {- if input.AuthorizationEndpoint == "" || input.TokenEndpoint == "" {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "both OAuth endpoints are required", nil)- }- // Advanced overrides still pass through the remotemcp package's public- // HTTPS checks when the authorization URL is built and the token is- // exchanged. Discovery remains mandatory so a random MCP endpoint cannot- // turn Multica into an arbitrary OAuth client.- metadata.AuthorizationEndpoint = strings.TrimSpace(input.AuthorizationEndpoint)- metadata.TokenEndpoint = strings.TrimSpace(input.TokenEndpoint)- }- if err := remotemcp.ValidateOAuthMetadata(ctx, metadata); err != nil {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "Remote MCP OAuth endpoints are invalid", err)- }-- registration := remotemcp.OAuthClientRegistration{- ClientID: strings.TrimSpace(input.ClientID), ClientSecret: input.ClientSecret,- TokenEndpointAuthMethod: strings.TrimSpace(input.TokenEndpointAuthMethod),- }- if registration.ClientID == "" {- registration, err = remotemcp.RegisterOAuthClient(ctx, metadata, input.RedirectURI)- if err != nil {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "Remote MCP OAuth client registration failed", err)- }- }- if registration.TokenEndpointAuthMethod == "" {- if registration.ClientSecret == "" {- registration.TokenEndpointAuthMethod = "none"- } else {- registration.TokenEndpointAuthMethod = "client_secret_basic"- }- }- if registration.TokenEndpointAuthMethod != "none" && registration.TokenEndpointAuthMethod != "client_secret_basic" && registration.TokenEndpointAuthMethod != "client_secret_post" {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "unsupported OAuth token endpoint authentication method", nil)- }-- state, err := secureRemoteMCPRandom()- if err != nil {- return RemoteMCPOAuthStartResult{}, err- }- verifier, err := secureRemoteMCPRandom()- if err != nil {- return RemoteMCPOAuthStartResult{}, err- }- scope := strings.TrimSpace(input.Scope)- if scope == "" {- scope = strings.Join(metadata.Scopes, " ")- }- stateSecret, _ := json.Marshal(remoteMCPOAuthStateSecret{- Verifier: verifier, ClientSecret: registration.ClientSecret,- TokenEndpointAuthMethod: registration.TokenEndpointAuthMethod,- })- sealed, err := s.RemoteMCPSecrets.Seal(stateSecret)- if err != nil {- return RemoteMCPOAuthStartResult{}, fmt.Errorf("encrypt Remote MCP OAuth state: %w", err)- }- stateHash := sha256.Sum256([]byte(state))- returnTo := sanitizeRemoteMCPReturnTo(input.ReturnTo)- _, _ = s.Queries.DeleteExpiredPluginRemoteMCPOAuthStates(ctx)- if _, err := s.Queries.CreatePluginRemoteMCPOAuthState(ctx, db.CreatePluginRemoteMCPOAuthStateParams{- StateHash: stateHash[:], WorkspaceID: workspaceID, InstallationID: installationID,- ContributionID: contribution.ID, ActorID: actorID, Endpoint: metadata.ResourceEndpoint,- PublicConfig: publicConfig, FailurePolicy: input.FailurePolicy,- AuthorizationEndpoint: metadata.AuthorizationEndpoint, TokenEndpoint: metadata.TokenEndpoint,- ClientID: registration.ClientID, Scope: scope, RedirectUri: input.RedirectURI,- ReturnTo: returnTo, SecretCiphertext: sealed,- ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(remoteMCPOAuthStateTTL), Valid: true},- }); err != nil {- return RemoteMCPOAuthStartResult{}, err- }- authorizationURL, err := remotemcp.BuildAuthorizationURL(metadata, registration, input.RedirectURI, state, verifier, scope)- if err != nil {- return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "build Remote MCP authorization URL", err)- }- return RemoteMCPOAuthStartResult{AuthorizationURL: authorizationURL}, nil-}--func (s *PluginService) CompleteRemoteMCPOAuth(ctx context.Context, state, code string) (RemoteMCPOAuthCallbackResult, error) {- if s.RemoteMCPSecrets == nil {- return RemoteMCPOAuthCallbackResult{}, newPluginError(PluginErrorIncompatible, "Remote MCP credential encryption is not configured", nil)- }- if state == "" {- return RemoteMCPOAuthCallbackResult{}, newPluginError(PluginErrorInvalid, "OAuth callback is missing state", nil)- }- stateHash := sha256.Sum256([]byte(state))- claimed, err := s.Queries.ClaimPluginRemoteMCPOAuthState(ctx, stateHash[:])- if errors.Is(err, pgx.ErrNoRows) {- return RemoteMCPOAuthCallbackResult{}, newPluginError(PluginErrorInvalid, "OAuth state is invalid, expired, or already used", nil)- }- if err != nil {- return RemoteMCPOAuthCallbackResult{}, err- }- if code == "" {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "OAuth callback did not include an authorization code", nil)- }- opened, err := s.RemoteMCPSecrets.Open(claimed.SecretCiphertext)- if err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "OAuth state cannot be decrypted", err)- }- var stateSecret remoteMCPOAuthStateSecret- if err := json.Unmarshal(opened, &stateSecret); err != nil || stateSecret.Verifier == "" {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "OAuth state is invalid", err)- }- registration := remotemcp.OAuthClientRegistration{- ClientID: claimed.ClientID, ClientSecret: stateSecret.ClientSecret,- TokenEndpointAuthMethod: stateSecret.TokenEndpointAuthMethod,- }- token, err := remotemcp.ExchangeOAuthCode(ctx, claimed.TokenEndpoint, claimed.Endpoint, code, claimed.RedirectUri, stateSecret.Verifier, registration)- if err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "Remote MCP OAuth token exchange failed", err)- }- if token.RefreshToken == "" {- // A non-expiring access token is usable without a refresh token. A- // short-lived token without one would leave a connection that appears- // healthy but predictably dies, so fail it at connect time.- if token.ExpiresIn > 0 {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "OAuth server returned an expiring token without refresh capability", nil)- }- }- headers := make(map[string][]string)- headers["Authorization"] = []string{"Bearer " + token.AccessToken}- contribution, declaration, err := s.loadRemoteMCPDeclarationByID(ctx, claimed.WorkspaceID, claimed.InstallationID, claimed.ContributionID)- if err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err- }- discovered, discoveredDigest, err := remotemcp.Discover(ctx, claimed.Endpoint, declaration.EndpointPolicy.AllowedHosts, declaration.ProtocolVersions, headers)- if err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "Remote MCP connection test failed after OAuth", err)- }- applyDeclaredRisk(discovered, declaration)- discoveredJSON, _ := json.Marshal(discovered)-- tokenSecret := remoteMCPOAuthTokenSecret{- AccessToken: token.AccessToken, RefreshToken: token.RefreshToken,- ExpiresAt: remotemcp.OAuthExpiry(time.Now(), token.ExpiresIn), Scope: token.Scope,- Resource: claimed.Endpoint, TokenEndpoint: claimed.TokenEndpoint,- ClientID: claimed.ClientID, ClientSecret: stateSecret.ClientSecret,- TokenEndpointAuthMethod: stateSecret.TokenEndpointAuthMethod,- }- tokenJSON, _ := json.Marshal(tokenSecret)- sealed, err := s.RemoteMCPSecrets.Seal(tokenJSON)- if err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, fmt.Errorf("encrypt Remote MCP OAuth token: %w", err)- }-- tx, err := s.TxStarter.Begin(ctx)- if err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err- }- defer tx.Rollback(ctx) //nolint:errcheck- q := s.Queries.WithTx(tx)- if _, err := q.LockPluginRemoteMCPInstallation(ctx, db.LockPluginRemoteMCPInstallationParams{- WorkspaceID: claimed.WorkspaceID, InstallationID: claimed.InstallationID, ContributionID: contribution.ID,- }); err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err- }- if _, err := q.RevokePluginRemoteMCPSecrets(ctx, db.RevokePluginRemoteMCPSecretsParams{- WorkspaceID: claimed.WorkspaceID, InstallationID: claimed.InstallationID, ContributionID: contribution.ID,- }); err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err- }- secret, err := q.CreatePluginRemoteMCPSecret(ctx, db.CreatePluginRemoteMCPSecretParams{- WorkspaceID: claimed.WorkspaceID, InstallationID: claimed.InstallationID, ContributionID: contribution.ID,- Ciphertext: sealed, Hint: "OAuth", CreatedBy: claimed.ActorID,- })- if err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err- }- if _, err := q.CreatePluginInstallationConfig(ctx, db.CreatePluginInstallationConfigParams{- WorkspaceID: claimed.WorkspaceID, InstallationID: claimed.InstallationID, ContributionID: contribution.ID,- Endpoint: claimed.Endpoint, PublicConfig: claimed.PublicConfig, AuthType: "oauth", AuthHeader: "Authorization",- SecretRef: secret.ID, DiscoveredTools: discoveredJSON,- DiscoveredSchemaDigest: pgtype.Text{String: discoveredDigest, Valid: true},- ApprovedTools: []byte(`[]`), FailurePolicy: claimed.FailurePolicy, CreatedBy: claimed.ActorID,- }); err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err- }- if _, err := s.bumpPluginConfigurationGeneration(ctx, q, claimed.WorkspaceID, claimed.InstallationID, claimed.ActorID); err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err- }- if _, err := s.reconcileWorkspaceTx(ctx, q, claimed.WorkspaceID); err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err- }- if err := tx.Commit(ctx); err != nil {- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err- }- return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, nil-}--func (s *PluginService) loadRemoteMCPDeclarationByID(ctx context.Context, workspaceID, installationID, contributionID pgtype.UUID) (db.GetInstallationRemoteMCPContributionRow, plugincontract.RemoteMCPContribution, error) {- row, err := s.Queries.GetInstallationRemoteMCPContributionByID(ctx, db.GetInstallationRemoteMCPContributionByIDParams{- WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,- })- if err != nil {- return db.GetInstallationRemoteMCPContributionRow{}, plugincontract.RemoteMCPContribution{}, err- }- var manifest plugincontract.Manifest- if err := json.Unmarshal(row.Manifest, &manifest); err != nil {- return db.GetInstallationRemoteMCPContributionRow{}, plugincontract.RemoteMCPContribution{}, err- }- for _, declaration := range manifest.Contributes.RemoteMCP {- if declaration.Key == row.ContributionKey {- // sqlc generates structurally identical row types for the key and id- // queries, but Go treats them as distinct. Resolve once by key to keep- // callers on the established service type.- return s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, row.ContributionKey)- }- }- return db.GetInstallationRemoteMCPContributionRow{}, plugincontract.RemoteMCPContribution{}, newPluginError(PluginErrorNotFound, "Remote MCP contribution not found", nil)-}--func secureRemoteMCPRandom() (string, error) {- value := make([]byte, 32)- if _, err := rand.Read(value); err != nil {- return "", err- }- return base64.RawURLEncoding.EncodeToString(value), nil-}--func sanitizeRemoteMCPReturnTo(value string) string {- value = strings.TrimSpace(value)- if !strings.HasPrefix(value, "/") || strings.HasPrefix(value, "//") || strings.ContainsAny(value, "\r\n") {- return "/"- }- return value-}--func (s *PluginService) remoteMCPOAuthAccessToken(ctx context.Context, workspaceID, installationID, contributionID, secretID pgtype.UUID) (string, error) {- if s.RemoteMCPSecrets == nil {- return "", errors.New("credential encryption is not configured")- }- _, token, err := s.loadRemoteMCPOAuthToken(ctx, s.Queries, workspaceID, installationID, contributionID, secretID)- if err != nil {- return "", err- }- if token.ExpiresAt.IsZero() || token.ExpiresAt.After(time.Now().Add(time.Minute)) {- return token.AccessToken, nil- }-- key := base64.RawURLEncoding.EncodeToString(secretID.Bytes[:])- value, err, _ := s.remoteMCPOAuthRefresh.Do(key, func() (any, error) {- secret, current, err := s.loadRemoteMCPOAuthToken(ctx, s.Queries, workspaceID, installationID, contributionID, secretID)- if err != nil {- return "", err- }- if current.ExpiresAt.IsZero() || current.ExpiresAt.After(time.Now().Add(time.Minute)) {- return current.AccessToken, nil- }- if current.RefreshToken == "" {- return "", errors.New("OAuth access token expired without a refresh token")- }-- refreshCtx, cancel := context.WithTimeout(ctx, remoteMCPOAuthRefreshTimeout)- defer cancel()- refreshed, err := remotemcp.RefreshOAuthToken(refreshCtx, current.TokenEndpoint, current.Resource, current.RefreshToken, remotemcp.OAuthClientRegistration{- ClientID: current.ClientID, ClientSecret: current.ClientSecret, TokenEndpointAuthMethod: current.TokenEndpointAuthMethod,- })- if err != nil {- return "", err- }- current.AccessToken = refreshed.AccessToken- if refreshed.RefreshToken != "" {- current.RefreshToken = refreshed.RefreshToken- }- if refreshed.Scope != "" {- current.Scope = refreshed.Scope- }- current.ExpiresAt = remotemcp.OAuthExpiry(time.Now(), refreshed.ExpiresIn)-- // The network call intentionally happens before the write lock. Once the- // provider responds, lock briefly to re-check revocation/rotation and- // publish the refreshed token atomically.- tx, err := s.TxStarter.Begin(ctx)- if err != nil {- return "", err- }- defer tx.Rollback(ctx) //nolint:errcheck- q := s.Queries.WithTx(tx)- locked, err := q.GetActivePluginRemoteMCPSecretForUpdate(ctx, db.GetActivePluginRemoteMCPSecretForUpdateParams{- ID: secretID, WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,- })- if err != nil {- return "", err- }- lockedToken, err := s.decodeRemoteMCPOAuthToken(locked.Ciphertext)- if err != nil {- return "", err- }- if lockedToken.ExpiresAt.IsZero() || lockedToken.ExpiresAt.After(time.Now().Add(time.Minute)) {- if err := tx.Commit(ctx); err != nil {- return "", err- }- return lockedToken.AccessToken, nil- }- if !bytes.Equal(locked.Ciphertext, secret.Ciphertext) {- return "", errors.New("OAuth token changed while it was being refreshed")- }-- encoded, _ := json.Marshal(current)- sealed, err := s.RemoteMCPSecrets.Seal(encoded)- if err != nil {- return "", err- }- if _, err := q.UpdateActivePluginRemoteMCPSecret(ctx, db.UpdateActivePluginRemoteMCPSecretParams{- Ciphertext: sealed, Hint: "OAuth", ID: secretID, WorkspaceID: workspaceID,- InstallationID: installationID, ContributionID: contributionID,- }); err != nil {- return "", err- }- if err := tx.Commit(ctx); err != nil {- return "", err- }- return current.AccessToken, nil- })- if err != nil {- return "", err- }- accessToken, ok := value.(string)- if !ok || accessToken == "" {- return "", errors.New("OAuth token refresh returned no access token")- }- return accessToken, nil-}--func (s *PluginService) loadRemoteMCPOAuthToken(ctx context.Context, q *db.Queries, workspaceID, installationID, contributionID, secretID pgtype.UUID) (db.PluginRemoteMcpSecret, remoteMCPOAuthTokenSecret, error) {- secret, err := q.GetActivePluginRemoteMCPSecret(ctx, db.GetActivePluginRemoteMCPSecretParams{- ID: secretID, WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,- })- if err != nil {- return db.PluginRemoteMcpSecret{}, remoteMCPOAuthTokenSecret{}, err- }- token, err := s.decodeRemoteMCPOAuthToken(secret.Ciphertext)- return secret, token, err-}--func (s *PluginService) decodeRemoteMCPOAuthToken(ciphertext []byte) (remoteMCPOAuthTokenSecret, error) {- opened, err := s.RemoteMCPSecrets.Open(ciphertext)- if err != nil {- return remoteMCPOAuthTokenSecret{}, err- }- var token remoteMCPOAuthTokenSecret- if err := json.Unmarshal(opened, &token); err != nil || token.AccessToken == "" {- return remoteMCPOAuthTokenSecret{}, errors.New("OAuth token is invalid")- }- return token, nil-}diff --git a/server/internal/service/plugin_remote_mcp_test.go b/server/internal/service/plugin_remote_mcp_test.godeleted file mode 100644index ba341b2a2e..0000000000--- a/server/internal/service/plugin_remote_mcp_test.go+++ /dev/null@@ -1,95 +0,0 @@-package service--import (- "encoding/json"- "strings"- "testing"-- "github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/pluginruntime"-)--func TestValidateRemoteMCPPublicConfigRejectsNestedSecretsAndSchemaViolations(t *testing.T) {- schema := json.RawMessage(`{- "type":"object",- "required":["region"],- "properties":{"region":{"type":"string","enum":["us","eu"]}},- "additionalProperties":false- }`)- canonical, err := validateRemoteMCPPublicConfig(json.RawMessage(`{"region":"eu"}`), schema)- if err != nil || string(canonical) != `{"region":"eu"}` {- t.Fatalf("valid config = %s, %v", canonical, err)- }- for _, raw := range []string{- `{"region":"ap"}`,- `{"region":"eu","extra":true}`,- `{"region":"eu","nested":{"access_token":"secret"}}`,- `{"region":"eu","items":[{"password":"secret"}]}`,- } {- if _, err := validateRemoteMCPPublicConfig(json.RawMessage(raw), schema); err == nil {- t.Fatalf("config %s was accepted", raw)- }- }-}--func TestSelectApprovedRemoteMCPToolsFailsClosed(t *testing.T) {- declaration := plugincontract.RemoteMCPContribution{ToolIntent: []plugincontract.RemoteMCPToolIntent{- {Name: "read", Risk: "read"}, {Name: "write", Risk: "write"},- }}- discovered := []pluginruntime.RemoteMCPTool{{Name: "read"}, {Name: "undeclared"}}- approved, err := selectApprovedRemoteMCPTools(discovered, declaration, []string{"read"})- if err != nil || len(approved) != 1 || approved[0].Name != "read" {- t.Fatalf("approved = %#v, %v", approved, err)- }- for _, names := range [][]string{nil, {"undeclared"}, {"write"}, {"read", "read"}} {- if _, err := selectApprovedRemoteMCPTools(discovered, declaration, names); err == nil {- t.Fatalf("approval %v was accepted", names)- }- }-}--func TestSelectApprovedRemoteMCPToolsAllowsExplicitlyReviewedWildcard(t *testing.T) {- declaration := plugincontract.RemoteMCPContribution{ToolIntent: []plugincontract.RemoteMCPToolIntent{- {Name: plugincontract.RemoteMCPAnyToolIntent, Risk: "write"},- }}- discovered := []pluginruntime.RemoteMCPTool{{Name: "search-screens"}, {Name: "get-flow"}}- applyDeclaredRisk(discovered, declaration)- approved, err := selectApprovedRemoteMCPTools(discovered, declaration, []string{"search-screens"})- if err != nil || len(approved) != 1 || approved[0].Name != "search-screens" || approved[0].Risk != "write" {- t.Fatalf("approved = %#v, %v", approved, err)- }- if _, err := selectApprovedRemoteMCPTools(discovered, declaration, []string{"not-discovered"}); err == nil {- t.Fatal("undiscovered wildcard tool was approved")- }-}--func TestSecretHintDoesNotExposeShortCredential(t *testing.T) {- if got := secretHint("abc"); got != "••••" || strings.Contains(got, "abc") {- t.Fatalf("secretHint = %q", got)- }- if got := secretHint("credential"); got != "••••tial" {- t.Fatalf("secretHint = %q", got)- }-}--func TestRemoteMCPAuthHeaderRejectsProtocolAndHopByHopHeaders(t *testing.T) {- if !validRemoteMCPAuthHeader("X-Example-Key") {- t.Fatal("safe custom header was rejected")- }- for _, header := range []string{"Host", "Connection", "Content-Length", "Mcp-Session-Id", "Proxy-Authorization", "bad header"} {- if validRemoteMCPAuthHeader(header) {- t.Fatalf("unsafe header %q was accepted", header)- }- }-}--func TestSanitizeRemoteMCPReturnTo(t *testing.T) {- if got := sanitizeRemoteMCPReturnTo("/workspace/settings?tab=plugins"); got != "/workspace/settings?tab=plugins" {- t.Fatalf("safe return path changed to %q", got)- }- for _, unsafe := range []string{"https://evil.example", "//evil.example/path", "/ok\r\nLocation: https://evil.example"} {- if got := sanitizeRemoteMCPReturnTo(unsafe); got != "/" {- t.Errorf("unsafe return path %q became %q", unsafe, got)- }- }-}diff --git a/server/internal/service/plugin_skill.go b/server/internal/service/plugin_skill.godeleted file mode 100644index f33a88f806..0000000000--- a/server/internal/service/plugin_skill.go+++ /dev/null@@ -1,142 +0,0 @@-package service--import (- "fmt"- "path"- "sort"- "strings"-- "github.com/jackc/pgx/v5/pgtype"- "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"- "github.com/multica-ai/multica/server/pkg/pluginruntime"- "github.com/multica-ai/multica/server/pkg/skillbundle"-)--// compilePluginSkillFiles turns every artifact file owned by a Skill root into-// an immutable execution-manifest pin. The manifest still declares only the-// canonical SKILL.md entry; companion files are discovered by convention so a-// community Skill directory can be packaged without translating its layout.-func compilePluginSkillFiles(releaseID pgtype.UUID, contributionKey, entryPath string, files []db.PluginArtifactFile) ([]pluginruntime.SkillFile, []skillbundle.File, error) {- root, err := pluginSkillRoot(contributionKey, entryPath)- if err != nil {- return nil, nil, err- }- foundEntry := false- seen := make(map[string]struct{})- pins := make([]pluginruntime.SkillFile, 0)- bundleFiles := make([]skillbundle.File, 0)- for _, file := range files {- if file.ReleaseID != releaseID {- return nil, nil, fmt.Errorf("plugin Skill artifact file belongs to another release")- }- if file.Path == entryPath {- foundEntry = true- continue- }- if !strings.HasPrefix(file.Path, root) {- continue- }- relative := strings.TrimPrefix(file.Path, root)- if err := validatePluginSkillRelativePath(relative); err != nil {- return nil, nil, err- }- if _, exists := seen[relative]; exists {- return nil, nil, fmt.Errorf("plugin Skill contains duplicate companion path %q", relative)- }- seen[relative] = struct{}{}- if file.Digest != plugincontract.DigestBytes([]byte(file.Content)) || file.SizeBytes != int64(len(file.Content)) {- return nil, nil, fmt.Errorf("plugin Skill companion file %q failed digest validation", relative)- }- pins = append(pins, pluginruntime.SkillFile{- ArtifactFileID: util.UUIDToString(file.ID),- Path: relative,- Digest: file.Digest,- SizeBytes: file.SizeBytes,- })- bundleFiles = append(bundleFiles, skillbundle.File{Path: relative, Content: file.Content})- }- if !foundEntry {- return nil, nil, fmt.Errorf("plugin Skill entry %q is missing from release artifacts", entryPath)- }- sort.Slice(pins, func(i, j int) bool { return pins[i].Path < pins[j].Path })- sort.Slice(bundleFiles, func(i, j int) bool { return bundleFiles[i].Path < bundleFiles[j].Path })- return pins, bundleFiles, nil-}--func materializePinnedPluginSkill(entry pluginruntime.CompiledEntry, filesByID map[string]db.PluginArtifactFile) (AgentSkillData, error) {- root, err := pluginSkillRoot(entry.ContributionKey, entry.EntryPath)- if err != nil {- return AgentSkillData{}, fmt.Errorf("execution manifest contains invalid plugin Skill: %w", err)- }- releaseID, err := util.ParseUUID(entry.ReleaseID)- if err != nil {- return AgentSkillData{}, fmt.Errorf("execution manifest contains invalid release id")- }- entryFile, ok := filesByID[entry.ArtifactFileID]- if !ok || entryFile.ReleaseID != releaseID || entryFile.Path != entry.EntryPath || entryFile.Digest != entry.EntryDigest || plugincontract.DigestBytes([]byte(entryFile.Content)) != entry.EntryDigest {- return AgentSkillData{}, fmt.Errorf("pinned plugin Skill entry failed digest validation")- }- if entry.SkillFileCount != len(entry.SkillFiles) {- return AgentSkillData{}, fmt.Errorf("pinned plugin Skill companion file count is invalid")- }-- skill := AgentSkillData{- ID: "plugin:" + entry.ContributionID,- Source: skillbundle.SourcePlugin,- Name: entry.ContributionKey,- Description: entry.Description,- Content: entryFile.Content,- Files: make([]AgentSkillFileData, 0, len(entry.SkillFiles)),- }- seenPaths := make(map[string]struct{}, len(entry.SkillFiles))- seenIDs := make(map[string]struct{}, len(entry.SkillFiles))- for _, pinned := range entry.SkillFiles {- if err := validatePluginSkillRelativePath(pinned.Path); err != nil {- return AgentSkillData{}, fmt.Errorf("execution manifest contains invalid plugin Skill companion file: %w", err)- }- if pinned.ArtifactFileID == "" || pinned.Digest == "" || pinned.SizeBytes < 0 {- return AgentSkillData{}, fmt.Errorf("execution manifest contains incomplete plugin Skill companion file")- }- if _, exists := seenPaths[pinned.Path]; exists {- return AgentSkillData{}, fmt.Errorf("execution manifest contains duplicate plugin Skill companion path %q", pinned.Path)- }- if _, exists := seenIDs[pinned.ArtifactFileID]; exists {- return AgentSkillData{}, fmt.Errorf("execution manifest contains duplicate plugin Skill artifact file id")- }- seenPaths[pinned.Path] = struct{}{}- seenIDs[pinned.ArtifactFileID] = struct{}{}-- file, ok := filesByID[pinned.ArtifactFileID]- if !ok || file.ReleaseID != releaseID || file.Path != root+pinned.Path || file.Digest != pinned.Digest || file.SizeBytes != pinned.SizeBytes || plugincontract.DigestBytes([]byte(file.Content)) != pinned.Digest || int64(len(file.Content)) != pinned.SizeBytes {- return AgentSkillData{}, fmt.Errorf("pinned plugin Skill companion file %q failed digest validation", pinned.Path)- }- skill.Files = append(skill.Files, AgentSkillFileData{- Path: pinned.Path,- Content: file.Content,- SHA256: pinned.Digest,- SizeBytes: pinned.SizeBytes,- })- }- return skill, nil-}--func pluginSkillRoot(contributionKey, entryPath string) (string, error) {- expected := "skills/" + contributionKey + "/SKILL.md"- if entryPath != expected {- return "", fmt.Errorf("plugin Skill entry must be %q", expected)- }- return strings.TrimSuffix(expected, "SKILL.md"), nil-}--func validatePluginSkillRelativePath(relative string) error {- firstSegment := relative- if separator := strings.IndexByte(relative, '/'); separator >= 0 {- firstSegment = relative[:separator]- }- if relative == "" || relative == "." || relative == ".." || strings.EqualFold(firstSegment, "SKILL.md") || strings.Contains(relative, "\\") || path.IsAbs(relative) || path.Clean(relative) != relative || strings.HasPrefix(relative, "../") {- return fmt.Errorf("plugin Skill companion path %q is invalid", relative)- }- return nil-}diff --git a/server/internal/service/plugin_skill_test.go b/server/internal/service/plugin_skill_test.godeleted file mode 100644index 37cf23a10b..0000000000--- a/server/internal/service/plugin_skill_test.go+++ /dev/null@@ -1,121 +0,0 @@-package service--import (- "testing"-- "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"- "github.com/multica-ai/multica/server/pkg/pluginruntime"-)--func pluginSkillArtifact(id, releaseID, path, content string) db.PluginArtifactFile {- return db.PluginArtifactFile{- ID: util.MustParseUUID(id),- ReleaseID: util.MustParseUUID(releaseID),- Path: path,- Digest: plugincontract.DigestBytes([]byte(content)),- SizeBytes: int64(len(content)),- Content: content,- }-}--func TestCompileAndMaterializePluginSkillCompanionFiles(t *testing.T) {- const (- releaseID = "11111111-1111-1111-1111-111111111111"- entryID = "22222222-2222-2222-2222-222222222222"- agentID = "33333333-3333-3333-3333-333333333333"- rulesID = "44444444-4444-4444-4444-444444444444"- )- entry := pluginSkillArtifact(entryID, releaseID, "skills/research/SKILL.md", "# Research")- agent := pluginSkillArtifact(agentID, releaseID, "skills/research/agents/openai.yaml", "interface: {}")- rules := pluginSkillArtifact(rulesID, releaseID, "skills/research/references/rules.md", "rules")- other := pluginSkillArtifact("55555555-5555-5555-5555-555555555555", releaseID, "skills/other/SKILL.md", "other")- license := pluginSkillArtifact("66666666-6666-6666-6666-666666666666", releaseID, "THIRD_PARTY_LICENSES/source.txt", "license")-- pins, bundleFiles, err := compilePluginSkillFiles(- util.MustParseUUID(releaseID),- "research",- "skills/research/SKILL.md",- []db.PluginArtifactFile{rules, other, entry, license, agent},- )- if err != nil {- t.Fatalf("compilePluginSkillFiles: %v", err)- }- if len(pins) != 2 || pins[0].Path != "agents/openai.yaml" || pins[1].Path != "references/rules.md" {- t.Fatalf("compiled pins = %#v", pins)- }- if len(bundleFiles) != 2 || bundleFiles[0].Path != pins[0].Path || bundleFiles[1].Path != pins[1].Path {- t.Fatalf("bundle files = %#v", bundleFiles)- }-- compiled := pluginruntime.CompiledEntry{- ReleaseID: releaseID,- ContributionID: "77777777-7777-7777-7777-777777777777",- ContributionKey: "research",- ArtifactFileID: entryID,- EntryPath: entry.Path,- EntryDigest: entry.Digest,- SkillFileCount: len(pins),- SkillFiles: pins,- Description: "Research from primary sources",- ContributionType: plugincontract.ContributionAgentSkillV1,- }- filesByID := map[string]db.PluginArtifactFile{- entryID: entry,- agentID: agent,- rulesID: rules,- }- skill, err := materializePinnedPluginSkill(compiled, filesByID)- if err != nil {- t.Fatalf("materializePinnedPluginSkill: %v", err)- }- if skill.Content != entry.Content || len(skill.Files) != 2 || skill.Files[0].Path != "agents/openai.yaml" || skill.Files[1].Path != "references/rules.md" {- t.Fatalf("materialized Skill = %#v", skill)- }-}--func TestCompilePluginSkillFilesRejectsDigestDrift(t *testing.T) {- const releaseID = "11111111-1111-1111-1111-111111111111"- entry := pluginSkillArtifact("22222222-2222-2222-2222-222222222222", releaseID, "skills/research/SKILL.md", "# Research")- companion := pluginSkillArtifact("33333333-3333-3333-3333-333333333333", releaseID, "skills/research/rules.md", "rules")- companion.Content = "tampered"- if _, _, err := compilePluginSkillFiles(util.MustParseUUID(releaseID), "research", entry.Path, []db.PluginArtifactFile{entry, companion}); err == nil {- t.Fatal("digest drift was accepted")- }-}--func TestMaterializePinnedPluginSkillRejectsPathEscape(t *testing.T) {- entryFile := pluginSkillArtifact(- "22222222-2222-2222-2222-222222222222",- "11111111-1111-1111-1111-111111111111",- "skills/research/SKILL.md",- "# Research",- )- entry := pluginruntime.CompiledEntry{- ReleaseID: "11111111-1111-1111-1111-111111111111",- ContributionKey: "research",- ArtifactFileID: "22222222-2222-2222-2222-222222222222",- EntryPath: "skills/research/SKILL.md",- EntryDigest: entryFile.Digest,- SkillFileCount: 1,- SkillFiles: []pluginruntime.SkillFile{{- ArtifactFileID: "33333333-3333-3333-3333-333333333333",- Path: "../escape.md",- Digest: "sha256:invalid",- SizeBytes: 1,- }},- }- if _, err := materializePinnedPluginSkill(entry, map[string]db.PluginArtifactFile{entry.ArtifactFileID: entryFile}); err == nil {- t.Fatal("path escape was accepted")- }-}--func TestValidatePluginSkillRelativePathRejectsPrimaryContentDescendant(t *testing.T) {- if err := validatePluginSkillRelativePath("SKILL.md/hidden.txt"); err == nil {- t.Fatal("primary content descendant was accepted")- }- if err := validatePluginSkillRelativePath(".."); err == nil {- t.Fatal("bare parent path was accepted")- }-}diff --git a/server/internal/service/plugin_storage.go b/server/internal/service/plugin_storage.gonew file mode 100644index 0000000000..9cb942dada--- /dev/null+++ b/server/internal/service/plugin_storage.go@@ -0,0 +1,175 @@+package service++import (+ "context"+ "errors"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Plugin storage scopes. There are exactly two, and adding a third is a product+// decision, not a configuration knob.+const (+ // PluginStorageWorkspace is team-shared state. scope_id is the workspace id.+ PluginStorageWorkspace = "workspace"+ // PluginStorageUser is per-member state, including that member's own+ // credentials for the plugin's external service. scope_id is the user id.+ PluginStorageUser = "user"+)++// Storage quotas. Enforced on write and never by eviction: a plugin that hits+// its ceiling gets an explicit error, because silently dropping the oldest key+// would corrupt state the plugin believes it stored.+const (+ MaxPluginStorageKeyBytes = 1024+ MaxPluginStorageValueBytes = 100 * 1024+ MaxPluginStorageKeys = 1000+ MaxPluginStorageTotalBytes = 5 * 1024 * 1024+)++// PluginStorageKey is one key in a listing. Values are deliberately absent:+// listing is for a plugin to discover what it wrote, not to bulk-read state.+type PluginStorageKey struct {+ Key string `json:"key"`+ SizeBytes int64 `json:"size_bytes"`+ UpdatedAt string `json:"updated_at"`+}++// ResolveStorageScope maps a scope name to the row's scope_id.+func ResolveStorageScope(scopeType string, workspaceID, userID pgtype.UUID) (pgtype.UUID, error) {+ switch scopeType {+ case PluginStorageWorkspace:+ return workspaceID, nil+ case PluginStorageUser:+ return userID, nil+ default:+ return pgtype.UUID{}, pluginErrf(PluginErrorInvalid, "storage scope must be %q or %q", PluginStorageWorkspace, PluginStorageUser)+ }+}++func validateStorageKey(key string) error {+ if key == "" {+ return pluginErrf(PluginErrorInvalid, "storage key is required")+ }+ if len(key) > MaxPluginStorageKeyBytes {+ return pluginErrf(PluginErrorQuota, "storage key exceeds %d bytes", MaxPluginStorageKeyBytes)+ }+ return nil+}++// GetStorageValue reads one value. This path can never reach plugin_secret:+// secrets live in a different table with no read query that returns ciphertext+// to a request handler.+func (s *PluginService) GetStorageValue(ctx context.Context, installationID pgtype.UUID, scopeType string, scopeID pgtype.UUID, key string) (string, error) {+ if err := validateStorageKey(key); err != nil {+ return "", err+ }+ row, err := s.Queries.GetPluginStorageValue(ctx, db.GetPluginStorageValueParams{+ InstallationID: installationID,+ ScopeType: scopeType,+ ScopeID: scopeID,+ Key: key,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return "", pluginErrf(PluginErrorNotFound, "storage key not found")+ }+ if err != nil {+ return "", &PluginError{Kind: PluginErrorUnavailable, Message: "read plugin storage", Err: err}+ }+ return row.Value, nil+}++func (s *PluginService) ListStorageKeys(ctx context.Context, installationID pgtype.UUID, scopeType string, scopeID pgtype.UUID) ([]PluginStorageKey, error) {+ rows, err := s.Queries.ListPluginStorageKeys(ctx, db.ListPluginStorageKeysParams{+ InstallationID: installationID,+ ScopeType: scopeType,+ ScopeID: scopeID,+ })+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "list plugin storage", Err: err}+ }+ keys := make([]PluginStorageKey, 0, len(rows))+ for _, row := range rows {+ keys = append(keys, PluginStorageKey{+ Key: row.Key,+ SizeBytes: row.SizeBytes,+ UpdatedAt: row.UpdatedAt.Time.UTC().Format("2006-01-02T15:04:05Z07:00"),+ })+ }+ return keys, nil+}++// EnforceStorageQuota decides whether one write fits, given the scope's usage+// with the candidate key excluded. Kept pure and separate from the write so the+// three limits have one canonical test, and so it is obvious that every bound+// is compared in bytes — the usage query reports octet_length for the same+// reason.+//+// Known bound: usage is read before the write without a lock, so concurrent+// writers to the same scope can overshoot by their own sizes. Serializing every+// plugin KV write to close that gap costs more than the overshoot is worth; the+// limits exist to stop runaway growth, not to be exact to the byte.+func EnforceStorageQuota(usage db.GetPluginStorageUsageRow, valueBytes int) error {+ if valueBytes > MaxPluginStorageValueBytes {+ return pluginErrf(PluginErrorQuota, "storage value exceeds %d bytes", MaxPluginStorageValueBytes)+ }+ if usage.KeyCount+1 > MaxPluginStorageKeys {+ return pluginErrf(PluginErrorQuota, "storage scope already holds the maximum of %d keys", MaxPluginStorageKeys)+ }+ if usage.TotalBytes+int64(valueBytes) > MaxPluginStorageTotalBytes {+ return pluginErrf(PluginErrorQuota, "storage scope exceeds its %d byte budget", MaxPluginStorageTotalBytes)+ }+ return nil+}++// SetStorageValue writes one value after checking every quota. The usage query+// excludes the key being written, so replacing a value is measured as a+// replacement and cannot fail a limit the existing row already occupies.+func (s *PluginService) SetStorageValue(ctx context.Context, installationID pgtype.UUID, scopeType string, scopeID pgtype.UUID, key, value string) error {+ if err := validateStorageKey(key); err != nil {+ return err+ }+ usage, err := s.Queries.GetPluginStorageUsage(ctx, db.GetPluginStorageUsageParams{+ InstallationID: installationID,+ ScopeType: scopeType,+ ScopeID: scopeID,+ Key: key,+ })+ if err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "read plugin storage usage", Err: err}+ }+ if err := EnforceStorageQuota(usage, len(value)); err != nil {+ return err+ }+ if _, err := s.Queries.UpsertPluginStorageValue(ctx, db.UpsertPluginStorageValueParams{+ InstallationID: installationID,+ ScopeType: scopeType,+ ScopeID: scopeID,+ Key: key,+ Value: value,+ }); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "write plugin storage", Err: err}+ }+ return nil+}++func (s *PluginService) DeleteStorageValue(ctx context.Context, installationID pgtype.UUID, scopeType string, scopeID pgtype.UUID, key string) error {+ if err := validateStorageKey(key); err != nil {+ return err+ }+ rows, err := s.Queries.DeletePluginStorageValue(ctx, db.DeletePluginStorageValueParams{+ InstallationID: installationID,+ ScopeType: scopeType,+ ScopeID: scopeID,+ Key: key,+ })+ if err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin storage", Err: err}+ }+ if rows == 0 {+ return pluginErrf(PluginErrorNotFound, "storage key not found")+ }+ return nil+}diff --git a/server/internal/service/plugin_storage_db_test.go b/server/internal/service/plugin_storage_db_test.gonew file mode 100644index 0000000000..38e89f8ce2--- /dev/null+++ b/server/internal/service/plugin_storage_db_test.go@@ -0,0 +1,186 @@+package service++import (+ "context"+ "encoding/json"+ "fmt"+ "os"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// The quota decision itself is covered by TestEnforceStorageQuota. What can+// only be pinned against a real database is the usage query underneath it: that+// it measures bytes rather than characters, and that excluding the candidate+// key makes an overwrite count as a replacement instead of an addition. Both+// are invisible to a unit test and both silently inflate the effective budget+// when wrong.++func newPluginStoragePool(t *testing.T) *pgxpool.Pool {+ t.Helper()++ dbURL := os.Getenv("DATABASE_URL")+ if dbURL == "" {+ dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"+ }++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ pool, err := pgxpool.New(ctx, dbURL)+ if err != nil {+ t.Skipf("database unavailable: %v", err)+ }+ if err := pool.Ping(ctx); err != nil {+ pool.Close()+ t.Skipf("database unreachable: %v", err)+ }+ t.Cleanup(pool.Close)+ return pool+}++// seedPluginInstallation creates the one row the storage tables hang off. There+// are no foreign keys, but the service always operates through an installation+// id, so the test does too.+func seedPluginInstallation(t *testing.T, pool *pgxpool.Pool) pgtype.UUID {+ t.Helper()+ ctx := context.Background()+ suffix := time.Now().UnixNano()++ var workspaceID string+ if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug) VALUES ('plugin ws', $1) RETURNING id`,+ fmt.Sprintf("plugin-storage-%d", suffix)).Scan(&workspaceID); err != nil {+ t.Fatalf("seed workspace: %v", err)+ }+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID) })++ manifest, _ := json.Marshal(map[string]any{"manifest_version": 1})+ var installationID string+ if err := pool.QueryRow(ctx,+ `INSERT INTO plugin_installation (workspace_id, plugin_key, source_url, version, manifest)+ VALUES ($1, $2, 'local:fixture', '1.0.0', $3) RETURNING id`,+ workspaceID, fmt.Sprintf("com.example.storage%d", suffix), manifest,+ ).Scan(&installationID); err != nil {+ t.Fatalf("seed plugin installation: %v", err)+ }+ t.Cleanup(func() {+ pool.Exec(context.Background(), `DELETE FROM plugin_storage WHERE installation_id = $1`, installationID)+ pool.Exec(context.Background(), `DELETE FROM plugin_installation WHERE id = $1`, installationID)+ })++ parsed, err := util.ParseUUID(installationID)+ if err != nil {+ t.Fatalf("parse installation id: %v", err)+ }+ return parsed+}++func TestPluginStorageUsageCountsBytesAndExcludesTheCandidateKey(t *testing.T) {+ pool := newPluginStoragePool(t)+ ctx := context.Background()+ queries := db.New(pool)+ service := &PluginService{Queries: queries}++ installationID := seedPluginInstallation(t, pool)+ scopeID := installationID // any UUID: the scope is opaque to storage++ // 10 four-byte characters: 10 runes, 40 bytes.+ value := strings.Repeat("🙂", 10)+ if err := service.SetStorageValue(ctx, installationID, PluginStorageWorkspace, scopeID, "emoji", value); err != nil {+ t.Fatalf("SetStorageValue: %v", err)+ }++ usage, err := queries.GetPluginStorageUsage(ctx, db.GetPluginStorageUsageParams{+ InstallationID: installationID,+ ScopeType: PluginStorageWorkspace,+ ScopeID: scopeID,+ Key: "other",+ })+ if err != nil {+ t.Fatalf("GetPluginStorageUsage: %v", err)+ }+ if usage.KeyCount != 1 {+ t.Fatalf("key_count = %d, want 1", usage.KeyCount)+ }+ if usage.TotalBytes != int64(len(value)) {+ t.Fatalf("total_bytes = %d, want %d (char_length would report %d)",+ usage.TotalBytes, len(value), len([]rune(value)))+ }++ // Same query with the stored key as the candidate: an overwrite must be+ // measured as a replacement, so the existing row drops out entirely.+ replacement, err := queries.GetPluginStorageUsage(ctx, db.GetPluginStorageUsageParams{+ InstallationID: installationID,+ ScopeType: PluginStorageWorkspace,+ ScopeID: scopeID,+ Key: "emoji",+ })+ if err != nil {+ t.Fatalf("GetPluginStorageUsage (replacement): %v", err)+ }+ if replacement.KeyCount != 0 || replacement.TotalBytes != 0 {+ t.Fatalf("replacement usage = (%d keys, %d bytes), want (0, 0)", replacement.KeyCount, replacement.TotalBytes)+ }++ // The listing reports the same byte count the quota is spent against.+ keys, err := service.ListStorageKeys(ctx, installationID, PluginStorageWorkspace, scopeID)+ if err != nil {+ t.Fatalf("ListStorageKeys: %v", err)+ }+ if len(keys) != 1 || keys[0].SizeBytes != int64(len(value)) {+ t.Fatalf("listed keys = %+v, want one key of %d bytes", keys, len(value))+ }+}++func TestPluginStorageRejectsAValueOverTheByteCap(t *testing.T) {+ pool := newPluginStoragePool(t)+ ctx := context.Background()+ service := &PluginService{Queries: db.New(pool)}++ installationID := seedPluginInstallation(t, pool)++ // Under the cap in characters, over it in bytes. Before the accounting was+ // byte-based this write was accepted by both the service and the column+ // constraint.+ oversized := strings.Repeat("🙂", MaxPluginStorageValueBytes/4+1)+ err := service.SetStorageValue(ctx, installationID, PluginStorageWorkspace, installationID, "big", oversized)+ if err == nil {+ t.Fatal("SetStorageValue accepted a value over the byte cap")+ }+ if kind := pluginErrKind(t, err); kind != PluginErrorQuota {+ t.Fatalf("kind = %q, want %q", kind, PluginErrorQuota)+ }+}++func TestPluginStorageScopesAreIsolated(t *testing.T) {+ pool := newPluginStoragePool(t)+ ctx := context.Background()+ service := &PluginService{Queries: db.New(pool)}++ installationID := seedPluginInstallation(t, pool)+ otherScope, err := util.ParseUUID("11111111-1111-1111-1111-111111111111")+ if err != nil {+ t.Fatalf("parse scope id: %v", err)+ }++ if err := service.SetStorageValue(ctx, installationID, PluginStorageUser, installationID, "pref", "mine"); err != nil {+ t.Fatalf("SetStorageValue: %v", err)+ }+ // A different member's user scope must not see it — this is the guarantee+ // that makes storage:user safe to grant.+ if _, err := service.GetStorageValue(ctx, installationID, PluginStorageUser, otherScope, "pref"); err == nil {+ t.Fatal("a user-scoped value was readable from another member's scope")+ } else if kind := pluginErrKind(t, err); kind != PluginErrorNotFound {+ t.Fatalf("kind = %q, want %q", kind, PluginErrorNotFound)+ }+ // Nor may the workspace scope, which is a different scope_type entirely.+ if _, err := service.GetStorageValue(ctx, installationID, PluginStorageWorkspace, installationID, "pref"); err == nil {+ t.Fatal("a user-scoped value was readable from the workspace scope")+ }+}diff --git a/server/internal/service/plugin_test.go b/server/internal/service/plugin_test.gonew file mode 100644index 0000000000..0982035098--- /dev/null+++ b/server/internal/service/plugin_test.go@@ -0,0 +1,365 @@+package service++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+)++const testManifestJSON = `{+ "manifest_version": 1,+ "key": "com.example.hello",+ "name": "Hello Panel",+ "version": "1.0.0",+ "author": { "name": "example" },+ "scopes": ["issues:read", "comments:write", "storage:user"],+ "config": {+ "repo": { "type": "string", "label": "Repo", "required": true },+ "count": { "type": "number", "label": "Count" },+ "verbose": { "type": "bool", "label": "Verbose" },+ "mode": { "type": "enum", "label": "Mode", "options": ["fast", "thorough"] },+ "token": { "type": "secret", "label": "Token" }+ },+ "contributes": {+ "surfaces": [{ "key": "hello", "type": "issue_panel", "name": "Hello", "entry": "ui/main.js" }]+ }+}`++func testManifest(t *testing.T) plugincontract.Manifest {+ t.Helper()+ manifest, _, err := plugincontract.ParseManifest([]byte(testManifestJSON))+ if err != nil {+ t.Fatalf("parse test manifest: %v", err)+ }+ return manifest+}++func pluginErrKind(t *testing.T, err error) PluginErrorKind {+ t.Helper()+ var pluginErr *PluginError+ if !errors.As(err, &pluginErr) {+ t.Fatalf("error %v is not a *PluginError", err)+ }+ return pluginErr.Kind+}++func TestRequireExactScopes(t *testing.T) {+ manifest := testManifest(t)++ if err := requireExactScopes(manifest.Scopes, []string{"comments:write", "storage:user", "issues:read"}); err != nil {+ t.Fatalf("exact scopes in a different order should be accepted: %v", err)+ }+ // Partial consent would install a plugin that silently fails on the scope+ // the administrator withheld, so it is a conflict rather than a warning.+ if err := requireExactScopes(manifest.Scopes, []string{"issues:read"}); err == nil {+ t.Fatal("partial consent was accepted")+ } else if kind := pluginErrKind(t, err); kind != PluginErrorConflict {+ t.Fatalf("partial consent kind = %q, want %q", kind, PluginErrorConflict)+ }+ // Granting more than the manifest asks for would hand out access the+ // consent screen never justified.+ if err := requireExactScopes(manifest.Scopes, []string{"issues:read", "comments:write", "issues:write"}); err == nil {+ t.Fatal("consent to an unrequested scope was accepted")+ }+}++func TestNormalizeConfigValue(t *testing.T) {+ manifest := testManifest(t)+ field := func(key string) plugincontract.ConfigField {+ got, ok := manifest.Config.Field(key)+ if !ok {+ t.Fatalf("config field %q missing from the test manifest", key)+ }+ return got+ }++ if value, err := normalizeConfigValue(field("repo"), "multica-ai/multica"); err != nil || value != "multica-ai/multica" {+ t.Fatalf("string field = (%v, %v)", value, err)+ }+ if value, err := normalizeConfigValue(field("count"), float64(3)); err != nil || value != float64(3) {+ t.Fatalf("number field = (%v, %v)", value, err)+ }+ if value, err := normalizeConfigValue(field("verbose"), true); err != nil || value != true {+ t.Fatalf("bool field = (%v, %v)", value, err)+ }+ if value, err := normalizeConfigValue(field("mode"), "fast"); err != nil || value != "fast" {+ t.Fatalf("enum field = (%v, %v)", value, err)+ }++ rejected := []struct {+ name string+ key string+ value any+ }{+ {"string given a number", "repo", float64(1)},+ {"number given a string", "count", "3"},+ {"bool given a string", "verbose", "true"},+ {"enum outside its options", "mode", "sloppy"},+ {"string over the length cap", "repo", strings.Repeat("x", 4097)},+ }+ for _, tc := range rejected {+ t.Run(tc.name, func(t *testing.T) {+ if _, err := normalizeConfigValue(field(tc.key), tc.value); err == nil {+ t.Fatalf("normalizeConfigValue accepted %v", tc.value)+ } else if kind := pluginErrKind(t, err); kind != PluginErrorInvalid {+ t.Fatalf("kind = %q, want %q", kind, PluginErrorInvalid)+ }+ })+ }+}++func TestPruneConfigDropsFieldsTheNewManifestRemoved(t *testing.T) {+ manifest := testManifest(t)+ pruned := pruneConfig([]byte(`{"repo":"a","gone":"b"}`), manifest)++ var values map[string]any+ if err := json.Unmarshal(pruned, &values); err != nil {+ t.Fatalf("decode pruned config: %v", err)+ }+ if values["repo"] != "a" {+ t.Fatalf("pruneConfig dropped a field the manifest still declares: %s", pruned)+ }+ if _, present := values["gone"]; present {+ t.Fatalf("pruneConfig kept an unreachable field: %s", pruned)+ }+ if got := string(pruneConfig(nil, manifest)); got != "{}" {+ t.Fatalf("pruneConfig(nil) = %q, want %q", got, "{}")+ }+}++func TestAddedScopesReportsOnlyNewGrants(t *testing.T) {+ added := addedScopes([]string{"issues:read"}, []string{"issues:read", "comments:write"})+ if len(added) != 1 || added[0] != "comments:write" {+ t.Fatalf("addedScopes = %v", added)+ }+ if added := addedScopes([]string{"issues:read", "comments:write"}, []string{"issues:read"}); len(added) != 0 {+ t.Fatalf("a narrowed scope set must not report additions, got %v", added)+ }+}++func TestParseInstallationManifestReadsTheConsentedSnapshot(t *testing.T) {+ _, canonical, err := plugincontract.ParseManifest([]byte(testManifestJSON))+ if err != nil {+ t.Fatalf("parse manifest: %v", err)+ }+ manifest, err := ParseInstallationManifest(db.PluginInstallation{Manifest: canonical})+ if err != nil {+ t.Fatalf("ParseInstallationManifest: %v", err)+ }+ if manifest.Key != "com.example.hello" || manifest.Config.Len() != 5 {+ t.Fatalf("unexpected manifest: %+v", manifest)+ }+ if _, err := ParseInstallationManifest(db.PluginInstallation{Manifest: []byte("not json")}); err == nil {+ t.Fatal("ParseInstallationManifest accepted a corrupt snapshot")+ }+}++func TestConfigFieldsForManifestKeepsDeclarationOrder(t *testing.T) {+ fields := ConfigFieldsForManifest(testManifest(t))+ want := []string{"repo", "count", "verbose", "mode", "token"}+ if len(fields) != len(want) {+ t.Fatalf("config fields = %d, want %d", len(fields), len(want))+ }+ for i, key := range want {+ if fields[i].Key != key {+ t.Fatalf("field %d = %q, want %q", i, fields[i].Key, key)+ }+ }+}++func TestFetchManifestFromLocalDir(t *testing.T) {+ root := t.TempDir()+ if err := os.MkdirAll(filepath.Join(root, "hello"), 0o755); err != nil {+ t.Fatalf("create local plugin dir: %v", err)+ }+ if err := os.WriteFile(filepath.Join(root, "hello", plugincontract.ManifestFilename), []byte(testManifestJSON), 0o644); err != nil {+ t.Fatalf("write local manifest: %v", err)+ }+ service := &PluginService{LocalDir: root}++ manifest, canonical, err := service.FetchManifest(context.Background(), LocalSourcePrefix+"hello")+ if err != nil {+ t.Fatalf("FetchManifest: %v", err)+ }+ if manifest.Key != "com.example.hello" || len(canonical) == 0 {+ t.Fatalf("unexpected manifest: %+v", manifest)+ }++ if _, _, err := service.FetchManifest(context.Background(), LocalSourcePrefix+"missing"); err == nil {+ t.Fatal("FetchManifest accepted a missing local plugin")+ } else if kind := pluginErrKind(t, err); kind != PluginErrorNotFound {+ t.Fatalf("missing local plugin kind = %q, want %q", kind, PluginErrorNotFound)+ }++ // A traversing name would let an API caller read any manifest-shaped file+ // on the host, so it is rejected before it reaches the filesystem.+ for _, name := range []string{"../secrets", "nested/plugin", ".hidden", ""} {+ if _, _, err := service.FetchManifest(context.Background(), LocalSourcePrefix+name); err == nil {+ t.Fatalf("FetchManifest accepted local source %q", name)+ }+ }++ disabled := &PluginService{}+ if _, _, err := disabled.FetchManifest(context.Background(), LocalSourcePrefix+"hello"); err == nil {+ t.Fatal("local sources must require MULTICA_PLUGIN_DIR")+ }+}++func TestFetchManifestRejectsNonPublicSources(t *testing.T) {+ service := &PluginService{}+ for _, source := range []string{+ "",+ "http://example.com/multica.plugin.json",+ "https://localhost/multica.plugin.json",+ "https://127.0.0.1/multica.plugin.json",+ "https://169.254.169.254/latest/meta-data",+ "file:///etc/passwd",+ "https://user:[email protected]/multica.plugin.json",+ } {+ if _, _, err := service.FetchManifest(context.Background(), source); err == nil {+ t.Fatalf("FetchManifest accepted source %q", source)+ }+ }+}++func TestResolveStorageScope(t *testing.T) {+ workspaceID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}+ userID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}++ if got, err := ResolveStorageScope(PluginStorageWorkspace, workspaceID, userID); err != nil || got != workspaceID {+ t.Fatalf("workspace scope = (%v, %v)", got, err)+ }+ if got, err := ResolveStorageScope(PluginStorageUser, workspaceID, userID); err != nil || got != userID {+ t.Fatalf("user scope = (%v, %v)", got, err)+ }+ if _, err := ResolveStorageScope("global", workspaceID, userID); err == nil {+ t.Fatal("ResolveStorageScope accepted an undefined scope")+ }+}++func TestValidateStorageKeyEnforcesTheKeyQuota(t *testing.T) {+ if err := validateStorageKey(""); err == nil {+ t.Fatal("validateStorageKey accepted an empty key")+ }+ if err := validateStorageKey(strings.Repeat("k", MaxPluginStorageKeyBytes)); err != nil {+ t.Fatalf("a key exactly at the limit must be accepted: %v", err)+ }+ err := validateStorageKey(strings.Repeat("k", MaxPluginStorageKeyBytes+1))+ if err == nil {+ t.Fatal("validateStorageKey accepted an oversized key")+ }+ if kind := pluginErrKind(t, err); kind != PluginErrorQuota {+ t.Fatalf("oversized key kind = %q, want %q", kind, PluginErrorQuota)+ }+}++func TestCapabilityMessageNamesTheMissingCapabilities(t *testing.T) {+ manifest := testManifest(t)+ err := manifest.CheckCapabilities(plugincontract.HostCapabilities())+ if err == nil {+ t.Fatal("expected the shipped host set to reject a surface contribution")+ }+ message := capabilityMessage(err)+ if !strings.Contains(message, "surface issue_panel") {+ t.Fatalf("capabilityMessage = %q, want it to name the missing capability", message)+ }+}++func TestEnforceStorageQuota(t *testing.T) {+ // Canonical layer for the three storage limits. SetStorageValue only wires+ // the usage query to this function; plugin_storage_db_test.go covers the+ // query's own semantics.+ cases := []struct {+ name string+ usage db.GetPluginStorageUsageRow+ valueBytes int+ wantKind PluginErrorKind+ }{+ {"empty scope", db.GetPluginStorageUsageRow{}, 10, ""},+ {"value exactly at the cap", db.GetPluginStorageUsageRow{}, MaxPluginStorageValueBytes, ""},+ {"value one byte over the cap", db.GetPluginStorageUsageRow{}, MaxPluginStorageValueBytes + 1, PluginErrorQuota},+ {+ "last free key slot",+ db.GetPluginStorageUsageRow{KeyCount: MaxPluginStorageKeys - 1},+ 1, "",+ },+ {+ "key slots exhausted",+ db.GetPluginStorageUsageRow{KeyCount: MaxPluginStorageKeys},+ 1, PluginErrorQuota,+ },+ {+ "total budget exactly filled",+ db.GetPluginStorageUsageRow{KeyCount: 1, TotalBytes: MaxPluginStorageTotalBytes - 10},+ 10, "",+ },+ {+ "total budget exceeded by one byte",+ db.GetPluginStorageUsageRow{KeyCount: 1, TotalBytes: MaxPluginStorageTotalBytes - 10},+ 11, PluginErrorQuota,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ err := EnforceStorageQuota(tc.usage, tc.valueBytes)+ if tc.wantKind == "" {+ if err != nil {+ t.Fatalf("EnforceStorageQuota = %v, want nil", err)+ }+ return+ }+ if err == nil {+ t.Fatal("EnforceStorageQuota accepted a write over quota")+ }+ if kind := pluginErrKind(t, err); kind != tc.wantKind {+ t.Fatalf("kind = %q, want %q", kind, tc.wantKind)+ }+ })+ }+}++func TestEnforceStorageQuotaCountsBytesNotCharacters(t *testing.T) {+ // A 4-byte emoji is one character. If any bound counted characters the+ // effective budget would be up to 4x what the limit advertises.+ emoji := "🙂"+ if len(emoji) != 4 {+ t.Fatalf("fixture is not 4 bytes: %d", len(emoji))+ }+ oversized := strings.Repeat(emoji, MaxPluginStorageValueBytes/4+1)+ if err := EnforceStorageQuota(db.GetPluginStorageUsageRow{}, len(oversized)); err == nil {+ t.Fatal("a value over the byte cap was accepted")+ }+ if len([]rune(oversized)) >= MaxPluginStorageValueBytes {+ t.Fatal("fixture does not distinguish characters from bytes")+ }+}++func TestOrphanedSecretFieldsAreDetectedByType(t *testing.T) {+ // The pure half of upgrade-time secret pruning: which stored keys the new+ // manifest no longer declares as a secret. A field that changed type away+ // from secret counts as orphaned — its ciphertext is unreachable too.+ manifest := testManifest(t)+ for _, tc := range []struct {+ key string+ want bool+ }{+ {"token", false},+ {"repo", true},+ {"removed_field", true},+ } {+ field, ok := manifest.Config.Field(tc.key)+ orphaned := !ok || field.Type != plugincontract.ConfigSecret+ if orphaned != tc.want {+ t.Fatalf("%q orphaned = %v, want %v", tc.key, orphaned, tc.want)+ }+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex d153fad85b..ea7d1685b1 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -27,8 +27,6 @@ import ("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/featureflag"- "github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/pluginruntime""github.com/multica-ai/multica/server/pkg/protocol""github.com/multica-ai/multica/server/pkg/redact""github.com/multica-ai/multica/server/pkg/skillbundle"@@ -5587,107 +5585,6 @@ func (s *TaskService) LoadAgentSkillBundles(ctx context.Context, agentID pgtype.return BuildAgentSkillBundles(skills)}-type PluginExecutionManifestData struct {- ID string `json:"id"`- SnapshotID string `json:"snapshot_id,omitempty"`- SnapshotRevision int64 `json:"snapshot_revision"`- SnapshotDigest string `json:"snapshot_digest,omitempty"`- ComposerVersion string `json:"composer_version"`- SchemaVersion int32 `json:"schema_version"`- OrderedContributions []pluginruntime.CompiledEntry `json:"ordered_contributions"`- Diagnostics []string `json:"diagnostics,omitempty"`-}--// LoadTaskPluginSkillBundles resolves only the immutable artifact files named-// by the task's enqueue-time execution manifest. It deliberately does not read-// current installation state, so disable/upgrade cannot mutate an in-flight or-// retried run's inputs.-func (s *TaskService) LoadTaskPluginSkillBundles(ctx context.Context, taskID pgtype.UUID) ([]AgentSkillData, []AgentSkillRefData, *PluginExecutionManifestData, error) {- manifest, err := s.Queries.GetPluginExecutionManifestByTask(ctx, taskID)- if errors.Is(err, pgx.ErrNoRows) {- return nil, nil, nil, nil- }- if err != nil {- return nil, nil, nil, fmt.Errorf("load plugin execution manifest: %w", err)- }- entries, err := pluginruntime.ParseEntries(manifest.OrderedContributions)- if err != nil {- return nil, nil, nil, err- }- data := &PluginExecutionManifestData{- ID: util.UUIDToString(manifest.ID),- SnapshotID: util.UUIDToString(manifest.SnapshotID),- SnapshotRevision: manifest.SnapshotRevision,- SnapshotDigest: manifest.SnapshotDigest.String,- ComposerVersion: manifest.ComposerVersion,- SchemaVersion: manifest.SchemaVersion,- OrderedContributions: entries,- }- if len(entries) == 0 {- return nil, nil, data, nil- }- artifactFileIDs := make([]pgtype.UUID, 0)- seenArtifactFileIDs := make(map[string]struct{})- for _, entry := range entries {- if entry.ContributionType != plugincontract.ContributionAgentSkillV1 {- continue- }- ids := make([]string, 0, len(entry.SkillFiles)+1)- ids = append(ids, entry.ArtifactFileID)- for _, file := range entry.SkillFiles {- ids = append(ids, file.ArtifactFileID)- }- for _, id := range ids {- if _, exists := seenArtifactFileIDs[id]; exists {- continue- }- parsed, parseErr := util.ParseUUID(id)- if parseErr != nil {- return nil, nil, nil, fmt.Errorf("execution manifest contains invalid artifact file id")- }- seenArtifactFileIDs[id] = struct{}{}- artifactFileIDs = append(artifactFileIDs, parsed)- }- }- artifactFilesByID := make(map[string]db.PluginArtifactFile, len(artifactFileIDs))- if len(artifactFileIDs) > 0 {- artifactFiles, listErr := s.Queries.ListPluginArtifactFilesByIDs(ctx, artifactFileIDs)- if listErr != nil {- return nil, nil, nil, fmt.Errorf("load pinned plugin Skill artifacts: %w", listErr)- }- for _, file := range artifactFiles {- artifactFilesByID[util.UUIDToString(file.ID)] = file- }- }-- skills := make([]AgentSkillData, 0, len(entries))- skillEntries := make([]pluginruntime.CompiledEntry, 0, len(entries))- for _, entry := range entries {- if entry.ContributionType == plugincontract.ContributionRemoteMCPV1 {- if entry.ConfigID == "" || entry.ConfigRevision <= 0 || entry.Endpoint == "" || len(entry.ApprovedTools) == 0 || entry.ToolSchemaDigest == "" {- return nil, nil, nil, fmt.Errorf("execution manifest contains invalid remote MCP contribution")- }- continue- }- if entry.ContributionType != plugincontract.ContributionAgentSkillV1 || entry.ArtifactFileID == "" {- return nil, nil, nil, fmt.Errorf("execution manifest contains unsupported plugin contribution")- }- skill, materializeErr := materializePinnedPluginSkill(entry, artifactFilesByID)- if materializeErr != nil {- return nil, nil, nil, materializeErr- }- skills = append(skills, skill)- skillEntries = append(skillEntries, entry)- }- bundles, refs := BuildAgentSkillBundles(skills)- for i := range refs {- if refs[i].Hash != skillEntries[i].SkillBundleHash || refs[i].SizeBytes != skillEntries[i].SkillSizeBytes || refs[i].FileCount != skillEntries[i].SkillFileCount {- return nil, nil, nil, fmt.Errorf("pinned plugin skill bundle failed manifest validation")- }- }- return bundles, refs, data, nil-}-func BuildAgentSkillBundles(skills []AgentSkillData) ([]AgentSkillData, []AgentSkillRefData) {bundles := make([]AgentSkillData, 0, len(skills))refs := make([]AgentSkillRefData, 0, len(skills))diff --git a/server/internal/testutil/plugintest/review_readiness.go b/server/internal/testutil/plugintest/review_readiness.godeleted file mode 100644index 37f18cfa91..0000000000--- a/server/internal/testutil/plugintest/review_readiness.go+++ /dev/null@@ -1,25 +0,0 @@-// Package plugintest exposes production bundled Plugin releases to lifecycle-// and execution-chain tests. Production code never depends on this package.-package plugintest--import (- "fmt"-- "github.com/multica-ai/multica/server/internal/pluginbundled"- "github.com/multica-ai/multica/server/pkg/plugincontract"-)--const (- ReviewReadinessPluginKey = "ai.multica.software-delivery"- ReviewReadinessVersion = "1.0.0"-)--// ReviewReadinessRelease returns the same signed, validated artifact shipped-// by the production bundled catalog.-func ReviewReadinessRelease() (plugincontract.ValidatedRelease, error) {- entry, ok := pluginbundled.Load().Find(ReviewReadinessPluginKey, ReviewReadinessVersion)- if !ok {- return plugincontract.ValidatedRelease{}, fmt.Errorf("bundled review-readiness release is unavailable")- }- return entry.Release, nil-}diff --git a/server/internal/testutil/plugintest/review_readiness_test.go b/server/internal/testutil/plugintest/review_readiness_test.godeleted file mode 100644index 6b7d3715ab..0000000000--- a/server/internal/testutil/plugintest/review_readiness_test.go+++ /dev/null@@ -1,22 +0,0 @@-package plugintest--import (- "strings"- "testing"-)--func TestReviewReadinessReleaseIsSignedAndValidated(t *testing.T) {- release, err := ReviewReadinessRelease()- if err != nil {- t.Fatalf("ReviewReadinessRelease: %v", err)- }- if release.Manifest.Metadata.Key != ReviewReadinessPluginKey || release.Manifest.Metadata.Version != ReviewReadinessVersion {- t.Fatalf("unexpected release identity: %s@%s", release.Manifest.Metadata.Key, release.Manifest.Metadata.Version)- }- if len(release.Signature) == 0 || len(release.Files) != 2 {- t.Fatalf("signature/files = %d/%d", len(release.Signature), len(release.Files))- }- if !strings.Contains(string(release.Files[1].Content), "# Review readiness") {- t.Fatal("reference review-readiness skill content missing")- }-}diff --git a/server/migrations/344_plugin_v2_reset.down.sql b/server/migrations/344_plugin_v2_reset.down.sqlnew file mode 100644index 0000000000..93b36d8850--- /dev/null+++ b/server/migrations/344_plugin_v2_reset.down.sql@@ -0,0 +1,8 @@+-- The dropped V1 plugin schema is not restorable here: it spanned migrations+-- 285-326 with append-only triggers, a snapshot compiler, and an execution+-- manifest trigger on agent_task_queue. Rolling back means running those+-- migrations again. This direction only removes what the up direction created.++DROP TABLE IF EXISTS plugin_secret;+DROP TABLE IF EXISTS plugin_storage;+DROP TABLE IF EXISTS plugin_installation;diff --git a/server/migrations/344_plugin_v2_reset.up.sql b/server/migrations/344_plugin_v2_reset.up.sqlnew file mode 100644index 0000000000..0e4d605f10--- /dev/null+++ b/server/migrations/344_plugin_v2_reset.up.sql@@ -0,0 +1,91 @@+-- Plugin system reset.+--+-- The previous design shipped 14 tables, an append-only revision log per+-- relationship, a capability-snapshot compiler, and a per-task execution+-- manifest pinned by an INSERT trigger on agent_task_queue. It never left its+-- feature flag and holds no production data, so this migration removes it+-- outright rather than migrating it forward.+--+-- What replaces it: one installation row per (workspace, plugin), holding the+-- manifest snapshot the administrator actually consented to, plus two leaf+-- tables for plugin-owned state. Relationships stay application-owned by+-- repository policy: no foreign keys, no cascades.++DROP TRIGGER IF EXISTS trg_agent_task_queue_plugin_execution_manifest ON agent_task_queue;+DROP FUNCTION IF EXISTS pin_plugin_execution_manifest();++DROP TRIGGER IF EXISTS trg_plugin_installation_config_append_only ON plugin_installation_config;+DROP TRIGGER IF EXISTS trg_plugin_health_append_only ON plugin_health;+DROP TRIGGER IF EXISTS trg_plugin_execution_manifest_append_only ON plugin_execution_manifest;+DROP TRIGGER IF EXISTS trg_plugin_capability_snapshot_append_only ON plugin_capability_snapshot;+DROP TRIGGER IF EXISTS trg_plugin_artifact_file_append_only ON plugin_artifact_file;+DROP TRIGGER IF EXISTS trg_plugin_binding_append_only ON plugin_binding;+DROP TRIGGER IF EXISTS trg_plugin_grant_append_only ON plugin_grant;+DROP TRIGGER IF EXISTS trg_plugin_contribution_append_only ON plugin_contribution;+DROP TRIGGER IF EXISTS trg_plugin_release_immutable ON plugin_release;+DROP FUNCTION IF EXISTS reject_plugin_append_only_update();+DROP FUNCTION IF EXISTS enforce_plugin_release_immutable();++ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS plugin_execution_manifest_id;++DROP TABLE IF EXISTS plugin_remote_mcp_oauth_state;+DROP TABLE IF EXISTS plugin_remote_mcp_secret;+DROP TABLE IF EXISTS plugin_installation_config;+DROP TABLE IF EXISTS plugin_health;+DROP TABLE IF EXISTS plugin_execution_manifest;+DROP TABLE IF EXISTS plugin_capability_snapshot;+DROP TABLE IF EXISTS plugin_workspace_capability_state;+DROP TABLE IF EXISTS plugin_artifact_file;+DROP TABLE IF EXISTS plugin_binding;+DROP TABLE IF EXISTS plugin_grant;+DROP TABLE IF EXISTS plugin_installation;+DROP TABLE IF EXISTS plugin_contribution;+DROP TABLE IF EXISTS plugin_release;+DROP TABLE IF EXISTS plugin_identity;++-- One row per installed plugin. `manifest` is the snapshot the administrator+-- saw and approved on the consent screen, not whatever the source URL serves+-- today: an upgrade re-fetches, re-consents, and overwrites it. That is why+-- there is no separate version table.+CREATE TABLE plugin_installation (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ plugin_key TEXT NOT NULL CHECK (char_length(plugin_key) BETWEEN 3 AND 255),+ source_url TEXT NOT NULL CHECK (char_length(source_url) BETWEEN 1 AND 2048),+ version TEXT NOT NULL CHECK (char_length(version) BETWEEN 1 AND 64),+ manifest JSONB NOT NULL CHECK (jsonb_typeof(manifest) = 'object'),+ granted_scopes JSONB NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(granted_scopes) = 'array'),+ config JSONB NOT NULL DEFAULT '{}'::jsonb CHECK (jsonb_typeof(config) = 'object'),+ enabled BOOLEAN NOT NULL DEFAULT TRUE,+ installed_by UUID,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- Plugin-owned key/value state. Exactly two scopes: workspace state shared by+-- the team, and per-member state. Quotas are enforced on write in application+-- code; nothing here is evicted behind the plugin's back.+CREATE TABLE plugin_storage (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ installation_id UUID NOT NULL,+ scope_type TEXT NOT NULL CHECK (scope_type IN ('workspace', 'user')),+ scope_id UUID NOT NULL,+ -- Byte-counted, matching the service-side quota: key and value are+ -- plugin-supplied and routinely non-ASCII.+ key TEXT NOT NULL CHECK (octet_length(key) BETWEEN 1 AND 1024),+ value TEXT NOT NULL CHECK (octet_length(value) <= 102400),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- Secrets live in their own table so no storage read path can reach them by+-- construction. Values are encrypted with MULTICA_PLUGIN_SECRET_KEY and are+-- never returned by any endpoint.+CREATE TABLE plugin_secret (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ installation_id UUID NOT NULL,+ key TEXT NOT NULL CHECK (char_length(key) BETWEEN 1 AND 128),+ ciphertext BYTEA NOT NULL CHECK (octet_length(ciphertext) > 0),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/345_plugin_installation_workspace_key_index.down.sql b/server/migrations/345_plugin_installation_workspace_key_index.down.sqlnew file mode 100644index 0000000000..96344522c9--- /dev/null+++ b/server/migrations/345_plugin_installation_workspace_key_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_installation_workspace_key;diff --git a/server/migrations/345_plugin_installation_workspace_key_index.up.sql b/server/migrations/345_plugin_installation_workspace_key_index.up.sqlnew file mode 100644index 0000000000..4b00c96610--- /dev/null+++ b/server/migrations/345_plugin_installation_workspace_key_index.up.sql@@ -0,0 +1,2 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_plugin_installation_workspace_key+ ON plugin_installation (workspace_id, plugin_key);diff --git a/server/migrations/346_plugin_storage_scope_key_index.down.sql b/server/migrations/346_plugin_storage_scope_key_index.down.sqlnew file mode 100644index 0000000000..3489ddfba9--- /dev/null+++ b/server/migrations/346_plugin_storage_scope_key_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_storage_scope_key;diff --git a/server/migrations/346_plugin_storage_scope_key_index.up.sql b/server/migrations/346_plugin_storage_scope_key_index.up.sqlnew file mode 100644index 0000000000..ac3a96b0e6--- /dev/null+++ b/server/migrations/346_plugin_storage_scope_key_index.up.sql@@ -0,0 +1,2 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_plugin_storage_scope_key+ ON plugin_storage (installation_id, scope_type, scope_id, key);diff --git a/server/migrations/347_plugin_secret_installation_key_index.down.sql b/server/migrations/347_plugin_secret_installation_key_index.down.sqlnew file mode 100644index 0000000000..875837c228--- /dev/null+++ b/server/migrations/347_plugin_secret_installation_key_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_secret_installation_key;diff --git a/server/migrations/347_plugin_secret_installation_key_index.up.sql b/server/migrations/347_plugin_secret_installation_key_index.up.sqlnew file mode 100644index 0000000000..822914ee0a--- /dev/null+++ b/server/migrations/347_plugin_secret_installation_key_index.up.sql@@ -0,0 +1,2 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_plugin_secret_installation_key+ ON plugin_secret (installation_id, key);diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 7575436e2e..38fc90d3a6 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -32,7 +32,7 @@ WHERE acknowledged.id = (WHERE attempt_count.trigger_evidence_kind = 'delegated_failure'AND attempt_count.trigger_evidence_ref_id = $2) >= $3::int-RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.plugin_execution_manifest_id, acknowledged.branch_name+RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name`type AcknowledgeExhaustedDelegatedFailureRecoveryParams struct {@@ -100,7 +100,6 @@ func (q *Queries) AcknowledgeExhaustedDelegatedFailureRecovery(ctx context.Conte&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -299,7 +298,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :oneUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Automatic cancellation without an explicit persisted failure reason. Unlike@@ -359,7 +358,6 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -419,7 +417,7 @@ SET status = 'cancelled',ENDWHERE task.id = $1AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.plugin_execution_manifest_id, task.branch_name+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name`// An explicit user cancellation is a terminal acknowledgement for any@@ -481,7 +479,6 @@ func (q *Queries) CancelAgentTaskByUser(ctx context.Context, id pgtype.UUID) (Ag&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -495,7 +492,7 @@ SET status = 'cancelled',failure_reason = $2,prepare_lease_expires_at = NULLWHERE id = $3 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CancelAgentTaskWithReasonParams struct {@@ -566,7 +563,6 @@ func (q *Queries) CancelAgentTaskWithReason(ctx context.Context, arg CancelAgent&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -576,7 +572,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Bulk-cancel every active (queued/dispatched/running) task for an agent.@@ -645,7 +641,6 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -662,7 +657,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :mUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Cancels active tasks belonging to a chat session. Called from@@ -731,7 +726,6 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -748,7 +742,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Cancels every active task on the issue and returns the affected rows so the@@ -817,7 +811,6 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -834,7 +827,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgenUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CancelAgentTasksByIssueAndAgentParams struct {@@ -907,7 +900,6 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -925,7 +917,7 @@ UPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Cancels active tasks whose planned batch contains the edited/deleted comment.@@ -993,7 +985,6 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -1015,9 +1006,9 @@ WITH cancelled AS (AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')AND primary_task.issue_id = $1AND primary_task.agent_id = $2- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id, fallback.quick_actions_disabled, fallback.regenerate_quick_actions_for, fallback.plugin_execution_manifest_id, fallback.branch_name+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id, fallback.quick_actions_disabled, fallback.regenerate_quick_actions_for, fallback.branch_name)-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM cancelled+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM cancelled`type CancelDeferredEscalationsForIssueAgentParams struct {@@ -1077,7 +1068,6 @@ type CancelDeferredEscalationsForIssueAgentRow struct {RetiredSessionID pgtype.Text `json:"retired_session_id"`QuickActionsDisabled bool `json:"quick_actions_disabled"`RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`- PluginExecutionManifestID pgtype.UUID `json:"plugin_execution_manifest_id"`BranchName pgtype.Text `json:"branch_name"`}@@ -1142,7 +1132,6 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -1160,7 +1149,7 @@ UPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE escalation_for_task_id = $1AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {@@ -1224,7 +1213,6 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -1243,7 +1231,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE id = $1AND chat_session_id = $2AND status = 'queued'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CancelQueuedAgentTaskParams struct {@@ -1308,7 +1296,6 @@ func (q *Queries) CancelQueuedAgentTask(ctx context.Context, arg CancelQueuedAge&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -1337,7 +1324,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE queued.chat_session_id = $1AND queued.status = 'queued'AND queued.id IS DISTINCT FROM (SELECT id FROM head)-RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.plugin_execution_manifest_id, queued.branch_name+RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name`// Clear only positional follow-ups. The first visible task is current even@@ -1405,7 +1392,6 @@ func (q *Queries) CancelQueuedAgentTasksForSession(ctx context.Context, chatSess&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -1456,7 +1442,7 @@ WHERE id = (LIMIT 1FOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type ClaimAgentTaskParams struct {@@ -1536,7 +1522,6 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -1546,7 +1531,7 @@ const claimChatFinalizeDeferred = `-- name: ClaimChatFinalizeDeferred :oneUPDATE agent_task_queueSET chat_finalize_deferred_at = NULLWHERE id = $1 AND chat_finalize_deferred_at IS NOT NULL-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Atomically claims the deferred marker so the daemon ack and the sweeper@@ -1606,7 +1591,6 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -1801,7 +1785,7 @@ SET status = 'completed', completed_at = now(), result = $2,retired_session_id = COALESCE($7, retired_session_id),prepare_lease_expires_at = NULLWHERE id = $1 AND status = 'running'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CompleteAgentTaskParams struct {@@ -1888,7 +1872,6 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -2127,7 +2110,7 @@ SELECT$21,$22WHERE lock_task_owner_rows($1, $3, $2)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CreateAgentTaskParams struct {@@ -2244,7 +2227,6 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -2272,7 +2254,7 @@ SELECT$18,$19WHERE lock_task_owner_rows($1, $3, $2)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CreateDeferredAgentTaskParams struct {@@ -2383,7 +2365,6 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -2421,7 +2402,7 @@ SELECT$22,$23WHERE lock_task_owner_rows($1, $3, $2)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CreateDeferredChannelIssueTaskParams struct {@@ -2536,7 +2517,6 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Create&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -2558,7 +2538,7 @@ SELECT$10,$11WHERE lock_task_owner_rows($1, NULL, $2)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CreateQuickCreateTaskParams struct {@@ -2652,7 +2632,6 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -2690,7 +2669,7 @@ SELECTFROM agent_task_queue pWHERE p.id = $1AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CreateRetryTaskParams struct {@@ -2819,7 +2798,6 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -2956,7 +2934,7 @@ WHERE t.id = v.idWHERE retry_parent.id = t.parent_task_idAND retry_parent.failure_reason = 'runtime_offline')-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.plugin_execution_manifest_id, t.branch_name+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name`type ExpireStaleQueuedTasksParams struct {@@ -3050,7 +3028,6 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -3070,7 +3047,7 @@ WHERE id = $1AND runtime_id = $2AND status IN ('dispatched', 'waiting_local_directory')AND started_at IS NULL-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type ExtendAgentTaskPrepareLeaseParams struct {@@ -3138,7 +3115,6 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -3157,7 +3133,7 @@ SET status = 'failed',retired_session_id = COALESCE($8, retired_session_id),prepare_lease_expires_at = NULLWHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type FailAgentTaskParams struct {@@ -3250,7 +3226,6 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -3298,7 +3273,7 @@ WHERE retry.id = victims.idAND COALESCE(runtime.last_seen_at, runtime.updated_at) >=now() - make_interval(secs => $2::double precision))-RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.plugin_execution_manifest_id, retry.branch_name+RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name`type FailExpiredRuntimeReconnectRetriesParams struct {@@ -3375,7 +3350,6 @@ func (q *Queries) FailExpiredRuntimeReconnectRetries(ctx context.Context, arg Fa&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -3431,7 +3405,7 @@ WHERE ()))-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type FailStaleTasksParams struct {@@ -3539,7 +3513,6 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -3777,7 +3750,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa}const getAgentTask = `-- name: GetAgentTask :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM agent_task_queueWHERE id = $1`@@ -3836,14 +3809,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err}const getAgentTaskForDelegatedFailureUpdate = `-- name: GetAgentTaskForDelegatedFailureUpdate :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM agent_task_queueWHERE id = $1FOR UPDATE`@@ -3906,14 +3878,13 @@ func (q *Queries) GetAgentTaskForDelegatedFailureUpdate(ctx context.Context, id&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err}const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.plugin_execution_manifest_id, atq.branch_name FROM agent_task_queue atq+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE atq.id = $1 AND a.workspace_id = $2`@@ -3985,7 +3956,6 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -4800,7 +4770,7 @@ func (q *Queries) ListActiveSiblingIssueTasks(ctx context.Context, arg ListActiv}const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM agent_task_queueWHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')ORDER BY created_at DESC`@@ -4871,7 +4841,6 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -4885,7 +4854,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI}const listAgentTasks = `-- name: ListAgentTasks :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM agent_task_queueWHERE agent_id = $1ORDER BY created_at DESC`@@ -4951,7 +4920,6 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -5140,7 +5108,7 @@ func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.U}const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM agent_task_queueWHERE chat_finalize_deferred_at IS NOT NULLAND chat_finalize_deferred_at < now() - make_interval(secs => $1::double precision)ORDER BY chat_finalize_deferred_at@@ -5216,7 +5184,6 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -5326,7 +5293,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max}const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM agent_task_queueWHERE runtime_id = $1 AND status IN ('queued', 'dispatched')ORDER BY priority DESC, created_at ASC`@@ -5392,7 +5359,6 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -5406,7 +5372,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp}const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM agent_task_queueWHERE runtime_id = $1 AND status = 'queued'ORDER BY priority DESC, created_at ASC`@@ -5480,7 +5446,6 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -5494,7 +5459,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim}const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM agent_task_queueWHERE runtime_id = ANY($1::uuid[]) AND status = 'queued'ORDER BY priority DESC, created_at ASC`@@ -5570,7 +5535,6 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -5584,7 +5548,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti}const listTasksByIssue = `-- name: ListTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM agent_task_queueWHERE issue_id = $1ORDER BY created_at DESC`@@ -5650,7 +5614,6 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -5725,16 +5688,16 @@ func (q *Queries) ListUserAgentsByRuntimeForUpdate(ctx context.Context, runtimeI}const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.plugin_execution_manifest_id, atq.branch_name FROM agent_task_queue atq+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')UNION ALL-SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.plugin_execution_manifest_id, latest.branch_name FROM agent a+SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name FROM agent aJOIN LATERAL (- SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.plugin_execution_manifest_id, atq.branch_name+ SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_nameFROM agent_task_queue atqWHERE atq.agent_id = a.idAND atq.status IN ('completed', 'failed')@@ -5830,7 +5793,6 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -6081,7 +6043,7 @@ SET status = 'waiting_local_directory',wait_reason = $2,prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)WHERE id = $1 AND status = 'dispatched'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type MarkAgentTaskWaitingLocalDirectoryParams struct {@@ -6154,7 +6116,6 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -6164,7 +6125,7 @@ const markChatFinalizeDeferred = `-- name: MarkChatFinalizeDeferred :oneUPDATE agent_task_queueSET chat_finalize_deferred_at = now()WHERE id = $1-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Arms the deferred chat-finalize marker for a cancelled chat task whose@@ -6224,7 +6185,6 @@ func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -6386,7 +6346,7 @@ WHERE id = (ORDER BY t.created_at DESCLIMIT 1)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type MergeDelegatedFailureCommentIntoPendingTaskParams struct {@@ -6462,7 +6422,6 @@ func (q *Queries) MergeDelegatedFailureCommentIntoPendingTask(ctx context.Contex&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -6472,7 +6431,7 @@ const promoteDeferredChannelIssueTask = `-- name: PromoteDeferredChannelIssueTasUPDATE agent_task_queueSET status = 'queued', fire_at = NULLWHERE id = $1 AND issue_id IS NOT NULL AND status = 'deferred'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Early promotion is idempotent at the service layer: a task already promoted@@ -6532,7 +6491,6 @@ func (q *Queries) PromoteDeferredChannelIssueTask(ctx context.Context, id pgtype&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -6551,7 +6509,7 @@ WHERE runtime_id = $1AND COALESCE(r.last_seen_at, r.updated_at) >=now() - make_interval(secs => $2::double precision))-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type PromoteDueDeferredTasksForRuntimeParams struct {@@ -6620,7 +6578,6 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, arg Pro&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -6646,7 +6603,7 @@ WHERE runtime_id = ANY($1::uuid[])AND COALESCE(r.last_seen_at, r.updated_at) >=now() - make_interval(secs => $2::double precision))-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type PromoteDueDeferredTasksForRuntimesParams struct {@@ -6717,7 +6674,6 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, arg Pr&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -6826,7 +6782,7 @@ WHERE id = (LIMIT 1FOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type ReclaimStaleDispatchedTaskForRuntimeParams struct {@@ -6901,7 +6857,6 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -6929,7 +6884,7 @@ WHERE id IN (LIMIT $5::intFOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type ReclaimStaleDispatchedTasksForRuntimesParams struct {@@ -7014,7 +6969,6 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -7036,7 +6990,7 @@ SET status = 'failed',wait_reason = NULL,prepare_lease_expires_at = NULLWHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Called by the daemon at startup. Atomically fails any dispatched/running/@@ -7106,7 +7060,6 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -7255,7 +7208,7 @@ WHERE id = $1AND status = 'dispatched'AND started_at IS NULLAND dispatched_at = $3-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type RequeueAgentTaskAfterClaimFailureParams struct {@@ -7324,7 +7277,6 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -7514,7 +7466,7 @@ SET status = 'running',wait_reason = NULL,prepare_lease_expires_at = NULLWHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Transitions a task to running. Accepts either 'dispatched' (the normal@@ -7578,7 +7530,6 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, errdiff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 74b20a80a5..b848554e6d 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -289,7 +289,7 @@ SELECT$10,$11WHERE lock_task_owner_rows($1, NULL, $2)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CreateAutopilotTaskParams struct {@@ -392,7 +392,6 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -757,7 +756,7 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD}const getAutopilotTaskByRun = `-- name: GetAutopilotTaskByRun :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name FROM agent_task_queueWHERE autopilot_run_id = $1ORDER BY created_atLIMIT 1@@ -820,7 +819,6 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, errdiff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 24cedb66ef..5703e8d0be 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -354,7 +354,7 @@ SELECT$14,$6::timestamptzWHERE lock_task_owner_rows($1, NULL, $2)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CreateChatTaskParams struct {@@ -451,7 +451,6 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -520,7 +519,7 @@ FROM (WHERE task.id = $1AND pending.max_until IS NOT NULLAND (task.fire_at IS NULL OR task.fire_at < pending.max_until)-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.plugin_execution_manifest_id, task.branch_name+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name`// Closes the enqueue-vs-append race: under READ COMMITTED a media message can@@ -584,7 +583,6 @@ func (q *Queries) DeferChatTaskForSealedPendingMedia(ctx context.Context, taskID&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, err@@ -2436,7 +2434,7 @@ WHERE task.chat_session_id = $1AND message.message_kind != 'channel_command'AND message.channel_media_pending_until > now())-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.plugin_execution_manifest_id, task.branch_name+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name`// Media completion may race with the 3s run batcher. Promote every original@@ -2506,7 +2504,6 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -2846,7 +2843,7 @@ const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :oneUPDATE agent_task_queueSET chat_input_task_id = idWHERE id = $1-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`// Stamps a freshly-created direct-chat task as the owner of its own input batch@@ -2911,7 +2908,6 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,)return i, errdiff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 722150b301..2e2405ec2e 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -168,7 +168,6 @@ type AgentTaskQueue struct {RetiredSessionID pgtype.Text `json:"retired_session_id"`QuickActionsDisabled bool `json:"quick_actions_disabled"`RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`- PluginExecutionManifestID pgtype.UUID `json:"plugin_execution_manifest_id"`BranchName pgtype.Text `json:"branch_name"`}@@ -909,214 +908,39 @@ type PinnedItem struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}-type PluginArtifactFile struct {- ID pgtype.UUID `json:"id"`- ReleaseID pgtype.UUID `json:"release_id"`- Path string `json:"path"`- Digest string `json:"digest"`- SizeBytes int64 `json:"size_bytes"`- Content string `json:"content"`- CreatedAt pgtype.Timestamptz `json:"created_at"`-}--type PluginBinding struct {- ID pgtype.UUID `json:"id"`- InstallationID pgtype.UUID `json:"installation_id"`- ScopeType string `json:"scope_type"`- ScopeID pgtype.UUID `json:"scope_id"`- Enabled bool `json:"enabled"`- BindingRevision int64 `json:"binding_revision"`- CreatedBy pgtype.UUID `json:"created_by"`- CreatedAt pgtype.Timestamptz `json:"created_at"`-}--type PluginCapabilitySnapshot struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- Revision int64 `json:"revision"`- SourceGenerations []byte `json:"source_generations"`- CompilerVersion string `json:"compiler_version"`- SchemaVersion int32 `json:"schema_version"`- SnapshotDigest string `json:"snapshot_digest"`- CompiledEntries []byte `json:"compiled_entries"`- Diagnostics []byte `json:"diagnostics"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- ActivatedAt pgtype.Timestamptz `json:"activated_at"`-}--type PluginContribution struct {- ID pgtype.UUID `json:"id"`- ReleaseID pgtype.UUID `json:"release_id"`- ContributionKey string `json:"contribution_key"`- Type string `json:"type"`- SchemaVersion int32 `json:"schema_version"`- DisplayName string `json:"display_name"`- Description string `json:"description"`- EntryPath string `json:"entry_path"`- EntryDigest string `json:"entry_digest"`- ArtifactDigest string `json:"artifact_digest"`- RequiredDaemonFeatures []byte `json:"required_daemon_features"`- Ordinal int32 `json:"ordinal"`- CreatedAt pgtype.Timestamptz `json:"created_at"`-}--type PluginExecutionManifest struct {- ID pgtype.UUID `json:"id"`- TaskID pgtype.UUID `json:"task_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`- SnapshotID pgtype.UUID `json:"snapshot_id"`- SnapshotRevision int64 `json:"snapshot_revision"`- SnapshotDigest pgtype.Text `json:"snapshot_digest"`- ComposerVersion string `json:"composer_version"`- SchemaVersion int32 `json:"schema_version"`- OrderedContributions []byte `json:"ordered_contributions"`- Diagnostics []byte `json:"diagnostics"`- CreatedAt pgtype.Timestamptz `json:"created_at"`-}--type PluginGrant struct {- ID pgtype.UUID `json:"id"`- InstallationID pgtype.UUID `json:"installation_id"`- Capability string `json:"capability"`- Decision string `json:"decision"`- Limits []byte `json:"limits"`- GrantRevision int64 `json:"grant_revision"`- ApprovedBy pgtype.UUID `json:"approved_by"`- ApprovedAt pgtype.Timestamptz `json:"approved_at"`- RevokedAt pgtype.Timestamptz `json:"revoked_at"`-}--type PluginHealth struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- InstallationID pgtype.UUID `json:"installation_id"`- ScopeType string `json:"scope_type"`- ScopeID pgtype.UUID `json:"scope_id"`- State string `json:"state"`- ReasonCode string `json:"reason_code"`- SafeDetail string `json:"safe_detail"`- ObservedGeneration int64 `json:"observed_generation"`- LastGoodSnapshotID pgtype.UUID `json:"last_good_snapshot_id"`- ObservedAt pgtype.Timestamptz `json:"observed_at"`-}--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"`- OwnerWorkspaceID pgtype.UUID `json:"owner_workspace_id"`-}-type PluginInstallation struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- PluginID pgtype.UUID `json:"plugin_id"`- SourceKind string `json:"source_kind"`- SourceRef string `json:"source_ref"`- DesiredReleaseID pgtype.UUID `json:"desired_release_id"`- ActiveReleaseID pgtype.UUID `json:"active_release_id"`- Enabled bool `json:"enabled"`- DesiredGeneration int64 `json:"desired_generation"`- ActiveGeneration int64 `json:"active_generation"`- LifecycleStatus string `json:"lifecycle_status"`- InstalledBy pgtype.UUID `json:"installed_by"`- InstalledAt pgtype.Timestamptz `json:"installed_at"`- UpdatedBy pgtype.UUID `json:"updated_by"`- UpdatedAt pgtype.Timestamptz `json:"updated_at"`- DisabledAt pgtype.Timestamptz `json:"disabled_at"`- UninstalledAt pgtype.Timestamptz `json:"uninstalled_at"`-}--type PluginInstallationConfig struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- InstallationID pgtype.UUID `json:"installation_id"`- ContributionID pgtype.UUID `json:"contribution_id"`- Revision int64 `json:"revision"`- Endpoint string `json:"endpoint"`- PublicConfig []byte `json:"public_config"`- AuthType string `json:"auth_type"`- AuthHeader string `json:"auth_header"`- SecretRef pgtype.UUID `json:"secret_ref"`- ApprovedTools []byte `json:"approved_tools"`- SchemaDigest pgtype.Text `json:"schema_digest"`- FailurePolicy string `json:"failure_policy"`- ReviewedBy pgtype.UUID `json:"reviewed_by"`- ReviewedAt pgtype.Timestamptz `json:"reviewed_at"`- CreatedBy pgtype.UUID `json:"created_by"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- DiscoveredTools []byte `json:"discovered_tools"`- DiscoveredSchemaDigest pgtype.Text `json:"discovered_schema_digest"`-}--type PluginRelease struct {- ID pgtype.UUID `json:"id"`- PluginID pgtype.UUID `json:"plugin_id"`- Version string `json:"version"`- Manifest []byte `json:"manifest"`- ManifestDigest string `json:"manifest_digest"`- SourceKind string `json:"source_kind"`- SourceRef string `json:"source_ref"`- ArchiveDigest string `json:"archive_digest"`- ArtifactRef string `json:"artifact_ref"`- ArtifactDigest string `json:"artifact_digest"`- ArtifactSize int64 `json:"artifact_size"`- Signature []byte `json:"signature"`- SignatureKeyID pgtype.Text `json:"signature_key_id"`- RevocationStatus string `json:"revocation_status"`- RevokedAt pgtype.Timestamptz `json:"revoked_at"`- RevocationReason pgtype.Text `json:"revocation_reason"`- PublishedAt pgtype.Timestamptz `json:"published_at"`-}--type PluginRemoteMcpOauthState struct {- StateHash []byte `json:"state_hash"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- InstallationID pgtype.UUID `json:"installation_id"`- ContributionID pgtype.UUID `json:"contribution_id"`- ActorID pgtype.UUID `json:"actor_id"`- Endpoint string `json:"endpoint"`- PublicConfig []byte `json:"public_config"`- FailurePolicy string `json:"failure_policy"`- AuthorizationEndpoint string `json:"authorization_endpoint"`- TokenEndpoint string `json:"token_endpoint"`- ClientID string `json:"client_id"`- Scope string `json:"scope"`- RedirectUri string `json:"redirect_uri"`- ReturnTo string `json:"return_to"`- SecretCiphertext []byte `json:"secret_ciphertext"`- ExpiresAt pgtype.Timestamptz `json:"expires_at"`- ConsumedAt pgtype.Timestamptz `json:"consumed_at"`- CreatedAt pgtype.Timestamptz `json:"created_at"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PluginKey string `json:"plugin_key"`+ SourceUrl string `json:"source_url"`+ Version string `json:"version"`+ Manifest []byte `json:"manifest"`+ GrantedScopes []byte `json:"granted_scopes"`+ Config []byte `json:"config"`+ Enabled bool `json:"enabled"`+ InstalledBy pgtype.UUID `json:"installed_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`}-type PluginRemoteMcpSecret struct {+type PluginSecret struct {ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`InstallationID pgtype.UUID `json:"installation_id"`- ContributionID pgtype.UUID `json:"contribution_id"`- Version int64 `json:"version"`+ Key string `json:"key"`Ciphertext []byte `json:"ciphertext"`- Hint string `json:"hint"`- Status string `json:"status"`- CreatedBy pgtype.UUID `json:"created_by"`CreatedAt pgtype.Timestamptz `json:"created_at"`- RevokedAt pgtype.Timestamptz `json:"revoked_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`}-type PluginWorkspaceCapabilityState struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- NextRevision int64 `json:"next_revision"`- ActiveSnapshotID pgtype.UUID `json:"active_snapshot_id"`- ActiveRevision int64 `json:"active_revision"`- UpdatedAt pgtype.Timestamptz `json:"updated_at"`+type PluginStorage struct {+ ID pgtype.UUID `json:"id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`+ Key string `json:"key"`+ Value string `json:"value"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`}type Project struct {diff --git a/server/pkg/db/generated/plugin.sql.go b/server/pkg/db/generated/plugin.sql.goindex 2b9467a0ee..74b3d976ee 100644--- a/server/pkg/db/generated/plugin.sql.go+++ b/server/pkg/db/generated/plugin.sql.go@@ -11,2177 +11,319 @@ import ("github.com/jackc/pgx/v5/pgtype")-const activatePluginInstallations = `-- name: ActivatePluginInstallations :many-UPDATE plugin_installation-SET active_release_id = desired_release_id,- active_generation = desired_generation,- lifecycle_status = CASE WHEN enabled THEN 'active' ELSE 'installed' END,- updated_at = now()-WHERE workspace_id = $1- AND uninstalled_at IS NULL-RETURNING 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-`--func (q *Queries) ActivatePluginInstallations(ctx context.Context, workspaceID pgtype.UUID) ([]PluginInstallation, error) {- rows, err := q.db.Query(ctx, activatePluginInstallations, 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 activatePluginWorkspaceCapabilitySnapshot = `-- name: ActivatePluginWorkspaceCapabilitySnapshot :one-UPDATE plugin_workspace_capability_state-SET active_snapshot_id = $1,- active_revision = $2,- next_revision = $3,- updated_at = now()-WHERE workspace_id = $4- AND next_revision = $2-RETURNING workspace_id, next_revision, active_snapshot_id, active_revision, updated_at+const createPluginInstallation = `-- name: CreatePluginInstallation :one+INSERT INTO plugin_installation (+ workspace_id, plugin_key, source_url, version, manifest, granted_scopes, installed_by+) VALUES ($1, $2, $3, $4, $5, $6, $7)+RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at`-type ActivatePluginWorkspaceCapabilitySnapshotParams struct {- ActiveSnapshotID pgtype.UUID `json:"active_snapshot_id"`- ActiveRevision int64 `json:"active_revision"`- NextRevision int64 `json:"next_revision"`- WorkspaceID pgtype.UUID `json:"workspace_id"`+type CreatePluginInstallationParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PluginKey string `json:"plugin_key"`+ SourceUrl string `json:"source_url"`+ Version string `json:"version"`+ Manifest []byte `json:"manifest"`+ GrantedScopes []byte `json:"granted_scopes"`+ InstalledBy pgtype.UUID `json:"installed_by"`}-func (q *Queries) ActivatePluginWorkspaceCapabilitySnapshot(ctx context.Context, arg ActivatePluginWorkspaceCapabilitySnapshotParams) (PluginWorkspaceCapabilityState, error) {- row := q.db.QueryRow(ctx, activatePluginWorkspaceCapabilitySnapshot,- arg.ActiveSnapshotID,- arg.ActiveRevision,- arg.NextRevision,+func (q *Queries) CreatePluginInstallation(ctx context.Context, arg CreatePluginInstallationParams) (PluginInstallation, error) {+ row := q.db.QueryRow(ctx, createPluginInstallation,arg.WorkspaceID,+ arg.PluginKey,+ arg.SourceUrl,+ arg.Version,+ arg.Manifest,+ arg.GrantedScopes,+ arg.InstalledBy,)- var i PluginWorkspaceCapabilityState- err := row.Scan(- &i.WorkspaceID,- &i.NextRevision,- &i.ActiveSnapshotID,- &i.ActiveRevision,- &i.UpdatedAt,- )- return i, err-}--const claimPluginRemoteMCPOAuthState = `-- name: ClaimPluginRemoteMCPOAuthState :one-UPDATE plugin_remote_mcp_oauth_state-SET consumed_at = now()-WHERE state_hash = $1- AND consumed_at IS NULL- AND expires_at > now()-RETURNING state_hash, workspace_id, installation_id, contribution_id, actor_id, endpoint, public_config, failure_policy, authorization_endpoint, token_endpoint, client_id, scope, redirect_uri, return_to, secret_ciphertext, expires_at, consumed_at, created_at-`--func (q *Queries) ClaimPluginRemoteMCPOAuthState(ctx context.Context, stateHash []byte) (PluginRemoteMcpOauthState, error) {- row := q.db.QueryRow(ctx, claimPluginRemoteMCPOAuthState, stateHash)- var i PluginRemoteMcpOauthState+ var i PluginInstallationerr := row.Scan(- &i.StateHash,+ &i.ID,&i.WorkspaceID,- &i.InstallationID,- &i.ContributionID,- &i.ActorID,- &i.Endpoint,- &i.PublicConfig,- &i.FailurePolicy,- &i.AuthorizationEndpoint,- &i.TokenEndpoint,- &i.ClientID,- &i.Scope,- &i.RedirectUri,- &i.ReturnTo,- &i.SecretCiphertext,- &i.ExpiresAt,- &i.ConsumedAt,+ &i.PluginKey,+ &i.SourceUrl,+ &i.Version,+ &i.Manifest,+ &i.GrantedScopes,+ &i.Config,+ &i.Enabled,+ &i.InstalledBy,&i.CreatedAt,+ &i.UpdatedAt,)return i, err}-const createPluginArtifactFile = `-- name: CreatePluginArtifactFile :one-WITH parent AS MATERIALIZED (- SELECT plugin_release.id- FROM plugin_release- WHERE plugin_release.id = $5- FOR KEY SHARE-)-INSERT INTO plugin_artifact_file (- release_id, path, digest, size_bytes, content-)-SELECT parent.id, $1, $2, $3, $4-FROM parent-RETURNING id, release_id, path, digest, size_bytes, content, created_at+const deletePluginInstallation = `-- name: DeletePluginInstallation :exec+DELETE FROM plugin_installation WHERE id = $1`-type CreatePluginArtifactFileParams struct {- Path string `json:"path"`- Digest string `json:"digest"`- SizeBytes int64 `json:"size_bytes"`- Content string `json:"content"`- ReleaseID pgtype.UUID `json:"release_id"`-}--func (q *Queries) CreatePluginArtifactFile(ctx context.Context, arg CreatePluginArtifactFileParams) (PluginArtifactFile, error) {- row := q.db.QueryRow(ctx, createPluginArtifactFile,- arg.Path,- arg.Digest,- arg.SizeBytes,- arg.Content,- arg.ReleaseID,- )- var i PluginArtifactFile- err := row.Scan(- &i.ID,- &i.ReleaseID,- &i.Path,- &i.Digest,- &i.SizeBytes,- &i.Content,- &i.CreatedAt,- )- return i, err+func (q *Queries) DeletePluginInstallation(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deletePluginInstallation, id)+ return err}-const createPluginBindingRevision = `-- name: CreatePluginBindingRevision :one-WITH workspace_scope AS MATERIALIZED (- SELECT i.id- FROM plugin_installation i- JOIN workspace w ON w.id = i.workspace_id- WHERE $1::text = 'workspace'- AND i.id = $5- AND i.workspace_id = $6- AND $2::uuid = i.workspace_id- AND i.uninstalled_at IS NULL- FOR UPDATE OF i- FOR KEY SHARE OF w-),-agent_scope AS MATERIALIZED (- SELECT i.id- FROM plugin_installation i- JOIN workspace w ON w.id = i.workspace_id- JOIN agent a ON a.id = $2 AND a.workspace_id = i.workspace_id- WHERE $1::text = 'agent'- AND i.id = $5- AND i.workspace_id = $6- AND i.uninstalled_at IS NULL- FOR UPDATE OF i- FOR KEY SHARE OF w, a-),-target AS MATERIALIZED (- SELECT id FROM workspace_scope- UNION ALL- SELECT id FROM agent_scope-),-next_revision AS (- SELECT COALESCE(MAX(b.binding_revision), 0) + 1 AS revision- FROM plugin_binding b- JOIN target ON target.id = b.installation_id- WHERE b.scope_type = $1 AND b.scope_id = $2-)-INSERT INTO plugin_binding (- installation_id, scope_type, scope_id, enabled,- binding_revision, created_by-)-SELECT- target.id, $1, $2, $3,- next_revision.revision, $4-FROM target CROSS JOIN next_revision-RETURNING id, installation_id, scope_type, scope_id, enabled, binding_revision, created_by, created_at+const deletePluginSecret = `-- name: DeletePluginSecret :execrows+DELETE FROM plugin_secret WHERE installation_id = $1 AND key = $2`-type CreatePluginBindingRevisionParams struct {- ScopeType string `json:"scope_type"`- ScopeID pgtype.UUID `json:"scope_id"`- Enabled bool `json:"enabled"`- CreatedBy pgtype.UUID `json:"created_by"`+type DeletePluginSecretParams struct {InstallationID pgtype.UUID `json:"installation_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`+ Key string `json:"key"`}-func (q *Queries) CreatePluginBindingRevision(ctx context.Context, arg CreatePluginBindingRevisionParams) (PluginBinding, error) {- row := q.db.QueryRow(ctx, createPluginBindingRevision,- arg.ScopeType,- arg.ScopeID,- arg.Enabled,- arg.CreatedBy,- arg.InstallationID,- arg.WorkspaceID,- )- var i PluginBinding- err := row.Scan(- &i.ID,- &i.InstallationID,- &i.ScopeType,- &i.ScopeID,- &i.Enabled,- &i.BindingRevision,- &i.CreatedBy,- &i.CreatedAt,- )- return i, err+func (q *Queries) DeletePluginSecret(ctx context.Context, arg DeletePluginSecretParams) (int64, error) {+ result, err := q.db.Exec(ctx, deletePluginSecret, arg.InstallationID, arg.Key)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil}-const createPluginCapabilitySnapshot = `-- name: CreatePluginCapabilitySnapshot :one-INSERT INTO plugin_capability_snapshot (- workspace_id, revision, source_generations,- compiler_version, schema_version, snapshot_digest,- compiled_entries, diagnostics-) VALUES (- $1, $2, $3,- $4, $5, $6,- $7, $8-)-RETURNING id, workspace_id, revision, source_generations, compiler_version, schema_version, snapshot_digest, compiled_entries, diagnostics, created_at, activated_at+const deletePluginSecretsByInstallation = `-- name: DeletePluginSecretsByInstallation :exec+DELETE FROM plugin_secret WHERE installation_id = $1`-type CreatePluginCapabilitySnapshotParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- Revision int64 `json:"revision"`- SourceGenerations []byte `json:"source_generations"`- CompilerVersion string `json:"compiler_version"`- SchemaVersion int32 `json:"schema_version"`- SnapshotDigest string `json:"snapshot_digest"`- CompiledEntries []byte `json:"compiled_entries"`- Diagnostics []byte `json:"diagnostics"`-}--func (q *Queries) CreatePluginCapabilitySnapshot(ctx context.Context, arg CreatePluginCapabilitySnapshotParams) (PluginCapabilitySnapshot, error) {- row := q.db.QueryRow(ctx, createPluginCapabilitySnapshot,- arg.WorkspaceID,- arg.Revision,- arg.SourceGenerations,- arg.CompilerVersion,- arg.SchemaVersion,- arg.SnapshotDigest,- arg.CompiledEntries,- arg.Diagnostics,- )- var i PluginCapabilitySnapshot- err := row.Scan(- &i.ID,- &i.WorkspaceID,- &i.Revision,- &i.SourceGenerations,- &i.CompilerVersion,- &i.SchemaVersion,- &i.SnapshotDigest,- &i.CompiledEntries,- &i.Diagnostics,- &i.CreatedAt,- &i.ActivatedAt,- )- return i, err+func (q *Queries) DeletePluginSecretsByInstallation(ctx context.Context, installationID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deletePluginSecretsByInstallation, installationID)+ return err}-const createPluginContribution = `-- name: CreatePluginContribution :one-WITH parent AS MATERIALIZED (- SELECT plugin_release.id, plugin_release.artifact_digest- FROM plugin_release- WHERE plugin_release.id = $10 AND plugin_release.revocation_status = 'active'- FOR KEY SHARE-)-INSERT INTO plugin_contribution (- release_id, contribution_key, type, schema_version,- display_name, description, entry_path, entry_digest,- artifact_digest, required_daemon_features, ordinal-)-SELECT- parent.id, $1, $2, $3,- $4, $5, $6, $7,- parent.artifact_digest, $8, $9-FROM parent-RETURNING id, release_id, contribution_key, type, schema_version, display_name, description, entry_path, entry_digest, artifact_digest, required_daemon_features, ordinal, created_at+const deletePluginStorageByInstallation = `-- name: DeletePluginStorageByInstallation :exec+DELETE FROM plugin_storage WHERE installation_id = $1`-type CreatePluginContributionParams struct {- ContributionKey string `json:"contribution_key"`- Type string `json:"type"`- SchemaVersion int32 `json:"schema_version"`- DisplayName string `json:"display_name"`- Description string `json:"description"`- EntryPath string `json:"entry_path"`- EntryDigest string `json:"entry_digest"`- RequiredDaemonFeatures []byte `json:"required_daemon_features"`- Ordinal int32 `json:"ordinal"`- ReleaseID pgtype.UUID `json:"release_id"`-}--func (q *Queries) CreatePluginContribution(ctx context.Context, arg CreatePluginContributionParams) (PluginContribution, error) {- row := q.db.QueryRow(ctx, createPluginContribution,- arg.ContributionKey,- arg.Type,- arg.SchemaVersion,- arg.DisplayName,- arg.Description,- arg.EntryPath,- arg.EntryDigest,- arg.RequiredDaemonFeatures,- arg.Ordinal,- arg.ReleaseID,- )- var i PluginContribution- err := row.Scan(- &i.ID,- &i.ReleaseID,- &i.ContributionKey,- &i.Type,- &i.SchemaVersion,- &i.DisplayName,- &i.Description,- &i.EntryPath,- &i.EntryDigest,- &i.ArtifactDigest,- &i.RequiredDaemonFeatures,- &i.Ordinal,- &i.CreatedAt,- )- return i, err+func (q *Queries) DeletePluginStorageByInstallation(ctx context.Context, installationID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deletePluginStorageByInstallation, installationID)+ return err}-const createPluginGrantRevision = `-- name: CreatePluginGrantRevision :one-WITH target AS MATERIALIZED (- SELECT i.id- FROM plugin_installation i- JOIN workspace w ON w.id = i.workspace_id- WHERE i.id = $5- AND i.workspace_id = $6- AND i.uninstalled_at IS NULL- FOR UPDATE OF i- FOR KEY SHARE OF w-),-next_revision AS (- SELECT COALESCE(MAX(g.grant_revision), 0) + 1 AS revision- FROM plugin_grant g- JOIN target ON target.id = g.installation_id- WHERE g.capability = $1-)-INSERT INTO plugin_grant (- installation_id, capability, decision, limits,- grant_revision, approved_by, revoked_at-)-SELECT- target.id, $1, $2, $3,- next_revision.revision, $4,- CASE WHEN $2::text = 'denied' THEN now() ELSE NULL END-FROM target CROSS JOIN next_revision-RETURNING id, installation_id, capability, decision, limits, grant_revision, approved_by, approved_at, revoked_at+const deletePluginStorageValue = `-- name: DeletePluginStorageValue :execrows+DELETE FROM plugin_storage+WHERE installation_id = $1 AND scope_type = $2 AND scope_id = $3 AND key = $4`-type CreatePluginGrantRevisionParams struct {- Capability string `json:"capability"`- Decision string `json:"decision"`- Limits []byte `json:"limits"`- ApprovedBy pgtype.UUID `json:"approved_by"`+type DeletePluginStorageValueParams struct {InstallationID pgtype.UUID `json:"installation_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`-}--func (q *Queries) CreatePluginGrantRevision(ctx context.Context, arg CreatePluginGrantRevisionParams) (PluginGrant, error) {- row := q.db.QueryRow(ctx, createPluginGrantRevision,- arg.Capability,- arg.Decision,- arg.Limits,- arg.ApprovedBy,- arg.InstallationID,- arg.WorkspaceID,- )- var i PluginGrant- err := row.Scan(- &i.ID,- &i.InstallationID,- &i.Capability,- &i.Decision,- &i.Limits,- &i.GrantRevision,- &i.ApprovedBy,- &i.ApprovedAt,- &i.RevokedAt,- )- return i, err-}--const createPluginHealth = `-- name: CreatePluginHealth :one-INSERT INTO plugin_health (- workspace_id, installation_id, scope_type, scope_id,- state, reason_code, safe_detail,- observed_generation, last_good_snapshot_id-) VALUES (- $1, $2, $3, $4,- $5, $6, $7,- $8, $9-)-RETURNING id, workspace_id, installation_id, scope_type, scope_id, state, reason_code, safe_detail, observed_generation, last_good_snapshot_id, observed_at-`--type CreatePluginHealthParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- InstallationID pgtype.UUID `json:"installation_id"`- ScopeType string `json:"scope_type"`- ScopeID pgtype.UUID `json:"scope_id"`- State string `json:"state"`- ReasonCode string `json:"reason_code"`- SafeDetail string `json:"safe_detail"`- ObservedGeneration int64 `json:"observed_generation"`- LastGoodSnapshotID pgtype.UUID `json:"last_good_snapshot_id"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`+ Key string `json:"key"`}-func (q *Queries) CreatePluginHealth(ctx context.Context, arg CreatePluginHealthParams) (PluginHealth, error) {- row := q.db.QueryRow(ctx, createPluginHealth,- arg.WorkspaceID,+func (q *Queries) DeletePluginStorageValue(ctx context.Context, arg DeletePluginStorageValueParams) (int64, error) {+ result, err := q.db.Exec(ctx, deletePluginStorageValue,arg.InstallationID,arg.ScopeType,arg.ScopeID,- arg.State,- arg.ReasonCode,- arg.SafeDetail,- arg.ObservedGeneration,- arg.LastGoodSnapshotID,- )- 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 createPluginIdentity = `-- name: CreatePluginIdentity :one-INSERT INTO plugin_identity (- plugin_key, display_name, publisher_id, publisher_type, trust_tier,- owner_workspace_id-) VALUES (- $1, $2, $3, $4, $5,- $6-)-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"`- OwnerWorkspaceID pgtype.UUID `json:"owner_workspace_id"`-}--func (q *Queries) CreatePluginIdentity(ctx context.Context, arg CreatePluginIdentityParams) (PluginIdentity, error) {- row := q.db.QueryRow(ctx, createPluginIdentity,- arg.PluginKey,- arg.DisplayName,- arg.PublisherID,- arg.PublisherType,- arg.TrustTier,- arg.OwnerWorkspaceID,- )- var i PluginIdentity- err := row.Scan(- &i.ID,- &i.PluginKey,- &i.DisplayName,- &i.PublisherID,- &i.PublisherType,- &i.TrustTier,- &i.CreatedAt,- &i.RetiredAt,- &i.OwnerWorkspaceID,+ arg.Key,)- return i, err+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil}-const createPluginInstallation = `-- name: CreatePluginInstallation :one-WITH parents AS MATERIALIZED (- SELECT w.id AS workspace_id, p.id AS plugin_id, r.id AS release_id,- r.source_kind, r.source_ref- FROM workspace w- JOIN plugin_identity p ON p.id = $2 AND p.retired_at IS NULL- JOIN plugin_release r ON r.id = $3- AND r.plugin_id = p.id- AND r.revocation_status = 'active'- WHERE w.id = $4- FOR KEY SHARE OF w, p, r-)-INSERT INTO plugin_installation (- workspace_id, plugin_id, source_kind, source_ref,- desired_release_id, enabled, lifecycle_status,- installed_by, updated_by-)-SELECT- parents.workspace_id, parents.plugin_id, parents.source_kind, parents.source_ref,- parents.release_id, FALSE, 'installed',- $1, $1-FROM parents-RETURNING 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+const getPluginInstallation = `-- name: GetPluginInstallation :one+SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at FROM plugin_installation WHERE id = $1`-type CreatePluginInstallationParams struct {- InstalledBy pgtype.UUID `json:"installed_by"`- PluginID pgtype.UUID `json:"plugin_id"`- ReleaseID pgtype.UUID `json:"release_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`-}--func (q *Queries) CreatePluginInstallation(ctx context.Context, arg CreatePluginInstallationParams) (PluginInstallation, error) {- row := q.db.QueryRow(ctx, createPluginInstallation,- arg.InstalledBy,- arg.PluginID,- arg.ReleaseID,- arg.WorkspaceID,- )+func (q *Queries) GetPluginInstallation(ctx context.Context, id pgtype.UUID) (PluginInstallation, error) {+ row := q.db.QueryRow(ctx, getPluginInstallation, id)var i PluginInstallationerr := row.Scan(&i.ID,&i.WorkspaceID,- &i.PluginID,- &i.SourceKind,- &i.SourceRef,- &i.DesiredReleaseID,- &i.ActiveReleaseID,+ &i.PluginKey,+ &i.SourceUrl,+ &i.Version,+ &i.Manifest,+ &i.GrantedScopes,+ &i.Config,&i.Enabled,- &i.DesiredGeneration,- &i.ActiveGeneration,- &i.LifecycleStatus,&i.InstalledBy,- &i.InstalledAt,- &i.UpdatedBy,+ &i.CreatedAt,&i.UpdatedAt,- &i.DisabledAt,- &i.UninstalledAt,)return i, err}-const createPluginInstallationConfig = `-- name: CreatePluginInstallationConfig :one-WITH parent AS MATERIALIZED (- SELECT installation.id, contribution.id AS contribution_id- FROM plugin_installation installation- JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = installation.plugin_id- AND release.revocation_status = 'active'- JOIN plugin_contribution contribution- ON contribution.release_id = release.id- AND contribution.id = $14- AND contribution.type = 'tool.remote-mcp.v1'- WHERE installation.id = $15- AND installation.workspace_id = $1- AND installation.uninstalled_at IS NULL- AND (- ($4::text = 'none' AND $6::uuid IS NULL)- OR EXISTS (- SELECT 1 FROM plugin_remote_mcp_secret secret- WHERE secret.id = $6::uuid- AND secret.workspace_id = $1- AND secret.installation_id = installation.id- AND secret.contribution_id = contribution.id- AND secret.status = 'active'- )- )- FOR UPDATE OF installation- FOR KEY SHARE OF release, contribution-), next_revision AS (- SELECT COALESCE(MAX(revision), 0) + 1 AS revision- FROM plugin_installation_config- WHERE installation_id = $15- AND contribution_id = $14-)-INSERT INTO plugin_installation_config (- workspace_id, installation_id, contribution_id, revision,- endpoint, public_config, auth_type, auth_header, secret_ref,- discovered_tools, discovered_schema_digest,- approved_tools, schema_digest, failure_policy,- reviewed_by, reviewed_at, created_by-)-SELECT- $1, parent.id, parent.contribution_id, next_revision.revision,- $2, $3, $4, $5, $6,- $7, $8,- $9, $10, $11,- $12,- CASE WHEN $12::uuid IS NULL THEN NULL ELSE now() END,- $13-FROM parent, next_revision-RETURNING id, workspace_id, installation_id, contribution_id, revision, endpoint, public_config, auth_type, auth_header, secret_ref, approved_tools, schema_digest, failure_policy, reviewed_by, reviewed_at, created_by, created_at, discovered_tools, discovered_schema_digest+const getPluginSecret = `-- name: GetPluginSecret :one+SELECT id, installation_id, key, ciphertext, created_at, updated_at FROM plugin_secret+WHERE installation_id = $1 AND key = $2`-type CreatePluginInstallationConfigParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- Endpoint string `json:"endpoint"`- PublicConfig []byte `json:"public_config"`- AuthType string `json:"auth_type"`- AuthHeader string `json:"auth_header"`- SecretRef pgtype.UUID `json:"secret_ref"`- DiscoveredTools []byte `json:"discovered_tools"`- DiscoveredSchemaDigest pgtype.Text `json:"discovered_schema_digest"`- ApprovedTools []byte `json:"approved_tools"`- SchemaDigest pgtype.Text `json:"schema_digest"`- FailurePolicy string `json:"failure_policy"`- ReviewedBy pgtype.UUID `json:"reviewed_by"`- CreatedBy pgtype.UUID `json:"created_by"`- ContributionID pgtype.UUID `json:"contribution_id"`- InstallationID pgtype.UUID `json:"installation_id"`+type GetPluginSecretParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ Key string `json:"key"`}-func (q *Queries) CreatePluginInstallationConfig(ctx context.Context, arg CreatePluginInstallationConfigParams) (PluginInstallationConfig, error) {- row := q.db.QueryRow(ctx, createPluginInstallationConfig,- arg.WorkspaceID,- arg.Endpoint,- arg.PublicConfig,- arg.AuthType,- arg.AuthHeader,- arg.SecretRef,- arg.DiscoveredTools,- arg.DiscoveredSchemaDigest,- arg.ApprovedTools,- arg.SchemaDigest,- arg.FailurePolicy,- arg.ReviewedBy,- arg.CreatedBy,- arg.ContributionID,- arg.InstallationID,- )- var i PluginInstallationConfig+func (q *Queries) GetPluginSecret(ctx context.Context, arg GetPluginSecretParams) (PluginSecret, error) {+ row := q.db.QueryRow(ctx, getPluginSecret, arg.InstallationID, arg.Key)+ var i PluginSecreterr := row.Scan(&i.ID,- &i.WorkspaceID,&i.InstallationID,- &i.ContributionID,- &i.Revision,- &i.Endpoint,- &i.PublicConfig,- &i.AuthType,- &i.AuthHeader,- &i.SecretRef,- &i.ApprovedTools,- &i.SchemaDigest,- &i.FailurePolicy,- &i.ReviewedBy,- &i.ReviewedAt,- &i.CreatedBy,+ &i.Key,+ &i.Ciphertext,&i.CreatedAt,- &i.DiscoveredTools,- &i.DiscoveredSchemaDigest,+ &i.UpdatedAt,)return i, err}-const createPluginRelease = `-- name: CreatePluginRelease :one-WITH parent AS MATERIALIZED (- SELECT plugin_identity.id- FROM plugin_identity- WHERE plugin_identity.id = $12 AND plugin_identity.retired_at IS NULL- FOR KEY SHARE-)-INSERT INTO plugin_release (- plugin_id, version, manifest, manifest_digest,- source_kind, source_ref,- archive_digest, artifact_ref, artifact_digest, artifact_size,- signature, signature_key_id-)-SELECT- parent.id, $1, $2, $3,- $4, $5,- $6, $7, $8, $9,- $10, $11-FROM parent-RETURNING 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+const getPluginStorageUsage = `-- name: GetPluginStorageUsage :one+SELECT COUNT(*)::bigint AS key_count,+ COALESCE(SUM(octet_length(value)), 0)::bigint AS total_bytes+FROM plugin_storage+WHERE installation_id = $1 AND scope_type = $2 AND scope_id = $3 AND key <> $4`-type CreatePluginReleaseParams struct {- Version string `json:"version"`- Manifest []byte `json:"manifest"`- ManifestDigest string `json:"manifest_digest"`- SourceKind string `json:"source_kind"`- SourceRef string `json:"source_ref"`- ArchiveDigest string `json:"archive_digest"`- ArtifactRef string `json:"artifact_ref"`- ArtifactDigest string `json:"artifact_digest"`- ArtifactSize int64 `json:"artifact_size"`- Signature []byte `json:"signature"`- SignatureKeyID pgtype.Text `json:"signature_key_id"`- PluginID pgtype.UUID `json:"plugin_id"`-}--func (q *Queries) CreatePluginRelease(ctx context.Context, arg CreatePluginReleaseParams) (PluginRelease, error) {- row := q.db.QueryRow(ctx, createPluginRelease,- arg.Version,- arg.Manifest,- arg.ManifestDigest,- arg.SourceKind,- arg.SourceRef,- arg.ArchiveDigest,- arg.ArtifactRef,- arg.ArtifactDigest,- arg.ArtifactSize,- arg.Signature,- arg.SignatureKeyID,- arg.PluginID,- )- 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+type GetPluginStorageUsageParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`+ Key string `json:"key"`}-const createPluginRemoteMCPOAuthState = `-- name: CreatePluginRemoteMCPOAuthState :one-INSERT INTO plugin_remote_mcp_oauth_state (- state_hash, workspace_id, installation_id, contribution_id, actor_id,- endpoint, public_config, failure_policy,- authorization_endpoint, token_endpoint, client_id, scope,- redirect_uri, return_to, secret_ciphertext, expires_at-) VALUES (- $1, $2, $3, $4, $5,- $6, $7, $8,- $9, $10, $11, $12,- $13, $14, $15, $16-)-RETURNING state_hash, workspace_id, installation_id, contribution_id, actor_id, endpoint, public_config, failure_policy, authorization_endpoint, token_endpoint, client_id, scope, redirect_uri, return_to, secret_ciphertext, expires_at, consumed_at, created_at-`--type CreatePluginRemoteMCPOAuthStateParams struct {- StateHash []byte `json:"state_hash"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- InstallationID pgtype.UUID `json:"installation_id"`- ContributionID pgtype.UUID `json:"contribution_id"`- ActorID pgtype.UUID `json:"actor_id"`- Endpoint string `json:"endpoint"`- PublicConfig []byte `json:"public_config"`- FailurePolicy string `json:"failure_policy"`- AuthorizationEndpoint string `json:"authorization_endpoint"`- TokenEndpoint string `json:"token_endpoint"`- ClientID string `json:"client_id"`- Scope string `json:"scope"`- RedirectUri string `json:"redirect_uri"`- ReturnTo string `json:"return_to"`- SecretCiphertext []byte `json:"secret_ciphertext"`- ExpiresAt pgtype.Timestamptz `json:"expires_at"`+type GetPluginStorageUsageRow struct {+ KeyCount int64 `json:"key_count"`+ TotalBytes int64 `json:"total_bytes"`}-func (q *Queries) CreatePluginRemoteMCPOAuthState(ctx context.Context, arg CreatePluginRemoteMCPOAuthStateParams) (PluginRemoteMcpOauthState, error) {- row := q.db.QueryRow(ctx, createPluginRemoteMCPOAuthState,- arg.StateHash,- arg.WorkspaceID,+// Quota accounting for one (installation, scope) pair. The candidate key is+// excluded so overwriting an existing key is measured as a replacement rather+// than an addition. octet_length, not char_length: the service compares these+// against byte budgets, and a UTF-8 character is up to 4 bytes.+func (q *Queries) GetPluginStorageUsage(ctx context.Context, arg GetPluginStorageUsageParams) (GetPluginStorageUsageRow, error) {+ row := q.db.QueryRow(ctx, getPluginStorageUsage,arg.InstallationID,- arg.ContributionID,- arg.ActorID,- arg.Endpoint,- arg.PublicConfig,- arg.FailurePolicy,- arg.AuthorizationEndpoint,- arg.TokenEndpoint,- arg.ClientID,- arg.Scope,- arg.RedirectUri,- arg.ReturnTo,- arg.SecretCiphertext,- arg.ExpiresAt,- )- var i PluginRemoteMcpOauthState- err := row.Scan(- &i.StateHash,- &i.WorkspaceID,- &i.InstallationID,- &i.ContributionID,- &i.ActorID,- &i.Endpoint,- &i.PublicConfig,- &i.FailurePolicy,- &i.AuthorizationEndpoint,- &i.TokenEndpoint,- &i.ClientID,- &i.Scope,- &i.RedirectUri,- &i.ReturnTo,- &i.SecretCiphertext,- &i.ExpiresAt,- &i.ConsumedAt,- &i.CreatedAt,+ arg.ScopeType,+ arg.ScopeID,+ arg.Key,)+ var i GetPluginStorageUsageRow+ err := row.Scan(&i.KeyCount, &i.TotalBytes)return i, err}-const createPluginRemoteMCPSecret = `-- name: CreatePluginRemoteMCPSecret :one-WITH parent AS MATERIALIZED (- SELECT installation.id, contribution.id AS contribution_id- FROM plugin_installation installation- JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = installation.plugin_id- AND release.revocation_status = 'active'- JOIN plugin_contribution contribution- ON contribution.release_id = release.id- AND contribution.id = $5- AND contribution.type = 'tool.remote-mcp.v1'- WHERE installation.id = $6- AND installation.workspace_id = $1- AND installation.uninstalled_at IS NULL- FOR UPDATE OF installation- FOR KEY SHARE OF release, contribution-), next_version AS (- SELECT COALESCE(MAX(version), 0) + 1 AS version- FROM plugin_remote_mcp_secret- WHERE installation_id = $6- AND contribution_id = $5-)-INSERT INTO plugin_remote_mcp_secret (- workspace_id, installation_id, contribution_id, version,- ciphertext, hint, created_by-)-SELECT- $1, parent.id, parent.contribution_id, next_version.version,- $2, $3, $4-FROM parent, next_version-RETURNING id, workspace_id, installation_id, contribution_id, version, ciphertext, hint, status, created_by, created_at, revoked_at+const getPluginStorageValue = `-- name: GetPluginStorageValue :one+SELECT id, installation_id, scope_type, scope_id, key, value, created_at, updated_at FROM plugin_storage+WHERE installation_id = $1 AND scope_type = $2 AND scope_id = $3 AND key = $4`-type CreatePluginRemoteMCPSecretParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- Ciphertext []byte `json:"ciphertext"`- Hint string `json:"hint"`- CreatedBy pgtype.UUID `json:"created_by"`- ContributionID pgtype.UUID `json:"contribution_id"`+type GetPluginStorageValueParams struct {InstallationID pgtype.UUID `json:"installation_id"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`+ Key string `json:"key"`}-func (q *Queries) CreatePluginRemoteMCPSecret(ctx context.Context, arg CreatePluginRemoteMCPSecretParams) (PluginRemoteMcpSecret, error) {- row := q.db.QueryRow(ctx, createPluginRemoteMCPSecret,- arg.WorkspaceID,- arg.Ciphertext,- arg.Hint,- arg.CreatedBy,- arg.ContributionID,+func (q *Queries) GetPluginStorageValue(ctx context.Context, arg GetPluginStorageValueParams) (PluginStorage, error) {+ row := q.db.QueryRow(ctx, getPluginStorageValue,arg.InstallationID,+ arg.ScopeType,+ arg.ScopeID,+ arg.Key,)- var i PluginRemoteMcpSecret+ var i PluginStorageerr := row.Scan(&i.ID,- &i.WorkspaceID,&i.InstallationID,- &i.ContributionID,- &i.Version,- &i.Ciphertext,- &i.Hint,- &i.Status,- &i.CreatedBy,+ &i.ScopeType,+ &i.ScopeID,+ &i.Key,+ &i.Value,&i.CreatedAt,- &i.RevokedAt,- )- return i, err-}--const deleteExpiredPluginRemoteMCPOAuthStates = `-- name: DeleteExpiredPluginRemoteMCPOAuthStates :execrows-DELETE FROM plugin_remote_mcp_oauth_state-WHERE expires_at <= now() OR consumed_at < now() - interval '1 hour'-`--func (q *Queries) DeleteExpiredPluginRemoteMCPOAuthStates(ctx context.Context) (int64, error) {- result, err := q.db.Exec(ctx, deleteExpiredPluginRemoteMCPOAuthStates)- if err != nil {- return 0, err- }- return result.RowsAffected(), nil-}--const ensurePluginWorkspaceCapabilityState = `-- name: EnsurePluginWorkspaceCapabilityState :one-WITH workspace_guard AS MATERIALIZED (- SELECT workspace.id- FROM workspace- WHERE workspace.id = $1- FOR KEY SHARE-)-INSERT INTO plugin_workspace_capability_state (workspace_id)-SELECT workspace_guard.id FROM workspace_guard-ON CONFLICT (workspace_id) DO UPDATE-SET workspace_id = EXCLUDED.workspace_id-RETURNING workspace_id, next_revision, active_snapshot_id, active_revision, updated_at-`--func (q *Queries) EnsurePluginWorkspaceCapabilityState(ctx context.Context, workspaceID pgtype.UUID) (PluginWorkspaceCapabilityState, error) {- row := q.db.QueryRow(ctx, ensurePluginWorkspaceCapabilityState, workspaceID)- var i PluginWorkspaceCapabilityState- err := row.Scan(- &i.WorkspaceID,- &i.NextRevision,- &i.ActiveSnapshotID,- &i.ActiveRevision,&i.UpdatedAt,)return i, err}-const getActivePluginRemoteMCPSecret = `-- name: GetActivePluginRemoteMCPSecret :one-SELECT id, workspace_id, installation_id, contribution_id, version, ciphertext, hint, status, created_by, created_at, revoked_at FROM plugin_remote_mcp_secret-WHERE id = $1- AND workspace_id = $2- AND installation_id = $3- AND contribution_id = $4- AND status = 'active'-`--type GetActivePluginRemoteMCPSecretParams struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- InstallationID pgtype.UUID `json:"installation_id"`- ContributionID pgtype.UUID `json:"contribution_id"`-}--func (q *Queries) GetActivePluginRemoteMCPSecret(ctx context.Context, arg GetActivePluginRemoteMCPSecretParams) (PluginRemoteMcpSecret, error) {- row := q.db.QueryRow(ctx, getActivePluginRemoteMCPSecret,- arg.ID,- arg.WorkspaceID,- arg.InstallationID,- arg.ContributionID,- )- var i PluginRemoteMcpSecret- err := row.Scan(- &i.ID,- &i.WorkspaceID,- &i.InstallationID,- &i.ContributionID,- &i.Version,- &i.Ciphertext,- &i.Hint,- &i.Status,- &i.CreatedBy,- &i.CreatedAt,- &i.RevokedAt,- )- return i, err-}--const getActivePluginRemoteMCPSecretForUpdate = `-- name: GetActivePluginRemoteMCPSecretForUpdate :one-SELECT id, workspace_id, installation_id, contribution_id, version, ciphertext, hint, status, created_by, created_at, revoked_at FROM plugin_remote_mcp_secret-WHERE id = $1- AND workspace_id = $2- AND installation_id = $3- AND contribution_id = $4- AND status = 'active'-FOR UPDATE-`--type GetActivePluginRemoteMCPSecretForUpdateParams struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- InstallationID pgtype.UUID `json:"installation_id"`- ContributionID pgtype.UUID `json:"contribution_id"`-}--func (q *Queries) GetActivePluginRemoteMCPSecretForUpdate(ctx context.Context, arg GetActivePluginRemoteMCPSecretForUpdateParams) (PluginRemoteMcpSecret, error) {- row := q.db.QueryRow(ctx, getActivePluginRemoteMCPSecretForUpdate,- arg.ID,- arg.WorkspaceID,- arg.InstallationID,- arg.ContributionID,- )- var i PluginRemoteMcpSecret- err := row.Scan(- &i.ID,- &i.WorkspaceID,- &i.InstallationID,- &i.ContributionID,- &i.Version,- &i.Ciphertext,- &i.Hint,- &i.Status,- &i.CreatedBy,- &i.CreatedAt,- &i.RevokedAt,- )- return i, err-}--const getInstallationRemoteMCPContribution = `-- name: GetInstallationRemoteMCPContribution :one-SELECT contribution.id, contribution.release_id, contribution.contribution_key, contribution.type, contribution.schema_version, contribution.display_name, contribution.description, contribution.entry_path, contribution.entry_digest, contribution.artifact_digest, contribution.required_daemon_features, contribution.ordinal, contribution.created_at, release.manifest-FROM plugin_installation installation-JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = installation.plugin_id- AND release.revocation_status = 'active'-JOIN plugin_contribution contribution- ON contribution.release_id = release.id- AND contribution.type = 'tool.remote-mcp.v1'-WHERE installation.id = $1- AND installation.workspace_id = $2- AND installation.uninstalled_at IS NULL- AND contribution.contribution_key = $3-`--type GetInstallationRemoteMCPContributionParams struct {- InstallationID pgtype.UUID `json:"installation_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- ContributionKey string `json:"contribution_key"`-}--type GetInstallationRemoteMCPContributionRow struct {- ID pgtype.UUID `json:"id"`- ReleaseID pgtype.UUID `json:"release_id"`- ContributionKey string `json:"contribution_key"`- Type string `json:"type"`- SchemaVersion int32 `json:"schema_version"`- DisplayName string `json:"display_name"`- Description string `json:"description"`- EntryPath string `json:"entry_path"`- EntryDigest string `json:"entry_digest"`- ArtifactDigest string `json:"artifact_digest"`- RequiredDaemonFeatures []byte `json:"required_daemon_features"`- Ordinal int32 `json:"ordinal"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- Manifest []byte `json:"manifest"`-}--func (q *Queries) GetInstallationRemoteMCPContribution(ctx context.Context, arg GetInstallationRemoteMCPContributionParams) (GetInstallationRemoteMCPContributionRow, error) {- row := q.db.QueryRow(ctx, getInstallationRemoteMCPContribution, arg.InstallationID, arg.WorkspaceID, arg.ContributionKey)- var i GetInstallationRemoteMCPContributionRow- err := row.Scan(- &i.ID,- &i.ReleaseID,- &i.ContributionKey,- &i.Type,- &i.SchemaVersion,- &i.DisplayName,- &i.Description,- &i.EntryPath,- &i.EntryDigest,- &i.ArtifactDigest,- &i.RequiredDaemonFeatures,- &i.Ordinal,- &i.CreatedAt,- &i.Manifest,- )- return i, err-}--const getInstallationRemoteMCPContributionByID = `-- name: GetInstallationRemoteMCPContributionByID :one-SELECT contribution.id, contribution.release_id, contribution.contribution_key, contribution.type, contribution.schema_version, contribution.display_name, contribution.description, contribution.entry_path, contribution.entry_digest, contribution.artifact_digest, contribution.required_daemon_features, contribution.ordinal, contribution.created_at, release.manifest-FROM plugin_installation installation-JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = installation.plugin_id- AND release.revocation_status = 'active'-JOIN plugin_contribution contribution- ON contribution.release_id = release.id- AND contribution.type = 'tool.remote-mcp.v1'-WHERE installation.id = $1- AND installation.workspace_id = $2- AND installation.uninstalled_at IS NULL- AND contribution.id = $3-`--type GetInstallationRemoteMCPContributionByIDParams struct {- InstallationID pgtype.UUID `json:"installation_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- ContributionID pgtype.UUID `json:"contribution_id"`-}--type GetInstallationRemoteMCPContributionByIDRow struct {- ID pgtype.UUID `json:"id"`- ReleaseID pgtype.UUID `json:"release_id"`- ContributionKey string `json:"contribution_key"`- Type string `json:"type"`- SchemaVersion int32 `json:"schema_version"`- DisplayName string `json:"display_name"`- Description string `json:"description"`- EntryPath string `json:"entry_path"`- EntryDigest string `json:"entry_digest"`- ArtifactDigest string `json:"artifact_digest"`- RequiredDaemonFeatures []byte `json:"required_daemon_features"`- Ordinal int32 `json:"ordinal"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- Manifest []byte `json:"manifest"`-}--func (q *Queries) GetInstallationRemoteMCPContributionByID(ctx context.Context, arg GetInstallationRemoteMCPContributionByIDParams) (GetInstallationRemoteMCPContributionByIDRow, error) {- row := q.db.QueryRow(ctx, getInstallationRemoteMCPContributionByID, arg.InstallationID, arg.WorkspaceID, arg.ContributionID)- var i GetInstallationRemoteMCPContributionByIDRow- err := row.Scan(- &i.ID,- &i.ReleaseID,- &i.ContributionKey,- &i.Type,- &i.SchemaVersion,- &i.DisplayName,- &i.Description,- &i.EntryPath,- &i.EntryDigest,- &i.ArtifactDigest,- &i.RequiredDaemonFeatures,- &i.Ordinal,- &i.CreatedAt,- &i.Manifest,- )- return i, err-}--const getLatestPluginInstallationConfig = `-- name: GetLatestPluginInstallationConfig :one-SELECT id, workspace_id, installation_id, contribution_id, revision, endpoint, public_config, auth_type, auth_header, secret_ref, approved_tools, schema_digest, failure_policy, reviewed_by, reviewed_at, created_by, created_at, discovered_tools, discovered_schema_digest FROM plugin_installation_config-WHERE workspace_id = $1- AND installation_id = $2- AND contribution_id = $3-ORDER BY revision DESC-LIMIT 1-`--type GetLatestPluginInstallationConfigParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- InstallationID pgtype.UUID `json:"installation_id"`- ContributionID pgtype.UUID `json:"contribution_id"`-}--func (q *Queries) GetLatestPluginInstallationConfig(ctx context.Context, arg GetLatestPluginInstallationConfigParams) (PluginInstallationConfig, error) {- row := q.db.QueryRow(ctx, getLatestPluginInstallationConfig, arg.WorkspaceID, arg.InstallationID, arg.ContributionID)- var i PluginInstallationConfig- err := row.Scan(- &i.ID,- &i.WorkspaceID,- &i.InstallationID,- &i.ContributionID,- &i.Revision,- &i.Endpoint,- &i.PublicConfig,- &i.AuthType,- &i.AuthHeader,- &i.SecretRef,- &i.ApprovedTools,- &i.SchemaDigest,- &i.FailurePolicy,- &i.ReviewedBy,- &i.ReviewedAt,- &i.CreatedBy,- &i.CreatedAt,- &i.DiscoveredTools,- &i.DiscoveredSchemaDigest,- )- return i, err-}--const getLatestPluginRelease = `-- name: GetLatestPluginRelease :one-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_identity identity ON identity.id = release.plugin_id-WHERE identity.plugin_key = $1- AND identity.retired_at IS NULL- AND release.revocation_status = 'active'-ORDER BY release.published_at DESC, release.id DESC-LIMIT 1-`--func (q *Queries) GetLatestPluginRelease(ctx context.Context, pluginKey string) (PluginRelease, error) {- row := q.db.QueryRow(ctx, getLatestPluginRelease, pluginKey)- 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 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 :one-SELECT id, release_id, path, digest, size_bytes, content, created_at FROM plugin_artifact_file-WHERE id = $1-`--func (q *Queries) GetPluginArtifactFile(ctx context.Context, id pgtype.UUID) (PluginArtifactFile, error) {- row := q.db.QueryRow(ctx, getPluginArtifactFile, id)- var i PluginArtifactFile- err := row.Scan(- &i.ID,- &i.ReleaseID,- &i.Path,- &i.Digest,- &i.SizeBytes,- &i.Content,- &i.CreatedAt,- )- return i, err-}--const getPluginArtifactFileByReleasePath = `-- name: GetPluginArtifactFileByReleasePath :one-SELECT id, release_id, path, digest, size_bytes, content, created_at FROM plugin_artifact_file-WHERE release_id = $1 AND path = $2-`--type GetPluginArtifactFileByReleasePathParams struct {- ReleaseID pgtype.UUID `json:"release_id"`- Path string `json:"path"`-}--func (q *Queries) GetPluginArtifactFileByReleasePath(ctx context.Context, arg GetPluginArtifactFileByReleasePathParams) (PluginArtifactFile, error) {- row := q.db.QueryRow(ctx, getPluginArtifactFileByReleasePath, arg.ReleaseID, arg.Path)- var i PluginArtifactFile- err := row.Scan(- &i.ID,- &i.ReleaseID,- &i.Path,- &i.Digest,- &i.SizeBytes,- &i.Content,- &i.CreatedAt,- )- return i, err-}--const getPluginExecutionManifestByTask = `-- name: GetPluginExecutionManifestByTask :one-SELECT manifest.id, manifest.task_id, manifest.workspace_id, manifest.agent_id, manifest.runtime_id, manifest.snapshot_id, manifest.snapshot_revision, manifest.snapshot_digest, manifest.composer_version, manifest.schema_version, manifest.ordered_contributions, manifest.diagnostics, manifest.created_at-FROM plugin_execution_manifest manifest-JOIN agent_task_queue task- ON task.plugin_execution_manifest_id = manifest.id-WHERE task.id = $1- AND manifest.task_id = task.id-`--func (q *Queries) GetPluginExecutionManifestByTask(ctx context.Context, taskID pgtype.UUID) (PluginExecutionManifest, error) {- row := q.db.QueryRow(ctx, getPluginExecutionManifestByTask, taskID)- var i PluginExecutionManifest- err := row.Scan(- &i.ID,- &i.TaskID,- &i.WorkspaceID,- &i.AgentID,- &i.RuntimeID,- &i.SnapshotID,- &i.SnapshotRevision,- &i.SnapshotDigest,- &i.ComposerVersion,- &i.SchemaVersion,- &i.OrderedContributions,- &i.Diagnostics,- &i.CreatedAt,- )- return i, err-}--const getPluginIdentity = `-- name: GetPluginIdentity :one-SELECT id, plugin_key, display_name, publisher_id, publisher_type, trust_tier, created_at, retired_at, owner_workspace_id FROM plugin_identity-WHERE id = $1-`--func (q *Queries) GetPluginIdentity(ctx context.Context, id pgtype.UUID) (PluginIdentity, error) {- row := q.db.QueryRow(ctx, getPluginIdentity, id)- 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 getPluginInstallation = `-- name: GetPluginInstallation :one-SELECT 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_installation-WHERE id = $1-`--func (q *Queries) GetPluginInstallation(ctx context.Context, id pgtype.UUID) (PluginInstallation, error) {- row := q.db.QueryRow(ctx, getPluginInstallation, id)- 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 getPluginRelease = `-- name: GetPluginRelease :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 id = $1-`--func (q *Queries) GetPluginRelease(ctx context.Context, id pgtype.UUID) (PluginRelease, error) {- row := q.db.QueryRow(ctx, getPluginRelease, id)- 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 getPluginReleaseByPluginKeyVersion = `-- name: GetPluginReleaseByPluginKeyVersion :one-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_identity identity ON identity.id = release.plugin_id-WHERE identity.plugin_key = $1- AND identity.owner_workspace_id IS NULL- AND identity.retired_at IS NULL- AND release.version = $2- AND release.revocation_status = 'active'-`--type GetPluginReleaseByPluginKeyVersionParams struct {- PluginKey string `json:"plugin_key"`- Version string `json:"version"`-}--func (q *Queries) GetPluginReleaseByPluginKeyVersion(ctx context.Context, arg GetPluginReleaseByPluginKeyVersionParams) (PluginRelease, error) {- row := q.db.QueryRow(ctx, getPluginReleaseByPluginKeyVersion, arg.PluginKey, 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 getPluginReleaseByVersion = `-- name: GetPluginReleaseByVersion :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 AND revocation_status = 'active'-`--type GetPluginReleaseByVersionParams struct {- PluginID pgtype.UUID `json:"plugin_id"`- Version string `json:"version"`-}--func (q *Queries) GetPluginReleaseByVersion(ctx context.Context, arg GetPluginReleaseByVersionParams) (PluginRelease, error) {- row := q.db.QueryRow(ctx, getPluginReleaseByVersion, 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 getPluginWorkspaceCapabilityStateForUpdate = `-- name: GetPluginWorkspaceCapabilityStateForUpdate :one-SELECT workspace_id, next_revision, active_snapshot_id, active_revision, updated_at FROM plugin_workspace_capability_state-WHERE workspace_id = $1-FOR UPDATE-`--func (q *Queries) GetPluginWorkspaceCapabilityStateForUpdate(ctx context.Context, workspaceID pgtype.UUID) (PluginWorkspaceCapabilityState, error) {- row := q.db.QueryRow(ctx, getPluginWorkspaceCapabilityStateForUpdate, workspaceID)- var i PluginWorkspaceCapabilityState- err := row.Scan(- &i.WorkspaceID,- &i.NextRevision,- &i.ActiveSnapshotID,- &i.ActiveRevision,- &i.UpdatedAt,- )- return 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 :one-SELECT 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_installation-WHERE workspace_id = $1 AND plugin_id = $2 AND uninstalled_at IS NULL-`--type GetWorkspacePluginInstallationParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- PluginID pgtype.UUID `json:"plugin_id"`-}--func (q *Queries) GetWorkspacePluginInstallation(ctx context.Context, arg GetWorkspacePluginInstallationParams) (PluginInstallation, error) {- row := q.db.QueryRow(ctx, getWorkspacePluginInstallation, arg.WorkspaceID, arg.PluginID)- 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 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 :many-SELECT DISTINCT ON (scope_type, scope_id) id, installation_id, scope_type, scope_id, enabled, binding_revision, created_by, created_at-FROM plugin_binding-WHERE installation_id = $1-ORDER BY scope_type, scope_id, binding_revision DESC-`--func (q *Queries) ListLatestPluginBindings(ctx context.Context, installationID pgtype.UUID) ([]PluginBinding, error) {- rows, err := q.db.Query(ctx, listLatestPluginBindings, installationID)- if err != nil {- return nil, err- }- defer rows.Close()- items := []PluginBinding{}- for rows.Next() {- var i PluginBinding- if err := rows.Scan(- &i.ID,- &i.InstallationID,- &i.ScopeType,- &i.ScopeID,- &i.Enabled,- &i.BindingRevision,- &i.CreatedBy,- &i.CreatedAt,- ); err != nil {- return nil, err- }- items = append(items, i)- }- if err := rows.Err(); err != nil {- return nil, err- }- return items, nil-}--const listLatestPluginGrants = `-- name: ListLatestPluginGrants :many-SELECT DISTINCT ON (capability) id, installation_id, capability, decision, limits, grant_revision, approved_by, approved_at, revoked_at-FROM plugin_grant-WHERE installation_id = $1-ORDER BY capability, grant_revision DESC-`--func (q *Queries) ListLatestPluginGrants(ctx context.Context, installationID pgtype.UUID) ([]PluginGrant, error) {- rows, err := q.db.Query(ctx, listLatestPluginGrants, installationID)- if err != nil {- return nil, err- }- defer rows.Close()- items := []PluginGrant{}- for rows.Next() {- var i PluginGrant- if err := rows.Scan(- &i.ID,- &i.InstallationID,- &i.Capability,- &i.Decision,- &i.Limits,- &i.GrantRevision,- &i.ApprovedBy,- &i.ApprovedAt,- &i.RevokedAt,- ); err != nil {- return nil, err- }- items = append(items, i)- }- if err := rows.Err(); err != nil {- return nil, err- }- return items, nil-}--const listLatestPluginInstallationConfigs = `-- name: ListLatestPluginInstallationConfigs :many-SELECT DISTINCT ON (config.contribution_id) config.id, config.workspace_id, config.installation_id, config.contribution_id, config.revision, config.endpoint, config.public_config, config.auth_type, config.auth_header, config.secret_ref, config.approved_tools, config.schema_digest, config.failure_policy, config.reviewed_by, config.reviewed_at, config.created_by, config.created_at, config.discovered_tools, config.discovered_schema_digest-FROM plugin_installation_config config-WHERE config.workspace_id = $1- AND config.installation_id = $2-ORDER BY config.contribution_id, config.revision DESC-`--type ListLatestPluginInstallationConfigsParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- InstallationID pgtype.UUID `json:"installation_id"`-}--func (q *Queries) ListLatestPluginInstallationConfigs(ctx context.Context, arg ListLatestPluginInstallationConfigsParams) ([]PluginInstallationConfig, error) {- rows, err := q.db.Query(ctx, listLatestPluginInstallationConfigs, arg.WorkspaceID, arg.InstallationID)- if err != nil {- return nil, err- }- defer rows.Close()- items := []PluginInstallationConfig{}- for rows.Next() {- var i PluginInstallationConfig- if err := rows.Scan(- &i.ID,- &i.WorkspaceID,- &i.InstallationID,- &i.ContributionID,- &i.Revision,- &i.Endpoint,- &i.PublicConfig,- &i.AuthType,- &i.AuthHeader,- &i.SecretRef,- &i.ApprovedTools,- &i.SchemaDigest,- &i.FailurePolicy,- &i.ReviewedBy,- &i.ReviewedAt,- &i.CreatedBy,- &i.CreatedAt,- &i.DiscoveredTools,- &i.DiscoveredSchemaDigest,- ); err != nil {- return nil, err- }- items = append(items, i)- }- if err := rows.Err(); err != nil {- return nil, err- }- return items, nil-}--const listPluginArtifactFilesByIDs = `-- name: ListPluginArtifactFilesByIDs :many-SELECT id, release_id, path, digest, size_bytes, content, created_at FROM plugin_artifact_file-WHERE id = ANY($1::uuid[])-ORDER BY path, id-`--func (q *Queries) ListPluginArtifactFilesByIDs(ctx context.Context, ids []pgtype.UUID) ([]PluginArtifactFile, error) {- rows, err := q.db.Query(ctx, listPluginArtifactFilesByIDs, ids)- if err != nil {- return nil, err- }- defer rows.Close()- items := []PluginArtifactFile{}- for rows.Next() {- var i PluginArtifactFile- if err := rows.Scan(- &i.ID,- &i.ReleaseID,- &i.Path,- &i.Digest,- &i.SizeBytes,- &i.Content,- &i.CreatedAt,- ); err != nil {- return nil, err- }- items = append(items, i)- }- if err := rows.Err(); err != nil {- return nil, err- }- return items, nil-}--const listPluginArtifactFilesByRelease = `-- name: ListPluginArtifactFilesByRelease :many-SELECT id, release_id, path, digest, size_bytes, content, created_at FROM plugin_artifact_file-WHERE release_id = $1-ORDER BY path, id-`--func (q *Queries) ListPluginArtifactFilesByRelease(ctx context.Context, releaseID pgtype.UUID) ([]PluginArtifactFile, error) {- rows, err := q.db.Query(ctx, listPluginArtifactFilesByRelease, releaseID)- if err != nil {- return nil, err- }- defer rows.Close()- items := []PluginArtifactFile{}- for rows.Next() {- var i PluginArtifactFile- if err := rows.Scan(- &i.ID,- &i.ReleaseID,- &i.Path,- &i.Digest,- &i.SizeBytes,- &i.Content,- &i.CreatedAt,- ); err != nil {- return nil, err- }- items = append(items, i)- }- if err := rows.Err(); err != nil {- return nil, err- }- return items, nil-}--const listPluginCompilationContributions = `-- name: ListPluginCompilationContributions :many-WITH latest_grants AS (- SELECT DISTINCT ON (installation_id, capability)- installation_id, capability, decision, limits, grant_revision- FROM plugin_grant- ORDER BY installation_id, capability, grant_revision DESC-),-latest_bindings AS (- SELECT DISTINCT ON (installation_id, scope_type, scope_id)- installation_id, scope_type, scope_id, enabled, binding_revision- FROM plugin_binding- ORDER BY installation_id, scope_type, scope_id, binding_revision DESC-),-latest_configs AS (- SELECT DISTINCT ON (installation_id, contribution_id) id, workspace_id, installation_id, contribution_id, revision, endpoint, public_config, auth_type, auth_header, secret_ref, approved_tools, schema_digest, failure_policy, reviewed_by, reviewed_at, created_by, created_at, discovered_tools, discovered_schema_digest- FROM plugin_installation_config- WHERE workspace_id = $1- ORDER BY installation_id, contribution_id, revision DESC-)-SELECT- installation.id AS installation_id,- installation.workspace_id,- installation.desired_generation,- identity.id AS plugin_id,- identity.plugin_key,- release.id AS release_id,- release.version AS release_version,- release.source_kind,- release.artifact_ref,- release.artifact_digest,- contribution.id AS contribution_id,- contribution.contribution_key,- contribution.type AS contribution_type,- contribution.display_name,- contribution.description,- contribution.entry_path,- contribution.entry_digest,- contribution.required_daemon_features,- contribution.ordinal,- artifact.id AS artifact_file_id,- artifact.content AS entry_content,- artifact.size_bytes AS entry_size_bytes,- binding.scope_type,- binding.scope_id,- binding.enabled AS binding_enabled,- binding.binding_revision,- grant_row.grant_revision,- config.id AS config_id,- config.revision AS config_revision,- config.endpoint,- config.public_config,- config.auth_type,- config.auth_header,- config.secret_ref,- config.approved_tools,- config.schema_digest,- config.failure_policy,- config.reviewed_at-FROM plugin_installation installation-JOIN plugin_identity identity- ON identity.id = installation.plugin_id-JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = identity.id- AND release.revocation_status = 'active'-JOIN plugin_contribution contribution- ON contribution.release_id = release.id-JOIN plugin_artifact_file artifact- ON artifact.release_id = release.id- AND artifact.path = contribution.entry_path-JOIN latest_grants grant_row- ON grant_row.installation_id = installation.id- AND grant_row.capability = CASE contribution.type- WHEN 'agent.skill.v1' THEN 'agent.skill.contribute'- WHEN 'tool.remote-mcp.v1' THEN 'tool.remote-mcp.connect'- END- AND grant_row.decision = 'granted'-LEFT JOIN latest_configs config- ON config.installation_id = installation.id- AND config.contribution_id = contribution.id-LEFT JOIN latest_bindings binding- ON binding.installation_id = installation.id-WHERE installation.workspace_id = $1- AND installation.uninstalled_at IS NULL- AND installation.enabled = TRUE- AND (- contribution.type = 'agent.skill.v1'- OR (- contribution.type = 'tool.remote-mcp.v1'- AND config.reviewed_at IS NOT NULL- AND jsonb_array_length(config.approved_tools) > 0- )- )-ORDER BY identity.plugin_key, contribution.ordinal,- contribution.contribution_key,- binding.scope_type NULLS FIRST, binding.scope_id NULLS FIRST+const getWorkspacePluginInstallation = `-- name: GetWorkspacePluginInstallation :one+SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at FROM plugin_installation+WHERE workspace_id = $1 AND id = $2`-type ListPluginCompilationContributionsRow struct {- InstallationID pgtype.UUID `json:"installation_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- DesiredGeneration int64 `json:"desired_generation"`- PluginID pgtype.UUID `json:"plugin_id"`- PluginKey string `json:"plugin_key"`- ReleaseID pgtype.UUID `json:"release_id"`- ReleaseVersion string `json:"release_version"`- SourceKind string `json:"source_kind"`- ArtifactRef string `json:"artifact_ref"`- ArtifactDigest string `json:"artifact_digest"`- ContributionID pgtype.UUID `json:"contribution_id"`- ContributionKey string `json:"contribution_key"`- ContributionType string `json:"contribution_type"`- DisplayName string `json:"display_name"`- Description string `json:"description"`- EntryPath string `json:"entry_path"`- EntryDigest string `json:"entry_digest"`- RequiredDaemonFeatures []byte `json:"required_daemon_features"`- Ordinal int32 `json:"ordinal"`- ArtifactFileID pgtype.UUID `json:"artifact_file_id"`- EntryContent string `json:"entry_content"`- EntrySizeBytes int64 `json:"entry_size_bytes"`- ScopeType pgtype.Text `json:"scope_type"`- ScopeID pgtype.UUID `json:"scope_id"`- BindingEnabled pgtype.Bool `json:"binding_enabled"`- BindingRevision pgtype.Int8 `json:"binding_revision"`- GrantRevision int64 `json:"grant_revision"`- ConfigID pgtype.UUID `json:"config_id"`- ConfigRevision pgtype.Int8 `json:"config_revision"`- Endpoint pgtype.Text `json:"endpoint"`- PublicConfig []byte `json:"public_config"`- AuthType pgtype.Text `json:"auth_type"`- AuthHeader pgtype.Text `json:"auth_header"`- SecretRef pgtype.UUID `json:"secret_ref"`- ApprovedTools []byte `json:"approved_tools"`- SchemaDigest pgtype.Text `json:"schema_digest"`- FailurePolicy pgtype.Text `json:"failure_policy"`- ReviewedAt pgtype.Timestamptz `json:"reviewed_at"`+type GetWorkspacePluginInstallationParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ID pgtype.UUID `json:"id"`}-func (q *Queries) ListPluginCompilationContributions(ctx context.Context, workspaceID pgtype.UUID) ([]ListPluginCompilationContributionsRow, error) {- rows, err := q.db.Query(ctx, listPluginCompilationContributions, workspaceID)- if err != nil {- return nil, err- }- defer rows.Close()- items := []ListPluginCompilationContributionsRow{}- for rows.Next() {- var i ListPluginCompilationContributionsRow- if err := rows.Scan(- &i.InstallationID,- &i.WorkspaceID,- &i.DesiredGeneration,- &i.PluginID,- &i.PluginKey,- &i.ReleaseID,- &i.ReleaseVersion,- &i.SourceKind,- &i.ArtifactRef,- &i.ArtifactDigest,- &i.ContributionID,- &i.ContributionKey,- &i.ContributionType,- &i.DisplayName,- &i.Description,- &i.EntryPath,- &i.EntryDigest,- &i.RequiredDaemonFeatures,- &i.Ordinal,- &i.ArtifactFileID,- &i.EntryContent,- &i.EntrySizeBytes,- &i.ScopeType,- &i.ScopeID,- &i.BindingEnabled,- &i.BindingRevision,- &i.GrantRevision,- &i.ConfigID,- &i.ConfigRevision,- &i.Endpoint,- &i.PublicConfig,- &i.AuthType,- &i.AuthHeader,- &i.SecretRef,- &i.ApprovedTools,- &i.SchemaDigest,- &i.FailurePolicy,- &i.ReviewedAt,- ); err != nil {- return nil, err- }- items = append(items, i)- }- if err := rows.Err(); err != nil {- return nil, err- }- return items, nil+func (q *Queries) GetWorkspacePluginInstallation(ctx context.Context, arg GetWorkspacePluginInstallationParams) (PluginInstallation, error) {+ row := q.db.QueryRow(ctx, getWorkspacePluginInstallation, arg.WorkspaceID, arg.ID)+ var i PluginInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginKey,+ &i.SourceUrl,+ &i.Version,+ &i.Manifest,+ &i.GrantedScopes,+ &i.Config,+ &i.Enabled,+ &i.InstalledBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err}-const listPluginContributionsByRelease = `-- name: ListPluginContributionsByRelease :many-SELECT id, release_id, contribution_key, type, schema_version, display_name, description, entry_path, entry_digest, artifact_digest, required_daemon_features, ordinal, created_at FROM plugin_contribution-WHERE release_id = $1-ORDER BY ordinal, id+const getWorkspacePluginInstallationByKey = `-- name: GetWorkspacePluginInstallationByKey :one+SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at FROM plugin_installation+WHERE workspace_id = $1 AND plugin_key = $2`-func (q *Queries) ListPluginContributionsByRelease(ctx context.Context, releaseID pgtype.UUID) ([]PluginContribution, error) {- rows, err := q.db.Query(ctx, listPluginContributionsByRelease, releaseID)- if err != nil {- return nil, err- }- defer rows.Close()- items := []PluginContribution{}- for rows.Next() {- var i PluginContribution- if err := rows.Scan(- &i.ID,- &i.ReleaseID,- &i.ContributionKey,- &i.Type,- &i.SchemaVersion,- &i.DisplayName,- &i.Description,- &i.EntryPath,- &i.EntryDigest,- &i.ArtifactDigest,- &i.RequiredDaemonFeatures,- &i.Ordinal,- &i.CreatedAt,- ); err != nil {- return nil, err- }- items = append(items, i)- }- if err := rows.Err(); err != nil {- return nil, err- }- return items, nil+type GetWorkspacePluginInstallationByKeyParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PluginKey string `json:"plugin_key"`+}++func (q *Queries) GetWorkspacePluginInstallationByKey(ctx context.Context, arg GetWorkspacePluginInstallationByKeyParams) (PluginInstallation, error) {+ row := q.db.QueryRow(ctx, getWorkspacePluginInstallationByKey, arg.WorkspaceID, arg.PluginKey)+ var i PluginInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginKey,+ &i.SourceUrl,+ &i.Version,+ &i.Manifest,+ &i.GrantedScopes,+ &i.Config,+ &i.Enabled,+ &i.InstalledBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err}-const listPluginInstallationsForCompile = `-- name: ListPluginInstallationsForCompile :many-SELECT 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_installation-WHERE workspace_id = $1 AND uninstalled_at IS NULL-ORDER BY id-FOR UPDATE+const listPluginSecretKeys = `-- name: ListPluginSecretKeys :many+SELECT key, updated_at FROM plugin_secret+WHERE installation_id = $1+ORDER BY key ASC`-func (q *Queries) ListPluginInstallationsForCompile(ctx context.Context, workspaceID pgtype.UUID) ([]PluginInstallation, error) {- rows, err := q.db.Query(ctx, listPluginInstallationsForCompile, workspaceID)+type ListPluginSecretKeysRow struct {+ Key string `json:"key"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++// Deliberately never selects ciphertext: the presence of a secret is readable,+// its value is not.+func (q *Queries) ListPluginSecretKeys(ctx context.Context, installationID pgtype.UUID) ([]ListPluginSecretKeysRow, error) {+ rows, err := q.db.Query(ctx, listPluginSecretKeys, installationID)if err != nil {return nil, err}defer rows.Close()- items := []PluginInstallation{}+ items := []ListPluginSecretKeysRow{}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 {+ var i ListPluginSecretKeysRow+ if err := rows.Scan(&i.Key, &i.UpdatedAt); err != nil {return nil, err}items = append(items, i)@@ -2192,78 +334,35 @@ 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+const listPluginStorageKeys = `-- name: ListPluginStorageKeys :many+SELECT key, octet_length(value)::bigint AS size_bytes, updated_at+FROM plugin_storage+WHERE installation_id = $1 AND scope_type = $2 AND scope_id = $3+ORDER BY key ASC`-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+type ListPluginStorageKeysParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`}-const listWorkspacePluginHealth = `-- name: ListWorkspacePluginHealth :many-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-ORDER BY observed_at DESC, id DESC-`+type ListPluginStorageKeysRow struct {+ Key string `json:"key"`+ SizeBytes int64 `json:"size_bytes"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}-func (q *Queries) ListWorkspacePluginHealth(ctx context.Context, workspaceID pgtype.UUID) ([]PluginHealth, error) {- rows, err := q.db.Query(ctx, listWorkspacePluginHealth, workspaceID)+func (q *Queries) ListPluginStorageKeys(ctx context.Context, arg ListPluginStorageKeysParams) ([]ListPluginStorageKeysRow, error) {+ rows, err := q.db.Query(ctx, listPluginStorageKeys, arg.InstallationID, arg.ScopeType, arg.ScopeID)if err != nil {return nil, err}defer rows.Close()- items := []PluginHealth{}+ items := []ListPluginStorageKeysRow{}for rows.Next() {- var i PluginHealth- if err := rows.Scan(- &i.ID,- &i.WorkspaceID,- &i.InstallationID,- &i.ScopeType,- &i.ScopeID,- &i.State,- &i.ReasonCode,- &i.SafeDetail,- &i.ObservedGeneration,- &i.LastGoodSnapshotID,- &i.ObservedAt,- ); err != nil {+ var i ListPluginStorageKeysRow+ if err := rows.Scan(&i.Key, &i.SizeBytes, &i.UpdatedAt); err != nil {return nil, err}items = append(items, i)@@ -2275,9 +374,9 @@ func (q *Queries) ListWorkspacePluginHealth(ctx context.Context, workspaceID pgt}const listWorkspacePluginInstallations = `-- name: ListWorkspacePluginInstallations :many-SELECT 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_installation-WHERE workspace_id = $1 AND uninstalled_at IS NULL-ORDER BY installed_at, id+SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at FROM plugin_installation+WHERE workspace_id = $1+ORDER BY created_at ASC`func (q *Queries) ListWorkspacePluginInstallations(ctx context.Context, workspaceID pgtype.UUID) ([]PluginInstallation, error) {@@ -2292,118 +391,16 @@ func (q *Queries) ListWorkspacePluginInstallations(ctx context.Context, workspacif 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 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.PluginKey,+ &i.SourceUrl,&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.GrantedScopes,+ &i.Config,&i.Enabled,- &i.DesiredGeneration,- &i.ActiveGeneration,- &i.LifecycleStatus,&i.InstalledBy,- &i.InstalledAt,- &i.UpdatedBy,+ &i.CreatedAt,&i.UpdatedAt,- &i.DisabledAt,- &i.UninstalledAt,); err != nil {return nil, err}@@ -2415,326 +412,175 @@ func (q *Queries) ListWorkspacePrivatePluginInstallations(ctx context.Context, wreturn items, nil}-const lockPluginRegistryKey = `-- name: LockPluginRegistryKey :exec-SELECT pg_advisory_xact_lock(hashtextextended($1, 0))-`--func (q *Queries) LockPluginRegistryKey(ctx context.Context, pluginKey string) error {- _, err := q.db.Exec(ctx, lockPluginRegistryKey, pluginKey)- return err-}--const lockPluginRemoteMCPInstallation = `-- name: LockPluginRemoteMCPInstallation :one-SELECT installation.id-FROM plugin_installation installation-JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = installation.plugin_id- AND release.revocation_status = 'active'-JOIN plugin_contribution contribution- ON contribution.release_id = release.id- AND contribution.id = $1- AND contribution.type = 'tool.remote-mcp.v1'-WHERE installation.id = $2- AND installation.workspace_id = $3- AND installation.uninstalled_at IS NULL-FOR UPDATE OF installation+const setPluginInstallationEnabled = `-- name: SetPluginInstallationEnabled :one+UPDATE plugin_installation+SET enabled = $2,+ updated_at = now()+WHERE id = $1+RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at`-type LockPluginRemoteMCPInstallationParams struct {- ContributionID pgtype.UUID `json:"contribution_id"`- InstallationID pgtype.UUID `json:"installation_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`-}--func (q *Queries) LockPluginRemoteMCPInstallation(ctx context.Context, arg LockPluginRemoteMCPInstallationParams) (pgtype.UUID, error) {- row := q.db.QueryRow(ctx, lockPluginRemoteMCPInstallation, arg.ContributionID, arg.InstallationID, arg.WorkspaceID)- var id pgtype.UUID- err := row.Scan(&id)- return id, err+type SetPluginInstallationEnabledParams struct {+ ID pgtype.UUID `json:"id"`+ Enabled bool `json:"enabled"`}-const retirePluginIdentity = `-- name: RetirePluginIdentity :one-UPDATE plugin_identity-SET 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, owner_workspace_id-`--func (q *Queries) RetirePluginIdentity(ctx context.Context, id pgtype.UUID) (PluginIdentity, error) {- row := q.db.QueryRow(ctx, retirePluginIdentity, id)- var i PluginIdentity+func (q *Queries) SetPluginInstallationEnabled(ctx context.Context, arg SetPluginInstallationEnabledParams) (PluginInstallation, error) {+ row := q.db.QueryRow(ctx, setPluginInstallationEnabled, arg.ID, arg.Enabled)+ var i PluginInstallationerr := row.Scan(&i.ID,+ &i.WorkspaceID,&i.PluginKey,- &i.DisplayName,- &i.PublisherID,- &i.PublisherType,- &i.TrustTier,+ &i.SourceUrl,+ &i.Version,+ &i.Manifest,+ &i.GrantedScopes,+ &i.Config,+ &i.Enabled,+ &i.InstalledBy,&i.CreatedAt,- &i.RetiredAt,- &i.OwnerWorkspaceID,+ &i.UpdatedAt,)return i, err}-const revokePluginRelease = `-- name: RevokePluginRelease :one-UPDATE plugin_release-SET revocation_status = $1,- revoked_at = now(),- revocation_reason = $2-WHERE id = $3 AND revocation_status = 'active'-RETURNING 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+const updatePluginInstallationConfig = `-- name: UpdatePluginInstallationConfig :one+UPDATE plugin_installation+SET config = $2,+ updated_at = now()+WHERE id = $1+RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at`-type RevokePluginReleaseParams struct {- RevocationStatus string `json:"revocation_status"`- RevocationReason pgtype.Text `json:"revocation_reason"`- ID pgtype.UUID `json:"id"`+type UpdatePluginInstallationConfigParams struct {+ ID pgtype.UUID `json:"id"`+ Config []byte `json:"config"`}-func (q *Queries) RevokePluginRelease(ctx context.Context, arg RevokePluginReleaseParams) (PluginRelease, error) {- row := q.db.QueryRow(ctx, revokePluginRelease, arg.RevocationStatus, arg.RevocationReason, arg.ID)- var i PluginRelease+func (q *Queries) UpdatePluginInstallationConfig(ctx context.Context, arg UpdatePluginInstallationConfigParams) (PluginInstallation, error) {+ row := q.db.QueryRow(ctx, updatePluginInstallationConfig, arg.ID, arg.Config)+ var i PluginInstallationerr := row.Scan(&i.ID,- &i.PluginID,+ &i.WorkspaceID,+ &i.PluginKey,+ &i.SourceUrl,&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,+ &i.GrantedScopes,+ &i.Config,+ &i.Enabled,+ &i.InstalledBy,+ &i.CreatedAt,+ &i.UpdatedAt,)return i, err}-const revokePluginRemoteMCPSecrets = `-- name: RevokePluginRemoteMCPSecrets :many-UPDATE plugin_remote_mcp_secret-SET status = 'revoked', revoked_at = now()-WHERE workspace_id = $1- AND installation_id = $2- AND contribution_id = $3- AND status = 'active'-RETURNING id, workspace_id, installation_id, contribution_id, version, ciphertext, hint, status, created_by, created_at, revoked_at-`--type RevokePluginRemoteMCPSecretsParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- InstallationID pgtype.UUID `json:"installation_id"`- ContributionID pgtype.UUID `json:"contribution_id"`-}--func (q *Queries) RevokePluginRemoteMCPSecrets(ctx context.Context, arg RevokePluginRemoteMCPSecretsParams) ([]PluginRemoteMcpSecret, error) {- rows, err := q.db.Query(ctx, revokePluginRemoteMCPSecrets, arg.WorkspaceID, arg.InstallationID, arg.ContributionID)- if err != nil {- return nil, err- }- defer rows.Close()- items := []PluginRemoteMcpSecret{}- for rows.Next() {- var i PluginRemoteMcpSecret- if err := rows.Scan(- &i.ID,- &i.WorkspaceID,- &i.InstallationID,- &i.ContributionID,- &i.Version,- &i.Ciphertext,- &i.Hint,- &i.Status,- &i.CreatedBy,- &i.CreatedAt,- &i.RevokedAt,- ); err != nil {- return nil, err- }- items = append(items, i)- }- if err := rows.Err(); err != nil {- return nil, err- }- return items, nil-}--const setPluginInstallationDesiredState = `-- name: SetPluginInstallationDesiredState :one-WITH workspace_guard AS MATERIALIZED (- SELECT workspace.id- FROM workspace- WHERE workspace.id = $3- FOR KEY SHARE-),-target AS MATERIALIZED (- SELECT i.id, r.id AS release_id- FROM plugin_installation i- JOIN workspace_guard w ON w.id = i.workspace_id- JOIN plugin_release r ON r.id = $4- AND r.plugin_id = i.plugin_id- AND r.revocation_status = 'active'- WHERE i.id = $5- AND i.workspace_id = $3- AND i.uninstalled_at IS NULL- FOR UPDATE OF i-)-UPDATE plugin_installation i-SET desired_release_id = target.release_id,- enabled = $1,- desired_generation = i.desired_generation + 1,- lifecycle_status = 'activating',- updated_by = $2,- updated_at = now(),- disabled_at = CASE WHEN $1::boolean THEN NULL ELSE now() END-FROM target-WHERE i.id = target.id-RETURNING i.id, i.workspace_id, i.plugin_id, i.source_kind, i.source_ref, i.desired_release_id, i.active_release_id, i.enabled, i.desired_generation, i.active_generation, i.lifecycle_status, i.installed_by, i.installed_at, i.updated_by, i.updated_at, i.disabled_at, i.uninstalled_at+const updatePluginInstallationManifest = `-- name: UpdatePluginInstallationManifest :one+UPDATE plugin_installation+SET source_url = $2,+ version = $3,+ manifest = $4,+ granted_scopes = $5,+ config = $6,+ updated_at = now()+WHERE id = $1+RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at`-type SetPluginInstallationDesiredStateParams struct {- Enabled bool `json:"enabled"`- UpdatedBy pgtype.UUID `json:"updated_by"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- DesiredReleaseID pgtype.UUID `json:"desired_release_id"`- ID pgtype.UUID `json:"id"`+type UpdatePluginInstallationManifestParams struct {+ ID pgtype.UUID `json:"id"`+ SourceUrl string `json:"source_url"`+ Version string `json:"version"`+ Manifest []byte `json:"manifest"`+ GrantedScopes []byte `json:"granted_scopes"`+ Config []byte `json:"config"`}-func (q *Queries) SetPluginInstallationDesiredState(ctx context.Context, arg SetPluginInstallationDesiredStateParams) (PluginInstallation, error) {- row := q.db.QueryRow(ctx, setPluginInstallationDesiredState,- arg.Enabled,- arg.UpdatedBy,- arg.WorkspaceID,- arg.DesiredReleaseID,+// Upgrade path: the re-consented manifest snapshot replaces the old one in+// place. Config values survive on purpose; fields the new manifest dropped are+// pruned by the service before this runs.+func (q *Queries) UpdatePluginInstallationManifest(ctx context.Context, arg UpdatePluginInstallationManifestParams) (PluginInstallation, error) {+ row := q.db.QueryRow(ctx, updatePluginInstallationManifest,arg.ID,+ arg.SourceUrl,+ arg.Version,+ arg.Manifest,+ arg.GrantedScopes,+ arg.Config,)var i PluginInstallationerr := row.Scan(&i.ID,&i.WorkspaceID,- &i.PluginID,- &i.SourceKind,- &i.SourceRef,- &i.DesiredReleaseID,- &i.ActiveReleaseID,+ &i.PluginKey,+ &i.SourceUrl,+ &i.Version,+ &i.Manifest,+ &i.GrantedScopes,+ &i.Config,&i.Enabled,- &i.DesiredGeneration,- &i.ActiveGeneration,- &i.LifecycleStatus,&i.InstalledBy,- &i.InstalledAt,- &i.UpdatedBy,+ &i.CreatedAt,&i.UpdatedAt,- &i.DisabledAt,- &i.UninstalledAt,)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+const upsertPluginSecret = `-- name: UpsertPluginSecret :exec+INSERT INTO plugin_secret (installation_id, key, ciphertext)+VALUES ($1, $2, $3)+ON CONFLICT (installation_id, key)+DO UPDATE SET ciphertext = EXCLUDED.ciphertext, updated_at = now()`-type UninstallPluginInstallationParams struct {- UpdatedBy pgtype.UUID `json:"updated_by"`- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`+type UpsertPluginSecretParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ Key string `json:"key"`+ Ciphertext []byte `json:"ciphertext"`}-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+func (q *Queries) UpsertPluginSecret(ctx context.Context, arg UpsertPluginSecretParams) error {+ _, err := q.db.Exec(ctx, upsertPluginSecret, arg.InstallationID, arg.Key, arg.Ciphertext)+ return err}-const updateActivePluginRemoteMCPSecret = `-- name: UpdateActivePluginRemoteMCPSecret :one-UPDATE plugin_remote_mcp_secret-SET ciphertext = $1,- hint = $2-WHERE id = $3- AND workspace_id = $4- AND installation_id = $5- AND contribution_id = $6- AND status = 'active'-RETURNING id, workspace_id, installation_id, contribution_id, version, ciphertext, hint, status, created_by, created_at, revoked_at+const upsertPluginStorageValue = `-- name: UpsertPluginStorageValue :one+INSERT INTO plugin_storage (installation_id, scope_type, scope_id, key, value)+VALUES ($1, $2, $3, $4, $5)+ON CONFLICT (installation_id, scope_type, scope_id, key)+DO UPDATE SET value = EXCLUDED.value, updated_at = now()+RETURNING id, installation_id, scope_type, scope_id, key, value, created_at, updated_at`-type UpdateActivePluginRemoteMCPSecretParams struct {- Ciphertext []byte `json:"ciphertext"`- Hint string `json:"hint"`- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`+type UpsertPluginStorageValueParams struct {InstallationID pgtype.UUID `json:"installation_id"`- ContributionID pgtype.UUID `json:"contribution_id"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`+ Key string `json:"key"`+ Value string `json:"value"`}-func (q *Queries) UpdateActivePluginRemoteMCPSecret(ctx context.Context, arg UpdateActivePluginRemoteMCPSecretParams) (PluginRemoteMcpSecret, error) {- row := q.db.QueryRow(ctx, updateActivePluginRemoteMCPSecret,- arg.Ciphertext,- arg.Hint,- arg.ID,- arg.WorkspaceID,+func (q *Queries) UpsertPluginStorageValue(ctx context.Context, arg UpsertPluginStorageValueParams) (PluginStorage, error) {+ row := q.db.QueryRow(ctx, upsertPluginStorageValue,arg.InstallationID,- arg.ContributionID,+ arg.ScopeType,+ arg.ScopeID,+ arg.Key,+ arg.Value,)- var i PluginRemoteMcpSecret+ var i PluginStorageerr := row.Scan(&i.ID,- &i.WorkspaceID,&i.InstallationID,- &i.ContributionID,- &i.Version,- &i.Ciphertext,- &i.Hint,- &i.Status,- &i.CreatedBy,+ &i.ScopeType,+ &i.ScopeID,+ &i.Key,+ &i.Value,&i.CreatedAt,- &i.RevokedAt,+ &i.UpdatedAt,)return i, err}diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 3dec3529d2..e228ed7099 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -16,7 +16,7 @@ UPDATE agent_task_queueSET status = 'cancelled', completed_at = now()WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name`type CancelAgentTasksByRuntimeOrAgentParams struct {@@ -107,7 +107,6 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, err@@ -248,7 +247,7 @@ SET status = 'failed', completed_at = now(), error = 'runtime went offline',FROM victimsWHERE task.id = victims.idAND task.status IN ('dispatched', 'running', 'waiting_local_directory')-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.plugin_execution_manifest_id, task.branch_name+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name`type FailTasksForOfflineRuntimesParams struct {@@ -325,7 +324,6 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context, arg FailTasks&i.RetiredSessionID,&i.QuickActionsDisabled,&i.RegenerateQuickActionsFor,- &i.PluginExecutionManifestID,&i.BranchName,); err != nil {return nil, errdiff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex f557674252..4a8aea4b7d 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -465,71 +465,20 @@ 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_health- WHERE workspace_id = $1-),-deleted_execution_manifests AS (- DELETE FROM plugin_execution_manifest- WHERE workspace_id = $1-),-deleted_snapshots AS (- DELETE FROM plugin_capability_snapshot- WHERE workspace_id = $1-),-deleted_workspace_state AS (- DELETE FROM plugin_workspace_capability_state- WHERE workspace_id = $1-),-deleted_remote_mcp_oauth_states AS (- DELETE FROM plugin_remote_mcp_oauth_state- WHERE workspace_id = $1-),-deleted_remote_mcp_configs AS (- DELETE FROM plugin_installation_config- WHERE workspace_id = $1-),-deleted_remote_mcp_secrets AS (- DELETE FROM plugin_remote_mcp_secret- WHERE workspace_id = $1-),-deleted_bindings AS (- DELETE FROM plugin_binding+deleted_storage AS (+ DELETE FROM plugin_storageWHERE installation_id IN (SELECT id FROM installations)),-deleted_grants AS (- DELETE FROM plugin_grant+deleted_secrets AS (+ DELETE FROM plugin_secretWHERE 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_identity WHERE id IN (SELECT id FROM private_identities)+DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations)`-// 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. Workspace-owned private registry-// rows are removed after their execution manifests have been removed.+// Plugin relationships have no foreign keys or cascades. Storage and secrets+// hang off the installation, so both leaf tables are cleared through the+// workspace's installation ids before the installations themselves.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 55ae57b914..d39e497545 100644--- a/server/pkg/db/queries/plugin.sql+++ b/server/pkg/db/queries/plugin.sql@@ -1,761 +1,109 @@--- name: LockPluginRegistryKey :exec-SELECT pg_advisory_xact_lock(hashtextextended(@plugin_key, 0));---- name: CreatePluginIdentity :one-INSERT INTO plugin_identity (- plugin_key, display_name, publisher_id, publisher_type, trust_tier,- owner_workspace_id-) VALUES (- @plugin_key, @display_name, @publisher_id, @publisher_type, @trust_tier,- sqlc.narg('owner_workspace_id')-)+-- name: CreatePluginInstallation :one+INSERT INTO plugin_installation (+ workspace_id, plugin_key, source_url, version, manifest, granted_scopes, installed_by+) VALUES ($1, $2, $3, $4, $5, $6, $7)RETURNING *;--- name: GetPluginIdentity :one-SELECT * FROM plugin_identity-WHERE id = $1;---- name: GetOfficialPluginIdentityByKey :one-SELECT * FROM plugin_identity-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 :one-UPDATE plugin_identity-SET retired_at = COALESCE(retired_at, now())+-- name: UpdatePluginInstallationManifest :one+-- Upgrade path: the re-consented manifest snapshot replaces the old one in+-- place. Config values survive on purpose; fields the new manifest dropped are+-- pruned by the service before this runs.+UPDATE plugin_installation+SET source_url = $2,+ version = $3,+ manifest = $4,+ granted_scopes = $5,+ config = $6,+ updated_at = now()WHERE id = $1RETURNING *;--- name: CreatePluginRelease :one-WITH parent AS MATERIALIZED (- SELECT plugin_identity.id- FROM plugin_identity- WHERE plugin_identity.id = @plugin_id AND plugin_identity.retired_at IS NULL- FOR KEY SHARE-)-INSERT INTO plugin_release (- plugin_id, version, manifest, manifest_digest,- source_kind, source_ref,- archive_digest, artifact_ref, artifact_digest, artifact_size,- signature, signature_key_id-)-SELECT- parent.id, @version, @manifest, @manifest_digest,- @source_kind, @source_ref,- @archive_digest, @artifact_ref, @artifact_digest, @artifact_size,- sqlc.narg('signature'), sqlc.narg('signature_key_id')-FROM parent-RETURNING *;---- name: GetPluginRelease :one-SELECT * FROM plugin_release-WHERE id = $1;---- name: GetPluginReleaseByVersion :one-SELECT * FROM plugin_release-WHERE plugin_id = $1 AND version = $2 AND revocation_status = 'active';---- name: GetRegisteredPluginReleaseByVersion :one-SELECT * FROM plugin_release-WHERE plugin_id = $1 AND version = $2;---- name: RevokePluginRelease :one-UPDATE plugin_release-SET revocation_status = @revocation_status,- revoked_at = now(),- revocation_reason = @revocation_reason-WHERE id = @id AND revocation_status = 'active'-RETURNING *;---- name: CreatePluginContribution :one-WITH parent AS MATERIALIZED (- SELECT plugin_release.id, plugin_release.artifact_digest- FROM plugin_release- WHERE plugin_release.id = @release_id AND plugin_release.revocation_status = 'active'- FOR KEY SHARE-)-INSERT INTO plugin_contribution (- release_id, contribution_key, type, schema_version,- display_name, description, entry_path, entry_digest,- artifact_digest, required_daemon_features, ordinal-)-SELECT- parent.id, @contribution_key, @type, @schema_version,- @display_name, @description, @entry_path, @entry_digest,- parent.artifact_digest, @required_daemon_features, @ordinal-FROM parent-RETURNING *;---- name: ListPluginContributionsByRelease :many-SELECT * FROM plugin_contribution-WHERE release_id = $1-ORDER BY ordinal, id;---- name: GetInstallationRemoteMCPContribution :one-SELECT contribution.*, release.manifest-FROM plugin_installation installation-JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = installation.plugin_id- AND release.revocation_status = 'active'-JOIN plugin_contribution contribution- ON contribution.release_id = release.id- AND contribution.type = 'tool.remote-mcp.v1'-WHERE installation.id = @installation_id- AND installation.workspace_id = @workspace_id- AND installation.uninstalled_at IS NULL- AND contribution.contribution_key = @contribution_key;---- name: GetInstallationRemoteMCPContributionByID :one-SELECT contribution.*, release.manifest-FROM plugin_installation installation-JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = installation.plugin_id- AND release.revocation_status = 'active'-JOIN plugin_contribution contribution- ON contribution.release_id = release.id- AND contribution.type = 'tool.remote-mcp.v1'-WHERE installation.id = @installation_id- AND installation.workspace_id = @workspace_id- AND installation.uninstalled_at IS NULL- AND contribution.id = @contribution_id;---- name: LockPluginRemoteMCPInstallation :one-SELECT installation.id-FROM plugin_installation installation-JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = installation.plugin_id- AND release.revocation_status = 'active'-JOIN plugin_contribution contribution- ON contribution.release_id = release.id- AND contribution.id = @contribution_id- AND contribution.type = 'tool.remote-mcp.v1'-WHERE installation.id = @installation_id- AND installation.workspace_id = @workspace_id- AND installation.uninstalled_at IS NULL-FOR UPDATE OF installation;---- name: CreatePluginRemoteMCPSecret :one-WITH parent AS MATERIALIZED (- SELECT installation.id, contribution.id AS contribution_id- FROM plugin_installation installation- JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = installation.plugin_id- AND release.revocation_status = 'active'- JOIN plugin_contribution contribution- ON contribution.release_id = release.id- AND contribution.id = @contribution_id- AND contribution.type = 'tool.remote-mcp.v1'- WHERE installation.id = @installation_id- AND installation.workspace_id = @workspace_id- AND installation.uninstalled_at IS NULL- FOR UPDATE OF installation- FOR KEY SHARE OF release, contribution-), next_version AS (- SELECT COALESCE(MAX(version), 0) + 1 AS version- FROM plugin_remote_mcp_secret- WHERE installation_id = @installation_id- AND contribution_id = @contribution_id-)-INSERT INTO plugin_remote_mcp_secret (- workspace_id, installation_id, contribution_id, version,- ciphertext, hint, created_by-)-SELECT- @workspace_id, parent.id, parent.contribution_id, next_version.version,- @ciphertext, @hint, sqlc.narg('created_by')-FROM parent, next_version-RETURNING *;---- name: GetActivePluginRemoteMCPSecret :one-SELECT * FROM plugin_remote_mcp_secret-WHERE id = @id- AND workspace_id = @workspace_id- AND installation_id = @installation_id- AND contribution_id = @contribution_id- AND status = 'active';---- name: GetActivePluginRemoteMCPSecretForUpdate :one-SELECT * FROM plugin_remote_mcp_secret-WHERE id = @id- AND workspace_id = @workspace_id- AND installation_id = @installation_id- AND contribution_id = @contribution_id- AND status = 'active'-FOR UPDATE;---- name: RevokePluginRemoteMCPSecrets :many-UPDATE plugin_remote_mcp_secret-SET status = 'revoked', revoked_at = now()-WHERE workspace_id = @workspace_id- AND installation_id = @installation_id- AND contribution_id = @contribution_id- AND status = 'active'-RETURNING *;---- name: UpdateActivePluginRemoteMCPSecret :one-UPDATE plugin_remote_mcp_secret-SET ciphertext = @ciphertext,- hint = @hint-WHERE id = @id- AND workspace_id = @workspace_id- AND installation_id = @installation_id- AND contribution_id = @contribution_id- AND status = 'active'-RETURNING *;---- name: CreatePluginRemoteMCPOAuthState :one-INSERT INTO plugin_remote_mcp_oauth_state (- state_hash, workspace_id, installation_id, contribution_id, actor_id,- endpoint, public_config, failure_policy,- authorization_endpoint, token_endpoint, client_id, scope,- redirect_uri, return_to, secret_ciphertext, expires_at-) VALUES (- @state_hash, @workspace_id, @installation_id, @contribution_id, @actor_id,- @endpoint, @public_config, @failure_policy,- @authorization_endpoint, @token_endpoint, @client_id, @scope,- @redirect_uri, @return_to, @secret_ciphertext, @expires_at-)-RETURNING *;---- name: ClaimPluginRemoteMCPOAuthState :one-UPDATE plugin_remote_mcp_oauth_state-SET consumed_at = now()-WHERE state_hash = @state_hash- AND consumed_at IS NULL- AND expires_at > now()-RETURNING *;---- name: DeleteExpiredPluginRemoteMCPOAuthStates :execrows-DELETE FROM plugin_remote_mcp_oauth_state-WHERE expires_at <= now() OR consumed_at < now() - interval '1 hour';---- name: CreatePluginInstallationConfig :one-WITH parent AS MATERIALIZED (- SELECT installation.id, contribution.id AS contribution_id- FROM plugin_installation installation- JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = installation.plugin_id- AND release.revocation_status = 'active'- JOIN plugin_contribution contribution- ON contribution.release_id = release.id- AND contribution.id = @contribution_id- AND contribution.type = 'tool.remote-mcp.v1'- WHERE installation.id = @installation_id- AND installation.workspace_id = @workspace_id- AND installation.uninstalled_at IS NULL- AND (- (@auth_type::text = 'none' AND sqlc.narg('secret_ref')::uuid IS NULL)- OR EXISTS (- SELECT 1 FROM plugin_remote_mcp_secret secret- WHERE secret.id = sqlc.narg('secret_ref')::uuid- AND secret.workspace_id = @workspace_id- AND secret.installation_id = installation.id- AND secret.contribution_id = contribution.id- AND secret.status = 'active'- )- )- FOR UPDATE OF installation- FOR KEY SHARE OF release, contribution-), next_revision AS (- SELECT COALESCE(MAX(revision), 0) + 1 AS revision- FROM plugin_installation_config- WHERE installation_id = @installation_id- AND contribution_id = @contribution_id-)-INSERT INTO plugin_installation_config (- workspace_id, installation_id, contribution_id, revision,- endpoint, public_config, auth_type, auth_header, secret_ref,- discovered_tools, discovered_schema_digest,- approved_tools, schema_digest, failure_policy,- reviewed_by, reviewed_at, created_by-)-SELECT- @workspace_id, parent.id, parent.contribution_id, next_revision.revision,- @endpoint, @public_config, @auth_type, @auth_header, sqlc.narg('secret_ref'),- @discovered_tools, sqlc.narg('discovered_schema_digest'),- @approved_tools, sqlc.narg('schema_digest'), @failure_policy,- sqlc.narg('reviewed_by'),- CASE WHEN sqlc.narg('reviewed_by')::uuid IS NULL THEN NULL ELSE now() END,- sqlc.narg('created_by')-FROM parent, next_revision+-- name: UpdatePluginInstallationConfig :one+UPDATE plugin_installation+SET config = $2,+ updated_at = now()+WHERE id = $1RETURNING *;--- name: GetLatestPluginInstallationConfig :one-SELECT * FROM plugin_installation_config-WHERE workspace_id = @workspace_id- AND installation_id = @installation_id- AND contribution_id = @contribution_id-ORDER BY revision DESC-LIMIT 1;---- name: ListLatestPluginInstallationConfigs :many-SELECT DISTINCT ON (config.contribution_id) config.*-FROM plugin_installation_config config-WHERE config.workspace_id = @workspace_id- AND config.installation_id = @installation_id-ORDER BY config.contribution_id, config.revision DESC;---- name: ListPluginReleasesByPlugin :many-SELECT * FROM plugin_release-WHERE plugin_id = $1 AND revocation_status = 'active'-ORDER BY published_at DESC, id DESC;---- name: CreatePluginInstallation :one-WITH parents AS MATERIALIZED (- SELECT w.id AS workspace_id, p.id AS plugin_id, r.id AS release_id,- r.source_kind, r.source_ref- FROM workspace w- JOIN plugin_identity p ON p.id = @plugin_id AND p.retired_at IS NULL- JOIN plugin_release r ON r.id = @release_id- AND r.plugin_id = p.id- AND r.revocation_status = 'active'- WHERE w.id = @workspace_id- FOR KEY SHARE OF w, p, r-)-INSERT INTO plugin_installation (- workspace_id, plugin_id, source_kind, source_ref,- desired_release_id, enabled, lifecycle_status,- installed_by, updated_by-)-SELECT- parents.workspace_id, parents.plugin_id, parents.source_kind, parents.source_ref,- parents.release_id, FALSE, 'installed',- sqlc.narg('installed_by'), sqlc.narg('installed_by')-FROM parents+-- name: SetPluginInstallationEnabled :one+UPDATE plugin_installation+SET enabled = $2,+ updated_at = now()+WHERE id = $1RETURNING *;-- name: GetPluginInstallation :one-SELECT * FROM plugin_installation-WHERE id = $1;+SELECT * FROM plugin_installation WHERE id = $1;-- name: GetWorkspacePluginInstallation :oneSELECT * FROM plugin_installation-WHERE workspace_id = $1 AND plugin_id = $2 AND uninstalled_at IS NULL;+WHERE workspace_id = $1 AND id = $2;--- name: ListWorkspacePluginInstallations :many+-- name: GetWorkspacePluginInstallationByKey :oneSELECT * FROM plugin_installation-WHERE workspace_id = $1 AND uninstalled_at IS NULL-ORDER 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 :one-WITH workspace_guard AS MATERIALIZED (- SELECT workspace.id- FROM workspace- WHERE workspace.id = @workspace_id- FOR KEY SHARE-),-target AS MATERIALIZED (- SELECT i.id, r.id AS release_id- FROM plugin_installation i- JOIN workspace_guard w ON w.id = i.workspace_id- JOIN plugin_release r ON r.id = @desired_release_id- AND r.plugin_id = i.plugin_id- AND r.revocation_status = 'active'- WHERE i.id = @id- AND i.workspace_id = @workspace_id- AND i.uninstalled_at IS NULL- FOR UPDATE OF i-)-UPDATE plugin_installation i-SET desired_release_id = target.release_id,- enabled = @enabled,- desired_generation = i.desired_generation + 1,- lifecycle_status = 'activating',- updated_by = sqlc.narg('updated_by'),- updated_at = now(),- disabled_at = CASE WHEN @enabled::boolean THEN NULL ELSE now() END-FROM target-WHERE i.id = target.id-RETURNING 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 :one-WITH target AS MATERIALIZED (- SELECT i.id- FROM plugin_installation i- JOIN workspace w ON w.id = i.workspace_id- WHERE i.id = @installation_id- AND i.workspace_id = @workspace_id- AND i.uninstalled_at IS NULL- FOR UPDATE OF i- FOR KEY SHARE OF w-),-next_revision AS (- SELECT COALESCE(MAX(g.grant_revision), 0) + 1 AS revision- FROM plugin_grant g- JOIN target ON target.id = g.installation_id- WHERE g.capability = @capability-)-INSERT INTO plugin_grant (- installation_id, capability, decision, limits,- grant_revision, approved_by, revoked_at-)-SELECT- target.id, @capability, @decision, @limits,- next_revision.revision, sqlc.narg('approved_by'),- CASE WHEN @decision::text = 'denied' THEN now() ELSE NULL END-FROM target CROSS JOIN next_revision-RETURNING *;---- name: ListLatestPluginGrants :many-SELECT DISTINCT ON (capability) *-FROM plugin_grant-WHERE installation_id = $1-ORDER BY capability, grant_revision DESC;---- name: CreatePluginBindingRevision :one-WITH workspace_scope AS MATERIALIZED (- SELECT i.id- FROM plugin_installation i- JOIN workspace w ON w.id = i.workspace_id- WHERE @scope_type::text = 'workspace'- AND i.id = @installation_id- AND i.workspace_id = @workspace_id- AND @scope_id::uuid = i.workspace_id- AND i.uninstalled_at IS NULL- FOR UPDATE OF i- FOR KEY SHARE OF w-),-agent_scope AS MATERIALIZED (- SELECT i.id- FROM plugin_installation i- JOIN workspace w ON w.id = i.workspace_id- JOIN agent a ON a.id = @scope_id AND a.workspace_id = i.workspace_id- WHERE @scope_type::text = 'agent'- AND i.id = @installation_id- AND i.workspace_id = @workspace_id- AND i.uninstalled_at IS NULL- FOR UPDATE OF i- FOR KEY SHARE OF w, a-),-target AS MATERIALIZED (- SELECT id FROM workspace_scope- UNION ALL- SELECT id FROM agent_scope-),-next_revision AS (- SELECT COALESCE(MAX(b.binding_revision), 0) + 1 AS revision- FROM plugin_binding b- JOIN target ON target.id = b.installation_id- WHERE b.scope_type = @scope_type AND b.scope_id = @scope_id-)-INSERT INTO plugin_binding (- installation_id, scope_type, scope_id, enabled,- binding_revision, created_by-)-SELECT- target.id, @scope_type, @scope_id, @enabled,- next_revision.revision, sqlc.narg('created_by')-FROM target CROSS JOIN next_revision-RETURNING *;---- name: ListLatestPluginBindings :many-SELECT DISTINCT ON (scope_type, scope_id) *-FROM plugin_binding-WHERE installation_id = $1-ORDER BY scope_type, scope_id, binding_revision DESC;---- name: CreatePluginArtifactFile :one-WITH parent AS MATERIALIZED (- SELECT plugin_release.id- FROM plugin_release- WHERE plugin_release.id = @release_id- FOR KEY SHARE-)-INSERT INTO plugin_artifact_file (- release_id, path, digest, size_bytes, content-)-SELECT parent.id, @path, @digest, @size_bytes, @content-FROM parent-RETURNING *;---- name: GetPluginArtifactFileByReleasePath :one-SELECT * FROM plugin_artifact_file-WHERE release_id = $1 AND path = $2;---- name: GetPluginArtifactFile :one-SELECT * FROM plugin_artifact_file-WHERE id = $1;---- name: ListPluginArtifactFilesByRelease :many-SELECT * FROM plugin_artifact_file-WHERE release_id = $1-ORDER BY path, id;+WHERE workspace_id = $1 AND plugin_key = $2;--- name: ListPluginArtifactFilesByIDs :many-SELECT * FROM plugin_artifact_file-WHERE id = ANY(@ids::uuid[])-ORDER BY path, id;---- name: GetLatestPluginRelease :one-SELECT release.*-FROM plugin_release release-JOIN plugin_identity identity ON identity.id = release.plugin_id-WHERE identity.plugin_key = @plugin_key- AND identity.retired_at IS NULL- AND release.revocation_status = 'active'-ORDER BY release.published_at DESC, release.id DESC-LIMIT 1;---- name: GetPluginReleaseByPluginKeyVersion :one-SELECT release.*-FROM plugin_release release-JOIN plugin_identity identity ON identity.id = release.plugin_id-WHERE identity.plugin_key = @plugin_key- AND identity.owner_workspace_id IS NULL- AND identity.retired_at IS NULL- AND release.version = @version- AND release.revocation_status = 'active';---- name: EnsurePluginWorkspaceCapabilityState :one-WITH workspace_guard AS MATERIALIZED (- SELECT workspace.id- FROM workspace- WHERE workspace.id = @workspace_id- FOR KEY SHARE-)-INSERT INTO plugin_workspace_capability_state (workspace_id)-SELECT workspace_guard.id FROM workspace_guard-ON CONFLICT (workspace_id) DO UPDATE-SET workspace_id = EXCLUDED.workspace_id-RETURNING *;---- name: GetPluginWorkspaceCapabilityStateForUpdate :one-SELECT * FROM plugin_workspace_capability_state-WHERE workspace_id = $1-FOR UPDATE;---- name: ListPluginInstallationsForCompile :many+-- name: ListWorkspacePluginInstallations :manySELECT * FROM plugin_installation-WHERE workspace_id = $1 AND uninstalled_at IS NULL-ORDER BY id-FOR UPDATE;---- name: ListPluginCompilationContributions :many-WITH latest_grants AS (- SELECT DISTINCT ON (installation_id, capability)- installation_id, capability, decision, limits, grant_revision- FROM plugin_grant- ORDER BY installation_id, capability, grant_revision DESC-),-latest_bindings AS (- SELECT DISTINCT ON (installation_id, scope_type, scope_id)- installation_id, scope_type, scope_id, enabled, binding_revision- FROM plugin_binding- ORDER BY installation_id, scope_type, scope_id, binding_revision DESC-),-latest_configs AS (- SELECT DISTINCT ON (installation_id, contribution_id) *- FROM plugin_installation_config- WHERE workspace_id = @workspace_id- ORDER BY installation_id, contribution_id, revision DESC-)-SELECT- installation.id AS installation_id,- installation.workspace_id,- installation.desired_generation,- identity.id AS plugin_id,- identity.plugin_key,- release.id AS release_id,- release.version AS release_version,- release.source_kind,- release.artifact_ref,- release.artifact_digest,- contribution.id AS contribution_id,- contribution.contribution_key,- contribution.type AS contribution_type,- contribution.display_name,- contribution.description,- contribution.entry_path,- contribution.entry_digest,- contribution.required_daemon_features,- contribution.ordinal,- artifact.id AS artifact_file_id,- artifact.content AS entry_content,- artifact.size_bytes AS entry_size_bytes,- binding.scope_type,- binding.scope_id,- binding.enabled AS binding_enabled,- binding.binding_revision,- grant_row.grant_revision,- config.id AS config_id,- config.revision AS config_revision,- config.endpoint,- config.public_config,- config.auth_type,- config.auth_header,- config.secret_ref,- config.approved_tools,- config.schema_digest,- config.failure_policy,- config.reviewed_at-FROM plugin_installation installation-JOIN plugin_identity identity- ON identity.id = installation.plugin_id-JOIN plugin_release release- ON release.id = installation.desired_release_id- AND release.plugin_id = identity.id- AND release.revocation_status = 'active'-JOIN plugin_contribution contribution- ON contribution.release_id = release.id-JOIN plugin_artifact_file artifact- ON artifact.release_id = release.id- AND artifact.path = contribution.entry_path-JOIN latest_grants grant_row- ON grant_row.installation_id = installation.id- AND grant_row.capability = CASE contribution.type- WHEN 'agent.skill.v1' THEN 'agent.skill.contribute'- WHEN 'tool.remote-mcp.v1' THEN 'tool.remote-mcp.connect'- END- AND grant_row.decision = 'granted'-LEFT JOIN latest_configs config- ON config.installation_id = installation.id- AND config.contribution_id = contribution.id-LEFT JOIN latest_bindings binding- ON binding.installation_id = installation.id-WHERE installation.workspace_id = @workspace_id- AND installation.uninstalled_at IS NULL- AND installation.enabled = TRUE- AND (- contribution.type = 'agent.skill.v1'- OR (- contribution.type = 'tool.remote-mcp.v1'- AND config.reviewed_at IS NOT NULL- AND jsonb_array_length(config.approved_tools) > 0- )- )-ORDER BY identity.plugin_key, contribution.ordinal,- contribution.contribution_key,- binding.scope_type NULLS FIRST, binding.scope_id NULLS FIRST;---- name: CreatePluginCapabilitySnapshot :one-INSERT INTO plugin_capability_snapshot (- workspace_id, revision, source_generations,- compiler_version, schema_version, snapshot_digest,- compiled_entries, diagnostics-) VALUES (- @workspace_id, @revision, @source_generations,- @compiler_version, @schema_version, @snapshot_digest,- @compiled_entries, @diagnostics-)-RETURNING *;---- name: ActivatePluginWorkspaceCapabilitySnapshot :one-UPDATE plugin_workspace_capability_state-SET active_snapshot_id = @active_snapshot_id,- active_revision = @active_revision,- next_revision = @next_revision,- updated_at = now()-WHERE workspace_id = @workspace_id- AND next_revision = @active_revision-RETURNING *;---- name: ActivatePluginInstallations :many-UPDATE plugin_installation-SET active_release_id = desired_release_id,- active_generation = desired_generation,- lifecycle_status = CASE WHEN enabled THEN 'active' ELSE 'installed' END,- updated_at = now()WHERE workspace_id = $1- AND uninstalled_at IS NULL-RETURNING *;---- name: CreatePluginHealth :one-INSERT INTO plugin_health (- workspace_id, installation_id, scope_type, scope_id,- state, reason_code, safe_detail,- observed_generation, last_good_snapshot_id-) VALUES (- @workspace_id, @installation_id, @scope_type, sqlc.narg('scope_id'),- @state, @reason_code, @safe_detail,- @observed_generation, sqlc.narg('last_good_snapshot_id')-)-RETURNING *;+ORDER BY created_at ASC;++-- name: DeletePluginInstallation :exec+DELETE FROM plugin_installation WHERE id = $1;++-- name: UpsertPluginStorageValue :one+INSERT INTO plugin_storage (installation_id, scope_type, scope_id, key, value)+VALUES ($1, $2, $3, $4, $5)+ON CONFLICT (installation_id, scope_type, scope_id, key)+DO UPDATE SET value = EXCLUDED.value, updated_at = now()+RETURNING *;++-- name: GetPluginStorageValue :one+SELECT * FROM plugin_storage+WHERE installation_id = $1 AND scope_type = $2 AND scope_id = $3 AND key = $4;++-- name: ListPluginStorageKeys :many+SELECT key, octet_length(value)::bigint AS size_bytes, updated_at+FROM plugin_storage+WHERE installation_id = $1 AND scope_type = $2 AND scope_id = $3+ORDER BY key ASC;++-- name: DeletePluginStorageValue :execrows+DELETE FROM plugin_storage+WHERE installation_id = $1 AND scope_type = $2 AND scope_id = $3 AND key = $4;++-- name: GetPluginStorageUsage :one+-- Quota accounting for one (installation, scope) pair. The candidate key is+-- excluded so overwriting an existing key is measured as a replacement rather+-- than an addition. octet_length, not char_length: the service compares these+-- against byte budgets, and a UTF-8 character is up to 4 bytes.+SELECT COUNT(*)::bigint AS key_count,+ COALESCE(SUM(octet_length(value)), 0)::bigint AS total_bytes+FROM plugin_storage+WHERE installation_id = $1 AND scope_type = $2 AND scope_id = $3 AND key <> $4;++-- name: DeletePluginStorageByInstallation :exec+DELETE FROM plugin_storage WHERE installation_id = $1;++-- name: UpsertPluginSecret :exec+INSERT INTO plugin_secret (installation_id, key, ciphertext)+VALUES ($1, $2, $3)+ON CONFLICT (installation_id, key)+DO UPDATE SET ciphertext = EXCLUDED.ciphertext, updated_at = now();++-- name: ListPluginSecretKeys :many+-- Deliberately never selects ciphertext: the presence of a secret is readable,+-- its value is not.+SELECT key, updated_at FROM plugin_secret+WHERE installation_id = $1+ORDER BY key ASC;--- name: GetPluginExecutionManifestByTask :one-SELECT manifest.*-FROM plugin_execution_manifest manifest-JOIN agent_task_queue task- ON task.plugin_execution_manifest_id = manifest.id-WHERE task.id = @task_id- AND manifest.task_id = task.id;+-- name: GetPluginSecret :one+SELECT * FROM plugin_secret+WHERE installation_id = $1 AND key = $2;--- name: ListWorkspacePluginHealth :many-SELECT * FROM plugin_health-WHERE workspace_id = $1-ORDER BY observed_at DESC, id DESC;+-- name: DeletePluginSecret :execrows+DELETE FROM plugin_secret WHERE installation_id = $1 AND key = $2;--- 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;+-- name: DeletePluginSecretsByInstallation :exec+DELETE FROM plugin_secret WHERE installation_id = $1;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 88c5adcaec..aa31b2df33 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -568,74 +568,23 @@ WITH deleted_squads AS (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. Workspace-owned private registry--- rows are removed after their execution manifests have been removed.+-- Plugin relationships have no foreign keys or cascades. Storage and secrets+-- hang off the installation, so both leaf tables are cleared through the+-- workspace's installation ids before the installations themselves.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_health- WHERE workspace_id = $1-),-deleted_execution_manifests AS (- DELETE FROM plugin_execution_manifest- WHERE workspace_id = $1-),-deleted_snapshots AS (- DELETE FROM plugin_capability_snapshot- WHERE workspace_id = $1-),-deleted_workspace_state AS (- DELETE FROM plugin_workspace_capability_state- WHERE workspace_id = $1-),-deleted_remote_mcp_oauth_states AS (- DELETE FROM plugin_remote_mcp_oauth_state- WHERE workspace_id = $1-),-deleted_remote_mcp_configs AS (- DELETE FROM plugin_installation_config- WHERE workspace_id = $1-),-deleted_remote_mcp_secrets AS (- DELETE FROM plugin_remote_mcp_secret- WHERE workspace_id = $1-),-deleted_bindings AS (- DELETE FROM plugin_binding+deleted_storage AS (+ DELETE FROM plugin_storageWHERE installation_id IN (SELECT id FROM installations)),-deleted_grants AS (- DELETE FROM plugin_grant+deleted_secrets AS (+ DELETE FROM plugin_secretWHERE 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_identity WHERE id IN (SELECT id FROM private_identities);+DELETE FROM plugin_installation WHERE id IN (SELECT id FROM installations);-- name: DeleteWorkspaceAgents :execDELETE FROM agent WHERE agent.workspace_id = $1;diff --git a/server/pkg/plugincontract/artifact.go b/server/pkg/plugincontract/artifact.godeleted file mode 100644index 37cb767a76..0000000000--- a/server/pkg/plugincontract/artifact.go+++ /dev/null@@ -1,262 +0,0 @@-package plugincontract--import (- "archive/zip"- "bytes"- "crypto/sha256"- "encoding/hex"- "fmt"- "io"- "path"- "sort"- "strings"- "unicode/utf8"-)--const (- MaxArchiveSize = 16 << 20- MaxArtifactSize = 32 << 20- MaxArtifactFiles = 1024- MaxFileSize = 1 << 20- MaxSkillSize = 8 << 20- MaxSkillFiles = 256-- ThirdPartyLicensesRoot = "THIRD_PARTY_LICENSES/"-)--type Artifact struct {- Manifest Manifest- CanonicalManifest []byte- ArchiveDigest string- ArtifactDigest string- SizeBytes int64- Files []ArtifactFile-}--type ArtifactFile struct {- Path string- Content []byte- Digest string- SizeBytes int64-}--// ValidateArtifact verifies an uploaded ZIP without extracting it to disk. It-// accepts only regular UTF-8 text files under declared contribution roots or-// the non-executable third-party license root and returns content-addressed-// metadata suitable for immutable release storage.-func ValidateArtifact(archive []byte) (Artifact, error) {- if len(archive) == 0 {- return Artifact{}, fmt.Errorf("plugin archive is empty")- }- if len(archive) > MaxArchiveSize {- return Artifact{}, fmt.Errorf("plugin archive exceeds %d bytes", MaxArchiveSize)- }-- reader, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive)))- if err != nil {- return Artifact{}, fmt.Errorf("open plugin archive: %w", err)- }-- files := make(map[string]ArtifactFile, len(reader.File))- caseFolded := make(map[string]string, len(reader.File))- var totalSize int64- for _, zipped := range reader.File {- name, isDirectory, err := validateArchivePath(zipped.Name)- if err != nil {- return Artifact{}, err- }- 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)- }- if prior, exists := caseFolded[strings.ToLower(name)]; exists {- return Artifact{}, fmt.Errorf("plugin archive path %q collides with %q", name, prior)- }- caseFolded[strings.ToLower(name)] = name-- mode := zipped.Mode()- if !mode.IsRegular() {- return Artifact{}, fmt.Errorf("plugin archive path %q is not a regular file", name)- }- if mode.Perm()&0o111 != 0 {- return Artifact{}, fmt.Errorf("plugin archive path %q is executable", name)- }- if zipped.UncompressedSize64 > MaxFileSize {- return Artifact{}, fmt.Errorf("plugin archive path %q exceeds %d bytes", name, MaxFileSize)- }-- content, err := readZipFile(zipped)- if err != nil {- return Artifact{}, fmt.Errorf("read plugin archive path %q: %w", name, err)- }- if !utf8.Valid(content) {- return Artifact{}, fmt.Errorf("plugin archive path %q is not UTF-8 text", name)- }- totalSize += int64(len(content))- if totalSize > MaxArtifactSize {- return Artifact{}, fmt.Errorf("plugin artifact exceeds %d uncompressed bytes", MaxArtifactSize)- }- files[name] = ArtifactFile{- Path: name,- Content: content,- Digest: DigestBytes(content),- SizeBytes: int64(len(content)),- }- }-- manifestFile, ok := files[ManifestFilename]- if !ok {- return Artifact{}, fmt.Errorf("plugin archive is missing root %s", ManifestFilename)- }- manifest, canonicalManifest, err := ParseManifest(manifestFile.Content)- if err != nil {- return Artifact{}, err- }- totalSize += int64(len(canonicalManifest) - len(manifestFile.Content))- manifestFile.Content = canonicalManifest- manifestFile.Digest = DigestBytes(canonicalManifest)- manifestFile.SizeBytes = int64(len(canonicalManifest))- files[ManifestFilename] = manifestFile-- allowedRoots := make(map[string]AgentSkillContribution, len(manifest.Contributes.AgentSkills))- for _, contribution := range manifest.Contributes.AgentSkills {- root := "skills/" + contribution.Key + "/"- allowedRoots[root] = contribution- if _, ok := files[contribution.Entry]; !ok {- return Artifact{}, fmt.Errorf("contribution %q entry %q is missing", contribution.Key, contribution.Entry)- }- }-- counts := make(map[string]int, len(allowedRoots))- sizes := make(map[string]int64, len(allowedRoots))- for name, file := range files {- if name == ManifestFilename {- continue- }- if isThirdPartyLicensePath(name) {- continue- }- root := contributionRoot(name, allowedRoots)- if root == "" {- return Artifact{}, fmt.Errorf("plugin archive path %q is outside a declared contribution", name)- }- if name != allowedRoots[root].Entry && skillCompanionCollidesWithEntry(name, root) {- return Artifact{}, fmt.Errorf("plugin archive path %q collides with reserved primary Skill content", name)- }- counts[root]++- sizes[root] += file.SizeBytes- if counts[root] > MaxSkillFiles {- return Artifact{}, fmt.Errorf("contribution %q exceeds %d files", allowedRoots[root].Key, MaxSkillFiles)- }- if sizes[root] > MaxSkillSize {- return Artifact{}, fmt.Errorf("contribution %q exceeds %d bytes", allowedRoots[root].Key, MaxSkillSize)- }- }-- ordered := make([]ArtifactFile, 0, len(files))- for _, file := range files {- ordered = append(ordered, file)- }- sort.Slice(ordered, func(i, j int) bool { return ordered[i].Path < ordered[j].Path })-- return Artifact{- Manifest: manifest,- CanonicalManifest: canonicalManifest,- ArchiveDigest: DigestBytes(archive),- ArtifactDigest: digestArtifactFiles(ordered),- SizeBytes: totalSize,- Files: ordered,- }, nil-}--func skillCompanionCollidesWithEntry(name, root string) bool {- relative := strings.TrimPrefix(name, root)- firstSegment := relative- if separator := strings.IndexByte(relative, '/'); separator >= 0 {- firstSegment = relative[:separator]- }- return strings.EqualFold(firstSegment, "SKILL.md")-}--func isThirdPartyLicensePath(name string) bool {- relative := strings.TrimPrefix(name, ThirdPartyLicensesRoot)- return relative != name && relative != ""-}--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)- }- isDirectory := strings.HasSuffix(name, "/")- trimmed := strings.TrimSuffix(name, "/")- if trimmed == "" || path.Clean(trimmed) != trimmed || trimmed == "." || strings.HasPrefix(trimmed, "../") {- return "", false, fmt.Errorf("plugin archive path %q is unsafe", name)- }- return trimmed, isDirectory, nil-}--func readZipFile(file *zip.File) ([]byte, error) {- reader, err := file.Open()- if err != nil {- return nil, err- }- defer reader.Close()-- content, err := io.ReadAll(io.LimitReader(reader, MaxFileSize+1))- if err != nil {- return nil, err- }- if len(content) > MaxFileSize {- return nil, fmt.Errorf("file exceeds %d bytes", MaxFileSize)- }- return content, nil-}--func contributionRoot(name string, roots map[string]AgentSkillContribution) string {- for root := range roots {- if strings.HasPrefix(name, root) {- return root- }- }- return ""-}--func digestArtifactFiles(files []ArtifactFile) string {- hash := sha256.New()- writeDigestPart(hash, "multica.plugin.artifact/v1")- for _, file := range files {- writeDigestPart(hash, file.Path)- writeDigestPart(hash, file.Digest)- writeDigestPart(hash, fmt.Sprintf("%d", file.SizeBytes))- }- return "sha256:" + hex.EncodeToString(hash.Sum(nil))-}--func writeDigestPart(writer io.Writer, value string) {- _, _ = fmt.Fprintf(writer, "%d:%s\n", len(value), value)-}--func DigestBytes(content []byte) string {- digest := sha256.Sum256(content)- return "sha256:" + hex.EncodeToString(digest[:])-}diff --git a/server/pkg/plugincontract/artifact_test.go b/server/pkg/plugincontract/artifact_test.godeleted file mode 100644index ae955a16ba..0000000000--- a/server/pkg/plugincontract/artifact_test.go+++ /dev/null@@ -1,174 +0,0 @@-package plugincontract--import (- "archive/zip"- "bytes"- "io/fs"- "strings"- "testing"-)--type zipFixtureFile struct {- name string- content []byte- mode fs.FileMode-}--func buildArchive(t *testing.T, files []zipFixtureFile) []byte {- t.Helper()- var buffer bytes.Buffer- writer := zip.NewWriter(&buffer)- for _, file := range files {- header := &zip.FileHeader{Name: file.name, Method: zip.Deflate}- mode := file.mode- if mode == 0 {- mode = 0o600- }- header.SetMode(mode)- entry, err := writer.CreateHeader(header)- if err != nil {- t.Fatalf("create zip entry %s: %v", file.name, err)- }- if _, err := entry.Write(file.content); err != nil {- t.Fatalf("write zip entry %s: %v", file.name, err)- }- }- if err := writer.Close(); err != nil {- t.Fatalf("close zip: %v", err)- }- return buffer.Bytes()-}--func referenceArchiveFiles(t *testing.T) []zipFixtureFile {- t.Helper()- return []zipFixtureFile{- {name: ManifestFilename, content: manifestJSON(t, validManifest())},- {name: "skills/review-readiness/SKILL.md", content: []byte("---\nname: review-readiness\n---\nReview the evidence.\n")},- {name: "skills/review-readiness/references/checklist.md", content: []byte("- Tests\n- Rollback\n")},- }-}--func TestValidateArtifactAcceptsReferencePlugin(t *testing.T) {- archive := buildArchive(t, referenceArchiveFiles(t))- artifact, err := ValidateArtifact(archive)- if err != nil {- t.Fatalf("ValidateArtifact: %v", err)- }- if artifact.Manifest.Metadata.Key != "ai.multica.software-delivery" {- t.Fatalf("plugin key = %q", artifact.Manifest.Metadata.Key)- }- if !validSHA256Digest(artifact.ArchiveDigest) || !validSHA256Digest(artifact.ArtifactDigest) {- t.Fatalf("invalid digests: archive=%q artifact=%q", artifact.ArchiveDigest, artifact.ArtifactDigest)- }- if len(artifact.Files) != 3 {- t.Fatalf("files = %d, want 3", len(artifact.Files))- }-}--func TestValidateArtifactAcceptsRemoteMCPOnlyPlugin(t *testing.T) {- archive := buildArchive(t, []zipFixtureFile{{- name: ManifestFilename, content: manifestJSON(t, validRemoteMCPManifest()),- }})- artifact, err := ValidateArtifact(archive)- if err != nil {- t.Fatalf("ValidateArtifact: %v", err)- }- if len(artifact.Files) != 1 || len(artifact.Manifest.Contributes.RemoteMCP) != 1 {- t.Fatalf("remote-only artifact files = %d, contributions = %d", len(artifact.Files), len(artifact.Manifest.Contributes.RemoteMCP))- }-}--func TestValidateArtifactAcceptsThirdPartyLicenseFiles(t *testing.T) {- files := append(referenceArchiveFiles(t), zipFixtureFile{- name: ThirdPartyLicensesRoot + "dependency-MIT.txt",- content: []byte("MIT License\n\nCopyright dependency author\n"),- })- artifact, err := ValidateArtifact(buildArchive(t, files))- if err != nil {- t.Fatalf("ValidateArtifact: %v", err)- }- if len(artifact.Files) != 4 {- t.Fatalf("files = %d, want 4", len(artifact.Files))- }-}--func TestArtifactDigestIgnoresZipEntryOrder(t *testing.T) {- files := referenceArchiveFiles(t)- reversed := []zipFixtureFile{files[2], files[1], files[0]}-- first, err := ValidateArtifact(buildArchive(t, files))- if err != nil {- t.Fatalf("ValidateArtifact first: %v", err)- }- second, err := ValidateArtifact(buildArchive(t, reversed))- if err != nil {- t.Fatalf("ValidateArtifact second: %v", err)- }- if first.ArtifactDigest != second.ArtifactDigest {- t.Fatalf("artifact digest depends on zip order: %s != %s", first.ArtifactDigest, second.ArtifactDigest)- }- if first.ArchiveDigest == second.ArchiveDigest {- t.Fatal("raw archive digests unexpectedly match across zip order")- }-}--func TestValidateArtifactRejectsUnsafeOrUnownedFiles(t *testing.T) {- tests := []struct {- name string- file zipFixtureFile- wantErr string- }{- {name: "traversal", file: zipFixtureFile{name: "../escape.md", content: []byte("no")}, wantErr: "unsafe"},- {name: "backslash", file: zipFixtureFile{name: `skills\escape.md`, content: []byte("no")}, wantErr: "unsafe"},- {name: "unowned", file: zipFixtureFile{name: "README.md", content: []byte("no")}, wantErr: "outside a declared contribution"},- {name: "primary content descendant", file: zipFixtureFile{name: "skills/review-readiness/SKILL.md/hidden.txt", content: []byte("no")}, wantErr: "reserved primary Skill content"},- {name: "executable", file: zipFixtureFile{name: "skills/review-readiness/run.sh", content: []byte("echo no"), mode: 0o700}, wantErr: "executable"},- {name: "symlink", file: zipFixtureFile{name: "skills/review-readiness/link", content: []byte("target"), mode: fs.ModeSymlink | 0o777}, wantErr: "not a regular file"},- {name: "binary", file: zipFixtureFile{name: "skills/review-readiness/binary", content: []byte{0xff, 0xfe}}, wantErr: "not UTF-8 text"},- }-- for _, test := range tests {- t.Run(test.name, func(t *testing.T) {- files := append(referenceArchiveFiles(t), test.file)- _, err := ValidateArtifact(buildArchive(t, files))- if err == nil || !strings.Contains(err.Error(), test.wantErr) {- t.Fatalf("ValidateArtifact error = %v, want containing %q", err, test.wantErr)- }- })- }-}--func TestValidateArtifactRejectsCaseFoldedCollision(t *testing.T) {- files := append(referenceArchiveFiles(t), zipFixtureFile{- name: "skills/review-readiness/skill.md",- content: []byte("collision"),- })- _, err := ValidateArtifact(buildArchive(t, files))- if err == nil || !strings.Contains(err.Error(), "collides") {- t.Fatalf("ValidateArtifact collision error = %v", err)- }-}--func TestValidateArtifactRejectsMissingDeclaredEntry(t *testing.T) {- files := referenceArchiveFiles(t)- files = []zipFixtureFile{files[0], files[2]}- _, err := ValidateArtifact(buildArchive(t, files))- if err == nil || !strings.Contains(err.Error(), "entry") {- 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/capabilities.go b/server/pkg/plugincontract/capabilities.gonew file mode 100644index 0000000000..55988975cd--- /dev/null+++ b/server/pkg/plugincontract/capabilities.go@@ -0,0 +1,80 @@+package plugincontract++import (+ "fmt"+ "sort"+ "strings"+)++// Capabilities is what this host build can actually run. The manifest schema is+// defined in full from the first release so publishers never chase a moving+// contract, but the host lands the machinery one slice at a time. Anything a+// manifest declares that is not listed here fails installation loudly — a+// silently ignored contribution would look installed and never fire.+//+// Flip an entry on in the same change that lands its runtime.+type Capabilities struct {+ SurfaceTypes map[string]bool+ HookTriggers map[string]bool+ HookTransport map[string]bool+ ResourceTypes map[string]bool+}++// HostCapabilities is the currently shipped set.+//+// Action API + issue/sidebar surfaces land with the surface runtime; hooks land+// with the hook engine; the agent trigger, the mcp transport, and skill+// resources land with the agent integration.+func HostCapabilities() Capabilities {+ return Capabilities{+ SurfaceTypes: map[string]bool{},+ HookTriggers: map[string]bool{},+ HookTransport: map[string]bool{},+ ResourceTypes: map[string]bool{},+ }+}++// ErrCapabilityUnavailable describes contributions this build cannot run yet.+type ErrCapabilityUnavailable struct {+ Missing []string+}++func (e *ErrCapabilityUnavailable) Error() string {+ return fmt.Sprintf("this Multica version does not support: %s", strings.Join(e.Missing, ", "))+}++// CheckCapabilities reports every declared contribution the host cannot run.+// It returns all of them at once so an administrator sees the full gap instead+// of discovering it one failed install at a time.+func (m Manifest) CheckCapabilities(host Capabilities) error {+ missing := map[string]bool{}+ for _, surface := range m.Contributes.Surfaces {+ if !host.SurfaceTypes[surface.Type] {+ missing["surface "+surface.Type] = true+ }+ }+ for _, hook := range m.Contributes.Hooks {+ for _, trigger := range hook.Triggers {+ if !host.HookTriggers[trigger] {+ missing["hook trigger "+trigger] = true+ }+ }+ if !host.HookTransport[hook.Transport.Type] {+ missing["hook transport "+hook.Transport.Type] = true+ }+ }+ for _, resource := range m.Contributes.Resources {+ if !host.ResourceTypes[resource.Type] {+ missing["resource "+resource.Type] = true+ }+ }+ if len(missing) == 0 {+ return nil+ }+ names := make([]string, 0, len(missing))+ for name := range missing {+ names = append(names, name)+ }+ sort.Strings(names)+ return &ErrCapabilityUnavailable{Missing: names}+}diff --git a/server/pkg/plugincontract/examples_test.go b/server/pkg/plugincontract/examples_test.godeleted file mode 100644index 628dc5fc79..0000000000--- a/server/pkg/plugincontract/examples_test.go+++ /dev/null@@ -1,33 +0,0 @@-package plugincontract--import (- "os"- "path/filepath"- "testing"-)--func TestExamplePluginsSatisfyArtifactContract(t *testing.T) {- root := filepath.Join("..", "..", "..", "examples", "plugins")- entries, err := os.ReadDir(root)- if err != nil {- t.Fatalf("read example plugins: %v", err)- }-- for _, entry := range entries {- if !entry.IsDir() {- continue- }- source := filepath.Join(root, entry.Name())- if _, err := os.Stat(filepath.Join(source, ManifestFilename)); err != nil {- if os.IsNotExist(err) {- continue- }- t.Fatalf("inspect %s manifest: %v", entry.Name(), err)- }- t.Run(entry.Name(), func(t *testing.T) {- if _, _, err := PackDirectory(source); err != nil {- t.Fatalf("pack example plugin: %v", err)- }- })- }-}diff --git a/server/pkg/plugincontract/manifest.go b/server/pkg/plugincontract/manifest.goindex ca73b3beeb..45787a9c4f 100644--- a/server/pkg/plugincontract/manifest.go+++ b/server/pkg/plugincontract/manifest.go@@ -1,6 +1,15 @@-// Package plugincontract defines the versioned public contract between Plugin-// publishers and the Multica host. It must remain independent from private-// handlers, services, and database implementations.+// Package plugincontract defines the versioned public contract between plugin+// authors and the Multica host. It must stay independent from private handlers,+// services, and database implementations.+//+// A plugin relates to Multica in exactly three ways:+//+// - Action (plugin -> Multica): host capabilities the plugin calls.+// - Hook (Multica -> plugin): plugin capabilities the host calls.+// - Resource (no call at all): static contributions such as skill text.+//+// "Who triggers" and "what capability is called" are orthogonal: a hook is+// declared once and may be invoked by any of the triggers it opts into.package plugincontractimport (@@ -14,127 +23,287 @@ import ()const (- APIVersionV1 = "multica.plugin/v1"- KindPlugin = "Plugin"+ // ManifestVersion1 is the only manifest version this host understands.+ ManifestVersion1 = 1- ContributionAgentSkillV1 = "agent.skill.v1"- CapabilityAgentSkillContribute = "agent.skill.contribute"- ContributionRemoteMCPV1 = "tool.remote-mcp.v1"- CapabilityRemoteMCPConnect = "tool.remote-mcp.connect"- RemoteMCPAnyToolIntent = "*"+ // ManifestFilename is the conventional file name inside a plugin package.+ ManifestFilename = "multica.plugin.json"- DaemonFeatureExecutionManifestV1 = "execution-manifest-v1"- DaemonFeatureAgentSkillV1 = "agent-skill-v1"- DaemonFeatureRemoteMCPV1 = "remote-mcp-v1"+ // MaxManifestSize bounds a fetched manifest before it is parsed.+ MaxManifestSize = 1 << 20- ManifestFilename = "multica.plugin.json"- MaxManifestSize = 1 << 20+ // MaxVersionLength mirrors the plugin_installation.version column bound.+ MaxVersionLength = 64+)++// Surface types. A surface is an iframe the host mounts at a fixed location.+const (+ SurfaceIssuePanel = "issue_panel"+ SurfaceSidebarPanel = "sidebar_panel"+ SurfaceModal = "modal"+)++// Hook triggers. Declaring a trigger says who may invoke the hook, never what+// the hook does. Only `event` is asynchronous, and it never blocks the host.+const (+ TriggerUI = "ui"+ TriggerManual = "manual"+ TriggerAgent = "agent"+ TriggerEvent = "event"+)++// Hook transports.+const (+ TransportHTTP = "http"+ TransportMCP = "mcp"+)++// Resource types. Resources involve no call in either direction.+const (+ ResourceSkill = "skill"+)++// Config field types. This is a deliberately small subset of JSON Schema: the+// host renders the configuration form from it, so plugins never ship form UI.+const (+ ConfigString = "string"+ ConfigNumber = "number"+ ConfigBool = "bool"+ ConfigEnum = "enum"+ ConfigSecret = "secret")+// Scopes. This list is complete and closed; anything else is rejected at parse+// time. `net:<domain>` is the only parameterized form.+const (+ ScopeIssuesRead = "issues:read"+ ScopeIssuesWrite = "issues:write"+ ScopeCommentsRead = "comments:read"+ ScopeCommentsWrite = "comments:write"+ ScopeTasksRead = "tasks:read"+ ScopeTasksWrite = "tasks:write"+ ScopeAgentsRead = "agents:read"+ ScopeMembersRead = "members:read"+ ScopeStorageUser = "storage:user"+ ScopeStorageWorkspace = "storage:workspace"++ // ScopeNetPrefix guards outbound network access: both the iframe CSP+ // connect-src allowlist and the hook transport host check derive from it.+ ScopeNetPrefix = "net:"+)++// Product events an `event`-triggered hook may subscribe to.+const (+ EventIssueCreated = "issue.created"+ EventIssueUpdated = "issue.updated"+ EventIssueStatusChanged = "issue.status_changed"+ EventCommentCreated = "comment.created"+ EventTaskStarted = "task.started"+ EventTaskCompleted = "task.completed"+ EventTaskFailed = "task.failed"+)++var fixedScopes = map[string]bool{+ ScopeIssuesRead: true,+ ScopeIssuesWrite: true,+ ScopeCommentsRead: true,+ ScopeCommentsWrite: true,+ ScopeTasksRead: true,+ ScopeTasksWrite: true,+ ScopeAgentsRead: true,+ ScopeMembersRead: true,+ ScopeStorageUser: true,+ ScopeStorageWorkspace: true,+}++var knownEvents = map[string]bool{+ EventIssueCreated: true,+ EventIssueUpdated: true,+ EventIssueStatusChanged: true,+ EventCommentCreated: true,+ EventTaskStarted: true,+ EventTaskCompleted: true,+ EventTaskFailed: true,+}+var (pluginKeySegmentPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$`)- contributionKeyPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$`)- publisherPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$`)+ contributionKeyPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[_-][a-z0-9]+)*$`)semverPattern = regexp.MustCompile(`^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$`)+ netDomainPattern = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$`)+ relativePathPattern = regexp.MustCompile(`^[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$`))type Manifest struct {- APIVersion string `json:"api_version"`- Kind string `json:"kind"`- Metadata Metadata `json:"metadata"`- Compatibility Compatibility `json:"compatibility"`- RequestedCapabilities []string `json:"requested_capabilities"`- Contributes ManifestContributions `json:"contributes"`+ ManifestVersion int `json:"manifest_version"`+ Key string `json:"key"`+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ Version string `json:"version"`+ Author Author `json:"author"`+ Icon string `json:"icon,omitempty"`+ Scopes []string `json:"scopes"`+ Config ConfigSchema `json:"config,omitempty"`+ Contributes Contributes `json:"contributes"`}-func remoteMCPHostAllowed(host string, policies []string) bool {- for _, policy := range policies {- policy = strings.ToLower(strings.TrimSuffix(policy, "."))- if host == policy {- return true- }- if strings.HasPrefix(policy, "*.") {- suffix := strings.TrimPrefix(policy, "*")- if strings.HasSuffix(host, suffix) && host != strings.TrimPrefix(suffix, ".") {- return true- }- }- }- return false+type Author struct {+ Name string `json:"name"`+ URL string `json:"url,omitempty"`}-type Metadata struct {- Key string `json:"key"`- Name string `json:"name"`- Description string `json:"description,omitempty"`- Version string `json:"version"`- Publisher string `json:"publisher"`+type Contributes struct {+ Surfaces []Surface `json:"surfaces,omitempty"`+ Hooks []Hook `json:"hooks,omitempty"`+ Resources []Resource `json:"resources,omitempty"`}-type Compatibility struct {- HostAPI string `json:"host_api"`- RequiredDaemonFeatures []string `json:"required_daemon_features"`+// Surface is a host-mounted iframe. The host owns where it appears; the plugin+// owns what renders inside it.+type Surface struct {+ Key string `json:"key"`+ Type string `json:"type"`+ Name string `json:"name"`+ Entry string `json:"entry"`+ Platforms []string `json:"platforms,omitempty"`}-type ManifestContributions struct {- AgentSkills []AgentSkillContribution `json:"agent_skills,omitempty"`- RemoteMCP []RemoteMCPContribution `json:"remote_mcp,omitempty"`+// Hook is one plugin-side capability. Triggers say who may invoke it; the host+// never invents a call site that is not listed here.+type Hook struct {+ Key string `json:"key"`+ Name string `json:"name"`+ Description string `json:"description"`+ InputSchema json.RawMessage `json:"input_schema,omitempty"`+ Triggers []string `json:"triggers"`+ Events []string `json:"events,omitempty"`+ Transport HookTransport `json:"transport"`+ TimeoutMs int `json:"timeout_ms,omitempty"`}-type AgentSkillContribution struct {- Key string `json:"key"`- Name string `json:"name"`- Description string `json:"description"`- // Entry is the canonical SKILL.md. Every other regular UTF-8 file below- // skills/<key>/ is carried as an immutable companion file in the same- // agent.skill.v1 bundle.+type HookTransport struct {+ Type string `json:"type"`+ URL string `json:"url"`+}++// Resource is a static contribution. No call happens in either direction, so a+// resource is not a hook.+type Resource struct {+ Type string `json:"type"`+ Key string `json:"key"`Entry string `json:"entry"`}-// RemoteMCPContribution is a declarative request to connect an installation to-// a remote MCP server. The package never contains an endpoint or credential:-// those are workspace-owned, revisioned installation configuration. ToolIntent-// is the maximum publisher-declared tool surface an administrator may approve.-type RemoteMCPContribution struct {- Key string `json:"key"`- Name string `json:"name"`- Description string `json:"description"`- Transport string `json:"transport"`- ProtocolVersions []string `json:"protocol_versions"`- EndpointPolicy RemoteMCPEndpointPolicy `json:"endpoint_policy"`- Authentication RemoteMCPAuthentication `json:"authentication,omitempty"`- ToolIntent []RemoteMCPToolIntent `json:"tool_intent"`- ConfigurationSchema json.RawMessage `json:"configuration_schema,omitempty"`+// ConfigField is one host-rendered configuration input. Secrets are stored+// write-only and never echoed back by any read endpoint.+type ConfigField struct {+ Key string `json:"-"`+ Type string `json:"type"`+ Label string `json:"label"`+ Description string `json:"description,omitempty"`+ Required bool `json:"required,omitempty"`+ Options []string `json:"options,omitempty"`+ Placeholder string `json:"placeholder,omitempty"`}-type RemoteMCPEndpointPolicy struct {- // DefaultEndpoint is the publisher-suggested hosted endpoint used by the- // one-click Connect flow. It is configuration, never a grant: the host must- // also be covered by AllowedHosts and the server still applies its public- // HTTPS/SSRF checks before every discovery or execution request.- DefaultEndpoint string `json:"default_endpoint,omitempty"`- AllowedHosts []string `json:"allowed_hosts,omitempty"`+// ConfigSchema keeps declaration order so the generated form is stable across+// installs. The wire format stays a JSON object keyed by field name.+type ConfigSchema struct {+ Fields []ConfigField}-type RemoteMCPAuthentication struct {- Preferred string `json:"preferred,omitempty"`- Supported []string `json:"supported,omitempty"`+func (c ConfigSchema) Len() int { return len(c.Fields) }++func (c ConfigSchema) Field(key string) (ConfigField, bool) {+ for _, field := range c.Fields {+ if field.Key == key {+ return field, true+ }+ }+ return ConfigField{}, false}-type RemoteMCPToolIntent struct {- // Name may be "*" for hosted MCP servers whose exact tool set is only- // available after authentication. The administrator must still explicitly- // approve discovered tool names, and execution pins each approved schema;- // newly discovered tools never become available automatically. Wildcard- // intent is conservatively classified as write until exact tools are known.- Name string `json:"name"`- Description string `json:"description,omitempty"`- Risk string `json:"risk"`+func (c ConfigSchema) MarshalJSON() ([]byte, error) {+ if len(c.Fields) == 0 {+ return []byte("{}"), nil+ }+ var buf bytes.Buffer+ buf.WriteByte('{')+ for i, field := range c.Fields {+ if i > 0 {+ buf.WriteByte(',')+ }+ key, err := json.Marshal(field.Key)+ if err != nil {+ return nil, err+ }+ buf.Write(key)+ buf.WriteByte(':')+ value, err := json.Marshal(struct {+ Type string `json:"type"`+ Label string `json:"label"`+ Description string `json:"description,omitempty"`+ Required bool `json:"required,omitempty"`+ Options []string `json:"options,omitempty"`+ Placeholder string `json:"placeholder,omitempty"`+ }{field.Type, field.Label, field.Description, field.Required, field.Options, field.Placeholder})+ if err != nil {+ return nil, err+ }+ buf.Write(value)+ }+ buf.WriteByte('}')+ return buf.Bytes(), nil+}++func (c *ConfigSchema) UnmarshalJSON(raw []byte) error {+ c.Fields = nil+ decoder := json.NewDecoder(bytes.NewReader(raw))+ token, err := decoder.Token()+ if err != nil {+ return fmt.Errorf("config must be a JSON object: %w", err)+ }+ if delim, ok := token.(json.Delim); !ok || delim != '{' {+ return fmt.Errorf("config must be a JSON object")+ }+ seen := map[string]bool{}+ for decoder.More() {+ keyToken, err := decoder.Token()+ if err != nil {+ return fmt.Errorf("config field name: %w", err)+ }+ key, ok := keyToken.(string)+ if !ok {+ return fmt.Errorf("config field name must be a string")+ }+ if seen[key] {+ return fmt.Errorf("config contains duplicate field %q", key)+ }+ seen[key] = true++ var body json.RawMessage+ if err := decoder.Decode(&body); err != nil {+ return fmt.Errorf("config.%s: %w", key, err)+ }+ fieldDecoder := json.NewDecoder(bytes.NewReader(body))+ fieldDecoder.DisallowUnknownFields()+ var field ConfigField+ if err := fieldDecoder.Decode(&field); err != nil {+ return fmt.Errorf("config.%s: %w", key, err)+ }+ field.Key = key+ c.Fields = append(c.Fields, field)+ }+ if _, err := decoder.Token(); err != nil {+ return fmt.Errorf("config object: %w", err)+ }+ return nil}-// ParseManifest decodes a strict V1 manifest and returns the canonical bytes-// that releases hash and sign. Unknown fields fail instead of being ignored so-// a typo cannot silently weaken the publisher's intended contract.+// ParseManifest decodes a strict v1 manifest and returns the canonical bytes an+// installation stores as its consented snapshot. Unknown fields fail instead of+// being ignored so a typo cannot silently weaken what the administrator+// approved.func ParseManifest(raw []byte) (Manifest, []byte, error) {if len(raw) == 0 {return Manifest{}, nil, fmt.Errorf("plugin manifest is empty")@@ -176,234 +345,327 @@ func rejectTrailingJSON(decoder *json.Decoder) error {}func (m Manifest) Validate() error {- if m.APIVersion != APIVersionV1 {- return fmt.Errorf("api_version must be %q", APIVersionV1)- }- if m.Kind != KindPlugin {- return fmt.Errorf("kind must be %q", KindPlugin)+ if m.ManifestVersion != ManifestVersion1 {+ return fmt.Errorf("manifest_version must be %d", ManifestVersion1)}- if err := validatePluginKey(m.Metadata.Key); err != nil {+ if err := validatePluginKey(m.Key); err != nil {return err}- if err := validateDisplayText("metadata.name", m.Metadata.Name, 160); err != nil {+ if err := validateDisplayText("name", m.Name, 160); err != nil {return err}- if len(m.Metadata.Description) > 2000 {- return fmt.Errorf("metadata.description exceeds 2000 bytes")+ if len(m.Description) > 2000 {+ return fmt.Errorf("description exceeds 2000 bytes")}- if !semverPattern.MatchString(m.Metadata.Version) {- return fmt.Errorf("metadata.version must be semantic versioning, got %q", m.Metadata.Version)+ if strings.ContainsAny(m.Description, "\r") {+ return fmt.Errorf("description must not contain carriage returns")}- if !publisherPattern.MatchString(m.Metadata.Publisher) {- return fmt.Errorf("metadata.publisher is invalid")+ // Bounded before the regex result is trusted: semver permits unbounded+ // build/prerelease segments, and plugin_installation.version is capped at+ // 64. Rejecting here turns a constraint violation at INSERT time into a+ // parse error that names the field.+ if len(m.Version) > MaxVersionLength {+ return fmt.Errorf("version exceeds %d bytes", MaxVersionLength)}- if strings.TrimSpace(m.Compatibility.HostAPI) == "" || len(m.Compatibility.HostAPI) > 256 || strings.ContainsAny(m.Compatibility.HostAPI, "\r\n") {- return fmt.Errorf("compatibility.host_api must be a non-empty single-line range")+ if !semverPattern.MatchString(m.Version) {+ return fmt.Errorf("version must be semantic versioning, got %q", m.Version)}-- capabilities, err := uniqueStrings("requested_capabilities", m.RequestedCapabilities)- if err != nil {+ if err := validateDisplayText("author.name", m.Author.Name, 160); err != nil {return err}- wantedCapabilities := map[string]bool{}- if len(m.Contributes.AgentSkills) > 0 {- wantedCapabilities[CapabilityAgentSkillContribute] = true- }- if len(m.Contributes.RemoteMCP) > 0 {- wantedCapabilities[CapabilityRemoteMCPConnect] = true+ if m.Author.URL != "" {+ if err := validateHTTPSURL("author.url", m.Author.URL); err != nil {+ return err+ }}- if len(wantedCapabilities) == 0 {- return fmt.Errorf("contributes must contain at least one agent_skills or remote_mcp contribution")+ if m.Icon != "" {+ if err := validateRelativePath("icon", m.Icon); err != nil {+ return err+ }}- if len(capabilities) != len(wantedCapabilities) {- return fmt.Errorf("requested_capabilities must exactly match declared capabilities %q", declaredCapabilityNames(wantedCapabilities))+ if err := m.validateScopes(); err != nil {+ return err}- for capability := range capabilities {- if !wantedCapabilities[capability] {- return fmt.Errorf("requested_capabilities contains unsupported capability %q", capability)- }+ if err := m.validateConfig(); err != nil {+ return err}+ return m.validateContributions()+}- features, err := uniqueStrings("compatibility.required_daemon_features", m.Compatibility.RequiredDaemonFeatures)- if err != nil {- return err+func (m Manifest) validateScopes() error {+ if len(m.Scopes) == 0 {+ return fmt.Errorf("scopes must not be empty")}- requiredFeatures := []string{DaemonFeatureExecutionManifestV1}- if len(m.Contributes.AgentSkills) > 0 {- requiredFeatures = append(requiredFeatures, DaemonFeatureAgentSkillV1)+ if len(m.Scopes) > 64 {+ return fmt.Errorf("scopes must not exceed 64 entries")}- if len(m.Contributes.RemoteMCP) > 0 {- requiredFeatures = append(requiredFeatures, DaemonFeatureRemoteMCPV1)+ seen := map[string]bool{}+ for index, scope := range m.Scopes {+ if seen[scope] {+ return fmt.Errorf("scopes contains duplicate value %q", scope)+ }+ seen[scope] = true+ if err := ValidateScope(scope); err != nil {+ return fmt.Errorf("scopes[%d]: %w", index, err)+ }}- for _, required := range requiredFeatures {- if !features[required] {- return fmt.Errorf("compatibility.required_daemon_features must include %q", required)+ return nil+}++// ValidateScope reports whether a single scope string is one this host defines.+func ValidateScope(scope string) error {+ if fixedScopes[scope] {+ return nil+ }+ if domain, ok := strings.CutPrefix(scope, ScopeNetPrefix); ok {+ if len(domain) > 253 || !netDomainPattern.MatchString(domain) {+ return fmt.Errorf("net scope has an invalid domain %q", domain)}+ return nil}+ return fmt.Errorf("unsupported scope %q", scope)+}- keys := make(map[string]bool, len(m.Contributes.AgentSkills)+len(m.Contributes.RemoteMCP))- names := make(map[string]bool, len(m.Contributes.AgentSkills)+len(m.Contributes.RemoteMCP))- for index, skill := range m.Contributes.AgentSkills {- field := fmt.Sprintf("contributes.agent_skills[%d]", index)- if !contributionKeyPattern.MatchString(skill.Key) {- return fmt.Errorf("%s.key is invalid", field)+// NetDomains returns the domains an installation may reach, taken only from the+// scopes it was granted.+func NetDomains(scopes []string) []string {+ domains := make([]string, 0, len(scopes))+ for _, scope := range scopes {+ if domain, ok := strings.CutPrefix(scope, ScopeNetPrefix); ok {+ domains = append(domains, domain)}- if strings.HasPrefix(skill.Key, "multica-") {- return fmt.Errorf("%s.key uses the reserved multica- namespace", field)+ }+ return domains+}++func (m Manifest) validateConfig() error {+ if m.Config.Len() > 32 {+ return fmt.Errorf("config must not exceed 32 fields")+ }+ for _, field := range m.Config.Fields {+ if !contributionKeyPattern.MatchString(field.Key) {+ return fmt.Errorf("config contains invalid field name %q", field.Key)}- if keys[skill.Key] {- return fmt.Errorf("duplicate contribution key %q", skill.Key)+ label := "config." + field.Key+ switch field.Type {+ case ConfigString, ConfigNumber, ConfigBool, ConfigSecret:+ if len(field.Options) > 0 {+ return fmt.Errorf("%s.options is only valid for enum fields", label)+ }+ case ConfigEnum:+ if len(field.Options) == 0 {+ return fmt.Errorf("%s.options must not be empty for enum fields", label)+ }+ if len(field.Options) > 64 {+ return fmt.Errorf("%s.options must not exceed 64 entries", label)+ }+ optionSeen := map[string]bool{}+ for _, option := range field.Options {+ if err := validateDisplayText(label+".options", option, 160); err != nil {+ return err+ }+ if optionSeen[option] {+ return fmt.Errorf("%s.options contains duplicate value %q", label, option)+ }+ optionSeen[option] = true+ }+ default:+ return fmt.Errorf("%s.type is unsupported: %q", label, field.Type)}- keys[skill.Key] = true- if err := validateDisplayText(field+".name", skill.Name, 160); err != nil {+ if err := validateDisplayText(label+".label", field.Label, 160); err != nil {return err}- nameKey := strings.ToLower(skill.Name)- if names[nameKey] {- return fmt.Errorf("duplicate contribution name %q", skill.Name)+ if len(field.Description) > 500 {+ return fmt.Errorf("%s.description exceeds 500 bytes", label)}- names[nameKey] = true- if err := validateDisplayText(field+".description", skill.Description, 2000); err != nil {- return err- }- wantEntry := "skills/" + skill.Key + "/SKILL.md"- if skill.Entry != wantEntry {- return fmt.Errorf("%s.entry must be %q", field, wantEntry)+ if len(field.Placeholder) > 160 {+ return fmt.Errorf("%s.placeholder exceeds 160 bytes", label)}}- for index, remote := range m.Contributes.RemoteMCP {- field := fmt.Sprintf("contributes.remote_mcp[%d]", index)- if err := validateContributionIdentity(field, remote.Key, remote.Name, remote.Description, keys, names); err != nil {- return err- }- if remote.Transport != "streamable-http" {- return fmt.Errorf("%s.transport must be %q", field, "streamable-http")+ return nil+}++func (m Manifest) validateContributions() error {+ total := len(m.Contributes.Surfaces) + len(m.Contributes.Hooks) + len(m.Contributes.Resources)+ if total == 0 {+ return fmt.Errorf("contributes must declare at least one surface, hook, or resource")+ }+ if total > 64 {+ return fmt.Errorf("contributes must not exceed 64 entries")+ }++ surfaceKeys := map[string]bool{}+ for index, surface := range m.Contributes.Surfaces {+ field := fmt.Sprintf("contributes.surfaces[%d]", index)+ if !contributionKeyPattern.MatchString(surface.Key) {+ return fmt.Errorf("%s.key is invalid", field)}- versions, err := uniqueStrings(field+".protocol_versions", remote.ProtocolVersions)- if err != nil {- return err+ if surfaceKeys[surface.Key] {+ return fmt.Errorf("duplicate surface key %q", surface.Key)}- if len(versions) == 0 {- return fmt.Errorf("%s.protocol_versions must not be empty", field)+ surfaceKeys[surface.Key] = true+ switch surface.Type {+ case SurfaceIssuePanel, SurfaceSidebarPanel, SurfaceModal:+ default:+ return fmt.Errorf("%s.type is unsupported: %q", field, surface.Type)}- for version := range versions {- if version != "2025-03-26" && version != "2024-11-05" {- return fmt.Errorf("%s.protocol_versions contains unsupported version %q", field, version)- }+ if err := validateDisplayText(field+".name", surface.Name, 160); err != nil {+ return err}- allowedHosts, err := uniqueStrings(field+".endpoint_policy.allowed_hosts", remote.EndpointPolicy.AllowedHosts)- if err != nil {+ if err := validateRelativePath(field+".entry", surface.Entry); err != nil {return err}- for host := range allowedHosts {- if strings.ContainsAny(host, "/:@?#") || strings.HasPrefix(host, ".") || strings.HasSuffix(host, ".") || strings.ToLower(host) != host {- return fmt.Errorf("%s.endpoint_policy.allowed_hosts contains invalid host %q", field, host)- }+ // The host generates the surface's HTML document and loads this script+ // into it. That is what lets the host attach the CSP derived from the+ // manifest's net: scopes — a plugin-authored HTML document would carry+ // whatever policy its own server sent, so net: would be a claim rather+ // than a control.+ if !strings.HasSuffix(surface.Entry, ".js") && !strings.HasSuffix(surface.Entry, ".mjs") {+ return fmt.Errorf("%s.entry must be a .js or .mjs script; the host renders the surface document itself", field)}- if remote.EndpointPolicy.DefaultEndpoint != "" {- endpoint, err := url.Parse(remote.EndpointPolicy.DefaultEndpoint)- if err != nil || endpoint.Scheme != "https" || endpoint.Hostname() == "" || endpoint.User != nil || endpoint.RawQuery != "" || endpoint.Fragment != "" {- return fmt.Errorf("%s.endpoint_policy.default_endpoint must be a plain HTTPS URL", field)+ platformSeen := map[string]bool{}+ for _, platform := range surface.Platforms {+ if platform != "web" && platform != "desktop" {+ return fmt.Errorf("%s.platforms contains unsupported platform %q", field, platform)}- host := strings.ToLower(strings.TrimSuffix(endpoint.Hostname(), "."))- if !remoteMCPHostAllowed(host, remote.EndpointPolicy.AllowedHosts) {- return fmt.Errorf("%s.endpoint_policy.default_endpoint host must be covered by allowed_hosts", field)+ if platformSeen[platform] {+ return fmt.Errorf("%s.platforms contains duplicate platform %q", field, platform)}+ platformSeen[platform] = true}- authModes, err := uniqueStrings(field+".authentication.supported", remote.Authentication.Supported)- if err != nil {- return err+ }++ hookKeys := map[string]bool{}+ for index, hook := range m.Contributes.Hooks {+ field := fmt.Sprintf("contributes.hooks[%d]", index)+ if !contributionKeyPattern.MatchString(hook.Key) {+ return fmt.Errorf("%s.key is invalid", field)}- for mode := range authModes {- if mode != "none" && mode != "oauth" && mode != "bearer" && mode != "header" {- return fmt.Errorf("%s.authentication.supported contains unsupported mode %q", field, mode)- }+ if hookKeys[hook.Key] {+ return fmt.Errorf("duplicate hook key %q", hook.Key)}- if remote.Authentication.Preferred != "" && !authModes[remote.Authentication.Preferred] {- return fmt.Errorf("%s.authentication.preferred must appear in supported", field)+ hookKeys[hook.Key] = true+ if err := validateDisplayText(field+".name", hook.Name, 160); err != nil {+ return err}- if len(remote.ToolIntent) == 0 {- return fmt.Errorf("%s.tool_intent must not be empty", field)+ // The description is what an agent reads as the MCP tool description,+ // so it is mandatory and may be multi-line.+ if strings.TrimSpace(hook.Description) == "" || len(hook.Description) > 2000 {+ return fmt.Errorf("%s.description must be non-empty and at most 2000 bytes", field)}- toolNames := make(map[string]bool, len(remote.ToolIntent))- for toolIndex, tool := range remote.ToolIntent {- toolField := fmt.Sprintf("%s.tool_intent[%d]", field, toolIndex)- if tool.Name != RemoteMCPAnyToolIntent && !contributionKeyPattern.MatchString(tool.Name) && !regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_.:-]{0,127}$`).MatchString(tool.Name) {- return fmt.Errorf("%s.name is invalid", toolField)- }- if toolNames[tool.Name] {- return fmt.Errorf("%s contains duplicate tool name %q", field+".tool_intent", tool.Name)+ if len(hook.InputSchema) > 0 {+ var schema map[string]any+ if err := json.Unmarshal(hook.InputSchema, &schema); err != nil {+ return fmt.Errorf("%s.input_schema must be a JSON object: %w", field, err)}- toolNames[tool.Name] = true- if tool.Description != "" {- if err := validateDisplayText(toolField+".description", tool.Description, 2000); err != nil {- return err- }+ if schemaType, _ := schema["type"].(string); schemaType != "object" {+ return fmt.Errorf("%s.input_schema.type must be object", field)}- if tool.Risk != "read" && tool.Risk != "write" {- return fmt.Errorf("%s.risk must be read or write", toolField)+ }+ if len(hook.Triggers) == 0 {+ return fmt.Errorf("%s.triggers must not be empty", field)+ }+ triggerSeen := map[string]bool{}+ for _, trigger := range hook.Triggers {+ switch trigger {+ case TriggerUI, TriggerManual, TriggerAgent, TriggerEvent:+ default:+ return fmt.Errorf("%s.triggers contains unsupported trigger %q", field, trigger)}- if tool.Name == RemoteMCPAnyToolIntent && tool.Risk != "write" {- return fmt.Errorf("%s.risk must be write for wildcard tool intent", toolField)+ if triggerSeen[trigger] {+ return fmt.Errorf("%s.triggers contains duplicate trigger %q", field, trigger)}+ triggerSeen[trigger] = true}- if len(remote.ConfigurationSchema) > 0 {- var schema map[string]any- if err := json.Unmarshal(remote.ConfigurationSchema, &schema); err != nil {- return fmt.Errorf("%s.configuration_schema must be a JSON object: %w", field, err)+ if triggerSeen[TriggerEvent] {+ if len(hook.Events) == 0 {+ return fmt.Errorf("%s.events must not be empty when the event trigger is declared", field)}- if schemaType, _ := schema["type"].(string); schemaType != "object" {- return fmt.Errorf("%s.configuration_schema.type must be object", field)+ eventSeen := map[string]bool{}+ for _, event := range hook.Events {+ if !knownEvents[event] {+ return fmt.Errorf("%s.events contains unsupported event %q", field, event)+ }+ if eventSeen[event] {+ return fmt.Errorf("%s.events contains duplicate event %q", field, event)+ }+ eventSeen[event] = true}+ } else if len(hook.Events) > 0 {+ return fmt.Errorf("%s.events requires the event trigger", field)+ }+ if err := m.validateHookTransport(field, hook.Transport); err != nil {+ return err+ }+ if hook.TimeoutMs != 0 && (hook.TimeoutMs < 100 || hook.TimeoutMs > 30000) {+ return fmt.Errorf("%s.timeout_ms must be between 100 and 30000", field)}}- return nil-}--func declaredCapabilityNames(capabilities map[string]bool) []string {- names := make([]string, 0, len(capabilities))- for _, capability := range []string{CapabilityAgentSkillContribute, CapabilityRemoteMCPConnect} {- if capabilities[capability] {- names = append(names, capability)+ resourceKeys := map[string]bool{}+ for index, resource := range m.Contributes.Resources {+ field := fmt.Sprintf("contributes.resources[%d]", index)+ if resource.Type != ResourceSkill {+ return fmt.Errorf("%s.type is unsupported: %q", field, resource.Type)+ }+ if !contributionKeyPattern.MatchString(resource.Key) {+ return fmt.Errorf("%s.key is invalid", field)+ }+ if resourceKeys[resource.Key] {+ return fmt.Errorf("duplicate resource key %q", resource.Key)+ }+ resourceKeys[resource.Key] = true+ if err := validateRelativePath(field+".entry", resource.Entry); err != nil {+ return err+ }+ if want := "skills/" + resource.Key + "/SKILL.md"; resource.Entry != want {+ return fmt.Errorf("%s.entry must be %q", field, want)}}- return names+ return nil}-func validateContributionIdentity(field, key, name, description string, keys, names map[string]bool) error {- if !contributionKeyPattern.MatchString(key) {- return fmt.Errorf("%s.key is invalid", field)- }- if strings.HasPrefix(key, "multica-") {- return fmt.Errorf("%s.key uses the reserved multica- namespace", field)- }- if keys[key] {- return fmt.Errorf("duplicate contribution key %q", key)- }- keys[key] = true- if err := validateDisplayText(field+".name", name, 160); err != nil {+// validateHookTransport enforces that a hook can only reach a host the manifest+// declared through a `net:` scope. Without this the consent screen would not+// describe where plugin data actually goes.+func (m Manifest) validateHookTransport(field string, transport HookTransport) error {+ switch transport.Type {+ case TransportHTTP, TransportMCP:+ default:+ return fmt.Errorf("%s.transport.type is unsupported: %q", field, transport.Type)+ }+ if err := validateHTTPSURL(field+".transport.url", transport.URL); err != nil {return err}- nameKey := strings.ToLower(name)- if names[nameKey] {- return fmt.Errorf("duplicate contribution name %q", name)+ endpoint, err := url.Parse(transport.URL)+ if err != nil {+ return fmt.Errorf("%s.transport.url is invalid", field)+ }+ // Exact host, never a suffix match. The consent screen renders one line per+ // scope ("send data to example.com"), and the same scope list becomes the+ // iframe's CSP connect-src, which is exact-host. A suffix match here would+ // make one scope string mean two different things in two places. A plugin+ // that needs a subdomain declares it: net:api.example.com.+ host := strings.ToLower(strings.TrimSuffix(endpoint.Hostname(), "."))+ for _, domain := range NetDomains(m.Scopes) {+ if host == domain {+ return nil+ }}- names[nameKey] = true- return validateDisplayText(field+".description", description, 2000)+ return fmt.Errorf("%s.transport.url host %q is not covered by a net: scope", field, host)}func validatePluginKey(key string) error {if len(key) > 255 {- return fmt.Errorf("metadata.key exceeds 255 bytes")+ return fmt.Errorf("key exceeds 255 bytes")}segments := strings.Split(key, ".")if len(segments) < 2 {- return fmt.Errorf("metadata.key must use a reverse-DNS namespace")+ return fmt.Errorf("key must use a reverse-DNS namespace")}for _, segment := range segments {if !pluginKeySegmentPattern.MatchString(segment) {- return fmt.Errorf("metadata.key contains invalid segment %q", segment)+ return fmt.Errorf("key contains invalid segment %q", segment)}}return nil@@ -422,16 +684,28 @@ func validateDisplayText(field, value string, maxBytes int) error {return nil}-func uniqueStrings(field string, values []string) (map[string]bool, error) {- seen := make(map[string]bool, len(values))- for _, value := range values {- if value == "" || value != strings.TrimSpace(value) || strings.ContainsAny(value, "\r\n") {- return nil, fmt.Errorf("%s contains an invalid value", field)- }- if seen[value] {- return nil, fmt.Errorf("%s contains duplicate value %q", field, value)+func validateRelativePath(field, value string) error {+ if value == "" || len(value) > 1024 {+ return fmt.Errorf("%s must be a relative path of at most 1024 bytes", field)+ }+ if !relativePathPattern.MatchString(value) {+ return fmt.Errorf("%s must be a relative path without protocol, leading slash, or traversal", field)+ }+ for _, segment := range strings.Split(value, "/") {+ if segment == "." || segment == ".." {+ return fmt.Errorf("%s must not contain path traversal", field)}- seen[value] = true}- return seen, nil+ return nil+}++func validateHTTPSURL(field, value string) error {+ if len(value) > 2048 {+ return fmt.Errorf("%s exceeds 2048 bytes", field)+ }+ parsed, err := url.Parse(strings.TrimSpace(value))+ if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" || parsed.User != nil || parsed.Fragment != "" {+ return fmt.Errorf("%s must be a plain HTTPS URL", field)+ }+ return nil}diff --git a/server/pkg/plugincontract/manifest_test.go b/server/pkg/plugincontract/manifest_test.goindex 1ad99bb855..d1c092017d 100644--- a/server/pkg/plugincontract/manifest_test.go+++ b/server/pkg/plugincontract/manifest_test.go@@ -6,188 +6,417 @@ import ("testing")-func validManifest() Manifest {- return Manifest{- APIVersion: APIVersionV1,- Kind: KindPlugin,- Metadata: Metadata{- Key: "ai.multica.software-delivery",- Name: "Software Delivery Skill Pack",- Version: "1.0.0",- Publisher: "multica",- },- Compatibility: Compatibility{- HostAPI: ">=1.0.0 <2.0.0",- RequiredDaemonFeatures: []string{- DaemonFeatureExecutionManifestV1,- DaemonFeatureAgentSkillV1,- },- },- RequestedCapabilities: []string{CapabilityAgentSkillContribute},- Contributes: ManifestContributions{- AgentSkills: []AgentSkillContribution{- {- Key: "review-readiness",- Name: "Review Readiness",- Description: "Prepare an evidence-based review handoff.",- Entry: "skills/review-readiness/SKILL.md",- },- },- },- }-}+// validManifest is the reference document every negative case mutates. Keeping+// one source avoids a test that passes because it drifted from the real shape.+const validManifest = `{+ "manifest_version": 1,+ "key": "com.example.hello",+ "name": "Hello Panel",+ "description": "A greeting panel.",+ "version": "1.0.0",+ "author": { "name": "example", "url": "https://example.com" },+ "icon": "icon.svg",+ "scopes": ["issues:read", "comments:write", "storage:user", "net:example.com"],+ "config": {+ "repo": { "type": "string", "label": "GitHub Repo", "required": true },+ "token": { "type": "secret", "label": "Access Token", "required": true },+ "mode": { "type": "enum", "label": "Mode", "options": ["fast", "thorough"] }+ },+ "contributes": {+ "surfaces": [{+ "key": "hello", "type": "issue_panel", "name": "Hello",+ "entry": "ui/main.js", "platforms": ["web", "desktop"]+ }],+ "hooks": [{+ "key": "summarize_thread",+ "name": "Summarize",+ "description": "Compress the issue discussion into bullet points.",+ "input_schema": { "type": "object", "properties": { "issue_id": { "type": "string" } } },+ "triggers": ["ui", "manual", "agent"],+ "transport": { "type": "http", "url": "https://example.com/hooks/summarize" },+ "timeout_ms": 10000+ }],+ "resources": [+ { "type": "skill", "key": "pr-review", "entry": "skills/pr-review/SKILL.md" }+ ]+ }+}`-func manifestJSON(t *testing.T, manifest Manifest) []byte {+func mutate(t *testing.T, edit func(doc map[string]any)) []byte {t.Helper()- content, err := json.Marshal(manifest)+ var doc map[string]any+ if err := json.Unmarshal([]byte(validManifest), &doc); err != nil {+ t.Fatalf("decode reference manifest: %v", err)+ }+ edit(doc)+ raw, err := json.Marshal(doc)if err != nil {- t.Fatalf("marshal manifest: %v", err)+ t.Fatalf("encode mutated manifest: %v", err)}- return content+ return raw}-func TestParseManifestAcceptsReferenceContract(t *testing.T) {- manifest, canonical, err := ParseManifest(manifestJSON(t, validManifest()))+func TestParseManifestAcceptsReferenceDocument(t *testing.T) {+ manifest, canonical, err := ParseManifest([]byte(validManifest))if err != nil {t.Fatalf("ParseManifest: %v", err)}- if manifest.Metadata.Key != "ai.multica.software-delivery" {- t.Fatalf("plugin key = %q", manifest.Metadata.Key)+ if manifest.Key != "com.example.hello" || manifest.Version != "1.0.0" {+ t.Fatalf("unexpected identity: %+v", manifest)}- if len(canonical) == 0 || canonical[len(canonical)-1] == '\n' {- t.Fatalf("canonical manifest is not compact JSON: %q", canonical)+ if len(manifest.Contributes.Surfaces) != 1 || len(manifest.Contributes.Hooks) != 1 || len(manifest.Contributes.Resources) != 1 {+ t.Fatalf("unexpected contributions: %+v", manifest.Contributes)+ }+ if len(canonical) == 0 {+ t.Fatal("canonical manifest is empty")+ }+ // The canonical form must reparse: it is what an installation stores and+ // later reads back as the consented snapshot.+ if _, _, err := ParseManifest(canonical); err != nil {+ t.Fatalf("canonical manifest does not reparse: %v", err)}}-func TestParseManifestRejectsUnknownExecutableContract(t *testing.T) {- raw := strings.TrimSuffix(string(manifestJSON(t, validManifest())), "}") + `,"scripts":{"postinstall":"./install.sh"}}`- if _, _, err := ParseManifest([]byte(raw)); err == nil || !strings.Contains(err.Error(), "unknown field") {- t.Fatalf("ParseManifest unknown scripts error = %v", err)+func TestConfigSchemaPreservesDeclarationOrder(t *testing.T) {+ manifest, canonical, err := ParseManifest([]byte(validManifest))+ if err != nil {+ t.Fatalf("ParseManifest: %v", err)+ }+ want := []string{"repo", "token", "mode"}+ if len(manifest.Config.Fields) != len(want) {+ t.Fatalf("config fields = %d, want %d", len(manifest.Config.Fields), len(want))+ }+ for i, key := range want {+ if manifest.Config.Fields[i].Key != key {+ t.Fatalf("config field %d = %q, want %q", i, manifest.Config.Fields[i].Key, key)+ }+ }+ // The generated form order must survive the snapshot round trip, otherwise+ // the same plugin renders its fields differently after an upgrade.+ if repo, token := strings.Index(string(canonical), `"repo"`), strings.Index(string(canonical), `"token"`); repo > token {+ t.Fatalf("canonical config lost declaration order: %s", canonical)+ }+ field, ok := manifest.Config.Field("mode")+ if !ok || field.Type != ConfigEnum || len(field.Options) != 2 {+ t.Fatalf("enum field not preserved: %+v", field)}}-func TestManifestRejectsMissingHostCapabilities(t *testing.T) {- manifest := validManifest()- manifest.RequestedCapabilities = nil- if err := manifest.Validate(); err == nil || !strings.Contains(err.Error(), CapabilityAgentSkillContribute) {- t.Fatalf("Validate missing capability error = %v", err)+func TestParseManifestRejectsMalformedDocuments(t *testing.T) {+ cases := []struct {+ name string+ raw []byte+ want string+ }{+ {"empty", []byte(""), "empty"},+ {"unknown top-level field", []byte(`{"manifest_version":1,"surprise":true}`), "unknown field"},+ {"trailing JSON", append([]byte(validManifest), []byte(`{"extra":1}`)...), "trailing"},+ {+ "unknown config field property",+ mutate(t, func(doc map[string]any) {+ doc["config"] = map[string]any{"a": map[string]any{"type": "string", "label": "A", "secret": true}}+ }),+ "unknown field",+ },+ {+ "wrong manifest version",+ mutate(t, func(doc map[string]any) { doc["manifest_version"] = 2 }),+ "manifest_version",+ },+ {+ "non reverse-DNS key",+ mutate(t, func(doc map[string]any) { doc["key"] = "hello" }),+ "reverse-DNS",+ },+ {+ "non semver version",+ mutate(t, func(doc map[string]any) { doc["version"] = "1.0" }),+ "semantic versioning",+ },+ {+ "overlong name",+ mutate(t, func(doc map[string]any) { doc["name"] = strings.Repeat("n", 161) }),+ "exceeds",+ },+ {+ "unknown scope",+ mutate(t, func(doc map[string]any) { doc["scopes"] = []any{"issues:read", "billing:write"} }),+ "unsupported scope",+ },+ {+ "malformed net scope",+ mutate(t, func(doc map[string]any) { doc["scopes"] = []any{"net:https://example.com"} }),+ "invalid domain",+ },+ {+ "duplicate scope",+ mutate(t, func(doc map[string]any) { doc["scopes"] = []any{"issues:read", "issues:read"} }),+ "duplicate",+ },+ {+ "empty scopes",+ mutate(t, func(doc map[string]any) { doc["scopes"] = []any{} }),+ "must not be empty",+ },+ {+ "unsupported config type",+ mutate(t, func(doc map[string]any) {+ doc["config"] = map[string]any{"a": map[string]any{"type": "json", "label": "A"}}+ }),+ "unsupported",+ },+ {+ "enum without options",+ mutate(t, func(doc map[string]any) {+ doc["config"] = map[string]any{"a": map[string]any{"type": "enum", "label": "A"}}+ }),+ "options must not be empty",+ },+ {+ "no contributions",+ mutate(t, func(doc map[string]any) { doc["contributes"] = map[string]any{} }),+ "at least one",+ },+ {+ "unsupported surface type",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ surfaces := contributes["surfaces"].([]any)+ surfaces[0].(map[string]any)["type"] = "fullscreen"+ }),+ "unsupported",+ },+ {+ "surface entry escapes the package",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ surfaces := contributes["surfaces"].([]any)+ surfaces[0].(map[string]any)["entry"] = "../../etc/passwd"+ }),+ "path traversal",+ },+ {+ "version over the column bound",+ mutate(t, func(doc map[string]any) {+ // A legal semver whose build metadata pushes it past the+ // plugin_installation.version cap.+ doc["version"] = "1.0.0+" + strings.Repeat("b", 64)+ }),+ "version exceeds",+ },+ {+ "surface entry is an HTML document",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ surfaces := contributes["surfaces"].([]any)+ surfaces[0].(map[string]any)["entry"] = "ui/index.html"+ }),+ "must be a .js or .mjs script",+ },+ {+ "hook transport on a subdomain of a net: scope",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ hooks := contributes["hooks"].([]any)+ hooks[0].(map[string]any)["transport"] = map[string]any{"type": "http", "url": "https://api.example.com/hooks/summarize"}+ }),+ "not covered by a net: scope",+ },+ {+ "surface entry is an absolute URL",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ surfaces := contributes["surfaces"].([]any)+ surfaces[0].(map[string]any)["entry"] = "https://evil.test/index.html"+ }),+ "relative path",+ },+ {+ "unsupported trigger",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ hooks := contributes["hooks"].([]any)+ hooks[0].(map[string]any)["triggers"] = []any{"cron"}+ }),+ "unsupported trigger",+ },+ {+ "event trigger without events",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ hooks := contributes["hooks"].([]any)+ hooks[0].(map[string]any)["triggers"] = []any{"event"}+ }),+ "events must not be empty",+ },+ {+ "events without the event trigger",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ hooks := contributes["hooks"].([]any)+ hooks[0].(map[string]any)["events"] = []any{"issue.created"}+ }),+ "requires the event trigger",+ },+ {+ "unknown event",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ hooks := contributes["hooks"].([]any)+ hooks[0].(map[string]any)["triggers"] = []any{"event"}+ hooks[0].(map[string]any)["events"] = []any{"issue.exploded"}+ }),+ "unsupported event",+ },+ {+ "hook transport outside the granted net scope",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ hooks := contributes["hooks"].([]any)+ hooks[0].(map[string]any)["transport"] = map[string]any{"type": "http", "url": "https://evil.test/hook"}+ }),+ "not covered by a net: scope",+ },+ {+ "plaintext hook transport",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ hooks := contributes["hooks"].([]any)+ hooks[0].(map[string]any)["transport"] = map[string]any{"type": "http", "url": "http://example.com/hook"}+ }),+ "HTTPS",+ },+ {+ "duplicate hook key",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ hooks := contributes["hooks"].([]any)+ clone := map[string]any{}+ for k, v := range hooks[0].(map[string]any) {+ clone[k] = v+ }+ contributes["hooks"] = []any{hooks[0], clone}+ }),+ "duplicate hook key",+ },+ {+ "unsupported resource type",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ contributes["resources"] = []any{map[string]any{"type": "font", "key": "a", "entry": "a"}}+ }),+ "unsupported",+ },+ {+ "resource entry does not match its key",+ mutate(t, func(doc map[string]any) {+ contributes := doc["contributes"].(map[string]any)+ contributes["resources"] = []any{map[string]any{"type": "skill", "key": "review", "entry": "skills/other/SKILL.md"}}+ }),+ "must be",+ },}- manifest = validManifest()- manifest.Compatibility.RequiredDaemonFeatures = []string{DaemonFeatureAgentSkillV1}- if err := manifest.Validate(); err == nil || !strings.Contains(err.Error(), DaemonFeatureExecutionManifestV1) {- t.Fatalf("Validate missing daemon feature error = %v", err)+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ _, _, err := ParseManifest(tc.raw)+ if err == nil {+ t.Fatalf("ParseManifest accepted %s", tc.name)+ }+ if !strings.Contains(err.Error(), tc.want) {+ t.Fatalf("error = %q, want it to mention %q", err.Error(), tc.want)+ }+ })}}-func TestManifestRejectsReservedAndNonNamespacedKeys(t *testing.T) {- manifest := validManifest()- manifest.Metadata.Key = "review"- if err := manifest.Validate(); err == nil || !strings.Contains(err.Error(), "reverse-DNS") {- t.Fatalf("Validate non-namespaced plugin key error = %v", err)+func TestParseManifestRejectsOversizedDocument(t *testing.T) {+ oversized := make([]byte, MaxManifestSize+1)+ for i := range oversized {+ oversized[i] = ' '}-- manifest = validManifest()- manifest.Contributes.AgentSkills[0].Key = "multica-policy"- manifest.Contributes.AgentSkills[0].Entry = "skills/multica-policy/SKILL.md"- if err := manifest.Validate(); err == nil || !strings.Contains(err.Error(), "reserved") {- t.Fatalf("Validate reserved contribution key error = %v", err)+ if _, _, err := ParseManifest(oversized); err == nil || !strings.Contains(err.Error(), "exceeds") {+ t.Fatalf("oversized manifest error = %v", err)}}-func TestManifestRejectsDuplicateContributionIdentity(t *testing.T) {- manifest := validManifest()- manifest.Contributes.AgentSkills = append(manifest.Contributes.AgentSkills, manifest.Contributes.AgentSkills[0])- if err := manifest.Validate(); err == nil || !strings.Contains(err.Error(), "duplicate contribution key") {- t.Fatalf("Validate duplicate contribution error = %v", err)+func TestValidateScope(t *testing.T) {+ valid := []string{+ ScopeIssuesRead, ScopeIssuesWrite, ScopeCommentsRead, ScopeCommentsWrite,+ ScopeTasksRead, ScopeTasksWrite, ScopeAgentsRead, ScopeMembersRead,+ ScopeStorageUser, ScopeStorageWorkspace,+ "net:example.com", "net:api.example.co.uk",+ }+ for _, scope := range valid {+ if err := ValidateScope(scope); err != nil {+ t.Fatalf("ValidateScope(%q) = %v", scope, err)+ }+ }+ invalid := []string{+ "", "issues", "issues:delete", "storage:global", "net:", "net:localhost",+ "net:EXAMPLE.com", "net:example.com/path", "net:*.example.com", "NET:example.com",+ }+ for _, scope := range invalid {+ if err := ValidateScope(scope); err == nil {+ t.Fatalf("ValidateScope(%q) accepted an invalid scope", scope)+ }}}-func validRemoteMCPManifest() Manifest {- manifest := validManifest()- manifest.Metadata.Key = "dev.local.fixture-mcp"- manifest.Metadata.Name = "Fixture MCP"- manifest.Contributes.AgentSkills = nil- manifest.Contributes.RemoteMCP = []RemoteMCPContribution{{- Key: "fixture-tools",- Name: "Fixture Tools",- Description: "Deterministic fixture tools.",- Transport: "streamable-http",- ProtocolVersions: []string{"2025-03-26", "2024-11-05"},- EndpointPolicy: RemoteMCPEndpointPolicy{- DefaultEndpoint: "https://mcp.example.test/mcp", AllowedHosts: []string{"mcp.example.test"},- },- Authentication: RemoteMCPAuthentication{Preferred: "oauth", Supported: []string{"oauth"}},- ToolIntent: []RemoteMCPToolIntent{- {Name: "fixture.read", Description: "Read fixture state.", Risk: "read"},- {Name: "fixture.write", Description: "Mutate fixture state.", Risk: "write"},- },- ConfigurationSchema: json.RawMessage(`{"type":"object","additionalProperties":false}`),- }}- manifest.RequestedCapabilities = []string{CapabilityRemoteMCPConnect}- manifest.Compatibility.RequiredDaemonFeatures = []string{- DaemonFeatureExecutionManifestV1,- DaemonFeatureRemoteMCPV1,- }- return manifest+func TestNetDomainsOnlyReturnsNetScopes(t *testing.T) {+ domains := NetDomains([]string{ScopeIssuesRead, "net:example.com", ScopeStorageUser, "net:api.example.com"})+ if len(domains) != 2 || domains[0] != "example.com" || domains[1] != "api.example.com" {+ t.Fatalf("NetDomains = %v", domains)+ }}-func TestManifestAcceptsRemoteMCPOnlyAndMixedContributions(t *testing.T) {- remoteOnly := validRemoteMCPManifest()- if err := remoteOnly.Validate(); err != nil {- t.Fatalf("Validate remote-only manifest: %v", err)+func TestCheckCapabilitiesReportsEveryUnavailableContribution(t *testing.T) {+ manifest, _, err := ParseManifest([]byte(validManifest))+ if err != nil {+ t.Fatalf("ParseManifest: %v", err)}- mixed := remoteOnly- mixed.Contributes.AgentSkills = validManifest().Contributes.AgentSkills- mixed.RequestedCapabilities = []string{CapabilityAgentSkillContribute, CapabilityRemoteMCPConnect}- mixed.Compatibility.RequiredDaemonFeatures = append(mixed.Compatibility.RequiredDaemonFeatures, DaemonFeatureAgentSkillV1)- if err := mixed.Validate(); err != nil {- t.Fatalf("Validate mixed manifest: %v", err)+ // The shipped host set is what gates a staged rollout: a manifest naming a+ // capability this build cannot run must fail loudly, never install+ // half-working.+ err = manifest.CheckCapabilities(HostCapabilities())+ if err == nil {+ t.Fatal("CheckCapabilities accepted contributions the host cannot run")+ }+ var unavailable *ErrCapabilityUnavailable+ if !asCapabilityError(err, &unavailable) {+ t.Fatalf("error type = %T, want *ErrCapabilityUnavailable", err)+ }+ for _, want := range []string{"surface issue_panel", "hook trigger ui", "hook transport http", "resource skill"} {+ if !containsString(unavailable.Missing, want) {+ t.Fatalf("missing = %v, want it to include %q", unavailable.Missing, want)+ }+ }++ full := Capabilities{+ SurfaceTypes: map[string]bool{SurfaceIssuePanel: true, SurfaceSidebarPanel: true, SurfaceModal: true},+ HookTriggers: map[string]bool{TriggerUI: true, TriggerManual: true, TriggerAgent: true, TriggerEvent: true},+ HookTransport: map[string]bool{TransportHTTP: true, TransportMCP: true},+ ResourceTypes: map[string]bool{ResourceSkill: true},+ }+ if err := manifest.CheckCapabilities(full); err != nil {+ t.Fatalf("CheckCapabilities with full host support: %v", err)}}-func TestManifestAcceptsReviewedWildcardRemoteMCPToolIntent(t *testing.T) {- manifest := validRemoteMCPManifest()- manifest.Contributes.RemoteMCP[0].ToolIntent = []RemoteMCPToolIntent{{- Name: RemoteMCPAnyToolIntent, Description: "Discover tools for explicit administrator review.", Risk: "write",- }}- if err := manifest.Validate(); err != nil {- t.Fatalf("Validate wildcard Remote MCP tool intent: %v", err)+func asCapabilityError(err error, target **ErrCapabilityUnavailable) bool {+ candidate, ok := err.(*ErrCapabilityUnavailable)+ if ok {+ *target = candidate}+ return ok}-func TestManifestRemoteMCPFailsClosed(t *testing.T) {- tests := []struct {- name string- edit func(*Manifest)- want string- }{- {name: "stdio transport", edit: func(m *Manifest) { m.Contributes.RemoteMCP[0].Transport = "stdio" }, want: "streamable-http"},- {name: "unsupported protocol", edit: func(m *Manifest) { m.Contributes.RemoteMCP[0].ProtocolVersions = []string{"2026-01-01"} }, want: "unsupported version"},- {name: "secret-looking endpoint", edit: func(m *Manifest) {- m.Contributes.RemoteMCP[0].EndpointPolicy.AllowedHosts = []string{"https://[email protected]"}- }, want: "invalid host"},- {name: "default endpoint outside allowlist", edit: func(m *Manifest) {- m.Contributes.RemoteMCP[0].EndpointPolicy.DefaultEndpoint = "https://other.example/mcp"- }, want: "covered by allowed_hosts"},- {name: "preferred auth not supported", edit: func(m *Manifest) {- m.Contributes.RemoteMCP[0].Authentication.Preferred = "bearer"- }, want: "must appear in supported"},- {name: "invalid risk", edit: func(m *Manifest) { m.Contributes.RemoteMCP[0].ToolIntent[0].Risk = "admin" }, want: "read or write"},- {name: "wildcard understates risk", edit: func(m *Manifest) {- m.Contributes.RemoteMCP[0].ToolIntent = []RemoteMCPToolIntent{{Name: RemoteMCPAnyToolIntent, Risk: "read"}}- }, want: "must be write for wildcard"},- {name: "missing capability", edit: func(m *Manifest) { m.RequestedCapabilities = nil }, want: "requested_capabilities"},- {name: "missing daemon feature", edit: func(m *Manifest) { m.Compatibility.RequiredDaemonFeatures = []string{DaemonFeatureExecutionManifestV1} }, want: DaemonFeatureRemoteMCPV1},- }- for _, test := range tests {- t.Run(test.name, func(t *testing.T) {- manifest := validRemoteMCPManifest()- test.edit(&manifest)- if err := manifest.Validate(); err == nil || !strings.Contains(err.Error(), test.want) {- t.Fatalf("Validate error = %v, want containing %q", err, test.want)- }- })+func containsString(values []string, want string) bool {+ for _, value := range values {+ if value == want {+ return true+ }}+ return false}diff --git a/server/pkg/plugincontract/pack.go b/server/pkg/plugincontract/pack.godeleted file mode 100644index 9c32681dd3..0000000000--- a/server/pkg/plugincontract/pack.go+++ /dev/null@@ -1,101 +0,0 @@-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.godeleted file mode 100644index ab7b60813f..0000000000--- a/server/pkg/plugincontract/pack_test.go+++ /dev/null@@ -1,73 +0,0 @@-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)- }-}diff --git a/server/pkg/plugincontract/release.go b/server/pkg/plugincontract/release.godeleted file mode 100644index d9ddaab3e9..0000000000--- a/server/pkg/plugincontract/release.go+++ /dev/null@@ -1,137 +0,0 @@-package plugincontract--import (- "fmt"- "strings"-)--const (- SourceBundled = "bundled"- SourcePrivateDev = "private_dev"-)--type ReleaseCandidate struct {- Archive []byte- SourceKind string- SourceRef string- SignatureKeyID string- Signature []byte-}--type ValidatedRelease struct {- Manifest Manifest- CanonicalManifest []byte- ManifestDigest string- ArchiveDigest string- ArtifactDigest string- ArtifactSize int64- SourceKind string- SourceRef string- SignatureKeyID string- Signature []byte- Contributions []ValidatedContribution- Files []ArtifactFile-}--type ValidatedContribution struct {- Key string- Type string- SchemaVersion int32- DisplayName string- Description string- EntryPath string- EntryDigest string- ArtifactDigest string- RequiredDaemonFeatures []string- Ordinal int32-}--// ValidateReleaseCandidate is the publication boundary. Bundled releases must-// carry a signature from the configured release trust store; private-dev-// releases may be unsigned, but a supplied signature is always verified.-func ValidateReleaseCandidate(candidate ReleaseCandidate, verifier ReleaseVerifier) (ValidatedRelease, error) {- if candidate.SourceKind != SourceBundled && candidate.SourceKind != SourcePrivateDev {- return ValidatedRelease{}, fmt.Errorf("plugin release source_kind %q is unsupported", candidate.SourceKind)- }- if candidate.SourceRef == "" || candidate.SourceRef != strings.TrimSpace(candidate.SourceRef) || len(candidate.SourceRef) > 2048 {- return ValidatedRelease{}, fmt.Errorf("plugin release source_ref is invalid")- }- if (candidate.SignatureKeyID == "") != (len(candidate.Signature) == 0) {- return ValidatedRelease{}, fmt.Errorf("plugin release signature and key id must be supplied together")- }- if candidate.SourceKind == SourceBundled && candidate.SignatureKeyID == "" {- return ValidatedRelease{}, fmt.Errorf("bundled plugin release must be signed")- }-- artifact, err := ValidateArtifact(candidate.Archive)- if err != nil {- return ValidatedRelease{}, err- }- manifestDigest := DigestBytes(artifact.CanonicalManifest)- envelope := ReleaseEnvelope{- PluginKey: artifact.Manifest.Metadata.Key,- Version: artifact.Manifest.Metadata.Version,- ManifestDigest: manifestDigest,- ArchiveDigest: artifact.ArchiveDigest,- ArtifactDigest: artifact.ArtifactDigest,- }- if candidate.SignatureKeyID != "" {- if verifier == nil {- return ValidatedRelease{}, fmt.Errorf("plugin release signature verifier is not configured")- }- if err := verifier.VerifyRelease(candidate.SignatureKeyID, envelope, candidate.Signature); err != nil {- return ValidatedRelease{}, err- }- }-- files := make(map[string]ArtifactFile, len(artifact.Files))- for _, file := range artifact.Files {- files[file.Path] = file- }- contributions := make([]ValidatedContribution, 0, len(artifact.Manifest.Contributes.AgentSkills)+len(artifact.Manifest.Contributes.RemoteMCP))- for ordinal, skill := range artifact.Manifest.Contributes.AgentSkills {- entry := files[skill.Entry]- contributions = append(contributions, ValidatedContribution{- Key: skill.Key,- Type: ContributionAgentSkillV1,- SchemaVersion: 1,- DisplayName: skill.Name,- Description: skill.Description,- EntryPath: skill.Entry,- EntryDigest: entry.Digest,- ArtifactDigest: artifact.ArtifactDigest,- RequiredDaemonFeatures: []string{DaemonFeatureExecutionManifestV1, DaemonFeatureAgentSkillV1},- Ordinal: int32(ordinal),- })- }- manifestEntry := files[ManifestFilename]- for index, remote := range artifact.Manifest.Contributes.RemoteMCP {- contributions = append(contributions, ValidatedContribution{- Key: remote.Key,- Type: ContributionRemoteMCPV1,- SchemaVersion: 1,- DisplayName: remote.Name,- Description: remote.Description,- EntryPath: ManifestFilename,- EntryDigest: manifestEntry.Digest,- ArtifactDigest: artifact.ArtifactDigest,- RequiredDaemonFeatures: []string{DaemonFeatureExecutionManifestV1, DaemonFeatureRemoteMCPV1},- Ordinal: int32(len(artifact.Manifest.Contributes.AgentSkills) + index),- })- }-- return ValidatedRelease{- Manifest: artifact.Manifest,- CanonicalManifest: append([]byte(nil), artifact.CanonicalManifest...),- ManifestDigest: manifestDigest,- ArchiveDigest: artifact.ArchiveDigest,- ArtifactDigest: artifact.ArtifactDigest,- ArtifactSize: artifact.SizeBytes,- SourceKind: candidate.SourceKind,- SourceRef: candidate.SourceRef,- SignatureKeyID: candidate.SignatureKeyID,- Signature: append([]byte(nil), candidate.Signature...),- Contributions: contributions,- Files: append([]ArtifactFile(nil), artifact.Files...),- }, nil-}diff --git a/server/pkg/plugincontract/release_test.go b/server/pkg/plugincontract/release_test.godeleted file mode 100644index ade2e67e5b..0000000000--- a/server/pkg/plugincontract/release_test.go+++ /dev/null@@ -1,107 +0,0 @@-package plugincontract--import (- "crypto/ed25519"- "crypto/rand"- "errors"- "testing"-)--func TestValidateReleaseCandidateRequiresAndVerifiesBundledSignature(t *testing.T) {- archive := buildArchive(t, referenceArchiveFiles(t))- unsigned := ReleaseCandidate{- Archive: archive,- SourceKind: SourceBundled,- SourceRef: "embedded://ai.multica.software-delivery/1.0.0",- }- if _, err := ValidateReleaseCandidate(unsigned, nil); err == nil {- t.Fatal("unsigned bundled release was accepted")- }-- publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- t.Fatalf("GenerateKey: %v", err)- }- signer, _ := NewEd25519Signer("release-2026-01", privateKey)- store, _ := NewEd25519TrustStore(map[string]ed25519.PublicKey{"release-2026-01": publicKey})- artifact, err := ValidateArtifact(archive)- if err != nil {- t.Fatalf("ValidateArtifact: %v", err)- }- envelope := ReleaseEnvelope{- PluginKey: artifact.Manifest.Metadata.Key,- Version: artifact.Manifest.Metadata.Version,- ManifestDigest: DigestBytes(artifact.CanonicalManifest),- ArchiveDigest: artifact.ArchiveDigest,- ArtifactDigest: artifact.ArtifactDigest,- }- signature, err := signer.SignRelease(envelope)- if err != nil {- t.Fatalf("SignRelease: %v", err)- }-- validated, err := ValidateReleaseCandidate(ReleaseCandidate{- Archive: archive,- SourceKind: SourceBundled,- SourceRef: unsigned.SourceRef,- SignatureKeyID: signer.KeyID(),- Signature: signature,- }, store)- if err != nil {- t.Fatalf("ValidateReleaseCandidate: %v", err)- }- if len(validated.Contributions) != 1 {- t.Fatalf("contributions = %d, want 1", len(validated.Contributions))- }- if len(validated.Files) != 3 {- t.Fatalf("files = %d, want 3", len(validated.Files))- }- contribution := validated.Contributions[0]- if contribution.Type != ContributionAgentSkillV1 || contribution.EntryDigest == "" {- t.Fatalf("validated contribution = %#v", contribution)- }-- tampered := append([]byte(nil), signature...)- tampered[0] ^= 0xff- _, err = ValidateReleaseCandidate(ReleaseCandidate{- Archive: archive,- SourceKind: SourceBundled,- SourceRef: unsigned.SourceRef,- SignatureKeyID: signer.KeyID(),- Signature: tampered,- }, store)- if !errors.Is(err, ErrInvalidSignature) {- t.Fatalf("tampered signature error = %v", err)- }-}--func TestValidateReleaseCandidateAllowsUnsignedPrivateDev(t *testing.T) {- validated, err := ValidateReleaseCandidate(ReleaseCandidate{- Archive: buildArchive(t, referenceArchiveFiles(t)),- SourceKind: SourcePrivateDev,- SourceRef: "local://software-delivery",- }, nil)- if err != nil {- t.Fatalf("ValidateReleaseCandidate: %v", err)- }- if validated.SourceKind != SourcePrivateDev || validated.SignatureKeyID != "" {- t.Fatalf("validated private-dev release = %#v", validated)- }-}--func TestValidateReleaseCandidateCompilesRemoteMCPAdapter(t *testing.T) {- archive := buildArchive(t, []zipFixtureFile{{name: ManifestFilename, content: manifestJSON(t, validRemoteMCPManifest())}})- validated, err := ValidateReleaseCandidate(ReleaseCandidate{- Archive: archive, SourceKind: SourcePrivateDev, SourceRef: "private://fixture",- }, nil)- if err != nil {- t.Fatalf("ValidateReleaseCandidate: %v", err)- }- if len(validated.Contributions) != 1 {- t.Fatalf("contributions = %d, want 1", len(validated.Contributions))- }- got := validated.Contributions[0]- if got.Type != ContributionRemoteMCPV1 || got.EntryPath != ManifestFilename || got.EntryDigest != validated.ManifestDigest {- t.Fatalf("remote MCP contribution = %#v", got)- }-}diff --git a/server/pkg/plugincontract/signature.go b/server/pkg/plugincontract/signature.godeleted file mode 100644index 1ccc2f3c7b..0000000000--- a/server/pkg/plugincontract/signature.go+++ /dev/null@@ -1,161 +0,0 @@-package plugincontract--import (- "crypto/ed25519"- "encoding/json"- "errors"- "fmt"- "sync"-)--var (- ErrUnknownSigningKey = errors.New("plugin release signing key is not trusted")- ErrInvalidSignature = errors.New("plugin release signature is invalid")-)--// ReleaseEnvelope is the complete immutable identity signed by an official-// publisher. It binds the manifest to both the uploaded archive and the-// canonical extracted artifact.-type ReleaseEnvelope 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"`-}--func (e ReleaseEnvelope) CanonicalBytes() ([]byte, error) {- if err := e.Validate(); err != nil {- return nil, err- }- content, err := json.Marshal(e)- if err != nil {- return nil, fmt.Errorf("canonicalize plugin release envelope: %w", err)- }- return content, nil-}--func (e ReleaseEnvelope) Validate() error {- if err := validatePluginKey(e.PluginKey); err != nil {- return err- }- if !semverPattern.MatchString(e.Version) {- return fmt.Errorf("release envelope version is invalid")- }- for field, digest := range map[string]string{- "manifest_digest": e.ManifestDigest,- "archive_digest": e.ArchiveDigest,- "artifact_digest": e.ArtifactDigest,- } {- if !validSHA256Digest(digest) {- return fmt.Errorf("release envelope %s is invalid", field)- }- }- return nil-}--type ReleaseSigner interface {- KeyID() string- SignRelease(ReleaseEnvelope) ([]byte, error)-}--type ReleaseVerifier interface {- VerifyRelease(keyID string, envelope ReleaseEnvelope, signature []byte) error-}--type Ed25519Signer struct {- keyID string- privateKey ed25519.PrivateKey-}--func NewEd25519Signer(keyID string, privateKey ed25519.PrivateKey) (*Ed25519Signer, error) {- if keyID == "" {- return nil, fmt.Errorf("plugin release signing key id is empty")- }- if len(privateKey) != ed25519.PrivateKeySize {- return nil, fmt.Errorf("plugin release private key has invalid size")- }- return &Ed25519Signer{keyID: keyID, privateKey: append(ed25519.PrivateKey(nil), privateKey...)}, nil-}--func (s *Ed25519Signer) KeyID() string {- return s.keyID-}--func (s *Ed25519Signer) SignRelease(envelope ReleaseEnvelope) ([]byte, error) {- content, err := envelope.CanonicalBytes()- if err != nil {- return nil, err- }- return ed25519.Sign(s.privateKey, content), nil-}--// Ed25519TrustStore supports overlapping public keys during release-key-// rotation. Private keys never enter the server trust store.-type Ed25519TrustStore struct {- mu sync.RWMutex- keys map[string]ed25519.PublicKey-}--func NewEd25519TrustStore(keys map[string]ed25519.PublicKey) (*Ed25519TrustStore, error) {- store := &Ed25519TrustStore{keys: make(map[string]ed25519.PublicKey, len(keys))}- for keyID, publicKey := range keys {- if err := store.AddKey(keyID, publicKey); err != nil {- return nil, err- }- }- return store, nil-}--func (s *Ed25519TrustStore) AddKey(keyID string, publicKey ed25519.PublicKey) error {- if keyID == "" {- return fmt.Errorf("plugin release trust key id is empty")- }- if len(publicKey) != ed25519.PublicKeySize {- return fmt.Errorf("plugin release public key %q has invalid size", keyID)- }- s.mu.Lock()- defer s.mu.Unlock()- s.keys[keyID] = append(ed25519.PublicKey(nil), publicKey...)- return nil-}--func (s *Ed25519TrustStore) RemoveKey(keyID string) {- s.mu.Lock()- defer s.mu.Unlock()- delete(s.keys, keyID)-}--func (s *Ed25519TrustStore) VerifyRelease(keyID string, envelope ReleaseEnvelope, signature []byte) error {- content, err := envelope.CanonicalBytes()- if err != nil {- return err- }- s.mu.RLock()- publicKey, ok := s.keys[keyID]- s.mu.RUnlock()- if !ok {- return fmt.Errorf("%w: %s", ErrUnknownSigningKey, keyID)- }- if !ed25519.Verify(publicKey, content, signature) {- return ErrInvalidSignature- }- return nil-}--func validSHA256Digest(value string) bool {- if len(value) != len("sha256:")+sha256HexSize {- return false- }- if value[:len("sha256:")] != "sha256:" {- return false- }- for _, char := range value[len("sha256:"):] {- if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') {- return false- }- }- return true-}--const sha256HexSize = 64diff --git a/server/pkg/plugincontract/signature_test.go b/server/pkg/plugincontract/signature_test.godeleted file mode 100644index 894c4ec491..0000000000--- a/server/pkg/plugincontract/signature_test.go+++ /dev/null@@ -1,88 +0,0 @@-package plugincontract--import (- "crypto/ed25519"- "crypto/rand"- "errors"- "testing"-)--func testReleaseEnvelope() ReleaseEnvelope {- return ReleaseEnvelope{- PluginKey: "ai.multica.software-delivery",- Version: "1.0.0",- ManifestDigest: DigestBytes([]byte("manifest")),- ArchiveDigest: DigestBytes([]byte("archive")),- ArtifactDigest: DigestBytes([]byte("artifact")),- }-}--func TestEd25519ReleaseSignatureRoundTripAndTamper(t *testing.T) {- publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- t.Fatalf("GenerateKey: %v", err)- }- signer, err := NewEd25519Signer("release-2026-01", privateKey)- if err != nil {- t.Fatalf("NewEd25519Signer: %v", err)- }- trustStore, err := NewEd25519TrustStore(map[string]ed25519.PublicKey{- signer.KeyID(): publicKey,- })- if err != nil {- t.Fatalf("NewEd25519TrustStore: %v", err)- }-- envelope := testReleaseEnvelope()- signature, err := signer.SignRelease(envelope)- if err != nil {- t.Fatalf("SignRelease: %v", err)- }- if err := trustStore.VerifyRelease(signer.KeyID(), envelope, signature); err != nil {- t.Fatalf("VerifyRelease: %v", err)- }-- tampered := envelope- tampered.ArtifactDigest = DigestBytes([]byte("tampered"))- if err := trustStore.VerifyRelease(signer.KeyID(), tampered, signature); !errors.Is(err, ErrInvalidSignature) {- t.Fatalf("VerifyRelease tampered error = %v", err)- }-}--func TestEd25519TrustStoreSupportsKeyRotation(t *testing.T) {- oldPublic, oldPrivate, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- t.Fatalf("GenerateKey old: %v", err)- }- newPublic, newPrivate, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- t.Fatalf("GenerateKey new: %v", err)- }- oldSigner, _ := NewEd25519Signer("old", oldPrivate)- newSigner, _ := NewEd25519Signer("new", newPrivate)- store, err := NewEd25519TrustStore(map[string]ed25519.PublicKey{"old": oldPublic})- if err != nil {- t.Fatalf("NewEd25519TrustStore: %v", err)- }- if err := store.AddKey("new", newPublic); err != nil {- t.Fatalf("AddKey: %v", err)- }-- envelope := testReleaseEnvelope()- oldSignature, _ := oldSigner.SignRelease(envelope)- newSignature, _ := newSigner.SignRelease(envelope)- if err := store.VerifyRelease("old", envelope, oldSignature); err != nil {- t.Fatalf("verify old during overlap: %v", err)- }- if err := store.VerifyRelease("new", envelope, newSignature); err != nil {- t.Fatalf("verify new during overlap: %v", err)- }-- store.RemoveKey("old")- if err := store.VerifyRelease("old", envelope, oldSignature); !errors.Is(err, ErrUnknownSigningKey) {- t.Fatalf("verify removed key error = %v", err)- }- if err := store.VerifyRelease("new", envelope, newSignature); err != nil {- t.Fatalf("verify new after rotation: %v", err)- }-}diff --git a/server/pkg/pluginruntime/runtime.go b/server/pkg/pluginruntime/runtime.godeleted file mode 100644index b5ed4fda33..0000000000--- a/server/pkg/pluginruntime/runtime.go+++ /dev/null@@ -1,161 +0,0 @@-// Package pluginruntime contains the versioned, JSON-serializable data that-// connects a compiled plugin snapshot to a task execution manifest.-package pluginruntime--import (- "encoding/json"- "fmt"- "sort"-- "github.com/multica-ai/multica/server/pkg/plugincontract"-)--const (- CompilerVersion = "plugin-compiler-v2"- ComposerVersion = "plugin-composer-v1"- SchemaVersion = 1-)--// CompiledEntry is one contribution made available at a workspace or agent-// scope. Execution manifests copy these entries verbatim at enqueue time.-type CompiledEntry struct {- PluginID string `json:"plugin_id"`- PluginKey string `json:"plugin_key"`- InstallationID string `json:"installation_id"`- ReleaseID string `json:"release_id"`- ReleaseVersion string `json:"release_version"`- ContributionID string `json:"contribution_id"`- ContributionKey string `json:"contribution_key"`- ContributionType string `json:"contribution_type"`- DisplayName string `json:"display_name"`- Description string `json:"description,omitempty"`- SourceKind string `json:"source_kind"`- ArtifactFileID string `json:"artifact_file_id"`- ArtifactRef string `json:"artifact_ref"`- ArtifactDigest string `json:"artifact_digest"`- EntryPath string `json:"entry_path"`- EntryDigest string `json:"entry_digest"`- RequiredDaemonFeatures []string `json:"required_daemon_features"`- Ordinal int32 `json:"ordinal"`- ScopeType string `json:"scope_type"`- ScopeID string `json:"scope_id"`- ExcludedAgentIDs []string `json:"excluded_agent_ids,omitempty"`- SkillBundleHash string `json:"skill_bundle_hash,omitempty"`- SkillSizeBytes int64 `json:"skill_size_bytes,omitempty"`- SkillFileCount int `json:"skill_file_count,omitempty"`- SkillFiles []SkillFile `json:"skill_files,omitempty"`- ConfigID string `json:"config_id,omitempty"`- ConfigRevision int64 `json:"config_revision,omitempty"`- Endpoint string `json:"endpoint,omitempty"`- PublicConfig json.RawMessage `json:"public_config,omitempty"`- SecretRef string `json:"secret_ref,omitempty"`- AuthType string `json:"auth_type,omitempty"`- AuthHeader string `json:"auth_header,omitempty"`- ApprovedTools []RemoteMCPTool `json:"approved_tools,omitempty"`- ToolSchemaDigest string `json:"tool_schema_digest,omitempty"`- FailurePolicy string `json:"failure_policy,omitempty"`- Transport string `json:"transport,omitempty"`- ProtocolVersions []string `json:"protocol_versions,omitempty"`- EndpointAllowedHosts []string `json:"endpoint_allowed_hosts,omitempty"`-}--// SkillFile pins one companion file from an agent.skill.v1 contribution.-// Path is relative to the contribution's skills/<key>/ root; SKILL.md remains-// pinned separately by ArtifactFileID, EntryPath, and EntryDigest.-type SkillFile struct {- ArtifactFileID string `json:"artifact_file_id"`- Path string `json:"path"`- Digest string `json:"digest"`- SizeBytes int64 `json:"size_bytes"`-}--type RemoteMCPTool struct {- Name string `json:"name"`- Description string `json:"description,omitempty"`- InputSchema json.RawMessage `json:"input_schema"`- SchemaDigest string `json:"schema_digest"`- Risk string `json:"risk,omitempty"`-}--// RemoteMCPConnection is claim-time, task-scoped connection metadata resolved-// from a pinned entry. Credentials are intentionally absent from this wire-// type and are resolved just-in-time by the daemon broker.-type RemoteMCPConnection struct {- InstallationID string `json:"installation_id"`- ContributionID string `json:"contribution_id"`- ContributionKey string `json:"contribution_key"`- ConfigID string `json:"config_id"`- ConfigRevision int64 `json:"config_revision"`- Endpoint string `json:"endpoint"`- PublicConfig json.RawMessage `json:"public_config,omitempty"`- Transport string `json:"transport"`- ProtocolVersions []string `json:"protocol_versions"`- EndpointAllowedHosts []string `json:"endpoint_allowed_hosts,omitempty"`- CredentialHeader string `json:"credential_header,omitempty"`- ApprovedTools []RemoteMCPTool `json:"approved_tools"`- ToolSchemaDigest string `json:"tool_schema_digest"`- FailurePolicy string `json:"failure_policy"`-}--type SnapshotPayload struct {- SourceGenerations map[string]int64 `json:"source_generations"`- CompilerVersion string `json:"compiler_version"`- SchemaVersion int `json:"schema_version"`- Entries []CompiledEntry `json:"entries"`-}--func Canonicalize(entries []CompiledEntry) {- for i := range entries {- sort.Strings(entries[i].ExcludedAgentIDs)- sort.Strings(entries[i].RequiredDaemonFeatures)- sort.Strings(entries[i].ProtocolVersions)- sort.Strings(entries[i].EndpointAllowedHosts)- sort.Slice(entries[i].SkillFiles, func(left, right int) bool {- if entries[i].SkillFiles[left].Path != entries[i].SkillFiles[right].Path {- return entries[i].SkillFiles[left].Path < entries[i].SkillFiles[right].Path- }- return entries[i].SkillFiles[left].ArtifactFileID < entries[i].SkillFiles[right].ArtifactFileID- })- sort.Slice(entries[i].ApprovedTools, func(left, right int) bool {- return entries[i].ApprovedTools[left].Name < entries[i].ApprovedTools[right].Name- })- }- sort.Slice(entries, func(i, j int) bool {- left, right := entries[i], entries[j]- if left.Ordinal != right.Ordinal {- return left.Ordinal < right.Ordinal- }- if left.PluginKey != right.PluginKey {- return left.PluginKey < right.PluginKey- }- if left.ContributionKey != right.ContributionKey {- return left.ContributionKey < right.ContributionKey- }- if left.ScopeType != right.ScopeType {- return left.ScopeType < right.ScopeType- }- return left.ScopeID < right.ScopeID- })-}--func SnapshotDigest(sourceGenerations map[string]int64, entries []CompiledEntry) (string, error) {- Canonicalize(entries)- content, err := json.Marshal(SnapshotPayload{- SourceGenerations: sourceGenerations,- CompilerVersion: CompilerVersion,- SchemaVersion: SchemaVersion,- Entries: entries,- })- if err != nil {- return "", fmt.Errorf("marshal plugin snapshot payload: %w", err)- }- return plugincontract.DigestBytes(content), nil-}--func ParseEntries(raw []byte) ([]CompiledEntry, error) {- var entries []CompiledEntry- if err := json.Unmarshal(raw, &entries); err != nil {- return nil, fmt.Errorf("decode plugin compiled entries: %w", err)- }- return entries, nil-}diff --git a/server/pkg/pluginruntime/runtime_test.go b/server/pkg/pluginruntime/runtime_test.godeleted file mode 100644index 09a6976ac5..0000000000--- a/server/pkg/pluginruntime/runtime_test.go+++ /dev/null@@ -1,52 +0,0 @@-package pluginruntime--import "testing"--func TestSnapshotDigestCanonicalizesEntryOrder(t *testing.T) {- left := []CompiledEntry{- {PluginKey: "z.plugin", ContributionKey: "b", Ordinal: 1, RequiredDaemonFeatures: []string{"b", "a"}},- {PluginKey: "a.plugin", ContributionKey: "a", Ordinal: 0},- }- right := []CompiledEntry{left[1], left[0]}- first, err := SnapshotDigest(map[string]int64{"b": 2, "a": 1}, left)- if err != nil {- t.Fatal(err)- }- second, err := SnapshotDigest(map[string]int64{"a": 1, "b": 2}, right)- if err != nil {- t.Fatal(err)- }- if first != second {- t.Fatalf("snapshot digest is not canonical: %s != %s", first, second)- }-}--func TestSnapshotDigestCanonicalizesSkillFileOrder(t *testing.T) {- left := []CompiledEntry{{- PluginKey: "example.plugin",- ContributionKey: "community-skill",- SkillFiles: []SkillFile{- {ArtifactFileID: "file-b", Path: "references/b.md", Digest: "sha256:b", SizeBytes: 2},- {ArtifactFileID: "file-a", Path: "agents/openai.yaml", Digest: "sha256:a", SizeBytes: 1},- },- }}- right := []CompiledEntry{{- PluginKey: "example.plugin",- ContributionKey: "community-skill",- SkillFiles: []SkillFile{- {ArtifactFileID: "file-a", Path: "agents/openai.yaml", Digest: "sha256:a", SizeBytes: 1},- {ArtifactFileID: "file-b", Path: "references/b.md", Digest: "sha256:b", SizeBytes: 2},- },- }}- first, err := SnapshotDigest(map[string]int64{"installation": 1}, left)- if err != nil {- t.Fatal(err)- }- second, err := SnapshotDigest(map[string]int64{"installation": 1}, right)- if err != nil {- t.Fatal(err)- }- if first != second {- t.Fatalf("snapshot digest depends on Skill file order: %s != %s", first, second)- }-}diff --git a/server/pkg/remotemcp/client.go b/server/pkg/remotemcp/client.goindex edcb96fd5a..364b98692f 100644--- a/server/pkg/remotemcp/client.go+++ b/server/pkg/remotemcp/client.go@@ -17,9 +17,6 @@ import ("sort""strings""time"-- "github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/pluginruntime")const (@@ -157,7 +154,7 @@ type discoveredTool struct {InputSchema json.RawMessage `json:"inputSchema"`}-func Discover(ctx context.Context, rawEndpoint string, allowedHosts, protocolVersions []string, headers http.Header) ([]pluginruntime.RemoteMCPTool, string, error) {+func Discover(ctx context.Context, rawEndpoint string, allowedHosts, protocolVersions []string, headers http.Header) ([]Tool, string, error) {endpoint, err := ValidatePublicHTTPSEndpoint(ctx, rawEndpoint, allowedHosts, nil)if err != nil {return nil, "", err@@ -204,7 +201,7 @@ func Discover(ctx context.Context, rawEndpoint string, allowedHosts, protocolVerif err := json.Unmarshal(toolsResponse.Result, &result); err != nil {return nil, "", fmt.Errorf("decode tools/list result: %w", err)}- tools := make([]pluginruntime.RemoteMCPTool, 0, len(result.Tools))+ tools := make([]Tool, 0, len(result.Tools))seen := map[string]bool{}for _, tool := range result.Tools {if strings.TrimSpace(tool.Name) == "" || seen[tool.Name] {@@ -215,9 +212,9 @@ func Discover(ctx context.Context, rawEndpoint string, allowedHosts, protocolVerif err != nil {return nil, "", fmt.Errorf("tool %q input schema: %w", tool.Name, err)}- tools = append(tools, pluginruntime.RemoteMCPTool{+ tools = append(tools, Tool{Name: tool.Name, Description: tool.Description, InputSchema: canonical,- SchemaDigest: plugincontract.DigestBytes(canonical),+ SchemaDigest: DigestBytes(canonical),})}sort.Slice(tools, func(i, j int) bool { return tools[i].Name < tools[j].Name })@@ -356,8 +353,8 @@ func canonicalJSON(raw json.RawMessage) (json.RawMessage, error) {return json.RawMessage(canonical), err}-func ToolSetDigest(tools []pluginruntime.RemoteMCPTool) (string, error) {- copyTools := append([]pluginruntime.RemoteMCPTool(nil), tools...)+func ToolSetDigest(tools []Tool) (string, error) {+ copyTools := append([]Tool(nil), tools...)for i := range copyTools {canonical, err := canonicalJSON(copyTools[i].InputSchema)if err != nil {@@ -370,5 +367,5 @@ func ToolSetDigest(tools []pluginruntime.RemoteMCPTool) (string, error) {if err != nil {return "", err}- return plugincontract.DigestBytes(raw), nil+ return DigestBytes(raw), nil}diff --git a/server/pkg/remotemcp/client_test.go b/server/pkg/remotemcp/client_test.goindex 33347603a6..c8f5b3cc88 100644--- a/server/pkg/remotemcp/client_test.go+++ b/server/pkg/remotemcp/client_test.go@@ -6,9 +6,6 @@ import ("net/netip""strings""testing"-- "github.com/multica-ai/multica/server/pkg/plugincontract"- "github.com/multica-ai/multica/server/pkg/pluginruntime")type staticResolver map[string][]netip.Addr@@ -66,15 +63,15 @@ func TestToolSetDigestIgnoresInputSchemaObjectKeyOrder(t *testing.T) {if err != nil {t.Fatal(err)}- schemaDigest := plugincontract.DigestBytes(canonical)+ schemaDigest := DigestBytes(canonical)- first, err := ToolSetDigest([]pluginruntime.RemoteMCPTool{{+ first, err := ToolSetDigest([]Tool{{Name: "search", InputSchema: firstSchema, SchemaDigest: schemaDigest, Risk: "read",}})if err != nil {t.Fatal(err)}- second, err := ToolSetDigest([]pluginruntime.RemoteMCPTool{{+ second, err := ToolSetDigest([]Tool{{Name: "search", InputSchema: secondSchema, SchemaDigest: schemaDigest, Risk: "read",}})if err != nil {diff --git a/server/pkg/remotemcp/types.go b/server/pkg/remotemcp/types.gonew file mode 100644index 0000000000..e36fa428a3--- /dev/null+++ b/server/pkg/remotemcp/types.go@@ -0,0 +1,44 @@+package remotemcp++import (+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+)++// Tool is one remote MCP tool pinned by an administrator. SchemaDigest freezes+// the exact input schema that was approved so the daemon broker can reject a+// server that later swaps a tool's contract underneath a running task.+type Tool struct {+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ InputSchema json.RawMessage `json:"input_schema"`+ SchemaDigest string `json:"schema_digest"`+ Risk string `json:"risk,omitempty"`+}++// Connection is claim-time, task-scoped connection metadata. Credentials are+// intentionally absent from this wire type and are resolved just-in-time by the+// daemon broker.+type Connection struct {+ InstallationID string `json:"installation_id"`+ ContributionID string `json:"contribution_id"`+ ContributionKey string `json:"contribution_key"`+ ConfigID string `json:"config_id"`+ ConfigRevision int64 `json:"config_revision"`+ Endpoint string `json:"endpoint"`+ PublicConfig json.RawMessage `json:"public_config,omitempty"`+ Transport string `json:"transport"`+ ProtocolVersions []string `json:"protocol_versions"`+ EndpointAllowedHosts []string `json:"endpoint_allowed_hosts,omitempty"`+ CredentialHeader string `json:"credential_header,omitempty"`+ ApprovedTools []Tool `json:"approved_tools"`+ ToolSchemaDigest string `json:"tool_schema_digest"`+ FailurePolicy string `json:"failure_policy"`+}++// DigestBytes is the content digest used to pin approved tool schemas.+func DigestBytes(content []byte) string {+ digest := sha256.Sum256(content)+ return "sha256:" + hex.EncodeToString(digest[:])+}