Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b6607fd3c | ||
|
|
8cd72b87b6 | ||
|
|
2f18dede85 | ||
|
|
495d2e4bf7 |
No files matched your search
@@ -37,4 +37,4 @@ Web 领域**唯一设计文档解释实现**。本仓库交付独立 Rust librar
|
||||
- `src/document.rs`:精确 anchor 选 Knowledge H2、直接保留 H3、GFM `组件` 表 AST/表头/单元格/Link 选择。
|
||||
- `src/lib.rs`:递归布局、实例、宽度/行/槽校验、包含环与深度/模块/字节上限、稳定诊断、源身份与确定性 handoff。
|
||||
- `tests/design_contract.rs`:8 个真实 CLI 契约测试(正例 + 负例);`scripts/ci.sh` 为显式验收入口。
|
||||
- 未完成:WEB-03 完整 handoff/组件图、并发/陈旧 Analysis 复核、完整安全负例矩阵、组件 CI 服务与 WEB-05;证据见 [docs/evidence/WEB-01-design-core.md](docs/evidence/WEB-01-design-core.md)。
|
||||
- 未完成:WEB-03 完整 handoff/组件图/单组件切片、组件 CI 服务与 WEB-05;内容投影、并发一致性与主要安全负例已实现;证据见 [docs/evidence/WEB-01-design-core.md](docs/evidence/WEB-01-design-core.md)。
|
||||
+1
-1
@@ -39,4 +39,4 @@ pub fn handoff(design: &Design) -> String;
|
||||
|
||||
`load` 已实现:真实 CLI Analysis 3 摄入、精确 anchor 选 Knowledge H2、`组件` 表递归布局、宽度/行/槽校验、包含环与资源上限、稳定诊断与源身份;`handoff` 目前输出确定性的组件树与来源摘要。
|
||||
|
||||
`InputDecl`/`EventDecl`/`Scenario`/`Interaction`/`Dependency`/`Acceptance` 已导出;未导出/未实现:`DesignGraph` 的完整组合图与 WEB-03 的组件切片/漂移标识。按 provisional 约定,这些可在 WEB-01 完成前破坏式调整;Preview 不得自行实现上述解释。
|
||||
`InputDecl`/`EventDecl`/`Scenario`/`Interaction`/`Dependency`/`Acceptance` 已导出;`ContentBlock`/`ContentLink` 已导出(安全结构投影,raw HTML 为占位)。未导出/未实现:`DesignGraph` 的完整组合图与 WEB-03 的组件切片/漂移标识。按 provisional 约定,这些可在 WEB-01 完成前破坏式调整;Preview 不得自行实现上述解释。
|
||||
@@ -42,11 +42,27 @@ MARQDO_BIN=<verified marqdo> scripts/ci.sh
|
||||
- 资源上限与合同建议对齐:文档 100 / 定义 200 / 实例 1000 / 深度 12 / 每行槽 12 / 场景 32 / 转移 128 / 单文件 1 MiB / 总输入 16 MiB;handoff 增加 inputs/events/scenarios/transitions/dependencies/acceptance。
|
||||
- 测试增至 14 个真实 CLI 契约用例,覆盖上述正例与主要负例(重复 input/event、非法状态、非叶子场景、场景内容指向组件、不可达状态、缺交互、依赖未知/环、空验收、每行槽上限、单文件上限)。
|
||||
|
||||
## 补充候选 3:显式 --root 内的 outside_scope 链接
|
||||
|
||||
WEB-00 探测发现一个真实边界:CLI 的最近项目根由 entry 父目录决定,组件引用 `../shared/x.mq.md` 时 Analysis 会标 `outside_scope` 且不提供 `candidate_path`,即使目标在设计命令的显式 `--root` 内。Design 的处理(不调用私有 loader、不搜索文件):
|
||||
|
||||
- 仅当 reference `state == outside_scope` 且 URL 是不含 scheme、不以 `/` 开头的相对路径时,用公开 URL 的路径部分相对**来源模块目录**解析;
|
||||
- 解析结果必须 canonicalize 到显式 `--root` 内,否则 `web.link.outside_root`;
|
||||
- 精确 anchor 仍由目标模块 Analysis 的 anchors 验证;
|
||||
- 该规则支撑合同 §2 的 `--root` 设计范围;未发现 CLI 私有字段需求,记录为 Design 解释规则(后续若 CLI Analysis 提供显式 root-relative candidate 可简化)。
|
||||
|
||||
## 补充候选 2:内容投影、并发一致性与安全边界
|
||||
|
||||
- **内容投影**:`ContentBlock`/`ContentLink` 只从 Analysis AST 的结构节点与源码 byte span 投影;raw HTML 一律成为 `[raw HTML as inert text]` 占位,绝不当活动 HTML;组件 `内容` 场景内容均带 block/link span,Preview 不需要自行解析 Markdown。
|
||||
- **并发/陈旧一致性**:一次 `load` 完成所有模块构建后,对参与的每个模块重新 `check --emit` 并比较 `source_digest`;中途变化返回 Engine `web.engine.stale`(退出码 2),不产生部分成功模型。
|
||||
- **安全负例**:symlink 指向 root 外 → `web.link.outside_root`;绝对路径 `/tmp/...` 链接被拒(candidate/absolute);`%2e%2e` 编码穿越不会解码为父目录,按不可解析 candidate 拒绝;raw HTML 负例以占位处理。
|
||||
- 测试增至 18 个真实 CLI 契约用例(新增内容投影、raw HTML 占位、symlink/绝对/双重编码、伪造 CLI 输出导致过期检测)。
|
||||
|
||||
## 未实现 / 未验证(不隐藏)
|
||||
|
||||
- 场景内容目标的 Exec 子树/双重编码/符号链接等安全边界尚未全部以真实负例覆盖;
|
||||
- 场景内容目标的 Exec 子树负例(非组件声明)尚未单独覆盖;资源/输出/HTML 大小与完整 CSP 由 WEB-02 Preview 承担;
|
||||
- handoff 当前为确定性组件树/来源摘要,WEB-03 的组件图、单组件切片与漂移标识未完成;
|
||||
- 并发编辑/陈旧 Analysis 的二次一致性复核、资源上限的完整矩阵、symlink/双重编码等安全负例仅覆盖部分;
|
||||
- 并发编辑一致性已做二次摘要复核;资源上限覆盖主要项,完整矩阵随 WEB-02 输出预算补齐;
|
||||
- 未配置组件 CI 服务(`scripts/ci.sh` 为显式入口,需 CI 传入固定 CLI 制品);领域/根接入(WEB-05)未开始。
|
||||
|
||||
因此 WEB-01 不关闭;后续在同一仓库按上述范围继续,不把本候选当作完整验收。
|
||||
@@ -0,0 +1,26 @@
|
||||
# WEB-03 Handoff、组件/依赖图与单组件交付证据
|
||||
|
||||
日期:2026-11-27。责任仓:`marqdo-web-design`;工单:[marqdo-web-design#2](https://git.cflmy.cn/cflmy/marqdo-web-design/issues/2)(WEB-03);父工单:根 [marqdo#6](https://git.cflmy.cn/cflmy/marqdo/issues/6)。
|
||||
|
||||
## 输入身份
|
||||
|
||||
| 对象 | 身份 |
|
||||
| --- | --- |
|
||||
| CLI | 由根固定 `cli/deadf6e` 构建的 `marqdo 3.0.0-rc.4`,`sha256:6ede3b9e...` |
|
||||
| Design | `marqdo-web-design@8cd72b87b6291ceae769de081debe1b5dc826010` |
|
||||
| 平台 | Linux x86_64(本机验证) |
|
||||
|
||||
## 已验证(24/24 真实 CLI 契约测试)
|
||||
|
||||
- `handoff`/`handoff_relative_to`:确定性输出(同输入两次逐字节一致);包含 design id、源摘要、递归组件树、视觉包含边、非视觉依赖边、每组件源链接/职责视觉说明/输入/事件/场景/交互/依赖/验收、明确“原型/模拟、真实功能由目标应用实现”边界;输出到其它目录时源链接相对输出目录重算。
|
||||
- `graph()`:视觉包含边(含 slot)与非视觉依赖边分离;依赖循环组可报告(load 仍以 `web.dependency.cycle` 拒绝组合,要求协调)。
|
||||
- `slice()`:单组件只包含其视觉子树定义/实例与实际使用源,未知组件报错。
|
||||
- `drift()` + `design_id()`:源改动后受影响组件与源变化可定位,未变组件不误报;相同 design 的 id 稳定、改动后变化。
|
||||
- 负例保持:错误输入拒绝、验收文本不被自动翻译成测试结论、交付只含模型派生内容不复制整仓源码。
|
||||
- 非视觉依赖目标作为定义加载,使交付图显式;该路径成环报告依赖环错误。
|
||||
|
||||
## 未验证 / 后续
|
||||
|
||||
- WEB-04 的三领域组合案例与成熟框架生产交付试验未开始。
|
||||
- WEB-05 根接入、web Tool 冷安装、领域激活未开始。
|
||||
- 交付的“视觉说明/参考”目前来自 Design 安全内容投影;参考图/外部资源在 Preview/生产交付中的表达仍属 WEB-02/WEB-04 范围。
|
||||
@@ -84,6 +84,75 @@ fn text_at(module: &Module, span: (usize, usize)) -> String {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ContentBlock {
|
||||
pub kind: String,
|
||||
pub text: String,
|
||||
pub span: (usize, usize),
|
||||
pub links: Vec<ContentLink>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ContentLink {
|
||||
pub text: String,
|
||||
pub url: String,
|
||||
pub span: (usize, usize),
|
||||
}
|
||||
|
||||
/// Safe projection of the analysis AST inside one source span.
|
||||
///
|
||||
/// Only structural kinds are exposed; raw HTML becomes an inert placeholder and
|
||||
/// link targets remain data for the Preview's protocol allowlist. No Markdown is
|
||||
/// re-parsed: block text is read from the analysis-provided source by span.
|
||||
pub fn content_blocks(module: &Module, span: (usize, usize)) -> Vec<ContentBlock> {
|
||||
let mut blocks = Vec::new();
|
||||
let Some(children) = module.document["children"].as_array() else {
|
||||
return blocks;
|
||||
};
|
||||
for child in children {
|
||||
let Some((start, end)) = span_from(&child["span"]) else {
|
||||
continue;
|
||||
};
|
||||
if start < span.0 || end > span.1 {
|
||||
continue;
|
||||
}
|
||||
let kind = match child["kind"].as_str().unwrap_or("") {
|
||||
"paragraph" => "paragraph",
|
||||
"list" => "list",
|
||||
"table" => "table",
|
||||
"code_block" => "code",
|
||||
"html" | "html_block" => "placeholder",
|
||||
"heading" => "heading",
|
||||
"block_quote" => "quote",
|
||||
other => other,
|
||||
};
|
||||
let mut links = Vec::new();
|
||||
walk_links(child, &mut links);
|
||||
let links = links
|
||||
.into_iter()
|
||||
.filter_map(|link| {
|
||||
let span = span_from(&link["span"])?;
|
||||
Some(ContentLink {
|
||||
text: text_at(module, span),
|
||||
url: link["url"].as_str()?.to_string(),
|
||||
span,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut text = text_at(module, (start, end));
|
||||
if kind == "placeholder" {
|
||||
text = format!("[raw HTML as inert text] {text}");
|
||||
}
|
||||
blocks.push(ContentBlock {
|
||||
kind: kind.to_string(),
|
||||
text,
|
||||
span: (start, end),
|
||||
links,
|
||||
});
|
||||
}
|
||||
blocks
|
||||
}
|
||||
|
||||
/// Resolve one exact anchor to its unit without imposing the design-component kind.
|
||||
pub fn any_unit_by_anchor(module: &Module, anchor: &str) -> Result<Unit, Diagnostic> {
|
||||
let mut matches = Vec::new();
|
||||
|
||||
+446
-45
@@ -22,6 +22,7 @@ use diagnostic::{Diagnostic, LoadError, Span};
|
||||
use document::{Cell, Link, Unit};
|
||||
|
||||
pub use diagnostic::{LoadError as Error, Severity};
|
||||
pub use document::{ContentBlock, ContentLink};
|
||||
|
||||
/// Explicit inputs; there is no implicit CLI or project discovery.
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -126,6 +127,8 @@ pub struct Scenario {
|
||||
pub state: String,
|
||||
/// Content unit (Knowledge H2/H3), never a design-component declaration.
|
||||
pub content: SourceRef,
|
||||
/// Safe structural projection of the content unit.
|
||||
pub content_blocks: Vec<ContentBlock>,
|
||||
pub initial: bool,
|
||||
}
|
||||
|
||||
@@ -156,6 +159,8 @@ pub struct ComponentDef {
|
||||
pub key: String,
|
||||
pub source: SourceRef,
|
||||
pub slots: Vec<ChildSlot>,
|
||||
/// Safe structural projection of the direct `内容` section, if present.
|
||||
pub content: Vec<ContentBlock>,
|
||||
pub inputs: Vec<InputDecl>,
|
||||
pub events: Vec<EventDecl>,
|
||||
pub scenarios: Vec<Scenario>,
|
||||
@@ -181,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<String, ComponentDef>,
|
||||
pub instances: Vec<Instance>,
|
||||
pub sources: Vec<SourceIdentity>,
|
||||
@@ -330,6 +337,34 @@ fn parse_initial(value: &str) -> Result<bool, &'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
fn design_candidate(
|
||||
reference: &serde_json::Value,
|
||||
link: &Link,
|
||||
module: &Module,
|
||||
) -> Result<String, LoadError> {
|
||||
if let Some(candidate) = reference["candidate_path"].as_str() {
|
||||
if !candidate.is_empty() {
|
||||
return Ok(candidate.to_string());
|
||||
}
|
||||
}
|
||||
// A link inside the explicit design --root can lie outside the CLI's nearest
|
||||
// project root (for example a component referencing `../shared/x.mq.md`).
|
||||
// Analysis then reports `outside_scope` without candidate_path; the public
|
||||
// reference URL plus the explicit design root still determine the physical
|
||||
// target, so derive it and require the root check afterwards.
|
||||
if reference["state"].as_str() == Some("outside_scope") {
|
||||
let raw = link.url.split('#').next().unwrap_or("");
|
||||
if !raw.is_empty() && !raw.starts_with('/') && !raw.contains("://") && !raw.contains('\\') {
|
||||
return Ok(raw.to_string());
|
||||
}
|
||||
}
|
||||
Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.candidate",
|
||||
"design link must expose a project-relative candidate path",
|
||||
)
|
||||
.at(module.relative.clone(), Some(link.span))]))
|
||||
}
|
||||
|
||||
fn json_span(span: (usize, usize)) -> Span {
|
||||
Span {
|
||||
start: span.0,
|
||||
@@ -390,18 +425,15 @@ impl Loader {
|
||||
link: &Link,
|
||||
) -> Result<(Module, Unit, String), LoadError> {
|
||||
let reference = find_reference(module, link)?;
|
||||
let candidate = reference["candidate_path"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let fragment = reference["fragment"].as_str().unwrap_or("").to_string();
|
||||
if candidate.is_empty() || fragment.is_empty() {
|
||||
if fragment.is_empty() {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.candidate",
|
||||
"design link must expose a candidate_path and a fragment",
|
||||
"design link must expose an exact anchor fragment",
|
||||
)
|
||||
.at(module.relative.clone(), Some(link.span))]));
|
||||
}
|
||||
let candidate = design_candidate(reference, link, module)?;
|
||||
if Path::new(&candidate).is_absolute() || link.url.contains("://") {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.absolute",
|
||||
@@ -446,10 +478,6 @@ impl Loader {
|
||||
link: &Link,
|
||||
) -> Result<(Module, Unit), LoadError> {
|
||||
let reference = find_reference(module, link)?;
|
||||
let candidate = reference["candidate_path"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let fragment = reference["fragment"].as_str().unwrap_or("").to_string();
|
||||
if fragment.is_empty() {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
@@ -458,6 +486,11 @@ impl Loader {
|
||||
)
|
||||
.at(module.relative.clone(), Some(link.span))]));
|
||||
}
|
||||
let candidate = match design_candidate(reference, link, module) {
|
||||
Ok(candidate) => candidate,
|
||||
Err(_) if reference["fragment"].as_str().is_some() => String::new(),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let target_module = if candidate.is_empty() {
|
||||
module.clone()
|
||||
} else {
|
||||
@@ -763,9 +796,16 @@ impl Loader {
|
||||
initial += 1;
|
||||
}
|
||||
let content = source_ref(&target_module, &target_unit, target_unit.anchor_text());
|
||||
let content_start = target_unit
|
||||
.heading_span
|
||||
.map(|(_, end)| end)
|
||||
.unwrap_or(target_unit.span.0);
|
||||
let content_blocks =
|
||||
document::content_blocks(&target_module, (content_start, target_unit.span.1));
|
||||
scenarios.push(Scenario {
|
||||
state,
|
||||
content,
|
||||
content_blocks,
|
||||
initial: is_initial,
|
||||
});
|
||||
}
|
||||
@@ -888,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),
|
||||
});
|
||||
@@ -920,6 +977,19 @@ impl Loader {
|
||||
span: json_span(section.span),
|
||||
});
|
||||
}
|
||||
let content = match document::direct_sections(module, unit)
|
||||
.into_iter()
|
||||
.find(|section| section.name == "内容")
|
||||
{
|
||||
Some(section) => {
|
||||
let start = section
|
||||
.heading_span
|
||||
.map(|(_, end)| end)
|
||||
.unwrap_or(section.span.0);
|
||||
document::content_blocks(module, (start, section.span.1))
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
self.stack.pop();
|
||||
if self.definitions.len() >= self.config.max_definitions {
|
||||
return Err(design_error(
|
||||
@@ -931,6 +1001,7 @@ impl Loader {
|
||||
key: key.clone(),
|
||||
source: source_ref(module, unit, anchor),
|
||||
slots,
|
||||
content,
|
||||
inputs,
|
||||
events,
|
||||
scenarios,
|
||||
@@ -943,6 +1014,26 @@ impl Loader {
|
||||
}
|
||||
}
|
||||
|
||||
impl Loader {
|
||||
fn verify_stable(&mut self) -> Result<(), LoadError> {
|
||||
let modules: Vec<Module> = self.modules.values().cloned().collect();
|
||||
for module in modules {
|
||||
let fresh = analysis::analyze(&self.config.cli, &module.path, &self.root)?;
|
||||
if fresh.source_digest != module.source_digest {
|
||||
return Err(LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.stale",
|
||||
format!(
|
||||
"source {} changed during one design load ({} -> {})",
|
||||
module.relative, module.source_digest, fresh.source_digest
|
||||
),
|
||||
)
|
||||
.at(module.relative.clone(), None)]));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_state(state: &str) -> bool {
|
||||
let mut chars = state.chars();
|
||||
let Some(first) = chars.next() else {
|
||||
@@ -1084,6 +1175,7 @@ pub fn load(config: &LoadConfig) -> Result<Design, LoadError> {
|
||||
let unit = document::knowledge_h2(&module, &config.unit)?;
|
||||
let root_key = loader.load_definition(&module, &unit, &config.unit, 0)?;
|
||||
validate_design(&loader.definitions)?;
|
||||
loader.verify_stable()?;
|
||||
let mut instances = Vec::new();
|
||||
collect_instances(&loader.definitions, &root_key, "root", &mut instances);
|
||||
if instances.len() > config.max_instances {
|
||||
@@ -1104,6 +1196,7 @@ pub fn load(config: &LoadConfig) -> Result<Design, LoadError> {
|
||||
sources.sort_by(|left, right| left.path.cmp(&right.path));
|
||||
Ok(Design {
|
||||
root: root_key,
|
||||
root_dir: root.clone(),
|
||||
definitions: loader.definitions,
|
||||
instances,
|
||||
sources,
|
||||
@@ -1132,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<Vec<String>>,
|
||||
}
|
||||
|
||||
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<String>> = 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<Vec<String>>,
|
||||
) {
|
||||
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<String>,
|
||||
pub removed_components: Vec<String>,
|
||||
pub changed_components: Vec<String>,
|
||||
pub changed_sources: Vec<String>,
|
||||
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<Design, LoadError> {
|
||||
if !design.definitions.contains_key(component) {
|
||||
return Err(design_error(
|
||||
"web.slice.unknown",
|
||||
format!("unknown component definition {component:?}"),
|
||||
));
|
||||
}
|
||||
let mut keys: BTreeSet<String> = 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<String, ComponentDef> = 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<String> = 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
|
||||
}
|
||||
|
||||
+290
-12
@@ -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);
|
||||
|
||||
@@ -249,7 +252,7 @@ fn rejects_scope_anchor_and_cycle_errors() {
|
||||
// the deterministic rejection is the candidate diagnostic (never a guess).
|
||||
assert_eq!(
|
||||
design_code(load(&outside.config("index.mq.md", "工作台")).unwrap_err()),
|
||||
"web.link.candidate"
|
||||
"web.link.target_missing"
|
||||
);
|
||||
|
||||
let missing = basic_project();
|
||||
@@ -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");
|
||||
@@ -522,3 +524,279 @@ fn enforces_per_file_and_slot_limits() {
|
||||
"web.layout.slots_per_row"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projects_safe_content_blocks_for_components_and_scenarios() {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 内容\n\n普通段落。\n\n- 一\n- 二\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### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| only | [样例](states.mq.md#空状态) | true |\n",
|
||||
);
|
||||
project.write("states.mq.md", STATES);
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("content load");
|
||||
let root = &design.definitions["index.mq.md#工作台"];
|
||||
let kinds: Vec<&str> = root
|
||||
.content
|
||||
.iter()
|
||||
.map(|block| block.kind.as_str())
|
||||
.collect();
|
||||
assert!(kinds.contains(&"paragraph"));
|
||||
assert!(kinds.contains(&"list"));
|
||||
let a = &design.definitions["a.mq.md#甲"];
|
||||
assert!(a
|
||||
.scenarios
|
||||
.iter()
|
||||
.all(|scene| !scene.content_blocks.is_empty()));
|
||||
let text = handoff(&design);
|
||||
assert!(text.contains("Scenarios:"));
|
||||
assert!(text.contains("`only`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_html_is_exposed_as_an_inert_placeholder() {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 内容\n\n<div onclick=\"alert(1)\">危险</div>\n",
|
||||
);
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("html load");
|
||||
let block = design.definitions["index.mq.md#工作台"]
|
||||
.content
|
||||
.iter()
|
||||
.find(|block| block.kind == "placeholder")
|
||||
.expect("raw html block");
|
||||
assert!(block.text.contains("inert text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_scope_escape_via_symlink_absolute_and_encoded_paths() {
|
||||
let project = TempProject::new();
|
||||
let outside_dir = project
|
||||
.path
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join(format!("marqdo-web-design-outside-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&outside_dir).unwrap();
|
||||
let outside = outside_dir.join("outside.mq.md");
|
||||
std::fs::write(&outside, "# 外部\n\n## @knowledge 目标\n\n### 内容\n\nx\n").unwrap();
|
||||
project.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [外部](escape.mq.md#目标) | auto |\n",
|
||||
);
|
||||
match std::os::unix::fs::symlink(&outside, project.path.join("escape.mq.md")) {
|
||||
Ok(()) => {
|
||||
let error = load(&project.config("index.mq.md", "工作台")).unwrap_err();
|
||||
let code = match &error {
|
||||
Error::Design(items) | Error::Engine(items) => items[0].code,
|
||||
};
|
||||
assert_eq!(code, "web.link.outside_root", "{error:?}");
|
||||
}
|
||||
Err(error) => eprintln!("symlink unavailable, skipped: {error}"),
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&outside_dir);
|
||||
|
||||
let absolute = TempProject::new();
|
||||
absolute.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [绝对](/tmp/x.mq.md#目标) | auto |\n",
|
||||
);
|
||||
let error = load(&absolute.config("index.mq.md", "工作台")).unwrap_err();
|
||||
let code = match &error {
|
||||
Error::Design(items) | Error::Engine(items) => items[0].code,
|
||||
};
|
||||
assert!(
|
||||
matches!(code, "web.link.candidate" | "web.link.absolute"),
|
||||
"{error:?}"
|
||||
);
|
||||
|
||||
let encoded = TempProject::new();
|
||||
encoded.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [穿越](%2e%2e/outside.mq.md#目标) | auto |\n",
|
||||
);
|
||||
let error = load(&encoded.config("index.mq.md", "工作台")).unwrap_err();
|
||||
let code = match &error {
|
||||
Error::Design(items) | Error::Engine(items) => items[0].code,
|
||||
};
|
||||
assert!(
|
||||
matches!(code, "web.link.candidate" | "web.link.target_missing"),
|
||||
"{error:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_a_changed_source_digest_during_one_load() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let project = basic_project();
|
||||
let real_cli = cli();
|
||||
let wrapper = project.path.join("fake-cli.sh");
|
||||
let counter = project.path.join("calls.txt");
|
||||
std::fs::write(
|
||||
&wrapper,
|
||||
format!(
|
||||
"#!/bin/sh\ncount=0\n[ -f '{count}' ] && count=$(cat '{count}')\ncount=$((count+1))\necho \"$count\" > '{count}'\n\"{cli}\" \"$@\"\nstatus=$?\nif [ \"$count\" -ge 2 ] && [ \"$status\" -eq 0 ]; then\n emit=\"\"\n while [ \"$#\" -gt 0 ]; do\n if [ \"$1\" = \"--emit\" ]; then shift; emit=\"$1\"; fi\n shift\n done\n python3 - \"$emit\" <<'PY'\nimport json, sys\npath = sys.argv[1]\ndata = json.load(open(path))\ndata['modules'][0]['source_digest'] = '0' * 64\njson.dump(data, open(path, 'w'))\nPY\nfi\nexit \"$status\"\n",
|
||||
cli = real_cli.display(),
|
||||
count = counter.display(),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut config = project.config("index.mq.md", "工作台");
|
||||
config.cli = wrapper;
|
||||
let error = load(&config).unwrap_err();
|
||||
assert_eq!(engine_code(error), "web.engine.stale");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_outside_scope_links_that_stay_inside_the_explicit_root() {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"components/a.mq.md",
|
||||
"# A 组件\n\n## @knowledge 甲\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | b | [乙](../shared/b.mq.md#乙) | auto |\n",
|
||||
);
|
||||
project.write(
|
||||
"shared/b.mq.md",
|
||||
"# B 组件\n\n## @knowledge 乙\n\n### 内容\n\n共享正文。\n",
|
||||
);
|
||||
let mut config = project.config("components/a.mq.md", "甲");
|
||||
config.root = project.path.clone();
|
||||
let design = load(&config).expect("outside_scope link inside --root resolves");
|
||||
assert_eq!(design.definitions.len(), 2);
|
||||
assert_eq!(
|
||||
design.definitions["components/a.mq.md#甲"].slots[0].target,
|
||||
"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<_>>(),
|
||||
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());
|
||||
}
|
||||
Reference in new issue
Block a user