diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 5b48a1db..f7df1e3b 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -596,8 +596,9 @@ or removing a command fails until the table changes in the same commit. | `project.checkName` | Check that a name can be a new project's directory name | | `project.extractArchive` | Extract a downloaded project archive into the staging directory, refusing unsafe entries | | `plugins.marketplace.validateIndex` | Validate a marketplace index and report each plugin's availability for one platform | -| `plugins.marketplace.resolveSource` | Resolve a user-entered marketplace source to the index URL to fetch | +| `plugins.marketplace.resolveSource` | Resolve a user-entered marketplace source to the index and companion recommendations URLs to fetch | | `plugins.marketplace.installReview` | List a package's permissions and programs, and those not yet approved | +| `plugins.marketplace.recommendForWorkspace` | Match sampled workspace files against marketplace recommendation catalogs and indexes | | `workspace.snapshot` | Enumerate visible workspace nodes and relative file paths; `nestedWorktrees` lists linked worktrees checked out inside their own repository, which are left out of the tree, files, and search index; hidden folders, Core's own and the ones enabled plugins declare through `workspace.configureVisibility`, are skipped without being read; `includeTree: false` returns only `files` and a childless `root`; `files` (and the tree, when included) keep the lowercase traversal order that bounded consumers such as Windows Quick Open rely on, not the natural display order of `workspace.listDirectories` | | `workspace.releaseIndexing` | Retire a policy and clear index/cache data at project close; accepts `root`, optional `ownerId`, and that owner's last observed `revision`, returns `released`; an old close must not retire a new generation | | `workspace.configureIndexing` | Install a process-local, canonical-root indexing policy before workspace consumers run; returns a monotonic revision, effective directory reasons and Git failure state; see `rust/fixtures/workspace/indexing-policy-v1.json` | @@ -5332,10 +5333,15 @@ archives and pass the parsed JSON. `validateIndex` accepts and returns `{ status: "ok", index: { plugins, rejected } }` with per-entry `availability`; a listed version is available only when its `pluginAPIVersion` is one Core supports and every capability it requires is in `hostCapabilities`; `resolveSource` accepts `{ url }` and returns -`{ status: "ok", source: { indexURL, repository, displayName } }`; +`{ status: "ok", source: { indexURL, recommendationsURL, repository, displayName } }`; `installReview` accepts `{ manifest, expectedID?, expectedVersion?, approvedPrograms?, hostCapabilities? }` and returns `{ status: "ok", review: { id, version, -permissions, programs, newPrograms } }`. Content problems use the same +permissions, programs, newPrograms } }`; +`recommendForWorkspace` accepts `{ platform, workspaceFiles, catalogs: [{ index, sourceKind, indexURL?, recommendations }], hostCapabilities?, installedPluginIDs?, dismissedPluginIDs? }` +and returns `{ status: "ok", recommendation: { plugins: [{ plugin, matchedMarkers, matchedExtensions, marketplaceIndexURL? }], rejected } }` +after validating each catalog, filtering to available/uninstalled/undismissed +matches, excluding `coveredBy` alternatives, deduplicating across catalogs, and +sorting marker matches ahead of extension-only matches. Content problems use the same `rejected` shape; see the Marketplace section of [`plugins/v1`](../../shared/plugins/contract/v1/README.md) and `fixtures/marketplace/`. diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 29646957..4317793f 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -297,6 +297,8 @@ pub enum PluginsCommand { MarketplaceResolveSource, /// Lists a package's permissions and programs before installation (`plugins.marketplace.installReview`). MarketplaceInstallReview, + /// Matches workspace file signals against marketplace recommendation catalogs (`plugins.marketplace.recommendForWorkspace`). + MarketplaceRecommendForWorkspace, } #[derive(Debug, Clone)] @@ -1260,6 +1262,9 @@ impl CoreCommand { "plugins.marketplace.installReview" => { Some(Self::Plugins(PluginsCommand::MarketplaceInstallReview)) } + "plugins.marketplace.recommendForWorkspace" => Some(Self::Plugins( + PluginsCommand::MarketplaceRecommendForWorkspace, + )), "workspace.snapshot" => Some(Self::Workspace(WorkspaceCommand::Snapshot)), "workspace.releaseIndexing" => Some(Self::Workspace(WorkspaceCommand::ReleaseIndexing)), "workspace.configureIndexing" => { diff --git a/rust/crates/core/src/runtime/dispatcher/plugins.rs b/rust/crates/core/src/runtime/dispatcher/plugins.rs index e4b23ecb..3f262182 100644 --- a/rust/crates/core/src/runtime/dispatcher/plugins.rs +++ b/rust/crates/core/src/runtime/dispatcher/plugins.rs @@ -176,5 +176,10 @@ pub(super) fn dispatch( payload, lithe_plugin_marketplace::install_review_command, ), + PluginsCommand::MarketplaceRecommendForWorkspace => plugin_response( + id, + payload, + lithe_plugin_marketplace::recommend_for_workspace_command, + ), } } diff --git a/rust/crates/core/src/tests/marketplace_plugins.rs b/rust/crates/core/src/tests/marketplace_plugins.rs index b2dc50a8..affb21e6 100644 --- a/rust/crates/core/src/tests/marketplace_plugins.rs +++ b/rust/crates/core/src/tests/marketplace_plugins.rs @@ -1,5 +1,6 @@ use lithe_plugin_marketplace::{ - install_review_command, resolve_source_command, validate_index_command, + install_review_command, recommend_for_workspace_command, resolve_source_command, + validate_index_command, }; use serde_json::{json, Value}; @@ -17,6 +18,9 @@ const INDEX: &str = contract_file!("fixtures/marketplace/index.json"); const INDEX_CASES: &str = contract_file!("fixtures/marketplace/index-cases.json"); const INVALID_ENTRIES: &str = contract_file!("fixtures/marketplace/invalid-index-entries.json"); const SOURCE_URLS: &str = contract_file!("fixtures/marketplace/source-urls.json"); +const RECOMMENDATIONS: &str = contract_file!("fixtures/marketplace/recommendations.json"); +const RECOMMENDATION_CASES: &str = + contract_file!("fixtures/marketplace/recommendations-cases.json"); const INSTALL_REVIEWS: &str = contract_file!("fixtures/marketplace/install-reviews.json"); const PHP_FIXTURE: &str = contract_file!("fixtures/languages/language-packaged-server.plugin.json"); const GO_FIXTURE: &str = contract_file!("fixtures/languages/language-system-command.plugin.json"); @@ -374,3 +378,149 @@ fn publisher_bundled_versions_require_host_trust_support_before_download() { assert_eq!(plugin["availability"]["status"], expected, "{outcome}"); } } + +#[test] +fn recommendation_fixtures_match_expected_plugins() { + let cases = json_file(RECOMMENDATION_CASES); + for case in cases["cases"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let outcome = recommend_for_workspace_command(json!({ + "platform": case["platform"], + "workspaceFiles": case["workspaceFiles"], + "catalogs": [{ + "index": json_file(INDEX), + "sourceKind": case["sourceKind"], + "indexURL": "https://example.com/lithe-plugin-index.json", + "recommendations": json_file(RECOMMENDATIONS), + }], + "hostCapabilities": case["hostCapabilities"], + "installedPluginIDs": case["installedPluginIDs"], + "dismissedPluginIDs": case["dismissedPluginIDs"], + })) + .expect("recommendation payload is well formed"); + assert_eq!(outcome["status"], "ok", "{name}: {outcome}"); + let plugins = outcome["recommendation"]["plugins"].as_array().unwrap(); + let expected = case["expectedPlugins"].as_array().unwrap(); + assert_eq!(plugins.len(), expected.len(), "{name}: {outcome}"); + for (actual, want) in plugins.iter().zip(expected) { + assert_eq!(actual["plugin"]["id"], want["id"], "{name}"); + assert_eq!(actual["matchedMarkers"], want["matchedMarkers"], "{name}"); + assert_eq!( + actual["matchedExtensions"], want["matchedExtensions"], + "{name}" + ); + assert_eq!( + actual["marketplaceIndexURL"], "https://example.com/lithe-plugin-index.json", + "{name}" + ); + } + } +} + +#[test] +fn recommendations_deduplicate_across_catalogs_and_reject_invalid_entries() { + let outcome = recommend_for_workspace_command(json!({ + "platform": "darwin-arm64", + "workspaceFiles": ["build.zig", "lib/app.ex"], + "catalogs": [ + { + "index": json_file(INDEX), + "sourceKind": "thirdParty", + "indexURL": "https://first.example.com/lithe-plugin-index.json", + "recommendations": { + "schemaVersion": 0, + "recommendations": [ + { "pluginID": "io.example.zig-support", "markers": ["build.zig"] }, + { "pluginID": "io.example.zig-support", "extensions": ["zig"] }, + { "pluginID": "io.example.bad", "markers": ["../bad"] }, + { "pluginID": "io.example.empty" }, + { "pluginID": "io.example.bad-ext", "extensions": [".zig"] }, + { "pluginID": "io.example.self-cover", "markers": ["m"], "coveredBy": ["io.example.self-cover"] } + ] + } + }, + { + "index": json_file(INDEX), + "sourceKind": "thirdParty", + "indexURL": "https://second.example.com/lithe-plugin-index.json", + "recommendations": { + "schemaVersion": 0, + "recommendations": [ + { "pluginID": "io.example.zig-support", "markers": ["build.zig"] }, + { "pluginID": "io.example.elixir-tools", "extensions": ["ex"] } + ] + } + }, + { + "index": json_file(INDEX), + "sourceKind": "thirdParty", + "recommendations": { "schemaVersion": 99, "recommendations": [] } + } + ], + "hostCapabilities": { "languageServers": [0], "languages": [0] }, + "installedPluginIDs": [], + "dismissedPluginIDs": [] + })) + .expect("recommendation payload is well formed"); + + assert_eq!(outcome["status"], "ok", "{outcome}"); + let plugins = outcome["recommendation"]["plugins"].as_array().unwrap(); + assert_eq!(plugins.len(), 2, "{outcome}"); + assert_eq!(plugins[0]["plugin"]["id"], "io.example.zig-support"); + assert_eq!( + plugins[0]["marketplaceIndexURL"], + "https://first.example.com/lithe-plugin-index.json" + ); + assert_eq!(plugins[1]["plugin"]["id"], "io.example.elixir-tools"); + assert_eq!( + plugins[1]["marketplaceIndexURL"], + "https://second.example.com/lithe-plugin-index.json" + ); + + let rejected = outcome["recommendation"]["rejected"].as_array().unwrap(); + let codes: Vec<&str> = rejected + .iter() + .map(|entry| entry["error"]["code"].as_str().unwrap()) + .collect(); + assert_eq!( + codes, + vec![ + "plugin.recommendations.duplicate", + "plugin.recommendations.invalid", + "plugin.recommendations.invalid", + "plugin.recommendations.invalid", + "plugin.recommendations.invalid", + "plugin.recommendations.schemaUnsupported", + ] + ); +} + +#[test] +fn recommend_for_workspace_dispatches_through_core_command() { + use crate::execute_json; + let request = json!({ + "id": "marketplace-recommend-for-workspace", + "command": "plugins.marketplace.recommendForWorkspace", + "payload": { + "platform": "darwin-arm64", + "workspaceFiles": ["build.zig"], + "catalogs": [{ + "index": json_file(INDEX), + "sourceKind": "thirdParty", + "recommendations": json_file(RECOMMENDATIONS), + }], + "hostCapabilities": { "languageServers": [0], "languages": [0] }, + "installedPluginIDs": [], + "dismissedPluginIDs": [] + } + }) + .to_string(); + let reply = execute_json(&request); + let value: Value = serde_json::from_str(&reply).unwrap(); + assert_eq!(value["ok"], true, "{value}"); + assert_eq!(value["data"]["status"], "ok", "{value}"); + assert_eq!( + value["data"]["recommendation"]["plugins"][0]["plugin"]["id"], "io.example.zig-support", + "{value}" + ); +} diff --git a/rust/crates/plugin-marketplace/src/lib.rs b/rust/crates/plugin-marketplace/src/lib.rs index 5fb5b98b..11908277 100644 --- a/rust/crates/plugin-marketplace/src/lib.rs +++ b/rust/crates/plugin-marketplace/src/lib.rs @@ -22,8 +22,12 @@ use url::Url; /// Marketplace index schema version understood by this Core build. pub const MARKETPLACE_INDEX_SCHEMA_VERSION: u64 = 0; +/// Marketplace recommendation catalog schema version understood by this Core build. +pub const MARKETPLACE_RECOMMENDATIONS_SCHEMA_VERSION: u64 = 0; /// Index file a GitHub repository URL resolves to. pub const REPOSITORY_INDEX_FILE_NAME: &str = "lithe-plugin-index.json"; +/// Companion workspace-recommendation file resolved beside a marketplace index. +pub const REPOSITORY_RECOMMENDATIONS_FILE_NAME: &str = "lithe-plugin-recommendations.json"; /// Platforms with a Lithe host today. Other well-formed identifiers are /// accepted so an index can list future platforms without breaking older /// hosts; they simply never match. @@ -523,6 +527,7 @@ fn resolve_source(input: &str) -> Validation { }; return Ok(json!({ "indexURL": index_url, + "recommendationsURL": sibling_recommendations_url(&index_url), "repository": repository.web_url(), "displayName": format!("{}/{}", repository.owner, repository.name), })); @@ -537,6 +542,7 @@ fn resolve_source(input: &str) -> Validation { }; Ok(json!({ "indexURL": index_url.as_str(), + "recommendationsURL": sibling_recommendations_url(index_url.as_str()), "repository": repository.as_ref().map(GitHubRepository::web_url), "displayName": repository .map(|repository| format!("{}/{}", repository.owner, repository.name)) @@ -544,6 +550,22 @@ fn resolve_source(input: &str) -> Validation { })) } +/// Derives the companion `lithe-plugin-recommendations.json` URL in the same +/// directory as a validated `indexURL`, dropping any query or fragment. +fn sibling_recommendations_url(index_url: &str) -> String { + let Ok(mut url) = Url::parse(index_url) else { + return String::new(); + }; + url.set_query(None); + url.set_fragment(None); + if let Ok(mut segments) = url.path_segments_mut() { + segments.pop_if_empty(); + segments.pop(); + segments.push(REPOSITORY_RECOMMENDATIONS_FILE_NAME); + } + url.to_string() +} + // MARK: Install review /// Summarizes what installing a package lets it do, and which programs are @@ -753,6 +775,369 @@ struct ResolveSourcePayload { url: String, } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RecommendForWorkspacePayload { + platform: String, + workspace_files: Vec, + catalogs: Vec, + #[serde(default)] + host_capabilities: Option, + #[serde(default, rename = "installedPluginIDs")] + installed_plugin_ids: Vec, + #[serde(default, rename = "dismissedPluginIDs")] + dismissed_plugin_ids: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RecommendationCatalogInput { + index: Value, + source_kind: SourceKind, + #[serde(default, rename = "indexURL")] + index_url: Option, + recommendations: Value, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RawRecommendationEntry { + #[serde(rename = "pluginID")] + plugin_id: String, + #[serde(default)] + markers: Vec, + #[serde(default)] + extensions: Vec, + #[serde(default)] + covered_by: Vec, +} + +struct ValidRecommendationEntry { + plugin_id: String, + markers: Vec, + extensions: Vec, + covered_by: Vec, +} + +struct MatchedRecommendation { + has_markers: bool, + name_key: String, + id_key: String, + value: Value, +} + +fn recommendations_invalid( + field: impl Into, + message: impl Into, +) -> PluginRejection { + PluginRejection::at("plugin.recommendations.invalid", field, message) +} + +fn is_recommendation_marker(value: &str) -> bool { + !value.is_empty() + && value == value.trim() + && value != "." + && value != ".." + && !value.contains('/') + && !value.contains('\\') +} + +fn is_recommendation_extension(value: &str) -> bool { + let bytes = value.as_bytes(); + !bytes.is_empty() + && bytes.len() <= 32 + && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit()) + && bytes[1..] + .iter() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"_-".contains(byte)) +} + +fn validate_recommendation_root(document: Value, prefix: &str) -> Validation> { + let Value::Object(mut root) = document else { + return Err(PluginRejection::at( + "plugin.recommendations.invalid", + prefix, + "The plugin recommendation catalog must be a JSON object.", + )); + }; + match root.get("schemaVersion").and_then(Value::as_u64) { + Some(MARKETPLACE_RECOMMENDATIONS_SCHEMA_VERSION) => {} + Some(version) => { + return Err(PluginRejection::at( + "plugin.recommendations.schemaUnsupported", + format!("{prefix}.schemaVersion"), + format!( + "Plugin recommendation catalog schema {version} is not supported by this version of Lithe." + ), + )) + } + None => { + return Err(recommendations_invalid( + format!("{prefix}.schemaVersion"), + "The plugin recommendation catalog has no schemaVersion.", + )) + } + } + let Some(Value::Array(entries)) = root.remove("recommendations") else { + return Err(recommendations_invalid( + format!("{prefix}.recommendations"), + "The plugin recommendation catalog has no recommendations list.", + )); + }; + if let Some(unknown) = root.keys().find(|key| key.as_str() != "schemaVersion") { + return Err(recommendations_invalid( + format!("{prefix}.{unknown}"), + format!("The plugin recommendation catalog has an unknown field: {unknown}."), + )); + } + Ok(entries) +} + +fn validate_recommendation_entry( + entry: RawRecommendationEntry, + field: &str, +) -> Validation { + if !is_plugin_id(&entry.plugin_id) { + return Err(recommendations_invalid( + format!("{field}.pluginID"), + "The plugin ID must use lowercase letters, digits, dots, and hyphens.", + )); + } + if entry.markers.is_empty() && entry.extensions.is_empty() { + return Err(recommendations_invalid( + field, + "Each recommendation entry must declare at least one marker or extension.", + )); + } + for (position, marker) in entry.markers.iter().enumerate() { + if !is_recommendation_marker(marker) { + return Err(recommendations_invalid( + format!("{field}.markers[{position}]"), + "Markers must be non-empty file basenames without path separators.", + )); + } + } + for (position, extension) in entry.extensions.iter().enumerate() { + if !is_recommendation_extension(extension) { + return Err(recommendations_invalid( + format!("{field}.extensions[{position}]"), + "Extensions must be lowercase identifiers without a leading dot.", + )); + } + } + for (position, alternative) in entry.covered_by.iter().enumerate() { + if !is_plugin_id(alternative) || alternative == &entry.plugin_id { + return Err(recommendations_invalid( + format!("{field}.coveredBy[{position}]"), + "coveredBy entries must be distinct valid plugin IDs.", + )); + } + } + Ok(ValidRecommendationEntry { + plugin_id: entry.plugin_id, + markers: entry.markers, + extensions: entry.extensions, + covered_by: entry.covered_by, + }) +} + +struct WorkspaceSignals { + basenames: Vec, + extensions: BTreeSet, +} + +fn collect_workspace_signals(workspace_files: &[String]) -> WorkspaceSignals { + let mut seen_basenames = BTreeSet::new(); + let mut extensions = BTreeSet::new(); + for path in workspace_files { + let trimmed = path.trim(); + let Some(basename) = trimmed.rsplit(['/', '\\']).next() else { + continue; + }; + if basename.is_empty() || basename == "." || basename == ".." { + continue; + } + seen_basenames.insert(basename.to_string()); + if let Some((stem, ext)) = basename.rsplit_once('.') { + if !stem.is_empty() && !ext.is_empty() { + extensions.insert(ext.to_ascii_lowercase()); + } + } + } + WorkspaceSignals { + basenames: seen_basenames.into_iter().collect(), + extensions, + } +} + +fn recommend_for_workspace(payload: RecommendForWorkspacePayload) -> Validation { + if !is_platform(&payload.platform) { + return Err(PluginRejection::at( + "plugin.index.invalid", + "platform", + "The host platform identifier is invalid.", + )); + } + let signals = collect_workspace_signals(&payload.workspace_files); + // Windows filesystems match build markers ASCII case-insensitively while Unix stays exact. + let marker_case_insensitive = payload.platform.starts_with("windows-"); + let installed: BTreeSet = payload.installed_plugin_ids.into_iter().collect(); + let dismissed: BTreeSet = payload.dismissed_plugin_ids.into_iter().collect(); + + let mut accepted_ids = BTreeSet::new(); + let mut matched_plugins: Vec = Vec::new(); + let mut rejected = Vec::new(); + + for (catalog_pos, catalog) in payload.catalogs.into_iter().enumerate() { + let catalog_prefix = format!("catalogs[{catalog_pos}].recommendations"); + let index_result = validate_index( + catalog.index, + catalog.source_kind, + &payload.platform, + payload.host_capabilities.as_ref(), + ); + let validated_index = match index_result { + Ok(index) => index, + Err(error) => { + rejected.push(json!({ "id": Value::Null, "error": error })); + continue; + } + }; + let entries = match validate_recommendation_root(catalog.recommendations, &catalog_prefix) { + Ok(entries) => entries, + Err(error) => { + rejected.push(json!({ "id": Value::Null, "error": error })); + continue; + } + }; + + let mut available_by_id: BTreeMap = BTreeMap::new(); + if let Some(plugins) = validated_index["plugins"].as_array() { + for plugin in plugins { + if plugin["availability"]["status"] == "available" { + if let Some(id) = plugin["id"].as_str() { + available_by_id.insert(id.to_string(), plugin.clone()); + } + } + } + } + + let mut seen_in_catalog = BTreeSet::new(); + for (entry_pos, raw) in entries.into_iter().enumerate() { + let field = format!("{catalog_prefix}.recommendations[{entry_pos}]"); + let raw_id = raw + .get("pluginID") + .and_then(Value::as_str) + .map(str::to_string); + let parsed = serde_json::from_value::(raw) + .map_err(|error| { + recommendations_invalid( + field.clone(), + format!("The recommendation entry is invalid: {error}"), + ) + }) + .and_then(|entry| validate_recommendation_entry(entry, &field)) + .and_then(|entry| { + if seen_in_catalog.insert(entry.plugin_id.clone()) { + Ok(entry) + } else { + Err(PluginRejection::at( + "plugin.recommendations.duplicate", + format!("{field}.pluginID"), + "The plugin is listed more than once in this recommendation catalog.", + )) + } + }); + let rule = match parsed { + Ok(rule) => rule, + Err(error) => { + rejected.push(json!({ "id": raw_id, "error": error })); + continue; + } + }; + + let matched_markers: BTreeSet = rule + .markers + .iter() + .filter(|marker| { + signals.basenames.iter().any(|name| { + if marker_case_insensitive { + name.eq_ignore_ascii_case(marker) + } else { + name == marker.as_str() + } + }) + }) + .cloned() + .collect(); + let matched_extensions: BTreeSet = rule + .extensions + .iter() + .filter(|ext| signals.extensions.contains(ext.as_str())) + .cloned() + .collect(); + + if matched_markers.is_empty() && matched_extensions.is_empty() { + continue; + } + if installed.contains(&rule.plugin_id) + || dismissed.contains(&rule.plugin_id) + || rule + .covered_by + .iter() + .any(|alternative| installed.contains(alternative)) + { + continue; + } + let Some(plugin_value) = available_by_id.get(&rule.plugin_id) else { + continue; + }; + if !accepted_ids.insert(rule.plugin_id.clone()) { + continue; + } + + let matched_markers: Vec = matched_markers.into_iter().collect(); + let matched_extensions: Vec = matched_extensions.into_iter().collect(); + let has_markers = !matched_markers.is_empty(); + let name_key = plugin_value["name"] + .as_str() + .unwrap_or_default() + .to_ascii_lowercase(); + let mut item = serde_json::Map::new(); + item.insert("plugin".to_string(), plugin_value.clone()); + item.insert("matchedMarkers".to_string(), json!(matched_markers)); + item.insert("matchedExtensions".to_string(), json!(matched_extensions)); + if let Some(index_url) = catalog + .index_url + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + { + item.insert("marketplaceIndexURL".to_string(), json!(index_url)); + } + matched_plugins.push(MatchedRecommendation { + has_markers, + name_key, + id_key: rule.plugin_id, + value: Value::Object(item), + }); + } + } + + matched_plugins.sort_by(|left, right| { + right + .has_markers + .cmp(&left.has_markers) + .then_with(|| left.name_key.cmp(&right.name_key)) + .then_with(|| left.id_key.cmp(&right.id_key)) + }); + let plugins: Vec = matched_plugins + .into_iter() + .map(|entry| entry.value) + .collect(); + Ok(json!({ "plugins": plugins, "rejected": rejected })) +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct InstallReviewPayload { @@ -823,3 +1208,12 @@ pub fn install_review_command(payload: Value) -> Result { ), )) } + +/// `plugins.marketplace.recommendForWorkspace`: validates companion +/// recommendation catalogs against marketplace indexes and returns matching, +/// available, uninstalled, and undismissed plugins. +pub fn recommend_for_workspace_command(payload: Value) -> Result { + let payload: RecommendForWorkspacePayload = + decode_payload(payload, "plugins.marketplace.recommendForWorkspace")?; + Ok(outcome("recommendation", recommend_for_workspace(payload))) +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 49cfc9c7..cd64e428 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -14,6 +14,7 @@ This directory is the cross-platform source of truth: | `plugin-manifest.schema.json` | JSON shape of `plugin.json` | | `plugin-ui.schema.json` | JSON shape of what a [plugin view](#plugin-views) function returns: whole views and patches the host draws | | `plugin-index.schema.json` | JSON shape of a marketplace source index | +| `plugin-recommendations.schema.json` | JSON shape of a marketplace companion recommendations file (`lithe-plugin-recommendations.json`) | | `plugin-l10n.schema.json` | JSON shape of a plugin's translation file `l10n/.json` | | `fixtures/` | Valid example manifests and golden cases, one folder per contract area (below). Manifests are named after the capability they exercise rather than a published plugin. Case files name their base manifest by file name, so file names are unique across the folders | | `toolchains/README.md` | Implemented Core foundation: plugin definitions/provider declarations, registry (a short tool ID defined by several enabled plugins belongs to none of them), reply validation, directory pins, snapshot resolution, version matching and discovery plans; hosts that declare `toolDefinitions` use it for read-only settings pages and for Build and run tools | @@ -36,7 +37,7 @@ This directory is the cross-platform source of truth: | `fixtures/project-generators/` | Project generators: template files (`templates/`), a scaffolding command, and an archive download; `project-generator-tool-field.plugin.json` with `templates/tool-field/` picks tool installations with `tool` fields; `project-plans.json` holds golden `project.*` form evaluations, generation plans, and name checks, and a case's optional `manifest` names the fixture it runs against (`project-generator.plugin.json` by default) | | `fixtures/toolchains/` | Production-shape fixtures for tool definitions and a packaged toolchain provider; they require `toolDefinitions` and `toolchainProviders`, which a host advertises only when it implements them | | `fixtures/package-trust/` | `publisher-bundled.plugin.json` and `signature-vectors.json`: public cross-platform vectors for the package publisher signature: the RFC 8032 test key, a fixed package with non-ASCII file names, its canonical payload, RFC 8032 deterministic signature, and content digest. Both platforms must build the same canonical payload and digest and accept the recorded signature; signers that add randomness, such as CryptoKit, check the signature by verification instead of byte comparison | -| `fixtures/marketplace/` | Marketplace index, availability, source URL, and install review golden cases | +| `fixtures/marketplace/` | Marketplace index, availability, source URL, workspace recommendation, and install review golden cases | Validation and template expansion are implemented once in Rust Core (`rust/crates/plugin-manifest/` and the `rust/crates/plugin-*` crates beside @@ -1769,11 +1770,36 @@ every product shows the same catalog and the same install review. is used as is (fragment removed); `https://github.com//` resolves to `lithe-plugin-index.json` at the repository root on its default branch (`HEAD`); a `…/blob//` page resolves to its raw file. - Plain http, embedded credentials, and other GitHub pages are refused with - `plugin.source.invalid`. + It also returns `recommendationsURL`, the sibling `lithe-plugin-recommendations.json` + beside `indexURL` (query and fragment cleared). Plain http, embedded + credentials, and other GitHub pages are refused with `plugin.source.invalid`. - Hosts cache fetched indexes in platform cache or application-support storage, never inside the installation. +### Workspace recommendations + +A marketplace source may publish a companion recommendations file +(`plugin-recommendations.schema.json`, `lithe-plugin-recommendations.json`) +beside `lithe-plugin-index.json`, keeping `lithe-plugin-index.json` (`schemaVersion: 0`) +unchanged for existing hosts. A source without `lithe-plugin-recommendations.json` +simply offers no automatic workspace recommendations. + +| Field | Meaning | +| --- | --- | +| `pluginID` | Plugin ID listed in the same source's `lithe-plugin-index.json`. | +| `markers` | Optional exact workspace file basenames (for example `pom.xml`, `go.mod`, `build.gradle.kts`). Matched case-sensitively on Unix (`darwin-*`, `linux-*`) and ASCII case-insensitively on Windows (`windows-*`). No path separators, `.`, or `..`. | +| `extensions` | Optional lowercase file extensions without a leading dot (for example `java`, `go`). Matched ASCII case-insensitively against sampled workspace files (ignoring leading-dot names without a stem such as `.gitignore`). | +| `coveredBy` | Optional other plugin IDs whose installation already covers this workflow; when any listed ID is in `installedPluginIDs`, this plugin is not recommended. | + +Each recommendation entry must declare at least one `markers` or `extensions` +value; duplicate `pluginID` values within one catalog are rejected with +`plugin.recommendations.duplicate` while keeping the first entry. +`plugins.marketplace.recommendForWorkspace` validates each catalog pair +(`index` + `recommendations`), filters to entries whose plugin is `available` on +the host platform and `hostCapabilities`, excludes installed, `coveredBy`-covered, +and dismissed IDs, deduplicates across catalogs (first catalog wins), and sorts +marker matches before extension-only matches, then by plugin name and ID. + ### Index entries | Field | Meaning | @@ -4933,6 +4959,9 @@ command payload is a Core `invalid_request` failure instead. | `plugin.index.duplicate` | Core | An index lists the same plugin ID more than once | | `plugin.index.platformUnsupported` | Core | No version has an archive for this platform (availability, not a rejection) | | `plugin.index.apiUnsupported` | Core | Only versions needing a plugin API or a capability version the host does not run list this platform (availability, not a rejection) | +| `plugin.recommendations.invalid` | Core | Malformed companion recommendation catalog root or entry (`pluginID`, `markers`, `extensions`, or `coveredBy`) | +| `plugin.recommendations.schemaUnsupported` | Core | The companion recommendation catalog `schemaVersion` is not `0` | +| `plugin.recommendations.duplicate` | Core | A companion recommendation catalog lists the same `pluginID` more than once | | `plugin.source.invalid` | Core | A marketplace source URL cannot be used | | `plugin.package.mismatch` | Core | A downloaded package's ID or version differs from its index entry | | `plugin.archive.checksumMismatch` | Host | A downloaded archive does not match the index SHA-256 | diff --git a/shared/plugins/contract/v1/fixtures/marketplace/recommendations-cases.json b/shared/plugins/contract/v1/fixtures/marketplace/recommendations-cases.json new file mode 100644 index 00000000..c64d65bb --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/marketplace/recommendations-cases.json @@ -0,0 +1,90 @@ +{ + "schemaVersion": 1, + "description": "plugins.marketplace.recommendForWorkspace matching, filtering, platform casing and sorting cases against index.json and recommendations.json.", + "cases": [ + { + "name": "matches marker and extension and sorts marker matches first", + "sourceKind": "official", + "platform": "darwin-arm64", + "hostCapabilities": { + "buildProviders": [0], + "buildSystems": [0], + "languageServers": [0], + "languages": [0] + }, + "workspaceFiles": ["build.zig", "lib/app.ex", "Futurefile", ".gitignore"], + "installedPluginIDs": [], + "dismissedPluginIDs": [], + "expectedPlugins": [ + { + "id": "io.example.zig-support", + "matchedMarkers": ["build.zig"], + "matchedExtensions": ["zig"] + }, + { + "id": "io.example.elixir-tools", + "matchedMarkers": [], + "matchedExtensions": ["ex"] + } + ] + }, + { + "name": "excludes installed, coveredBy and dismissed plugins", + "sourceKind": "thirdParty", + "platform": "darwin-arm64", + "hostCapabilities": { + "buildProviders": [0], + "buildSystems": [0], + "languageServers": [0], + "languages": [0] + }, + "workspaceFiles": ["build.zig", "src/main.zig", "mix.exs", "composer.json"], + "installedPluginIDs": ["io.example.zig-support", "io.example.elixir-lite"], + "dismissedPluginIDs": ["dev.lithe.fixture.language-packaged-server"], + "expectedPlugins": [] + }, + { + "name": "marker matching is case-sensitive on Unix and case-insensitive on Windows", + "sourceKind": "thirdParty", + "platform": "darwin-arm64", + "hostCapabilities": { + "languageServers": [0], + "languages": [0] + }, + "workspaceFiles": ["BUILD.ZIG", "src/MAIN.ZIG"], + "installedPluginIDs": [], + "dismissedPluginIDs": [], + "expectedPlugins": [ + { + "id": "io.example.zig-support", + "matchedMarkers": [], + "matchedExtensions": ["zig"] + } + ] + }, + { + "name": "windows matches markers ASCII case-insensitively", + "sourceKind": "thirdParty", + "platform": "windows-x64", + "hostCapabilities": { + "languageServers": [0], + "languages": [0] + }, + "workspaceFiles": ["BUILD.ZIG", "lib\\APP.EX"], + "installedPluginIDs": [], + "dismissedPluginIDs": [], + "expectedPlugins": [ + { + "id": "io.example.zig-support", + "matchedMarkers": ["build.zig"], + "matchedExtensions": ["zig"] + }, + { + "id": "io.example.elixir-tools", + "matchedMarkers": [], + "matchedExtensions": ["ex"] + } + ] + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/marketplace/recommendations.json b/shared/plugins/contract/v1/fixtures/marketplace/recommendations.json new file mode 100644 index 00000000..abeee5e4 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/marketplace/recommendations.json @@ -0,0 +1,25 @@ +{ + "schemaVersion": 0, + "recommendations": [ + { + "pluginID": "dev.lithe.fixture.language-packaged-server", + "markers": ["composer.json"], + "extensions": ["php"] + }, + { + "pluginID": "io.example.elixir-tools", + "markers": ["mix.exs"], + "extensions": ["ex", "exs"], + "coveredBy": ["io.example.elixir-lite"] + }, + { + "pluginID": "io.example.future-tools", + "markers": ["Futurefile"] + }, + { + "pluginID": "io.example.zig-support", + "markers": ["build.zig"], + "extensions": ["zig"] + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json b/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json index eb25e38d..309fe754 100644 --- a/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json +++ b/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json @@ -1,12 +1,12 @@ { "schemaVersion": 1, - "description": "plugins.marketplace.resolveSource inputs and the index URL every host must fetch, or the rejection code.", + "description": "plugins.marketplace.resolveSource inputs and the index and companion recommendations URLs every host must fetch, or the rejection code.", "cases": [ - { "input": "https://github.com/example/lithe-plugins", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, - { "input": " https://github.com/example/lithe-plugins.git/ ", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, - { "input": "https://github.com/example/lithe-plugins/blob/release/v1/indexes/lithe-plugin-index.json", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-index.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, - { "input": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, - { "input": "https://plugins.example.com/lithe/index.json#latest", "expected": { "indexURL": "https://plugins.example.com/lithe/index.json", "repository": null, "displayName": "plugins.example.com" } }, + { "input": "https://github.com/example/lithe-plugins", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, + { "input": " https://github.com/example/lithe-plugins.git/ ", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, + { "input": "https://github.com/example/lithe-plugins/blob/release/v1/indexes/lithe-plugin-index.json", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, + { "input": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, + { "input": "https://plugins.example.com/lithe/index.json#latest", "expected": { "indexURL": "https://plugins.example.com/lithe/index.json", "recommendationsURL": "https://plugins.example.com/lithe/lithe-plugin-recommendations.json", "repository": null, "displayName": "plugins.example.com" } }, { "input": "http://plugins.example.com/index.json", "expectedCode": "plugin.source.invalid" }, { "input": "https://token@github.com/example/lithe-plugins", "expectedCode": "plugin.source.invalid" }, { "input": "https://github.com/example", "expectedCode": "plugin.source.invalid" }, diff --git a/shared/plugins/contract/v1/plugin-recommendations.schema.json b/shared/plugins/contract/v1/plugin-recommendations.schema.json new file mode 100644 index 00000000..39dc3287 --- /dev/null +++ b/shared/plugins/contract/v1/plugin-recommendations.schema.json @@ -0,0 +1,52 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/Lithe-IDEA/Lithe-core-rust/main/shared/plugins/contract/v1/plugin-recommendations.schema.json", + "title": "Lithe plugin marketplace recommendations (plugin contract v1)", + "description": "Shape of a marketplace companion recommendations file, lithe-plugin-recommendations.json. Semantic rules (non-empty signal requirement, non-`.`/.. markers, distinct coveredBy IDs, duplicate pluginID) are defined in README.md and enforced by plugins.marketplace.recommendForWorkspace.", + "type": "object", + "additionalProperties": false, + "required": ["schemaVersion", "recommendations"], + "properties": { + "schemaVersion": { "const": 0 }, + "recommendations": { + "type": "array", + "items": { "$ref": "#/$defs/entry" } + } + }, + "$defs": { + "pluginID": { + "type": "string", + "pattern": "^[a-z0-9.-]+$" + }, + "entry": { + "type": "object", + "additionalProperties": false, + "required": ["pluginID"], + "properties": { + "pluginID": { "$ref": "#/$defs/pluginID" }, + "markers": { + "description": "Exact workspace file basenames (matched case-sensitively on Unix and ASCII case-insensitively on Windows).", + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "pattern": "^[^/\\\\]+$" + } + }, + "extensions": { + "description": "Lowercase file extensions without a leading dot (matched ASCII case-insensitively).", + "type": "array", + "items": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]{0,31}$" + } + }, + "coveredBy": { + "description": "Other plugin IDs whose installation satisfies the same workflow, so this plugin is not recommended when any of them is already installed.", + "type": "array", + "items": { "$ref": "#/$defs/pluginID" } + } + } + } + } +} diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 2eb9a93d..bd48a332 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,8 @@ ## 待合入 +- [#130](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/130),[@1lck](https://github.com/1lck),**工作区插件推荐**:市场契约新增同级推荐索引格式 `plugin-recommendations.schema.json`(`schemaVersion: 0`,独立于只增不破旧版的 `lithe-plugin-index.json`);`plugins.marketplace.resolveSource` 额外返回 `recommendationsURL`,并新增宿主内部 Core 命令 `plugins.marketplace.recommendForWorkspace`(不是插件 RPC),基于工作区采集文件名与已有市场索引匹配可安装的缺失插件。见 [1lck/Lithe-IDEA#2228](https://github.com/1lck/Lithe-IDEA/issues/2228)。 + - [#127](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/127),[@Mucheen](https://github.com/Mucheen),**API-25**:从 `grammar.path` 指定的 TextMate 语法或独立的 `grammars/.first-line.json` 读取可选 `firstLineMatch`。独立文件可沿用宿主现有高亮。旧桌面仍可安装 `languages: 0` 的同一插件包。Core 解码返回可选提示并匹配完整首行,既有路径与用户关联优先。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 - [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-23、API-29):`run/start` 的 `process` 和提供者 `lithe/build/prepareRun` 的返回值新增可选 `outputEncoding`,用稳定编码 ID 或别名声明进程写入管道的编码;Core 校验并规范化,拒绝未知或不兼容 ASCII 的编码。用户固定编码优先;自动模式逐行尝试声明、UTF-8,以及仅 Windows 的 GBK。省略字段时所有平台默认 UTF-8,Windows 兼容 GBK;不修改进程环境或终端代码页。新增宿主内部 Core 命令 `outputEncoding.resolve`,返回同一解析规则的候选与可选编码列表,不是插件 RPC。见 [1lck/Lithe-IDEA#2186](https://github.com/1lck/Lithe-IDEA/issues/2186)。 @@ -37,6 +39,7 @@ | 插件网页桥 `window.lithe.version` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `litheSettingsSources`、`litheSettingsSourceEdit` | 0 | 2026-11-15 | [#57](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/57) | +| 市场推荐索引 `schemaVersion` | 0 | 待合入 | [#130](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/130) | ### 能力版本(`requires`)