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

+940
View File
@@ -0,0 +1,940 @@
//! Analysis v2 validation and static semantic projection.
//!
//! This module is the only consumer of the public Analysis JSON. It verifies
//! protocol identity first, then projects functions/units/statements/diagnostics
//! into View-owned types with **validated** source spans. A span that is out of
//! range or not on a UTF-8 boundary is dropped with an explicit View warning
//! instead of being pointed at nearby text (RFC-VIEW-0001 §4.3, §8.2).
use crate::error::{ViewError, ViewResult};
use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
use serde::Deserialize;
use serde_json::Value;
/// Stable DOM identity for one source-bound annotation, local to this document
/// and run. It is not a cross-edit identity.
pub fn source_id(module_id: &str, span: SourceSpan, kind: &str) -> String {
let material = format!("{module_id}\0{}:{}:{}", span.start, span.end, kind);
sha256_hex(material.as_bytes())[..16].to_string()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnitKind {
Root,
Namespace,
Function,
Knowledge,
Section,
Other,
}
#[derive(Debug, Clone)]
pub struct SemanticUnit {
pub id: String,
pub name: String,
pub level: u8,
pub kind: UnitKind,
pub function: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct FunctionParam {
pub name: String,
pub ty: String,
pub required: bool,
pub default: Option<String>,
pub span: Option<SourceSpan>,
}
#[derive(Debug, Clone)]
pub struct FunctionSignature {
pub kind: String,
pub params: Vec<FunctionParam>,
}
#[derive(Debug, Clone)]
pub struct SemanticFunction {
pub id: String,
pub unit_id: String,
pub local_name: String,
pub namespace: Option<String>,
pub span: SourceSpan,
pub heading_span: SourceSpan,
pub signature: FunctionSignature,
pub effects: Vec<String>,
pub statements: Vec<SemanticStatement>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatementKind {
Assign,
Expression,
Branch,
Loop,
Return,
Other,
}
impl StatementKind {
pub fn label(&self) -> &'static str {
match self {
StatementKind::Assign => "赋值",
StatementKind::Expression => "表达式",
StatementKind::Branch => "条件分支",
StatementKind::Loop => "循环",
StatementKind::Return => "返回",
StatementKind::Other => "语句",
}
}
pub fn data_value(&self) -> &'static str {
match self {
StatementKind::Assign => "assign",
StatementKind::Expression => "expression",
StatementKind::Branch => "branch",
StatementKind::Loop => "loop",
StatementKind::Return => "return",
StatementKind::Other => "other",
}
}
}
#[derive(Debug, Clone)]
pub struct SemanticStatement {
pub kind: StatementKind,
/// Header span for control flow, payload span for simple statements.
pub span: SourceSpan,
/// For `if` arms and `while` conditions: the condition text span as the
/// compiler recorded it.
pub condition_span: Option<SourceSpan>,
pub arms: Vec<SemanticArm>,
pub body: Vec<SemanticStatement>,
/// Target name for assignments (local name or `index` form), for static
/// outline display only. Never a runtime value.
pub target: Option<String>,
}
#[derive(Debug, Clone)]
pub struct SemanticArm {
pub span: Option<SourceSpan>,
pub condition_span: Option<SourceSpan>,
pub body: Vec<SemanticStatement>,
}
impl SemanticFunction {
/// Depth-first statement walk in source order.
pub fn flattened_statements(&self) -> Vec<&SemanticStatement> {
let mut out = Vec::new();
for statement in &self.statements {
collect_statements(statement, &mut out);
}
out
}
}
fn collect_statements<'a>(statement: &'a SemanticStatement, out: &mut Vec<&'a SemanticStatement>) {
out.push(statement);
for arm in &statement.arms {
for child in &arm.body {
collect_statements(child, out);
}
}
for child in &statement.body {
collect_statements(child, out);
}
}
#[derive(Debug, Clone)]
pub struct StaticResource {
pub id: String,
pub kind: String,
pub span: SourceSpan,
pub content_digest: String,
pub language: Option<String>,
pub display: bool,
}
#[derive(Debug, Clone)]
pub struct StaticImport {
pub alias: String,
pub target: String,
pub resolved: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct StaticReference {
pub url: String,
pub span: SourceSpan,
pub state: String,
pub target_module: Option<String>,
pub target_unit: Option<String>,
}
#[derive(Debug, Clone)]
pub struct StaticCall {
pub state: String,
pub target: Option<String>,
pub function: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct CoreDiagnostic {
pub module: Option<String>,
pub relative_path: Option<String>,
pub span: Option<SourceSpan>,
pub line: Option<u64>,
pub column: Option<u64>,
pub severity: String,
pub code: String,
pub message: String,
pub hints: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct ViewWarning {
pub code: String,
pub message: String,
pub span: Option<SourceSpan>,
}
#[derive(Debug, Clone)]
pub struct ModuleSummary {
pub id: String,
pub package_instance_id: String,
pub relative_path: String,
pub source_digest: String,
}
#[derive(Debug, Clone)]
pub struct SemanticProjection {
pub analysis_sha256: String,
pub analysis_digest: String,
pub producer_version: String,
pub markdown_profile: String,
pub project_root_id: String,
pub identity_kind: String,
pub lock_digest: String,
pub stdlib_version: Option<String>,
pub module_id: String,
pub package_instance_id: String,
pub relative_path: String,
pub source_digest: String,
pub units: Vec<SemanticUnit>,
pub functions: Vec<SemanticFunction>,
pub resources: Vec<StaticResource>,
pub imports: Vec<StaticImport>,
pub references: Vec<StaticReference>,
pub calls: Vec<StaticCall>,
pub diagnostics: Vec<CoreDiagnostic>,
pub warnings: Vec<ViewWarning>,
pub modules: Vec<ModuleSummary>,
}
#[derive(Debug)]
pub struct VerifiedAnalysis {
pub projection: SemanticProjection,
}
impl SemanticProjection {
pub fn unit_for_heading(&self, span: SourceSpan, level: u8) -> Option<&SemanticUnit> {
self.units
.iter()
.filter(|unit| unit.level == level && unit.span.contains(span))
.min_by_key(|unit| unit.span.len())
}
pub fn function_by_heading(&self, span: SourceSpan) -> Option<&SemanticFunction> {
self.functions
.iter()
.find(|function| function.heading_span == span)
.or_else(|| {
self.functions
.iter()
.find(|function| function.span.contains(span))
})
}
/// All statements of all functions, flattened in deterministic order.
pub fn all_statements(&self) -> Vec<(&SemanticFunction, &SemanticStatement)> {
let mut out = Vec::new();
for function in &self.functions {
for statement in function.flattened_statements() {
out.push((function, statement));
}
}
out
}
/// The innermost statement whose span is contained in `inline_span`.
pub fn statement_for_inline(
&self,
inline_span: SourceSpan,
) -> Option<(&SemanticFunction, &SemanticStatement)> {
self.all_statements()
.into_iter()
.filter(|(_, statement)| {
statement.span.start >= inline_span.start
&& statement.span.end <= inline_span.end
&& !statement.span.is_empty()
})
.max_by_key(|(_, statement)| statement.span.start)
}
pub fn resource_for_span(&self, span: SourceSpan) -> Option<&StaticResource> {
self.resources
.iter()
.find(|resource| resource.span == span || resource.span.contains(span))
}
pub fn reference_for_span(&self, span: SourceSpan) -> Option<&StaticReference> {
self.references
.iter()
.find(|reference| reference.span == span || reference.span.contains(span))
}
}
// ---------------------------------------------------------------------------
// Raw protocol types (additive fields are tolerated and ignored).
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
struct RawAnalysis {
schema: String,
schema_version: u32,
producer: RawProducer,
project: RawProject,
modules: Vec<RawModule>,
#[serde(default)]
diagnostics: Vec<RawDiagnostic>,
}
#[derive(Debug, Deserialize)]
struct RawProducer {
#[serde(default)]
name: String,
#[serde(default)]
version: String,
#[serde(default)]
markdown_profile: String,
}
#[derive(Debug, Deserialize)]
struct RawProject {
#[serde(default)]
root_id: String,
#[serde(default)]
identity_kind: String,
#[serde(default)]
lock_digest: String,
#[serde(default)]
stdlib: Option<RawStdlib>,
}
#[derive(Debug, Deserialize)]
struct RawStdlib {
#[serde(default)]
version: String,
}
#[derive(Debug, Deserialize)]
struct RawModule {
#[serde(default)]
id: String,
#[serde(default)]
package_instance_id: String,
#[serde(default)]
relative_path: String,
#[serde(default)]
source_digest: String,
#[serde(default)]
units: Vec<RawUnit>,
#[serde(default)]
functions: Vec<RawFunction>,
#[serde(default)]
imports: Vec<RawImport>,
#[serde(default)]
references: Vec<RawReference>,
#[serde(default)]
calls: Vec<RawCall>,
#[serde(default)]
resources: Vec<RawResource>,
}
#[derive(Debug, Deserialize)]
struct RawUnit {
#[serde(default)]
id: String,
#[serde(default)]
name: String,
#[serde(default)]
level: u8,
#[serde(default)]
kind: String,
#[serde(default)]
function: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawFunction {
#[serde(default)]
id: String,
#[serde(default)]
unit_id: String,
#[serde(default)]
local_name: String,
#[serde(default)]
namespace: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
heading_span: Option<SourceSpan>,
#[serde(default)]
signature: Option<RawSignature>,
#[serde(default)]
effects: Vec<String>,
#[serde(default)]
body: Vec<RawStatement>,
}
#[derive(Debug, Deserialize)]
struct RawSignature {
#[serde(default)]
kind: String,
#[serde(default)]
params: Vec<RawParam>,
}
#[derive(Debug, Deserialize)]
struct RawParam {
#[serde(default)]
name: String,
#[serde(default, rename = "type")]
ty: Option<String>,
#[serde(default)]
required: bool,
#[serde(default)]
default: Option<Value>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawStatement {
#[serde(default)]
kind: String,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
condition_span: Option<SourceSpan>,
#[serde(default)]
arms: Vec<RawArm>,
#[serde(default)]
body: Vec<RawStatement>,
#[serde(default)]
target: Option<Value>,
}
#[derive(Debug, Deserialize)]
struct RawArm {
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
condition_span: Option<SourceSpan>,
#[serde(default)]
body: Vec<RawStatement>,
}
#[derive(Debug, Deserialize)]
struct RawResource {
#[serde(default)]
id: String,
#[serde(default)]
kind: String,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
content_digest: String,
#[serde(default)]
language: Option<String>,
#[serde(default)]
display: bool,
}
#[derive(Debug, Deserialize)]
struct RawImport {
#[serde(default)]
alias: String,
#[serde(default)]
target: String,
#[serde(default)]
resolved: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawReference {
#[serde(default)]
url: String,
#[serde(default)]
state: String,
#[serde(default)]
target_module: Option<String>,
#[serde(default)]
target_unit: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawCall {
#[serde(default)]
state: String,
#[serde(default)]
target: Option<String>,
#[serde(default)]
function: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawDiagnostic {
#[serde(default)]
module: Option<String>,
#[serde(default)]
relative_path: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
line: Option<u64>,
#[serde(default)]
column: Option<u64>,
#[serde(default)]
severity: String,
#[serde(default)]
code: String,
#[serde(default)]
message: String,
#[serde(default)]
hints: Vec<String>,
}
// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------
/// Verify Analysis bytes against the exact source and project the static facts.
///
/// Rejects protocol incompatibility and source-digest mismatch as errors; drops
/// individual invalid spans as warnings so the prose stays readable.
pub fn verify_analysis(
analysis_bytes: &[u8],
source: &str,
source_index: &SourceIndex,
expected_relative_path: &str,
) -> ViewResult<VerifiedAnalysis> {
let raw: RawAnalysis =
serde_json::from_slice(analysis_bytes).map_err(|err| ViewError::AnalysisFailed {
detail: format!("Analysis v2 is not valid JSON: {err}"),
})?;
if raw.schema != "marqdo.analysis" {
return Err(ViewError::ProtocolIncompatible {
detail: format!("unexpected Analysis schema {:?}", raw.schema),
});
}
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,
crate::protocol::tool_v1::ANALYSIS_PROTOCOL
),
});
}
if raw.producer.name != "marqdo" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis producer.name {:?} is not `marqdo`",
raw.producer.name
),
});
}
if raw.producer.markdown_profile != "marqdo.md.v1" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unexpected Markdown profile {:?}; this View targets marqdo.md.v1",
raw.producer.markdown_profile
),
});
}
if raw.project.root_id.is_empty() {
return Err(ViewError::AnalysisFailed {
detail: "Analysis project.root_id is empty".to_string(),
});
}
let actual_digest = sha256_hex(source.as_bytes());
let module = raw
.modules
.iter()
.find(|module| module.relative_path == expected_relative_path)
.ok_or_else(|| ViewError::AnalysisFailed {
detail: format!("Analysis has no module for {expected_relative_path}"),
})?;
if module.source_digest != actual_digest {
return Err(ViewError::SourceMismatch {
expected: module.source_digest.clone(),
actual: actual_digest,
});
}
let mut warnings = Vec::new();
let mut valid_span = |span: Option<SourceSpan>, what: &str| -> Option<SourceSpan> {
let span = span?;
if source_index.validate_span_bytes(source.as_bytes(), span) {
Some(span)
} else {
warnings.push(ViewWarning {
code: "view.source_span_invalid".to_string(),
message: format!("{what} 的字节区间超出源码或不在 UTF-8 边界,已跳过该标注"),
span: Some(span),
});
None
}
};
let units: Vec<SemanticUnit> = module
.units
.iter()
.filter_map(|unit| {
let span = valid_span(unit.span, "语义单元")?;
Some(SemanticUnit {
id: unit.id.clone(),
name: unit.name.clone(),
level: unit.level,
kind: match unit.kind.as_str() {
"root" => UnitKind::Root,
"namespace" => UnitKind::Namespace,
"function" => UnitKind::Function,
"knowledge" => UnitKind::Knowledge,
"section" => UnitKind::Section,
_ => UnitKind::Other,
},
function: unit.function.clone(),
span,
})
})
.collect();
let functions: Vec<SemanticFunction> = module
.functions
.iter()
.filter_map(|function| {
let span = valid_span(function.span, "函数范围")?;
let heading_span = valid_span(function.heading_span, "函数标题")?;
let statements = function
.body
.iter()
.filter_map(|statement| convert_statement(statement, &mut valid_span))
.collect();
Some(SemanticFunction {
id: function.id.clone(),
unit_id: function.unit_id.clone(),
local_name: function.local_name.clone(),
namespace: function.namespace.clone(),
span,
heading_span,
signature: FunctionSignature {
kind: function
.signature
.as_ref()
.map(|signature| signature.kind.clone())
.unwrap_or_default(),
params: function
.signature
.as_ref()
.map(|signature| {
signature
.params
.iter()
.map(|param| FunctionParam {
name: param.name.clone(),
ty: param.ty.clone().unwrap_or_default(),
required: param.required,
default: param.default.as_ref().map(compact_value),
span: param.span.filter(|span| {
source_index.validate_span_bytes(source.as_bytes(), *span)
}),
})
.collect()
})
.unwrap_or_default(),
},
effects: function.effects.clone(),
statements,
})
})
.collect();
let resources: Vec<StaticResource> = module
.resources
.iter()
.filter(|resource| matches!(resource.kind.as_str(), "formula" | "code"))
.filter_map(|resource| {
let span = valid_span(resource.span, "资源")?;
Some(StaticResource {
id: resource.id.clone(),
kind: resource.kind.clone(),
span,
content_digest: resource.content_digest.clone(),
language: resource.language.clone(),
display: resource.display,
})
})
.collect();
let imports: Vec<StaticImport> = module
.imports
.iter()
.filter_map(|import| {
Some(StaticImport {
alias: import.alias.clone(),
target: import.target.clone(),
resolved: import.resolved.clone(),
span: valid_span(import.span, "导入声明")?,
})
})
.collect();
let references: Vec<StaticReference> = module
.references
.iter()
.filter_map(|reference| {
Some(StaticReference {
url: reference.url.clone(),
state: reference.state.clone(),
target_module: reference.target_module.clone(),
target_unit: reference.target_unit.clone(),
span: valid_span(reference.span, "Markdown 引用")?,
})
})
.collect();
let calls: Vec<StaticCall> = module
.calls
.iter()
.filter_map(|call| {
Some(StaticCall {
state: call.state.clone(),
target: call.target.clone(),
function: call.function.clone(),
span: valid_span(call.span, "调用点")?,
})
})
.collect();
let diagnostics: Vec<CoreDiagnostic> = raw
.diagnostics
.iter()
.map(|diagnostic| {
let span = diagnostic
.span
.filter(|span| source_index.validate_span_bytes(source.as_bytes(), *span));
CoreDiagnostic {
module: diagnostic.module.clone(),
relative_path: diagnostic.relative_path.clone(),
span,
line: diagnostic.line,
column: diagnostic.column,
severity: if diagnostic.severity.is_empty() {
"error".to_string()
} else {
diagnostic.severity.clone()
},
code: diagnostic.code.clone(),
message: diagnostic.message.clone(),
hints: diagnostic.hints.clone(),
}
})
.collect();
let modules = raw
.modules
.iter()
.map(|module| ModuleSummary {
id: module.id.clone(),
package_instance_id: module.package_instance_id.clone(),
relative_path: module.relative_path.clone(),
source_digest: module.source_digest.clone(),
})
.collect();
Ok(VerifiedAnalysis {
projection: SemanticProjection {
analysis_sha256: sha256_hex(analysis_bytes),
analysis_digest: sha256_prefixed(analysis_bytes),
producer_version: raw.producer.version.clone(),
markdown_profile: raw.producer.markdown_profile.clone(),
project_root_id: raw.project.root_id.clone(),
identity_kind: raw.project.identity_kind.clone(),
lock_digest: raw.project.lock_digest.clone(),
stdlib_version: raw.project.stdlib.as_ref().map(|s| s.version.clone()),
module_id: module.id.clone(),
package_instance_id: module.package_instance_id.clone(),
relative_path: module.relative_path.clone(),
source_digest: module.source_digest.clone(),
units,
functions,
resources,
imports,
references,
calls,
diagnostics,
warnings,
modules,
},
})
}
fn convert_statement(
raw: &RawStatement,
valid_span: &mut impl FnMut(Option<SourceSpan>, &str) -> Option<SourceSpan>,
) -> Option<SemanticStatement> {
let span = valid_span(raw.span, "语句")?;
let kind = match raw.kind.as_str() {
"assign" => StatementKind::Assign,
"expression" => StatementKind::Expression,
"branch" => StatementKind::Branch,
"loop" => StatementKind::Loop,
"return" => StatementKind::Return,
_ => StatementKind::Other,
};
let body = raw
.body
.iter()
.filter_map(|child| convert_statement(child, valid_span))
.collect();
let arms = raw
.arms
.iter()
.map(|arm| SemanticArm {
span: valid_span(arm.span, "分支臂"),
condition_span: valid_span(arm.condition_span, "分支条件"),
body: arm
.body
.iter()
.filter_map(|child| convert_statement(child, valid_span))
.collect(),
})
.collect();
Some(SemanticStatement {
kind,
span,
condition_span: valid_span(raw.condition_span, "控制条件"),
arms,
body,
target: raw.target.as_ref().and_then(assignment_target_label),
})
}
fn assignment_target_label(target: &Value) -> Option<String> {
match target {
Value::String(name) => Some(name.clone()),
Value::Object(map) => {
if map.get("kind").and_then(Value::as_str) == Some("index") {
Some("索引赋值".to_string())
} else {
None
}
}
_ => None,
}
}
fn compact_value(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
other => {
let text = other.to_string();
if text.chars().count() > 40 {
format!("{}…", text.chars().take(40).collect::<String>())
} else {
text
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn analysis(schema_version: u32, digest: &str) -> Vec<u8> {
serde_json::json!({
"schema": "marqdo.analysis",
"schema_version": schema_version,
"producer": {"name": "marqdo", "version": "3.0.0-beta.1", "markdown_profile": "marqdo.md.v1"},
"project": {"root_id": "root:t@0.1.0", "identity_kind": "manifest", "lock_digest": "", "stdlib": null},
"modules": [{
"id": "root:t@0.1.0::index.mq.md",
"package_instance_id": "root:t@0.1.0",
"relative_path": "index.mq.md",
"source_digest": digest,
"units": [],
"functions": [],
"imports": [],
"references": [],
"calls": [],
"resources": []
}],
"diagnostics": []
})
.to_string()
.into_bytes()
}
#[test]
fn rejects_unknown_schema_major_and_profile() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let digest = sha256_hex(source.as_bytes());
let err =
verify_analysis(&analysis(3, &digest), source, &index, "index.mq.md").unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
}
#[test]
fn rejects_digest_mismatch() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let err = verify_analysis(&analysis(2, &"0".repeat(64)), source, &index, "index.mq.md")
.unwrap_err();
assert_eq!(err.code(), "view.source_mismatch");
}
#[test]
fn projects_valid_analysis() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let digest = sha256_hex(source.as_bytes());
let verified =
verify_analysis(&analysis(2, &digest), source, &index, "index.mq.md").unwrap();
assert_eq!(verified.projection.project_root_id, "root:t@0.1.0");
assert_eq!(verified.projection.relative_path, "index.mq.md");
}
#[test]
fn source_id_is_deterministic_and_bounded() {
let span = SourceSpan::new(1, 5);
let id = source_id("mod", span, "statement");
assert_eq!(id.len(), 16);
assert_eq!(id, source_id("mod", span, "statement"));
assert_ne!(id, source_id("mod", span, "resource"));
}
}
+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;
+149
View File
@@ -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());
}
}
+627
View File
@@ -0,0 +1,627 @@
//! Trace v2 validation and run projection.
//!
//! Trace data is observed execution, not execution itself. Validation is hard:
//! the trace must bind to the exact Analysis bytes and project identity, and
//! every event module id must exist in Analysis. Missing capabilities (per
//! assignment values, memory snapshots, proofs) are explicit `UNSUPPORTED`
//! states, never invented (RFC-VIEW-0001 §4.4, §12).
use crate::error::{ViewError, ViewResult};
use crate::protocol::analysis_v2::{ModuleSummary, SemanticProjection};
use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
use serde::Deserialize;
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunDisplayState {
NotRun,
StaticOnly,
Running,
Succeeded,
Failed,
Stale,
Truncated,
Unsupported,
}
impl RunDisplayState {
pub fn data_value(&self) -> &'static str {
match self {
RunDisplayState::NotRun => "not-run",
RunDisplayState::StaticOnly => "static-only",
RunDisplayState::Running => "running",
RunDisplayState::Succeeded => "succeeded",
RunDisplayState::Failed => "failed",
RunDisplayState::Stale => "stale",
RunDisplayState::Truncated => "truncated",
RunDisplayState::Unsupported => "unsupported",
}
}
pub fn label(&self) -> &'static str {
match self {
RunDisplayState::NotRun => "未运行",
RunDisplayState::StaticOnly => "仅静态检查",
RunDisplayState::Running => "运行中",
RunDisplayState::Succeeded => "运行成功",
RunDisplayState::Failed => "运行失败",
RunDisplayState::Stale => "结果已过期",
RunDisplayState::Truncated => "Trace 已截断",
RunDisplayState::Unsupported => "当前协议不支持",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TraceKind {
CallEnter,
CallExit,
BranchEval,
LoopIteration,
Return,
Effect,
Truncated,
Other(String),
}
impl TraceKind {
pub fn data_value(&self) -> &str {
match self {
TraceKind::CallEnter => "call.enter",
TraceKind::CallExit => "call.exit",
TraceKind::BranchEval => "branch.eval",
TraceKind::LoopIteration => "loop.iteration",
TraceKind::Return => "return",
TraceKind::Effect => "effect",
TraceKind::Truncated => "trace.truncated",
TraceKind::Other(kind) => kind,
}
}
fn parse(raw: &str) -> TraceKind {
match raw {
"call.enter" => TraceKind::CallEnter,
"call.exit" => TraceKind::CallExit,
"branch.eval" => TraceKind::BranchEval,
"loop.iteration" => TraceKind::LoopIteration,
"return" => TraceKind::Return,
"effect" => TraceKind::Effect,
"trace.truncated" => TraceKind::Truncated,
other => TraceKind::Other(other.to_string()),
}
}
}
#[derive(Debug, Clone)]
pub struct TraceEvent {
pub seq: u64,
pub kind: TraceKind,
pub function_id: Option<String>,
pub module_id: Option<String>,
/// Validated span in the entry module; `None` for other modules or invalid
/// spans (which are reported as warnings).
pub span: Option<SourceSpan>,
/// Presentation-only span in an event's own module, kept for the panel.
pub raw_span: Option<SourceSpan>,
/// Statement span in the entry document this event attaches to, if any.
pub anchor_span: Option<SourceSpan>,
pub detail: Option<String>,
pub operation: Option<String>,
pub duration_micros: Option<u64>,
}
impl TraceEvent {
pub fn kind_label(&self) -> &str {
self.kind.data_value()
}
pub fn is_entry_module(&self, entry_module: &str) -> bool {
self.module_id.as_deref() == Some(entry_module)
}
}
#[derive(Debug, Clone)]
pub struct Truncation {
pub reason: String,
pub limit: u64,
pub written: u64,
}
impl Truncation {
pub fn label(&self) -> String {
let reason = match self.reason.as_str() {
"event_budget" => "事件数量上限",
"byte_budget" => "字节上限",
other => other,
};
format!("{reason}(上限 {},已写入 {})", self.limit, self.written)
}
}
#[derive(Debug, Clone)]
pub struct RunValue {
pub ty: String,
pub display: String,
}
#[derive(Debug, Clone, Default)]
pub struct EventCounts {
pub call_enter: usize,
pub call_exit: usize,
pub branch_eval: usize,
pub loop_iteration: usize,
pub return_events: usize,
pub effect: usize,
pub other: usize,
}
impl EventCounts {
pub fn total(&self) -> usize {
self.call_enter
+ self.call_exit
+ self.branch_eval
+ self.loop_iteration
+ self.return_events
+ self.effect
+ self.other
}
}
#[derive(Debug, Clone)]
pub struct RunProjection {
pub run_id: String,
pub entry: Option<String>,
/// Raw `run.status` from the Core (`ok` or a stable runtime error code).
pub run_status: String,
pub state: RunDisplayState,
pub error_code: Option<String>,
pub analysis_digest: String,
pub events: Vec<TraceEvent>,
pub truncated: Option<Truncation>,
pub stdout: String,
pub stderr: String,
pub exit_code: i32,
pub result_value: Option<RunValue>,
pub counts: EventCounts,
/// Counts per event module: entry document vs other modules.
pub entry_event_count: usize,
pub other_event_count: usize,
pub warnings: Vec<String>,
}
impl RunProjection {
pub fn state_label(&self) -> &'static str {
self.state.label()
}
pub fn is_success(&self) -> bool {
matches!(
self.state,
RunDisplayState::Succeeded | RunDisplayState::Truncated
)
}
/// Events whose statement anchor is exactly `span`, in sequence order.
pub fn events_for_anchor(&self, span: SourceSpan) -> Vec<&TraceEvent> {
self.events
.iter()
.filter(|event| event.anchor_span == Some(span))
.collect()
}
/// Compact inline summary for one statement anchor, or `None` when the
/// statement has no sourced run event.
pub fn anchor_summary(&self, span: SourceSpan) -> Option<RunAnchorSummary> {
let events = self.events_for_anchor(span);
if events.is_empty() {
return None;
}
let last = events.last().expect("non-empty");
let mut kinds: Vec<&str> = Vec::new();
for event in &events {
if !kinds.contains(&event.kind_label()) {
kinds.push(event.kind_label());
}
}
let detail = match last.kind {
TraceKind::BranchEval => format!("if → {}", last.detail.as_deref().unwrap_or("?")),
TraceKind::LoopIteration => {
let outcome = match last.detail.as_deref() {
Some("continue") => "continue",
Some("exit") => "exit",
other => other.unwrap_or("?"),
};
format!("loop {outcome}")
}
TraceKind::Return => format!("return {}", last.detail.as_deref().unwrap_or("Unit")),
TraceKind::CallEnter => "call".to_string(),
TraceKind::CallExit => "call exit".to_string(),
TraceKind::Effect => format!("effect {}", last.operation.as_deref().unwrap_or("ok")),
_ => last.kind_label().to_string(),
};
Some(RunAnchorSummary {
count: events.len(),
detail,
kinds: kinds.into_iter().map(str::to_string).collect(),
last_seq: last.seq,
})
}
}
#[derive(Debug, Clone)]
pub struct RunAnchorSummary {
pub count: usize,
pub detail: String,
pub kinds: Vec<String>,
pub last_seq: u64,
}
#[derive(Debug, Clone)]
pub struct VerifiedRun {
pub projection: RunProjection,
}
#[derive(Debug, Deserialize)]
struct RawTrace {
schema: String,
schema_version: u32,
run: RawRun,
source: RawTraceSource,
#[serde(default)]
truncated: Option<RawTruncation>,
#[serde(default)]
events: Vec<RawEvent>,
}
#[derive(Debug, Deserialize)]
struct RawRun {
#[serde(default)]
id: String,
#[serde(default)]
entry: Option<String>,
#[serde(default)]
status: String,
}
#[derive(Debug, Deserialize)]
struct RawTraceSource {
#[serde(default)]
root_id: String,
#[serde(default)]
analysis_digest: String,
}
#[derive(Debug, Deserialize)]
struct RawTruncation {
#[serde(default)]
reason: String,
#[serde(default)]
limit: u64,
#[serde(default)]
written: u64,
}
#[derive(Debug, Deserialize)]
struct RawEvent {
#[serde(default)]
seq: u64,
#[serde(default)]
kind: String,
#[serde(default)]
function_id: Option<String>,
#[serde(default)]
module_id: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
detail: Option<String>,
#[serde(default)]
operation: Option<String>,
#[serde(default)]
duration_micros: Option<u64>,
}
pub struct TraceVerificationInput<'a> {
pub trace_bytes: &'a [u8],
pub analysis_bytes: &'a [u8],
pub semantic: &'a SemanticProjection,
pub modules: &'a [ModuleSummary],
pub source: &'a str,
pub source_index: &'a SourceIndex,
pub run_json: &'a Value,
pub exit_code: i32,
}
/// Verify Trace v2 against the current Analysis and project it for the reader.
pub fn verify_trace(input: TraceVerificationInput<'_>) -> ViewResult<VerifiedRun> {
let raw: RawTrace =
serde_json::from_slice(input.trace_bytes).map_err(|err| ViewError::TraceStale {
detail: format!("Trace v2 is not valid JSON: {err}"),
})?;
if raw.schema != "marqdo.trace" {
return Err(ViewError::ProtocolIncompatible {
detail: format!("unexpected Trace schema {:?}", raw.schema),
});
}
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::protocol::tool_v1::TRACE_PROTOCOL
),
});
}
let expected_digest = sha256_prefixed(input.analysis_bytes);
if raw.source.analysis_digest != expected_digest {
return Err(ViewError::TraceStale {
detail: format!(
"trace.source.analysis_digest {} does not match current Analysis {}",
raw.source.analysis_digest, expected_digest
),
});
}
if raw.source.root_id != input.semantic.project_root_id {
return Err(ViewError::TraceStale {
detail: format!(
"trace.source.root_id {} does not match Analysis project {}",
raw.source.root_id, input.semantic.project_root_id
),
});
}
let known_modules: std::collections::HashSet<&str> = input
.modules
.iter()
.map(|module| module.id.as_str())
.collect();
for event in &raw.events {
if let Some(module) = event.module_id.as_deref() {
if !known_modules.contains(module) {
return Err(ViewError::TraceStale {
detail: format!(
"trace event seq {} references unknown module {module}",
event.seq
),
});
}
}
}
let entry_module = input.semantic.module_id.as_str();
let statements = input.semantic.all_statements();
let mut warnings = Vec::new();
let mut counts = EventCounts::default();
let mut entry_event_count = 0usize;
let mut other_event_count = 0usize;
let mut events = Vec::with_capacity(raw.events.len());
for event in raw.events {
let kind = TraceKind::parse(&event.kind);
match kind {
TraceKind::CallEnter => counts.call_enter += 1,
TraceKind::CallExit => counts.call_exit += 1,
TraceKind::BranchEval => counts.branch_eval += 1,
TraceKind::LoopIteration => counts.loop_iteration += 1,
TraceKind::Return => counts.return_events += 1,
TraceKind::Effect => counts.effect += 1,
_ => counts.other += 1,
}
let is_entry = event.module_id.as_deref() == Some(entry_module);
if is_entry {
entry_event_count += 1;
} else {
other_event_count += 1;
}
// Only entry-module spans can be anchored to the rendered document.
let (span, anchor_span) = if is_entry {
match event.span {
Some(span)
if input
.source_index
.validate_span_bytes(input.source.as_bytes(), span) =>
{
let anchor = statements
.iter()
.filter(|(_, statement)| {
statement.span == span
|| statement.condition_span == Some(span)
|| statement
.arms
.iter()
.any(|arm| arm.condition_span == Some(span))
})
.min_by_key(|(_, statement)| statement.span.len())
.map(|(_, statement)| statement.span)
.or_else(|| {
statements
.iter()
.filter(|(_, statement)| statement.span.contains(span))
.min_by_key(|(_, statement)| statement.span.len())
.map(|(_, statement)| statement.span)
});
(Some(span), anchor)
}
other => {
if other.is_some() {
warnings.push(format!(
"事件 seq {} 的 span 超出当前源码或不在 UTF-8 边界,已取消位置绑定",
event.seq
));
}
(None, None)
}
}
} else {
(None, None)
};
events.push(TraceEvent {
seq: event.seq,
kind,
function_id: event.function_id,
module_id: event.module_id,
span,
raw_span: event.span,
anchor_span,
detail: event.detail,
operation: event.operation,
duration_micros: event.duration_micros,
});
}
// Sequence numbers must be strictly increasing; a broken trace is stale.
for pair in events.windows(2) {
if pair[1].seq <= pair[0].seq {
return Err(ViewError::TraceStale {
detail: format!(
"trace seq is not strictly increasing ({} then {})",
pair[0].seq, pair[1].seq
),
});
}
}
let truncated = raw.truncated.map(|truncated| Truncation {
reason: truncated.reason,
limit: truncated.limit,
written: truncated.written,
});
let run_status = if raw.run.status.is_empty() {
"ok".to_string()
} else {
raw.run.status.clone()
};
let success = input
.run_json
.get("success")
.and_then(Value::as_bool)
.unwrap_or(false);
let error_code = input
.run_json
.get("error")
.and_then(|error| error.get("code"))
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| {
if run_status == "ok" {
None
} else {
Some(run_status.clone())
}
});
let state = if truncated.is_some() {
RunDisplayState::Truncated
} else if success && run_status == "ok" {
RunDisplayState::Succeeded
} else {
RunDisplayState::Failed
};
let stdout = bounded_text(input.run_json, "stdout", 64 * 1024);
let stderr = bounded_text(input.run_json, "stderr", 64 * 1024);
let result_value = input.run_json.get("value").and_then(|value| {
let ty = value.get("type").and_then(Value::as_str)?;
let display = value
.get("decimal")
.and_then(Value::as_str)
.or_else(|| value.get("text").and_then(Value::as_str))
.or_else(|| value.get("value").and_then(Value::as_str))
.map(str::to_string)
.unwrap_or_else(|| compact_json(value));
Some(RunValue {
ty: ty.to_string(),
display,
})
});
let _ = sha256_hex(input.trace_bytes);
Ok(VerifiedRun {
projection: RunProjection {
run_id: raw.run.id,
entry: raw.run.entry,
run_status,
state,
error_code,
analysis_digest: expected_digest,
events,
truncated,
stdout,
stderr,
exit_code: input.exit_code,
result_value,
counts,
entry_event_count,
other_event_count,
warnings,
},
})
}
fn bounded_text(run_json: &Value, key: &str, limit: usize) -> String {
let text = run_json
.get(key)
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
if text.len() <= limit {
text
} else {
let mut truncated: String = text.chars().take(limit).collect();
truncated.push_str("\n…(输出已截断)");
truncated
}
}
fn compact_json(value: &Value) -> String {
let text = value.to_string();
if text.chars().count() > 80 {
format!("{}…", text.chars().take(80).collect::<String>())
} else {
text
}
}
/// Build a stale run projection that keeps the raw result accessible without
/// binding any event to the current document.
pub fn stale_projection(analysis_digest: &str, source: &SourceIndex) -> RunProjection {
let _ = source;
RunProjection {
run_id: String::new(),
entry: None,
run_status: "stale".to_string(),
state: RunDisplayState::Stale,
error_code: Some("view.trace_stale".to_string()),
analysis_digest: analysis_digest.to_string(),
events: Vec::new(),
truncated: None,
stdout: String::new(),
stderr: String::new(),
exit_code: 0,
result_value: None,
counts: EventCounts::default(),
entry_event_count: 0,
other_event_count: 0,
warnings: vec!["Trace 与当前 Analysis 字节摘要不匹配,未绑定任何事件。".to_string()],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn state_values_are_stable() {
assert_eq!(RunDisplayState::Succeeded.data_value(), "succeeded");
assert_eq!(RunDisplayState::Truncated.data_value(), "truncated");
assert_eq!(RunDisplayState::Failed.data_value(), "failed");
assert_eq!(RunDisplayState::Stale.label(), "结果已过期");
}
#[test]
fn trace_kinds_are_additive_safe() {
assert_eq!(TraceKind::parse("branch.eval"), TraceKind::BranchEval);
assert_eq!(
TraceKind::parse("future.event"),
TraceKind::Other("future.event".to_string())
);
assert_eq!(
TraceKind::parse("future.event").data_value(),
"future.event"
);
}
}