Skip to main content

dalo/
plugin.rs

1//! Passive portable plugin package discovery and validation.
2//!
3//! A plugin package is inert inventory. Discovery never executes provider
4//! overlays or reserved active component descriptors.
5
6use std::collections::{BTreeMap, BTreeSet};
7use std::fs;
8use std::os::unix::fs::PermissionsExt;
9use std::path::{Path, PathBuf};
10
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13
14use crate::agent::AgentResolution;
15use crate::config::{PluginPolicyDecision, PluginPolicyLayer, UserConfig};
16use crate::hook::{self, HookBindingType, HookDescriptorV1};
17use crate::inventory::SourceInventory;
18use crate::resolver::Resolution;
19use crate::source::SourceConfig;
20use crate::team_manifest::{self, StackRequirement, TEAM_MANIFEST_FILE};
21
22#[cfg(test)]
23thread_local! {
24    static SOURCE_PLUGIN_SCAN_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
25}
26
27#[cfg(test)]
28pub(crate) fn reset_source_plugin_scan_count() {
29    SOURCE_PLUGIN_SCAN_COUNT.with(|count| count.set(0));
30}
31
32#[cfg(test)]
33pub(crate) fn source_plugin_scan_count() -> usize {
34    SOURCE_PLUGIN_SCAN_COUNT.with(std::cell::Cell::get)
35}
36
37/// Canonical plugin manifest filename.
38pub const PLUGIN_FILE: &str = "PLUGIN.toml";
39
40const MAX_MANIFEST_BYTES: u64 = 1024 * 1024;
41const MAX_STRING_BYTES: usize = 16 * 1024;
42const MAX_LIST_ENTRIES: usize = 1024;
43const MAX_TABLE_DEPTH: usize = 32;
44const MAX_PACKAGE_ENTRIES: usize = 4096;
45const MAX_PACKAGE_DEPTH: usize = 32;
46const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024;
47const MAX_PACKAGE_BYTES: u64 = 256 * 1024 * 1024;
48
49type PackageFiles = Vec<PackageFile>;
50
51#[derive(Debug, Clone)]
52struct PackageFile {
53    path: String,
54    executable: bool,
55    bytes: Vec<u8>,
56}
57
58/// Passive plugin inventory for one source.
59#[derive(Debug, Clone, Default, Serialize)]
60pub struct PluginInventory {
61    /// Valid passive plugin packages.
62    pub plugins: Vec<PluginRecord>,
63    /// Non-fatal malformed-package findings.
64    pub warnings: Vec<PluginInventoryWarning>,
65}
66
67/// One validated passive plugin package.
68#[derive(Debug, Clone, Serialize)]
69pub struct PluginRecord {
70    /// Source containing the package.
71    pub source_id: String,
72    /// Canonical identity, `<source-id>:<slot-name>`.
73    pub source_ref: String,
74    /// Plugin slot name.
75    pub slot_name: String,
76    /// Optional stable identity.
77    pub id: Option<String>,
78    /// Human-facing description.
79    pub description: String,
80    /// Optional authored version.
81    pub version: Option<String>,
82    /// Package directory.
83    pub path: PathBuf,
84    /// Canonical manifest path.
85    pub manifest_file: PathBuf,
86    /// Ordered passive component declarations.
87    pub members: Vec<PluginMember>,
88    /// Validated active local-tool descriptors. Discovery remains inert.
89    pub tools: Vec<ToolRecord>,
90    /// Validated hook contracts bound to same-plugin local tools.
91    pub hooks: Vec<HookRecord>,
92    /// Ordered plugin dependency declarations.
93    pub requires: Vec<PluginDependency>,
94    /// Inert provider overlays retained for adapter-specific validation.
95    pub providers: BTreeMap<String, toml::Value>,
96    /// SHA-256 over the complete bounded package tree.
97    pub package_hash: String,
98}
99
100/// One inert plugin-local hook contract with its exact approval identity.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
102pub struct HookRecord {
103    /// Source-qualified identity, `<source>:<plugin>#hook:<id>`.
104    pub source_ref: String,
105    /// Closed portable hook descriptor.
106    pub descriptor: HookDescriptorV1,
107    /// Exact same-plugin tool identity.
108    pub tool_source_ref: String,
109    /// Referenced invocation-contract hash from #499.
110    pub tool_contract_hash: String,
111    /// Complete security-relevant hook contract hash.
112    pub contract_hash: String,
113}
114
115/// One validated plugin-local executable contract. Inventory never executes it.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub struct ToolRecord {
118    /// Descriptor schema version.
119    pub schema_version: u32,
120    /// Plugin-local ID.
121    pub id: String,
122    /// Source-qualified identity, `<source>:<plugin>#tool:<id>`.
123    pub source_ref: String,
124    /// Plugin-root-relative executable entry path.
125    pub entry: String,
126    /// Runtime used to invoke the entry.
127    pub runtime: ToolRuntime,
128    /// Optional authored runtime version requirement.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub runtime_version: Option<String>,
131    /// Explicit supported operating systems; empty means every Dalo platform.
132    pub platforms: Vec<ToolPlatform>,
133    /// Event-independent named input schema.
134    pub inputs: Vec<ToolInput>,
135    /// Canonical exec-style argument template.
136    pub argv: Vec<String>,
137    /// Working-directory policy.
138    pub cwd: ToolCwd,
139    /// Environment variable names admitted into the invocation.
140    pub env: Vec<String>,
141    /// Portable capability claims.
142    pub capabilities: Vec<ToolCapability>,
143    /// Whether missing availability blocks the plugin.
144    pub availability: ToolAvailability,
145    /// Files in the bounded security-relevant closure.
146    pub files: Vec<ToolFileRecord>,
147    /// Deterministic invocation-contract hash; excludes whole-package provenance.
148    pub contract_hash: String,
149}
150
151/// Supported local-tool runtime kinds.
152#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
153#[serde(rename_all = "snake_case")]
154pub enum ToolRuntime {
155    /// Execute the immutable entry directly, without a shell.
156    Executable,
157    /// Invoke the immutable entry with `python3`.
158    Python,
159    /// Invoke the immutable entry with `node`.
160    Node,
161}
162
163impl std::fmt::Display for ToolRuntime {
164    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        formatter.write_str(match self {
166            Self::Executable => "executable",
167            Self::Python => "python",
168            Self::Node => "node",
169        })
170    }
171}
172
173impl ToolRuntime {
174    /// Runtime executable required on PATH, if any.
175    #[must_use]
176    pub const fn executable(self) -> Option<&'static str> {
177        match self {
178            Self::Executable => None,
179            Self::Python => Some("python3"),
180            Self::Node => Some("node"),
181        }
182    }
183}
184
185/// Portable operating-system requirements.
186#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
187#[serde(rename_all = "snake_case")]
188pub enum ToolPlatform {
189    /// Apple macOS.
190    Macos,
191    /// Linux.
192    Linux,
193}
194
195/// One named input admitted by the tool-owned argv template.
196#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
197#[serde(deny_unknown_fields)]
198pub struct ToolInput {
199    /// Stable lower-snake input name.
200    pub name: String,
201    /// Primitive value type.
202    #[serde(rename = "type")]
203    pub kind: ToolInputType,
204    /// Whether callers must supply a value.
205    #[serde(default = "default_true")]
206    pub required: bool,
207}
208
209/// Primitive named-input types supported by descriptor v1.
210#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
211#[serde(rename_all = "snake_case")]
212pub enum ToolInputType {
213    /// UTF-8 text.
214    String,
215    /// Filesystem path passed as opaque argument data.
216    Path,
217    /// Signed integer.
218    Integer,
219    /// Boolean rendered as `true` or `false`.
220    Boolean,
221}
222
223/// Working directory used for execution.
224#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
225#[serde(rename_all = "snake_case")]
226pub enum ToolCwd {
227    /// Root of the immutable staged tool closure.
228    ToolRoot,
229}
230
231/// Portable active-code capability claims.
232#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
233#[serde(rename_all = "snake_case")]
234pub enum ToolCapability {
235    /// Read files outside the immutable closure.
236    FilesystemRead,
237    /// Write files outside the immutable closure.
238    FilesystemWrite,
239    /// Start child processes.
240    Subprocess,
241    /// Access the network.
242    Network,
243}
244
245impl std::fmt::Display for ToolCapability {
246    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247        formatter.write_str(match self {
248            Self::FilesystemRead => "filesystem_read",
249            Self::FilesystemWrite => "filesystem_write",
250            Self::Subprocess => "subprocess",
251            Self::Network => "network",
252        })
253    }
254}
255
256/// Required versus optional tool availability.
257#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
258#[serde(rename_all = "snake_case")]
259pub enum ToolAvailability {
260    /// Unavailable or unapproved blocks coherent activation.
261    Required,
262    /// Unavailable or unapproved is a visible omission.
263    Optional,
264}
265
266impl std::fmt::Display for ToolAvailability {
267    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268        formatter.write_str(match self {
269            Self::Required => "required",
270            Self::Optional => "optional",
271        })
272    }
273}
274
275/// One regular file participating in the tool contract closure.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277pub struct ToolFileRecord {
278    /// Plugin-root-relative path.
279    pub path: String,
280    /// Whether the source file had any executable bit.
281    pub executable: bool,
282    /// SHA-256 of the exact bytes.
283    pub content_hash: String,
284}
285
286/// One passive plugin member.
287#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
288pub struct PluginMember {
289    /// Authored portable reference.
290    #[serde(rename = "ref")]
291    pub reference: ComponentReference,
292    /// Required, optional, or instruction-only recommended membership.
293    pub requirement: MemberRequirement,
294    /// Optional agent-to-required-skill inline fallback.
295    #[serde(skip_serializing_if = "Option::is_none")]
296    pub fallback: Option<InlineFallback>,
297}
298
299/// One plugin dependency.
300#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
301pub struct PluginDependency {
302    /// Authored plugin reference.
303    #[serde(rename = "ref")]
304    pub reference: ComponentReference,
305    /// Dependency strength.
306    pub requirement: DependencyRequirement,
307}
308
309/// Parsed portable component reference.
310#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
311pub struct ComponentReference {
312    /// Component namespace.
313    pub kind: ComponentKind,
314    /// Exact source ID for a cross-source reference, otherwise `None`.
315    #[serde(skip_serializing_if = "Option::is_none")]
316    pub source_id: Option<String>,
317    /// Slot or stable-ID selector.
318    pub selector: String,
319}
320
321impl ComponentReference {
322    /// Render the canonical authored grammar.
323    #[must_use]
324    pub fn as_string(&self) -> String {
325        self.source_id.as_ref().map_or_else(
326            || format!("{}:{}", self.kind.as_str(), self.selector),
327            |source_id| format!("{}:{source_id}:{}", self.kind.as_str(), self.selector),
328        )
329    }
330}
331
332/// Passive component namespaces accepted by schema version 1.
333#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
334#[serde(rename_all = "snake_case")]
335pub enum ComponentKind {
336    /// Another plugin package.
337    Plugin,
338    /// Managed skill.
339    Skill,
340    /// Canonical agent package.
341    Agent,
342    /// Instruction pack.
343    Instruction,
344}
345
346impl ComponentKind {
347    /// Stable reference prefix.
348    #[must_use]
349    pub const fn as_str(self) -> &'static str {
350        match self {
351            Self::Plugin => "plugin",
352            Self::Skill => "skill",
353            Self::Agent => "agent",
354            Self::Instruction => "instruction",
355        }
356    }
357}
358
359/// Membership requirement.
360#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
361#[serde(rename_all = "snake_case")]
362pub enum MemberRequirement {
363    /// Missing or inactive blocks plugin coherence.
364    Required,
365    /// Omission is visible but non-blocking.
366    Optional,
367    /// Instruction-only recommendation that never activates the pack.
368    Recommended,
369}
370
371impl std::fmt::Display for MemberRequirement {
372    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373        formatter.write_str(match self {
374            Self::Required => "required",
375            Self::Optional => "optional",
376            Self::Recommended => "recommended",
377        })
378    }
379}
380
381/// Plugin dependency requirement.
382#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
383#[serde(rename_all = "snake_case")]
384pub enum DependencyRequirement {
385    /// Missing or blocked dependency blocks the dependent.
386    Required,
387    /// Missing dependency is a visible non-blocking omission.
388    Optional,
389}
390
391/// Authored inline fallback for an agent member.
392#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
393pub struct InlineFallback {
394    /// Required skill member used as canonical inline behavior.
395    pub skill: ComponentReference,
396}
397
398/// One non-fatal plugin inventory warning.
399#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
400pub struct PluginInventoryWarning {
401    /// Stable machine-readable warning code.
402    pub code: PluginInventoryWarningCode,
403    /// Package or entry path.
404    pub path: PathBuf,
405    /// Actionable detail.
406    pub message: String,
407}
408
409/// Plugin inventory warning codes.
410#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
411#[serde(rename_all = "snake_case")]
412pub enum PluginInventoryWarningCode {
413    /// Invalid schema, identity, reference, or a violated safety bound.
414    InvalidPackage,
415    /// Symlink or unsupported special file in the package boundary.
416    UnsafePackageEntry,
417    /// Two valid packages declare the same stable identity.
418    DuplicateStableId,
419    /// A source path could not be read.
420    UnreadablePath,
421    /// Reserved active-code descriptors are not accepted by the passive slice.
422    UnsupportedActiveComponentSchema,
423}
424
425impl PluginInventoryWarningCode {
426    /// Stable snake-case label.
427    #[must_use]
428    pub const fn as_str(self) -> &'static str {
429        match self {
430            Self::InvalidPackage => "invalid_plugin_package",
431            Self::UnsafePackageEntry => "unsafe_plugin_package_entry",
432            Self::DuplicateStableId => "duplicate_plugin_stable_id",
433            Self::UnreadablePath => "unreadable_plugin_path",
434            Self::UnsupportedActiveComponentSchema => "unsupported_active_component_schema",
435        }
436    }
437}
438
439impl std::fmt::Display for PluginInventoryWarningCode {
440    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
441        formatter.write_str(self.as_str())
442    }
443}
444
445#[derive(Debug, Deserialize)]
446#[serde(deny_unknown_fields)]
447struct Manifest {
448    schema_version: u32,
449    plugin: ManifestPlugin,
450    #[serde(default)]
451    providers: BTreeMap<String, toml::Value>,
452    #[serde(default, rename = "tool")]
453    tools: Vec<ManifestTool>,
454    #[serde(default, rename = "hook")]
455    hooks: Vec<HookDescriptorV1>,
456}
457
458#[derive(Debug, Deserialize)]
459#[serde(deny_unknown_fields)]
460struct ManifestPlugin {
461    name: String,
462    #[serde(default)]
463    id: Option<String>,
464    description: String,
465    #[serde(default)]
466    version: Option<String>,
467    #[serde(default)]
468    members: Vec<ManifestMember>,
469    #[serde(default)]
470    requires: Vec<ManifestDependency>,
471}
472
473#[derive(Debug, Deserialize)]
474#[serde(deny_unknown_fields)]
475struct ManifestMember {
476    #[serde(rename = "ref")]
477    reference: String,
478    requirement: MemberRequirement,
479    #[serde(default)]
480    fallback: Option<ManifestFallback>,
481}
482
483#[derive(Debug, Deserialize)]
484#[serde(deny_unknown_fields)]
485struct ManifestDependency {
486    #[serde(rename = "ref")]
487    reference: String,
488    requirement: DependencyRequirement,
489}
490
491#[derive(Debug, Deserialize)]
492#[serde(deny_unknown_fields)]
493struct ManifestFallback {
494    kind: String,
495    skill: String,
496}
497
498#[derive(Debug, Deserialize)]
499#[serde(deny_unknown_fields)]
500struct ManifestTool {
501    schema_version: u32,
502    id: String,
503    entry: String,
504    runtime: ToolRuntime,
505    #[serde(default)]
506    runtime_version: Option<String>,
507    #[serde(default)]
508    platforms: Vec<ToolPlatform>,
509    #[serde(default)]
510    inputs: Vec<ToolInput>,
511    argv: Vec<String>,
512    #[serde(default)]
513    files: Vec<String>,
514    cwd: ToolCwd,
515    #[serde(default)]
516    env: Vec<String>,
517    #[serde(default)]
518    capabilities: Vec<ToolCapability>,
519    availability: ToolAvailability,
520}
521
522const fn default_true() -> bool {
523    true
524}
525
526/// Scan only exact `plugins/<name>/PLUGIN.toml` packages in one source.
527#[must_use]
528pub fn scan_source_plugins(source_id: &str, source_root: &Path) -> PluginInventory {
529    #[cfg(test)]
530    SOURCE_PLUGIN_SCAN_COUNT.with(|count| count.set(count.get() + 1));
531    let plugins_root = source_root.join("plugins");
532    let metadata = match fs::symlink_metadata(&plugins_root) {
533        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
534            return PluginInventory::default();
535        }
536        Err(error) => {
537            return inventory_warning(
538                PluginInventoryWarningCode::UnreadablePath,
539                plugins_root,
540                error.to_string(),
541            );
542        }
543        Ok(metadata) => metadata,
544    };
545    if metadata.file_type().is_symlink() {
546        return inventory_warning(
547            PluginInventoryWarningCode::UnsafePackageEntry,
548            plugins_root,
549            "the source `plugins` directory must not be a symlink".to_owned(),
550        );
551    }
552    if !metadata.is_dir() {
553        return inventory_warning(
554            PluginInventoryWarningCode::InvalidPackage,
555            plugins_root,
556            "the source `plugins` path must be a directory".to_owned(),
557        );
558    }
559
560    let entries = match fs::read_dir(&plugins_root) {
561        Ok(entries) => entries,
562        Err(error) => {
563            return inventory_warning(
564                PluginInventoryWarningCode::UnreadablePath,
565                plugins_root,
566                error.to_string(),
567            );
568        }
569    };
570    let mut packages = Vec::new();
571    let mut warnings = Vec::new();
572    for entry in entries {
573        let entry = match entry {
574            Ok(entry) => entry,
575            Err(error) => {
576                warnings.push(warning(
577                    PluginInventoryWarningCode::UnreadablePath,
578                    plugins_root.clone(),
579                    error.to_string(),
580                ));
581                continue;
582            }
583        };
584        let path = entry.path();
585        let file_type = match entry.file_type() {
586            Ok(file_type) => file_type,
587            Err(error) => {
588                warnings.push(warning(
589                    PluginInventoryWarningCode::UnreadablePath,
590                    path,
591                    error.to_string(),
592                ));
593                continue;
594            }
595        };
596        if file_type.is_symlink() {
597            warnings.push(warning(
598                PluginInventoryWarningCode::UnsafePackageEntry,
599                path,
600                "plugin package directories must not be symlinks".to_owned(),
601            ));
602        } else if file_type.is_dir() && path.join(PLUGIN_FILE).exists() {
603            packages.push(path);
604        }
605    }
606    packages.sort();
607
608    let mut plugins = Vec::new();
609    for package_path in packages {
610        match scan_package(source_id, &package_path) {
611            Ok(plugin) => plugins.push(plugin),
612            Err((code, error)) => warnings.push(warning(code, package_path, error)),
613        }
614    }
615    reject_duplicate_stable_ids(source_id, &mut plugins, &mut warnings);
616    plugins.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
617    warnings.sort_by(|left, right| {
618        left.path
619            .cmp(&right.path)
620            .then_with(|| left.code.as_str().cmp(right.code.as_str()))
621    });
622    PluginInventory { plugins, warnings }
623}
624
625fn inventory_warning(
626    code: PluginInventoryWarningCode,
627    path: PathBuf,
628    message: String,
629) -> PluginInventory {
630    PluginInventory {
631        plugins: Vec::new(),
632        warnings: vec![warning(code, path, message)],
633    }
634}
635
636fn warning(
637    code: PluginInventoryWarningCode,
638    path: PathBuf,
639    message: String,
640) -> PluginInventoryWarning {
641    PluginInventoryWarning {
642        code,
643        path,
644        message,
645    }
646}
647
648fn scan_package(
649    source_id: &str,
650    package_path: &Path,
651) -> Result<PluginRecord, (PluginInventoryWarningCode, String)> {
652    let package_name = package_path
653        .file_name()
654        .and_then(|name| name.to_str())
655        .ok_or_else(|| invalid("plugin package directory name must be valid UTF-8"))?;
656    if !is_plugin_name(package_name) {
657        return Err(invalid(
658            "plugin package directory must use lower kebab-case",
659        ));
660    }
661    let entries = collect_package_files(package_path)?;
662    let manifest_file = package_path.join(PLUGIN_FILE);
663    let manifest_bytes = entries
664        .iter()
665        .find_map(|entry| (entry.path == PLUGIN_FILE).then_some(entry.bytes.as_slice()))
666        .ok_or_else(|| invalid(format!("package is missing {PLUGIN_FILE}")))?;
667    if manifest_bytes.len() as u64 > MAX_MANIFEST_BYTES {
668        return Err(invalid(format!(
669            "{PLUGIN_FILE} exceeds the {MAX_MANIFEST_BYTES}-byte safety limit"
670        )));
671    }
672    let document = std::str::from_utf8(manifest_bytes)
673        .map_err(|_| invalid(format!("{PLUGIN_FILE} must be valid UTF-8")))?;
674    let value: toml::Value =
675        toml::from_str(document).map_err(|error| invalid(format!("invalid TOML: {error}")))?;
676    validate_toml_bounds(&value, 0)?;
677    let manifest: Manifest = value
678        .try_into()
679        .map_err(|error| invalid(format!("invalid plugin schema: {error}")))?;
680    if manifest.schema_version != 1 {
681        return Err(invalid(format!(
682            "unsupported plugin schema version {} (supported: 1)",
683            manifest.schema_version
684        )));
685    }
686    validate_manifest(package_name, &manifest)?;
687    let members = manifest
688        .plugin
689        .members
690        .iter()
691        .map(parse_member)
692        .collect::<Result<Vec<_>, _>>()?;
693    let requires = manifest
694        .plugin
695        .requires
696        .iter()
697        .map(parse_dependency)
698        .collect::<Result<Vec<_>, _>>()?;
699    validate_member_closure(&members)?;
700    let plugin_ref = format!("{source_id}:{package_name}");
701    let tools = parse_tools(&plugin_ref, &manifest.tools, &entries)?;
702    let hooks = parse_hooks(&plugin_ref, &manifest.hooks, &tools)?;
703    let package_hash = hash_package_files(&entries);
704
705    Ok(PluginRecord {
706        source_id: source_id.to_owned(),
707        source_ref: plugin_ref,
708        slot_name: package_name.to_owned(),
709        id: manifest.plugin.id,
710        description: manifest.plugin.description,
711        version: manifest.plugin.version,
712        path: package_path.to_path_buf(),
713        manifest_file,
714        members,
715        tools,
716        hooks,
717        requires,
718        providers: manifest.providers,
719        package_hash,
720    })
721}
722
723fn parse_hooks(
724    plugin_ref: &str,
725    descriptors: &[HookDescriptorV1],
726    tools: &[ToolRecord],
727) -> Result<Vec<HookRecord>, (PluginInventoryWarningCode, String)> {
728    if descriptors.len() > MAX_LIST_ENTRIES {
729        return Err(invalid(format!(
730            "plugin declares more than {MAX_LIST_ENTRIES} hooks"
731        )));
732    }
733    let mut ids = BTreeSet::new();
734    let mut hooks = Vec::with_capacity(descriptors.len());
735    for descriptor in descriptors {
736        if descriptor.schema_version != 1 {
737            return Err((
738                PluginInventoryWarningCode::UnsupportedActiveComponentSchema,
739                format!(
740                    "hook `{}` uses unsupported descriptor schema {} (supported: 1)",
741                    descriptor.id, descriptor.schema_version
742                ),
743            ));
744        }
745        hook::validate_descriptor(descriptor).map_err(invalid)?;
746        if !ids.insert(descriptor.id.as_str()) {
747            return Err(invalid(format!(
748                "plugin contains duplicate hook ID `{}`",
749                descriptor.id
750            )));
751        }
752        let tool = tools
753            .iter()
754            .find(|candidate| candidate.id == descriptor.tool)
755            .ok_or_else(|| {
756                invalid(format!(
757                    "hook `{}` references missing same-plugin tool `{}`",
758                    descriptor.id, descriptor.tool
759                ))
760            })?;
761        let tool_inputs = tool
762            .inputs
763            .iter()
764            .map(|input| (input.name.as_str(), input))
765            .collect::<BTreeMap<_, _>>();
766        for binding in &descriptor.bindings {
767            let input = tool_inputs.get(binding.input.as_str()).ok_or_else(|| {
768                invalid(format!(
769                    "hook `{}` binds unknown tool input `{}`",
770                    descriptor.id, binding.input
771                ))
772            })?;
773            let expected = match input.kind {
774                ToolInputType::String => Some(HookBindingType::String),
775                ToolInputType::Path => Some(HookBindingType::Path),
776                ToolInputType::Boolean => Some(HookBindingType::Boolean),
777                ToolInputType::Integer => None,
778            };
779            if expected != Some(binding.field.input_type()) {
780                return Err(invalid(format!(
781                    "hook `{}` field `{}` is incompatible with tool input `{}`",
782                    descriptor.id,
783                    binding.field.as_str(),
784                    binding.input
785                )));
786            }
787        }
788        for input in tool.inputs.iter().filter(|input| input.required) {
789            if !descriptor
790                .bindings
791                .iter()
792                .any(|binding| binding.input == input.name)
793            {
794                return Err(invalid(format!(
795                    "hook `{}` does not bind required tool input `{}`",
796                    descriptor.id, input.name
797                )));
798            }
799        }
800        let source_ref = format!("{plugin_ref}#hook:{}", descriptor.id);
801        let contract_hash = hook::contract_hash(
802            &source_ref,
803            descriptor,
804            &tool.source_ref,
805            &tool.contract_hash,
806        );
807        hooks.push(HookRecord {
808            source_ref,
809            descriptor: descriptor.clone(),
810            tool_source_ref: tool.source_ref.clone(),
811            tool_contract_hash: tool.contract_hash.clone(),
812            contract_hash,
813        });
814    }
815    hooks.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
816    Ok(hooks)
817}
818
819fn invalid(message: impl Into<String>) -> (PluginInventoryWarningCode, String) {
820    (PluginInventoryWarningCode::InvalidPackage, message.into())
821}
822
823fn validate_manifest(
824    package_name: &str,
825    manifest: &Manifest,
826) -> Result<(), (PluginInventoryWarningCode, String)> {
827    let plugin = &manifest.plugin;
828    if plugin.name != package_name {
829        return Err(invalid(format!(
830            "plugin.name `{}` must equal package directory `{package_name}`",
831            plugin.name
832        )));
833    }
834    if plugin.description.trim().is_empty() {
835        return Err(invalid("plugin.description must not be empty"));
836    }
837    if let Some(id) = &plugin.id
838        && !is_stable_id(id)
839    {
840        return Err(invalid(
841            "plugin.id must be 1-128 ASCII lower-case characters using dots or hyphens as separators",
842        ));
843    }
844    if plugin.members.len() > MAX_LIST_ENTRIES || plugin.requires.len() > MAX_LIST_ENTRIES {
845        return Err(invalid(format!(
846            "plugin lists may contain at most {MAX_LIST_ENTRIES} entries"
847        )));
848    }
849    let member_refs = plugin
850        .members
851        .iter()
852        .map(|member| member.reference.as_str())
853        .collect::<BTreeSet<_>>();
854    if member_refs.len() != plugin.members.len() {
855        return Err(invalid("plugin contains duplicate member declarations"));
856    }
857    let dependency_refs = plugin
858        .requires
859        .iter()
860        .map(|dependency| dependency.reference.as_str())
861        .collect::<BTreeSet<_>>();
862    if dependency_refs.len() != plugin.requires.len() {
863        return Err(invalid("plugin contains duplicate dependency declarations"));
864    }
865    Ok(())
866}
867
868fn parse_member(
869    member: &ManifestMember,
870) -> Result<PluginMember, (PluginInventoryWarningCode, String)> {
871    let reference = parse_reference(&member.reference)?;
872    if reference.kind == ComponentKind::Plugin {
873        return Err(invalid(
874            "plugin members may reference only skill, agent, or instruction components",
875        ));
876    }
877    if member.requirement == MemberRequirement::Recommended
878        && reference.kind != ComponentKind::Instruction
879    {
880        return Err(invalid(
881            "recommended membership is valid only for instructions",
882        ));
883    }
884    let fallback = member
885        .fallback
886        .as_ref()
887        .map(|fallback| {
888            if reference.kind != ComponentKind::Agent {
889                return Err(invalid("fallback is valid only for agent members"));
890            }
891            if fallback.kind != "inline" {
892                return Err(invalid("fallback.kind must be `inline`"));
893            }
894            let skill = parse_reference(&fallback.skill)?;
895            if skill.kind != ComponentKind::Skill {
896                return Err(invalid("inline fallback must reference a skill"));
897            }
898            Ok(InlineFallback { skill })
899        })
900        .transpose()?;
901    Ok(PluginMember {
902        reference,
903        requirement: member.requirement,
904        fallback,
905    })
906}
907
908fn parse_dependency(
909    dependency: &ManifestDependency,
910) -> Result<PluginDependency, (PluginInventoryWarningCode, String)> {
911    let reference = parse_reference(&dependency.reference)?;
912    if reference.kind != ComponentKind::Plugin {
913        return Err(invalid(
914            "plugin.requires entries must use plugin references",
915        ));
916    }
917    Ok(PluginDependency {
918        reference,
919        requirement: dependency.requirement,
920    })
921}
922
923fn parse_reference(
924    reference: &str,
925) -> Result<ComponentReference, (PluginInventoryWarningCode, String)> {
926    let parts = reference.split(':').collect::<Vec<_>>();
927    if !(parts.len() == 2 || parts.len() == 3) || parts.iter().any(|part| part.is_empty()) {
928        return Err(invalid(format!("invalid portable reference `{reference}`")));
929    }
930    let kind = match parts[0] {
931        "plugin" => ComponentKind::Plugin,
932        "skill" => ComponentKind::Skill,
933        "agent" => ComponentKind::Agent,
934        "instruction" => ComponentKind::Instruction,
935        _ => return Err(invalid(format!("unknown reference kind in `{reference}`"))),
936    };
937    let (source_id, selector) = if parts.len() == 3 {
938        if !is_reference_atom(parts[1]) {
939            return Err(invalid(format!("invalid source ID in `{reference}`")));
940        }
941        (Some(parts[1].to_owned()), parts[2])
942    } else {
943        (None, parts[1])
944    };
945    if !is_reference_atom(selector) {
946        return Err(invalid(format!("invalid selector in `{reference}`")));
947    }
948    Ok(ComponentReference {
949        kind,
950        source_id,
951        selector: selector.to_owned(),
952    })
953}
954
955fn validate_member_closure(
956    members: &[PluginMember],
957) -> Result<(), (PluginInventoryWarningCode, String)> {
958    let required_skills = members
959        .iter()
960        .filter(|member| {
961            member.reference.kind == ComponentKind::Skill
962                && member.requirement == MemberRequirement::Required
963        })
964        .map(|member| &member.reference)
965        .collect::<BTreeSet<_>>();
966    for fallback in members.iter().filter_map(|member| member.fallback.as_ref()) {
967        if !required_skills.contains(&fallback.skill) {
968            return Err(invalid(format!(
969                "inline fallback `{}` must also be a required skill member",
970                fallback.skill.as_string()
971            )));
972        }
973    }
974    Ok(())
975}
976
977fn parse_tools(
978    plugin_ref: &str,
979    descriptors: &[ManifestTool],
980    package_files: &PackageFiles,
981) -> Result<Vec<ToolRecord>, (PluginInventoryWarningCode, String)> {
982    if descriptors.len() > MAX_LIST_ENTRIES {
983        return Err(invalid(format!(
984            "plugin declares more than {MAX_LIST_ENTRIES} tools"
985        )));
986    }
987    let mut ids = BTreeSet::new();
988    let mut tools = Vec::with_capacity(descriptors.len());
989    for descriptor in descriptors {
990        if descriptor.schema_version != 1 {
991            return Err((
992                PluginInventoryWarningCode::UnsupportedActiveComponentSchema,
993                format!(
994                    "tool `{}` uses unsupported descriptor schema {} (supported: 1)",
995                    descriptor.id, descriptor.schema_version
996                ),
997            ));
998        }
999        if !is_plugin_name(&descriptor.id) {
1000            return Err(invalid("tool.id must use lower kebab-case"));
1001        }
1002        if !ids.insert(descriptor.id.as_str()) {
1003            return Err(invalid(format!(
1004                "plugin contains duplicate tool ID `{}`",
1005                descriptor.id
1006            )));
1007        }
1008        let entry = validate_tool_path(&descriptor.entry)?;
1009        if descriptor.files.len() > MAX_LIST_ENTRIES {
1010            return Err(invalid(format!(
1011                "tool `{}` declares too many closure files",
1012                descriptor.id
1013            )));
1014        }
1015        if descriptor.argv.len() > MAX_LIST_ENTRIES {
1016            return Err(invalid(format!(
1017                "tool `{}` argv template is too large",
1018                descriptor.id
1019            )));
1020        }
1021        let mut input_names = BTreeSet::new();
1022        for input in &descriptor.inputs {
1023            if !is_input_name(&input.name) || !input_names.insert(input.name.as_str()) {
1024                return Err(invalid(format!(
1025                    "tool `{}` input names must be unique lower_snake_case values",
1026                    descriptor.id
1027                )));
1028            }
1029        }
1030        for argument in &descriptor.argv {
1031            if argument.len() > MAX_STRING_BYTES {
1032                return Err(invalid(format!(
1033                    "tool `{}` contains an oversized argv element",
1034                    descriptor.id
1035                )));
1036            }
1037            if let Some(name) = argument
1038                .strip_prefix("${input.")
1039                .and_then(|value| value.strip_suffix('}'))
1040            {
1041                if !input_names.contains(name) {
1042                    return Err(invalid(format!(
1043                        "tool `{}` argv references unknown input `{name}`",
1044                        descriptor.id
1045                    )));
1046                }
1047            } else if argument.contains("${") {
1048                return Err(invalid(format!(
1049                    "tool `{}` uses an unsafe placeholder; v1 accepts only whole-token `${{input.name}}` values",
1050                    descriptor.id
1051                )));
1052            }
1053        }
1054        if let Some(version) = &descriptor.runtime_version
1055            && (version.is_empty()
1056                || version.len() > 128
1057                || !version.bytes().all(|byte| {
1058                    byte.is_ascii_alphanumeric()
1059                        || matches!(byte, b'.' | b'-' | b'+' | b'<' | b'>' | b'=' | b' ')
1060                }))
1061        {
1062            return Err(invalid(format!(
1063                "tool `{}` has an invalid runtime_version requirement",
1064                descriptor.id
1065            )));
1066        }
1067        let mut platforms = descriptor.platforms.clone();
1068        platforms.sort();
1069        platforms.dedup();
1070        let mut env = descriptor.env.clone();
1071        env.sort();
1072        env.dedup();
1073        if env.len() != descriptor.env.len() || env.iter().any(|name| !is_env_name(name)) {
1074            return Err(invalid(format!(
1075                "tool `{}` env values must be unique portable environment names",
1076                descriptor.id
1077            )));
1078        }
1079        let mut capabilities = descriptor.capabilities.clone();
1080        capabilities.sort();
1081        capabilities.dedup();
1082
1083        let mut closure_paths = BTreeSet::from([entry.clone()]);
1084        for path in &descriptor.files {
1085            let path = validate_tool_path(path)?;
1086            if !closure_paths.insert(path) {
1087                return Err(invalid(format!(
1088                    "tool `{}` contains a duplicate closure path",
1089                    descriptor.id
1090                )));
1091            }
1092        }
1093        let mut files = Vec::with_capacity(closure_paths.len());
1094        for path in closure_paths {
1095            let package_file = package_files
1096                .iter()
1097                .find(|candidate| candidate.path == path)
1098                .ok_or_else(|| {
1099                    invalid(format!(
1100                        "tool `{}` references missing regular file `{path}`",
1101                        descriptor.id
1102                    ))
1103                })?;
1104            files.push(ToolFileRecord {
1105                path,
1106                executable: package_file.executable,
1107                content_hash: hash_bytes(&package_file.bytes),
1108            });
1109        }
1110        if descriptor.runtime == ToolRuntime::Executable
1111            && !files
1112                .iter()
1113                .find(|file| file.path == entry)
1114                .is_some_and(|file| file.executable)
1115        {
1116            return Err(invalid(format!(
1117                "tool `{}` executable entry is not marked executable",
1118                descriptor.id
1119            )));
1120        }
1121        let source_ref = format!("{plugin_ref}#tool:{}", descriptor.id);
1122        let mut record = ToolRecord {
1123            schema_version: descriptor.schema_version,
1124            id: descriptor.id.clone(),
1125            source_ref,
1126            entry,
1127            runtime: descriptor.runtime,
1128            runtime_version: descriptor.runtime_version.clone(),
1129            platforms,
1130            inputs: descriptor.inputs.clone(),
1131            argv: descriptor.argv.clone(),
1132            cwd: descriptor.cwd,
1133            env,
1134            capabilities,
1135            availability: descriptor.availability,
1136            files,
1137            contract_hash: String::new(),
1138        };
1139        record.contract_hash = hash_tool_contract(&record);
1140        tools.push(record);
1141    }
1142    tools.sort_by(|left, right| left.id.cmp(&right.id));
1143    Ok(tools)
1144}
1145
1146fn validate_tool_path(path: &str) -> Result<String, (PluginInventoryWarningCode, String)> {
1147    if path.is_empty() || path.len() > MAX_STRING_BYTES || path.contains('\\') {
1148        return Err(invalid(
1149            "tool paths must be non-empty portable relative paths",
1150        ));
1151    }
1152    let candidate = Path::new(path);
1153    if candidate.is_absolute()
1154        || candidate.components().any(|part| {
1155            !matches!(part, std::path::Component::Normal(_)) || part.as_os_str().to_str().is_none()
1156        })
1157    {
1158        return Err(invalid(format!(
1159            "tool path `{path}` must stay lexically inside the plugin package"
1160        )));
1161    }
1162    Ok(candidate
1163        .components()
1164        .map(|part| part.as_os_str().to_string_lossy())
1165        .collect::<Vec<_>>()
1166        .join("/"))
1167}
1168
1169fn is_input_name(value: &str) -> bool {
1170    !value.is_empty()
1171        && value.len() <= 128
1172        && value
1173            .bytes()
1174            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1175        && value.as_bytes()[0].is_ascii_lowercase()
1176        && !value.ends_with('_')
1177        && !value.contains("__")
1178}
1179
1180fn is_env_name(value: &str) -> bool {
1181    !value.is_empty()
1182        && value.len() <= 128
1183        && (value.as_bytes()[0].is_ascii_uppercase() || value.as_bytes()[0] == b'_')
1184        && value
1185            .bytes()
1186            .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_')
1187}
1188
1189fn hash_bytes(bytes: &[u8]) -> String {
1190    let digest = Sha256::digest(bytes);
1191    digest.iter().map(|byte| format!("{byte:02x}")).collect()
1192}
1193
1194fn hash_tool_contract(tool: &ToolRecord) -> String {
1195    let mut hash = Sha256::new();
1196    hash.update(b"dalo-tool-contract-v1\0");
1197    hash_contract_value(&mut hash, &tool.source_ref);
1198    hash_contract_value(&mut hash, &tool.schema_version.to_string());
1199    hash_contract_value(&mut hash, &tool.entry);
1200    hash_contract_value(&mut hash, &format!("{:?}", tool.runtime));
1201    hash_contract_value(&mut hash, tool.runtime_version.as_deref().unwrap_or(""));
1202    for platform in &tool.platforms {
1203        hash_contract_value(&mut hash, &format!("platform:{platform:?}"));
1204    }
1205    for input in &tool.inputs {
1206        hash_contract_value(
1207            &mut hash,
1208            &format!("input:{}:{:?}:{}", input.name, input.kind, input.required),
1209        );
1210    }
1211    for argument in &tool.argv {
1212        hash_contract_value(&mut hash, &format!("argv:{argument}"));
1213    }
1214    hash_contract_value(&mut hash, &format!("cwd:{:?}", tool.cwd));
1215    for name in &tool.env {
1216        hash_contract_value(&mut hash, &format!("env:{name}"));
1217    }
1218    for capability in &tool.capabilities {
1219        hash_contract_value(&mut hash, &format!("capability:{capability:?}"));
1220    }
1221    hash_contract_value(&mut hash, &format!("availability:{:?}", tool.availability));
1222    for file in &tool.files {
1223        hash_contract_value(
1224            &mut hash,
1225            &format!(
1226                "file:{}:{}:{}",
1227                file.path, file.executable, file.content_hash
1228            ),
1229        );
1230    }
1231    hash.finalize()
1232        .iter()
1233        .map(|byte| format!("{byte:02x}"))
1234        .collect()
1235}
1236
1237/// Length-prefixed framing shared by every contract hash in this crate.
1238pub(crate) fn hash_contract_value(hash: &mut Sha256, value: &str) {
1239    hash.update((value.len() as u64).to_be_bytes());
1240    hash.update(value.as_bytes());
1241}
1242
1243fn validate_toml_bounds(
1244    value: &toml::Value,
1245    depth: usize,
1246) -> Result<(), (PluginInventoryWarningCode, String)> {
1247    if depth > MAX_TABLE_DEPTH {
1248        return Err(invalid(format!(
1249            "TOML nesting exceeds {MAX_TABLE_DEPTH} levels"
1250        )));
1251    }
1252    match value {
1253        toml::Value::String(value) if value.len() > MAX_STRING_BYTES => Err(invalid(format!(
1254            "TOML string exceeds {MAX_STRING_BYTES} bytes"
1255        ))),
1256        toml::Value::Array(values) => {
1257            if values.len() > MAX_LIST_ENTRIES {
1258                return Err(invalid(format!(
1259                    "TOML list exceeds {MAX_LIST_ENTRIES} entries"
1260                )));
1261            }
1262            for value in values {
1263                validate_toml_bounds(value, depth + 1)?;
1264            }
1265            Ok(())
1266        }
1267        toml::Value::Table(values) => {
1268            if values.len() > MAX_LIST_ENTRIES {
1269                return Err(invalid(format!(
1270                    "TOML table exceeds {MAX_LIST_ENTRIES} entries"
1271                )));
1272            }
1273            for (key, value) in values {
1274                if key.len() > MAX_STRING_BYTES {
1275                    return Err(invalid(format!(
1276                        "TOML key exceeds {MAX_STRING_BYTES} bytes"
1277                    )));
1278                }
1279                validate_toml_bounds(value, depth + 1)?;
1280            }
1281            Ok(())
1282        }
1283        _ => Ok(()),
1284    }
1285}
1286
1287fn collect_package_files(
1288    package_path: &Path,
1289) -> Result<PackageFiles, (PluginInventoryWarningCode, String)> {
1290    let mut files = Vec::new();
1291    let mut entry_count = 0;
1292    let mut total_bytes = 0_u64;
1293    collect_package_files_inner(
1294        package_path,
1295        package_path,
1296        0,
1297        &mut files,
1298        &mut entry_count,
1299        &mut total_bytes,
1300    )?;
1301    files.sort_by(|left, right| left.path.cmp(&right.path));
1302    Ok(files)
1303}
1304
1305fn collect_package_files_inner(
1306    package_root: &Path,
1307    current: &Path,
1308    depth: usize,
1309    files: &mut PackageFiles,
1310    entry_count: &mut usize,
1311    total_bytes: &mut u64,
1312) -> Result<(), (PluginInventoryWarningCode, String)> {
1313    if depth > MAX_PACKAGE_DEPTH {
1314        return Err(invalid(format!(
1315            "package exceeds {MAX_PACKAGE_DEPTH} directory levels"
1316        )));
1317    }
1318    let mut entries = fs::read_dir(current)
1319        .map_err(|error| {
1320            (
1321                PluginInventoryWarningCode::UnreadablePath,
1322                error.to_string(),
1323            )
1324        })?
1325        .map(|entry| {
1326            entry.map_err(|error| {
1327                (
1328                    PluginInventoryWarningCode::UnreadablePath,
1329                    error.to_string(),
1330                )
1331            })
1332        })
1333        .collect::<Result<Vec<_>, _>>()?;
1334    entries.sort_by_key(|entry| entry.file_name());
1335    for entry in entries {
1336        *entry_count += 1;
1337        if *entry_count > MAX_PACKAGE_ENTRIES {
1338            return Err(invalid(format!(
1339                "package exceeds {MAX_PACKAGE_ENTRIES} entries"
1340            )));
1341        }
1342        let path = entry.path();
1343        let file_type = entry.file_type().map_err(|error| {
1344            (
1345                PluginInventoryWarningCode::UnreadablePath,
1346                error.to_string(),
1347            )
1348        })?;
1349        if file_type.is_symlink() {
1350            return Err((
1351                PluginInventoryWarningCode::UnsafePackageEntry,
1352                format!("package contains symlink `{}`", path.display()),
1353            ));
1354        }
1355        if file_type.is_dir() {
1356            collect_package_files_inner(
1357                package_root,
1358                &path,
1359                depth + 1,
1360                files,
1361                entry_count,
1362                total_bytes,
1363            )?;
1364            continue;
1365        }
1366        if !file_type.is_file() {
1367            return Err((
1368                PluginInventoryWarningCode::UnsafePackageEntry,
1369                format!(
1370                    "package contains unsupported special file `{}`",
1371                    path.display()
1372                ),
1373            ));
1374        }
1375        let metadata = entry.metadata().map_err(|error| {
1376            (
1377                PluginInventoryWarningCode::UnreadablePath,
1378                error.to_string(),
1379            )
1380        })?;
1381        if metadata.len() > MAX_FILE_BYTES {
1382            return Err(invalid(format!(
1383                "file `{}` exceeds {MAX_FILE_BYTES} bytes",
1384                path.display()
1385            )));
1386        }
1387        let relative = relative_package_path(package_root, &path)?;
1388        let executable = metadata.permissions().mode() & 0o111 != 0;
1389        let bytes = fs::read(&path).map_err(|error| {
1390            (
1391                PluginInventoryWarningCode::UnreadablePath,
1392                error.to_string(),
1393            )
1394        })?;
1395        if bytes.len() as u64 > MAX_FILE_BYTES {
1396            return Err(invalid(format!(
1397                "file `{}` exceeded {MAX_FILE_BYTES} bytes while being read",
1398                path.display()
1399            )));
1400        }
1401        *total_bytes = total_bytes
1402            .checked_add(bytes.len() as u64)
1403            .ok_or_else(|| invalid("package byte count overflowed"))?;
1404        if *total_bytes > MAX_PACKAGE_BYTES {
1405            return Err(invalid(format!(
1406                "package exceeds {MAX_PACKAGE_BYTES} total bytes"
1407            )));
1408        }
1409        files.push(PackageFile {
1410            path: relative,
1411            executable,
1412            bytes,
1413        });
1414    }
1415    Ok(())
1416}
1417
1418fn relative_package_path(
1419    package_root: &Path,
1420    path: &Path,
1421) -> Result<String, (PluginInventoryWarningCode, String)> {
1422    let relative = path
1423        .strip_prefix(package_root)
1424        .map_err(|_| invalid("package entry escaped its package root"))?;
1425    let mut parts = Vec::new();
1426    for part in relative.components() {
1427        let std::path::Component::Normal(part) = part else {
1428            return Err(invalid("package contains a non-normal path component"));
1429        };
1430        parts.push(
1431            part.to_str()
1432                .ok_or_else(|| invalid("package entry path must be valid UTF-8"))?,
1433        );
1434    }
1435    Ok(parts.join("/"))
1436}
1437
1438fn hash_package_files(entries: &PackageFiles) -> String {
1439    let mut hash = Sha256::new();
1440    hash.update(b"dalo-plugin-package-v1\0");
1441    for entry in entries {
1442        hash.update((entry.path.len() as u64).to_be_bytes());
1443        hash.update(entry.path.as_bytes());
1444        hash.update(*b"f");
1445        hash.update([u8::from(entry.executable)]);
1446        hash.update((entry.bytes.len() as u64).to_be_bytes());
1447        hash.update(&entry.bytes);
1448    }
1449    hash.finalize()
1450        .iter()
1451        .map(|byte| format!("{byte:02x}"))
1452        .collect()
1453}
1454
1455fn reject_duplicate_stable_ids(
1456    source_id: &str,
1457    plugins: &mut Vec<PluginRecord>,
1458    warnings: &mut Vec<PluginInventoryWarning>,
1459) {
1460    let mut paths_by_id = BTreeMap::<String, Vec<PathBuf>>::new();
1461    for plugin in plugins.iter() {
1462        if let Some(id) = &plugin.id {
1463            paths_by_id
1464                .entry(id.clone())
1465                .or_default()
1466                .push(plugin.path.clone());
1467        }
1468    }
1469    let duplicated = paths_by_id
1470        .into_iter()
1471        .filter(|(_, paths)| paths.len() > 1)
1472        .collect::<Vec<_>>();
1473    for (id, paths) in duplicated {
1474        for path in paths {
1475            warnings.push(warning(
1476                PluginInventoryWarningCode::DuplicateStableId,
1477                path,
1478                format!("source `{source_id}` contains multiple plugins with stable ID `{id}`"),
1479            ));
1480        }
1481        plugins.retain(|plugin| plugin.id.as_deref() != Some(id.as_str()));
1482    }
1483}
1484
1485/// Lower kebab-case name rule shared by plugin slots, tool IDs, and binary IDs.
1486pub(crate) fn is_plugin_name(value: &str) -> bool {
1487    !value.is_empty()
1488        && value
1489            .bytes()
1490            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
1491        && !value.starts_with('-')
1492        && !value.ends_with('-')
1493        && !value.contains("--")
1494}
1495
1496fn is_stable_id(value: &str) -> bool {
1497    !value.is_empty()
1498        && value.len() <= 128
1499        && value.is_ascii()
1500        && value.bytes().all(|byte| {
1501            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'-')
1502        })
1503        && value
1504            .bytes()
1505            .next()
1506            .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
1507        && value
1508            .bytes()
1509            .last()
1510            .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
1511        && !value.contains("..")
1512        && !value.contains("--")
1513        && !value.contains(".-")
1514        && !value.contains("-.")
1515}
1516
1517fn is_reference_atom(value: &str) -> bool {
1518    !value.is_empty() && value.len() <= MAX_STRING_BYTES && !value.contains([':', '#', '/', '\\'])
1519}
1520
1521/// Source of selected plugin intent.
1522#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1523#[serde(rename_all = "snake_case")]
1524pub enum SelectionOriginKind {
1525    /// Authored team stack manifest.
1526    Stack,
1527    /// Additive local user selection.
1528    Direct,
1529    /// Reachable dependency from another selected plugin.
1530    Dependency,
1531}
1532
1533/// Strength retained on one selection origin.
1534#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1535#[serde(rename_all = "snake_case")]
1536pub enum SelectionStrength {
1537    /// Optional dependency intent.
1538    Optional,
1539    /// Recommended authored-stack intent.
1540    Recommended,
1541    /// Required stack, direct, or dependency intent.
1542    Required,
1543}
1544
1545/// Provenance for one selected plugin identity.
1546#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1547pub struct SelectionOrigin {
1548    /// Origin namespace.
1549    pub kind: SelectionOriginKind,
1550    /// Manifest source, local config, or declaring plugin identity.
1551    pub declared_by: String,
1552    /// Strength contributed by this origin.
1553    pub requirement: SelectionStrength,
1554}
1555
1556/// Canonical plugin state before target adapters run.
1557#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1558#[serde(rename_all = "snake_case")]
1559pub enum PluginState {
1560    /// Selected passive package with a coherent required closure.
1561    Selected,
1562    /// Required dependency or component is not coherent.
1563    Blocked,
1564    /// Selected intent suppressed by an explicit local policy.
1565    Declined,
1566    /// Selected candidate lost its plugin slot to a higher-precedence candidate.
1567    Shadowed,
1568}
1569
1570impl std::fmt::Display for PluginState {
1571    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1572        formatter.write_str(match self {
1573            Self::Selected => "selected",
1574            Self::Blocked => "blocked",
1575            Self::Declined => "declined",
1576            Self::Shadowed => "shadowed",
1577        })
1578    }
1579}
1580
1581/// Passive component availability state.
1582#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1583#[serde(rename_all = "snake_case")]
1584pub enum PluginComponentState {
1585    /// Component passed its independent activation boundary.
1586    Active,
1587    /// Component exists but still needs its scoped approval.
1588    PendingApproval,
1589    /// Component exists but lost its own namespace slot.
1590    Shadowed,
1591    /// Component exists but its own closure is blocked.
1592    Blocked,
1593    /// Canonical component is present in the exact requested source.
1594    Available,
1595    /// Instruction is present but remains independently inactive.
1596    Inactive,
1597    /// Reference matched no component.
1598    Missing,
1599    /// Slot and stable-ID lookup matched different components.
1600    Ambiguous,
1601}
1602
1603impl std::fmt::Display for PluginComponentState {
1604    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1605        formatter.write_str(match self {
1606            Self::Active => "active",
1607            Self::PendingApproval => "pending_approval",
1608            Self::Shadowed => "shadowed",
1609            Self::Blocked => "blocked",
1610            Self::Available => "available",
1611            Self::Inactive => "inactive",
1612            Self::Missing => "missing",
1613            Self::Ambiguous => "ambiguous",
1614        })
1615    }
1616}
1617
1618/// Evaluated passive member in canonical structured output.
1619#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1620pub struct ResolvedPluginMember {
1621    /// Authored portable reference.
1622    pub reference: String,
1623    /// Membership requirement.
1624    pub requirement: MemberRequirement,
1625    /// Availability without granting activation.
1626    pub state: PluginComponentState,
1627    /// Canonical source-qualified component identity when resolved.
1628    #[serde(skip_serializing_if = "Option::is_none")]
1629    pub resolved_ref: Option<String>,
1630    /// Authored required-skill inline fallback for an agent member.
1631    #[serde(default, skip_serializing_if = "Option::is_none")]
1632    pub fallback: Option<String>,
1633}
1634
1635/// Canonical dependency outcome retained for planning and display.
1636#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1637pub struct ResolvedPluginDependency {
1638    /// Authored plugin reference.
1639    pub reference: String,
1640    /// Dependency requirement.
1641    pub requirement: DependencyRequirement,
1642    /// Exact dependency outcome.
1643    pub state: PluginDependencyState,
1644    /// Canonical identity when reference lookup succeeded.
1645    #[serde(default, skip_serializing_if = "Option::is_none")]
1646    pub resolved_ref: Option<String>,
1647}
1648
1649/// Canonical plugin dependency state.
1650#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1651#[serde(rename_all = "snake_case")]
1652pub enum PluginDependencyState {
1653    /// Dependency is the selected winner of its plugin slot.
1654    Selected,
1655    /// Dependency candidate exists but lost its plugin slot.
1656    Shadowed,
1657    /// Dependency is suppressed by explicit local policy.
1658    Declined,
1659    /// Exact source contained no matching plugin.
1660    Missing,
1661    /// Slot and stable-ID lookup selected different packages.
1662    Ambiguous,
1663}
1664
1665impl std::fmt::Display for PluginDependencyState {
1666    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1667        formatter.write_str(match self {
1668            Self::Selected => "selected",
1669            Self::Shadowed => "shadowed",
1670            Self::Declined => "declined",
1671            Self::Missing => "missing",
1672            Self::Ambiguous => "ambiguous",
1673        })
1674    }
1675}
1676
1677/// One canonical selected or shadowed plugin.
1678#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1679pub struct ResolvedPlugin {
1680    /// Canonical `<source-id>:<slot-name>` identity.
1681    pub source_ref: String,
1682    /// Plugin slot name.
1683    pub slot_name: String,
1684    /// Stable optional identity.
1685    pub id: Option<String>,
1686    /// Source priority used for deterministic winner selection.
1687    pub source_priority: i32,
1688    /// Complete package-tree hash.
1689    pub package_hash: String,
1690    /// Effective passive closure hash, excluding selection provenance.
1691    pub closure_hash: String,
1692    /// All retained selection origins.
1693    pub origins: Vec<SelectionOrigin>,
1694    /// Applied policy decisions, retained outside the closure hash.
1695    pub policies: Vec<AppliedPluginPolicy>,
1696    /// Canonical state.
1697    pub state: PluginState,
1698    /// Winning identity for a shadowed candidate.
1699    #[serde(skip_serializing_if = "Option::is_none")]
1700    pub shadowed_by: Option<String>,
1701    /// Passive component findings.
1702    pub members: Vec<ResolvedPluginMember>,
1703    /// Canonical dependency outcomes.
1704    pub dependencies: Vec<ResolvedPluginDependency>,
1705    /// Deterministic blocking reasons.
1706    pub blocking_reasons: Vec<String>,
1707}
1708
1709/// One applied local policy decision with its audit provenance.
1710#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1711pub struct AppliedPluginPolicy {
1712    /// Persisted local layer.
1713    pub layer: PluginPolicyLayer,
1714    /// Stable rule identity.
1715    pub rule_id: String,
1716    /// Version-2 policy decision.
1717    pub decision: PluginPolicyDecision,
1718    /// Human audit context; excluded from closure hashing.
1719    pub reason: String,
1720}
1721
1722/// Machine-readable plugin resolution diagnostic.
1723#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1724pub struct PluginDiagnostic {
1725    /// Stable diagnostic code.
1726    pub code: PluginDiagnosticCode,
1727    /// Affected authored reference or canonical identity.
1728    pub subject: String,
1729    /// Actionable detail.
1730    pub message: String,
1731}
1732
1733/// Plugin resolution diagnostic codes.
1734#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1735#[serde(rename_all = "snake_case")]
1736pub enum PluginDiagnosticCode {
1737    /// Authored stack could not be parsed or did not identify its source.
1738    InvalidStackSelection,
1739    /// Selected plugin or dependency does not exist in the exact source.
1740    MissingPlugin,
1741    /// Slot and stable identity select different packages.
1742    AmbiguousPluginReference,
1743    /// Required plugin dependencies contain a cycle.
1744    RequiredDependencyCycle,
1745    /// A selected candidate lost its global plugin slot.
1746    ShadowedPlugin,
1747    /// Required member is missing or inactive.
1748    RequiredMemberBlocked,
1749    /// Explicit local decline retained selection intent.
1750    DeclinedPlugin,
1751}
1752
1753impl std::fmt::Display for PluginDiagnosticCode {
1754    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1755        formatter.write_str(match self {
1756            Self::InvalidStackSelection => "invalid_stack_selection",
1757            Self::MissingPlugin => "missing_plugin",
1758            Self::AmbiguousPluginReference => "ambiguous_plugin_reference",
1759            Self::RequiredDependencyCycle => "required_dependency_cycle",
1760            Self::ShadowedPlugin => "shadowed_plugin",
1761            Self::RequiredMemberBlocked => "required_member_blocked",
1762            Self::DeclinedPlugin => "declined_plugin",
1763        })
1764    }
1765}
1766
1767/// Deterministic target-independent passive plugin resolution.
1768#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
1769pub struct PluginResolution {
1770    /// Reachable selected and shadowed plugin candidates.
1771    pub plugins: Vec<ResolvedPlugin>,
1772    /// Typed graph and coherence diagnostics.
1773    pub diagnostics: Vec<PluginDiagnostic>,
1774}
1775
1776/// Safe read-only candidate summary used by plugin list/show.
1777#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1778pub struct PluginCandidate {
1779    /// Canonical source-qualified identity.
1780    pub source_ref: String,
1781    /// Plugin slot name.
1782    pub slot_name: String,
1783    /// Optional stable identity.
1784    pub id: Option<String>,
1785    /// Human-facing description.
1786    pub description: String,
1787    /// Optional authored version.
1788    pub version: Option<String>,
1789    /// Package directory.
1790    pub path: PathBuf,
1791    /// Complete bounded package hash.
1792    pub package_hash: String,
1793    /// Passive members.
1794    pub members: Vec<PluginMember>,
1795    /// Inert validated local-tool contracts.
1796    pub tools: Vec<ToolRecord>,
1797    /// Inert validated hook contracts.
1798    pub hooks: Vec<HookRecord>,
1799    /// Plugin dependencies.
1800    pub requires: Vec<PluginDependency>,
1801    /// Provider overlay names; overlay values remain adapter-private.
1802    pub provider_overlays: Vec<String>,
1803}
1804
1805/// Read-only plugin list report including unselected offers and selected state.
1806#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1807pub struct PluginListReport {
1808    /// Every valid candidate in enabled source order, then identity order.
1809    pub candidates: Vec<PluginCandidate>,
1810    /// Canonical selected graph.
1811    pub resolution: PluginResolution,
1812}
1813
1814/// Read-only detail for one exact candidate.
1815#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1816pub struct PluginShowReport {
1817    /// Candidate package metadata.
1818    pub candidate: PluginCandidate,
1819    /// Selected state when the candidate is reachable, otherwise `None`.
1820    #[serde(skip_serializing_if = "Option::is_none")]
1821    pub selected: Option<ResolvedPlugin>,
1822}
1823
1824/// Build a deterministic safe candidate list without exposing provider overlay
1825/// values that may contain source-authored secrets.
1826#[must_use]
1827pub fn list_report(
1828    sources: &[SourceConfig],
1829    inventories: &[SourceInventory],
1830    resolution: PluginResolution,
1831) -> PluginListReport {
1832    let priorities = sources
1833        .iter()
1834        .filter(|source| source.enabled)
1835        .map(|source| (source.id.as_str(), source.priority))
1836        .collect::<BTreeMap<_, _>>();
1837    let mut candidates = inventories
1838        .iter()
1839        .flat_map(|inventory| &inventory.plugins)
1840        .map(candidate_summary)
1841        .collect::<Vec<_>>();
1842    candidates.sort_by(|left, right| {
1843        priorities
1844            .get(
1845                left.source_ref
1846                    .split_once(':')
1847                    .map_or("", |(source, _)| source),
1848            )
1849            .unwrap_or(&i32::MAX)
1850            .cmp(
1851                priorities
1852                    .get(
1853                        right
1854                            .source_ref
1855                            .split_once(':')
1856                            .map_or("", |(source, _)| source),
1857                    )
1858                    .unwrap_or(&i32::MAX),
1859            )
1860            .then_with(|| left.source_ref.cmp(&right.source_ref))
1861    });
1862    PluginListReport {
1863        candidates,
1864        resolution,
1865    }
1866}
1867
1868/// Build read-only detail for a normalized candidate identity.
1869#[must_use]
1870pub fn show_report(
1871    identity: &str,
1872    inventories: &[SourceInventory],
1873    resolution: &PluginResolution,
1874) -> Option<PluginShowReport> {
1875    let record = inventories
1876        .iter()
1877        .flat_map(|inventory| &inventory.plugins)
1878        .find(|plugin| plugin.source_ref == identity)?;
1879    Some(PluginShowReport {
1880        candidate: candidate_summary(record),
1881        selected: resolution
1882            .plugins
1883            .iter()
1884            .find(|plugin| plugin.source_ref == identity)
1885            .cloned(),
1886    })
1887}
1888
1889fn candidate_summary(record: &PluginRecord) -> PluginCandidate {
1890    PluginCandidate {
1891        source_ref: record.source_ref.clone(),
1892        slot_name: record.slot_name.clone(),
1893        id: record.id.clone(),
1894        description: record.description.clone(),
1895        version: record.version.clone(),
1896        path: record.path.clone(),
1897        package_hash: record.package_hash.clone(),
1898        members: record.members.clone(),
1899        tools: record.tools.clone(),
1900        hooks: record.hooks.clone(),
1901        requires: record.requires.clone(),
1902        provider_overlays: record.providers.keys().cloned().collect(),
1903    }
1904}
1905
1906#[derive(Debug, Clone)]
1907struct CandidateIndex<'a> {
1908    by_source: BTreeMap<&'a str, Vec<&'a PluginRecord>>,
1909    source_priority: BTreeMap<&'a str, i32>,
1910}
1911
1912/// Resolve authored stack and direct-user plugin intent without target input.
1913#[must_use]
1914pub fn resolve_plugins(config: &UserConfig, inventories: &[SourceInventory]) -> PluginResolution {
1915    let index = candidate_index(&config.sources, inventories);
1916    let mut diagnostics = Vec::new();
1917    let mut roots = BTreeSet::new();
1918    let mut origins = BTreeMap::<String, BTreeSet<SelectionOrigin>>::new();
1919
1920    for reference in &config.plugins.direct {
1921        add_root(
1922            reference,
1923            SelectionOrigin {
1924                kind: SelectionOriginKind::Direct,
1925                declared_by: "user_config".to_owned(),
1926                requirement: SelectionStrength::Required,
1927            },
1928            &index,
1929            &mut roots,
1930            &mut origins,
1931            &mut diagnostics,
1932        );
1933    }
1934    for source in config.sources.iter().filter(|source| source.enabled) {
1935        let source_root =
1936            match crate::source::scoped_source_root(&source.path, source.subpath.as_deref()) {
1937                Ok(root) => root,
1938                Err(error) => {
1939                    diagnostics.push(PluginDiagnostic {
1940                        code: PluginDiagnosticCode::InvalidStackSelection,
1941                        subject: source.id.clone(),
1942                        message: error.to_string(),
1943                    });
1944                    continue;
1945                }
1946            };
1947        let path = source_root.join(TEAM_MANIFEST_FILE);
1948        let manifest = match team_manifest::read_manifest(&path) {
1949            Ok(Some(manifest)) => manifest,
1950            Ok(None) => continue,
1951            Err(error) => {
1952                diagnostics.push(PluginDiagnostic {
1953                    code: PluginDiagnosticCode::InvalidStackSelection,
1954                    subject: source.id.clone(),
1955                    message: error.to_string(),
1956                });
1957                continue;
1958            }
1959        };
1960        let Some(selection) = manifest.selection else {
1961            continue;
1962        };
1963        if manifest
1964            .source
1965            .as_ref()
1966            .and_then(|metadata| metadata.id.as_deref())
1967            != Some(source.id.as_str())
1968        {
1969            diagnostics.push(PluginDiagnostic {
1970                code: PluginDiagnosticCode::InvalidStackSelection,
1971                subject: source.id.clone(),
1972                message: "[source].id must match the configured source when [selection] is present"
1973                    .to_owned(),
1974            });
1975            continue;
1976        }
1977        let mut seen = BTreeSet::new();
1978        for selected in selection.plugins {
1979            if !seen.insert(selected.reference.clone()) {
1980                diagnostics.push(PluginDiagnostic {
1981                    code: PluginDiagnosticCode::InvalidStackSelection,
1982                    subject: selected.reference,
1983                    message: "duplicate plugin selection in one manifest".to_owned(),
1984                });
1985                continue;
1986            }
1987            add_root(
1988                &selected.reference,
1989                SelectionOrigin {
1990                    kind: SelectionOriginKind::Stack,
1991                    declared_by: source.id.clone(),
1992                    requirement: match selected.requirement {
1993                        StackRequirement::Required => SelectionStrength::Required,
1994                        StackRequirement::Recommended => SelectionStrength::Recommended,
1995                    },
1996                },
1997                &index,
1998                &mut roots,
1999                &mut origins,
2000                &mut diagnostics,
2001            );
2002        }
2003    }
2004
2005    let mut reachable = roots.clone();
2006    loop {
2007        let winners = winner_map(&reachable, &index);
2008        let mut next = roots.clone();
2009        let mut queue = winners.values().cloned().collect::<Vec<_>>();
2010        queue.sort();
2011        while let Some(identity) = queue.pop() {
2012            let Some(plugin) = plugin_by_identity(&identity, &index) else {
2013                continue;
2014            };
2015            for dependency in &plugin.requires {
2016                match resolve_component_reference(&dependency.reference, &plugin.source_id, &index)
2017                {
2018                    ReferenceMatch::One(candidate) => {
2019                        let dependency_id = candidate.source_ref.clone();
2020                        origins
2021                            .entry(dependency_id.clone())
2022                            .or_default()
2023                            .insert(SelectionOrigin {
2024                                kind: SelectionOriginKind::Dependency,
2025                                declared_by: plugin.source_ref.clone(),
2026                                requirement: match dependency.requirement {
2027                                    DependencyRequirement::Required => SelectionStrength::Required,
2028                                    DependencyRequirement::Optional => SelectionStrength::Optional,
2029                                },
2030                            });
2031                        if next.insert(dependency_id.clone()) {
2032                            queue.push(dependency_id);
2033                        }
2034                    }
2035                    ReferenceMatch::Missing
2036                        if dependency.requirement == DependencyRequirement::Required =>
2037                    {
2038                        diagnostics.push(PluginDiagnostic {
2039                            code: PluginDiagnosticCode::MissingPlugin,
2040                            subject: plugin.source_ref.clone(),
2041                            message: format!(
2042                                "required dependency `{}` is missing",
2043                                dependency.reference.as_string()
2044                            ),
2045                        });
2046                    }
2047                    ReferenceMatch::Ambiguous
2048                        if dependency.requirement == DependencyRequirement::Required =>
2049                    {
2050                        diagnostics.push(PluginDiagnostic {
2051                            code: PluginDiagnosticCode::AmbiguousPluginReference,
2052                            subject: plugin.source_ref.clone(),
2053                            message: format!(
2054                                "required dependency `{}` is ambiguous",
2055                                dependency.reference.as_string()
2056                            ),
2057                        });
2058                    }
2059                    _ => {}
2060                }
2061            }
2062        }
2063        if next == reachable {
2064            break;
2065        }
2066        reachable = next;
2067    }
2068
2069    let winners = winner_map(&reachable, &index);
2070    let cycles = required_cycle_nodes(&winners, &index);
2071    for cycle in &cycles {
2072        diagnostics.push(PluginDiagnostic {
2073            code: PluginDiagnosticCode::RequiredDependencyCycle,
2074            subject: cycle.join(","),
2075            message: format!("required plugin dependency cycle: {}", cycle.join(" -> ")),
2076        });
2077    }
2078    let cycle_nodes = cycles.iter().flatten().cloned().collect::<BTreeSet<_>>();
2079    let mut policies = applied_policies(config, &index, &mut diagnostics);
2080    let declined = policies.keys().cloned().collect::<BTreeSet<_>>();
2081    let mut resolved = Vec::new();
2082    for identity in &reachable {
2083        let Some(plugin) = plugin_by_identity(identity, &index) else {
2084            continue;
2085        };
2086        let winner = winners.get(&plugin.slot_name).cloned();
2087        let shadowed_by = winner
2088            .as_ref()
2089            .filter(|winner| *winner != identity)
2090            .cloned();
2091        let mut blocking_reasons = Vec::new();
2092        let members = evaluate_members(plugin, &config.sources, inventories, &mut blocking_reasons);
2093        for reason in &blocking_reasons {
2094            diagnostics.push(PluginDiagnostic {
2095                code: PluginDiagnosticCode::RequiredMemberBlocked,
2096                subject: identity.clone(),
2097                message: reason.clone(),
2098            });
2099        }
2100        let dependencies = plugin
2101            .requires
2102            .iter()
2103            .map(|dependency| {
2104                let (state, resolved_ref) = match resolve_component_reference(
2105                    &dependency.reference,
2106                    &plugin.source_id,
2107                    &index,
2108                ) {
2109                    ReferenceMatch::One(target) => {
2110                        let state = if winners.get(&target.slot_name) != Some(&target.source_ref) {
2111                            PluginDependencyState::Shadowed
2112                        } else if declined.contains(&target.source_ref) {
2113                            PluginDependencyState::Declined
2114                        } else {
2115                            PluginDependencyState::Selected
2116                        };
2117                        (state, Some(target.source_ref.clone()))
2118                    }
2119                    ReferenceMatch::Missing => (PluginDependencyState::Missing, None),
2120                    ReferenceMatch::Ambiguous => (PluginDependencyState::Ambiguous, None),
2121                };
2122                if dependency.requirement == DependencyRequirement::Required
2123                    && state != PluginDependencyState::Selected
2124                {
2125                    blocking_reasons.push(
2126                        format!(
2127                            "required dependency `{}` is {state}",
2128                            dependency.reference.as_string()
2129                        )
2130                        .to_lowercase(),
2131                    );
2132                }
2133                ResolvedPluginDependency {
2134                    reference: dependency.reference.as_string(),
2135                    requirement: dependency.requirement,
2136                    state,
2137                    resolved_ref,
2138                }
2139            })
2140            .collect::<Vec<_>>();
2141        if cycle_nodes.contains(identity) {
2142            blocking_reasons.push("required dependency cycle".to_owned());
2143        }
2144        let state = if shadowed_by.is_some() {
2145            PluginState::Shadowed
2146        } else if policies.contains_key(identity) {
2147            PluginState::Declined
2148        } else if blocking_reasons.is_empty() {
2149            PluginState::Selected
2150        } else {
2151            PluginState::Blocked
2152        };
2153        if let Some(winner) = &shadowed_by {
2154            diagnostics.push(PluginDiagnostic {
2155                code: PluginDiagnosticCode::ShadowedPlugin,
2156                subject: identity.clone(),
2157                message: format!("selected plugin is shadowed by `{winner}`"),
2158            });
2159        }
2160        let closure_hash = closure_hash(
2161            plugin,
2162            &members,
2163            &dependencies,
2164            &blocking_reasons,
2165            state,
2166            &winners,
2167            &index,
2168        );
2169        resolved.push(ResolvedPlugin {
2170            source_ref: identity.clone(),
2171            slot_name: plugin.slot_name.clone(),
2172            id: plugin.id.clone(),
2173            source_priority: *index
2174                .source_priority
2175                .get(plugin.source_id.as_str())
2176                .unwrap_or(&i32::MAX),
2177            package_hash: plugin.package_hash.clone(),
2178            closure_hash,
2179            origins: origins
2180                .remove(identity)
2181                .unwrap_or_default()
2182                .into_iter()
2183                .collect(),
2184            policies: policies.remove(identity).unwrap_or_default(),
2185            state,
2186            shadowed_by,
2187            members,
2188            dependencies,
2189            blocking_reasons,
2190        });
2191    }
2192    resolved.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
2193    diagnostics.sort_by(|left, right| {
2194        left.subject
2195            .cmp(&right.subject)
2196            .then_with(|| format!("{:?}", left.code).cmp(&format!("{:?}", right.code)))
2197            .then_with(|| left.message.cmp(&right.message))
2198    });
2199    diagnostics.dedup();
2200    PluginResolution {
2201        plugins: resolved,
2202        diagnostics,
2203    }
2204}
2205
2206/// Normalize a source-qualified slot or stable-ID selector to canonical plugin
2207/// identity without changing selection state.
2208pub fn normalize_plugin_reference(
2209    config: &UserConfig,
2210    inventories: &[SourceInventory],
2211    reference: &str,
2212) -> Result<String, String> {
2213    let index = candidate_index(&config.sources, inventories);
2214    match resolve_qualified(reference, &index) {
2215        ReferenceMatch::One(plugin) => Ok(plugin.source_ref.clone()),
2216        ReferenceMatch::Missing => Err(format!(
2217            "plugin `{reference}` does not exist in the exact configured source"
2218        )),
2219        ReferenceMatch::Ambiguous => Err(format!(
2220            "plugin `{reference}` is ambiguous between a slot and stable ID"
2221        )),
2222    }
2223}
2224
2225/// Project existing component activation facts onto the canonical plugin graph.
2226/// This operation never grants approval or enables an instruction pack.
2227pub fn apply_component_resolution(
2228    plugins: &mut PluginResolution,
2229    skills: &Resolution,
2230    agents: &AgentResolution,
2231    active_instructions: &BTreeSet<String>,
2232) {
2233    for plugin in &mut plugins.plugins {
2234        let previous_member_states = plugin
2235            .members
2236            .iter()
2237            .map(|member| member.state)
2238            .collect::<Vec<_>>();
2239        let previous_state = plugin.state;
2240        plugin
2241            .blocking_reasons
2242            .retain(|reason| !reason.starts_with("required member `"));
2243        for member in &mut plugin.members {
2244            let Some(identity) = member.resolved_ref.as_deref() else {
2245                continue;
2246            };
2247            member.state = if member.reference.starts_with("skill:") {
2248                if skills
2249                    .active_skills
2250                    .iter()
2251                    .any(|skill| skill.source_ref == identity)
2252                {
2253                    PluginComponentState::Active
2254                } else if skills
2255                    .pending_approval_skills
2256                    .iter()
2257                    .any(|skill| skill.source_ref == identity)
2258                {
2259                    PluginComponentState::PendingApproval
2260                } else if skills
2261                    .blocked_skills
2262                    .iter()
2263                    .any(|skill| skill.skill.source_ref == identity)
2264                {
2265                    PluginComponentState::Blocked
2266                } else if skills
2267                    .unlinked_skills
2268                    .iter()
2269                    .any(|skill| skill.skill.source_ref == identity)
2270                {
2271                    PluginComponentState::Shadowed
2272                } else {
2273                    PluginComponentState::Available
2274                }
2275            } else if member.reference.starts_with("agent:") {
2276                if agents
2277                    .active_agents
2278                    .iter()
2279                    .any(|agent| agent.agent.source_ref == identity)
2280                {
2281                    PluginComponentState::Active
2282                } else if agents
2283                    .pending_approval_agents
2284                    .iter()
2285                    .any(|agent| agent.agent.source_ref == identity)
2286                {
2287                    PluginComponentState::PendingApproval
2288                } else if agents
2289                    .shadowed_agents
2290                    .iter()
2291                    .any(|agent| agent.agent.agent.source_ref == identity)
2292                {
2293                    PluginComponentState::Shadowed
2294                } else {
2295                    PluginComponentState::Available
2296                }
2297            } else if active_instructions.contains(identity) {
2298                PluginComponentState::Active
2299            } else {
2300                PluginComponentState::Inactive
2301            };
2302            if member.requirement == MemberRequirement::Required
2303                && member.state != PluginComponentState::Active
2304            {
2305                plugin.blocking_reasons.push(
2306                    format!("required member `{}` is {}", member.reference, member.state)
2307                        .to_lowercase(),
2308                );
2309            }
2310        }
2311        plugin.blocking_reasons.sort();
2312        plugin.blocking_reasons.dedup();
2313        if !matches!(plugin.state, PluginState::Shadowed | PluginState::Declined) {
2314            plugin.state = if plugin.blocking_reasons.is_empty() {
2315                PluginState::Selected
2316            } else {
2317                PluginState::Blocked
2318            };
2319        }
2320        let changed = previous_state != plugin.state
2321            || previous_member_states
2322                .iter()
2323                .zip(&plugin.members)
2324                .any(|(previous, member)| *previous != member.state);
2325        if !changed {
2326            continue;
2327        }
2328        let mut hash = Sha256::new();
2329        hash.update(b"dalo-plugin-activation-closure-v1\0");
2330        hash.update(&plugin.closure_hash);
2331        for member in &plugin.members {
2332            hash.update([0]);
2333            hash.update(&member.reference);
2334            hash.update(format!("{:?}{:?}", member.requirement, member.state));
2335            if let Some(identity) = &member.resolved_ref {
2336                hash.update(identity);
2337            }
2338        }
2339        plugin.closure_hash = hash
2340            .finalize()
2341            .iter()
2342            .map(|byte| format!("{byte:02x}"))
2343            .collect();
2344    }
2345}
2346
2347fn candidate_index<'a>(
2348    sources: &'a [SourceConfig],
2349    inventories: &'a [SourceInventory],
2350) -> CandidateIndex<'a> {
2351    let enabled = sources
2352        .iter()
2353        .filter(|source| source.enabled)
2354        .map(|source| (source.id.as_str(), source.priority))
2355        .collect::<BTreeMap<_, _>>();
2356    let mut by_source = BTreeMap::<&str, Vec<&PluginRecord>>::new();
2357    for inventory in inventories {
2358        if enabled.contains_key(inventory.source_id.as_str()) {
2359            by_source
2360                .entry(inventory.source_id.as_str())
2361                .or_default()
2362                .extend(&inventory.plugins);
2363        }
2364    }
2365    for plugins in by_source.values_mut() {
2366        plugins.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
2367    }
2368    CandidateIndex {
2369        by_source,
2370        source_priority: enabled,
2371    }
2372}
2373
2374enum ReferenceMatch<'a> {
2375    One(&'a PluginRecord),
2376    Missing,
2377    Ambiguous,
2378}
2379
2380fn resolve_qualified<'a>(reference: &str, index: &'a CandidateIndex<'a>) -> ReferenceMatch<'a> {
2381    let mut parts = reference.split(':');
2382    let (Some(source), Some(selector), None) = (parts.next(), parts.next(), parts.next()) else {
2383        return ReferenceMatch::Missing;
2384    };
2385    resolve_selector(source, selector, index)
2386}
2387
2388fn resolve_component_reference<'a>(
2389    reference: &ComponentReference,
2390    declaring_source: &str,
2391    index: &'a CandidateIndex<'a>,
2392) -> ReferenceMatch<'a> {
2393    let source = reference.source_id.as_deref().unwrap_or(declaring_source);
2394    resolve_selector(source, &reference.selector, index)
2395}
2396
2397fn resolve_selector<'a>(
2398    source: &str,
2399    selector: &str,
2400    index: &'a CandidateIndex<'a>,
2401) -> ReferenceMatch<'a> {
2402    let Some(candidates) = index.by_source.get(source) else {
2403        return ReferenceMatch::Missing;
2404    };
2405    let slot = candidates
2406        .iter()
2407        .copied()
2408        .find(|plugin| plugin.slot_name == selector);
2409    let stable = candidates
2410        .iter()
2411        .copied()
2412        .find(|plugin| plugin.id.as_deref() == Some(selector));
2413    match (slot, stable) {
2414        (Some(left), Some(right)) if left.source_ref != right.source_ref => {
2415            ReferenceMatch::Ambiguous
2416        }
2417        (Some(plugin), _) | (_, Some(plugin)) => ReferenceMatch::One(plugin),
2418        _ => ReferenceMatch::Missing,
2419    }
2420}
2421
2422fn add_root(
2423    reference: &str,
2424    origin: SelectionOrigin,
2425    index: &CandidateIndex<'_>,
2426    roots: &mut BTreeSet<String>,
2427    origins: &mut BTreeMap<String, BTreeSet<SelectionOrigin>>,
2428    diagnostics: &mut Vec<PluginDiagnostic>,
2429) {
2430    match resolve_qualified(reference, index) {
2431        ReferenceMatch::One(plugin) => {
2432            roots.insert(plugin.source_ref.clone());
2433            origins
2434                .entry(plugin.source_ref.clone())
2435                .or_default()
2436                .insert(origin);
2437        }
2438        ReferenceMatch::Missing => diagnostics.push(PluginDiagnostic {
2439            code: PluginDiagnosticCode::MissingPlugin,
2440            subject: reference.to_owned(),
2441            message: "selected plugin does not exist in the exact source".to_owned(),
2442        }),
2443        ReferenceMatch::Ambiguous => diagnostics.push(PluginDiagnostic {
2444            code: PluginDiagnosticCode::AmbiguousPluginReference,
2445            subject: reference.to_owned(),
2446            message: "selector matches different slot and stable-ID candidates".to_owned(),
2447        }),
2448    }
2449}
2450
2451fn plugin_by_identity<'a>(
2452    identity: &str,
2453    index: &'a CandidateIndex<'a>,
2454) -> Option<&'a PluginRecord> {
2455    index
2456        .by_source
2457        .values()
2458        .flatten()
2459        .copied()
2460        .find(|plugin| plugin.source_ref == identity)
2461}
2462
2463fn winner_map(
2464    reachable: &BTreeSet<String>,
2465    index: &CandidateIndex<'_>,
2466) -> BTreeMap<String, String> {
2467    let mut groups = BTreeMap::<String, Vec<&PluginRecord>>::new();
2468    for identity in reachable {
2469        if let Some(plugin) = plugin_by_identity(identity, index) {
2470            groups
2471                .entry(plugin.slot_name.clone())
2472                .or_default()
2473                .push(plugin);
2474        }
2475    }
2476    groups
2477        .into_iter()
2478        .map(|(slot, mut plugins)| {
2479            plugins.sort_by(|left, right| {
2480                index
2481                    .source_priority
2482                    .get(left.source_id.as_str())
2483                    .unwrap_or(&i32::MAX)
2484                    .cmp(
2485                        index
2486                            .source_priority
2487                            .get(right.source_id.as_str())
2488                            .unwrap_or(&i32::MAX),
2489                    )
2490                    .then_with(|| left.source_id.cmp(&right.source_id))
2491            });
2492            (slot, plugins[0].source_ref.clone())
2493        })
2494        .collect()
2495}
2496
2497fn required_cycle_nodes(
2498    winners: &BTreeMap<String, String>,
2499    index: &CandidateIndex<'_>,
2500) -> Vec<Vec<String>> {
2501    let winner_ids = winners.values().cloned().collect::<BTreeSet<_>>();
2502    let mut graph = BTreeMap::<String, Vec<String>>::new();
2503    for identity in &winner_ids {
2504        let Some(plugin) = plugin_by_identity(identity, index) else {
2505            continue;
2506        };
2507        let mut edges = Vec::new();
2508        for dependency in plugin
2509            .requires
2510            .iter()
2511            .filter(|dependency| dependency.requirement == DependencyRequirement::Required)
2512        {
2513            if let ReferenceMatch::One(target) =
2514                resolve_component_reference(&dependency.reference, &plugin.source_id, index)
2515                && winner_ids.contains(&target.source_ref)
2516            {
2517                edges.push(target.source_ref.clone());
2518            }
2519        }
2520        edges.sort();
2521        graph.insert(identity.clone(), edges);
2522    }
2523    let mut cycles = BTreeSet::<Vec<String>>::new();
2524    for start in graph.keys() {
2525        find_cycles(
2526            start,
2527            start,
2528            &graph,
2529            &mut Vec::new(),
2530            &mut BTreeSet::new(),
2531            &mut cycles,
2532        );
2533    }
2534    cycles.into_iter().collect()
2535}
2536
2537fn find_cycles(
2538    start: &str,
2539    current: &str,
2540    graph: &BTreeMap<String, Vec<String>>,
2541    path: &mut Vec<String>,
2542    visiting: &mut BTreeSet<String>,
2543    cycles: &mut BTreeSet<Vec<String>>,
2544) {
2545    if !visiting.insert(current.to_owned()) {
2546        return;
2547    }
2548    path.push(current.to_owned());
2549    for next in graph.get(current).into_iter().flatten() {
2550        if next == start {
2551            let mut cycle = path.clone();
2552            cycle.sort();
2553            cycle.dedup();
2554            cycles.insert(cycle);
2555        } else {
2556            find_cycles(start, next, graph, path, visiting, cycles);
2557        }
2558    }
2559    path.pop();
2560    visiting.remove(current);
2561}
2562
2563fn applied_policies(
2564    config: &UserConfig,
2565    index: &CandidateIndex<'_>,
2566    diagnostics: &mut Vec<PluginDiagnostic>,
2567) -> BTreeMap<String, Vec<AppliedPluginPolicy>> {
2568    let mut applied = BTreeMap::<String, Vec<AppliedPluginPolicy>>::new();
2569    for policy in &config.plugin_policy {
2570        if policy.decision == PluginPolicyDecision::Decline
2571            && let ReferenceMatch::One(plugin) = resolve_qualified(&policy.plugin, index)
2572        {
2573            applied
2574                .entry(plugin.source_ref.clone())
2575                .or_default()
2576                .push(AppliedPluginPolicy {
2577                    layer: policy.layer,
2578                    rule_id: policy.rule_id.clone(),
2579                    decision: policy.decision,
2580                    reason: policy.reason.clone(),
2581                });
2582            diagnostics.push(PluginDiagnostic {
2583                code: PluginDiagnosticCode::DeclinedPlugin,
2584                subject: plugin.source_ref.clone(),
2585                message: policy.reason.clone(),
2586            });
2587        }
2588    }
2589    for policies in applied.values_mut() {
2590        policies.sort_by(|left, right| left.rule_id.cmp(&right.rule_id));
2591    }
2592    applied
2593}
2594
2595fn evaluate_members(
2596    plugin: &PluginRecord,
2597    sources: &[SourceConfig],
2598    inventories: &[SourceInventory],
2599    blocking: &mut Vec<String>,
2600) -> Vec<ResolvedPluginMember> {
2601    plugin
2602        .members
2603        .iter()
2604        .map(|member| {
2605            let source = member
2606                .reference
2607                .source_id
2608                .as_deref()
2609                .unwrap_or(&plugin.source_id);
2610            let (state, resolved_ref) = match member.reference.kind {
2611                ComponentKind::Skill => resolve_asset(
2612                    source,
2613                    &member.reference.selector,
2614                    inventories,
2615                    |inventory| {
2616                        inventory
2617                            .skills
2618                            .iter()
2619                            .map(|skill| {
2620                                (
2621                                    &skill.slot_name,
2622                                    skill.id.as_ref(),
2623                                    skill.source_ref.as_str(),
2624                                )
2625                            })
2626                            .collect()
2627                    },
2628                ),
2629                ComponentKind::Agent => resolve_asset(
2630                    source,
2631                    &member.reference.selector,
2632                    inventories,
2633                    |inventory| {
2634                        inventory
2635                            .agents
2636                            .iter()
2637                            .map(|agent| {
2638                                (
2639                                    &agent.slot_name,
2640                                    agent.id.as_ref(),
2641                                    agent.source_ref.as_str(),
2642                                )
2643                            })
2644                            .collect()
2645                    },
2646                ),
2647                ComponentKind::Instruction => {
2648                    let available = sources
2649                        .iter()
2650                        .find(|candidate| candidate.enabled && candidate.id == source)
2651                        .map(|candidate| {
2652                            candidate
2653                                .path
2654                                .join("instructions")
2655                                .join(format!("{}.md", member.reference.selector))
2656                                .is_file()
2657                        })
2658                        .unwrap_or(false);
2659                    if available {
2660                        (
2661                            PluginComponentState::Inactive,
2662                            Some(format!("{source}:{}", member.reference.selector)),
2663                        )
2664                    } else {
2665                        (PluginComponentState::Missing, None)
2666                    }
2667                }
2668                ComponentKind::Plugin => (PluginComponentState::Missing, None),
2669            };
2670            if member.requirement == MemberRequirement::Required
2671                && matches!(
2672                    state,
2673                    PluginComponentState::Missing
2674                        | PluginComponentState::Ambiguous
2675                        | PluginComponentState::Inactive
2676                )
2677            {
2678                blocking.push(
2679                    format!(
2680                        "required member `{}` is {}",
2681                        member.reference.as_string(),
2682                        state
2683                    )
2684                    .to_lowercase(),
2685                );
2686            }
2687            ResolvedPluginMember {
2688                reference: member.reference.as_string(),
2689                requirement: member.requirement,
2690                state,
2691                resolved_ref,
2692                fallback: member
2693                    .fallback
2694                    .as_ref()
2695                    .map(|fallback| fallback.skill.as_string()),
2696            }
2697        })
2698        .collect()
2699}
2700
2701fn resolve_asset<'a, F>(
2702    source: &str,
2703    selector: &str,
2704    inventories: &'a [SourceInventory],
2705    collect: F,
2706) -> (PluginComponentState, Option<String>)
2707where
2708    F: Fn(&'a SourceInventory) -> Vec<(&'a String, Option<&'a String>, &'a str)>,
2709{
2710    let Some(inventory) = inventories
2711        .iter()
2712        .find(|inventory| inventory.source_id == source)
2713    else {
2714        return (PluginComponentState::Missing, None);
2715    };
2716    let candidates = collect(inventory);
2717    let slot = candidates
2718        .iter()
2719        .find(|(name, _, _)| name.as_str() == selector)
2720        .map(|(_, _, identity)| *identity);
2721    let stable = candidates
2722        .iter()
2723        .find(|(_, id, _)| id.is_some_and(|id| id == selector))
2724        .map(|(_, _, identity)| *identity);
2725    match (slot, stable) {
2726        (Some(left), Some(right)) if left != right => (PluginComponentState::Ambiguous, None),
2727        (Some(identity), _) | (_, Some(identity)) => {
2728            (PluginComponentState::Available, Some(identity.to_owned()))
2729        }
2730        _ => (PluginComponentState::Missing, None),
2731    }
2732}
2733
2734fn closure_hash(
2735    plugin: &PluginRecord,
2736    members: &[ResolvedPluginMember],
2737    dependencies: &[ResolvedPluginDependency],
2738    blocking: &[String],
2739    state: PluginState,
2740    winners: &BTreeMap<String, String>,
2741    index: &CandidateIndex<'_>,
2742) -> String {
2743    let mut hash = Sha256::new();
2744    hash.update(b"dalo-plugin-closure-v1\0");
2745    hash.update(&plugin.source_ref);
2746    hash.update([0]);
2747    hash.update(&plugin.package_hash);
2748    for dependency in &plugin.requires {
2749        hash.update([0]);
2750        hash.update(dependency.reference.as_string());
2751        hash.update(format!("{:?}", dependency.requirement));
2752        if let ReferenceMatch::One(target) =
2753            resolve_component_reference(&dependency.reference, &plugin.source_id, index)
2754        {
2755            hash.update(&target.source_ref);
2756            if winners.get(&target.slot_name) == Some(&target.source_ref) {
2757                hash.update(b"winner");
2758            }
2759        }
2760    }
2761    for member in members {
2762        hash.update([0]);
2763        hash.update(&member.reference);
2764        hash.update(format!("{:?}{:?}", member.requirement, member.state));
2765        if let Some(identity) = &member.resolved_ref {
2766            hash.update(identity);
2767        }
2768    }
2769    for dependency in dependencies {
2770        hash.update([0]);
2771        hash.update(&dependency.reference);
2772        hash.update(format!(
2773            "{:?}{:?}",
2774            dependency.requirement, dependency.state
2775        ));
2776        if let Some(identity) = &dependency.resolved_ref {
2777            hash.update(identity);
2778        }
2779    }
2780    for reason in blocking {
2781        hash.update([0]);
2782        hash.update(reason);
2783    }
2784    hash.update(format!("{:?}", state));
2785    hash.finalize()
2786        .iter()
2787        .map(|byte| format!("{byte:02x}"))
2788        .collect()
2789}
2790
2791#[cfg(test)]
2792mod tests {
2793    use super::*;
2794    use crate::config::{PluginConfig, Settings};
2795    use crate::inventory;
2796    use crate::source::{SourceConfig, SourceKind};
2797    use tempfile::TempDir;
2798
2799    fn write_plugin(root: &Path, name: &str, manifest: &str) -> PathBuf {
2800        let package = root.join("plugins").join(name);
2801        fs::create_dir_all(&package).unwrap();
2802        fs::write(package.join(PLUGIN_FILE), manifest).unwrap();
2803        package
2804    }
2805
2806    fn valid_manifest(name: &str) -> String {
2807        format!(
2808            r#"schema_version = 1
2809[plugin]
2810name = "{name}"
2811id = "dev.example.{name}"
2812description = "Example"
2813
2814[[plugin.members]]
2815ref = "skill:core"
2816requirement = "required"
2817
2818[[plugin.members]]
2819ref = "agent:reviewer"
2820requirement = "optional"
2821[plugin.members.fallback]
2822kind = "inline"
2823skill = "skill:core"
2824
2825[[plugin.requires]]
2826ref = "plugin:base"
2827requirement = "optional"
2828"#
2829        )
2830    }
2831
2832    fn source(id: &str, path: &Path, priority: i32) -> SourceConfig {
2833        SourceConfig {
2834            id: id.to_owned(),
2835            kind: SourceKind::Team,
2836            path: path.to_path_buf(),
2837            subpath: None,
2838            priority,
2839            namespace: None,
2840            enabled: true,
2841            trusted: false,
2842            url: None,
2843            branch: None,
2844            update_policy: None,
2845            selection: Vec::new(),
2846            declared_by: None,
2847            declared_ref: None,
2848        }
2849    }
2850
2851    fn config(sources: Vec<SourceConfig>, direct: &[&str]) -> UserConfig {
2852        UserConfig {
2853            version: crate::config::CONFIG_VERSION,
2854            settings: Settings {
2855                autosync: false,
2856                sync_interval: None,
2857            },
2858            sources,
2859            plugins: PluginConfig {
2860                direct: direct.iter().map(|value| (*value).to_owned()).collect(),
2861            },
2862            plugin_policy: Vec::new(),
2863            project_selections: None,
2864        }
2865    }
2866
2867    #[test]
2868    fn discovers_exact_valid_packages_and_hashes_support_files() {
2869        let temp = TempDir::new().unwrap();
2870        let package = write_plugin(temp.path(), "example", &valid_manifest("example"));
2871        fs::write(package.join("README.md"), "one").unwrap();
2872        write_plugin(
2873            &temp.path().join("nested"),
2874            "ignored",
2875            &valid_manifest("ignored"),
2876        );
2877        let first = scan_source_plugins("team", temp.path());
2878        assert_eq!(first.plugins.len(), 1);
2879        assert!(first.warnings.is_empty());
2880        fs::write(package.join("README.md"), "two").unwrap();
2881        let second = scan_source_plugins("team", temp.path());
2882        assert_ne!(
2883            first.plugins[0].package_hash,
2884            second.plugins[0].package_hash
2885        );
2886    }
2887
2888    #[test]
2889    fn plugin_support_files_are_not_discovered_as_standalone_skills() {
2890        let temp = TempDir::new().unwrap();
2891        let package = write_plugin(temp.path(), "example", &valid_manifest("example"));
2892        let embedded = package.join("embedded");
2893        fs::create_dir_all(&embedded).unwrap();
2894        fs::write(embedded.join("SKILL.md"), "# Inert support file\n").unwrap();
2895
2896        let inventory = inventory::scan_source("team", temp.path()).unwrap();
2897
2898        assert!(inventory.skills.is_empty());
2899        assert_eq!(inventory.plugins.len(), 1);
2900    }
2901
2902    #[test]
2903    fn invalid_sibling_does_not_hide_valid_package() {
2904        let temp = TempDir::new().unwrap();
2905        write_plugin(temp.path(), "valid", &valid_manifest("valid"));
2906        write_plugin(temp.path(), "broken", "schema_version = 99\n");
2907        let inventory = scan_source_plugins("team", temp.path());
2908        assert_eq!(inventory.plugins.len(), 1);
2909        assert_eq!(inventory.warnings.len(), 1);
2910        assert_eq!(
2911            inventory.warnings[0].code,
2912            PluginInventoryWarningCode::InvalidPackage
2913        );
2914    }
2915
2916    #[test]
2917    fn unsupported_hook_descriptor_versions_block_package() {
2918        let temp = TempDir::new().unwrap();
2919        let manifest = format!(
2920            "{}\n[[hook]]\nschema_version = 99\nid = \"future\"\ntool = \"detector\"\nsubject = \"tool_call\"\nphase = \"before\"\neffect = \"allow_deny\"\nrequirement = \"required\"\ntimeout_ms = 2000\nfailure_policy = \"fail_closed\"\nretry = \"never\"\nerror_visibility = \"model_and_user\"\nblocking_scope = \"matched_event\"\n",
2921            valid_manifest("example")
2922        );
2923        write_plugin(temp.path(), "example", &manifest);
2924        let inventory = scan_source_plugins("team", temp.path());
2925        assert!(inventory.plugins.is_empty());
2926        assert_eq!(
2927            inventory.warnings[0].code,
2928            PluginInventoryWarningCode::UnsupportedActiveComponentSchema
2929        );
2930    }
2931
2932    #[test]
2933    fn hook_descriptor_binds_an_exact_same_plugin_tool_contract() {
2934        let temp = TempDir::new().unwrap();
2935        let manifest = format!(
2936            r#"{}
2937
2938[[hook]]
2939schema_version = 1
2940id = "protect-bash"
2941tool = "detector"
2942subject = "tool_call"
2943phase = "before"
2944effect = "allow_deny"
2945requirement = "required"
2946timeout_ms = 2000
2947failure_policy = "fail_closed"
2948retry = "never"
2949error_visibility = "model_and_user"
2950blocking_scope = "matched_event"
2951bindings = [{{ input = "path", field = "session.cwd" }}]
2952matcher = {{ tool_names = ["Bash"] }}
2953"#,
2954            tool_manifest("example", "\"${input.path}\"")
2955        );
2956        let package = write_plugin(temp.path(), "example", &manifest);
2957        write_tool_files(&package);
2958
2959        let inventory = scan_source_plugins("team", temp.path());
2960        assert!(inventory.warnings.is_empty(), "{:?}", inventory.warnings);
2961        let hook = &inventory.plugins[0].hooks[0];
2962        assert_eq!(hook.source_ref, "team:example#hook:protect-bash");
2963        assert_eq!(hook.tool_source_ref, "team:example#tool:detector");
2964        assert_eq!(hook.contract_hash.len(), 64);
2965    }
2966
2967    fn tool_manifest(name: &str, argv: &str) -> String {
2968        format!(
2969            r#"{}
2970[[tool]]
2971schema_version = 1
2972id = "detector"
2973entry = "bin/detect.py"
2974runtime = "python"
2975runtime_version = ">=3.11"
2976platforms = ["macos", "linux"]
2977argv = ["--path", {argv}]
2978files = ["lib/rules.txt"]
2979cwd = "tool_root"
2980env = ["DALO_LOG"]
2981capabilities = ["filesystem_read"]
2982availability = "required"
2983
2984[[tool.inputs]]
2985name = "path"
2986type = "path"
2987required = true
2988"#,
2989            valid_manifest(name)
2990        )
2991    }
2992
2993    fn write_tool_files(package: &Path) {
2994        fs::create_dir_all(package.join("bin")).unwrap();
2995        fs::create_dir_all(package.join("lib")).unwrap();
2996        fs::write(package.join("bin/detect.py"), b"print('ok')\n").unwrap();
2997        fs::write(package.join("lib/rules.txt"), b"rules\n").unwrap();
2998    }
2999
3000    #[test]
3001    fn discovers_tool_and_hashes_only_security_relevant_closure() {
3002        let temp = TempDir::new().unwrap();
3003        let package = write_plugin(
3004            temp.path(),
3005            "example",
3006            &tool_manifest("example", r#""${input.path}""#),
3007        );
3008        write_tool_files(&package);
3009        fs::write(package.join("README.md"), "one").unwrap();
3010        let first = scan_source_plugins("team", temp.path());
3011        assert!(first.warnings.is_empty(), "{:?}", first.warnings);
3012        assert_eq!(first.plugins[0].tools.len(), 1);
3013        let contract = first.plugins[0].tools[0].contract_hash.clone();
3014        let package_hash = first.plugins[0].package_hash.clone();
3015
3016        fs::write(package.join("README.md"), "two").unwrap();
3017        let second = scan_source_plugins("team", temp.path());
3018        assert_eq!(second.plugins[0].tools[0].contract_hash, contract);
3019        assert_ne!(second.plugins[0].package_hash, package_hash);
3020
3021        fs::write(package.join("lib/rules.txt"), "changed").unwrap();
3022        let third = scan_source_plugins("team", temp.path());
3023        assert_ne!(third.plugins[0].tools[0].contract_hash, contract);
3024    }
3025
3026    #[test]
3027    fn rejects_path_escape_and_partial_or_unknown_placeholders() {
3028        let temp = TempDir::new().unwrap();
3029        let package = write_plugin(
3030            temp.path(),
3031            "escape",
3032            &tool_manifest("escape", r#""prefix-${input.path}""#),
3033        );
3034        write_tool_files(&package);
3035        let placeholder = scan_source_plugins("team", temp.path());
3036        assert!(placeholder.plugins.is_empty());
3037        assert!(
3038            placeholder.warnings[0]
3039                .message
3040                .contains("unsafe placeholder")
3041        );
3042
3043        let package = write_plugin(
3044            temp.path(),
3045            "outside",
3046            &tool_manifest("outside", r#""${input.path}""#)
3047                .replace("bin/detect.py", "../detect.py"),
3048        );
3049        write_tool_files(&package);
3050        let escaped = scan_source_plugins("team", temp.path());
3051        assert!(
3052            escaped
3053                .warnings
3054                .iter()
3055                .any(|warning| warning.path.ends_with("outside")
3056                    && warning.message.contains("inside"))
3057        );
3058    }
3059
3060    #[test]
3061    fn descriptor_input_or_argv_drift_invalidates_contract() {
3062        let temp = TempDir::new().unwrap();
3063        let package = write_plugin(
3064            temp.path(),
3065            "example",
3066            &tool_manifest("example", r#""${input.path}""#),
3067        );
3068        write_tool_files(&package);
3069        let first = scan_source_plugins("team", temp.path());
3070        let contract = first.plugins[0].tools[0].contract_hash.clone();
3071        fs::write(
3072            package.join(PLUGIN_FILE),
3073            tool_manifest("example", r#""${input.path}", "--strict""#),
3074        )
3075        .unwrap();
3076        let second = scan_source_plugins("team", temp.path());
3077        assert_ne!(second.plugins[0].tools[0].contract_hash, contract);
3078    }
3079
3080    #[test]
3081    fn fallback_must_name_required_skill_member() {
3082        let temp = TempDir::new().unwrap();
3083        let manifest = valid_manifest("example")
3084            .replace("requirement = \"required\"", "requirement = \"optional\"");
3085        write_plugin(temp.path(), "example", &manifest);
3086        let inventory = scan_source_plugins("team", temp.path());
3087        assert!(inventory.plugins.is_empty());
3088        assert!(
3089            inventory.warnings[0]
3090                .message
3091                .contains("required skill member")
3092        );
3093    }
3094
3095    #[test]
3096    fn duplicate_stable_ids_invalidate_both_packages() {
3097        let temp = TempDir::new().unwrap();
3098        let first = valid_manifest("first").replace("dev.example.first", "dev.example.shared");
3099        let second = valid_manifest("second").replace("dev.example.second", "dev.example.shared");
3100        write_plugin(temp.path(), "first", &first);
3101        write_plugin(temp.path(), "second", &second);
3102        let inventory = scan_source_plugins("team", temp.path());
3103        assert!(inventory.plugins.is_empty());
3104        assert_eq!(inventory.warnings.len(), 2);
3105        assert!(
3106            inventory
3107                .warnings
3108                .iter()
3109                .all(|warning| warning.code == PluginInventoryWarningCode::DuplicateStableId)
3110        );
3111    }
3112
3113    #[cfg(unix)]
3114    #[test]
3115    fn symlink_in_package_is_blocking() {
3116        use std::os::unix::fs::symlink;
3117        let temp = TempDir::new().unwrap();
3118        let package = write_plugin(temp.path(), "example", &valid_manifest("example"));
3119        symlink(temp.path(), package.join("escape")).unwrap();
3120        let inventory = scan_source_plugins("team", temp.path());
3121        assert!(inventory.plugins.is_empty());
3122        assert_eq!(
3123            inventory.warnings[0].code,
3124            PluginInventoryWarningCode::UnsafePackageEntry
3125        );
3126    }
3127
3128    #[test]
3129    fn resolves_exact_cross_source_dependency_and_deterministic_winner() {
3130        let temp = TempDir::new().unwrap();
3131        let one = temp.path().join("one");
3132        let two = temp.path().join("two");
3133        let root_manifest = valid_manifest("shared")
3134            .replace("plugin:base", "plugin:two:base")
3135            .replace("requirement = \"optional\"", "requirement = \"required\"");
3136        write_plugin(&one, "shared", &root_manifest);
3137        write_plugin(&two, "base", &valid_manifest("base"));
3138        write_plugin(&two, "shared", &valid_manifest("shared"));
3139        let sources = vec![source("one", &one, 20), source("two", &two, 10)];
3140        let inventories = sources
3141            .iter()
3142            .map(|source| inventory::scan_source(&source.id, &source.path).unwrap())
3143            .collect::<Vec<_>>();
3144        let config = config(sources, &["one:shared", "two:shared"]);
3145
3146        let resolution = resolve_plugins(&config, &inventories);
3147
3148        assert_eq!(resolution.plugins.len(), 3);
3149        let one_shared = resolution
3150            .plugins
3151            .iter()
3152            .find(|plugin| plugin.source_ref == "one:shared")
3153            .unwrap();
3154        assert_eq!(one_shared.state, PluginState::Shadowed);
3155        assert_eq!(one_shared.shadowed_by.as_deref(), Some("two:shared"));
3156        assert!(
3157            resolution
3158                .plugins
3159                .iter()
3160                .any(|plugin| plugin.source_ref == "two:base")
3161        );
3162        assert_eq!(
3163            serde_json::to_string(&resolution).unwrap(),
3164            serde_json::to_string(&resolve_plugins(&config, &inventories)).unwrap()
3165        );
3166    }
3167
3168    #[test]
3169    fn required_dependency_cycle_blocks_every_cycle_member() {
3170        let temp = TempDir::new().unwrap();
3171        let root = temp.path().join("team");
3172        let alpha = valid_manifest("alpha")
3173            .replace("plugin:base", "plugin:beta")
3174            .replace("requirement = \"optional\"", "requirement = \"required\"");
3175        let beta = valid_manifest("beta")
3176            .replace("plugin:base", "plugin:alpha")
3177            .replace("requirement = \"optional\"", "requirement = \"required\"");
3178        write_plugin(&root, "alpha", &alpha);
3179        write_plugin(&root, "beta", &beta);
3180        let sources = vec![source("team", &root, 10)];
3181        let inventories = vec![inventory::scan_source("team", &root).unwrap()];
3182
3183        let resolution = resolve_plugins(&config(sources, &["team:alpha"]), &inventories);
3184
3185        assert!(
3186            resolution
3187                .plugins
3188                .iter()
3189                .all(|plugin| plugin.state == PluginState::Blocked)
3190        );
3191        assert_eq!(
3192            resolution
3193                .diagnostics
3194                .iter()
3195                .filter(
3196                    |diagnostic| diagnostic.code == PluginDiagnosticCode::RequiredDependencyCycle
3197                )
3198                .count(),
3199            1
3200        );
3201    }
3202
3203    #[test]
3204    fn slot_stable_id_confusion_is_blocking() {
3205        let temp = TempDir::new().unwrap();
3206        let root = temp.path().join("team");
3207        let slot = valid_manifest("foo").replace("dev.example.foo", "dev.example.slot");
3208        let stable = valid_manifest("other").replace("dev.example.other", "foo");
3209        write_plugin(&root, "foo", &slot);
3210        write_plugin(&root, "other", &stable);
3211        let sources = vec![source("team", &root, 10)];
3212        let inventories = vec![inventory::scan_source("team", &root).unwrap()];
3213
3214        let resolution = resolve_plugins(&config(sources, &["team:foo"]), &inventories);
3215
3216        assert!(resolution.plugins.is_empty());
3217        assert_eq!(
3218            resolution.diagnostics[0].code,
3219            PluginDiagnosticCode::AmbiguousPluginReference
3220        );
3221    }
3222}