refactor(PR-02): protocol/reader architecture, /api/documents and reader IA

- migrate crate to RFC-0002 §5.3 Reader layout: src/protocol/{analysis_v2,
  trace_v2,tool_v1}.rs, src/reader/{source,markdown,model,assemble,render,
  assets}.rs, src/config.rs; lib.rs is the composition root; delete app/project/
  semantic/trace/document/presentation/source_map/render/assets top-level files
- split presentation into model (types) and assemble (merge/stale/DocumentService)
- merge controlled project root/path boundary and UTF-8 byte spans into
  reader/source.rs; move view.json config to config.rs
- replace GET /api/document with read-only GET /api/documents (documents list +
  current outline/function/analysis summary) and add contract tests
- reading UI: drop variable/memory placeholder actions, keep one explicit
  unsupported explanation, add simple dark theme toggle over the single token
  layer; assert via rendering test
- reorganize tests into Cargo [[test]] suites tests/contract and
  tests/integration; record docs/evidence/PR-02
- unit 41 + contract 41 + integration 33 all pass; clippy clean
This commit is contained in:
cflmy committed 2026-11-22 13:08:09 +08:00
1 parent 5a61788bc9
commit 5c9a313424
43 files changed
+1222 -936

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
//! View-only site configuration (`view.json`).
//!
//! This is **not** a Marqdo language protocol and cannot grant execution. Only
//! welcome/site_title/theme are read, and the welcome path is subject to the
//! same project-root boundary (RFC-VIEW-0002 §4.2/§5.3).
use crate::error::{ViewError, ViewResult};
use crate::reader::source::SafeRelativePath;
use std::path::Path;
/// Optional View-only site configuration (`view.json`).
///
/// This is **not** a Marqdo language protocol and cannot grant execution: only
/// the fields below are read, and the welcome path is still subject to the same
/// project-root boundary (RFC-VIEW-0001 §9.4).
#[derive(Debug, Clone, Default)]
pub struct ViewConfig {
pub welcome: Option<SafeRelativePath>,
pub site_title: Option<String>,
pub theme: Option<String>,
}
impl ViewConfig {
pub fn load(root: &Path) -> ViewResult<Self> {
let path = root.join("view.json");
let metadata = match std::fs::metadata(&path) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
Err(err) => return Err(ViewError::io(&format!("stat {}", path.display()), err)),
};
if !metadata.is_file() || metadata.len() > 64 * 1024 {
return Err(ViewError::PathForbidden {
detail: "view.json must be a regular file under 64 KiB".to_string(),
});
}
let bytes = std::fs::read(&path)
.map_err(|err| ViewError::io(&format!("read {}", path.display()), err))?;
#[derive(serde::Deserialize)]
struct RawConfig {
#[serde(default)]
schema: String,
#[serde(default)]
schema_version: u32,
#[serde(default)]
welcome: Option<String>,
#[serde(default)]
site_title: Option<String>,
#[serde(default)]
theme: Option<String>,
}
let raw: RawConfig = serde_json::from_slice(&bytes).map_err(|err| ViewError::Io {
detail: format!("view.json is not valid JSON: {err}"),
})?;
if raw.schema != "marqdo.view-config" || raw.schema_version != 1 {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unsupported view.json schema {:?} version {}; expected marqdo.view-config v1",
raw.schema, raw.schema_version
),
});
}
let welcome = match raw.welcome {
Some(path) => Some(SafeRelativePath::parse(&path)?),
None => None,
};
if let Some(welcome) = &welcome {
if !root.join(welcome.to_path()).is_file() {
return Err(ViewError::PathForbidden {
detail: format!(
"view.json welcome file {welcome} does not exist under the project root"
),
});
}
}
let site_title = raw
.site_title
.map(|title| title.trim().to_string())
.filter(|title| !title.is_empty() && title.chars().count() <= 80);
let theme = raw
.theme
.map(|theme| theme.trim().to_string())
.filter(|theme| theme == "botanical" || theme == "paper");
Ok(Self {
welcome,
site_title,
theme,
})
}
}
+149 -10
View File
@@ -10,9 +10,9 @@
//! 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 crate::protocol::tool_v1::{self, CoreVersion};
use crate::reader::source::{sha256_hex, sha256_prefixed};
use crate::reader::source::{Project, SafeRelativePath};
use serde::{Deserialize, Serialize};
use std::ffi::OsString;
use std::io::Read;
@@ -240,9 +240,9 @@ impl CoreClient {
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(),
tool: std::env::var(tool_v1::ENV_TOOL_PROTOCOL).ok(),
analysis: std::env::var(tool_v1::ENV_PROTOCOL_ANALYSIS).ok(),
trace: std::env::var(tool_v1::ENV_PROTOCOL_TRACE).ok(),
},
})
}
@@ -265,7 +265,7 @@ impl CoreClient {
/// 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(
tool_v1::negotiate_protocol_env(
self.protocol_env.tool.as_deref(),
self.protocol_env.analysis.as_deref(),
self.protocol_env.trace.as_deref(),
@@ -285,13 +285,13 @@ impl CoreClient {
),
});
}
let version = version::parse_version_output(&output.stdout)?;
if !version::product_is_compatible(&version.version) {
let version = tool_v1::parse_version_output(&output.stdout)?;
if !tool_v1::product_is_compatible(&version.version) {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"core {} is outside the supported range {}",
version.version,
version::PRODUCT_RANGE
tool_v1::PRODUCT_RANGE
),
});
}
@@ -655,6 +655,145 @@ fn summarize_stderr(stderr: &str) -> String {
}
}
// ---------------------------------------------------------------------------
// `marqdo view verify`: static Analysis/source binding check. Never executes.
// ---------------------------------------------------------------------------
use crate::cli::{RuntimeOpts, VerifyArgs};
use crate::protocol::analysis_v2;
pub fn verify_command(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 = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
detail: format!("{entry} is not valid UTF-8: {err}"),
})?;
let source_index = crate::reader::source::SourceIndex::new(&source);
let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?;
let core_version = client.negotiate()?;
let response = client.check(
&project,
&entry,
&CheckOptions {
refs: args.refs,
timeout: None,
},
)?;
let check = match response {
CheckResponse {
success: false,
diagnostics,
exit_code,
..
} => {
let first = diagnostics
.first()
.map(|diagnostic| {
format!(
"{}: {}",
if diagnostic.code.is_empty() {
"diagnostic"
} else {
&diagnostic.code
},
diagnostic.message
)
})
.unwrap_or_else(|| "no diagnostic detail".to_string());
return Err(ViewError::AnalysisFailed {
detail: format!(
"`marqdo check` failed with exit code {exit_code} ({} diagnostic(s)); first: {first}",
diagnostics.len()
),
});
}
CheckResponse {
analysis: Some(check),
..
} => check,
CheckResponse { analysis: None, .. } => {
return Err(ViewError::AnalysisFailed {
detail: "`marqdo check` succeeded but emitted no Analysis".to_string(),
})
}
};
let verified = analysis_v2::verify_analysis(
&check.analysis_bytes,
&source,
&source_index,
entry.as_str(),
)?;
let projection = &verified.projection;
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": tool_v1::PRODUCT_RANGE,
},
"analysis": {
"schema": "marqdo.analysis",
"schema_version": tool_v1::ANALYSIS_PROTOCOL,
"digest": projection.analysis_digest,
"producer_version": projection.producer_version,
"markdown_profile": projection.markdown_profile,
"functions": projection.functions.len(),
"units": projection.units.len(),
"diagnostics": projection.diagnostics.len(),
},
"project": {
"root_id": projection.project_root_id,
"identity_kind": projection.identity_kind,
"lock_digest": projection.lock_digest,
"stdlib_version": projection.stdlib_version,
},
"document": {
"relative_path": entry.as_str(),
"module_id": projection.module_id,
"source_digest": projection.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,
tool_v1::PRODUCT_RANGE
);
println!(
"project: {} ({})",
projection.project_root_id, projection.identity_kind
);
println!("document: {entry}");
println!(
"analysis: schema=marqdo.analysis v2 modules={} functions={} digest={}",
projection.modules.len(),
projection.functions.len(),
projection.analysis_digest
);
println!("source digest: match");
println!("result: PASS (static only; document not executed)");
}
Ok(0)
}
#[cfg(test)]
mod tests {
use super::*;
+14 -13
View File
@@ -1,15 +1,15 @@
//! Pure static site export.
//!
//! Export uses the same `AppContext::load` (static `check` only) and the same
//! Export uses the same `DocumentService::load` (static `check` only) and the same
//! `ReaderRenderer` as Live; it never calls `run`, never starts a provider and
//! never writes into the source project (RFC-VIEW-0001 §11.3).
use crate::app::AppContext;
use crate::assets::AssetBundle;
use crate::error::{ViewError, ViewResult};
use crate::project::SafeRelativePath;
use crate::render::ReaderRenderer;
use crate::source_map::sha256_hex;
use crate::reader::assemble::DocumentService;
use crate::reader::assets::AssetBundle;
use crate::reader::render::ReaderRenderer;
use crate::reader::source::sha256_hex;
use crate::reader::source::SafeRelativePath;
use std::path::{Path, PathBuf};
const MANIFEST_SCHEMA: &str = "marqdo.view-export";
@@ -28,7 +28,7 @@ pub struct ExportSummary {
pub manifest_sha256: String,
}
pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult<ExportSummary> {
pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<ExportSummary> {
let bundle = AssetBundle::get();
let renderer = ReaderRenderer::new();
let root = context.project().root().to_path_buf();
@@ -89,7 +89,7 @@ pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult<Expor
let model = context.load(relative)?;
let depth = relative.as_str().split('/').count();
let context =
crate::render::RenderContext::static_export(depth, !options.no_annotations);
crate::reader::render::RenderContext::static_export(depth, !options.no_annotations);
let page = renderer.render(&model, &context);
let page_path = pages_dir.join(format!("{}.html", relative.as_str()));
if let Some(parent) = page_path.parent() {
@@ -119,7 +119,8 @@ pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult<Expor
// index.html is the same renderer output with site-root depth.
let entry_model = context.load(&entry)?;
let entry_context = crate::render::RenderContext::static_export(0, !options.no_annotations);
let entry_context =
crate::reader::render::RenderContext::static_export(0, !options.no_annotations);
let index_page = renderer.render(&entry_model, &entry_context);
let index_path = staging.join("index.html");
std::fs::write(&index_path, index_page.html.as_bytes())
@@ -145,10 +146,10 @@ pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult<Expor
"version": env!("CARGO_PKG_VERSION"),
},
"compatibility": {
"marqdo": crate::version::PRODUCT_RANGE,
"tool_protocol": crate::version::TOOL_PROTOCOL,
"analysis": crate::version::ANALYSIS_PROTOCOL,
"trace": crate::version::TRACE_PROTOCOL,
"marqdo": crate::protocol::tool_v1::PRODUCT_RANGE,
"tool_protocol": crate::protocol::tool_v1::TOOL_PROTOCOL,
"analysis": crate::protocol::tool_v1::ANALYSIS_PROTOCOL,
"trace": crate::protocol::tool_v1::TRACE_PROTOCOL,
"markdown_profile": "marqdo.md.v1",
},
"core_version": entry_model.core_version,
+53 -19
View File
@@ -1,38 +1,72 @@
//! marqdo-view library: a single package with one presentation pipeline.
//! marqdo-view library: one package, one presentation pipeline, one renderer.
//!
//! 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.
//! Dependency direction (RFC-VIEW-0002 §5.1/§5.4):
//! `CLI/Server → Reader(assemble) → Protocol(Analysis/Trace) + CoreClient`,
//! and `Reader(model) → Renderer → Assets`. `Execution` may only be reached
//! from an explicit `POST /api/runs` handler; page loads and export never form
//! an execution edge.
pub mod app;
pub mod assets;
pub mod cli;
pub mod config;
pub mod core_client;
pub mod document;
pub mod error;
pub mod export;
pub mod presentation;
pub mod project;
pub mod render;
pub mod semantic;
pub mod protocol;
pub mod reader;
pub mod server;
pub mod source_map;
pub mod trace;
pub mod version;
pub use cli::Cli;
pub use error::{ViewError, ViewResult};
use cli::{ExportArgs, RuntimeOpts};
use export::ExportOptions;
use reader::assemble::DocumentService;
/// 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),
Some(cli::Command::Verify(args)) => core_client::verify_command(&opts, &args),
Some(cli::Command::Export(args)) => export_command(&opts, &args),
None => browse_command(&opts),
}
}
/// `marqdo view [PATH]`: open the read-only Live reader. Never executes.
fn browse_command(opts: &RuntimeOpts) -> ViewResult<i32> {
let path = opts
.path
.clone()
.unwrap_or_else(|| std::path::PathBuf::from("."));
let service = DocumentService::open(&path, opts.marqdo_bin.as_deref())?;
crate::server::serve(service, opts)
}
/// `marqdo view export PATH --out DIR`: static export through the same Reader
/// model. The export path has no execution capability by type (RFC §5.4).
fn export_command(opts: &RuntimeOpts, args: &ExportArgs) -> ViewResult<i32> {
let path = args
.path
.clone()
.or_else(|| opts.path.clone())
.unwrap_or_else(|| std::path::PathBuf::from("."));
let service = DocumentService::open(&path, opts.marqdo_bin.as_deref())?;
let summary = export::export(
&service,
&ExportOptions {
out: args.out.clone(),
no_annotations: args.no_annotations,
},
)?;
println!(
"marqdo view export: {} page(s), {} file(s) → {}",
summary.pages,
summary.files,
summary.out.display()
);
println!("manifest: sha256:{}", summary.manifest_sha256);
println!("executed: false (纯静态导出,未运行任何文档)");
Ok(0)
}
@@ -7,8 +7,7 @@
//! instead of being pointed at nearby text (RFC-VIEW-0001 §4.3, §8.2).
use crate::error::{ViewError, ViewResult};
use crate::source_map::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
use crate::version;
use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
use serde::Deserialize;
use serde_json::Value;
@@ -549,12 +548,12 @@ pub fn verify_analysis(
detail: format!("unexpected Analysis schema {:?}", raw.schema),
});
}
if raw.schema_version != version::ANALYSIS_PROTOCOL {
if raw.schema_version != crate::protocol::tool_v1::ANALYSIS_PROTOCOL {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis schema_version {} is not supported (View implements v{})",
raw.schema_version,
version::ANALYSIS_PROTOCOL
crate::protocol::tool_v1::ANALYSIS_PROTOCOL
),
});
}
+8
View File
@@ -0,0 +1,8 @@
//! Public protocol adapters consumed by View.
//!
//! These modules are a **consumer** of the published CLI formats, never a
//! second publisher or implementation of them (RFC-VIEW-0002 §5.3).
pub mod analysis_v2;
pub mod tool_v1;
pub mod trace_v2;
File renamed without changes.
+4 -4
View File
@@ -7,8 +7,8 @@
//! states, never invented (RFC-VIEW-0001 §4.4, §12).
use crate::error::{ViewError, ViewResult};
use crate::semantic::{ModuleSummary, SemanticProjection};
use crate::source_map::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
use crate::protocol::analysis_v2::{ModuleSummary, SemanticProjection};
use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
use serde::Deserialize;
use serde_json::Value;
@@ -343,12 +343,12 @@ pub fn verify_trace(input: TraceVerificationInput<'_>) -> ViewResult<VerifiedRun
detail: format!("unexpected Trace schema {:?}", raw.schema),
});
}
if raw.schema_version != crate::version::TRACE_PROTOCOL {
if raw.schema_version != crate::protocol::tool_v1::TRACE_PROTOCOL {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Trace schema_version {} is not supported (View implements v{})",
raw.schema_version,
crate::version::TRACE_PROTOCOL
crate::protocol::tool_v1::TRACE_PROTOCOL
),
});
}
+147 -190
View File
@@ -1,25 +1,148 @@
//! Application layer: turns parsed commands into use cases.
//! Assembly of the one `PresentationModel`.
//!
//! No HTML is built here and no Markdown semantics are decided here. Browse and
//! (later) Export call the same `load` + one `ReaderRenderer`.
//! Merges the raw document, verified Analysis v2, diagnostics and an optional
//! verified Trace v2 run into the model; decides stale/revoked semantics here
//! and nowhere else (RFC-VIEW-0002 §5.2/§5.4).
use crate::config::ViewConfig;
use crate::protocol::analysis_v2::{CoreDiagnostic, SemanticProjection};
use crate::protocol::trace_v2::VerifiedRun;
use crate::reader::markdown::{DocumentIdentity, DocumentModel};
use crate::reader::model::{
Navigation, OutlineEntry, OutlineKind, PresentationModel, SourceStatus,
};
use crate::reader::source::{Project, SafeRelativePath};
use crate::cli::{ExportArgs, RuntimeOpts, VerifyArgs};
use crate::core_client::{
CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic, RunOptions, SandboxMode,
};
use crate::document::{DocumentIdentity, DocumentModel};
use crate::error::{ViewError, ViewResult};
use crate::export::{export as run_export, ExportOptions};
use crate::presentation::{self, BuildInput, Navigation, PresentationModel, SourceStatus};
use crate::project::{Project, SafeRelativePath, ViewConfig};
use crate::semantic::{self, CoreDiagnostic};
use crate::trace::{self, TraceVerificationInput, VerifiedRun};
use crate::version;
use crate::protocol::analysis_v2;
use crate::protocol::trace_v2::{self, TraceVerificationInput};
use crate::reader::model::{anchor_for_span, PRESENTATION_VERSION};
/// Process-wide context for one browsed project: root, optional site config and
/// an optional negotiated frozen core. A missing core degrades to prose only;
/// an incompatible protocol is a hard error (RFC §4).
pub struct AppContext {
/// Input to the one builder. `analysis` is already protocol/byte verified.
pub struct BuildInput<'a> {
pub document: DocumentModel,
pub analysis: Option<&'a crate::protocol::analysis_v2::VerifiedAnalysis>,
pub status: SourceStatus,
pub status_note: Option<String>,
pub diagnostics: Vec<CoreDiagnostic>,
pub navigation: Navigation,
pub core_version: Option<String>,
pub run: Option<&'a crate::protocol::trace_v2::VerifiedRun>,
}
pub fn build(input: BuildInput<'_>) -> PresentationModel {
let BuildInput {
mut document,
analysis,
status,
status_note,
mut diagnostics,
navigation,
core_version,
run,
} = input;
let semantic = analysis.map(|verified| verified.projection.clone());
if let Some(projection) = &semantic {
document.identity = DocumentIdentity {
project_root_id: projection.project_root_id.clone(),
module_id: projection.module_id.clone(),
relative_path: projection.relative_path.clone(),
source_sha256: projection.source_digest.clone(),
};
for diagnostic in &projection.diagnostics {
if !diagnostics.iter().any(|existing| {
existing.code == diagnostic.code
&& existing.message == diagnostic.message
&& existing.span == diagnostic.span
}) {
diagnostics.push(diagnostic.clone());
}
}
}
let warnings = semantic
.as_ref()
.map(|projection| projection.warnings.clone())
.unwrap_or_default();
let outline = semantic.as_ref().map(build_outline).unwrap_or_default();
PresentationModel {
version: PRESENTATION_VERSION,
title: document.title(),
document,
semantic,
source_status: status,
status_note,
diagnostics,
warnings,
navigation,
outline,
core_version,
run: run.map(|verified| verified.projection.clone()),
}
}
fn build_outline(projection: &SemanticProjection) -> Vec<OutlineEntry> {
let mut entries = Vec::new();
for function in &projection.functions {
let params = if function.signature.params.is_empty() {
String::new()
} else {
function
.signature
.params
.iter()
.map(|param| {
if param.ty.is_empty() {
param.name.clone()
} else {
format!("{}: {}", param.name, param.ty)
}
})
.collect::<Vec<_>>()
.join(", ")
};
let detail = if params.is_empty() {
"无参数".to_string()
} else {
format!("params({params})")
};
entries.push(OutlineEntry {
label: function.local_name.clone(),
anchor: anchor_for_span(function.heading_span.start, function.heading_span.end),
detail,
kind: OutlineKind::Function,
});
}
for unit in &projection.units {
let kind = match unit.kind {
crate::protocol::analysis_v2::UnitKind::Knowledge if unit.level >= 2 => {
OutlineKind::Knowledge
}
crate::protocol::analysis_v2::UnitKind::Section => OutlineKind::Section,
_ => continue,
};
if unit.name.is_empty() {
continue;
}
entries.push(OutlineEntry {
label: unit.name.clone(),
anchor: anchor_for_span(unit.span.start, unit.span.end),
detail: if unit.level == 2 {
"知识单元".to_string()
} else {
"章节".to_string()
},
kind,
});
}
entries
}
pub struct DocumentService {
project: Project,
config: ViewConfig,
core: Option<CoreClient>,
@@ -27,7 +150,7 @@ pub struct AppContext {
core_note: Option<String>,
}
impl AppContext {
impl DocumentService {
pub fn open(path: &std::path::Path, marqdo_bin: Option<&std::path::Path>) -> ViewResult<Self> {
let project = Project::open(path)?;
let config = ViewConfig::load(project.root())?;
@@ -126,7 +249,7 @@ impl AppContext {
success: true,
analysis: Some(check),
..
} => match semantic::verify_analysis(
} => match analysis_v2::verify_analysis(
&check.analysis_bytes,
&document.source,
&document.source_index,
@@ -172,7 +295,7 @@ impl AppContext {
})
} else {
Some(VerifiedRun {
projection: trace::stale_projection(
projection: trace_v2::stale_projection(
&run.projection.analysis_digest,
&document.source_index,
),
@@ -180,7 +303,7 @@ impl AppContext {
}
}
(Some(run), None) => Some(VerifiedRun {
projection: trace::stale_projection(
projection: trace_v2::stale_projection(
&run.projection.analysis_digest,
&document.source_index,
),
@@ -188,7 +311,7 @@ impl AppContext {
(None, _) => None,
};
Ok(presentation::build(BuildInput {
Ok(build(BuildInput {
document,
analysis: verified.as_ref(),
status,
@@ -208,11 +331,11 @@ impl AppContext {
detail: "没有可用的冻结核心(MARQDO_BIN),运行被拒绝".to_string(),
})?;
let source_bytes = self.project.read_source(relative)?;
let source_digest = crate::source_map::sha256_hex(&source_bytes);
let source_digest = crate::reader::source::sha256_hex(&source_bytes);
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
detail: format!("{relative} is not valid UTF-8: {err}"),
})?;
let source_index = crate::source_map::SourceIndex::new(&source);
let source_index = crate::reader::source::SourceIndex::new(&source);
let run = client.run(
&self.project,
@@ -237,13 +360,13 @@ impl AppContext {
let check = response.analysis.ok_or_else(|| ViewError::AnalysisFailed {
detail: "运行后的静态检查失败,无法绑定 Trace".to_string(),
})?;
let verified = semantic::verify_analysis(
let verified = analysis_v2::verify_analysis(
&check.analysis_bytes,
&source,
&source_index,
relative.as_str(),
)?;
let verified_run = trace::verify_trace(TraceVerificationInput {
let verified_run = trace_v2::verify_trace(TraceVerificationInput {
trace_bytes: &trace_bytes,
analysis_bytes: &check.analysis_bytes,
semantic: &verified.projection,
@@ -267,172 +390,6 @@ pub struct ExecutedRun {
pub analysis_digest: String,
}
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 = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
detail: format!("{entry} is not valid UTF-8: {err}"),
})?;
let source_index = crate::source_map::SourceIndex::new(&source);
let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?;
let core_version = client.negotiate()?;
let response = client.check(
&project,
&entry,
&CheckOptions {
refs: args.refs,
timeout: None,
},
)?;
let check = match response {
CheckResponse {
success: false,
diagnostics,
exit_code,
..
} => {
let first = diagnostics
.first()
.map(|diagnostic| {
format!(
"{}: {}",
if diagnostic.code.is_empty() {
"diagnostic"
} else {
&diagnostic.code
},
diagnostic.message
)
})
.unwrap_or_else(|| "no diagnostic detail".to_string());
return Err(ViewError::AnalysisFailed {
detail: format!(
"`marqdo check` failed with exit code {exit_code} ({} diagnostic(s)); first: {first}",
diagnostics.len()
),
});
}
CheckResponse {
analysis: Some(check),
..
} => check,
CheckResponse { analysis: None, .. } => {
return Err(ViewError::AnalysisFailed {
detail: "`marqdo check` succeeded but emitted no Analysis".to_string(),
})
}
};
let verified = semantic::verify_analysis(
&check.analysis_bytes,
&source,
&source_index,
entry.as_str(),
)?;
let projection = &verified.projection;
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": version::ANALYSIS_PROTOCOL,
"digest": projection.analysis_digest,
"producer_version": projection.producer_version,
"markdown_profile": projection.markdown_profile,
"functions": projection.functions.len(),
"units": projection.units.len(),
"diagnostics": projection.diagnostics.len(),
},
"project": {
"root_id": projection.project_root_id,
"identity_kind": projection.identity_kind,
"lock_digest": projection.lock_digest,
"stdlib_version": projection.stdlib_version,
},
"document": {
"relative_path": entry.as_str(),
"module_id": projection.module_id,
"source_digest": projection.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: {} ({})",
projection.project_root_id, projection.identity_kind
);
println!("document: {entry}");
println!(
"analysis: schema=marqdo.analysis v2 modules={} functions={} digest={}",
projection.modules.len(),
projection.functions.len(),
projection.analysis_digest
);
println!("source digest: match");
println!("result: PASS (static only; document not executed)");
}
Ok(0)
}
pub fn browse(opts: &RuntimeOpts) -> ViewResult<i32> {
let path = opts
.path
.clone()
.unwrap_or_else(|| std::path::PathBuf::from("."));
let context = AppContext::open(&path, opts.marqdo_bin.as_deref())?;
crate::server::serve(context, opts)
}
pub fn export(opts: &RuntimeOpts, args: &ExportArgs) -> ViewResult<i32> {
let path = args
.path
.clone()
.or_else(|| opts.path.clone())
.unwrap_or_else(|| std::path::PathBuf::from("."));
let context = AppContext::open(&path, opts.marqdo_bin.as_deref())?;
let summary = run_export(
&context,
&ExportOptions {
out: args.out.clone(),
no_annotations: args.no_annotations,
},
)?;
println!(
"marqdo view export: {} page(s), {} file(s) → {}",
summary.pages,
summary.files,
summary.out.display()
);
println!("manifest: sha256:{}", summary.manifest_sha256);
println!("executed: false (纯静态导出,未运行任何文档)");
Ok(0)
}
fn generic_core_note(err: &ViewError) -> String {
match err.code() {
"view.core_missing" => {
+9 -9
View File
@@ -4,7 +4,7 @@
//! asset carries its SHA-256; browser URLs use a hash prefix so a changed asset
//! can never be confused with a cached older one.
use crate::source_map::sha256_hex;
use crate::reader::source::sha256_hex;
use std::collections::HashMap;
use std::sync::OnceLock;
@@ -45,31 +45,31 @@ impl AssetBundle {
"reader",
"css",
"text/css; charset=utf-8",
include_bytes!("../assets/reader.css"),
include_bytes!("../../assets/reader.css"),
),
asset(
"reader",
"js",
"text/javascript; charset=utf-8",
include_bytes!("../assets/reader.js"),
include_bytes!("../../assets/reader.js"),
),
asset(
"logo",
"svg",
"image/svg+xml",
include_bytes!("../assets/logo.svg"),
include_bytes!("../../assets/logo.svg"),
),
asset(
"blossom",
"webp",
"image/webp",
include_bytes!("../assets/blossom.webp"),
include_bytes!("../../assets/blossom.webp"),
),
asset(
"feather",
"webp",
"image/webp",
include_bytes!("../assets/feather.webp"),
include_bytes!("../../assets/feather.webp"),
),
];
let mut by_hashed_name = HashMap::new();
@@ -183,15 +183,15 @@ mod tests {
let bundle = AssetBundle::get();
assert_eq!(
bundle.css().sha256,
sha256_hex(include_bytes!("../assets/reader.css"))
sha256_hex(include_bytes!("../../assets/reader.css"))
);
assert_eq!(
bundle.js().sha256,
sha256_hex(include_bytes!("../assets/reader.js"))
sha256_hex(include_bytes!("../../assets/reader.js"))
);
assert_eq!(
bundle.logo().sha256,
sha256_hex(include_bytes!("../assets/logo.svg"))
sha256_hex(include_bytes!("../../assets/logo.svg"))
);
assert_eq!(bundle.assets[3].sha256.len(), 64);
assert!(bundle.by_path(&bundle.logo().hashed_name()).is_some());
+2 -2
View File
@@ -6,8 +6,8 @@
//! No semantic decision (which node is executable) is taken here — that comes
//! exclusively from validated Analysis v2 (`semantic.rs`).
use crate::project::SafeRelativePath;
use crate::source_map::{sha256_hex, SourceIndex, SourceSpan};
use crate::reader::source::SafeRelativePath;
use crate::reader::source::{sha256_hex, SourceIndex, SourceSpan};
use comrak::nodes::{ListType, NodeValue, Sourcepos, TableAlignment};
use comrak::{parse_document, Arena, Options};
+12
View File
@@ -0,0 +1,12 @@
//! Reader layer: controlled source access, Markdown rendering, the one
//! presentation model, assembly from public protocols, and the one renderer.
//!
//! Live and Export share every type here; only link policy and interaction
//! availability differ (RFC-VIEW-0002 §4.3/§5.4).
pub mod assemble;
pub mod assets;
pub mod markdown;
pub mod model;
pub mod render;
pub mod source;
+8 -126
View File
@@ -1,13 +1,14 @@
//! Presentation model: the one intermediate form between verified domain data
//! and the one `ReaderRenderer`.
//! and the one `ReaderRenderer` (RFC-VIEW-0002 §5.2).
//!
//! Nothing here spawns processes, builds HTML or parses Markdown semantics. It
//! only composes already-verified pieces (RFC-VIEW-0001 §6.3, §14.2).
//! Nothing here spawns processes, builds HTML or parses Markdown semantics.
//! Assembly from Analysis/Trace happens in `reader::assemble`.
use crate::document::{DocumentIdentity, DocumentModel};
use crate::project::{Project, SafeRelativePath, ViewConfig};
use crate::semantic::{CoreDiagnostic, SemanticProjection, ViewWarning};
use crate::trace::{RunDisplayState, RunProjection};
use crate::config::ViewConfig;
use crate::protocol::analysis_v2::{CoreDiagnostic, SemanticProjection, ViewWarning};
use crate::protocol::trace_v2::{RunDisplayState, RunProjection};
use crate::reader::markdown::DocumentModel;
use crate::reader::source::{Project, SafeRelativePath};
/// Private View presentation-model version. Not a public protocol.
pub const PRESENTATION_VERSION: u32 = 1;
@@ -158,125 +159,6 @@ impl PresentationModel {
}
}
/// Input to the one builder. `analysis` is already protocol/byte verified.
pub struct BuildInput<'a> {
pub document: DocumentModel,
pub analysis: Option<&'a crate::semantic::VerifiedAnalysis>,
pub status: SourceStatus,
pub status_note: Option<String>,
pub diagnostics: Vec<CoreDiagnostic>,
pub navigation: Navigation,
pub core_version: Option<String>,
pub run: Option<&'a crate::trace::VerifiedRun>,
}
pub fn build(input: BuildInput<'_>) -> PresentationModel {
let BuildInput {
mut document,
analysis,
status,
status_note,
mut diagnostics,
navigation,
core_version,
run,
} = input;
let semantic = analysis.map(|verified| verified.projection.clone());
if let Some(projection) = &semantic {
document.identity = DocumentIdentity {
project_root_id: projection.project_root_id.clone(),
module_id: projection.module_id.clone(),
relative_path: projection.relative_path.clone(),
source_sha256: projection.source_digest.clone(),
};
for diagnostic in &projection.diagnostics {
if !diagnostics.iter().any(|existing| {
existing.code == diagnostic.code
&& existing.message == diagnostic.message
&& existing.span == diagnostic.span
}) {
diagnostics.push(diagnostic.clone());
}
}
}
let warnings = semantic
.as_ref()
.map(|projection| projection.warnings.clone())
.unwrap_or_default();
let outline = semantic.as_ref().map(build_outline).unwrap_or_default();
PresentationModel {
version: PRESENTATION_VERSION,
title: document.title(),
document,
semantic,
source_status: status,
status_note,
diagnostics,
warnings,
navigation,
outline,
core_version,
run: run.map(|verified| verified.projection.clone()),
}
}
fn build_outline(projection: &SemanticProjection) -> Vec<OutlineEntry> {
let mut entries = Vec::new();
for function in &projection.functions {
let params = if function.signature.params.is_empty() {
String::new()
} else {
function
.signature
.params
.iter()
.map(|param| {
if param.ty.is_empty() {
param.name.clone()
} else {
format!("{}: {}", param.name, param.ty)
}
})
.collect::<Vec<_>>()
.join(", ")
};
let detail = if params.is_empty() {
"无参数".to_string()
} else {
format!("params({params})")
};
entries.push(OutlineEntry {
label: function.local_name.clone(),
anchor: anchor_for_span(function.heading_span.start, function.heading_span.end),
detail,
kind: OutlineKind::Function,
});
}
for unit in &projection.units {
let kind = match unit.kind {
crate::semantic::UnitKind::Knowledge if unit.level >= 2 => OutlineKind::Knowledge,
crate::semantic::UnitKind::Section => OutlineKind::Section,
_ => continue,
};
if unit.name.is_empty() {
continue;
}
entries.push(OutlineEntry {
label: unit.name.clone(),
anchor: anchor_for_span(unit.span.start, unit.span.end),
detail: if unit.level == 2 {
"知识单元".to_string()
} else {
"章节".to_string()
},
kind,
});
}
entries
}
/// Deterministic heading anchor derived from the heading byte span. It never
/// depends on rendered text, so duplicate headings cannot collide.
pub fn anchor_for_span(start: u64, end: u64) -> String {
+13 -13
View File
@@ -10,12 +10,12 @@
//! Markdown is serialized here from the View-owned `DocBlock` tree, with raw
//! HTML omitted by default and every URL scheme sanitized.
use crate::assets::AssetBundle;
use crate::document::{DocBlock, Inline, TableAlign};
use crate::presentation::{anchor_for_span, PresentationModel};
use crate::project::SafeRelativePath;
use crate::semantic::{source_id, UnitKind};
use crate::source_map::SourceSpan;
use crate::protocol::analysis_v2::{source_id, UnitKind};
use crate::reader::assets::AssetBundle;
use crate::reader::markdown::{DocBlock, Inline, TableAlign};
use crate::reader::model::{anchor_for_span, PresentationModel};
use crate::reader::source::SafeRelativePath;
use crate::reader::source::SourceSpan;
use std::fmt::Write as _;
/// How links to other documents are resolved. This is the only Live/Export
@@ -156,7 +156,7 @@ impl ReaderRenderer {
<link rel="stylesheet" href="{css}"/>
<script defer src="{js}"></script>
</head>
<body class="mq-reader" data-mode="document" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-live="{live}">
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-live="{live}">
<a class="mq-skip" href="#mq-main">跳到正文</a>
"##,
presentation_version = model.version,
@@ -205,7 +205,7 @@ impl ReaderRenderer {
html: &mut String,
model: &PresentationModel,
_ctx: &RenderContext,
navigation: &crate::presentation::Navigation,
navigation: &crate::reader::model::Navigation,
) {
let active = model
.navigation
@@ -254,7 +254,7 @@ impl ReaderRenderer {
);
}
fn render_welcome(&self, html: &mut String, navigation: &crate::presentation::Navigation) {
fn render_welcome(&self, html: &mut String, navigation: &crate::reader::model::Navigation) {
let _ = write!(
html,
r##"<section class="mq-welcome" aria-label="欢迎页">
@@ -509,6 +509,7 @@ impl ReaderRenderer {
<div class="mq-dialog-head"><h2 id="mq-settings-title">阅读设置</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭设置">×</button></div>
<ul class="mq-menu-list">
<li><button type="button" data-action="size">正文字号 <span class="mq-menu-hint">标准 / 大 / 小</span></button></li>
<li><button type="button" data-action="theme">主题 <span class="mq-menu-hint">暖纸 / 深色</span></button></li>
<li><button type="button" data-action="annotations">语义标注显隐 <span class="mq-menu-hint">锚点与侧注</span></button></li>
<li><button type="button" data-action="print">打印 / 保存为 PDF <span class="mq-menu-hint">保留正文与注释</span></button></li>
</ul>
@@ -519,8 +520,7 @@ impl ReaderRenderer {
<li><button type="button" data-action="mode-document">文档态 <span class="mq-menu-hint">原始 Markdown 阅读</span></button></li>
<li><button type="button" data-action="mode-source">源码态 <span class="mq-menu-hint">逐行原文,含标记</span></button></li>
<li><button type="button" data-action="functions">函数大纲 <span class="mq-menu-hint">来自 Analysis v2</span></button></li>
<li><button type="button" data-action="variables">变量信息 <span class="mq-menu-hint">静态目标 · 运行值不支持</span></button></li>
<li><button type="button" data-action="memory">内存快照 <span class="mq-menu-hint">当前协议不支持</span></button></li>
<li><button type="button" data-action="unsupported">未提供的能力 <span class="mq-menu-hint">变量 / 内存 / 调试 / 证明</span></button></li>
<li><button type="button" data-action="print">打印 <span class="mq-menu-hint">隐藏交互与装饰</span></button></li>
<li><button type="button" data-action="about">关于 Marqdo View <span class="mq-menu-hint">版本与协议</span></button></li>
</ul>
@@ -918,7 +918,7 @@ fn resolve_heading_unit(
model: &PresentationModel,
heading_span: SourceSpan,
level: u8,
) -> Option<&crate::semantic::SemanticUnit> {
) -> Option<&crate::protocol::analysis_v2::SemanticUnit> {
let projection = model.semantic.as_ref()?;
// A function heading maps to its function unit exactly; never borrow the
// ancestor function for H3/H4 sections (that would duplicate DOM ids).
@@ -945,7 +945,7 @@ fn resolve_heading_unit(
fn display_heading_content(
content: &[Inline],
unit: Option<&crate::semantic::SemanticUnit>,
unit: Option<&crate::protocol::analysis_v2::SemanticUnit>,
) -> (Option<(&'static str, &'static str)>, Vec<Inline>) {
let Some(unit) = unit else {
return (None, content.to_vec());
+288 -85
View File
@@ -1,10 +1,293 @@
//! Project-root and path boundary enforcement.
//! Exact UTF-8 byte ↔ line/column ↔ JavaScript UTF-16 offset mapping.
//!
//! Production, HTTP, Export and tests all use these functions; there is no
//! second path validator (RFC-VIEW-0001 §14.4).
//! 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)
}
/// Byte offset of the start of a 1-based line.
pub fn line_start(&self, line: usize) -> Option<usize> {
if line == 0 {
return None;
}
self.line_starts.get(line - 1).copied()
}
/// Number of lines in the source.
pub fn line_count(&self) -> usize {
self.line_starts.len()
}
/// Text of a 1-based line without its trailing newline.
pub fn line_text<'a>(&self, source: &'a str, line: usize) -> Option<&'a str> {
let start = self.line_start(line)?;
let end = self.line_starts.get(line).copied().unwrap_or(self.len);
let bytes = source.as_bytes();
let mut end = end.min(bytes.len());
if end > start && bytes.get(end - 1) == Some(&b'\n') {
end -= 1;
if end > start && bytes.get(end - 1) == Some(&b'\r') {
end -= 1;
}
}
source.get(start..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}")
);
}
}
// ---------------------------------------------------------------------------
// Controlled project root, path boundary and document source access.
//
// All production/HTTP/Export/tests use these functions; there is no second
// path validator (RFC-VIEW-0002 §5.2/§6.8).
// ---------------------------------------------------------------------------
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.
@@ -306,86 +589,6 @@ impl Project {
}
}
/// Optional View-only site configuration (`view.json`).
///
/// This is **not** a Marqdo language protocol and cannot grant execution: only
/// the fields below are read, and the welcome path is still subject to the same
/// project-root boundary (RFC-VIEW-0001 §9.4).
#[derive(Debug, Clone, Default)]
pub struct ViewConfig {
pub welcome: Option<SafeRelativePath>,
pub site_title: Option<String>,
pub theme: Option<String>,
}
impl ViewConfig {
pub fn load(root: &Path) -> ViewResult<Self> {
let path = root.join("view.json");
let metadata = match std::fs::metadata(&path) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
Err(err) => return Err(ViewError::io(&format!("stat {}", path.display()), err)),
};
if !metadata.is_file() || metadata.len() > 64 * 1024 {
return Err(ViewError::PathForbidden {
detail: "view.json must be a regular file under 64 KiB".to_string(),
});
}
let bytes = std::fs::read(&path)
.map_err(|err| ViewError::io(&format!("read {}", path.display()), err))?;
#[derive(serde::Deserialize)]
struct RawConfig {
#[serde(default)]
schema: String,
#[serde(default)]
schema_version: u32,
#[serde(default)]
welcome: Option<String>,
#[serde(default)]
site_title: Option<String>,
#[serde(default)]
theme: Option<String>,
}
let raw: RawConfig = serde_json::from_slice(&bytes).map_err(|err| ViewError::Io {
detail: format!("view.json is not valid JSON: {err}"),
})?;
if raw.schema != "marqdo.view-config" || raw.schema_version != 1 {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unsupported view.json schema {:?} version {}; expected marqdo.view-config v1",
raw.schema, raw.schema_version
),
});
}
let welcome = match raw.welcome {
Some(path) => Some(SafeRelativePath::parse(&path)?),
None => None,
};
if let Some(welcome) = &welcome {
if !root.join(welcome.to_path()).is_file() {
return Err(ViewError::PathForbidden {
detail: format!(
"view.json welcome file {welcome} does not exist under the project root"
),
});
}
}
let site_title = raw
.site_title
.map(|title| title.trim().to_string())
.filter(|title| !title.is_empty() && title.chars().count() <= 80);
let theme = raw
.theme
.map(|theme| theme.trim().to_string())
.filter(|theme| theme == "botanical" || theme == "paper");
Ok(Self {
welcome,
site_title,
theme,
})
}
}
/// 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 {
@@ -434,7 +637,7 @@ fn canonicalize(path: &Path, what: &str) -> ViewResult<PathBuf> {
}
#[cfg(test)]
mod tests {
mod path_tests {
use super::*;
#[test]
+86 -57
View File
@@ -4,15 +4,15 @@
//! exposed until the explicit-run flow lands; every response carries a strict
//! CSP and the Host header is validated to blunt DNS-rebinding.
use crate::app::AppContext;
use crate::assets::AssetBundle;
use crate::cli::RuntimeOpts;
use crate::error::{ViewError, ViewResult};
use crate::presentation::PresentationModel;
use crate::project::SafeRelativePath;
use crate::render::{ReaderRenderer, RenderContext};
use crate::source_map::sha256_hex;
use crate::trace::VerifiedRun;
use crate::protocol::trace_v2::VerifiedRun;
use crate::reader::assemble::DocumentService;
use crate::reader::assets::AssetBundle;
use crate::reader::model::PresentationModel;
use crate::reader::render::{ReaderRenderer, RenderContext};
use crate::reader::source::sha256_hex;
use crate::reader::source::SafeRelativePath;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
@@ -22,7 +22,7 @@ const MAX_URL_BYTES: usize = 2048;
const MAX_QUERY_BYTES: usize = 4096;
const MAX_BODY_BYTES: usize = 16 * 1024;
pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult<i32> {
pub fn serve(ctx: DocumentService, opts: &RuntimeOpts) -> ViewResult<i32> {
let address = format!("{}:{}", opts.host, opts.port);
let server = Server::http(&address).map_err(|err| ViewError::Io {
detail: format!("listen on {address}: {err}"),
@@ -89,7 +89,7 @@ pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult<i32> {
}
struct ServerState {
ctx: AppContext,
ctx: DocumentService,
csrf_token: String,
renderer: ReaderRenderer,
cache: Mutex<HashMap<String, CacheEntry>>,
@@ -291,7 +291,7 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
Err(err) => serve_error_page(request, &err, is_head),
}
}
"/api/document" => {
"/api/documents" => {
let relative = match query_param(query, "path")
.and_then(|raw| percent_decode(&raw))
.map(|decoded| SafeRelativePath::parse(&decoded))
@@ -303,7 +303,7 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
None => state.ctx.project().entry().relative.clone(),
};
match state.load_for_page(&relative, query_param(query, "run").as_deref()) {
Ok(model) => serve_document_json(request, &model),
Ok(model) => serve_documents_json(state, request, &relative, &model),
Err(err) => respond_json_error(request, StatusCode(500), &err),
}
}
@@ -326,9 +326,9 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
"version": state.ctx.core_version(),
},
"protocols": {
"tool": crate::version::TOOL_PROTOCOL,
"analysis": crate::version::ANALYSIS_PROTOCOL,
"trace": crate::version::TRACE_PROTOCOL,
"tool": crate::protocol::tool_v1::TOOL_PROTOCOL,
"analysis": crate::protocol::tool_v1::ANALYSIS_PROTOCOL,
"trace": crate::protocol::tool_v1::TRACE_PROTOCOL,
},
"documents": documents,
"run_api": true,
@@ -684,7 +684,7 @@ fn serve_page(
is_head: bool,
) -> ViewResult<()> {
let ctx = RenderContext {
links: crate::render::LinkPolicy::LocalServer,
links: crate::reader::render::LinkPolicy::LocalServer,
live: true,
csrf_token: Some(state.csrf_token.clone()),
run_available: state.ctx.core().is_some() && model.can_offer_run(),
@@ -703,55 +703,84 @@ fn serve_error_page(request: Request, err: &ViewError, is_head: bool) -> ViewRes
respond_html(request, html.into_bytes(), is_head)
}
fn serve_document_json(request: Request, model: &PresentationModel) -> ViewResult<()> {
fn serve_documents_json(
state: &ServerState,
request: Request,
relative: &SafeRelativePath,
model: &PresentationModel,
) -> ViewResult<()> {
let semantic = model.semantic.as_ref();
let documents = state
.ctx
.project()
.list_documents()
.unwrap_or_default()
.into_iter()
.map(|path| {
serde_json::json!({
"path": path.as_str(),
"active": path == *relative,
})
})
.collect::<Vec<_>>();
let functions = model
.outline
.iter()
.filter(|entry| entry.kind == crate::reader::model::OutlineKind::Function)
.map(|entry| {
serde_json::json!({
"label": entry.label,
"anchor": entry.anchor,
"detail": entry.detail,
})
})
.collect::<Vec<_>>();
let doc = serde_json::json!({
"schema": "marqdo.view-document",
"schema": "marqdo.view-documents",
"schema_version": 1,
"title": model.title,
"document": {
"entry": state.ctx.project().entry().relative.as_str(),
"documents": documents,
"current": {
"relative_path": model.document.identity.relative_path,
"module_id": model.document.identity.module_id,
"title": model.title,
"source_sha256": sha256_hex(model.document.source.as_bytes()),
"source_status": model.source_status.data_value(),
"semantics_usable": model.source_status.semantics_usable(),
"analysis": semantic.map(|projection| serde_json::json!({
"digest": projection.analysis_digest,
"schema_version": crate::protocol::tool_v1::ANALYSIS_PROTOCOL,
"producer_version": projection.producer_version,
"project_root_id": projection.project_root_id,
"functions": projection.functions.len(),
"units": projection.units.len(),
"diagnostics": projection.diagnostics.len(),
})),
"outline": model.outline.iter().map(|entry| serde_json::json!({
"label": entry.label,
"anchor": entry.anchor,
"detail": entry.detail,
"kind": match entry.kind {
crate::reader::model::OutlineKind::Function => "function",
crate::reader::model::OutlineKind::Knowledge => "knowledge",
crate::reader::model::OutlineKind::Section => "section",
},
})).collect::<Vec<_>>(),
"functions": functions,
"run": model.run.as_ref().map(|run| serde_json::json!({
"state": run.state.data_value(),
"label": run.state.label(),
"run_id": run.run_id,
"run_status": run.run_status,
"exit_code": run.exit_code,
"event_count": run.counts.total(),
"entry_event_count": run.entry_event_count,
"truncated": run.truncated.as_ref().map(|truncated| truncated.label()),
"has_result_value": run.result_value.is_some(),
})),
"can_offer_run": model.can_offer_run(),
},
"source_status": model.source_status.data_value(),
"semantics_usable": model.source_status.semantics_usable(),
"analysis": semantic.map(|projection| serde_json::json!({
"digest": projection.analysis_digest,
"schema_version": crate::version::ANALYSIS_PROTOCOL,
"producer_version": projection.producer_version,
"project_root_id": projection.project_root_id,
"functions": projection.functions.len(),
"units": projection.units.len(),
"diagnostics": projection.diagnostics.len(),
})),
"outline": model.outline.iter().map(|entry| serde_json::json!({
"label": entry.label,
"anchor": entry.anchor,
"detail": entry.detail,
"kind": match entry.kind {
crate::presentation::OutlineKind::Function => "function",
crate::presentation::OutlineKind::Knowledge => "knowledge",
crate::presentation::OutlineKind::Section => "section",
},
})).collect::<Vec<_>>(),
"navigation": {
"documents": model.navigation.documents.iter().map(|doc| doc.as_str()).collect::<Vec<_>>(),
"welcome": model.navigation.welcome,
},
"run": model.run.as_ref().map(|run| serde_json::json!({
"state": run.state.data_value(),
"label": run.state.label(),
"run_id": run.run_id,
"run_status": run.run_status,
"exit_code": run.exit_code,
"event_count": run.counts.total(),
"entry_event_count": run.entry_event_count,
"truncated": run.truncated.as_ref().map(|truncated| truncated.label()),
"has_result_value": run.result_value.is_some(),
})),
"can_offer_run": model.can_offer_run(),
"note": "Read-only PresentationModel summary; this page load never executes the document.",
"note": "Read-only document structure; this request never executes the document.",
});
respond_json(request, StatusCode(200), &doc)
}
-281
View File
@@ -1,281 +0,0 @@
//! 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)
}
/// Byte offset of the start of a 1-based line.
pub fn line_start(&self, line: usize) -> Option<usize> {
if line == 0 {
return None;
}
self.line_starts.get(line - 1).copied()
}
/// Number of lines in the source.
pub fn line_count(&self) -> usize {
self.line_starts.len()
}
/// Text of a 1-based line without its trailing newline.
pub fn line_text<'a>(&self, source: &'a str, line: usize) -> Option<&'a str> {
let start = self.line_start(line)?;
let end = self.line_starts.get(line).copied().unwrap_or(self.len);
let bytes = source.as_bytes();
let mut end = end.min(bytes.len());
if end > start && bytes.get(end - 1) == Some(&b'\n') {
end -= 1;
if end > start && bytes.get(end - 1) == Some(&b'\r') {
end -= 1;
}
}
source.get(start..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}")
);
}
}