Skip to main content

agent_works/plugin/
manifest.rs

1//! plugin.json manifest (schemaVersion 1) — parsing, fail-closed validation,
2//! pre-install human review digest.
3//!
4//! The contract itself = `agent-works/schemas/plugin.schema.json` (a P0 asset;
5//! the schema is the authority published to authors; this module is the runtime
6//! fail-closed enforcement — both sides share the same law).
7//!
8//! - Name law / reserved words go through [`crate::tool_provider::ToolIdentity`]
9//!   (defined in one place);
10//! - Path law goes through [`crate::script_tool::resolve_under_root`] (resolve
11//!   relative to the plugin root + reject escape from it), the same law as the
12//!   global script anti-substitution rules;
13//! - Form exclusivity is enforced per form by serde's `deny_unknown_fields`
14//!   (wasm has no `run`, script has no `capabilities`, mcp has no
15//!   `parameters`…);
16//! - [`PluginManifest::review`] produces the pre-install review digest: full
17//!   manifest + capability breakdown (**resolved concrete values** for
18//!   paths/hosts) — nothing is written to disk before a human signs off
19//!   (product-level gate).
20
21use std::collections::{BTreeMap, BTreeSet};
22use std::path::Path;
23
24use serde::{Deserialize, Serialize};
25
26use crate::script_tool::{
27    ExposureSpec, ParamSpec, ScriptLawError, pin_from_plugin_root, resolve_under_root,
28};
29use crate::tool_provider::{IdentityError, ToolIdentity};
30
31/// Default timeout (seconds) for the wasm form.
32pub const WASM_DEFAULT_TIMEOUT_SECS: u64 = 30;
33
34/// Manifest format version (schemaVersion starts at 1; evolution bumps the
35/// version instead of changing semantics).
36pub const MANIFEST_SCHEMA_VERSION: u32 = 1;
37
38/// Manifest parse/validation errors. fail-closed: reject anything invalid, no
39/// compromises.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub enum ManifestError {
42    /// Wrong JSON syntax or shape (serde).
43    Json(String),
44    /// `schemaVersion` is not 1.
45    BadSchemaVersion(u32),
46    /// Plugin name or tool name is invalid (charset / reserved word / too long).
47    BadName { name: String, source: IdentityError },
48    /// `tools` is empty.
49    EmptyTools,
50    /// Duplicate tool name (including the mcp server label).
51    DuplicateTool { name: String },
52    /// `timeout_secs` is 0 (schema minimum 1).
53    BadTimeout { tool: String },
54    /// `exposure` uses a tier outside the schema (v1 has only direct/deferred).
55    BadExposure { tool: String },
56    /// Invalid capability entry (`fs:read` without paths / `net:http` without
57    /// hosts / empty list).
58    BadCapability { tool: String, reason: String },
59    /// Invalid mcp `server` (command/url not mutually exclusive, env/headers on
60    /// the wrong side, url shape).
61    BadServer { tool: String, reason: String },
62    /// Path-law violation (relative path escaping the plugin root, etc.).
63    PathLaw {
64        tool: String,
65        source: ScriptLawError,
66    },
67    /// `version` is empty.
68    EmptyVersion,
69    /// `skills` entry is an empty string or duplicated.
70    BadSkills { reason: String },
71}
72
73impl std::fmt::Display for ManifestError {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        match self {
76            Self::Json(e) => write!(f, "plugin.json parse error: {e}"),
77            Self::BadSchemaVersion(v) => write!(
78                f,
79                "plugin.json schemaVersion {v} is not supported (this build understands {MANIFEST_SCHEMA_VERSION})"
80            ),
81            Self::BadName { name, source } => write!(f, "invalid name `{name}`: {source}"),
82            Self::EmptyTools => write!(f, "plugin.json must declare at least one tool"),
83            Self::DuplicateTool { name } => {
84                write!(f, "duplicate tool name `{name}` in plugin.json")
85            }
86            Self::BadTimeout { tool } => {
87                write!(f, "tool `{tool}`: timeout_secs must be >= 1")
88            }
89            Self::BadExposure { tool } => {
90                write!(f, "tool `{tool}`: exposure must be `direct` or `deferred`")
91            }
92            Self::BadCapability { tool, reason } => {
93                write!(f, "tool `{tool}`: invalid capability ({reason})")
94            }
95            Self::BadServer { tool, reason } => {
96                write!(f, "tool `{tool}`: invalid mcp server spec ({reason})")
97            }
98            Self::PathLaw { tool, source } => write!(f, "tool `{tool}`: {source}"),
99            Self::EmptyVersion => write!(f, "plugin.json `version` must not be empty"),
100            Self::BadSkills { reason } => write!(f, "plugin.json `skills`: {reason}"),
101        }
102    }
103}
104
105impl std::error::Error for ManifestError {}
106
107/// Payload of a `fs:read` capability entry (`paths`; extra fields rejected —
108/// strict oneOf law).
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(deny_unknown_fields)]
111pub struct FsReadSpec {
112    /// Readable directories/files relative to the plugin root.
113    pub paths: Vec<String>,
114}
115
116/// Payload of a `net:http` capability entry (`hosts`; extra fields rejected —
117/// strict oneOf law).
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(deny_unknown_fields)]
120pub struct NetHttpSpec {
121    /// Outbound HTTP host allow-list.
122    pub hosts: Vec<String>,
123}
124
125/// Capability allow-list entry (declaration form; fail-closed, undeclared =
126/// not granted). wasm form only.
127///
128/// `fs:read` must come with `paths` (WASI preopens are path-scoped: no preopen
129/// = can read nothing, preopening `/` = giving everything); `net:http` must
130/// come with a `hosts` allow-list (filtered at outbound-request time, not on
131/// the list = rejected). Cross fields (fs with hosts / net with paths) are
132/// enforced by the payload structs' `deny_unknown_fields`.
133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(tag = "type", rename_all = "snake_case")]
135pub enum CapabilitySpec {
136    /// Readable directories/files relative to the plugin root (resolved to
137    /// absolute paths at install time and pinned into the registry).
138    #[serde(rename = "fs:read")]
139    FsRead(FsReadSpec),
140    /// Outbound HTTP host allow-list (normalized and pinned into the registry at
141    /// install time).
142    #[serde(rename = "net:http")]
143    NetHttp(NetHttpSpec),
144}
145
146/// Capability allow-list entry (resolved form: paths absolutized / hosts
147/// normalized) — the pinned values in the registry.
148///
149/// Capability enforcement **reads only this** (the external registry), never
150/// the plugin's own manifest.
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152#[serde(tag = "type", rename_all = "snake_case")]
153pub enum ResolvedCapability {
154    /// Absolute path list (pinned at install time via [`resolve_under_root`]).
155    #[serde(rename = "fs:read")]
156    FsRead { paths: Vec<String> },
157    /// Normalized host allow-list (lowercased, whitespace stripped).
158    #[serde(rename = "net:http")]
159    NetHttp { hosts: Vec<String> },
160}
161
162/// Resolve a batch of capability declarations (relative to `plugin_root`).
163pub fn resolve_capabilities(
164    caps: &[CapabilitySpec],
165    plugin_root: &Path,
166) -> Result<Vec<ResolvedCapability>, ScriptLawError> {
167    caps.iter()
168        .map(|c| match c {
169            CapabilitySpec::FsRead(spec) => {
170                let mut resolved = Vec::with_capacity(spec.paths.len());
171                for p in &spec.paths {
172                    resolved.push(resolve_under_root(plugin_root, p)?);
173                }
174                Ok(ResolvedCapability::FsRead { paths: resolved })
175            }
176            CapabilitySpec::NetHttp(spec) => Ok(ResolvedCapability::NetHttp {
177                hosts: spec
178                    .hosts
179                    .iter()
180                    .map(|h| h.trim().to_ascii_lowercase())
181                    .collect(),
182            }),
183        })
184        .collect()
185}
186
187/// In-package MCP server (stdio command or remote URL; env/headers values
188/// reference secrets only as `${ENV:VAR}`, resolved at product-layer
189/// registration).
190#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
191#[serde(deny_unknown_fields)]
192pub struct McpServerSpec {
193    /// stdio form: argv array, no shell. In-package relative paths are pinned
194    /// absolute at install time.
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub command: Option<Vec<String>>,
197    /// stdio environment overrides (inherit + override).
198    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
199    pub env: BTreeMap<String, String>,
200    /// Remote URL form (`http(s)://`).
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub url: Option<String>,
203    /// Remote URL request headers.
204    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
205    pub headers: BTreeMap<String, String>,
206}
207
208/// wasm-form tool entry.
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(deny_unknown_fields)]
211pub struct WasmToolSpec {
212    /// Identity-key tool segment.
213    pub name: String,
214    /// Description shown to the model.
215    pub description: String,
216    /// Component path (relative to the plugin root). WIT world `phi:tool@0.1.0`.
217    pub module: String,
218    /// Parameter sketch (the host validates against it before entering wasm).
219    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
220    pub parameters: BTreeMap<String, ParamSpec>,
221    /// Capability allow-list (fail-closed, undeclared = not granted).
222    #[serde(default, skip_serializing_if = "Vec::is_empty")]
223    pub capabilities: Vec<CapabilitySpec>,
224    /// Timeout (seconds). Defaults to [`WASM_DEFAULT_TIMEOUT_SECS`].
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub timeout_secs: Option<u64>,
227    /// Tool-table budget tier, default direct.
228    #[serde(default)]
229    pub exposure: ExposureSpec,
230}
231
232/// script-form tool entry (in-package relative paths pinned at install time,
233/// the same law as global scripts).
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
235#[serde(deny_unknown_fields)]
236pub struct ScriptToolSpec {
237    /// Identity-key tool segment.
238    pub name: String,
239    /// Description shown to the model.
240    pub description: String,
241    /// argv array, `${param}` substituted per element, no shell.
242    pub run: Vec<String>,
243    /// Parameter sketch.
244    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
245    pub parameters: BTreeMap<String, ParamSpec>,
246    /// Timeout (seconds). Defaults to 60s ([`crate::script_tool::DEFAULT_TIMEOUT_MS`]).
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub timeout_secs: Option<u64>,
249    /// Tool-table budget tier, default direct.
250    #[serde(default)]
251    pub exposure: ExposureSpec,
252}
253
254/// mcp-form tool entry. `name` is a **server label** (not a tool name); each
255/// tool exposed by that server gets one `plugin.{plugin}.{tool-name}` key
256/// (normalized at load time).
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258#[serde(deny_unknown_fields)]
259pub struct McpToolSpec {
260    /// Server label (unique within the manifest; not part of the identity key).
261    pub name: String,
262    /// In-package MCP server (owned by the plugin, not written to
263    /// connections.json).
264    pub server: McpServerSpec,
265    /// Timeout (seconds; reserved for call-level timeouts).
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub timeout_secs: Option<u64>,
268    /// Tool-table budget tier, default direct.
269    #[serde(default)]
270    pub exposure: ExposureSpec,
271}
272
273/// One tool line in plugin.json (the form is decided by `form`).
274///
275/// Form exclusivity (wasm without run/server, script without
276/// module/server/capabilities, mcp without
277/// module/run/capabilities/parameters/description) is enforced by each form
278/// struct's `deny_unknown_fields`.
279#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(tag = "form", rename_all = "lowercase")]
281pub enum PluginToolSpec {
282    /// In-process WASM sandbox (WIT `phi:tool@0.1.0`).
283    Wasm(WasmToolSpec),
284    /// argv-spawned script.
285    Script(ScriptToolSpec),
286    /// In-package MCP server (the answer for multi-language).
287    Mcp(McpToolSpec),
288}
289
290impl PluginToolSpec {
291    /// The `name` field in the manifest (wasm/script = tool name; mcp = server
292    /// label).
293    pub fn name(&self) -> &str {
294        match self {
295            Self::Wasm(t) => &t.name,
296            Self::Script(t) => &t.name,
297            Self::Mcp(t) => &t.name,
298        }
299    }
300
301    /// Form name (for the review digest / registry).
302    pub fn form(&self) -> &'static str {
303        match self {
304            Self::Wasm(_) => "wasm",
305            Self::Script(_) => "script",
306            Self::Mcp(_) => "mcp",
307        }
308    }
309
310    /// Timeout (seconds); `None` if unset (the runtime uses the form's default).
311    pub fn timeout_secs(&self) -> Option<u64> {
312        match self {
313            Self::Wasm(t) => t.timeout_secs,
314            Self::Script(t) => t.timeout_secs,
315            Self::Mcp(t) => t.timeout_secs,
316        }
317    }
318
319    /// Identity key. For wasm/script it is directly `plugin.{plugin}.{name}`;
320    /// for the mcp form the entry name is a server label, and the real tool keys
321    /// are generated at load time from the server's tool names — the label key
322    /// returned here is only used for de-duplication within the manifest and
323    /// review annotations.
324    pub fn identity(&self, plugin_name: &str) -> Result<String, IdentityError> {
325        ToolIdentity::plugin(plugin_name, self.name()).map(|id| id.to_key())
326    }
327}
328
329/// Runtime shape of plugin.json (schemaVersion 1).
330#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
331#[serde(deny_unknown_fields)]
332pub struct PluginManifest {
333    /// Manifest format version (only [`MANIFEST_SCHEMA_VERSION`] is accepted).
334    #[serde(rename = "schemaVersion")]
335    pub schema_version: u32,
336    /// Plugin name (`[a-z0-9_-]{1,32}`; hitting a reserved word is rejected).
337    pub name: String,
338    /// Author-declared version (integrity is governed by the manifest hash, not
339    /// by this field).
340    pub version: String,
341    /// Tools contributed by this plugin (at least one).
342    pub tools: Vec<PluginToolSpec>,
343    /// Skill root directory inside the plugin (relative to the plugin root).
344    #[serde(default, skip_serializing_if = "Vec::is_empty")]
345    pub skills: Vec<String>,
346}
347
348/// One line of the pre-install review digest: the full picture of one tool.
349#[derive(Debug, Clone, PartialEq, Eq)]
350pub struct ReviewTool {
351    /// Identity key (the label key for the mcp form; server tools are normalized
352    /// separately at load time).
353    pub identity: String,
354    /// Form (wasm / script / mcp).
355    pub form: &'static str,
356    /// Execution summary (script = pinned argv; wasm = absolute component path;
357    /// mcp = command/URL).
358    pub summary: String,
359    /// Timeout (seconds; `None` = the form's default).
360    pub timeout_secs: Option<u64>,
361    /// This tool's capability breakdown (**resolved** concrete paths/hosts).
362    pub capabilities: Vec<ResolvedCapability>,
363}
364
365/// Pre-install review digest: the full manifest picture (tools / execution
366/// summaries / capability breakdown).
367///
368/// "Write to disk only after human confirmation": the product layer renders
369/// this, and only after a human nods is
370/// [`crate::plugin::install::commit_install`] allowed (plugins requested by an
371/// agent are never allowed through by default — guaranteed by the product
372/// layer).
373#[derive(Debug, Clone, PartialEq, Eq)]
374pub struct ReviewDigest {
375    /// Plugin name.
376    pub name: String,
377    /// Author version.
378    pub version: String,
379    /// Full picture per tool.
380    pub tools: Vec<ReviewTool>,
381    /// Skill root directories (relative to the plugin root).
382    pub skills: Vec<String>,
383}
384
385impl PluginManifest {
386    /// Parse + fail-closed validation (serde shape + name law + form law +
387    /// capability law).
388    pub fn from_json(raw: &str) -> Result<Self, ManifestError> {
389        let manifest: Self =
390            serde_json::from_str(raw).map_err(|e| ManifestError::Json(e.to_string()))?;
391        manifest.validate()?;
392        Ok(manifest)
393    }
394
395    /// fail-closed validation (rule by rule after parsing).
396    pub fn validate(&self) -> Result<(), ManifestError> {
397        if self.schema_version != MANIFEST_SCHEMA_VERSION {
398            return Err(ManifestError::BadSchemaVersion(self.schema_version));
399        }
400        check_name(&self.name, &self.name)?;
401        if self.version.trim().is_empty() {
402            return Err(ManifestError::EmptyVersion);
403        }
404        if self.tools.is_empty() {
405            return Err(ManifestError::EmptyTools);
406        }
407
408        let mut seen = BTreeSet::new();
409        for tool in &self.tools {
410            check_name(&self.name, tool.name())?;
411            if !seen.insert(tool.name().to_string()) {
412                return Err(ManifestError::DuplicateTool {
413                    name: tool.name().to_string(),
414                });
415            }
416            self.validate_tool(tool)?;
417        }
418
419        let mut skills_seen = BTreeSet::new();
420        for skill in &self.skills {
421            if skill.trim().is_empty() {
422                return Err(ManifestError::BadSkills {
423                    reason: "empty skill directory".into(),
424                });
425            }
426            if !skills_seen.insert(skill.clone()) {
427                return Err(ManifestError::BadSkills {
428                    reason: format!("duplicate skill directory `{skill}`"),
429                });
430            }
431        }
432        Ok(())
433    }
434
435    fn validate_tool(&self, tool: &PluginToolSpec) -> Result<(), ManifestError> {
436        let name = tool.name();
437        if matches!(tool.timeout_secs(), Some(0)) {
438            return Err(ManifestError::BadTimeout {
439                tool: name.to_string(),
440            });
441        }
442        match tool {
443            PluginToolSpec::Wasm(t) => {
444                if t.module.trim().is_empty() {
445                    return Err(ManifestError::PathLaw {
446                        tool: name.to_string(),
447                        source: ScriptLawError::EmptyRun,
448                    });
449                }
450                if t.exposure == ExposureSpec::Hidden {
451                    return Err(ManifestError::BadExposure {
452                        tool: name.to_string(),
453                    });
454                }
455                for cap in &t.capabilities {
456                    match cap {
457                        CapabilitySpec::FsRead(spec) if spec.paths.is_empty() => {
458                            return Err(ManifestError::BadCapability {
459                                tool: name.to_string(),
460                                reason: "fs:read needs at least one path".into(),
461                            });
462                        }
463                        CapabilitySpec::NetHttp(spec) if spec.hosts.is_empty() => {
464                            return Err(ManifestError::BadCapability {
465                                tool: name.to_string(),
466                                reason: "net:http needs at least one host".into(),
467                            });
468                        }
469                        CapabilitySpec::NetHttp(spec)
470                            if spec.hosts.iter().any(|h| h.trim().is_empty()) =>
471                        {
472                            return Err(ManifestError::BadCapability {
473                                tool: name.to_string(),
474                                reason: "net:http host must not be empty".into(),
475                            });
476                        }
477                        _ => {}
478                    }
479                }
480            }
481            PluginToolSpec::Script(t) => {
482                if t.exposure == ExposureSpec::Hidden {
483                    return Err(ManifestError::BadExposure {
484                        tool: name.to_string(),
485                    });
486                }
487                // Here we only check the shape (non-empty); the path law
488                // (`run[0]` absolute / interpreter allow-list) is checked in the
489                // [`pin_from_plugin_root`] of review / install — in-plugin `run`
490                // is **relative to the plugin root**, so before pinning it is
491                // not an absolute path in the first place.
492                if t.run.is_empty() {
493                    return Err(ManifestError::PathLaw {
494                        tool: name.to_string(),
495                        source: ScriptLawError::EmptyRun,
496                    });
497                }
498                if t.run.iter().any(|c| c.trim().is_empty()) {
499                    return Err(ManifestError::PathLaw {
500                        tool: name.to_string(),
501                        source: ScriptLawError::EmptyRun,
502                    });
503                }
504            }
505            PluginToolSpec::Mcp(t) => {
506                if t.exposure == ExposureSpec::Hidden {
507                    return Err(ManifestError::BadExposure {
508                        tool: name.to_string(),
509                    });
510                }
511                validate_server(name, &t.server)?;
512            }
513        }
514        Ok(())
515    }
516
517    /// Pre-install review digest: full manifest + capability breakdown (the
518    /// resolved concrete values of paths/hosts).
519    ///
520    /// `plugin_root` is the **install target root** (`~/.phimint/plugins/<name>`)
521    /// — the absolute paths in the digest are the final authorization values a
522    /// human reviews. Path-law violations fail-closed here too.
523    pub fn review(&self, plugin_root: &Path) -> Result<ReviewDigest, ManifestError> {
524        let mut tools = Vec::with_capacity(self.tools.len());
525        for tool in &self.tools {
526            let identity = tool
527                .identity(&self.name)
528                .map_err(|source| ManifestError::BadName {
529                    name: tool.name().to_string(),
530                    source,
531                })?;
532            let (summary, capabilities) = match tool {
533                PluginToolSpec::Wasm(t) => {
534                    let module = resolve_under_root(plugin_root, &t.module).map_err(|source| {
535                        ManifestError::PathLaw {
536                            tool: t.name.clone(),
537                            source,
538                        }
539                    })?;
540                    let caps =
541                        resolve_capabilities(&t.capabilities, plugin_root).map_err(|source| {
542                            ManifestError::PathLaw {
543                                tool: t.name.clone(),
544                                source,
545                            }
546                        })?;
547                    (format!("wasm module {module}"), caps)
548                }
549                PluginToolSpec::Script(t) => {
550                    let run = pin_from_plugin_root(&t.run, plugin_root).map_err(|source| {
551                        ManifestError::PathLaw {
552                            tool: t.name.clone(),
553                            source,
554                        }
555                    })?;
556                    (run.join(" "), Vec::new())
557                }
558                PluginToolSpec::Mcp(t) => {
559                    let summary = match (&t.server.command, &t.server.url) {
560                        (Some(cmd), _) => format!("mcp stdio: {}", cmd.join(" ")),
561                        (_, Some(url)) => format!("mcp http: {url}"),
562                        _ => "mcp server (invalid)".into(),
563                    };
564                    (summary, Vec::new())
565                }
566            };
567            tools.push(ReviewTool {
568                identity,
569                form: tool.form(),
570                summary,
571                timeout_secs: tool.timeout_secs(),
572                capabilities,
573            });
574        }
575        Ok(ReviewDigest {
576            name: self.name.clone(),
577            version: self.version.clone(),
578            tools,
579            skills: self.skills.clone(),
580        })
581    }
582}
583
584fn check_name(plugin_name: &str, segment: &str) -> Result<(), ManifestError> {
585    ToolIdentity::plugin(plugin_name, segment)
586        .map(|_| ())
587        .map_err(|source| ManifestError::BadName {
588            name: segment.to_string(),
589            source,
590        })
591}
592
593fn validate_server(tool: &str, server: &McpServerSpec) -> Result<(), ManifestError> {
594    let bad = |reason: &str| ManifestError::BadServer {
595        tool: tool.to_string(),
596        reason: reason.to_string(),
597    };
598    match (&server.command, &server.url) {
599        (Some(cmd), None) => {
600            if cmd.is_empty() {
601                return Err(bad("command must not be empty"));
602            }
603            if cmd.iter().any(|c| c.trim().is_empty()) {
604                return Err(bad("command argv entries must not be empty"));
605            }
606            if !server.headers.is_empty() {
607                return Err(bad("headers belong to the url form"));
608            }
609        }
610        (None, Some(url)) => {
611            if !(url.starts_with("https://") || url.starts_with("http://")) {
612                return Err(bad("url must be http(s)://"));
613            }
614            if !server.env.is_empty() {
615                return Err(bad("env belongs to the stdio command form"));
616            }
617        }
618        (Some(_), Some(_)) => return Err(bad("command and url are mutually exclusive")),
619        (None, None) => return Err(bad("either command or url is required")),
620    }
621    Ok(())
622}
623
624#[cfg(test)]
625mod tests {
626    use super::*;
627
628    fn root() -> std::path::PathBuf {
629        // The platform absolute-path law is the same as Path::is_absolute
630        // (runs on unix/windows alike).
631        std::env::current_dir().unwrap().join("plugin-root-test")
632    }
633
634    fn minimal_json() -> serde_json::Value {
635        serde_json::json!({
636            "schemaVersion": 1,
637            "name": "my-tools",
638            "version": "0.1.0",
639            "tools": [{
640                "name": "deploy",
641                "form": "script",
642                "description": "deploy",
643                "run": ["scripts/deploy.sh", "${env}"],
644                "parameters": {"env": {"type": "string"}}
645            }]
646        })
647    }
648
649    #[test]
650    fn parses_design_example_shape() {
651        // The three-form example from the design doc "the shape of a plugin set".
652        let raw = serde_json::json!({
653            "schemaVersion": 1,
654            "name": "my-tools",
655            "version": "0.1.0",
656            "tools": [
657                {
658                    "name": "search", "form": "wasm",
659                    "module": "wasm/search.wasm",
660                    "description": "search",
661                    "parameters": {"q": {"type": "string", "description": "query"}},
662                    "capabilities": [{"type": "fs:read", "paths": ["./data"]}],
663                    "timeout_secs": 30
664                },
665                {
666                    "name": "deploy", "form": "script",
667                    "run": ["scripts/deploy.sh", "${env}"],
668                    "description": "deploy",
669                    "parameters": {"env": {"type": "string"}},
670                    "timeout_secs": 120
671                },
672                {
673                    "name": "wiki", "form": "mcp",
674                    "server": {
675                        "command": ["python", "server/main.py"],
676                        "env": {"WIKI_TOKEN": "${ENV:WIKI_TOKEN}"}
677                    }
678                }
679            ],
680            "skills": ["skills"]
681        });
682        let manifest = PluginManifest::from_json(&raw.to_string()).expect("design example parses");
683        assert_eq!(manifest.tools.len(), 3);
684        assert_eq!(manifest.tools[0].form(), "wasm");
685        assert_eq!(manifest.tools[1].form(), "script");
686        assert_eq!(manifest.tools[2].form(), "mcp");
687        assert_eq!(manifest.skills, vec!["skills"]);
688    }
689
690    #[test]
691    fn rejects_bad_schema_version() {
692        let mut raw = minimal_json();
693        raw["schemaVersion"] = serde_json::json!(2);
694        let err = PluginManifest::from_json(&raw.to_string()).unwrap_err();
695        assert!(matches!(err, ManifestError::BadSchemaVersion(2)), "{err}");
696    }
697
698    #[test]
699    fn rejects_reserved_plugin_name_and_bad_segments() {
700        for name in [
701            "mcp",
702            "script",
703            "plugin",
704            "My Tools",
705            "",
706            "a".repeat(33).as_str(),
707        ] {
708            let mut raw = minimal_json();
709            raw["name"] = serde_json::json!(name);
710            let err = PluginManifest::from_json(&raw.to_string()).unwrap_err();
711            assert!(
712                matches!(err, ManifestError::BadName { .. } | ManifestError::Json(_)),
713                "{name:?} → {err}"
714            );
715        }
716    }
717
718    #[test]
719    fn rejects_duplicate_tool_names() {
720        let mut raw = minimal_json();
721        raw["tools"]
722            .as_array_mut()
723            .unwrap()
724            .push(minimal_json()["tools"][0].clone());
725        let err = PluginManifest::from_json(&raw.to_string()).unwrap_err();
726        assert!(
727            matches!(err, ManifestError::DuplicateTool { ref name } if name == "deploy"),
728            "{err}"
729        );
730    }
731
732    #[test]
733    fn rejects_form_field_bleed() {
734        // Form exclusivity: script cannot carry capabilities / module / server.
735        let mut raw = minimal_json();
736        raw["tools"][0]["capabilities"] = serde_json::json!([{"type": "fs:read", "paths": ["."]}]);
737        assert!(matches!(
738            PluginManifest::from_json(&raw.to_string()),
739            Err(ManifestError::Json(_))
740        ));
741
742        let mut raw = minimal_json();
743        raw["tools"][0]["module"] = serde_json::json!("wasm/x.wasm");
744        assert!(matches!(
745            PluginManifest::from_json(&raw.to_string()),
746            Err(ManifestError::Json(_))
747        ));
748
749        // mcp cannot carry description / parameters.
750        let mut raw = minimal_json();
751        raw["tools"][0] = serde_json::json!({
752            "name": "wiki", "form": "mcp",
753            "description": "nope",
754            "server": {"url": "https://x"}
755        });
756        assert!(matches!(
757            PluginManifest::from_json(&raw.to_string()),
758            Err(ManifestError::Json(_))
759        ));
760    }
761
762    #[test]
763    fn rejects_bad_capability_shapes() {
764        let mut raw = minimal_json();
765        raw["tools"][0] = serde_json::json!({
766            "name": "search", "form": "wasm", "module": "wasm/s.wasm", "description": "d",
767            "capabilities": [{"type": "fs:read", "paths": []}]
768        });
769        let err = PluginManifest::from_json(&raw.to_string()).unwrap_err();
770        assert!(matches!(err, ManifestError::BadCapability { .. }), "{err}");
771
772        // fs:read cannot carry hosts; net:http cannot carry paths (schema oneOf).
773        let mut raw = minimal_json();
774        raw["tools"][0] = serde_json::json!({
775            "name": "search", "form": "wasm", "module": "wasm/s.wasm", "description": "d",
776            "capabilities": [{"type": "fs:read", "paths": ["."], "hosts": ["x"]}]
777        });
778        assert!(matches!(
779            PluginManifest::from_json(&raw.to_string()),
780            Err(ManifestError::Json(_))
781        ));
782    }
783
784    #[test]
785    fn rejects_bad_mcp_server_spec() {
786        // command + url not mutually exclusive / neither present / env hung on
787        // the url side.
788        for server in [
789            serde_json::json!({"command": ["python", "s.py"], "url": "https://x"}),
790            serde_json::json!({}),
791            serde_json::json!({"url": "https://x", "env": {"A": "b"}}),
792            serde_json::json!({"url": "ftp://x"}),
793            serde_json::json!({"command": []}),
794        ] {
795            let mut raw = minimal_json();
796            raw["tools"][0] = serde_json::json!({
797                "name": "wiki", "form": "mcp", "server": server
798            });
799            let err = PluginManifest::from_json(&raw.to_string()).unwrap_err();
800            assert!(
801                matches!(
802                    err,
803                    ManifestError::BadServer { .. } | ManifestError::Json(_)
804                ),
805                "{server} → {err}"
806            );
807        }
808    }
809
810    #[test]
811    fn rejects_zero_timeout_and_hidden_exposure() {
812        let mut raw = minimal_json();
813        raw["tools"][0]["timeout_secs"] = serde_json::json!(0);
814        assert!(matches!(
815            PluginManifest::from_json(&raw.to_string()),
816            Err(ManifestError::BadTimeout { .. })
817        ));
818
819        let mut raw = minimal_json();
820        raw["tools"][0]["exposure"] = serde_json::json!("hidden");
821        assert!(matches!(
822            PluginManifest::from_json(&raw.to_string()),
823            Err(ManifestError::BadExposure { .. })
824        ));
825    }
826
827    #[test]
828    fn review_shows_full_view_with_resolved_paths() {
829        let raw = serde_json::json!({
830            "schemaVersion": 1,
831            "name": "my-tools",
832            "version": "0.1.0",
833            "tools": [
834                {
835                    "name": "search", "form": "wasm",
836                    "module": "wasm/search.wasm",
837                    "description": "search",
838                    "capabilities": [
839                        {"type": "fs:read", "paths": ["./data"]},
840                        {"type": "net:http", "hosts": ["API.Example.com"]}
841                    ],
842                    "timeout_secs": 30
843                },
844                {
845                    "name": "deploy", "form": "script",
846                    "run": ["scripts/deploy.sh", "--env", "${env}"],
847                    "description": "deploy"
848                }
849            ]
850        });
851        let manifest = PluginManifest::from_json(&raw.to_string()).unwrap();
852        let root = root();
853        let digest = manifest.review(&root).unwrap();
854
855        assert_eq!(digest.name, "my-tools");
856        assert_eq!(digest.tools.len(), 2);
857
858        // wasm: the capability breakdown must be resolved concrete values
859        // (absolute paths / lowercase hosts).
860        let wasm = &digest.tools[0];
861        assert_eq!(wasm.identity, "plugin.my-tools.search");
862        let data_abs = root.join("data").to_string_lossy().into_owned();
863        assert_eq!(
864            wasm.capabilities,
865            vec![
866                ResolvedCapability::FsRead {
867                    paths: vec![data_abs]
868                },
869                ResolvedCapability::NetHttp {
870                    hosts: vec!["api.example.com".into()]
871                }
872            ]
873        );
874
875        // script: the execution summary = the pinned argv (absolute paths).
876        let script = &digest.tools[1];
877        assert_eq!(script.identity, "plugin.my-tools.deploy");
878        let run_abs = root
879            .join("scripts/deploy.sh")
880            .to_string_lossy()
881            .into_owned();
882        assert_eq!(script.summary, format!("{run_abs} --env ${{env}}"));
883    }
884
885    #[test]
886    fn review_rejects_escaping_paths() {
887        // Capability/script paths escaping the plugin root → rejected (same law
888        // as anti-substitution).
889        let raw = serde_json::json!({
890            "schemaVersion": 1,
891            "name": "my-tools",
892            "version": "0.1.0",
893            "tools": [{
894                "name": "search", "form": "wasm",
895                "module": "wasm/search.wasm", "description": "d",
896                "capabilities": [{"type": "fs:read", "paths": ["../outside"]}]
897            }]
898        });
899        let manifest = PluginManifest::from_json(&raw.to_string()).unwrap();
900        let err = manifest.review(&root()).unwrap_err();
901        assert!(matches!(err, ManifestError::PathLaw { .. }), "{err}");
902    }
903
904    #[test]
905    fn round_trips_through_json() {
906        let manifest = PluginManifest::from_json(&minimal_json().to_string()).unwrap();
907        let back: PluginManifest =
908            serde_json::from_str(&serde_json::to_string(&manifest).unwrap()).unwrap();
909        assert_eq!(manifest, back);
910    }
911}