From f83d992c61b428f450bb95a3ea1c1ee652072b67 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 14:23:48 +0800 Subject: [PATCH] tool: require exact current contracts without negotiation --- crates/cli/src/tool.rs | 223 +++++++----------- crates/cli/tests/examples_r6.rs | 2 +- crates/cli/tests/tool_protocol.rs | 149 +++++------- .../0068-single-current-public-contracts.md | 4 +- .../tool-samples/sample-knowledge/tool.json | 8 +- examples/tool-samples/sample-proof/tool.json | 8 +- examples/tool-samples/sample-view/src/main.rs | 2 +- examples/tool-samples/sample-view/tool.json | 7 +- examples/tool-unknown-name/README.md | 2 +- .../tool-unknown-name/bin/marqdo-benchmark | 2 +- examples/tool-unknown-name/tool.json | 4 +- spec/cli-tool.md | 43 ++++ ...ol-v1.schema.json => cli-tool.schema.json} | 38 ++- spec/tool-v1.md | 89 ------- tests/consumers/validate_protocols.py | 6 +- tests/fixtures/tool_echo.rs | 8 +- 16 files changed, 229 insertions(+), 366 deletions(-) create mode 100644 spec/cli-tool.md rename spec/schemas/{tool-v1.schema.json => cli-tool.schema.json} (59%) delete mode 100644 spec/tool-v1.md diff --git a/crates/cli/src/tool.rs b/crates/cli/src/tool.rs index 474dc8e..1881677 100644 --- a/crates/cli/src/tool.rs +++ b/crates/cli/src/tool.rs @@ -1,4 +1,4 @@ -//! Generic external CLI tool protocol (spec/tool-v1.md). +//! Generic external CLI tool protocol (spec/cli-tool.md). //! //! The core never knows a tool's name. It validates a user-supplied //! `tool.json`, verifies protocol compatibility, copies the whole bundle into a @@ -11,7 +11,7 @@ use std::ffi::OsString; use std::path::{Component, Path, PathBuf}; use std::process::Command as ProcessCommand; -use semver::{Version, VersionReq}; +use semver::Version; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -21,19 +21,7 @@ const RECORD_VERSION: u32 = 2; const MAX_BUNDLE_FILES: usize = 4096; const MAX_BUNDLE_BYTES: u64 = 256 * 1024 * 1024; -/// Protocols this core can provide to tools. -#[derive(Debug, Clone, Copy)] -struct SupportedProtocols { - tool: u32, - analysis: &'static [u32], - trace: &'static [u32], -} - -const SUPPORTED: SupportedProtocols = SupportedProtocols { - tool: PROTOCOL_VERSION, - analysis: &[crate::analysis::SCHEMA_VERSION], - trace: &[2], -}; +const API_REVISION: u32 = 1; const BUILTIN_COMMANDS: &[&str] = &[ "init", "run", "call", "check", "inspect", "fmt", "plugin", "add", "remove", "lock", "sync", @@ -41,6 +29,7 @@ const BUILTIN_COMMANDS: &[&str] = &[ ]; #[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] struct ToolManifest { schema: String, schema_version: u32, @@ -48,38 +37,29 @@ struct ToolManifest { version: String, command: String, entrypoint: PathBuf, - #[serde(default)] - compatibility: Compatibility, + requires: Requirements, } -#[derive(Debug, Clone, Default, Deserialize)] -struct Compatibility { - #[serde(default)] - marqdo: Option, - #[serde(default)] - analysis: Option>, - #[serde(default)] - trace: Option>, +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Requirements { + api_revision: u32, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "read_requirement" + )] + analysis: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "read_requirement" + )] + observation: Option, } -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct RecordedCompatibility { - #[serde(default, skip_serializing_if = "Option::is_none")] - marqdo: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - analysis: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - trace: Option>, -} - -impl RecordedCompatibility { - fn as_compatibility(&self) -> Compatibility { - Compatibility { - marqdo: self.marqdo.clone(), - analysis: self.analysis.clone(), - trace: self.trace.clone(), - } - } +fn read_requirement<'de, D: serde::Deserializer<'de>>(reader: D) -> Result, D::Error> { + u32::deserialize(reader).map(Some) } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -90,6 +70,7 @@ struct BundleEntry { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] struct ToolRecord { record_version: u32, command: String, @@ -100,8 +81,7 @@ struct ToolRecord { bundle_sha256: String, source: String, schema_version: u32, - #[serde(default)] - compatibility: RecordedCompatibility, + requires: Requirements, } /// `marqdo tool install `. @@ -201,11 +181,7 @@ fn install_inner(manifest_path: &Path) -> Result { bundle_sha256: bundle_sha256.clone(), source: manifest_file.display().to_string(), schema_version: manifest.schema_version, - compatibility: RecordedCompatibility { - marqdo: manifest.compatibility.marqdo.clone(), - analysis: manifest.compatibility.analysis.clone(), - trace: manifest.compatibility.trace.clone(), - }, + requires: manifest.requires.clone(), }; let record_json = serde_json::to_string_pretty(&record) .map_err(|error| format!("cannot serialize record: {error}"))?; @@ -226,7 +202,7 @@ impl ToolManifest { let text = std::fs::read_to_string(path) .map_err(|error| format!("cannot read `{}`: {error}", path.display()))?; let manifest: Self = - serde_json::from_str(&text).map_err(|error| format!("invalid tool.json: {error}"))?; + serde_json::from_str(&text).map_err(|error| format!("invalid tool.json: {error}. Build the tool with current exact protocol requirements"))?; Ok(manifest) } } @@ -235,10 +211,10 @@ fn validate_manifest(manifest: &ToolManifest) -> Result<(), String> { if manifest.schema != SCHEMA { return Err(format!("unsupported tool schema `{}`", manifest.schema)); } - if manifest.schema_version != SUPPORTED.tool { + if manifest.schema_version != PROTOCOL_VERSION { return Err(format!( "unsupported tool schema_version {} (expected {})", - manifest.schema_version, SUPPORTED.tool + manifest.schema_version, PROTOCOL_VERSION )); } if !is_valid_command(&manifest.command) { @@ -262,57 +238,34 @@ fn validate_manifest(manifest: &ToolManifest) -> Result<(), String> { manifest.version ) })?; - negotiate(&manifest.version, &manifest.compatibility) + validate_requirements(&manifest.requires) } -fn negotiate(tool_version: &str, compatibility: &Compatibility) -> Result<(), String> { - Version::parse(tool_version) - .map_err(|error| format!("tool version `{tool_version}` is not valid SemVer: {error}"))?; - let core_version = Version::parse(env!("CARGO_PKG_VERSION")) - .map_err(|error| format!("core version is not valid SemVer: {error}"))?; - if let Some(range) = &compatibility.marqdo { - let requirement = VersionReq::parse(range) - .map_err(|error| format!("invalid marqdo compatibility range `{range}`: {error}"))?; - if !requirement.matches(&core_version) { - return Err(format!( - "tool requires marqdo `{range}`, this core is {}", - env!("CARGO_PKG_VERSION") - )); +fn validate_requirements(requires: &Requirements) -> Result<(), String> { + for (name, requested, current) in [ + ("api_revision", Some(requires.api_revision), API_REVISION), + ( + "analysis", + requires.analysis, + crate::analysis::SCHEMA_VERSION, + ), + ( + "observation", + requires.observation, + crate::execution_events::SCHEMA_VERSION, + ), + ] { + if let Some(requested) = requested { + if requested != current { + return Err(format!( + "tool.protocol_incompatible: tool requires {name} {requested}, this core provides {current}" + )); + } } } - negotiate_protocol( - "analysis", - compatibility.analysis.as_deref(), - SUPPORTED.analysis, - )?; - negotiate_protocol("trace", compatibility.trace.as_deref(), SUPPORTED.trace)?; Ok(()) } -fn negotiate_protocol( - name: &str, - requested: Option<&[u32]>, - supported: &[u32], -) -> Result<(), String> { - let Some(requested) = requested else { - return Ok(()); - }; - if shared_version(requested, supported).is_none() { - return Err(format!( - "tool.protocol_incompatible: tool requires {name} version(s) {requested:?}, this core supports {supported:?}" - )); - } - Ok(()) -} - -fn shared_version(requested: &[u32], supported: &[u32]) -> Option { - requested - .iter() - .copied() - .filter(|version| supported.contains(version)) - .max() -} - fn is_valid_command(command: &str) -> bool { let mut bytes = command.bytes(); matches!(bytes.next(), Some(byte) if byte.is_ascii_lowercase()) @@ -483,7 +436,7 @@ pub fn list(json: bool) -> i32 { "name": record.name, "version": record.version, "bundle_files": record.bundle.len(), - "compatibility": record.compatibility, + "requires": record.requires, }) }) .collect(); @@ -568,8 +521,8 @@ pub fn dispatch(args: &[OsString]) -> i32 { return 2; }; let command = first.to_string_lossy(); - if BUILTIN_COMMANDS.contains(&command.as_ref()) { - eprintln!("error: internal dispatch error for built-in command `{command}`"); + if !is_valid_command(&command) || BUILTIN_COMMANDS.contains(&command.as_ref()) { + eprintln!("error: invalid external command `{command}`"); return 2; } let home = match tool_home() { @@ -582,6 +535,10 @@ pub fn dispatch(args: &[OsString]) -> i32 { let dir = home.join(command.as_ref()); let record = match load_record(&dir) { Ok(record) => record, + Err(error) if dir.exists() => { + eprintln!("error: tool `{command}`: {error}"); + return 1; + } Err(_) => { eprintln!( "error: unknown command `{command}`; install a tool with `marqdo tool install `" @@ -593,14 +550,6 @@ pub fn dispatch(args: &[OsString]) -> i32 { eprintln!("error: tool record does not match command `{command}`; reinstall it"); return 1; } - if let Err(error) = negotiate(&record.version, &record.compatibility.as_compatibility()) { - eprintln!("error: tool `{command}` is not compatible with this core: {error}"); - return 1; - } - if record.record_version != RECORD_VERSION { - eprintln!("error: tool `{command}` uses an old record; reinstall it"); - return 1; - } let bundle = match collect_bundle(&dir, true) { Ok(bundle) => bundle, Err(error) => { @@ -627,26 +576,16 @@ pub fn dispatch(args: &[OsString]) -> i32 { }; let mut process = ProcessCommand::new(&entrypoint); process.args(&args[1..]); - if let Ok(bin) = std::env::current_exe() { - process.env("MARQDO_BIN", bin); - } - process.env("MARQDO_TOOL_PROTOCOL", "1"); - if let Some(version) = record - .compatibility - .analysis - .as_deref() - .and_then(|versions| shared_version(versions, SUPPORTED.analysis)) - { - process.env("MARQDO_PROTOCOL_ANALYSIS", version.to_string()); - } - if let Some(version) = record - .compatibility - .trace - .as_deref() - .and_then(|versions| shared_version(versions, SUPPORTED.trace)) - { - process.env("MARQDO_PROTOCOL_TRACE", version.to_string()); + match std::env::current_exe() { + Ok(bin) => { + process.env("MARQDO_BIN", bin); + } + Err(error) => { + eprintln!("error: cannot locate marqdo for tool `{command}`: {error}"); + return 1; + } } + process.env("MARQDO_API_REVISION", API_REVISION.to_string()); match process.status() { Ok(status) => status.code().unwrap_or(1), Err(error) => { @@ -690,7 +629,10 @@ fn installed_records() -> Result, String> { if entry.file_name().to_string_lossy().starts_with('.') { continue; } - if let Ok(record) = load_record(&entry.path()) { + if entry.path().join("record.json").is_file() { + let record = load_record(&entry.path()).map_err(|error| { + format!("tool `{}`: {error}", entry.file_name().to_string_lossy()) + })?; records.insert(record.command.clone(), record); } } @@ -698,13 +640,26 @@ fn installed_records() -> Result, String> { } fn load_record(dir: &Path) -> Result { - let text = std::fs::read_to_string(dir.join("record.json")) - .map_err(|error| format!("tool record is missing: {error}"))?; - let record: ToolRecord = - serde_json::from_str(&text).map_err(|error| format!("invalid tool record: {error}"))?; - if record.record_version != RECORD_VERSION { - return Err("tool record is from an older protocol; reinstall it".to_string()); + let record_path = dir.join("record.json"); + let inspect = |path| { + std::fs::symlink_metadata(path) + .map_err(|error| format!("cannot inspect tool registration: {error}")) + }; + if !inspect(dir)?.is_dir() || !inspect(record_path.as_path())?.is_file() { + return Err("invalid tool registration path. Remove and reinstall the tool".to_string()); } + let text = std::fs::read_to_string(record_path) + .map_err(|error| format!("tool record is missing: {error}"))?; + let record: ToolRecord = serde_json::from_str(&text).map_err(|error| { + format!("invalid or retired tool record: {error}. Remove and reinstall the tool") + })?; + if record.record_version != RECORD_VERSION || record.schema_version != PROTOCOL_VERSION { + return Err( + "tool record uses an unsupported format. Remove and reinstall the tool".to_string(), + ); + } + validate_requirements(&record.requires) + .map_err(|error| format!("{error}. Remove and reinstall the tool"))?; Ok(record) } diff --git a/crates/cli/tests/examples_r6.rs b/crates/cli/tests/examples_r6.rs index 64f35db..0cf6306 100644 --- a/crates/cli/tests/examples_r6.rs +++ b/crates/cli/tests/examples_r6.rs @@ -133,7 +133,7 @@ fn unknown_tool_name_installs_and_dispatches() { #[test] fn public_schemas_are_valid_json_and_versioned() { - for name in ["analysis", "trace-v1", "tool-v1", "execution-events-v1"] { + for name in ["analysis", "trace-v1", "cli-tool", "execution-events-v1"] { let path = repo() .join("spec/schemas") .join(format!("{name}.schema.json")); diff --git a/crates/cli/tests/tool_protocol.rs b/crates/cli/tests/tool_protocol.rs index 7d91718..7612823 100644 --- a/crates/cli/tests/tool_protocol.rs +++ b/crates/cli/tests/tool_protocol.rs @@ -1,4 +1,4 @@ -//! External CLI Tool Protocol v1 black-box tests (spec/tool-v1.md). +//! External CLI CLI Tool black-box tests (spec/cli-tool.md). //! //! The tool fixture is compiled with rustc from `tests/fixtures/tool_echo.rs` //! rather than a shell script, so these tests run on Windows and macOS too. @@ -95,7 +95,7 @@ fn write_tool(dir: &Path, command: &str, _script: &str) -> PathBuf { std::fs::write( &manifest, format!( - r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=3.0.0-beta.1,<4.0.0"}}}}"# + r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","requires":{{"api_revision":1}}}}"# ), ) .unwrap(); @@ -120,7 +120,7 @@ fn repo_root() -> PathBuf { } /// Compile one of the checked-in independent consumer samples and package it -/// as a Tool Protocol v1 bundle. Sources live in `examples/tool-samples/` so +/// as a CLI Tool bundle. Sources live in `examples/tool-samples/` so /// they are reviewable software, not hidden test strings. fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf { let root = repo_root(); @@ -142,7 +142,7 @@ fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf { std::fs::write( &manifest, format!( - r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=3.0.0-beta.1,<4.0.0","analysis":[2],"trace":[2]}}}}"# + r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","requires":{{"api_revision":1,"analysis":3,"observation":1}}}}"# ), ) .unwrap(); @@ -200,7 +200,7 @@ fn independent_sample_tools_consume_public_analysis_and_trace() { assert_eq!(view.status.code(), Some(0), "{}", stderr(&view)); let text = stdout(&view); assert!( - text.contains("sample-view schema=marqdo.analysis version=2"), + text.contains("sample-view schema=marqdo.analysis version=3"), "{text}" ); assert!(text.contains("modules="), "{text}"); @@ -245,7 +245,7 @@ fn install_dispatch_list_remove_without_core_knowledge_of_the_name() { let manifest = write_tool( dir.path(), "benchmark", - "#!/bin/sh\nfor a in \"$@\"; do printf 'arg=%s\\n' \"$a\"; done\nprintf 'protocol=%s\\n' \"$MARQDO_TOOL_PROTOCOL\"\nexit 7\n", + "#!/bin/sh\nfor a in \"$@\"; do printf 'arg=%s\\n' \"$a\"; done\nprintf 'protocol=%s\\n' \"$MARQDO_API_REVISION\"\nexit 7\n", ); let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]); @@ -301,7 +301,7 @@ fn invalid_manifests_and_path_escapes_are_rejected() { let incompatible = std::fs::read_to_string(&manifest) .unwrap() - .replace(">=3.0.0-beta.1,<4.0.0", ">=99.0"); + .replace("\"api_revision\":1", "\"api_revision\":99"); let incompatible_manifest = dir.path().join("incompatible.json"); std::fs::write(&incompatible_manifest, incompatible).unwrap(); let output = cli( @@ -309,7 +309,7 @@ fn invalid_manifests_and_path_escapes_are_rejected() { &["tool", "install", incompatible_manifest.to_str().unwrap()], ); assert_eq!(output.status.code(), Some(1)); - assert!(stderr(&output).contains("requires marqdo")); + assert!(stderr(&output).contains("requires api_revision")); } #[test] @@ -355,58 +355,61 @@ fn tampered_binary_and_path_hijack_are_not_executed() { } #[test] -fn protocol_negotiation_accepts_declared_versions_and_rejects_disjoint_ones() { +fn tool_requires_exact_current_protocols_and_rejects_retired_registrations() { + use serde_json::json; + let dir = TempDir::new("protocols"); let home = dir.path().join("home"); - let manifest = write_tool( - dir.path(), - "proto", - "#!/bin/sh\nprintf 'analysis=%s\\ntrace=%s\\n' \"$MARQDO_PROTOCOL_ANALYSIS\" \"$MARQDO_PROTOCOL_TRACE\"\n", - ); - let text = std::fs::read_to_string(&manifest).unwrap().replace( - "\"marqdo\":\">=3.0.0-beta.1,<4.0.0\"", - "\"marqdo\":\">=3.0.0-beta.1,<4.0.0\",\"analysis\":[2],\"trace\":[2]", - ); - std::fs::write(&manifest, text).unwrap(); - let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]); - assert_eq!(install.status.code(), Some(0), "{}", stderr(&install)); - let output = cli(&home, &["proto"]); - assert_eq!(output.status.code(), Some(7), "{}", stderr(&output)); - let text = stdout(&output); - assert!(text.contains("analysis=2"), "{text}"); - assert!(text.contains("trace=2"), "{text}"); - - let manifest = write_tool(dir.path(), "proto-v3", ""); - let mut declared: serde_json::Value = + let manifest = write_tool(dir.path(), "proto", ""); + let mut document: serde_json::Value = serde_json::from_slice(&std::fs::read(&manifest).unwrap()).unwrap(); - declared["compatibility"]["analysis"] = serde_json::json!([2, 3]); - std::fs::write(&manifest, declared.to_string()).unwrap(); - let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]); - assert_eq!(install.status.code(), Some(0), "{}", stderr(&install)); - let output = cli(&home, &["proto-v3"]); - assert_eq!(output.status.code(), Some(7), "{}", stderr(&output)); - assert!(stdout(&output).contains("analysis=3")); - - for (compat, tag) in [ - ("\"analysis\":[99]", "analysis-disjoint"), - ("\"analysis\":[]", "analysis-empty"), - ("\"trace\":[9]", "trace-disjoint"), + for (requires, expected) in [ + ( + json!({"api_revision": 1, "analysis": [3]}), + "invalid tool.json", + ), + ( + json!({"api_revision": 1, "analysis": null}), + "invalid tool.json", + ), + ( + json!({"api_revision": 1, "analysis": 2}), + "tool.protocol_incompatible", + ), + ( + json!({"api_revision": 1, "observation": 99}), + "tool.protocol_incompatible", + ), ] { - let command = format!("bad-{tag}"); - let manifest = write_tool(dir.path(), &command, "#!/bin/sh\nexit 0\n"); - let text = std::fs::read_to_string(&manifest).unwrap().replace( - "\"marqdo\":\">=3.0.0-beta.1,<4.0.0\"", - &format!("\"marqdo\":\">=3.0.0-beta.1,<4.0.0\",{compat}"), - ); - std::fs::write(&manifest, text).unwrap(); + document["requires"] = requires; + std::fs::write(&manifest, document.to_string()).unwrap(); let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]); - assert_eq!(output.status.code(), Some(1), "{tag}"); - assert!( - stderr(&output).contains("protocol_incompatible"), - "{tag}: {}", - stderr(&output) - ); + assert_eq!(output.status.code(), Some(1)); + assert!(stderr(&output).contains(expected), "{}", stderr(&output)); } + document.as_object_mut().unwrap().remove("requires"); + document["compatibility"] = json!({"analysis": [2, 3]}); + std::fs::write(&manifest, document.to_string()).unwrap(); + let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]); + assert_eq!(output.status.code(), Some(1)); + assert!(stderr(&output).contains("invalid tool.json")); + + document.as_object_mut().unwrap().remove("compatibility"); + document["requires"] = json!({"api_revision": 1, "analysis": 3, "observation": 1}); + std::fs::write(&manifest, document.to_string()).unwrap(); + let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]); + assert!(output.status.success(), "{}", stderr(&output)); + assert_eq!(cli(&home, &["proto"]).status.code(), Some(7)); + let record = home.join("proto/record.json"); + let mut installed: serde_json::Value = + serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap(); + installed.as_object_mut().unwrap().remove("requires"); + installed["compatibility"] = json!({"analysis": [2, 3]}); + std::fs::write(&record, installed.to_string()).unwrap(); + let output = cli(&home, &["proto"]); + assert_eq!(output.status.code(), Some(1)); + assert!(stderr(&output).contains("Remove and reinstall")); + assert!(cli(&home, &["tool", "remove", "proto"]).status.success()); } #[test] @@ -460,41 +463,3 @@ fn a_root_record_json_in_the_source_package_is_rejected() { assert_eq!(output.status.code(), Some(1)); assert!(stderr(&output).contains("must not contain a root record.json")); } - -#[test] -fn prerelease_core_requires_an_explicit_prerelease_compatible_range() { - let dir = TempDir::new("prerelease-range"); - let home = dir.path().join("home"); - let core = env!("CARGO_PKG_VERSION"); - - for (range, compatible) in [ - (">=3.0.0-beta.1,<4.0.0".to_string(), true), - (format!("={core}"), true), - (">=3.0.0,<4.0.0".to_string(), !core.contains('-')), - (">=0.1,<1".to_string(), false), - ] { - let manifest = write_tool(dir.path(), "prerelease", "#!/bin/sh\nexit 0\n"); - let text = std::fs::read_to_string(&manifest) - .unwrap() - .replace(">=3.0.0-beta.1,<4.0.0", &range); - std::fs::write(&manifest, text).unwrap(); - let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]); - assert_eq!( - output.status.success(), - compatible, - "{range} on {core}: {}", - stderr(&output) - ); - if compatible { - assert!(cli(&home, &["tool", "remove", "prerelease"]) - .status - .success()); - } else { - assert!( - stderr(&output).contains("requires marqdo"), - "{}", - stderr(&output) - ); - } - } -} diff --git a/docs/adr/0068-single-current-public-contracts.md b/docs/adr/0068-single-current-public-contracts.md index 59ab16d..89dfcaf 100644 --- a/docs/adr/0068-single-current-public-contracts.md +++ b/docs/adr/0068-single-current-public-contracts.md @@ -27,10 +27,12 @@ requires its own compatibility policy. `run` and `call` use `--output text|json|jsonl` and `--observation-file PATH`. Capture selections and budgets apply to all observation destinations. -- Tool manifests use `marqdo.cli-tool` revision 2, with a required +- Tool manifests use `marqdo.cli-tool` with its existing revision 1, a required `requires.api_revision: 1` and optional exact Analysis and Observation requirements. Reinstall tools registered under earlier formats. The existing Tool subcommands and external dispatch suffice for this workflow. + Required fields and strict validation reject retired input at the existing + format identifier. This change introduces no new numeric protocol versions. - Keep the three current extension descriptors. Callable exports, resource rights and foreign interpreter selection have independent validation and lifecycles. Share value encoding and equivalent process transport diff --git a/examples/tool-samples/sample-knowledge/tool.json b/examples/tool-samples/sample-knowledge/tool.json index 8f9af9a..0be35cd 100644 --- a/examples/tool-samples/sample-knowledge/tool.json +++ b/examples/tool-samples/sample-knowledge/tool.json @@ -5,9 +5,9 @@ "version": "0.1.0", "command": "sample-knowledge", "entrypoint": "bin/sample-knowledge", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2], - "trace": [2] + "requires": { + "api_revision": 1, + "analysis": 3, + "observation": 1 } } diff --git a/examples/tool-samples/sample-proof/tool.json b/examples/tool-samples/sample-proof/tool.json index cbe2533..2a2ec51 100644 --- a/examples/tool-samples/sample-proof/tool.json +++ b/examples/tool-samples/sample-proof/tool.json @@ -5,9 +5,9 @@ "version": "0.1.0", "command": "sample-proof", "entrypoint": "bin/sample-proof", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2], - "trace": [2] + "requires": { + "api_revision": 1, + "analysis": 3, + "observation": 1 } } diff --git a/examples/tool-samples/sample-view/src/main.rs b/examples/tool-samples/sample-view/src/main.rs index 6f18309..6cd830f 100644 --- a/examples/tool-samples/sample-view/src/main.rs +++ b/examples/tool-samples/sample-view/src/main.rs @@ -48,7 +48,7 @@ fn main() { std::process::exit(1); } let version = number_field(&json, "schema_version").unwrap_or_default(); - if version != 2 { + if version != 3 { eprintln!("sample-view: unsupported Analysis version {version}"); std::process::exit(1); } diff --git a/examples/tool-samples/sample-view/tool.json b/examples/tool-samples/sample-view/tool.json index 8f5e91a..e7134d0 100644 --- a/examples/tool-samples/sample-view/tool.json +++ b/examples/tool-samples/sample-view/tool.json @@ -5,9 +5,8 @@ "version": "0.1.0", "command": "sample-view", "entrypoint": "bin/sample-view", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2], - "trace": [2] + "requires": { + "api_revision": 1, + "analysis": 3 } } diff --git a/examples/tool-unknown-name/README.md b/examples/tool-unknown-name/README.md index 99147e7..b688668 100644 --- a/examples/tool-unknown-name/README.md +++ b/examples/tool-unknown-name/README.md @@ -12,7 +12,7 @@ marqdo tool remove benchmark ``` The executable receives the remaining arguments verbatim, inherits stdio/cwd, -and its exit code is propagated. `MARQDO_TOOL_PROTOCOL=1` and `MARQDO_BIN` are +and its exit code is propagated. `MARQDO_API_REVISION=1` and `MARQDO_BIN` are provided for tools that need `check --emit`/`run --trace-file`. A Tool is a user-run native process. It is **not** a C ABI plugin, a foreign diff --git a/examples/tool-unknown-name/bin/marqdo-benchmark b/examples/tool-unknown-name/bin/marqdo-benchmark index ce08edc..9be771e 100755 --- a/examples/tool-unknown-name/bin/marqdo-benchmark +++ b/examples/tool-unknown-name/bin/marqdo-benchmark @@ -1,7 +1,7 @@ #!/bin/sh # A deliberately tool-specific program: the Marqdo CLI knows no `benchmark` # command or its options. -printf 'benchmark tool: protocol=%s\n' "${MARQDO_TOOL_PROTOCOL:-unset}" +printf 'benchmark tool: protocol=%s\n' "${MARQDO_API_REVISION:-unset}" for argument in "$@"; do printf 'arg=%s\n' "$argument" done diff --git a/examples/tool-unknown-name/tool.json b/examples/tool-unknown-name/tool.json index 1080666..007e921 100644 --- a/examples/tool-unknown-name/tool.json +++ b/examples/tool-unknown-name/tool.json @@ -5,7 +5,7 @@ "version": "0.1.0", "command": "benchmark", "entrypoint": "bin/marqdo-benchmark", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0" + "requires": { + "api_revision": 1 } } diff --git a/spec/cli-tool.md b/spec/cli-tool.md new file mode 100644 index 0000000..2f6e729 --- /dev/null +++ b/spec/cli-tool.md @@ -0,0 +1,43 @@ +# Marqdo CLI Tool + +A CLI Tool is an independent executable registered as a Marqdo subcommand. +It uses public CLI commands and runs with the invoking user's OS permissions. +Plugin trust, Provider grants, Foreign grants and the language sandbox apply +only at their own boundaries. + +## Manifest + +Put `tool.json` alongside the package's executable and support files. + +```json +{ + "schema": "marqdo.cli-tool", + "schema_version": 1, + "name": "demo.viewer", + "version": "0.3.0", + "command": "demo-view", + "entrypoint": "bin/demo-view", + "requires": {"api_revision": 1, "analysis": 3, "observation": 1} +} +``` + +The [manifest schema](schemas/cli-tool.schema.json) is authoritative. +`version` identifies the tool package and uses SemVer. `api_revision` is +required. Declare `analysis` and `observation` only when the tool consumes +those contracts. Every declared requirement is a single exact integer. + +## Install and run + +Use `marqdo tool install PATH`, `marqdo tool list` and +`marqdo tool remove COMMAND`. Run this sample as `marqdo demo-view ...`. +Commands must match `^[a-z][a-z0-9-]*$` and be available. The entrypoint +must be an executable regular file within the bundle. Symlinks, special +files and root `record.json` are rejected. The CLI verifies and installs +the entire bundle atomically, then checks the installed file set and +SHA-256 digests before execution. + +The process inherits standard streams and receives the original arguments, +`MARQDO_BIN` and `MARQDO_API_REVISION`. Tool discovery is explicit through +the install directory, which may be set with `MARQDO_TOOL_HOME`. +To replace a retired registration, remove its command, rebuild the tool +with this manifest and install the rebuilt bundle. diff --git a/spec/schemas/tool-v1.schema.json b/spec/schemas/cli-tool.schema.json similarity index 59% rename from spec/schemas/tool-v1.schema.json rename to spec/schemas/cli-tool.schema.json index e8d1be4..6c7ae9e 100644 --- a/spec/schemas/tool-v1.schema.json +++ b/spec/schemas/cli-tool.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://marqdo.dev/schemas/tool-v1.schema.json", - "title": "Marqdo CLI Tool Manifest v1", + "$id": "https://marqdo.dev/schemas/cli-tool.schema.json", + "title": "Marqdo CLI Tool Manifest", "type": "object", "required": [ "schema", @@ -9,7 +9,8 @@ "name", "version", "command", - "entrypoint" + "entrypoint", + "requires" ], "properties": { "schema": { @@ -35,31 +36,24 @@ "minLength": 1, "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$)).+$" }, - "compatibility": { + "requires": { "type": "object", + "required": [ + "api_revision" + ], + "additionalProperties": false, "properties": { - "marqdo": { - "type": "string" + "api_revision": { + "const": 1 }, "analysis": { - "type": "array", - "minItems": 1, - "items": { - "type": "integer", - "minimum": 1 - } + "const": 3 }, - "trace": { - "type": "array", - "minItems": 1, - "items": { - "type": "integer", - "minimum": 1 - } + "observation": { + "const": 1 } - }, - "additionalProperties": true + } } }, - "additionalProperties": true + "additionalProperties": false } diff --git a/spec/tool-v1.md b/spec/tool-v1.md deleted file mode 100644 index 4a7967b..0000000 --- a/spec/tool-v1.md +++ /dev/null @@ -1,89 +0,0 @@ -# Marqdo CLI Tool Protocol v1 — 通用外部工具协议 - -> 状态:**Implemented / frozen protocol v1**(独立于产品版本)。核心根命令同样优先;任何官方/第三方工具一视同仁;该协议**不是** C ABI 插件协议。安装、校验、分发与协议协商均已实现并由 `crates/cli/tests/tool_protocol.rs` 覆盖。 - -## 1. 范围与不变量 - -- Core 不含具体 Tool `command` 名的注册、适配、白名单、下载地址;仅维护自身原生命令集合与用户安装的工具注册记录。 -- 任何语言写成的**独立可执行工具**均可安装;CLI 不链接其 Rust crate、不解释其业务子命令。 -- 最小实现只支持 `marqdo tool install /path/to/tool.json`、`marqdo tool list`、`marqdo tool remove `,以及未知顶层命令的已注册工具回退。 -- 无索引服务、无网络时一样能够本地安装;`marqdo tool install ` 的远程名称解析是以后独立的可选索引能力,不要求 core 自带官方/社区工具列表。 -- 工具仅能调用公开的 `marqdo` 命令/Analysis/Trace 文件协议;不得依赖私有 `marqdo-ir` 序列化、宿主内存指针或“已知官方工具名”。 - -## 2. 安装清单 - -`tool.json` 使用 UTF-8 JSON,v1 的最小规范清单示例: - -```json -{ - "schema": "marqdo.cli-tool", - "schema_version": 1, - "name": "benchmark", - "version": "0.1.0", - "command": "benchmark", - "entrypoint": "bin/marqdo-benchmark", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2] - } -} -``` - -类型:`schema` 固定字符串,`schema_version` 正整数(首版仅 1),`name`/`version`/`command`/`entrypoint` 非空字符串,`version` 必须是合法 SemVer,`compatibility.marqdo` 必须是可解析的 SemVer 范围,`analysis`、`trace` 为可选的非空正整数数组;仅当工具使用该数据协议时声明。当前开发分支提供 Analysis v2/v3 与 Trace v2。声明与对应版本集合无交集时,安装和分发会拒绝。未来可以增加可选字段,但不得改变现有字段含义。 - -`command`:建议 `^[a-z][a-z0-9-]*$`,不得与任何内置命令或保留参数冲突;同一注册表中命令唯一,名字冲突拒绝且不覆盖。`entrypoint`:包内受控相对路径,不能是绝对路径、`.`/`..` 跳出根目录、符号链接逃逸或可直接解释的任意 shell 片段。真实文件应可执行并与目标平台匹配;若扩展名或平台格式与 OS 不兼容应显式失败。 - -## 3. 注册与验证 - -本地安装流程:读取用户指定的 `tool.json` → 校验 schema、SemVer 与协议交集 → 校验 entrypoint 不越界 → 检查内置/已注册命令冲突 → 收集**整包**规范化文件清单(相对路径、大小、SHA-256,拒绝符号链接/特殊文件/非 UTF-8 路径,限制文件数与总字节)→ 以临时目录按同一清单复制 → 对 staging 重新计算清单并要求逐项一致 → 写入记录并原子 rename 发布。失败时清理 staging,不留下半安装。 - -注册记录(`record_version: 2`)包含 `command`、`name`、`version`、`entrypoint`(包内相对路径)、`bundle[]`(每文件 path/size/sha256)、`bundle_sha256`、`source`、`schema_version`、`compatibility`。`bundle_sha256` 是排序后 `path\0size\0sha256\n` 的 SHA-256。注册不是来源认证;摘要只能检查安装后未被改变。对互联网下载必须额外有可信索引给出的摘要/签名;禁止在用户未同意前自动从网络下载。 - -运行时在启动前重新计算磁盘上的整包清单,与记录逐项比较(排除根 `record.json`),并验证 entrypoint 属于该清单、记录命令与请求命令一致、版本/协议仍兼容。任何不一致拒绝而非降低校验强度。旧记录版本不复用,提示重新安装。实现优先使用正确的跨平台配置目录 API,不要把 `~` 当成可移植的用户目录。多个用户/多个版本并存属于独立目录隔离;同一个命令只能解析到一个注册项,除非未来另有显式版本选择规范。 - -## 4. 分发算法 - -输入 `marqdo `,先检查内置命令,内置优先;否则从已安装的只读注册映射查找 ``。找到则重新协商 Tool/分析/追踪协议,验证整包清单与 entrypoint,使用 `Command::new(entrypoint).args(args)` **直接启动**,从调用者原样保留 `cwd`、`stdin/stdout/stderr` 和可保留的环境(敏感环境变量策略另行安全审计),原样传播退出状态;绝不调用 `sh -c`、不拼接命令字符串。 - -工具负责自己的命令层级与帮助,如 `marqdo benchmark run .`、`marqdo benchmark --help`。CLI 不读取或修改工具业务选项。Rust `clap` 可通过单一 `external_subcommand` 捕获未知子命令,但必须保留 `OsString` 原样传参;不能让工具要求 CLI 添加 `Command::View` 等专门枚举项。不要求工具在处理 `--help` 时调用核心。未知命令时报错;即使 PATH 中存在 `marqdo-`,**没有显式注册也不能执行它**。 - -可选辅助环境:`MARQDO_BIN`(当前核心 CLI 的绝对路径),`MARQDO_TOOL_PROTOCOL=1`;仅当工具声明并协商了对应协议时,额外设置 `MARQDO_PROTOCOL_ANALYSIS` 与/或 `MARQDO_PROTOCOL_TRACE`,值是双方支持的最高版本。 -Analysis 写入器按项目内容选择版本。工具应先检查输出的 `schema_version`,支持两版的工具声明 `analysis: [2, 3]`。工具通过此路径运行 `marqdo check ... --emit ...` 和 `marqdo run ... --trace-file ...`,不拥有额外宿主内部 API。不得自动将密钥、项目能力授予记录、ABI 插件加载句柄或用户外联会话传给工具。 - -## 5. 三个独立安全域 - -1. **Tool CLI 进程**:用户主动安装并运行的原生程序,按当前用户身份执行。它**不受** Marqdo 的 `pure/project/strict` `.mq.md` 语言沙箱自动约束;工具执行不是安装后自动执行。 -2. **Marqdo 程序**:通过 `marqdo run/call` 和 `CapabilityHost` 执行,严格隔离需受支持的 OS adapter。 -3. **运行时 ABI 插件**:扩展可调用函数,必须有自己版本化 C ABI、显式信任或 isolated worker,和 Tool 注册表严格区分。 - -## 6. 向后兼容 - -`schema_version` 不支持、`marqdo` 范围不匹配、工具版本不是合法 SemVer,或声明的 Analysis/Trace 列表与核心支持集(当前 `analysis: [2, 3]`、`trace: [2]`)无交集时,安装与分发都必须以稳定错误拒绝;错误信息包含 `tool.protocol_incompatible`。可忽略的未知扩展字段允许透传,但不能被视为隐含授权。没有声明数据协议的工具不受该检查约束,也不会收到协议环境变量。 - -原生命令集合是保留命名空间;未来新增与社区工具冲突的新核心顶层命令属于破坏性变化,必须经过 ADR、迁移期诊断和工具冲突统计,不能静默覆盖已有已注册工具。 - -## 7. 正反向黑盒测试(完成标准) - -| 用例 | 期望 | -|---|---| -| `tool install` 本地清单 `benchmark` 后调用 `marqdo benchmark run .` | 无需 CLI 源码改动,可原样传参并传播退出码 | -| 将工具名改成 `lintx`,重建外部程序但不重建 CLI | 能直接注册和调用 | -| 工具没有 `analysis/trace` 兼容字段 | 可以独立使用;不强制创建分析或运行记录 | -| 工具声明 `analysis:[2]`/`trace:[2]` | 安装并分发,环境变量反映协商结果 | -| 工具声明 `analysis:[1]`、`[]` 或与支持集无交集 | 安装/分发拒绝,错误含 `tool.protocol_incompatible`,不回退猜测 | -| 工具注册名冲突 `run` 或另一已安装工具 | 拒绝,不覆盖 | -| PATH 中存在同名 `marqdo-benchmark` 但未注册 | 未知命令错误,不执行 PATH 程序 | -| 篡改已安装二进制的一个字节 | 拒绝启动,指明整包摘要不匹配 | -| 仅篡改辅助脚本、增加未列文件或删除文件 | 拒绝启动,整包清单不一致 | -| 源包包含根 `record.json` | 安装拒绝(记录文件由核心保留) | -| `entrypoint` 是 `../outside`、绝对路径或越界符号链接 | 安装失败,无残留注册 | -| 安装时被杀/写盘失败/并发安装 | 不留下半安装或不一致的注册 | -| `marqdo tool remove benchmark` | 注册与受控安装制品删除;其他工具正常 | -| `--help`、复杂 Unicode 参数和 stdin/stdout | 工具获得原样参数/流,核心不解释私有业务语义 | - -验收同时要求 `marqdo-cli` **不包含** `view/knowledge/prove/benchmark` 的特殊分发匹配、下载 URL、业务参数类型及平台分支。把测试工具迁移至新的仓库,并在不同机器上单独编译安装后仍可通过本协议。 - -## 8. 参考 - -- Cargo External Tools: https://doc.rust-lang.org/cargo/reference/external-tools.html —— 可扩展子命令而无需修改核心。 -- kubectl plugins: https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/ —— 独立可执行文件、自动分发的经验;其默认 PATH 信任模型不直接沿用。 diff --git a/tests/consumers/validate_protocols.py b/tests/consumers/validate_protocols.py index b0d0cd9..c5c0ab7 100644 --- a/tests/consumers/validate_protocols.py +++ b/tests/consumers/validate_protocols.py @@ -51,7 +51,7 @@ def main(): analysis_schema = "analysis.schema.json" require_valid(analysis_schema, analysis, "analysis") require_valid("trace-v2.schema.json", trace, "trace") - require_valid("tool-v1.schema.json", tool, "tool") + require_valid("cli-tool.schema.json", tool, "tool") # Negative mutations: structure, version and traversal must fail closed. bad = copy.deepcopy(analysis) @@ -76,11 +76,11 @@ def main(): bad = copy.deepcopy(tool) bad["entrypoint"] = "../outside" - require_invalid("tool-v1.schema.json", bad, "tool traversal entrypoint") + require_invalid("cli-tool.schema.json", bad, "tool traversal entrypoint") bad = copy.deepcopy(tool) bad["version"] = "not semver" - require_invalid("tool-v1.schema.json", bad, "tool invalid version") + require_invalid("cli-tool.schema.json", bad, "tool invalid version") print( "validated analysis/trace/tool artifacts " diff --git a/tests/fixtures/tool_echo.rs b/tests/fixtures/tool_echo.rs index 35e4dcc..2d20cf1 100644 --- a/tests/fixtures/tool_echo.rs +++ b/tests/fixtures/tool_echo.rs @@ -13,14 +13,8 @@ fn main() { } println!( "protocol={}", - std::env::var("MARQDO_TOOL_PROTOCOL").unwrap_or_default() + std::env::var("MARQDO_API_REVISION").unwrap_or_default() ); - if let Ok(value) = std::env::var("MARQDO_PROTOCOL_ANALYSIS") { - println!("analysis={value}"); - } - if let Ok(value) = std::env::var("MARQDO_PROTOCOL_TRACE") { - println!("trace={value}"); - } let mut stdin = String::new(); let _ = std::io::stdin().read_to_string(&mut stdin); if !stdin.is_empty() {