tool: require exact current contracts without negotiation
This commit is contained in:
1 parent
8bfe0c36ee
commit
f83d992c61
16 files changed
+229
-366
No files matched your search
+89
-134
@@ -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
|
//! The core never knows a tool's name. It validates a user-supplied
|
||||||
//! `tool.json`, verifies protocol compatibility, copies the whole bundle into a
|
//! `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::path::{Component, Path, PathBuf};
|
||||||
use std::process::Command as ProcessCommand;
|
use std::process::Command as ProcessCommand;
|
||||||
|
|
||||||
use semver::{Version, VersionReq};
|
use semver::Version;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
@@ -21,19 +21,7 @@ const RECORD_VERSION: u32 = 2;
|
|||||||
const MAX_BUNDLE_FILES: usize = 4096;
|
const MAX_BUNDLE_FILES: usize = 4096;
|
||||||
const MAX_BUNDLE_BYTES: u64 = 256 * 1024 * 1024;
|
const MAX_BUNDLE_BYTES: u64 = 256 * 1024 * 1024;
|
||||||
|
|
||||||
/// Protocols this core can provide to tools.
|
const API_REVISION: u32 = 1;
|
||||||
#[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 BUILTIN_COMMANDS: &[&str] = &[
|
const BUILTIN_COMMANDS: &[&str] = &[
|
||||||
"init", "run", "call", "check", "inspect", "fmt", "plugin", "add", "remove", "lock", "sync",
|
"init", "run", "call", "check", "inspect", "fmt", "plugin", "add", "remove", "lock", "sync",
|
||||||
@@ -41,6 +29,7 @@ const BUILTIN_COMMANDS: &[&str] = &[
|
|||||||
];
|
];
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
struct ToolManifest {
|
struct ToolManifest {
|
||||||
schema: String,
|
schema: String,
|
||||||
schema_version: u32,
|
schema_version: u32,
|
||||||
@@ -48,38 +37,29 @@ struct ToolManifest {
|
|||||||
version: String,
|
version: String,
|
||||||
command: String,
|
command: String,
|
||||||
entrypoint: PathBuf,
|
entrypoint: PathBuf,
|
||||||
#[serde(default)]
|
requires: Requirements,
|
||||||
compatibility: Compatibility,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
struct Compatibility {
|
#[serde(deny_unknown_fields)]
|
||||||
#[serde(default)]
|
struct Requirements {
|
||||||
marqdo: Option<String>,
|
api_revision: u32,
|
||||||
#[serde(default)]
|
#[serde(
|
||||||
analysis: Option<Vec<u32>>,
|
default,
|
||||||
#[serde(default)]
|
skip_serializing_if = "Option::is_none",
|
||||||
trace: Option<Vec<u32>>,
|
deserialize_with = "read_requirement"
|
||||||
|
)]
|
||||||
|
analysis: Option<u32>,
|
||||||
|
#[serde(
|
||||||
|
default,
|
||||||
|
skip_serializing_if = "Option::is_none",
|
||||||
|
deserialize_with = "read_requirement"
|
||||||
|
)]
|
||||||
|
observation: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
fn read_requirement<'de, D: serde::Deserializer<'de>>(reader: D) -> Result<Option<u32>, D::Error> {
|
||||||
struct RecordedCompatibility {
|
u32::deserialize(reader).map(Some)
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
marqdo: Option<String>,
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
analysis: Option<Vec<u32>>,
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
trace: Option<Vec<u32>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RecordedCompatibility {
|
|
||||||
fn as_compatibility(&self) -> Compatibility {
|
|
||||||
Compatibility {
|
|
||||||
marqdo: self.marqdo.clone(),
|
|
||||||
analysis: self.analysis.clone(),
|
|
||||||
trace: self.trace.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
@@ -90,6 +70,7 @@ struct BundleEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
struct ToolRecord {
|
struct ToolRecord {
|
||||||
record_version: u32,
|
record_version: u32,
|
||||||
command: String,
|
command: String,
|
||||||
@@ -100,8 +81,7 @@ struct ToolRecord {
|
|||||||
bundle_sha256: String,
|
bundle_sha256: String,
|
||||||
source: String,
|
source: String,
|
||||||
schema_version: u32,
|
schema_version: u32,
|
||||||
#[serde(default)]
|
requires: Requirements,
|
||||||
compatibility: RecordedCompatibility,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `marqdo tool install <manifest-or-directory>`.
|
/// `marqdo tool install <manifest-or-directory>`.
|
||||||
@@ -201,11 +181,7 @@ fn install_inner(manifest_path: &Path) -> Result<ToolRecord, String> {
|
|||||||
bundle_sha256: bundle_sha256.clone(),
|
bundle_sha256: bundle_sha256.clone(),
|
||||||
source: manifest_file.display().to_string(),
|
source: manifest_file.display().to_string(),
|
||||||
schema_version: manifest.schema_version,
|
schema_version: manifest.schema_version,
|
||||||
compatibility: RecordedCompatibility {
|
requires: manifest.requires.clone(),
|
||||||
marqdo: manifest.compatibility.marqdo.clone(),
|
|
||||||
analysis: manifest.compatibility.analysis.clone(),
|
|
||||||
trace: manifest.compatibility.trace.clone(),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
let record_json = serde_json::to_string_pretty(&record)
|
let record_json = serde_json::to_string_pretty(&record)
|
||||||
.map_err(|error| format!("cannot serialize record: {error}"))?;
|
.map_err(|error| format!("cannot serialize record: {error}"))?;
|
||||||
@@ -226,7 +202,7 @@ impl ToolManifest {
|
|||||||
let text = std::fs::read_to_string(path)
|
let text = std::fs::read_to_string(path)
|
||||||
.map_err(|error| format!("cannot read `{}`: {error}", path.display()))?;
|
.map_err(|error| format!("cannot read `{}`: {error}", path.display()))?;
|
||||||
let manifest: Self =
|
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)
|
Ok(manifest)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -235,10 +211,10 @@ fn validate_manifest(manifest: &ToolManifest) -> Result<(), String> {
|
|||||||
if manifest.schema != SCHEMA {
|
if manifest.schema != SCHEMA {
|
||||||
return Err(format!("unsupported tool schema `{}`", manifest.schema));
|
return Err(format!("unsupported tool schema `{}`", manifest.schema));
|
||||||
}
|
}
|
||||||
if manifest.schema_version != SUPPORTED.tool {
|
if manifest.schema_version != PROTOCOL_VERSION {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"unsupported tool schema_version {} (expected {})",
|
"unsupported tool schema_version {} (expected {})",
|
||||||
manifest.schema_version, SUPPORTED.tool
|
manifest.schema_version, PROTOCOL_VERSION
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if !is_valid_command(&manifest.command) {
|
if !is_valid_command(&manifest.command) {
|
||||||
@@ -262,57 +238,34 @@ fn validate_manifest(manifest: &ToolManifest) -> Result<(), String> {
|
|||||||
manifest.version
|
manifest.version
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
negotiate(&manifest.version, &manifest.compatibility)
|
validate_requirements(&manifest.requires)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn negotiate(tool_version: &str, compatibility: &Compatibility) -> Result<(), String> {
|
fn validate_requirements(requires: &Requirements) -> Result<(), String> {
|
||||||
Version::parse(tool_version)
|
for (name, requested, current) in [
|
||||||
.map_err(|error| format!("tool version `{tool_version}` is not valid SemVer: {error}"))?;
|
("api_revision", Some(requires.api_revision), API_REVISION),
|
||||||
let core_version = Version::parse(env!("CARGO_PKG_VERSION"))
|
(
|
||||||
.map_err(|error| format!("core version is not valid SemVer: {error}"))?;
|
"analysis",
|
||||||
if let Some(range) = &compatibility.marqdo {
|
requires.analysis,
|
||||||
let requirement = VersionReq::parse(range)
|
crate::analysis::SCHEMA_VERSION,
|
||||||
.map_err(|error| format!("invalid marqdo compatibility range `{range}`: {error}"))?;
|
),
|
||||||
if !requirement.matches(&core_version) {
|
(
|
||||||
return Err(format!(
|
"observation",
|
||||||
"tool requires marqdo `{range}`, this core is {}",
|
requires.observation,
|
||||||
env!("CARGO_PKG_VERSION")
|
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(())
|
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<u32> {
|
|
||||||
requested
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.filter(|version| supported.contains(version))
|
|
||||||
.max()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_valid_command(command: &str) -> bool {
|
fn is_valid_command(command: &str) -> bool {
|
||||||
let mut bytes = command.bytes();
|
let mut bytes = command.bytes();
|
||||||
matches!(bytes.next(), Some(byte) if byte.is_ascii_lowercase())
|
matches!(bytes.next(), Some(byte) if byte.is_ascii_lowercase())
|
||||||
@@ -483,7 +436,7 @@ pub fn list(json: bool) -> i32 {
|
|||||||
"name": record.name,
|
"name": record.name,
|
||||||
"version": record.version,
|
"version": record.version,
|
||||||
"bundle_files": record.bundle.len(),
|
"bundle_files": record.bundle.len(),
|
||||||
"compatibility": record.compatibility,
|
"requires": record.requires,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -568,8 +521,8 @@ pub fn dispatch(args: &[OsString]) -> i32 {
|
|||||||
return 2;
|
return 2;
|
||||||
};
|
};
|
||||||
let command = first.to_string_lossy();
|
let command = first.to_string_lossy();
|
||||||
if BUILTIN_COMMANDS.contains(&command.as_ref()) {
|
if !is_valid_command(&command) || BUILTIN_COMMANDS.contains(&command.as_ref()) {
|
||||||
eprintln!("error: internal dispatch error for built-in command `{command}`");
|
eprintln!("error: invalid external command `{command}`");
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
let home = match tool_home() {
|
let home = match tool_home() {
|
||||||
@@ -582,6 +535,10 @@ pub fn dispatch(args: &[OsString]) -> i32 {
|
|||||||
let dir = home.join(command.as_ref());
|
let dir = home.join(command.as_ref());
|
||||||
let record = match load_record(&dir) {
|
let record = match load_record(&dir) {
|
||||||
Ok(record) => record,
|
Ok(record) => record,
|
||||||
|
Err(error) if dir.exists() => {
|
||||||
|
eprintln!("error: tool `{command}`: {error}");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"error: unknown command `{command}`; install a tool with `marqdo tool install <tool.json>`"
|
"error: unknown command `{command}`; install a tool with `marqdo tool install <tool.json>`"
|
||||||
@@ -593,14 +550,6 @@ pub fn dispatch(args: &[OsString]) -> i32 {
|
|||||||
eprintln!("error: tool record does not match command `{command}`; reinstall it");
|
eprintln!("error: tool record does not match command `{command}`; reinstall it");
|
||||||
return 1;
|
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) {
|
let bundle = match collect_bundle(&dir, true) {
|
||||||
Ok(bundle) => bundle,
|
Ok(bundle) => bundle,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
@@ -627,26 +576,16 @@ pub fn dispatch(args: &[OsString]) -> i32 {
|
|||||||
};
|
};
|
||||||
let mut process = ProcessCommand::new(&entrypoint);
|
let mut process = ProcessCommand::new(&entrypoint);
|
||||||
process.args(&args[1..]);
|
process.args(&args[1..]);
|
||||||
if let Ok(bin) = std::env::current_exe() {
|
match std::env::current_exe() {
|
||||||
process.env("MARQDO_BIN", bin);
|
Ok(bin) => {
|
||||||
}
|
process.env("MARQDO_BIN", bin);
|
||||||
process.env("MARQDO_TOOL_PROTOCOL", "1");
|
}
|
||||||
if let Some(version) = record
|
Err(error) => {
|
||||||
.compatibility
|
eprintln!("error: cannot locate marqdo for tool `{command}`: {error}");
|
||||||
.analysis
|
return 1;
|
||||||
.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());
|
|
||||||
}
|
}
|
||||||
|
process.env("MARQDO_API_REVISION", API_REVISION.to_string());
|
||||||
match process.status() {
|
match process.status() {
|
||||||
Ok(status) => status.code().unwrap_or(1),
|
Ok(status) => status.code().unwrap_or(1),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
@@ -690,7 +629,10 @@ fn installed_records() -> Result<Vec<ToolRecord>, String> {
|
|||||||
if entry.file_name().to_string_lossy().starts_with('.') {
|
if entry.file_name().to_string_lossy().starts_with('.') {
|
||||||
continue;
|
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);
|
records.insert(record.command.clone(), record);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -698,13 +640,26 @@ fn installed_records() -> Result<Vec<ToolRecord>, String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn load_record(dir: &Path) -> Result<ToolRecord, String> {
|
fn load_record(dir: &Path) -> Result<ToolRecord, String> {
|
||||||
let text = std::fs::read_to_string(dir.join("record.json"))
|
let record_path = dir.join("record.json");
|
||||||
.map_err(|error| format!("tool record is missing: {error}"))?;
|
let inspect = |path| {
|
||||||
let record: ToolRecord =
|
std::fs::symlink_metadata(path)
|
||||||
serde_json::from_str(&text).map_err(|error| format!("invalid tool record: {error}"))?;
|
.map_err(|error| format!("cannot inspect tool registration: {error}"))
|
||||||
if record.record_version != RECORD_VERSION {
|
};
|
||||||
return Err("tool record is from an older protocol; reinstall it".to_string());
|
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)
|
Ok(record)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -133,7 +133,7 @@ fn unknown_tool_name_installs_and_dispatches() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn public_schemas_are_valid_json_and_versioned() {
|
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()
|
let path = repo()
|
||||||
.join("spec/schemas")
|
.join("spec/schemas")
|
||||||
.join(format!("{name}.schema.json"));
|
.join(format!("{name}.schema.json"));
|
||||||
|
|||||||
@@ -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`
|
//! 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.
|
//! 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(
|
std::fs::write(
|
||||||
&manifest,
|
&manifest,
|
||||||
format!(
|
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();
|
.unwrap();
|
||||||
@@ -120,7 +120,7 @@ fn repo_root() -> PathBuf {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Compile one of the checked-in independent consumer samples and package it
|
/// 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.
|
/// they are reviewable software, not hidden test strings.
|
||||||
fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf {
|
fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf {
|
||||||
let root = repo_root();
|
let root = repo_root();
|
||||||
@@ -142,7 +142,7 @@ fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf {
|
|||||||
std::fs::write(
|
std::fs::write(
|
||||||
&manifest,
|
&manifest,
|
||||||
format!(
|
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();
|
.unwrap();
|
||||||
@@ -200,7 +200,7 @@ fn independent_sample_tools_consume_public_analysis_and_trace() {
|
|||||||
assert_eq!(view.status.code(), Some(0), "{}", stderr(&view));
|
assert_eq!(view.status.code(), Some(0), "{}", stderr(&view));
|
||||||
let text = stdout(&view);
|
let text = stdout(&view);
|
||||||
assert!(
|
assert!(
|
||||||
text.contains("sample-view schema=marqdo.analysis version=2"),
|
text.contains("sample-view schema=marqdo.analysis version=3"),
|
||||||
"{text}"
|
"{text}"
|
||||||
);
|
);
|
||||||
assert!(text.contains("modules="), "{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(
|
let manifest = write_tool(
|
||||||
dir.path(),
|
dir.path(),
|
||||||
"benchmark",
|
"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()]);
|
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)
|
let incompatible = std::fs::read_to_string(&manifest)
|
||||||
.unwrap()
|
.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");
|
let incompatible_manifest = dir.path().join("incompatible.json");
|
||||||
std::fs::write(&incompatible_manifest, incompatible).unwrap();
|
std::fs::write(&incompatible_manifest, incompatible).unwrap();
|
||||||
let output = cli(
|
let output = cli(
|
||||||
@@ -309,7 +309,7 @@ fn invalid_manifests_and_path_escapes_are_rejected() {
|
|||||||
&["tool", "install", incompatible_manifest.to_str().unwrap()],
|
&["tool", "install", incompatible_manifest.to_str().unwrap()],
|
||||||
);
|
);
|
||||||
assert_eq!(output.status.code(), Some(1));
|
assert_eq!(output.status.code(), Some(1));
|
||||||
assert!(stderr(&output).contains("requires marqdo"));
|
assert!(stderr(&output).contains("requires api_revision"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -355,58 +355,61 @@ fn tampered_binary_and_path_hijack_are_not_executed() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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 dir = TempDir::new("protocols");
|
||||||
let home = dir.path().join("home");
|
let home = dir.path().join("home");
|
||||||
let manifest = write_tool(
|
let manifest = write_tool(dir.path(), "proto", "");
|
||||||
dir.path(),
|
let mut document: serde_json::Value =
|
||||||
"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 =
|
|
||||||
serde_json::from_slice(&std::fs::read(&manifest).unwrap()).unwrap();
|
serde_json::from_slice(&std::fs::read(&manifest).unwrap()).unwrap();
|
||||||
declared["compatibility"]["analysis"] = serde_json::json!([2, 3]);
|
for (requires, expected) in [
|
||||||
std::fs::write(&manifest, declared.to_string()).unwrap();
|
(
|
||||||
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
|
json!({"api_revision": 1, "analysis": [3]}),
|
||||||
assert_eq!(install.status.code(), Some(0), "{}", stderr(&install));
|
"invalid tool.json",
|
||||||
let output = cli(&home, &["proto-v3"]);
|
),
|
||||||
assert_eq!(output.status.code(), Some(7), "{}", stderr(&output));
|
(
|
||||||
assert!(stdout(&output).contains("analysis=3"));
|
json!({"api_revision": 1, "analysis": null}),
|
||||||
|
"invalid tool.json",
|
||||||
for (compat, tag) in [
|
),
|
||||||
("\"analysis\":[99]", "analysis-disjoint"),
|
(
|
||||||
("\"analysis\":[]", "analysis-empty"),
|
json!({"api_revision": 1, "analysis": 2}),
|
||||||
("\"trace\":[9]", "trace-disjoint"),
|
"tool.protocol_incompatible",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"api_revision": 1, "observation": 99}),
|
||||||
|
"tool.protocol_incompatible",
|
||||||
|
),
|
||||||
] {
|
] {
|
||||||
let command = format!("bad-{tag}");
|
document["requires"] = requires;
|
||||||
let manifest = write_tool(dir.path(), &command, "#!/bin/sh\nexit 0\n");
|
std::fs::write(&manifest, document.to_string()).unwrap();
|
||||||
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();
|
|
||||||
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
|
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
|
||||||
assert_eq!(output.status.code(), Some(1), "{tag}");
|
assert_eq!(output.status.code(), Some(1));
|
||||||
assert!(
|
assert!(stderr(&output).contains(expected), "{}", stderr(&output));
|
||||||
stderr(&output).contains("protocol_incompatible"),
|
|
||||||
"{tag}: {}",
|
|
||||||
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]
|
#[test]
|
||||||
@@ -460,41 +463,3 @@ fn a_root_record_json_in_the_source_package_is_rejected() {
|
|||||||
assert_eq!(output.status.code(), Some(1));
|
assert_eq!(output.status.code(), Some(1));
|
||||||
assert!(stderr(&output).contains("must not contain a root record.json"));
|
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)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -27,10 +27,12 @@ requires its own compatibility policy.
|
|||||||
`run` and `call` use `--output text|json|jsonl` and
|
`run` and `call` use `--output text|json|jsonl` and
|
||||||
`--observation-file PATH`. Capture selections and budgets apply to all
|
`--observation-file PATH`. Capture selections and budgets apply to all
|
||||||
observation destinations.
|
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
|
`requires.api_revision: 1` and optional exact Analysis and Observation
|
||||||
requirements. Reinstall tools registered under earlier formats. The
|
requirements. Reinstall tools registered under earlier formats. The
|
||||||
existing Tool subcommands and external dispatch suffice for this workflow.
|
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
|
- Keep the three current extension descriptors. Callable exports, resource
|
||||||
rights and foreign interpreter selection have independent validation and
|
rights and foreign interpreter selection have independent validation and
|
||||||
lifecycles. Share value encoding and equivalent process transport
|
lifecycles. Share value encoding and equivalent process transport
|
||||||
|
|||||||
@@ -5,9 +5,9 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"command": "sample-knowledge",
|
"command": "sample-knowledge",
|
||||||
"entrypoint": "bin/sample-knowledge",
|
"entrypoint": "bin/sample-knowledge",
|
||||||
"compatibility": {
|
"requires": {
|
||||||
"marqdo": ">=3.0.0-beta.1,<4.0.0",
|
"api_revision": 1,
|
||||||
"analysis": [2],
|
"analysis": 3,
|
||||||
"trace": [2]
|
"observation": 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,9 +5,9 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"command": "sample-proof",
|
"command": "sample-proof",
|
||||||
"entrypoint": "bin/sample-proof",
|
"entrypoint": "bin/sample-proof",
|
||||||
"compatibility": {
|
"requires": {
|
||||||
"marqdo": ">=3.0.0-beta.1,<4.0.0",
|
"api_revision": 1,
|
||||||
"analysis": [2],
|
"analysis": 3,
|
||||||
"trace": [2]
|
"observation": 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -48,7 +48,7 @@ fn main() {
|
|||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
let version = number_field(&json, "schema_version").unwrap_or_default();
|
let version = number_field(&json, "schema_version").unwrap_or_default();
|
||||||
if version != 2 {
|
if version != 3 {
|
||||||
eprintln!("sample-view: unsupported Analysis version {version}");
|
eprintln!("sample-view: unsupported Analysis version {version}");
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,9 +5,8 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"command": "sample-view",
|
"command": "sample-view",
|
||||||
"entrypoint": "bin/sample-view",
|
"entrypoint": "bin/sample-view",
|
||||||
"compatibility": {
|
"requires": {
|
||||||
"marqdo": ">=3.0.0-beta.1,<4.0.0",
|
"api_revision": 1,
|
||||||
"analysis": [2],
|
"analysis": 3
|
||||||
"trace": [2]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,7 +12,7 @@ marqdo tool remove benchmark
|
|||||||
```
|
```
|
||||||
|
|
||||||
The executable receives the remaining arguments verbatim, inherits stdio/cwd,
|
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`.
|
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
|
A Tool is a user-run native process. It is **not** a C ABI plugin, a foreign
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# A deliberately tool-specific program: the Marqdo CLI knows no `benchmark`
|
# A deliberately tool-specific program: the Marqdo CLI knows no `benchmark`
|
||||||
# command or its options.
|
# 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
|
for argument in "$@"; do
|
||||||
printf 'arg=%s\n' "$argument"
|
printf 'arg=%s\n' "$argument"
|
||||||
done
|
done
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"command": "benchmark",
|
"command": "benchmark",
|
||||||
"entrypoint": "bin/marqdo-benchmark",
|
"entrypoint": "bin/marqdo-benchmark",
|
||||||
"compatibility": {
|
"requires": {
|
||||||
"marqdo": ">=3.0.0-beta.1,<4.0.0"
|
"api_revision": 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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.
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://marqdo.dev/schemas/tool-v1.schema.json",
|
"$id": "https://marqdo.dev/schemas/cli-tool.schema.json",
|
||||||
"title": "Marqdo CLI Tool Manifest v1",
|
"title": "Marqdo CLI Tool Manifest",
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": [
|
"required": [
|
||||||
"schema",
|
"schema",
|
||||||
@@ -9,7 +9,8 @@
|
|||||||
"name",
|
"name",
|
||||||
"version",
|
"version",
|
||||||
"command",
|
"command",
|
||||||
"entrypoint"
|
"entrypoint",
|
||||||
|
"requires"
|
||||||
],
|
],
|
||||||
"properties": {
|
"properties": {
|
||||||
"schema": {
|
"schema": {
|
||||||
@@ -35,31 +36,24 @@
|
|||||||
"minLength": 1,
|
"minLength": 1,
|
||||||
"pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$)).+$"
|
"pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$)).+$"
|
||||||
},
|
},
|
||||||
"compatibility": {
|
"requires": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"api_revision"
|
||||||
|
],
|
||||||
|
"additionalProperties": false,
|
||||||
"properties": {
|
"properties": {
|
||||||
"marqdo": {
|
"api_revision": {
|
||||||
"type": "string"
|
"const": 1
|
||||||
},
|
},
|
||||||
"analysis": {
|
"analysis": {
|
||||||
"type": "array",
|
"const": 3
|
||||||
"minItems": 1,
|
|
||||||
"items": {
|
|
||||||
"type": "integer",
|
|
||||||
"minimum": 1
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"trace": {
|
"observation": {
|
||||||
"type": "array",
|
"const": 1
|
||||||
"minItems": 1,
|
|
||||||
"items": {
|
|
||||||
"type": "integer",
|
|
||||||
"minimum": 1
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
"additionalProperties": true
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"additionalProperties": true
|
"additionalProperties": false
|
||||||
}
|
}
|
||||||
@@ -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 <command>`,以及未知顶层命令的已注册工具回退。
|
|
||||||
- 无索引服务、无网络时一样能够本地安装;`marqdo tool install <name>` 的远程名称解析是以后独立的可选索引能力,不要求 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 <first> <args...>`,先检查内置命令,内置优先;否则从已安装的只读注册映射查找 `<first>`。找到则重新协商 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-<first>`,**没有显式注册也不能执行它**。
|
|
||||||
|
|
||||||
可选辅助环境:`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 信任模型不直接沿用。
|
|
||||||
@@ -51,7 +51,7 @@ def main():
|
|||||||
analysis_schema = "analysis.schema.json"
|
analysis_schema = "analysis.schema.json"
|
||||||
require_valid(analysis_schema, analysis, "analysis")
|
require_valid(analysis_schema, analysis, "analysis")
|
||||||
require_valid("trace-v2.schema.json", trace, "trace")
|
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.
|
# Negative mutations: structure, version and traversal must fail closed.
|
||||||
bad = copy.deepcopy(analysis)
|
bad = copy.deepcopy(analysis)
|
||||||
@@ -76,11 +76,11 @@ def main():
|
|||||||
|
|
||||||
bad = copy.deepcopy(tool)
|
bad = copy.deepcopy(tool)
|
||||||
bad["entrypoint"] = "../outside"
|
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 = copy.deepcopy(tool)
|
||||||
bad["version"] = "not semver"
|
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(
|
print(
|
||||||
"validated analysis/trace/tool artifacts "
|
"validated analysis/trace/tool artifacts "
|
||||||
|
|||||||
Vendored
+1
-7
@@ -13,14 +13,8 @@ fn main() {
|
|||||||
}
|
}
|
||||||
println!(
|
println!(
|
||||||
"protocol={}",
|
"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 mut stdin = String::new();
|
||||||
let _ = std::io::stdin().read_to_string(&mut stdin);
|
let _ = std::io::stdin().read_to_string(&mut stdin);
|
||||||
if !stdin.is_empty() {
|
if !stdin.is_empty() {
|
||||||
|
|||||||
Reference in new issue
Block a user