From 8cd72b87b6291ceae769de081debe1b5dc826010 Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 27 Nov 2026 08:56:03 +0800 Subject: [PATCH] feat: handoff, design graph, single-component slice and drift (WEB-03) Extend the Design public API for delivery consumers: - handoff/handoff_relative_to derive deterministic Markdown from the model only: design id, source digests, component tree, separated visual containment and non-visual dependency graph, per-component source links, responsibility/visual notes from safe content blocks, inputs, events, scenarios, interactions, dependencies, acceptance and an explicit prototype/not-implemented boundary. Source links are recomputed relative to the output directory when requested. - graph() separates visual containment edges from dependency edges and reports dependency cycle groups (load still rejects cycles for coordination). - slice() selects one loaded component and its visual subtree as an independent Design with only the used sources (single-component delivery). - drift(previous,current) reports added/removed/changed components and changed source digests; design_id() is a deterministic identity for drift checks. - Non-visual dependency targets are loaded as definitions so the graph is explicit even when the dependency is not placed in the visual tree; a cycle on that path reports web.dependency.cycle. - Six new real-CLI tests cover deterministic handoff, relative links, drift, slicing, graph separation and the unchanged negative contract. Refs cflmy/marqdo-web-design#2, cflmy/marqdo#6 --- src/lib.rs | 398 +++++++++++++++++++++++++++++++++++---- tests/design_contract.rs | 156 +++++++++++++-- 2 files changed, 507 insertions(+), 47 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 1974028..58cf25a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -186,6 +186,8 @@ pub struct SourceIdentity { #[derive(Debug, Clone)] pub struct Design { pub root: String, + /// Canonical explicit design root; source links are derived from it. + pub root_dir: PathBuf, pub definitions: BTreeMap, pub instances: Vec, pub sources: Vec, @@ -926,8 +928,25 @@ impl Loader { } let (target_module, target_unit) = self.resolve_dependency_component(module, link)?; + // A dependency names a design component that may not be placed in + // this visual tree; load its definition so the graph is explicit. + let target_key = normalized_key(&target_module, target_unit.anchor_text()); + if self.stack.iter().any(|item| item == &target_key) { + return Err(design_error( + "web.dependency.cycle", + format!( + "design dependency cycle at {target_key}; coordination is required" + ), + )); + } + let target_key = self.load_definition( + &target_module, + &target_unit, + target_unit.anchor_text(), + depth + 1, + )?; dependencies.push(Dependency { - target: normalized_key(&target_module, target_unit.anchor_text()), + target: target_key, reason, span: json_span(cells[0].span), }); @@ -1177,6 +1196,7 @@ pub fn load(config: &LoadConfig) -> Result { sources.sort_by(|left, right| left.path.cmp(&right.path)); Ok(Design { root: root_key, + root_dir: root.clone(), definitions: loader.definitions, instances, sources, @@ -1205,81 +1225,389 @@ fn collect_instances( } } -/// Derive a Markdown handoff from the model only; never re-reads sources. +/// Deterministic design identity (FNV-1a over root, sources and definitions). +pub fn design_id(design: &Design) -> String { + fn fnv(bytes: &[u8]) -> u64 { + let mut hash = 0xcbf2_9ce4_8422_2325u64; + for byte in bytes { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x100_0000_01b3); + } + hash + } + let mut material = String::new(); + material.push_str(&design.root); + material.push('\n'); + for source in &design.sources { + material.push_str(&format!("{}:{}\n", source.path, source.source_digest)); + } + for (key, definition) in &design.definitions { + material.push_str(&format!("{key}:")); + for slot in &definition.slots { + material.push_str(&format!("{}:{};", slot.slot, slot.target)); + } + material.push('\n'); + } + format!( + "fnv128:{:016x}{:016x}", + fnv(material.as_bytes()), + material.len() + ) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DesignGraph { + /// Visual containment: parent definition key -> child definition key (+slot). + pub visual_edges: Vec<(String, String, String)>, + /// Non-visual design dependencies: definition key -> target definition key. + pub dependency_edges: Vec<(String, String, String)>, + /// Dependency cycles that need coordination (normally empty; load rejects them). + pub dependency_cycles: Vec>, +} + +pub fn graph(design: &Design) -> DesignGraph { + let mut visual_edges = Vec::new(); + let mut dependency_edges = Vec::new(); + for (key, definition) in &design.definitions { + for slot in &definition.slots { + visual_edges.push((key.clone(), slot.target.clone(), slot.slot.clone())); + } + for dependency in &definition.dependencies { + dependency_edges.push(( + key.clone(), + dependency.target.clone(), + dependency.reason.clone(), + )); + } + } + let mut adjacency: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); + for (from, to, _) in &dependency_edges { + adjacency + .entry(from.as_str()) + .or_default() + .push(to.as_str()); + } + let mut cycles: Vec> = Vec::new(); + let mut done: BTreeSet<&str> = BTreeSet::new(); + fn walk<'a>( + node: &'a str, + adjacency: &BTreeMap<&'a str, Vec<&'a str>>, + stack: &mut Vec<&'a str>, + done: &mut BTreeSet<&'a str>, + cycles: &mut Vec>, + ) { + if done.contains(node) { + return; + } + if let Some(position) = stack.iter().position(|item| *item == node) { + cycles.push( + stack[position..] + .iter() + .map(|item| item.to_string()) + .collect(), + ); + return; + } + stack.push(node); + if let Some(targets) = adjacency.get(node) { + for target in targets { + walk(target, adjacency, stack, done, cycles); + } + } + stack.pop(); + done.insert(node); + } + for node in adjacency.keys() { + let mut stack = Vec::new(); + walk(node, &adjacency, &mut stack, &mut done, &mut cycles); + } + cycles.sort(); + cycles.dedup(); + DesignGraph { + visual_edges, + dependency_edges, + dependency_cycles: cycles, + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Drift { + pub added_components: Vec, + pub removed_components: Vec, + pub changed_components: Vec, + pub changed_sources: Vec, + pub unchanged: bool, +} + +/// Compare two accepted designs; a changed source digest or component model is drift. +pub fn drift(previous: &Design, current: &Design) -> Drift { + let mut added = Vec::new(); + let mut removed = Vec::new(); + let mut changed = Vec::new(); + for key in current.definitions.keys() { + match previous.definitions.get(key) { + None => added.push(key.clone()), + Some(before) if before != ¤t.definitions[key] => changed.push(key.clone()), + Some(_) => {} + } + } + for key in previous.definitions.keys() { + if !current.definitions.contains_key(key) { + removed.push(key.clone()); + } + } + let mut changed_sources = Vec::new(); + let previous_sources: BTreeMap<&str, &str> = previous + .sources + .iter() + .map(|source| (source.path.as_str(), source.source_digest.as_str())) + .collect(); + let current_sources: BTreeMap<&str, &str> = current + .sources + .iter() + .map(|source| (source.path.as_str(), source.source_digest.as_str())) + .collect(); + for path in current_sources.keys() { + if previous_sources.get(path) != current_sources.get(path) { + changed_sources.push(path.to_string()); + } + } + for path in previous_sources.keys() { + if !current_sources.contains_key(path) { + changed_sources.push(path.to_string()); + } + } + added.sort(); + removed.sort(); + changed.sort(); + changed_sources.sort(); + let unchanged = + added.is_empty() && removed.is_empty() && changed.is_empty() && changed_sources.is_empty(); + Drift { + added_components: added, + removed_components: removed, + changed_components: changed, + changed_sources, + unchanged, + } +} + +/// Select one loaded component and its visual subtree as an independent Design. +pub fn slice(design: &Design, component: &str) -> Result { + if !design.definitions.contains_key(component) { + return Err(design_error( + "web.slice.unknown", + format!("unknown component definition {component:?}"), + )); + } + let mut keys: BTreeSet = BTreeSet::new(); + let mut queue = vec![component.to_string()]; + while let Some(key) = queue.pop() { + if !keys.insert(key.clone()) { + continue; + } + if let Some(definition) = design.definitions.get(&key) { + for slot in &definition.slots { + queue.push(slot.target.clone()); + } + } + } + let definitions: BTreeMap = design + .definitions + .iter() + .filter(|(key, _)| keys.contains(*key)) + .map(|(key, definition)| (key.clone(), definition.clone())) + .collect(); + let mut instances = Vec::new(); + collect_instances(&definitions, component, "root", &mut instances); + let used_paths: BTreeSet = definitions + .values() + .map(|definition| definition.source.path.clone()) + .collect(); + let sources = design + .sources + .iter() + .filter(|source| used_paths.contains(&source.path)) + .cloned() + .collect(); + Ok(Design { + root: component.to_string(), + root_dir: design.root_dir.clone(), + definitions, + instances, + sources, + }) +} + +fn relative_link(base: Option<&Path>, root: &Path, path: &str) -> String { + let Some(base) = base else { + return path.to_string(); + }; + let target = root.join(path); + let base_components: Vec<_> = base.components().collect(); + let target_components: Vec<_> = target.components().collect(); + let mut common = 0; + while common < base_components.len() + && common < target_components.len() + && base_components[common] == target_components[common] + { + common += 1; + } + let mut relative = PathBuf::new(); + for _ in common..base_components.len() { + relative.push(".."); + } + for component in &target_components[common..] { + relative.push(component.as_os_str()); + } + relative.to_string_lossy().replace('\\', "/") +} + +fn push_source_link(out: &mut String, base: Option<&Path>, design: &Design, source: &SourceRef) { + let link = relative_link(base, &design.root_dir, &source.path); + out.push_str(&format!( + "- [{}]({}#{}) — `sha256:{}`\n", + source.path, link, source.anchor, source.source_digest + )); +} + +/// Derive the Markdown handoff from the model only; never re-reads sources. +/// Links are project-relative (authoritative when the handoff stays in-project). pub fn handoff(design: &Design) -> String { + handoff_with_base(design, None) +} + +/// Handoff whose source links are recomputed relative to an output directory. +pub fn handoff_relative_to(design: &Design, output_dir: &Path) -> String { + handoff_with_base(design, Some(output_dir)) +} + +fn handoff_with_base(design: &Design, base: Option<&Path>) -> String { + let graph = graph(design); let mut out = String::new(); out.push_str("# Design handoff\n\n"); - out.push_str(&format!("root: `{}`\n\n", design.root)); - out.push_str("## Component tree\n\n"); + out.push_str(&format!("- design id: `{}`\n", design_id(design))); + out.push_str(&format!("- root: `{}`\n\n", design.root)); + out.push_str("## Sources\n\n"); + for source in &design.sources { + out.push_str(&format!( + "- `{}` — `sha256:{}`\n", + source.path, source.source_digest + )); + } + out.push_str("\n## Component tree\n\n"); for instance in &design.instances { - let definition = design.definitions.get(&instance.definition); let depth = instance.id.matches('/').count(); let indent = " ".repeat(depth); out.push_str(&format!( - "{indent}- `{}` ({})", + "{indent}- `{}` → `{}`\n", instance.id, instance.definition )); - if let Some(definition) = definition { + } + out.push_str("\n## Design graph\n\n"); + out.push_str("Visual containment:\n"); + for (parent, child, slot) in &graph.visual_edges { + out.push_str(&format!("- `{parent}` --{slot}--> `{child}`\n")); + } + out.push_str("\nNon-visual dependencies:\n"); + if graph.dependency_edges.is_empty() { + out.push_str("- 未声明\n"); + } + for (from, to, reason) in &graph.dependency_edges { + out.push_str(&format!("- `{from}` -> `{to}`: {reason}\n")); + } + if !graph.dependency_cycles.is_empty() { + out.push_str("\nDependency cycle groups (需要协调,不自动宣称可并行):\n"); + for group in &graph.dependency_cycles { + out.push_str(&format!("- {}\n", group.join(" -> "))); + } + } + out.push_str("\n## Components\n\n"); + for (key, definition) in &design.definitions { + out.push_str(&format!("### `{key}`\n\n")); + out.push_str("Source:\n"); + push_source_link(&mut out, base, design, &definition.source); + let instances: Vec<&str> = design + .instances + .iter() + .filter(|instance| &instance.definition == key) + .map(|instance| instance.id.as_str()) + .collect(); + if !instances.is_empty() { + out.push_str(&format!("\nInstances: {}\n", instances.join(", "))); + } + if !definition.content.is_empty() { + out.push_str("\nResponsibility / visual notes:\n"); + for block in &definition.content { + let text = block.text.trim(); + if !text.is_empty() { + out.push_str(&format!( + "- ({}) `{}`\n", + block.kind, + text.replace('`', "\\`").replace('\n', " ") + )); + } + } + } + out.push_str(&format!("\nLayout slots ({}):\n", definition.slots.len())); + for slot in &definition.slots { out.push_str(&format!( - " — {} [{}]", - definition.source.path, definition.source.anchor + "- row {} slot `{}` width `{}` -> `{}`\n", + slot.row, slot.slot, slot.width, slot.target )); } - out.push('\n'); - if let Some(definition) = definition { - for slot in &definition.slots { - out.push_str(&format!( - "{indent} - slot `{}` row {} {} -> `{}`\n", - slot.slot, slot.row, slot.width, slot.target - )); - } + if !definition.inputs.is_empty() { + out.push_str("\nInputs:\n"); for input in &definition.inputs { out.push_str(&format!( - "{indent} - input `{}` ({}) {}\n", + "- `{}` ({}) {}\n", input.name, input.entry_type, input.description )); } + } + if !definition.events.is_empty() { + out.push_str("\nEvents:\n"); for event in &definition.events { out.push_str(&format!( - "{indent} - event `{}` ({}) {}\n", + "- `{}` ({}) {}\n", event.name, event.data, event.description )); } + } + if !definition.scenarios.is_empty() { + out.push_str("\nScenarios:\n"); for scenario in &definition.scenarios { out.push_str(&format!( - "{indent} - scenario `{}`{} -> `{}#{}`\n", + "- `{}`{} content `{}#{}`\n", scenario.state, if scenario.initial { " (initial)" } else { "" }, scenario.content.path, scenario.content.anchor )); } + } + if !definition.interactions.is_empty() { + out.push_str("\nInteractions:\n"); for interaction in &definition.interactions { out.push_str(&format!( - "{indent} - transition `{}` --{}--> `{}`\n", + "- `{}` --{}--> `{}`\n", interaction.current, interaction.event, interaction.next )); } + } + if !definition.dependencies.is_empty() { + out.push_str("\nDependencies:\n"); for dependency in &definition.dependencies { out.push_str(&format!( - "{indent} - dependency `{}`: {}\n", + "- `{}`: {}\n", dependency.target, dependency.reason )); } - if let Some(acceptance) = &definition.acceptance { - out.push_str(&format!( - "{indent} - acceptance: {}\n", - acceptance.text.replace('\n', " ") - )); - } } - } - out.push_str("\n## Sources\n\n"); - for source in &design.sources { - out.push_str(&format!( - "- `{}` digest `sha256:{}`\n", - source.path, source.source_digest - )); + if let Some(acceptance) = &definition.acceptance { + out.push_str(&format!("\nAcceptance:\n{}\n", acceptance.text)); + } + out.push_str("\n未实现/边界: 原型与模拟交付;真实业务功能、登录/支付/数据库/网络由目标应用实现;本 handoff 不生成生产代码。\n\n"); } out } diff --git a/tests/design_contract.rs b/tests/design_contract.rs index d711c83..e637f6a 100644 --- a/tests/design_contract.rs +++ b/tests/design_contract.rs @@ -3,7 +3,10 @@ use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; -use marqdo_web_design::{handoff, load, statistics, Error, LoadConfig}; +use marqdo_web_design::{ + design_id, drift, graph, handoff, handoff_relative_to, load, slice, statistics, Error, + LoadConfig, +}; static UNIQUE: AtomicU64 = AtomicU64::new(0); @@ -356,10 +359,13 @@ fn loads_full_leaf_contract_inputs_events_scenarios_interactions_dependencies() assert_eq!(a.dependencies[0].target, "components/b.mq.md#乙"); assert!(a.acceptance.as_ref().unwrap().text.contains("模拟保存")); let text = handoff(&design); - assert!(text.contains("scenario `empty` (initial)")); - assert!(text.contains("transition `empty` --模拟保存--> `done`")); - assert!(text.contains("dependency `components/b.mq.md#乙`")); - assert!(text.contains("acceptance:")); + assert!(text.contains("Scenarios:")); + assert!(text.contains("`empty` (initial)")); + assert!(text.contains("Interactions:")); + assert!(text.contains("--模拟保存--> `done`")); + assert!(text.contains("Dependencies:")); + assert!(text.contains("`components/b.mq.md#乙`: 提交后展示详情")); + assert!(text.contains("Acceptance:")); } fn leaf_project(sections: &str) -> TempProject { @@ -456,15 +462,11 @@ fn rejects_invalid_inputs_dependencies_and_acceptance() { ); let unknown = leaf_project( - "### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [目标](target.mq.md#目标) | 需要 |\n", - ); - unknown.write( - "target.mq.md", - "# 目标页面\n\n## @knowledge 目标\n\n### 内容\n\nx\n", + "### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [目标](missing.mq.md#目标) | 需要 |\n", ); assert_eq!( design_code(load(&unknown.config("a.mq.md", "甲")).unwrap_err()), - "web.dependency.unknown" + "web.dependency.target" ); let empty = leaf_project("### 验收\n\n \n"); @@ -550,7 +552,8 @@ fn projects_safe_content_blocks_for_components_and_scenarios() { .iter() .all(|scene| !scene.content_blocks.is_empty())); let text = handoff(&design); - assert!(text.contains("scenario `only`")); + assert!(text.contains("Scenarios:")); + assert!(text.contains("`only`")); } #[test] @@ -668,3 +671,132 @@ fn resolves_outside_scope_links_that_stay_inside_the_explicit_root() { "shared/b.mq.md#乙" ); } + +#[test] +fn handoff_is_deterministic_and_contains_graph_sources_and_contracts() { + let project = TempProject::new(); + project.write( + "index.mq.md", + "# 页面\n\n## @knowledge 工作台\n\n### 内容\n\n页面职责。\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [A](a.mq.md#甲) | auto |\n| 1 | b | [B](b.mq.md#乙) | auto |\n", + ); + project.write( + "a.mq.md", + "# A 组件\n\n## @knowledge 甲\n\n### 输入\n\n| 名称 | 类型 | 说明 |\n| --- | --- | --- |\n| x | Text | 输入 |\n\n### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| only | [样例](states.mq.md#空状态) | true |\n\n### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [B](b.mq.md#乙) | 组合交付 |\n\n### 验收\n\n- A 可见。\n", + ); + project.write( + "b.mq.md", + "# B 组件\n\n## @knowledge 乙\n\n### 内容\n\nB 正文。\n", + ); + project.write("states.mq.md", STATES); + let design = load(&project.config("index.mq.md", "工作台")).expect("load"); + let first = handoff(&design); + assert_eq!(first, handoff(&design)); + assert_eq!( + first, + handoff(&load(&project.config("index.mq.md", "工作台")).expect("reload")) + ); + assert!(first.contains("design id:")); + assert!(first.contains("## Sources")); + assert!(first.contains("## Design graph")); + assert!(first.contains("Visual containment:")); + assert!(first.contains("Non-visual dependencies:")); + assert!(first.contains("--a-->")); + assert!(first.contains("`a.mq.md#甲`")); + assert!(first.contains("Inputs:")); + assert!(first.contains("Scenarios:")); + assert!(first.contains("Acceptance:")); + assert!(first.contains("未实现/边界")); + assert!(first.contains("sha256:")); +} + +#[test] +fn handoff_relative_to_recomputes_source_links_for_another_directory() { + let project = basic_project(); + let design = load(&project.config("index.mq.md", "工作台")).expect("load"); + let out_dir = project.path.join("deliver/out"); + std::fs::create_dir_all(&out_dir).unwrap(); + let text = handoff_relative_to(&design, &out_dir); + assert!(!text.contains(&format!("({}", project.path.display()))); + assert!(text.contains("../../components/leaf.mq.md#叶子")); +} + +#[test] +fn drift_reports_changed_components_and_sources_only() { + let project = basic_project(); + let before = load(&project.config("index.mq.md", "工作台")).expect("load v1"); + let before_id = design_id(&before); + project.write( + "components/nav.mq.md", + "# 导航组件\n\n## @knowledge 导航\n\n### 内容\n\n更新后的导航正文。\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | leaf | [叶子](leaf.mq.md#叶子) | auto |\n", + ); + let after = load(&project.config("index.mq.md", "工作台")).expect("load v2"); + assert_ne!(before_id, design_id(&after)); + let report = drift(&before, &after); + assert!(!report.unchanged); + assert_eq!(report.changed_components, vec!["components/nav.mq.md#导航"]); + assert_eq!(report.changed_sources, vec!["components/nav.mq.md"]); + assert!(!report + .changed_components + .contains(&"components/leaf.mq.md#叶子".to_string())); + assert!(drift(&after, &after).unchanged); +} + +#[test] +fn slice_keeps_only_the_visual_subtree_and_its_sources() { + let project = basic_project(); + let design = load(&project.config("index.mq.md", "工作台")).expect("load"); + let sliced = slice(&design, "components/nav.mq.md#导航").expect("slice"); + assert_eq!(sliced.root, "components/nav.mq.md#导航"); + assert_eq!( + sliced.definitions.keys().cloned().collect::>(), + vec!["components/leaf.mq.md#叶子", "components/nav.mq.md#导航"] + ); + let ids: Vec<&str> = sliced + .instances + .iter() + .map(|item| item.id.as_str()) + .collect(); + assert_eq!(ids, vec!["root", "root/leaf"]); + let sources: Vec<&str> = sliced + .sources + .iter() + .map(|item| item.path.as_str()) + .collect(); + assert_eq!( + sources, + vec!["components/leaf.mq.md", "components/nav.mq.md"] + ); + assert!(slice(&design, "missing").is_err()); +} + +#[test] +fn graph_separates_visual_containment_from_design_dependencies() { + let project = TempProject::new(); + project.write( + "index.mq.md", + "# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [A](a.mq.md#甲) | auto |\n", + ); + project.write( + "a.mq.md", + "# A 组件\n\n## @knowledge 甲\n\n### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [B](b.mq.md#乙) | 共享合同 |\n", + ); + project.write( + "b.mq.md", + "# B 组件\n\n## @knowledge 乙\n\n### 内容\n\nB。\n", + ); + let design = load(&project.config("index.mq.md", "工作台")).expect("load"); + let graph = graph(&design); + assert!(graph + .visual_edges + .iter() + .any(|(parent, child, slot)| parent == "index.mq.md#工作台" + && child == "a.mq.md#甲" + && slot == "a")); + assert!(graph + .dependency_edges + .iter() + .any(|(from, to, reason)| from == "a.mq.md#甲" + && to == "b.mq.md#乙" + && reason == "共享合同")); + assert!(graph.dependency_cycles.is_empty()); +}