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

@@ -49,7 +49,7 @@ fn reused_assets_match_their_recorded_hashes() {
#[test]
fn embedded_asset_bundle_matches_disk_and_has_one_theme() {
let bundle = marqdo_view::assets::AssetBundle::get();
let bundle = marqdo_view::reader::assets::AssetBundle::get();
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let css = std::fs::read(root.join("assets/reader.css")).unwrap();
assert_eq!(sha256_hex(&css), bundle.css().sha256);
@@ -1,7 +1,7 @@
//! CLI surface tests: this program owns its own help/subcommands and refuses
//! unsafe defaults. Exit codes follow RFC-VIEW-0001 §10.2.
mod common;
use crate::common;
use common::run_view;
@@ -76,7 +76,7 @@ fn degradation_without_core_keeps_prose_readable() {
project.marqdo_project("# @knowledge 标题\n\n正文 **加粗**。\n");
// Explicitly point at a missing core so the test is independent of the
// caller environment (acceptance scripts export MARQDO_BIN).
let context = marqdo_view::app::AppContext::open(
let context = marqdo_view::reader::assemble::DocumentService::open(
&project.dir,
Some(std::path::Path::new("/definitely/missing/marqdo-frozen")),
)
@@ -4,11 +4,11 @@
//! The fake core is a shell script, not a mocked Rust trait, so everything at
//! the process boundary is exercised for real.
mod common;
use crate::common;
use common::{minimal_analysis, sha256_hex, FakeCore, TempProject};
use marqdo_view::core_client::{CheckOptions, CheckResponse, CoreClient, RunOptions};
use marqdo_view::project::Project;
use marqdo_view::reader::source::Project;
fn fixture(name: &str) -> (TempProject, FakeCore) {
let project = TempProject::new(name);
+12
View File
@@ -0,0 +1,12 @@
//! Contract suite: the frozen CLI black-box process contract, Analysis v2 /
//! Trace v2 validation, the View CLI surface, and architecture/asset gates.
#[path = "../common/mod.rs"]
mod common;
mod asset_integrity;
mod cli_surface;
mod core_contract;
mod no_coupling;
mod presentation_states;
mod trace_contract;
File renamed without changes.
@@ -1,11 +1,11 @@
//! Degradation/state matrix contract (RFC-VIEW-0001 S-05..S-07, §12.3):
//! prose stays readable while semantics become explicitly unusable.
mod common;
use crate::common;
use common::{minimal_analysis, sha256_hex, FakeCore, TempProject};
use marqdo_view::app::AppContext;
use marqdo_view::presentation::SourceStatus;
use marqdo_view::reader::assemble::DocumentService;
use marqdo_view::reader::model::SourceStatus;
fn project(name: &str) -> (TempProject, FakeCore) {
let project = TempProject::new(name);
@@ -24,7 +24,7 @@ fn failed_check_keeps_prose_and_shows_core_diagnostics() {
core.set_check_json(
r#"{"command":"check","success":false,"errors":1,"diagnostics":[{"code":"sem.unclosed_control","column":1,"file":"/home/secret/index.mq.md","line":3,"message":"`if` is not closed by `end`","module":"root:fixture@0.1.0::index.mq.md","severity":"error"}]}"#,
);
let context = AppContext::open(&project.dir, Some(&core.script)).unwrap();
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
let relative = context.project().entry().relative.clone();
let model = context.load(&relative).unwrap();
assert_eq!(model.source_status, SourceStatus::CoreError);
@@ -46,7 +46,7 @@ fn failed_check_keeps_prose_and_shows_core_diagnostics() {
fn source_digest_mismatch_degrades_instead_of_misbinding() {
let (project, core) = project("state-source-mismatch");
core.set_analysis(&minimal_analysis("index.mq.md", &"0".repeat(64), 2));
let context = AppContext::open(&project.dir, Some(&core.script)).unwrap();
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
let relative = context.project().entry().relative.clone();
let model = context.load(&relative).unwrap();
assert_eq!(model.source_status, SourceStatus::SourceMismatch);
@@ -59,7 +59,7 @@ fn unknown_analysis_schema_is_a_hard_protocol_error() {
let (project, core) = project("state-protocol");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3));
let context = AppContext::open(&project.dir, Some(&core.script)).unwrap();
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
let relative = context.project().entry().relative.clone();
let err = context.load(&relative).unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
@@ -78,7 +78,7 @@ fn invalid_core_span_is_dropped_with_an_explicit_warning() {
"span": {"start": 0, "end": 999_999}
}]);
core.set_analysis(&serde_json::to_string(&analysis).unwrap());
let context = AppContext::open(&project.dir, Some(&core.script)).unwrap();
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
let relative = context.project().entry().relative.clone();
let model = context.load(&relative).unwrap();
assert_eq!(model.source_status, SourceStatus::StaticOk);
@@ -105,30 +105,36 @@ fn run_attached_to_changed_source_becomes_stale() {
let analysis =
std::fs::read(repo_root.join("tests/golden/analysis-v2/control-flow.json")).unwrap();
core.set_analysis(std::str::from_utf8(&analysis).unwrap());
let context = AppContext::open(&project.dir, Some(&core.script)).unwrap();
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
let relative = context.project().entry().relative.clone();
// Build a verified run directly from the golden trace + golden analysis.
let source_index = marqdo_view::source_map::SourceIndex::new(&source);
let verified_analysis =
marqdo_view::semantic::verify_analysis(&analysis, &source, &source_index, "index.mq.md")
.unwrap();
let source_index = marqdo_view::reader::source::SourceIndex::new(&source);
let verified_analysis = marqdo_view::protocol::analysis_v2::verify_analysis(
&analysis,
&source,
&source_index,
"index.mq.md",
)
.unwrap();
let trace =
std::fs::read(repo_root.join("tests/golden/trace-v2/control-flow.trace.json")).unwrap();
let run_json: serde_json::Value = serde_json::from_slice(
&std::fs::read(repo_root.join("tests/golden/trace-v2/control-flow.run.json")).unwrap(),
)
.unwrap();
let run = marqdo_view::trace::verify_trace(marqdo_view::trace::TraceVerificationInput {
trace_bytes: &trace,
analysis_bytes: &analysis,
semantic: &verified_analysis.projection,
modules: &verified_analysis.projection.modules,
source: &source,
source_index: &source_index,
run_json: &run_json,
exit_code: 0,
})
let run = marqdo_view::protocol::trace_v2::verify_trace(
marqdo_view::protocol::trace_v2::TraceVerificationInput {
trace_bytes: &trace,
analysis_bytes: &analysis,
semantic: &verified_analysis.projection,
modules: &verified_analysis.projection.modules,
source: &source,
source_index: &source_index,
run_json: &run_json,
exit_code: 0,
},
)
.unwrap();
let attached = context.load_with_run(&relative, Some(&run)).unwrap();
assert_eq!(attached.run_state().data_value(), "succeeded");
@@ -2,9 +2,9 @@
//! goldens bind to the committed Analysis v2 bytes by digest, so a changed
//! source cannot silently reuse an old trace.
use marqdo_view::semantic;
use marqdo_view::source_map::{sha256_prefixed, SourceIndex};
use marqdo_view::trace::{verify_trace, RunDisplayState, TraceVerificationInput};
use marqdo_view::protocol::analysis_v2 as semantic;
use marqdo_view::protocol::trace_v2::{verify_trace, RunDisplayState, TraceVerificationInput};
use marqdo_view::reader::source::{sha256_prefixed, SourceIndex};
use serde_json::Value;
struct Fixture {
@@ -43,7 +43,7 @@ fn verify(
trace_golden: &str,
run_golden: &str,
exit_code: i32,
) -> marqdo_view::trace::VerifiedRun {
) -> marqdo_view::protocol::trace_v2::VerifiedRun {
let trace = golden_bytes(trace_golden);
let run_json = golden_json(run_golden);
verify_trace(TraceVerificationInput {
@@ -1,7 +1,7 @@
//! Static export contract tests: pure read-only, same renderer, offline assets,
//! safe output paths and no execution (RFC-VIEW-0001 §11.3, R-02, X-04).
mod common;
use crate::common;
use common::{run_view, sha256_hex, FakeCore, TempProject};
use std::path::{Path, PathBuf};
@@ -124,7 +124,7 @@ fn exports_offline_site_with_shared_renderer_and_relative_links() {
assert_eq!(sha256_hex(&bytes), entry["sha256"].as_str().unwrap());
}
// Assets are exactly the embedded bundle bytes.
let bundle = marqdo_view::assets::AssetBundle::get();
let bundle = marqdo_view::reader::assets::AssetBundle::get();
let css = std::fs::read(out.join("assets").join(bundle.hashed_css_name())).unwrap();
assert_eq!(css, bundle.css_bytes());
@@ -2,7 +2,7 @@
//! The server is a real child process so startup, URL output, routing, security
//! headers, CSRF and the explicit-run flow are exercised end to end.
mod common;
use crate::common;
use common::{run_view, FakeCore};
use std::io::{BufRead, BufReader, Read, Write};
@@ -567,3 +567,23 @@ fn cli_verify_output_contract_still_holds_for_installed_style_invocation() {
assert_eq!(json["executed"], false);
assert_eq!(json["analysis"]["schema_version"], 2);
}
#[test]
fn documents_api_is_a_read_only_structure_and_old_route_is_gone() {
let server = start_server();
let response = http_get(server.port, None, "/api/documents");
assert_eq!(response.status, 200);
let body = json_body(&response.body);
assert_eq!(body["schema"], "marqdo.view-documents");
assert_eq!(body["schema_version"], 1);
assert!(body["documents"].is_array());
assert!(body["documents"].as_array().unwrap().len() >= 2);
assert!(body["current"]["relative_path"].is_string());
assert!(body["current"]["outline"].is_array());
assert!(body["current"]["note"].is_null() || body["current"]["note"].is_string());
assert!(body["note"].as_str().unwrap().contains("never executes"));
// The old singular route is not part of the target API surface.
let old = http_get(server.port, None, "/api/document?path=index.mq.md");
assert_eq!(old.status, 404);
}
+10
View File
@@ -0,0 +1,10 @@
//! Integration suite: the Live HTTP surface, the one renderer, Unicode span
//! mapping and the static export path.
#[path = "../common/mod.rs"]
mod common;
mod export;
mod http_live;
mod rendering;
mod unicode_spans;
@@ -1,15 +1,15 @@
//! Rendering contract tests: one renderer, safe Markdown, exact source view,
//! verified semantic annotations and Live/Export link differences.
mod common;
use marqdo_view::config::ViewConfig;
use marqdo_view::protocol::analysis_v2 as semantic;
use marqdo_view::reader::assemble::{self as assemble, BuildInput};
use marqdo_view::reader::markdown::{DocumentIdentity, DocumentModel};
use marqdo_view::reader::model::{Navigation, SourceStatus};
use marqdo_view::reader::render::{ReaderRenderer, RenderContext};
use marqdo_view::reader::source::{Project, SafeRelativePath};
use marqdo_view::document::{DocumentIdentity, DocumentModel};
use marqdo_view::presentation::{self, BuildInput, Navigation, SourceStatus};
use marqdo_view::project::{Project, SafeRelativePath, ViewConfig};
use marqdo_view::render::{ReaderRenderer, RenderContext};
use marqdo_view::semantic;
fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String) {
fn example(name: &str) -> (marqdo_view::reader::model::PresentationModel, String) {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("examples")
.join(name);
@@ -29,7 +29,7 @@ fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String)
.unwrap_or_else(|err| panic!("golden does not verify for {name}: {err}"));
let config = ViewConfig::load(project.root()).unwrap_or_default();
let navigation = Navigation::from_project(&project, &config, &entry);
let model = presentation::build(BuildInput {
let model = assemble::build(BuildInput {
document,
analysis: Some(&verified),
status: SourceStatus::StaticOk,
@@ -42,13 +42,13 @@ fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String)
(model, source)
}
fn render_live(model: &marqdo_view::presentation::PresentationModel) -> String {
fn render_live(model: &marqdo_view::reader::model::PresentationModel) -> String {
ReaderRenderer::new()
.render(model, &RenderContext::live())
.html
}
fn render_static(model: &marqdo_view::presentation::PresentationModel, depth: usize) -> String {
fn render_static(model: &marqdo_view::reader::model::PresentationModel, depth: usize) -> String {
ReaderRenderer::new()
.render(model, &RenderContext::static_site(depth))
.html
@@ -203,7 +203,7 @@ fn malicious_markdown_cannot_inject_markup_or_scripts() {
&config,
&SafeRelativePath::parse("index.mq.md").unwrap(),
);
let model = presentation::build(BuildInput {
let model = assemble::build(BuildInput {
document,
analysis: None,
status: SourceStatus::CoreUnavailable,
@@ -250,3 +250,14 @@ fn run_controls_are_explicitly_unavailable_before_pr04() {
assert!(!html.contains("data-run-state=\"running\""));
assert!(!html.contains("data-run-state=\"succeeded\""));
}
#[test]
fn reader_exposes_simple_theme_toggle_and_no_variable_or_memory_tabs() {
let (model, _source) = example("welcome");
let html = render_live(&model);
assert!(html.contains("data-theme=\"light\""));
assert!(html.contains("data-action=\"theme\""));
assert!(!html.contains("data-action=\"variables\""));
assert!(!html.contains("data-action=\"memory\""));
assert!(html.contains("data-action=\"unsupported\""));
}
@@ -1,12 +1,14 @@
//! Unicode/CRLF/duplicate-text span contract (RFC-VIEW-0001 S-04).
//! Goldens are emitted by the frozen CLI from the exact fixture bytes.
use marqdo_view::document::{DocumentIdentity, DocumentModel};
use marqdo_view::presentation::{self, BuildInput, Navigation, SourceStatus};
use marqdo_view::project::{Project, SafeRelativePath, ViewConfig};
use marqdo_view::render::{ReaderRenderer, RenderContext};
use marqdo_view::semantic;
use marqdo_view::source_map::sha256_hex;
use marqdo_view::config::ViewConfig;
use marqdo_view::protocol::analysis_v2 as semantic;
use marqdo_view::reader::assemble::{self as assemble, BuildInput};
use marqdo_view::reader::markdown::{DocumentIdentity, DocumentModel};
use marqdo_view::reader::model::{Navigation, SourceStatus};
use marqdo_view::reader::render::{ReaderRenderer, RenderContext};
use marqdo_view::reader::source::sha256_hex;
use marqdo_view::reader::source::{Project, SafeRelativePath};
fn repo_root() -> std::path::PathBuf {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -15,7 +17,7 @@ fn repo_root() -> std::path::PathBuf {
fn load(path: &str, golden: &str) -> (String, Vec<u8>, semantic::VerifiedAnalysis) {
let root = repo_root();
let source = std::fs::read_to_string(root.join(path)).unwrap();
let index = marqdo_view::source_map::SourceIndex::new(&source);
let index = marqdo_view::reader::source::SourceIndex::new(&source);
let analysis = std::fs::read(root.join(golden)).unwrap();
let relative = std::path::Path::new(path)
.file_name()
@@ -32,7 +34,7 @@ fn render(verified: &semantic::VerifiedAnalysis, source: &str, relative: &str) -
let entry = SafeRelativePath::parse(relative).unwrap();
let document = DocumentModel::parse(source.to_string(), DocumentIdentity::placeholder(&entry));
let navigation = Navigation::from_project(&project, &ViewConfig::default(), &entry);
let model = presentation::build(BuildInput {
let model = assemble::build(BuildInput {
document,
analysis: Some(verified),
status: SourceStatus::StaticOk,
@@ -67,7 +69,7 @@ fn unicode_spans_are_exact_and_duplicate_returns_get_distinct_anchors() {
let first = returns[0].span;
let second = returns[1].span;
assert_ne!(first, second);
let index = marqdo_view::source_map::SourceIndex::new(&source);
let index = marqdo_view::reader::source::SourceIndex::new(&source);
// Core statement spans cover the whole carrier node (including markers).
assert_eq!(index.source_text(&source, first), Some("`return 1`"));
assert_eq!(index.source_text(&source, second), Some("`return 1`"));
@@ -106,7 +108,7 @@ fn crlf_source_keeps_exact_digest_and_line_mapping() {
verified.projection.source_digest,
sha256_hex(source.as_bytes())
);
let index = marqdo_view::source_map::SourceIndex::new(&source);
let index = marqdo_view::reader::source::SourceIndex::new(&source);
let function = &verified.projection.functions[0];
for (_, statement) in verified
.projection
@@ -137,7 +139,7 @@ fn knowledge_emphasis_never_becomes_an_execution_anchor() {
let project = Project::open(&root.join("examples/mixed-modes")).unwrap();
let entry = project.entry().relative.clone();
let source = project.read_source_text(&entry).unwrap();
let index = marqdo_view::source_map::SourceIndex::new(&source);
let index = marqdo_view::reader::source::SourceIndex::new(&source);
let analysis = std::fs::read(root.join("tests/golden/analysis-v2/mixed-modes.json")).unwrap();
let verified = semantic::verify_analysis(&analysis, &source, &index, entry.as_str()).unwrap();
assert_eq!(
@@ -146,7 +148,7 @@ fn knowledge_emphasis_never_becomes_an_execution_anchor() {
);
let document = DocumentModel::parse(source.clone(), DocumentIdentity::placeholder(&entry));
let navigation = Navigation::from_project(&project, &ViewConfig::default(), &entry);
let model = presentation::build(BuildInput {
let model = assemble::build(BuildInput {
document,
analysis: Some(&verified),
status: SourceStatus::StaticOk,