feat(PR-01): single Rust package, Tool Protocol v1 bundle and PublicCoreClient
- src/lib.rs module layout + thin main.rs dispatcher; CLI owns browse/export/verify - core_client: MARQDO_BIN only, explicit argv (no shell), 0700 scratch dirs, wall-clock timeout killing the whole process group, version/protocol negotiation - project/source_map: canonical path boundary, SafeRelativePath, exact UTF-8 byte <-> line/column <-> UTF-16 mapping, SHA-256 of exact bytes - stable view.* error codes with 0/1/2 exit classes; BindDenied for non-loopback - verify use case: Analysis v2 schema/profile/root_id/source_digest binding, no execution - tool.json + tools/package.sh + tools/install-smoke.sh; frozen-CLI install smoke PASS - contract tests with a real fake-core executable + architectural coupling gates - COMPATIBILITY/CHANGELOG/STATUS updated
This commit is contained in:
1 parent
ef546f2ca6
commit
8ba20a5c67
23 files changed
+3692
-8
No files matched your search
+221
@@ -0,0 +1,221 @@
|
||||
//! Application layer: turns parsed commands into use cases.
|
||||
//!
|
||||
//! No HTML is built here; no Markdown is parsed here. Browse uses the single
|
||||
//! renderer (PR-02+), verify only checks bindings, export only writes static
|
||||
//! files through the same renderer (PR-05).
|
||||
|
||||
use crate::cli::{ExportArgs, RuntimeOpts, VerifyArgs};
|
||||
use crate::core_client::{CheckOptions, CoreClient};
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::project::Project;
|
||||
use crate::source_map::sha256_hex;
|
||||
use crate::version;
|
||||
|
||||
pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
|
||||
let path = args
|
||||
.path
|
||||
.clone()
|
||||
.or_else(|| opts.path.clone())
|
||||
.unwrap_or_else(|| std::path::PathBuf::from("."));
|
||||
let project = Project::open(&path)?;
|
||||
let entry = project.entry().relative.clone();
|
||||
let source_bytes = project.read_source(&entry)?;
|
||||
let source_text = String::from_utf8(source_bytes.clone()).map_err(|err| ViewError::Io {
|
||||
detail: format!("{entry} is not valid UTF-8: {err}"),
|
||||
})?;
|
||||
let _ = source_text;
|
||||
|
||||
let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?;
|
||||
let core_version = client.negotiate()?;
|
||||
let check = client.check(
|
||||
&project,
|
||||
&entry,
|
||||
&CheckOptions {
|
||||
refs: args.refs,
|
||||
timeout: None,
|
||||
},
|
||||
)?;
|
||||
|
||||
let analysis: serde_json::Value =
|
||||
serde_json::from_slice(&check.analysis_bytes).map_err(|err| ViewError::AnalysisFailed {
|
||||
detail: format!("emitted Analysis is not JSON: {err}"),
|
||||
})?;
|
||||
let summary = validate_static_binding(&analysis, entry.as_str(), &source_bytes)?;
|
||||
|
||||
if args.json {
|
||||
let doc = serde_json::json!({
|
||||
"schema": "marqdo.view-verify",
|
||||
"schema_version": 1,
|
||||
"ok": true,
|
||||
"core": {
|
||||
"version": core_version.version.to_string(),
|
||||
"supported_range": version::PRODUCT_RANGE,
|
||||
},
|
||||
"analysis": {
|
||||
"schema": "marqdo.analysis",
|
||||
"schema_version": 2,
|
||||
"digest": check.analysis_digest,
|
||||
"producer_version": summary.producer_version,
|
||||
},
|
||||
"project": {
|
||||
"root_id": summary.root_id,
|
||||
"identity_kind": summary.identity_kind,
|
||||
},
|
||||
"document": {
|
||||
"relative_path": entry.as_str(),
|
||||
"source_digest": summary.source_digest,
|
||||
"source_digest_matches": true,
|
||||
},
|
||||
"result": "PASS",
|
||||
"executed": false,
|
||||
"note": "Static verification only; the document was not executed.",
|
||||
});
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string())
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"core: marqdo {} (supported {})",
|
||||
core_version.version,
|
||||
version::PRODUCT_RANGE
|
||||
);
|
||||
println!("project: {} ({})", summary.root_id, summary.identity_kind);
|
||||
println!("document: {}", entry);
|
||||
println!(
|
||||
"analysis: schema=marqdo.analysis v2 modules={} digest={}",
|
||||
summary.module_count, check.analysis_digest
|
||||
);
|
||||
println!("source digest: match");
|
||||
println!("result: PASS (static only; document not executed)");
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
pub fn export(_opts: &RuntimeOpts, _args: &ExportArgs) -> ViewResult<i32> {
|
||||
Err(ViewError::Unsupported {
|
||||
detail: "static export lands with PR-05; this build teaches Tool Protocol and statics only"
|
||||
.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn browse(_opts: &RuntimeOpts) -> ViewResult<i32> {
|
||||
Err(ViewError::Unsupported {
|
||||
detail: "the Live reader lands with PR-02/PR-03; this build teaches Tool Protocol and statics only"
|
||||
.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
struct BindingSummary {
|
||||
root_id: String,
|
||||
identity_kind: String,
|
||||
producer_version: String,
|
||||
module_count: usize,
|
||||
source_digest: String,
|
||||
}
|
||||
|
||||
/// Structural binding checks that do not need the full typed projection yet
|
||||
/// (the typed `SemanticProjection` replaces this in PR-02 without changing the
|
||||
/// externally visible `verify` result).
|
||||
fn validate_static_binding(
|
||||
analysis: &serde_json::Value,
|
||||
relative_path: &str,
|
||||
source_bytes: &[u8],
|
||||
) -> ViewResult<BindingSummary> {
|
||||
let schema = analysis
|
||||
.get("schema")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
if schema != "marqdo.analysis" {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!("unexpected Analysis schema {schema:?}"),
|
||||
});
|
||||
}
|
||||
match analysis.get("schema_version").and_then(|v| v.as_u64()) {
|
||||
Some(2) => {}
|
||||
other => {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"Analysis schema_version {other:?} is not supported (View implements v{})",
|
||||
version::ANALYSIS_PROTOCOL
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
let producer = analysis
|
||||
.get("producer")
|
||||
.ok_or_else(|| ViewError::AnalysisFailed {
|
||||
detail: "Analysis is missing producer".to_string(),
|
||||
})?;
|
||||
let producer_version = producer
|
||||
.get("version")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let markdown_profile = producer
|
||||
.get("markdown_profile")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
if markdown_profile != "marqdo.md.v1" {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"unexpected Markdown profile {markdown_profile:?}; this View targets marqdo.md.v1"
|
||||
),
|
||||
});
|
||||
}
|
||||
let project = analysis
|
||||
.get("project")
|
||||
.ok_or_else(|| ViewError::AnalysisFailed {
|
||||
detail: "Analysis is missing project".to_string(),
|
||||
})?;
|
||||
let root_id = project
|
||||
.get("root_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if root_id.is_empty() {
|
||||
return Err(ViewError::AnalysisFailed {
|
||||
detail: "Analysis project.root_id is empty".to_string(),
|
||||
});
|
||||
}
|
||||
let identity_kind = project
|
||||
.get("identity_kind")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let modules = analysis
|
||||
.get("modules")
|
||||
.and_then(|v| v.as_array())
|
||||
.ok_or_else(|| ViewError::AnalysisFailed {
|
||||
detail: "Analysis is missing modules[]".to_string(),
|
||||
})?;
|
||||
let expected_digest = sha256_hex(source_bytes);
|
||||
let mut matches = 0usize;
|
||||
for module in modules {
|
||||
if module.get("relative_path").and_then(|v| v.as_str()) == Some(relative_path) {
|
||||
matches += 1;
|
||||
let digest = module
|
||||
.get("source_digest")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
if digest != expected_digest {
|
||||
return Err(ViewError::SourceMismatch {
|
||||
expected: digest.to_string(),
|
||||
actual: expected_digest,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches == 0 {
|
||||
return Err(ViewError::AnalysisFailed {
|
||||
detail: format!("Analysis has no module for {relative_path}"),
|
||||
});
|
||||
}
|
||||
Ok(BindingSummary {
|
||||
root_id,
|
||||
identity_kind,
|
||||
producer_version,
|
||||
module_count: modules.len(),
|
||||
source_digest: expected_digest,
|
||||
})
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
//! Command-line surface owned entirely by View.
|
||||
//!
|
||||
//! The Core registers this program as the `view` tool and passes the arguments
|
||||
//! after `view` unchanged. View therefore parses its own subcommands, options
|
||||
//! and help; the Core never knows about `export`, `verify`, `--out` or
|
||||
//! `--no-open` (RFC-VIEW-0001 §10.1).
|
||||
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
name = "marqdo-view",
|
||||
version,
|
||||
about = "Read .mq.md documents as documents: static Analysis v2, optional explicit run Trace v2",
|
||||
long_about = "Marqdo View renders the original Markdown and attaches verified Analysis v2 facts. \
|
||||
Running is never implicit: it requires an explicit user action. \
|
||||
Export is always a pure read-only operation.",
|
||||
disable_help_subcommand = true,
|
||||
propagate_version = true
|
||||
)]
|
||||
pub struct Cli {
|
||||
/// A `.mq.md` document or a project directory (default: `.`).
|
||||
#[arg(value_name = "PATH")]
|
||||
pub path: Option<PathBuf>,
|
||||
|
||||
/// Development only: explicit path to the frozen `marqdo` binary.
|
||||
/// Installed Tool Protocol runs get the path from `MARQDO_BIN`.
|
||||
#[arg(long, value_name = "PATH", global = true)]
|
||||
pub marqdo_bin: Option<PathBuf>,
|
||||
|
||||
/// Loopback host for the Live reader (default 127.0.0.1).
|
||||
#[arg(long, default_value = "127.0.0.1", global = true)]
|
||||
pub host: String,
|
||||
|
||||
/// Port for the Live reader; `0` lets the OS choose and prints the real URL.
|
||||
#[arg(long, default_value_t = 7429, global = true)]
|
||||
pub port: u16,
|
||||
|
||||
/// Do not open a browser (the full local URL is still printed).
|
||||
#[arg(long, global = true)]
|
||||
pub no_open: bool,
|
||||
|
||||
/// Advanced: allow a non-loopback bind. No execution API is opened by it.
|
||||
#[arg(long, global = true, hide = true)]
|
||||
pub unsafe_expose: bool,
|
||||
|
||||
#[command(subcommand)]
|
||||
pub command: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub enum Command {
|
||||
/// Write a static, read-only HTML site (never executes the document).
|
||||
Export(ExportArgs),
|
||||
/// Check CLI/Analysis/source binding only; never executes.
|
||||
Verify(VerifyArgs),
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
pub struct ExportArgs {
|
||||
/// A `.mq.md` document or a project directory (default: parent PATH option).
|
||||
#[arg(value_name = "PATH")]
|
||||
pub path: Option<PathBuf>,
|
||||
|
||||
/// Output directory for the generated site.
|
||||
#[arg(short = 'o', long = "out", value_name = "DIR")]
|
||||
pub out: PathBuf,
|
||||
|
||||
/// Disable semantic annotations but keep the prose readable.
|
||||
#[arg(long)]
|
||||
pub no_annotations: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
pub struct VerifyArgs {
|
||||
/// A `.mq.md` document or a project directory.
|
||||
#[arg(value_name = "PATH")]
|
||||
pub path: Option<PathBuf>,
|
||||
|
||||
/// Also validate Markdown link targets (`check --refs`); may fail where the
|
||||
/// plain syntax check passes.
|
||||
#[arg(long)]
|
||||
pub refs: bool,
|
||||
|
||||
/// Machine readable JSON on stdout.
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
/// Options shared by every command after parsing.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RuntimeOpts {
|
||||
pub path: Option<PathBuf>,
|
||||
pub marqdo_bin: Option<PathBuf>,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub no_open: bool,
|
||||
pub unsafe_expose: bool,
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
pub fn runtime(&self) -> RuntimeOpts {
|
||||
RuntimeOpts {
|
||||
path: self.path.clone(),
|
||||
marqdo_bin: self.marqdo_bin.clone(),
|
||||
host: self.host.clone(),
|
||||
port: self.port,
|
||||
no_open: self.no_open,
|
||||
unsafe_expose: self.unsafe_expose,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// First-version bind policy: loopback only unless the hidden advanced flag is
|
||||
/// given. Even then no execution API becomes reachable without a session token.
|
||||
pub fn validate_bind(host: &str, unsafe_expose: bool) -> Result<(), String> {
|
||||
let loopback = matches!(host, "127.0.0.1" | "localhost" | "::1" | "[::1]");
|
||||
if loopback {
|
||||
return Ok(());
|
||||
}
|
||||
if unsafe_expose {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"refusing to bind non-loopback host {host:?}: the Live reader defaults to 127.0.0.1. \
|
||||
Use --unsafe-expose only if you understand that it exposes read-only pages on your network."
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::Parser;
|
||||
|
||||
#[test]
|
||||
fn parses_browse_defaults() {
|
||||
let cli = Cli::parse_from(["marqdo-view"]);
|
||||
assert!(cli.path.is_none());
|
||||
assert!(cli.command.is_none());
|
||||
assert_eq!(cli.host, "127.0.0.1");
|
||||
assert_eq!(cli.port, 7429);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_export_subcommand() {
|
||||
let cli = Cli::parse_from(["marqdo-view", "export", "examples", "--out", "site"]);
|
||||
match cli.command {
|
||||
Some(Command::Export(args)) => {
|
||||
assert_eq!(args.path.unwrap(), PathBuf::from("examples"));
|
||||
assert_eq!(args.out, PathBuf::from("site"));
|
||||
assert!(!args.no_annotations);
|
||||
}
|
||||
other => panic!("expected export, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_requires_out() {
|
||||
let err = Cli::try_parse_from(["marqdo-view", "export", "examples"]).unwrap_err();
|
||||
assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_verify_and_global_options_anywhere() {
|
||||
let cli = Cli::parse_from([
|
||||
"marqdo-view",
|
||||
"verify",
|
||||
"index.mq.md",
|
||||
"--refs",
|
||||
"--json",
|
||||
"--marqdo-bin",
|
||||
"/opt/marqdo",
|
||||
]);
|
||||
assert_eq!(
|
||||
cli.marqdo_bin.as_deref(),
|
||||
Some(std::path::Path::new("/opt/marqdo"))
|
||||
);
|
||||
match cli.command {
|
||||
Some(Command::Verify(args)) => {
|
||||
assert!(args.refs);
|
||||
assert!(args.json);
|
||||
assert_eq!(args.path.unwrap(), PathBuf::from("index.mq.md"));
|
||||
}
|
||||
other => panic!("expected verify, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_policy_is_loopback_by_default() {
|
||||
assert!(validate_bind("127.0.0.1", false).is_ok());
|
||||
assert!(validate_bind("localhost", false).is_ok());
|
||||
assert!(validate_bind("0.0.0.0", false).is_err());
|
||||
assert!(validate_bind("0.0.0.0", true).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
//! The only way View talks to the frozen CLI.
|
||||
//!
|
||||
//! Invariants (RFC-VIEW-0001 §4.2, §10.3, §14.1):
|
||||
//! * absolute `MARQDO_BIN`, argv arrays, never `sh -c`, never shell strings;
|
||||
//! * `check --emit` is the only static channel; `run --trace-file --json` the
|
||||
//! only dynamic one; private Core IR dumps are never used;
|
||||
//! * stdout/stderr/exit status are handled separately; a stderr JSON blob is
|
||||
//! never promoted to a successful Analysis;
|
||||
//! * temporary artifacts live in a private 0700 directory and are removed on
|
||||
//! drop.
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::project::{Project, SafeRelativePath};
|
||||
use crate::source_map::{sha256_hex, sha256_prefixed};
|
||||
use crate::version::{self, CoreVersion};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ffi::OsString;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Default View-level wall clock cap for one Core `run`.
|
||||
pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
/// Default View-level wall clock cap for one Core `check`.
|
||||
pub const DEFAULT_CHECK_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
const ENV_MARQDO_BIN: &str = "MARQDO_BIN";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SandboxMode {
|
||||
Pure,
|
||||
Project,
|
||||
Strict,
|
||||
}
|
||||
|
||||
impl SandboxMode {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
SandboxMode::Pure => "pure",
|
||||
SandboxMode::Project => "project",
|
||||
SandboxMode::Strict => "strict",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicit grants assembled only from a user-approved run request. View never
|
||||
/// reads project capability declarations to derive grants.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Grants {
|
||||
pub allow_read: Vec<String>,
|
||||
pub allow_write: Vec<String>,
|
||||
pub allow_net: Vec<String>,
|
||||
pub allow_env: Vec<String>,
|
||||
pub allow_process: Vec<String>,
|
||||
pub allow_random: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CheckOptions {
|
||||
/// `--refs` also validates Markdown link targets; it is a stricter check
|
||||
/// and may fail where plain syntax succeeds.
|
||||
pub refs: bool,
|
||||
pub timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunOptions {
|
||||
pub mode: SandboxMode,
|
||||
pub grants: Grants,
|
||||
pub fuel: Option<u64>,
|
||||
pub stack: Option<u64>,
|
||||
pub max_output: Option<u64>,
|
||||
pub timeout_seconds: Option<u64>,
|
||||
pub view_timeout: Option<Duration>,
|
||||
pub trace_max_events: Option<u64>,
|
||||
pub trace_max_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for RunOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mode: SandboxMode::Pure,
|
||||
grants: Grants::default(),
|
||||
fuel: None,
|
||||
stack: None,
|
||||
max_output: None,
|
||||
timeout_seconds: None,
|
||||
view_timeout: Some(DEFAULT_RUN_TIMEOUT),
|
||||
trace_max_events: None,
|
||||
trace_max_bytes: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CheckOutput {
|
||||
/// Exact bytes written by `check --emit`, the digest source of truth.
|
||||
pub analysis_bytes: Vec<u8>,
|
||||
/// Lowercase hex SHA-256 of `analysis_bytes`.
|
||||
pub analysis_sha256: String,
|
||||
/// Prefixed digest (`sha256:...`) for comparison with Trace v2.
|
||||
pub analysis_digest: String,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RunOutput {
|
||||
/// Exactly one JSON document emitted on stdout by the Core.
|
||||
pub json: serde_json::Value,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub exit_code: i32,
|
||||
/// Raw Trace v2 bytes when the Core wrote them (even for a failed run).
|
||||
pub trace_bytes: Option<Vec<u8>>,
|
||||
pub trace_sha256: Option<String>,
|
||||
}
|
||||
|
||||
/// A private temporary directory for Core artifacts.
|
||||
pub struct ScratchDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl ScratchDir {
|
||||
pub fn create(label: &str) -> ViewResult<Self> {
|
||||
let base = std::env::temp_dir();
|
||||
let unique = format!(
|
||||
"marqdo-view-{}-{}-{}",
|
||||
std::process::id(),
|
||||
unique_counter(),
|
||||
sanitize_label(label)
|
||||
);
|
||||
let path = base.join(unique);
|
||||
std::fs::create_dir_all(&path)
|
||||
.map_err(|err| ViewError::io(&format!("create scratch {}", path.display()), err))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))
|
||||
.map_err(|err| ViewError::io(&format!("chmod scratch {}", path.display()), err))?;
|
||||
}
|
||||
Ok(Self { path })
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
pub fn file(&self, name: &str) -> PathBuf {
|
||||
self.path.join(name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ScratchDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn unique_counter() -> u64 {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos() as u64)
|
||||
.unwrap_or(0);
|
||||
seq ^ nanos.rotate_left(17)
|
||||
}
|
||||
|
||||
fn sanitize_label(label: &str) -> String {
|
||||
label
|
||||
.chars()
|
||||
.map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' })
|
||||
.take(32)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Negotiated public-client for one frozen core binary.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CoreClient {
|
||||
bin: PathBuf,
|
||||
protocol_env: ProtocolEnv,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct ProtocolEnv {
|
||||
tool: Option<String>,
|
||||
analysis: Option<String>,
|
||||
trace: Option<String>,
|
||||
}
|
||||
|
||||
impl CoreClient {
|
||||
/// Build a client from `--marqdo-bin` (development) or `MARQDO_BIN`
|
||||
/// (installed Tool Protocol). Never guesses a `PATH` binary: a wrong
|
||||
/// version must fail loudly, not silently.
|
||||
pub fn from_env(explicit: Option<&Path>) -> ViewResult<Self> {
|
||||
let bin = locate_bin(explicit)?;
|
||||
Self::with_bin(bin)
|
||||
}
|
||||
|
||||
/// Construct from an explicit binary path, still reading any negotiated
|
||||
/// protocol environment. Useful for `--marqdo-bin` and integration tests;
|
||||
/// production dispatch should prefer [`CoreClient::from_env`].
|
||||
pub fn with_bin(bin: impl Into<PathBuf>) -> ViewResult<Self> {
|
||||
let bin = validate_bin(&bin.into(), "core binary")?;
|
||||
Ok(Self {
|
||||
bin,
|
||||
protocol_env: ProtocolEnv {
|
||||
tool: std::env::var(version::ENV_TOOL_PROTOCOL).ok(),
|
||||
analysis: std::env::var(version::ENV_PROTOCOL_ANALYSIS).ok(),
|
||||
trace: std::env::var(version::ENV_PROTOCOL_TRACE).ok(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// Test-only constructor with an explicit binary and no environment
|
||||
/// negotiation input.
|
||||
#[cfg(test)]
|
||||
pub fn for_test(bin: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
bin: bin.into(),
|
||||
protocol_env: ProtocolEnv::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bin(&self) -> &Path {
|
||||
&self.bin
|
||||
}
|
||||
|
||||
/// Run `--version`, validate the product range and any negotiated protocol
|
||||
/// environment variables. A missing Development-mode env is allowed; an
|
||||
/// unknown major is a hard error.
|
||||
pub fn negotiate(&self) -> ViewResult<CoreVersion> {
|
||||
version::negotiate_protocol_env(
|
||||
self.protocol_env.tool.as_deref(),
|
||||
self.protocol_env.analysis.as_deref(),
|
||||
self.protocol_env.trace.as_deref(),
|
||||
)?;
|
||||
let output = self.execute(
|
||||
&[OsString::from("--version")],
|
||||
&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
|
||||
DEFAULT_CHECK_TIMEOUT,
|
||||
)?;
|
||||
if output.exit_code != 0 {
|
||||
return Err(ViewError::CoreMissing {
|
||||
detail: format!(
|
||||
"{} --version failed (exit {}): {}",
|
||||
self.bin.display(),
|
||||
output.exit_code,
|
||||
output.stderr.trim()
|
||||
),
|
||||
});
|
||||
}
|
||||
let version = version::parse_version_output(&output.stdout)?;
|
||||
if !version::product_is_compatible(&version.version) {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"core {} is outside the supported range {}",
|
||||
version.version,
|
||||
version::PRODUCT_RANGE
|
||||
),
|
||||
});
|
||||
}
|
||||
Ok(version)
|
||||
}
|
||||
|
||||
/// `check --emit`; on success returns the exact Analysis v2 bytes.
|
||||
pub fn check(
|
||||
&self,
|
||||
project: &Project,
|
||||
relative: &SafeRelativePath,
|
||||
options: &CheckOptions,
|
||||
) -> ViewResult<CheckOutput> {
|
||||
let entry = project.absolute_for(relative)?;
|
||||
let scratch = ScratchDir::create("check")?;
|
||||
let emit = scratch.file("analysis.json");
|
||||
let mut args = build_check_args(&entry);
|
||||
|
||||
// Scratch path is ours; the argument vector is explicit, no shell.
|
||||
args.push(OsString::from("--emit"));
|
||||
args.push(emit.clone().into_os_string());
|
||||
if options.refs {
|
||||
args.push(OsString::from("--refs"));
|
||||
}
|
||||
|
||||
let output = self.execute(
|
||||
&args,
|
||||
project.root(),
|
||||
options.timeout.unwrap_or(DEFAULT_CHECK_TIMEOUT),
|
||||
)?;
|
||||
if output.exit_code != 0 {
|
||||
return Err(ViewError::AnalysisFailed {
|
||||
detail: format!(
|
||||
"`marqdo check` failed with exit code {}: {}",
|
||||
output.exit_code,
|
||||
summarize_stderr(&output.stderr)
|
||||
),
|
||||
});
|
||||
}
|
||||
let analysis_bytes = std::fs::read(&emit).map_err(|err| ViewError::AnalysisFailed {
|
||||
detail: format!(
|
||||
"`marqdo check` succeeded but emitted no Analysis at {}: {err}",
|
||||
emit.display()
|
||||
),
|
||||
})?;
|
||||
if analysis_bytes.is_empty() {
|
||||
return Err(ViewError::AnalysisFailed {
|
||||
detail: "`marqdo check` emitted an empty Analysis file".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(CheckOutput {
|
||||
analysis_sha256: sha256_hex(&analysis_bytes),
|
||||
analysis_digest: sha256_prefixed(&analysis_bytes),
|
||||
analysis_bytes,
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
})
|
||||
}
|
||||
|
||||
/// `run --trace-file --json`, only after an explicit user confirmation in
|
||||
/// the calling layer. Returns the CLI JSON document and raw Trace bytes.
|
||||
pub fn run(
|
||||
&self,
|
||||
project: &Project,
|
||||
relative: &SafeRelativePath,
|
||||
options: &RunOptions,
|
||||
) -> ViewResult<RunOutput> {
|
||||
let entry = project.absolute_for(relative)?;
|
||||
let scratch = ScratchDir::create("run")?;
|
||||
let trace_path = scratch.file("trace.json");
|
||||
let args = build_run_args(&entry, &trace_path, options);
|
||||
let output = self.execute(
|
||||
&args,
|
||||
project.root(),
|
||||
options.view_timeout.unwrap_or(DEFAULT_RUN_TIMEOUT),
|
||||
)?;
|
||||
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_slice(&output.stdout_bytes).map_err(|err| ViewError::Io {
|
||||
detail: format!(
|
||||
"`marqdo run --json` did not emit exactly one JSON document: {err}; stderr: {}",
|
||||
summarize_stderr(&output.stderr)
|
||||
),
|
||||
})?;
|
||||
if !json.is_object() {
|
||||
return Err(ViewError::Io {
|
||||
detail: "`marqdo run --json` emitted a non-object JSON document".to_string(),
|
||||
});
|
||||
}
|
||||
let trace_bytes = match std::fs::read(&trace_path) {
|
||||
Ok(bytes) => {
|
||||
if bytes.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(bytes)
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(err) => {
|
||||
return Err(ViewError::io(
|
||||
&format!("read trace {}", trace_path.display()),
|
||||
err,
|
||||
))
|
||||
}
|
||||
};
|
||||
Ok(RunOutput {
|
||||
json,
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
exit_code: output.exit_code,
|
||||
trace_sha256: trace_bytes.as_deref().map(sha256_hex),
|
||||
trace_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Spawn the core with an explicit argv, private cwd and a wall-clock cap.
|
||||
fn execute(&self, args: &[OsString], cwd: &Path, timeout: Duration) -> ViewResult<ExecOutput> {
|
||||
let mut command = Command::new(&self.bin);
|
||||
command
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
// Put the core in its own process group so a View-level timeout kills
|
||||
// the whole subtree, not just the immediate shell-less child.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
// SAFETY: `setpgid` is async-signal-safe and only touches the child
|
||||
// before exec.
|
||||
unsafe {
|
||||
command.pre_exec(|| {
|
||||
if libc::setpgid(0, 0) != 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
|
||||
detail: format!("spawn {}: {err}", self.bin.display()),
|
||||
})?;
|
||||
let stdout = child.stdout.take().expect("piped stdout");
|
||||
let stderr = child.stderr.take().expect("piped stderr");
|
||||
let stdout_thread = std::thread::spawn(move || read_all(stdout));
|
||||
let stderr_thread = std::thread::spawn(move || read_all(stderr));
|
||||
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) => {
|
||||
if Instant::now() >= deadline {
|
||||
kill_process_tree(&mut child);
|
||||
let _ = child.wait();
|
||||
let _ = stdout_thread.join();
|
||||
let _ = stderr_thread.join();
|
||||
return Err(ViewError::CoreTimeout {
|
||||
detail: format!(
|
||||
"core did not finish within {}s and was killed",
|
||||
timeout.as_secs()
|
||||
),
|
||||
});
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(err) => {
|
||||
let _ = child.kill();
|
||||
return Err(ViewError::CoreSpawn {
|
||||
detail: format!("wait for {}: {err}", self.bin.display()),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let stdout_bytes = stdout_thread.join().unwrap_or_default();
|
||||
let stderr_bytes = stderr_thread.join().unwrap_or_default();
|
||||
let stdout = String::from_utf8_lossy(&stdout_bytes).to_string();
|
||||
let stderr = String::from_utf8_lossy(&stderr_bytes).to_string();
|
||||
Ok(ExecOutput {
|
||||
exit_code: status.code().unwrap_or(-1),
|
||||
stdout_bytes,
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ExecOutput {
|
||||
exit_code: i32,
|
||||
stdout_bytes: Vec<u8>,
|
||||
stdout: String,
|
||||
stderr: String,
|
||||
}
|
||||
|
||||
/// Kill the core and every descendant in its process group (Unix), or just the
|
||||
/// direct child elsewhere. Never leaves a runaway subprocess behind.
|
||||
fn kill_process_tree(child: &mut std::process::Child) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let pid = child.id() as i32;
|
||||
if pid > 0 {
|
||||
// SAFETY: negative pid targets the process group created by
|
||||
// pre_exec(setpgid); ESRCH is harmless when it already exited.
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
}
|
||||
|
||||
fn read_all(mut reader: impl Read) -> Vec<u8> {
|
||||
let mut bytes = Vec::new();
|
||||
let _ = reader.read_to_end(&mut bytes);
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Build the base `check` arguments. The caller appends `--emit <path>` and
|
||||
/// optionally `--refs`; this function exists so the argv shape is unit-testable.
|
||||
fn build_check_args(entry: &Path) -> Vec<OsString> {
|
||||
vec![OsString::from("check"), entry.as_os_str().to_os_string()]
|
||||
}
|
||||
|
||||
/// Build `run` arguments from an already user-approved request.
|
||||
pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec<OsString> {
|
||||
let mut args = vec![
|
||||
OsString::from("run"),
|
||||
entry.as_os_str().to_os_string(),
|
||||
OsString::from("--mode"),
|
||||
OsString::from(options.mode.as_str()),
|
||||
OsString::from("--json"),
|
||||
OsString::from("--trace-file"),
|
||||
trace_path.as_os_str().to_os_string(),
|
||||
];
|
||||
fn push_pair(args: &mut Vec<OsString>, flag: &str, value: &str) {
|
||||
args.push(OsString::from(flag));
|
||||
args.push(OsString::from(value));
|
||||
}
|
||||
for glob in &options.grants.allow_read {
|
||||
push_pair(&mut args, "--allow-read", glob);
|
||||
}
|
||||
for glob in &options.grants.allow_write {
|
||||
push_pair(&mut args, "--allow-write", glob);
|
||||
}
|
||||
for host in &options.grants.allow_net {
|
||||
push_pair(&mut args, "--allow-net", host);
|
||||
}
|
||||
for name in &options.grants.allow_env {
|
||||
push_pair(&mut args, "--allow-env", name);
|
||||
}
|
||||
for program in &options.grants.allow_process {
|
||||
push_pair(&mut args, "--allow-process", program);
|
||||
}
|
||||
if options.grants.allow_random {
|
||||
args.push(OsString::from("--allow-random"));
|
||||
}
|
||||
if let Some(fuel) = options.fuel {
|
||||
push_pair(&mut args, "--fuel", &fuel.to_string());
|
||||
}
|
||||
if let Some(stack) = options.stack {
|
||||
push_pair(&mut args, "--stack", &stack.to_string());
|
||||
}
|
||||
if let Some(max_output) = options.max_output {
|
||||
push_pair(&mut args, "--max-output", &max_output.to_string());
|
||||
}
|
||||
if let Some(timeout) = options.timeout_seconds {
|
||||
push_pair(&mut args, "--timeout", &timeout.to_string());
|
||||
}
|
||||
if let Some(max_events) = options.trace_max_events {
|
||||
push_pair(&mut args, "--trace-max-events", &max_events.to_string());
|
||||
}
|
||||
if let Some(max_bytes) = options.trace_max_bytes {
|
||||
push_pair(&mut args, "--trace-max-bytes", &max_bytes.to_string());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
fn locate_bin(explicit: Option<&Path>) -> ViewResult<PathBuf> {
|
||||
if let Some(path) = explicit {
|
||||
return validate_bin(path, "--marqdo-bin");
|
||||
}
|
||||
if let Some(raw) = std::env::var_os(ENV_MARQDO_BIN) {
|
||||
if raw.is_empty() {
|
||||
return Err(ViewError::CoreMissing {
|
||||
detail: format!("{ENV_MARQDO_BIN} is set but empty"),
|
||||
});
|
||||
}
|
||||
return validate_bin(Path::new(&raw), ENV_MARQDO_BIN);
|
||||
}
|
||||
Err(ViewError::CoreMissing {
|
||||
detail: format!(
|
||||
"{ENV_MARQDO_BIN} is not set. Install this tool with `marqdo tool install <bundle>/tool.json`, \
|
||||
or pass --marqdo-bin <path> when running marqdo-view directly."
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_bin(path: &Path, origin: &str) -> ViewResult<PathBuf> {
|
||||
let canonical = path.canonicalize().map_err(|err| ViewError::CoreMissing {
|
||||
detail: format!("{origin} points to {}: {err}", path.display()),
|
||||
})?;
|
||||
let metadata = std::fs::metadata(&canonical).map_err(|err| ViewError::CoreMissing {
|
||||
detail: format!("{origin} points to {}: {err}", canonical.display()),
|
||||
})?;
|
||||
if !metadata.is_file() {
|
||||
return Err(ViewError::CoreMissing {
|
||||
detail: format!("{origin} {} is not a regular file", canonical.display()),
|
||||
});
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if metadata.permissions().mode() & 0o111 == 0 {
|
||||
return Err(ViewError::CoreMissing {
|
||||
detail: format!("{origin} {} is not executable", canonical.display()),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(canonical)
|
||||
}
|
||||
|
||||
fn summarize_stderr(stderr: &str) -> String {
|
||||
let trimmed = stderr.trim();
|
||||
if trimmed.is_empty() {
|
||||
"(no stderr)".to_string()
|
||||
} else {
|
||||
let mut text: String = trimmed.chars().take(1200).collect();
|
||||
if trimmed.chars().count() > 1200 {
|
||||
text.push('…');
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn run_args_are_explicit_argv_never_shell() {
|
||||
let args = build_run_args(
|
||||
Path::new("/p/index.mq.md"),
|
||||
Path::new("/t/trace.json"),
|
||||
&RunOptions {
|
||||
mode: SandboxMode::Pure,
|
||||
grants: Grants {
|
||||
allow_read: vec!["data/**".into()],
|
||||
allow_net: vec!["example.com".into()],
|
||||
..Default::default()
|
||||
},
|
||||
fuel: Some(1000),
|
||||
trace_max_events: Some(20),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let text: Vec<String> = args
|
||||
.iter()
|
||||
.map(|arg| arg.to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert_eq!(text[0], "run");
|
||||
assert_eq!(text[1], "/p/index.mq.md");
|
||||
assert!(text.contains(&"pure".to_string()));
|
||||
assert!(text.contains(&"--json".to_string()));
|
||||
assert!(text.contains(&"--trace-file".to_string()));
|
||||
assert!(text.contains(&"data/**".to_string()));
|
||||
assert!(text.contains(&"example.com".to_string()));
|
||||
assert!(text.contains(&"1000".to_string()));
|
||||
assert!(text.contains(&"20".to_string()));
|
||||
// No token is a shell fragment: every argument is a separate value.
|
||||
assert!(!text
|
||||
.iter()
|
||||
.any(|t| t.contains(';') || t.contains('|') || t.contains('&')));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_args_are_plain_argv() {
|
||||
let args = build_check_args(Path::new("/p/index.mq.md"));
|
||||
assert_eq!(args[0], OsString::from("check"));
|
||||
assert_eq!(args[1], OsString::from("/p/index.mq.md"));
|
||||
assert_eq!(args.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_bin_has_stable_code() {
|
||||
let err = locate_bin(Some(Path::new("/definitely/not/here/marqdo"))).unwrap_err();
|
||||
assert_eq!(err.code(), "view.core_missing");
|
||||
assert_eq!(err.exit_code(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scratch_dir_is_private_and_removed() {
|
||||
let scratch = ScratchDir::create("unit").unwrap();
|
||||
let path = scratch.path().to_path_buf();
|
||||
assert!(path.is_dir());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
|
||||
assert_eq!(mode & 0o777, 0o700);
|
||||
}
|
||||
drop(scratch);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stderr_summary_is_bounded() {
|
||||
let text = summarize_stderr(&"x".repeat(5000));
|
||||
assert!(text.chars().count() <= 1201);
|
||||
assert_eq!(summarize_stderr(" "), "(no stderr)");
|
||||
}
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
//! Stable View-owned error kinds.
|
||||
//!
|
||||
//! Every failure that reaches the user has exactly one stable machine code
|
||||
//! (`view.*`), an exit code class and a `source` field so Core diagnostics can
|
||||
//! never be mistaken for View diagnostics. See RFC-VIEW-0001 §10.2.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Exit code 0: success. Exit code 1: runtime/I/O failure. Exit code 2:
|
||||
/// argument, protocol or permission failure.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ExitClass {
|
||||
Runtime,
|
||||
Argument,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ViewError {
|
||||
/// `MARQDO_BIN` unset, missing, or not executable.
|
||||
CoreMissing { detail: String },
|
||||
/// Tool/Analysis/Trace protocol or product range mismatch.
|
||||
ProtocolIncompatible { detail: String },
|
||||
/// Core `check` failed; prose stays readable but semantics are unusable.
|
||||
AnalysisFailed { detail: String },
|
||||
/// Analysis `source_digest` does not match the current source bytes.
|
||||
SourceMismatch { expected: String, actual: String },
|
||||
/// A Core byte span is out of range or not on a UTF-8 boundary.
|
||||
SourceSpanInvalid { detail: String },
|
||||
/// Trace does not bind to the current Analysis bytes.
|
||||
TraceStale { detail: String },
|
||||
/// The user did not confirm, or the requested mode/grants are not allowed.
|
||||
RunDenied { detail: String },
|
||||
/// Path escapes the allowed project root or is otherwise forbidden.
|
||||
PathForbidden { detail: String },
|
||||
/// Refused a bind address that is not explicitly allowed.
|
||||
BindDenied { detail: String },
|
||||
/// Embedded asset digest mismatch (build/package integrity).
|
||||
AssetIntegrity { detail: String },
|
||||
/// Export target is unsafe or the write failed.
|
||||
ExportFailed { detail: String },
|
||||
/// A configured resource limit was exceeded.
|
||||
ResourceLimit { detail: String },
|
||||
/// Core subprocess could not be spawned.
|
||||
CoreSpawn { detail: String },
|
||||
/// Core subprocess exceeded the View-level timeout and was killed.
|
||||
CoreTimeout { detail: String },
|
||||
/// Local file system / HTTP I/O failure.
|
||||
Io { detail: String },
|
||||
/// Feature intentionally not implemented in this build (honest status).
|
||||
Unsupported { detail: String },
|
||||
}
|
||||
|
||||
impl ViewError {
|
||||
pub fn code(&self) -> &'static str {
|
||||
match self {
|
||||
ViewError::CoreMissing { .. } => "view.core_missing",
|
||||
ViewError::ProtocolIncompatible { .. } => "view.protocol_incompatible",
|
||||
ViewError::AnalysisFailed { .. } => "view.analysis_failed",
|
||||
ViewError::SourceMismatch { .. } => "view.source_mismatch",
|
||||
ViewError::SourceSpanInvalid { .. } => "view.source_span_invalid",
|
||||
ViewError::TraceStale { .. } => "view.trace_stale",
|
||||
ViewError::RunDenied { .. } => "view.run_denied",
|
||||
ViewError::PathForbidden { .. } => "view.path_forbidden",
|
||||
ViewError::BindDenied { .. } => "view.bind_denied",
|
||||
ViewError::AssetIntegrity { .. } => "view.asset_integrity",
|
||||
ViewError::ExportFailed { .. } => "view.export_failed",
|
||||
ViewError::ResourceLimit { .. } => "view.resource_limit",
|
||||
ViewError::CoreSpawn { .. } => "view.core_spawn",
|
||||
ViewError::CoreTimeout { .. } => "view.core_timeout",
|
||||
ViewError::Io { .. } => "view.io",
|
||||
ViewError::Unsupported { .. } => "view.unsupported",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exit_class(&self) -> ExitClass {
|
||||
match self {
|
||||
ViewError::CoreMissing { .. }
|
||||
| ViewError::ProtocolIncompatible { .. }
|
||||
| ViewError::RunDenied { .. }
|
||||
| ViewError::PathForbidden { .. }
|
||||
| ViewError::BindDenied { .. }
|
||||
| ViewError::SourceSpanInvalid { .. }
|
||||
| ViewError::Unsupported { .. } => ExitClass::Argument,
|
||||
_ => ExitClass::Runtime,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exit_code(&self) -> i32 {
|
||||
match self.exit_class() {
|
||||
ExitClass::Runtime => 1,
|
||||
ExitClass::Argument => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// `core` is used only for diagnostics that came from the frozen CLI.
|
||||
pub fn source(&self) -> &'static str {
|
||||
"view"
|
||||
}
|
||||
|
||||
/// JSON diagnostic with `source:"view"` so it can never masquerade as a
|
||||
/// Core diagnostic. Contains no absolute machine paths beyond what the
|
||||
/// caller already supplied.
|
||||
pub fn to_json(&self) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"schema": "marqdo.view-error",
|
||||
"schema_version": 1,
|
||||
"code": self.code(),
|
||||
"source": self.source(),
|
||||
"message": self.detail(),
|
||||
"exit_code": self.exit_code(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn detail(&self) -> &str {
|
||||
match self {
|
||||
ViewError::CoreMissing { detail }
|
||||
| ViewError::ProtocolIncompatible { detail }
|
||||
| ViewError::AnalysisFailed { detail }
|
||||
| ViewError::SourceSpanInvalid { detail }
|
||||
| ViewError::TraceStale { detail }
|
||||
| ViewError::RunDenied { detail }
|
||||
| ViewError::PathForbidden { detail }
|
||||
| ViewError::BindDenied { detail }
|
||||
| ViewError::AssetIntegrity { detail }
|
||||
| ViewError::ExportFailed { detail }
|
||||
| ViewError::ResourceLimit { detail }
|
||||
| ViewError::CoreSpawn { detail }
|
||||
| ViewError::CoreTimeout { detail }
|
||||
| ViewError::Io { detail }
|
||||
| ViewError::Unsupported { detail } => detail,
|
||||
ViewError::SourceMismatch { expected, actual } => {
|
||||
// Cannot return a formatted &str; handled in Display instead.
|
||||
let _ = (expected, actual);
|
||||
"source digest mismatch"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ViewError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ViewError::SourceMismatch { expected, actual } => write!(
|
||||
f,
|
||||
"{}: source digest mismatch (expected {expected}, actual {actual})",
|
||||
self.code()
|
||||
),
|
||||
other => write!(f, "{}: {}", other.code(), other.detail()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ViewError {}
|
||||
|
||||
impl From<std::io::Error> for ViewError {
|
||||
fn from(err: std::io::Error) -> Self {
|
||||
ViewError::Io {
|
||||
detail: err.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type ViewResult<T> = Result<T, ViewError>;
|
||||
|
||||
impl ViewError {
|
||||
pub fn io(context: &str, err: std::io::Error) -> Self {
|
||||
ViewError::Io {
|
||||
detail: format!("{context}: {err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
//! marqdo-view library: a single package with one presentation pipeline.
|
||||
//!
|
||||
//! Layer direction (RFC-VIEW-0001 §6.1):
|
||||
//! `CLI/Server → Application → Domain → ProtocolAdapter`, and
|
||||
//! `Application → Presentation → Renderer → Assets`.
|
||||
//! `main.rs` is only a dispatcher; integration tests and future server code use
|
||||
//! this library so there is never a second renderer or a second parser.
|
||||
|
||||
pub mod app;
|
||||
pub mod cli;
|
||||
pub mod core_client;
|
||||
pub mod error;
|
||||
pub mod project;
|
||||
pub mod source_map;
|
||||
pub mod version;
|
||||
|
||||
pub use cli::Cli;
|
||||
pub use error::{ViewError, ViewResult};
|
||||
|
||||
/// Dispatch a parsed CLI invocation. Returns the process exit code.
|
||||
pub fn run(cli: Cli) -> ViewResult<i32> {
|
||||
let opts = cli.runtime();
|
||||
cli::validate_bind(&opts.host, opts.unsafe_expose)
|
||||
.map_err(|detail| ViewError::BindDenied { detail })?;
|
||||
match cli.command {
|
||||
Some(cli::Command::Verify(args)) => app::verify(&opts, &args),
|
||||
Some(cli::Command::Export(args)) => app::export(&opts, &args),
|
||||
None => app::browse(&opts),
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
//! Thin binary entry point: parse arguments, dispatch through the library,
|
||||
//! print one stable diagnostic and exit with the View-owned exit code.
|
||||
|
||||
use clap::Parser;
|
||||
|
||||
fn main() {
|
||||
let cli = marqdo_view::Cli::parse();
|
||||
match marqdo_view::run(cli) {
|
||||
Ok(code) => std::process::exit(code),
|
||||
Err(err) => {
|
||||
eprintln!("{err}");
|
||||
std::process::exit(err.exit_code());
|
||||
}
|
||||
}
|
||||
}
|
||||
+398
@@ -0,0 +1,398 @@
|
||||
//! Project-root and path boundary enforcement.
|
||||
//!
|
||||
//! Production, HTTP, Export and tests all use these functions; there is no
|
||||
//! second path validator (RFC-VIEW-0001 §14.4).
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::source_map::sha256_hex;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Hard cap on one source document, matching the Core read limit family.
|
||||
pub const MAX_SOURCE_BYTES: u64 = 8 * 1024 * 1024;
|
||||
/// Hard cap on discovered documents per project to bound scans.
|
||||
pub const MAX_DOCUMENTS: usize = 5_000;
|
||||
/// Directories never scanned for documents (VCS, caches, build output).
|
||||
pub const SKIP_DIRS: &[&str] = &[
|
||||
".git",
|
||||
".marqdo",
|
||||
".hg",
|
||||
".svn",
|
||||
"node_modules",
|
||||
"target",
|
||||
"dist",
|
||||
];
|
||||
|
||||
/// A project-relative path that is safe to join under a project root.
|
||||
///
|
||||
/// Rejects absolute paths, `..`, root/prefix components, NUL and control bytes.
|
||||
/// Backslashes are normalized to `/` so a Windows-style input can never be
|
||||
/// reinterpreted as a separator by the OS while looking harmless here.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct SafeRelativePath(String);
|
||||
|
||||
impl SafeRelativePath {
|
||||
pub fn parse(raw: &str) -> ViewResult<Self> {
|
||||
if raw.is_empty() {
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: "empty relative path".to_string(),
|
||||
});
|
||||
}
|
||||
if raw.contains('\0') {
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: "path contains NUL".to_string(),
|
||||
});
|
||||
}
|
||||
if raw.chars().any(|ch| ch.is_control()) {
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: "path contains control characters".to_string(),
|
||||
});
|
||||
}
|
||||
let normalized = raw.replace('\\', "/");
|
||||
if normalized.starts_with('/') {
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: format!("absolute path is not a project-relative path: {raw:?}"),
|
||||
});
|
||||
}
|
||||
if normalized
|
||||
.split('/')
|
||||
.next()
|
||||
.map(|first| first.len() == 2 && first.ends_with(':'))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: format!("drive-absolute path is not allowed: {raw:?}"),
|
||||
});
|
||||
}
|
||||
let mut parts = Vec::new();
|
||||
for part in normalized.split('/') {
|
||||
if part.is_empty() || part == "." {
|
||||
continue;
|
||||
}
|
||||
if part == ".." {
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: format!("path escapes the project root: {raw:?}"),
|
||||
});
|
||||
}
|
||||
parts.push(part);
|
||||
}
|
||||
if parts.is_empty() {
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: "path does not name a file".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(Self(parts.join("/")))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn to_path(&self) -> PathBuf {
|
||||
PathBuf::from(self.0.replace('/', std::path::MAIN_SEPARATOR_STR))
|
||||
}
|
||||
|
||||
pub fn file_name(&self) -> &str {
|
||||
self.0.rsplit('/').next().unwrap_or(&self.0)
|
||||
}
|
||||
|
||||
pub fn parent(&self) -> Option<SafeRelativePath> {
|
||||
self.0
|
||||
.rsplit_once('/')
|
||||
.map(|(parent, _)| SafeRelativePath(parent.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for SafeRelativePath {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// One resolved document inside a project.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DocumentRef {
|
||||
pub relative: SafeRelativePath,
|
||||
pub absolute: PathBuf,
|
||||
}
|
||||
|
||||
/// An opened project root (directory) and its selected entry document.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Project {
|
||||
root: PathBuf,
|
||||
entry: DocumentRef,
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// Open `path` (file or directory) and select the entry document.
|
||||
///
|
||||
/// File input: the project root is the nearest ancestor containing
|
||||
/// `marqdo.yaml`, else the file's own directory.
|
||||
/// Directory input: the directory is the root; `index.mq.md` wins, else the
|
||||
/// first document in stable sorted order (RFC-VIEW-0001 §9.4).
|
||||
pub fn open(path: &Path) -> ViewResult<Self> {
|
||||
let canonical = canonicalize(path, "project path")?;
|
||||
let metadata = std::fs::metadata(&canonical)
|
||||
.map_err(|err| ViewError::io(&format!("stat {}", canonical.display()), err))?;
|
||||
if metadata.is_file() {
|
||||
let root = discover_project_root(&canonical);
|
||||
let project = Self {
|
||||
entry: DocumentRef {
|
||||
relative: SafeRelativePath("placeholder".to_string()),
|
||||
absolute: canonical.clone(),
|
||||
},
|
||||
root,
|
||||
};
|
||||
let relative = project.relative_for(&canonical)?;
|
||||
Ok(Self {
|
||||
root: project.root,
|
||||
entry: DocumentRef {
|
||||
relative,
|
||||
absolute: canonical,
|
||||
},
|
||||
})
|
||||
} else if metadata.is_dir() {
|
||||
let project = Self {
|
||||
root: canonical.clone(),
|
||||
entry: DocumentRef {
|
||||
relative: SafeRelativePath("placeholder".to_string()),
|
||||
absolute: canonical.clone(),
|
||||
},
|
||||
};
|
||||
let documents = project.list_documents()?;
|
||||
let chosen = choose_entry(&project.root, &documents)?;
|
||||
Ok(Self {
|
||||
root: project.root,
|
||||
entry: chosen,
|
||||
})
|
||||
} else {
|
||||
Err(ViewError::PathForbidden {
|
||||
detail: format!("{} is not a regular file or directory", path.display()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub fn entry(&self) -> &DocumentRef {
|
||||
&self.entry
|
||||
}
|
||||
|
||||
/// Resolve an absolute path under the root into a safe relative path.
|
||||
pub fn relative_for(&self, absolute: &Path) -> ViewResult<SafeRelativePath> {
|
||||
let canonical = canonicalize(absolute, "document path")?;
|
||||
if !canonical.starts_with(&self.root) {
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: format!(
|
||||
"document {} is outside project root {}",
|
||||
canonical.display(),
|
||||
self.root.display()
|
||||
),
|
||||
});
|
||||
}
|
||||
let relative =
|
||||
canonical
|
||||
.strip_prefix(&self.root)
|
||||
.map_err(|_| ViewError::PathForbidden {
|
||||
detail: "document path is not under the project root".to_string(),
|
||||
})?;
|
||||
SafeRelativePath::parse(&relative.to_string_lossy())
|
||||
}
|
||||
|
||||
/// Absolute path for a safe relative path, with a final real-path check.
|
||||
pub fn absolute_for(&self, relative: &SafeRelativePath) -> ViewResult<PathBuf> {
|
||||
let joined = self.root.join(relative.to_path());
|
||||
let canonical = canonicalize(&joined, "document path")?;
|
||||
if !canonical.starts_with(&self.root) {
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: format!("{} escapes the project root", relative),
|
||||
});
|
||||
}
|
||||
Ok(canonical)
|
||||
}
|
||||
|
||||
/// Read exact source bytes. Never normalizes line endings or Unicode.
|
||||
pub fn read_source(&self, relative: &SafeRelativePath) -> ViewResult<Vec<u8>> {
|
||||
let absolute = self.absolute_for(relative)?;
|
||||
let metadata = std::fs::metadata(&absolute)
|
||||
.map_err(|err| ViewError::io(&format!("stat {}", absolute.display()), err))?;
|
||||
if !metadata.is_file() {
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: format!("{} is not a regular file", relative),
|
||||
});
|
||||
}
|
||||
if metadata.len() > MAX_SOURCE_BYTES {
|
||||
return Err(ViewError::ResourceLimit {
|
||||
detail: format!(
|
||||
"{} is {} bytes, above the {} byte View limit",
|
||||
relative,
|
||||
metadata.len(),
|
||||
MAX_SOURCE_BYTES
|
||||
),
|
||||
});
|
||||
}
|
||||
std::fs::read(&absolute)
|
||||
.map_err(|err| ViewError::io(&format!("read {}", absolute.display()), err))
|
||||
}
|
||||
|
||||
/// Read one document as UTF-8 text.
|
||||
pub fn read_source_text(&self, relative: &SafeRelativePath) -> ViewResult<String> {
|
||||
let bytes = self.read_source(relative)?;
|
||||
String::from_utf8(bytes).map_err(|err| ViewError::Io {
|
||||
detail: format!("{} is not valid UTF-8: {err}", relative),
|
||||
})
|
||||
}
|
||||
|
||||
/// Stable sorted list of `*.mq.md` documents under the root.
|
||||
pub fn list_documents(&self) -> ViewResult<Vec<SafeRelativePath>> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![self.root.clone()];
|
||||
while let Some(dir) = stack.pop() {
|
||||
let mut entries = Vec::new();
|
||||
for entry in std::fs::read_dir(&dir)
|
||||
.map_err(|err| ViewError::io(&format!("read dir {}", dir.display()), err))?
|
||||
{
|
||||
entries.push(entry.map_err(|err| ViewError::io("read dir entry", err))?);
|
||||
}
|
||||
entries.sort_by_key(|entry| entry.file_name());
|
||||
for entry in entries {
|
||||
let file_type = entry
|
||||
.file_type()
|
||||
.map_err(|err| ViewError::io("file type", err))?;
|
||||
if file_type.is_symlink() {
|
||||
// Never follow links while scanning; explicit file input is
|
||||
// canonicalized and boundary-checked separately.
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
if file_type.is_dir() {
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if SKIP_DIRS.contains(&name.as_ref()) {
|
||||
continue;
|
||||
}
|
||||
stack.push(path);
|
||||
continue;
|
||||
}
|
||||
if file_type.is_file() && is_marqdo_document(&path) {
|
||||
let relative = self.relative_for(&path)?;
|
||||
out.push(relative);
|
||||
if out.len() > MAX_DOCUMENTS {
|
||||
return Err(ViewError::ResourceLimit {
|
||||
detail: format!(
|
||||
"more than {MAX_DOCUMENTS} documents under project root"
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Resolve a browser-facing relative path to a document reference.
|
||||
pub fn document(&self, relative: &SafeRelativePath) -> ViewResult<DocumentRef> {
|
||||
Ok(DocumentRef {
|
||||
relative: relative.clone(),
|
||||
absolute: self.absolute_for(relative)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// `source_digest` of the exact bytes, matching Analysis `source_digest`.
|
||||
pub fn source_digest(&self, relative: &SafeRelativePath) -> ViewResult<String> {
|
||||
Ok(sha256_hex(&self.read_source(relative)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Discover the project root for a source file: nearest ancestor with
|
||||
/// `marqdo.yaml`, else the file's directory. The file itself is canonical.
|
||||
pub fn discover_project_root(file: &Path) -> PathBuf {
|
||||
let start = file.parent().unwrap_or_else(|| Path::new("/"));
|
||||
for ancestor in start.ancestors() {
|
||||
if ancestor.join("marqdo.yaml").is_file() {
|
||||
return ancestor.to_path_buf();
|
||||
}
|
||||
}
|
||||
start.to_path_buf()
|
||||
}
|
||||
|
||||
pub fn is_marqdo_document(path: &Path) -> bool {
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.map(|name| name.ends_with(".mq.md"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn choose_entry(root: &Path, documents: &[SafeRelativePath]) -> ViewResult<DocumentRef> {
|
||||
if documents.is_empty() {
|
||||
return Err(ViewError::PathForbidden {
|
||||
detail: format!("no .mq.md documents under {}", root.display()),
|
||||
});
|
||||
}
|
||||
if let Some(index) = documents.iter().find(|doc| doc.as_str() == "index.mq.md") {
|
||||
return Ok(DocumentRef {
|
||||
relative: index.clone(),
|
||||
absolute: root.join(index.to_path()),
|
||||
});
|
||||
}
|
||||
let first = documents[0].clone();
|
||||
Ok(DocumentRef {
|
||||
relative: first.clone(),
|
||||
absolute: root.join(first.to_path()),
|
||||
})
|
||||
}
|
||||
|
||||
fn canonicalize(path: &Path, what: &str) -> ViewResult<PathBuf> {
|
||||
// CLI arguments may legitimately contain `..`; the security boundary is
|
||||
// the canonicalized result staying under the canonicalized project root.
|
||||
// Browser/Export never reach this layer with raw user input: they must go
|
||||
// through `SafeRelativePath` first.
|
||||
path.canonicalize()
|
||||
.map_err(|err| ViewError::io(&format!("canonicalize {} ({what})", path.display()), err))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_unsafe_relative_paths() {
|
||||
for raw in [
|
||||
"",
|
||||
"/etc/passwd",
|
||||
"../secret",
|
||||
"a/../../b",
|
||||
"a\0b",
|
||||
"a\nb",
|
||||
"..",
|
||||
".",
|
||||
] {
|
||||
assert!(
|
||||
SafeRelativePath::parse(raw).is_err(),
|
||||
"expected rejection for {raw:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_harmless_forms() {
|
||||
assert_eq!(
|
||||
SafeRelativePath::parse("./docs/../x").unwrap_err().code(),
|
||||
"view.path_forbidden"
|
||||
);
|
||||
assert_eq!(
|
||||
SafeRelativePath::parse("./docs/index.mq.md")
|
||||
.unwrap()
|
||||
.as_str(),
|
||||
"docs/index.mq.md"
|
||||
);
|
||||
assert_eq!(
|
||||
SafeRelativePath::parse("docs\\index.mq.md")
|
||||
.unwrap()
|
||||
.as_str(),
|
||||
"docs/index.mq.md"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
//! Exact UTF-8 byte ↔ line/column ↔ JavaScript UTF-16 offset mapping.
|
||||
//!
|
||||
//! Core Analysis/Trace spans are half-open UTF-8 **byte** offsets into the
|
||||
//! original file bytes. Browsers count UTF-16 code units. This module is the
|
||||
//! only place that converts between them (RFC-VIEW-0001 §8.2).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// Half-open byte span `[start, end)` into one module's exact source bytes.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub struct SourceSpan {
|
||||
pub start: u64,
|
||||
pub end: u64,
|
||||
}
|
||||
|
||||
impl SourceSpan {
|
||||
pub fn new(start: u64, end: u64) -> Self {
|
||||
Self { start, end }
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.start == self.end
|
||||
}
|
||||
|
||||
pub fn len(&self) -> u64 {
|
||||
self.end.saturating_sub(self.start)
|
||||
}
|
||||
|
||||
pub fn contains(&self, other: SourceSpan) -> bool {
|
||||
self.start <= other.start && other.end <= self.end
|
||||
}
|
||||
|
||||
pub fn intersects(&self, other: SourceSpan) -> bool {
|
||||
self.start < other.end && other.start < self.end
|
||||
}
|
||||
|
||||
pub fn as_usize_range(&self) -> Option<std::ops::Range<usize>> {
|
||||
let start = usize::try_from(self.start).ok()?;
|
||||
let end = usize::try_from(self.end).ok()?;
|
||||
if start > end {
|
||||
return None;
|
||||
}
|
||||
Some(start..end)
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute lowercase hex SHA-256 of exact bytes (no normalization).
|
||||
pub fn sha256_hex(bytes: &[u8]) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(bytes);
|
||||
let digest = hasher.finalize();
|
||||
let mut out = String::with_capacity(64);
|
||||
for byte in digest {
|
||||
use std::fmt::Write as _;
|
||||
let _ = write!(out, "{byte:02x}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// SHA-256 with the `sha256:` prefix used by Analysis/Trace identity fields.
|
||||
pub fn sha256_prefixed(bytes: &[u8]) -> String {
|
||||
format!("sha256:{}", sha256_hex(bytes))
|
||||
}
|
||||
|
||||
/// Immutable source index built from the exact original bytes.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SourceIndex {
|
||||
/// Byte length of the source.
|
||||
len: usize,
|
||||
/// Byte offset of the start of every line (0-based line number).
|
||||
line_starts: Vec<usize>,
|
||||
/// Number of leading UTF-8 BOM bytes tolerated before the first content
|
||||
/// byte. Spans in Analysis are relative to the file bytes, so the BOM
|
||||
/// stays part of the index.
|
||||
bom_len: usize,
|
||||
}
|
||||
|
||||
impl SourceIndex {
|
||||
pub fn new(source: &str) -> Self {
|
||||
let bytes = source.as_bytes();
|
||||
let bom_len = if source.starts_with('\u{feff}') { 3 } else { 0 };
|
||||
let mut line_starts = vec![0usize];
|
||||
let mut index = bom_len;
|
||||
while index < bytes.len() {
|
||||
if bytes[index] == b'\n' {
|
||||
line_starts.push(index + 1);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
Self {
|
||||
len: bytes.len(),
|
||||
line_starts,
|
||||
bom_len,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len == 0
|
||||
}
|
||||
|
||||
pub fn bom_len(&self) -> usize {
|
||||
self.bom_len
|
||||
}
|
||||
|
||||
pub fn source_text<'a>(&self, source: &'a str, span: SourceSpan) -> Option<&'a str> {
|
||||
if !self.validate_span_bytes(source.as_bytes(), span) {
|
||||
return None;
|
||||
}
|
||||
let range = span.as_usize_range()?;
|
||||
source.get(range)
|
||||
}
|
||||
|
||||
/// True when the span is in range and both ends are UTF-8 code-point
|
||||
/// boundaries of the supplied original bytes.
|
||||
pub fn validate_span_bytes(&self, bytes: &[u8], span: SourceSpan) -> bool {
|
||||
let (Ok(start), Ok(end)) = (usize::try_from(span.start), usize::try_from(span.end)) else {
|
||||
return false;
|
||||
};
|
||||
if start > end || end > bytes.len() {
|
||||
return false;
|
||||
}
|
||||
is_char_boundary(bytes, start) && is_char_boundary(bytes, end)
|
||||
}
|
||||
|
||||
/// 1-based line and 1-based byte column for a byte offset, clamped to the
|
||||
/// file length. Column counts bytes, matching Core's presentation fields.
|
||||
pub fn line_col(&self, byte: usize) -> (usize, usize) {
|
||||
let byte = byte.min(self.len);
|
||||
let line_index = match self.line_starts.binary_search(&byte) {
|
||||
Ok(found) => found,
|
||||
Err(insert) => insert.saturating_sub(1),
|
||||
};
|
||||
let line_start = self.line_starts[line_index];
|
||||
(line_index + 1, byte - line_start + 1)
|
||||
}
|
||||
|
||||
/// Byte offset → number of UTF-16 code units before it (JS string index).
|
||||
pub fn utf16_offset(&self, source: &str, byte: usize) -> Option<usize> {
|
||||
if byte > source.len() || !is_char_boundary(source.as_bytes(), byte) {
|
||||
return None;
|
||||
}
|
||||
Some(source[..byte].encode_utf16().count())
|
||||
}
|
||||
|
||||
/// Byte offset for a UTF-16 offset, only when it lands on a boundary.
|
||||
pub fn byte_for_utf16(&self, source: &str, utf16: usize) -> Option<usize> {
|
||||
let mut units = 0usize;
|
||||
for (byte, ch) in source.char_indices() {
|
||||
if units == utf16 {
|
||||
return Some(byte);
|
||||
}
|
||||
if units > utf16 {
|
||||
return None;
|
||||
}
|
||||
units += ch.len_utf16();
|
||||
}
|
||||
if units == utf16 {
|
||||
Some(source.len())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// True when an arbitrary `(line, column)` from a Core diagnostic is inside
|
||||
/// the source index; line/column are presentation hints, spans are primary.
|
||||
pub fn line_col_in_range(&self, line: u64, column: u64) -> bool {
|
||||
let Ok(line) = usize::try_from(line) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(column) = usize::try_from(column) else {
|
||||
return false;
|
||||
};
|
||||
if line == 0 || column == 0 || line > self.line_starts.len() {
|
||||
return false;
|
||||
}
|
||||
let start = self.line_starts[line - 1];
|
||||
let end = self.line_starts.get(line).copied().unwrap_or(self.len);
|
||||
start + column - 1 <= end
|
||||
}
|
||||
}
|
||||
|
||||
fn is_char_boundary(bytes: &[u8], offset: usize) -> bool {
|
||||
if offset == 0 || offset >= bytes.len() {
|
||||
return offset <= bytes.len();
|
||||
}
|
||||
// UTF-8 continuation bytes start with 0b10.
|
||||
bytes[offset] & 0b1100_0000 != 0b1000_0000
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn maps_multibyte_and_emoji_offsets() {
|
||||
let source = "中文\nemoji🙂x\r\nlast";
|
||||
let index = SourceIndex::new(source);
|
||||
let emoji_byte = source.find('🙂').unwrap();
|
||||
assert_eq!(index.line_col(emoji_byte), (2, 6));
|
||||
let utf16 = index.utf16_offset(source, emoji_byte).unwrap();
|
||||
assert_eq!(index.byte_for_utf16(source, utf16), Some(emoji_byte));
|
||||
// Inside the emoji is not a char boundary.
|
||||
assert!(index.utf16_offset(source, emoji_byte + 1).is_none());
|
||||
let span = SourceSpan::new(emoji_byte as u64, (emoji_byte + 4) as u64);
|
||||
assert_eq!(index.source_text(source, span), Some("🙂"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_out_of_range_and_misaligned_spans() {
|
||||
let source = "# 数学";
|
||||
let index = SourceIndex::new(source);
|
||||
assert!(
|
||||
index.validate_span_bytes(source.as_bytes(), SourceSpan::new(0, source.len() as u64))
|
||||
);
|
||||
assert!(!index.validate_span_bytes(
|
||||
source.as_bytes(),
|
||||
SourceSpan::new(0, source.len() as u64 + 1)
|
||||
));
|
||||
assert!(!index.validate_span_bytes(source.as_bytes(), SourceSpan::new(2, 1)));
|
||||
// 2 is the middle of the 3-byte 字/数? Either way it is not a boundary
|
||||
// for the CJK character starting at 2..5; check the interior byte 3.
|
||||
assert!(!index.validate_span_bytes(source.as_bytes(), SourceSpan::new(3, 5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digest_is_exact_bytes() {
|
||||
assert_eq!(
|
||||
sha256_hex(b""),
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
);
|
||||
assert_eq!(
|
||||
sha256_prefixed(b"a"),
|
||||
"sha256:ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bom_is_still_indexed() {
|
||||
let source = "\u{feff}# hi";
|
||||
let index = SourceIndex::new(source);
|
||||
assert_eq!(index.bom_len(), 3);
|
||||
assert_eq!(index.line_col(3), (1, 4));
|
||||
assert_eq!(
|
||||
index.source_text(source, SourceSpan::new(0, 3)),
|
||||
Some("\u{feff}")
|
||||
);
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
//! Product/protocol version negotiation with the frozen CLI.
|
||||
//!
|
||||
//! Version axes are independent (RFC-VIEW-0001 §4): product SemVer,
|
||||
//! Analysis major, Trace major and Tool protocol. We never infer one from
|
||||
//! another and never silently fall back to a latest-looking JSON.
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use semver::Version;
|
||||
|
||||
/// Product range this View build targets. Must match `tool.json`.
|
||||
pub const PRODUCT_RANGE: &str = ">=3.0.0-beta.1,<4.0.0";
|
||||
|
||||
/// Lowest compatible product version (inclusive).
|
||||
pub const MIN_PRODUCT: &str = "3.0.0-beta.1";
|
||||
|
||||
pub const TOOL_PROTOCOL: u32 = 1;
|
||||
pub const ANALYSIS_PROTOCOL: u32 = 2;
|
||||
pub const TRACE_PROTOCOL: u32 = 2;
|
||||
|
||||
/// Environment variables injected by CLI Tool Protocol v1.
|
||||
pub const ENV_MARQDO_BIN: &str = "MARQDO_BIN";
|
||||
pub const ENV_TOOL_PROTOCOL: &str = "MARQDO_TOOL_PROTOCOL";
|
||||
pub const ENV_PROTOCOL_ANALYSIS: &str = "MARQDO_PROTOCOL_ANALYSIS";
|
||||
pub const ENV_PROTOCOL_TRACE: &str = "MARQDO_PROTOCOL_TRACE";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CoreVersion {
|
||||
pub version: Version,
|
||||
/// Exact `marqdo --version` first line, kept for evidence output.
|
||||
pub raw: String,
|
||||
}
|
||||
|
||||
/// Parse the output of `marqdo --version` (`marqdo 3.0.0-beta.1`).
|
||||
pub fn parse_version_output(output: &str) -> ViewResult<CoreVersion> {
|
||||
let line = output
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|line| !line.is_empty())
|
||||
.ok_or_else(|| ViewError::ProtocolIncompatible {
|
||||
detail: "core printed no version text".to_string(),
|
||||
})?;
|
||||
let token = line
|
||||
.split_whitespace()
|
||||
.last()
|
||||
.ok_or_else(|| ViewError::ProtocolIncompatible {
|
||||
detail: format!("cannot parse core version from {line:?}"),
|
||||
})?;
|
||||
let version = Version::parse(token).map_err(|err| ViewError::ProtocolIncompatible {
|
||||
detail: format!("core version {token:?} is not SemVer: {err}"),
|
||||
})?;
|
||||
Ok(CoreVersion {
|
||||
version,
|
||||
raw: line.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// True when `version` is inside the product range without relying on
|
||||
/// prerelease quirks of `semver::VersionReq`: any 3.x at or above the first
|
||||
/// beta is accepted, so a later `3.1.0-beta.1` keeps working.
|
||||
pub fn product_is_compatible(version: &Version) -> bool {
|
||||
let min = Version::parse(MIN_PRODUCT).expect("MIN_PRODUCT is valid SemVer");
|
||||
version.major == 3 && version >= &min
|
||||
}
|
||||
|
||||
/// Validate the negotiated environment for Tool Protocol v1.
|
||||
///
|
||||
/// Absence of `MARQDO_PROTOCOL_*` is allowed for a directly-run development
|
||||
/// binary (`--marqdo-bin`), but presence of an unknown major is a hard error.
|
||||
pub fn negotiate_protocol_env(
|
||||
tool_protocol: Option<&str>,
|
||||
analysis_protocol: Option<&str>,
|
||||
trace_protocol: Option<&str>,
|
||||
) -> ViewResult<()> {
|
||||
if let Some(raw) = tool_protocol {
|
||||
let value = parse_env_u32(ENV_TOOL_PROTOCOL, raw)?;
|
||||
if value != TOOL_PROTOCOL {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"{ENV_TOOL_PROTOCOL}={value} is not supported (this View implements protocol {TOOL_PROTOCOL})"
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(raw) = analysis_protocol {
|
||||
let value = parse_env_u32(ENV_PROTOCOL_ANALYSIS, raw)?;
|
||||
if value != ANALYSIS_PROTOCOL {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"{ENV_PROTOCOL_ANALYSIS}={value} is not supported (this View requires Analysis v{ANALYSIS_PROTOCOL})"
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(raw) = trace_protocol {
|
||||
let value = parse_env_u32(ENV_PROTOCOL_TRACE, raw)?;
|
||||
if value != TRACE_PROTOCOL {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"{ENV_PROTOCOL_TRACE}={value} is not supported (this View requires Trace v{TRACE_PROTOCOL})"
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_env_u32(name: &str, raw: &str) -> ViewResult<u32> {
|
||||
raw.trim()
|
||||
.parse::<u32>()
|
||||
.map_err(|_| ViewError::ProtocolIncompatible {
|
||||
detail: format!("{name}={raw:?} is not a positive integer protocol version"),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_official_version_line() {
|
||||
let version = parse_version_output("marqdo 3.0.0-beta.1\n").unwrap();
|
||||
assert_eq!(version.version.to_string(), "3.0.0-beta.1");
|
||||
assert!(product_is_compatible(&version.version));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_stable_only_reinterpretation() {
|
||||
// 2.9.1 is the old product line and must never be accepted.
|
||||
let old = Version::parse("2.9.1").unwrap();
|
||||
assert!(!product_is_compatible(&old));
|
||||
// A future major is rejected too.
|
||||
assert!(!product_is_compatible(&Version::parse("4.0.0").unwrap()));
|
||||
// Later prereleases in the 3.x line remain compatible.
|
||||
assert!(product_is_compatible(
|
||||
&Version::parse("3.1.0-beta.1").unwrap()
|
||||
));
|
||||
assert!(product_is_compatible(&Version::parse("3.0.0").unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negotiates_known_protocols_only() {
|
||||
assert!(negotiate_protocol_env(Some("1"), Some("2"), Some("2")).is_ok());
|
||||
assert!(negotiate_protocol_env(None, None, None).is_ok());
|
||||
assert!(negotiate_protocol_env(Some("2"), None, None).is_err());
|
||||
assert!(negotiate_protocol_env(None, Some("1"), None).is_err());
|
||||
assert!(negotiate_protocol_env(None, None, Some("3")).is_err());
|
||||
assert!(negotiate_protocol_env(None, Some("two"), None).is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user