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