Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61b4dd370e | ||
|
|
5c7e517121 | ||
|
|
37404dbc6a | ||
|
|
a231068f23 | ||
|
|
cbef7b622a | ||
|
|
1b6607fd3c | ||
|
|
8cd72b87b6 | ||
|
|
2f18dede85 | ||
|
|
495d2e4bf7 | ||
|
|
9684e388ce | ||
|
|
75cd26ef89 |
No files matched your search
+2
-4
@@ -1,4 +1,2 @@
|
||||
/target/
|
||||
/dist/
|
||||
/.secrets/
|
||||
*.log
|
||||
/target
|
||||
dist/
|
||||
@@ -0,0 +1,13 @@
|
||||
# Unified Woodpecker CI for a Rust component.
|
||||
#
|
||||
# One published `marqdo-ci-rust` image (Rust 1.100, rustfmt/clippy, warm cargo
|
||||
# cache, released CLI/Bundle) is reused. No per-repository toolchain download or
|
||||
# CLI rebuild; the repository only runs its own CI entry.
|
||||
when:
|
||||
event: [push, pull_request, manual]
|
||||
|
||||
steps:
|
||||
test:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
|
||||
commands:
|
||||
- scripts/ci.sh
|
||||
@@ -0,0 +1,26 @@
|
||||
when:
|
||||
- event: [tag, manual]
|
||||
steps:
|
||||
publish:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
|
||||
environment:
|
||||
GITEA_PUBLISH_TOKEN:
|
||||
from_secret: gitea_publish_token
|
||||
COMPONENT_ID: web-design
|
||||
REPOSITORY: cflmy/marqdo-web-design
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
test -n "${GITEA_PUBLISH_TOKEN:?}"
|
||||
test -n "${CI_COMMIT_TAG:?}"
|
||||
export SOURCE_SHA="${CI_COMMIT_SHA}"
|
||||
export VERSION="${CI_COMMIT_TAG#v}"
|
||||
export COMPONENT_ID=web-design
|
||||
export REPOSITORY=cflmy/marqdo-web-design
|
||||
sh scripts/package.sh
|
||||
ARCHIVE="dist/marqdo-web-design-${VERSION}-source.tar.gz"
|
||||
python3 scripts/release/publish_gitea.py \
|
||||
--repo cflmy/marqdo-web-design --tag "${CI_COMMIT_TAG}" --target "$SOURCE_SHA" --prerelease \
|
||||
--body "Automated source release for web-design ${CI_COMMIT_TAG}." \
|
||||
--asset "$ARCHIVE" --asset "${ARCHIVE}.sha256" --asset dist/release-evidence.json \
|
||||
--evidence-out dist/gitea-publish-result.json
|
||||
@@ -0,0 +1,12 @@
|
||||
when:
|
||||
event: [release]
|
||||
steps:
|
||||
notify:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
|
||||
environment:
|
||||
WOODPECKER_NOTIFY_TOKEN:
|
||||
from_secret: woodpecker_notify_token
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
python3 scripts/release/notify_root.py --hint-component web-design --hint-tag "${CI_COMMIT_TAG:-}"
|
||||
@@ -1,5 +1,10 @@
|
||||
# marqdo-web-design 维护指引
|
||||
|
||||
<!-- marqdo:repo-conventions v1 -->
|
||||
|
||||
生态级仓库开发规范:https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/REPOSITORY-CONVENTIONS.md
|
||||
|
||||
|
||||
1. 只以 `marqdo-ext-web` 的 [WEB-DESIGN](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md) 为现行作者合同;本仓库是实现者,不是合同所有者。合同语义冲突先在领域仓库开 ADR 工单,不同时维护两套解释。
|
||||
2. 只消费 CLI 公开接口(`check --emit` 的 Analysis 3 与文档化的 CLI/Tool 合同)。禁止复制 parser、读取 CLI 私有结构或以 `inspect` 等私有输出替代 Analysis;边界不够用时先取证再向 CLI 开通用工单。
|
||||
3. 不启动服务、不渲染 DOM、不写 HTML、不读密钥、不调用模型、不执行文档、不修改源文件。库失败必须返回带稳定错误码与来源 span 的 `Diagnostics`,禁止静默跳过子组件。
|
||||
|
||||
Generated
+105
@@ -0,0 +1,105 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-web-design"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "marqdo-web-design"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.89"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Deterministic interpreter of the Marqdo Web design contract over public CLI Analysis 3"
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1"
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Web 领域**唯一设计文档解释实现**。本仓库交付独立 Rust library,消费真实 CLI 的公开 Analysis,把符合 [WEB-DESIGN 合同](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md) 的 `.mq.md` 解释为设计模型、诊断与交付快照。
|
||||
|
||||
**当前状态:`planned`。** 尚未实现、尚未发布、没有 CI 入口或制品;仓库中的 API 与目录均为暂定计划,未经真实 CLI 夹具验证。
|
||||
**当前状态:`active`。** 已实现并固定于领域 gitlink:消费真实 CLI Analysis 3,提供设计模型/诊断/handoff 与 `scripts/ci.sh`;24 个真实 CLI 契约测试通过。发布身份仍以领域/根固定提交与证据为准。
|
||||
|
||||
## 职责与禁止
|
||||
|
||||
@@ -30,3 +30,11 @@ Web 领域**唯一设计文档解释实现**。本仓库交付独立 Rust librar
|
||||
## 工单
|
||||
|
||||
首版开发任务:WEB-01(Analysis 3 消费与设计编译)、WEB-03(handoff/组件图/单组件交付)。合同语义冲突归 `marqdo-ext-web` 协调;只有 CLI 公开 Analysis 合同本身不满足需求时才向 `marqdo-cli` 发工单,并附固定 SHA 与最小复现。
|
||||
|
||||
## 实现进展
|
||||
|
||||
- `src/analysis.rs`:真实 CLI `check --emit` 调用、Analysis 3 协议/摘要校验、单一模块快照。
|
||||
- `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/组件图/单组件切片、组件 CI 服务与 WEB-05;内容投影、并发一致性与主要安全负例已实现;证据见 [docs/evidence/WEB-01-design-core.md](docs/evidence/WEB-01-design-core.md)。
|
||||
@@ -34,3 +34,9 @@ pub fn handoff(design: &Design) -> String;
|
||||
|
||||
- `load`/`handoff` 与数据模型在 WEB-01 前为 provisional,可破坏式调整;WEB-01 后进入 SemVer。
|
||||
- 需要破坏性变更时,Design 与 Preview 在同一领域候选组合中一起升级,`Cargo.lock` 固定实际消费身份;不维护旧协议 fallback。
|
||||
|
||||
## 实现状态(WEB-01 核心候选)
|
||||
|
||||
`load` 已实现:真实 CLI Analysis 3 摄入、精确 anchor 选 Knowledge H2、`组件` 表递归布局、宽度/行/槽校验、包含环与资源上限、稳定诊断与源身份;`handoff` 目前输出确定性的组件树与来源摘要。
|
||||
|
||||
`InputDecl`/`EventDecl`/`Scenario`/`Interaction`/`Dependency`/`Acceptance` 已导出;`ContentBlock`/`ContentLink` 已导出(安全结构投影,raw HTML 为占位)。未导出/未实现:`DesignGraph` 的完整组合图与 WEB-03 的组件切片/漂移标识。按 provisional 约定,这些可在 WEB-01 完成前破坏式调整;Preview 不得自行实现上述解释。
|
||||
+10
-11
@@ -27,22 +27,21 @@ RC.4 Analysis 只包含已静态加载模块,`not_loaded` 不等于缺失。
|
||||
- `missing/ambiguous/outside_scope/invalid/external` 对设计依赖是错误;普通内容链接不追踪。无法从公开字段确认物理映射时报告“不支持”,不得调用私有 loader 或搜索文件名。
|
||||
- 并发编辑一致性:以实际输入 bytes 与 digest 校验;同一文件在一轮中两次 Analysis 内容不同即失败重试;输出前复核所有参与设计的源码/资产摘要。交付只列真正使用的输入,不打包全部已加载依赖。
|
||||
|
||||
## 计划代码结构(尚未创建)
|
||||
## 代码结构(WEB-01 核心已创建)
|
||||
|
||||
```text
|
||||
Cargo.toml / Cargo.lock
|
||||
src/lib.rs # 公开 API 与结果类型
|
||||
src/analysis.rs # CLI 调用、公开协议校验、静态输入快照
|
||||
src/document.rs # 确定的章节/表格选择、单元引用
|
||||
src/model.rs # 定义、实例、布局、场景、来源
|
||||
src/graph.rs # 递归链接、循环、依赖与限制
|
||||
src/handoff.rs # Markdown 交付
|
||||
src/diagnostic.rs # 稳定错误码与来源位置
|
||||
tests/ # 单元、负例、真实 CLI contract
|
||||
scripts/ci.sh # 激活时提供的独立验收入口
|
||||
docs/
|
||||
src/lib.rs # 公开 API、递归布局/实例/上限/handoff(WEB-01 核心)
|
||||
src/analysis.rs # CLI check --emit 调用、Analysis 3 校验、模块快照
|
||||
src/document.rs # 精确 anchor/H3/GFM 表/Link 选择
|
||||
src/diagnostic.rs # 稳定错误码、span、Engine/Design 区分
|
||||
tests/design_contract.rs # 真实 CLI 正例 + 负例
|
||||
scripts/ci.sh # 显式独立验收入口(fmt/clippy/test)
|
||||
docs/ # API、开发指南与证据
|
||||
```
|
||||
|
||||
尚未拆分 `model.rs`/`graph.rs`/`handoff.rs` 是当前规模下的有意选择;场景/输入事件合同与完整 handoff 落地时再按真实边界拆分,不做预先空壳。
|
||||
|
||||
不为每个表格新建 crate;Design 与 Preview 各一个主要 crate。`docs/WEB-DESIGN.md` 在领域仓库,本仓库不得复制。
|
||||
|
||||
## 公开 API 原则
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# WEB-01 Design 核心候选证据(布局 / 源身份 / 诊断)
|
||||
|
||||
日期:2026-11-27。责任仓:`marqdo-web-design`;工单:[marqdo-web-design#1](https://git.cflmy.cn/cflmy/marqdo-web-design/issues/1)(WEB-01);父工单:根 [marqdo#6](https://git.cflmy.cn/cflmy/marqdo/issues/6)。
|
||||
|
||||
本文件记录 WEB-01 的**核心候选**:Analysis 3 摄入、精确组件引用、递归布局、稳定诊断与源身份。场景/输入/事件/依赖与更完整 handoff 仍属 WEB-01/WEB-03 后续,未在本证据中声明完成。
|
||||
|
||||
## 输入身份
|
||||
|
||||
| 对象 | 身份 |
|
||||
| --- | --- |
|
||||
| CLI | 由根固定 `cli/deadf6e` 构建的 `marqdo 3.0.0-rc.4`,SHA-256 `sha256:6ede3b9e8bcfad3942573e68b5f54b2c5bc2866b37d102f63acd49a55cb212db` |
|
||||
| 根组合 | `cflmy/marqdo@d4ccb77` |
|
||||
| 合同 | `marqdo-ext-web` 的 `docs/WEB-DESIGN.md`(只读引用,不复制) |
|
||||
| 平台 | Linux x86_64(本机验证) |
|
||||
|
||||
## 执行
|
||||
|
||||
```sh
|
||||
MARQDO_BIN=<verified marqdo> scripts/ci.sh
|
||||
# = cargo fmt --check; cargo clippy --all-targets --locked -D warnings; cargo test --locked
|
||||
```
|
||||
|
||||
测试直接启动真实 CLI `check --emit` 生成 Analysis 3(无 mock),临时工程由测试写入。
|
||||
|
||||
## 已验证(8 个真实 CLI 契约测试)
|
||||
|
||||
- 正例:递归 `组件` 布局(index → nav → leaf、workspace 内容组件)、定义复用但实例独立(`root`/`root/left`/`root/right`)、内容-only 组件、宽度 `auto`/`1fr..12fr`/`120px..1200px`。
|
||||
- 源身份:每个参与模块的 root-relative path、module id、`source_digest`、Unit path/anchor/UTF-8 span;两次加载的 handoff 逐字节一致。
|
||||
- 负例(稳定诊断码):缺失/歧义 anchor、H2 非 Knowledge(Exec)、带 `#` 的 unit、表头/列数/非 Link 单元格/非法宽度/重复 slot/行号不连续、目标越界(Analysis 无可用 candidate)、目标 anchor 缺失、包含环、模块/深度/源字节上限、CLI 缺失、ENTRY 越出 root、ENTRY 不存在。
|
||||
- 引擎失败与作者合同错误区分(`LoadError::Engine`/`Design`),宿主据此映射退出码 2/1;失败不产生部分模型。
|
||||
- 不使用 `../design` 路径依赖,不复制 Markdown/语言解析器;只消费 Analysis 公开字段。
|
||||
|
||||
## 补充候选:保留合同表格(输入/事件/场景/交互/依赖/验收)
|
||||
|
||||
同一候选后续提交实现了 WEB-DESIGN §3.2/§5 的保留 H3 合同:
|
||||
|
||||
- `输入`(名称/类型/说明)、`事件`(名称/数据/说明):纯文本单元格、名称非空且组件内唯一;链接被拒绝。
|
||||
- `场景`(状态/内容/初始):ASCII slug 状态、组件内唯一、恰好一个 initial;内容单元格必须且只能含一个 Link,指向 Knowledge 单元(拒绝 Exec/设计组件声明);只允许叶子组件;数量上限 32。
|
||||
- `交互`(当前/事件/下一状态):状态必须存在、事件标签非空且同一当前状态唯一、每个状态从初始状态可达;多状态必须有交互;无场景不得有交互;转移上限 128。
|
||||
- `依赖`(组件/原因):必须指向已加载设计组件、原因非空;跨组件设计依赖环确定性报错(报告协调需求,不宣称可并行)。
|
||||
- `验收`:直接 H3 内容必须非空,作为交付文本保留,不自动解释为测试。
|
||||
- 资源上限与合同建议对齐:文档 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 子树负例(非组件声明)尚未单独覆盖;资源/输出/HTML 大小与完整 CSP 由 WEB-02 Preview 承担;
|
||||
- handoff 当前为确定性组件树/来源摘要,WEB-03 的组件图、单组件切片与漂移标识未完成;
|
||||
- 并发编辑一致性已做二次摘要复核;资源上限覆盖主要项,完整矩阵随 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 范围。
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# WEB-01 independent entry: explicit verified CLI, real Analysis contract tests.
|
||||
set -eu
|
||||
: "${MARQDO_BIN:?set MARQDO_BIN to the verified marqdo executable}"
|
||||
export MARQDO_BIN
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --all-targets --locked -- -D warnings
|
||||
cargo test --locked
|
||||
Executable
+49
@@ -0,0 +1,49 @@
|
||||
#!/bin/sh
|
||||
# Deterministic source archive + release-evidence.json for this component.
|
||||
#
|
||||
# Required env:
|
||||
# COMPONENT_ID catalog id (e.g. std-text)
|
||||
# REPOSITORY owner/name (e.g. cflmy/marqdo-std-text)
|
||||
# Optional:
|
||||
# VERSION without leading v (default: derived from CI_COMMIT_TAG)
|
||||
# SOURCE_SHA full commit (default: HEAD)
|
||||
# OUT_DIR default dist
|
||||
# DEPENDENCY repeatable write_evidence dependency specs via env DEP_ARGS
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
COMPONENT_ID=${COMPONENT_ID:?COMPONENT_ID is required}
|
||||
REPOSITORY=${REPOSITORY:?REPOSITORY is required}
|
||||
SOURCE_SHA=${SOURCE_SHA:-$(git -C "$ROOT" rev-parse HEAD)}
|
||||
OUT_DIR=${OUT_DIR:-dist}
|
||||
TAG=${CI_COMMIT_TAG:-${TAG:-}}
|
||||
if [ -n "${VERSION:-}" ]; then
|
||||
:
|
||||
elif [ -n "$TAG" ]; then
|
||||
VERSION=${TAG#v}
|
||||
else
|
||||
echo "package.sh: set VERSION or CI_COMMIT_TAG" >&2
|
||||
exit 1
|
||||
fi
|
||||
TAG=${TAG:-v$VERSION}
|
||||
|
||||
python3 "$ROOT/scripts/release/package_source.py" \
|
||||
--root "$ROOT" \
|
||||
--component-id "$COMPONENT_ID" \
|
||||
--version "$VERSION" \
|
||||
--out-dir "$OUT_DIR"
|
||||
|
||||
ARCHIVE=$(ls "$ROOT/$OUT_DIR"/marqdo-"$COMPONENT_ID"-"$VERSION"-source.tar.gz)
|
||||
SHAFILE="$ARCHIVE.sha256"
|
||||
|
||||
EVIDENCE_ARGS="--component-id $COMPONENT_ID --repository $REPOSITORY --tag $TAG --source-sha $SOURCE_SHA --asset $ARCHIVE --asset $SHAFILE --out $ROOT/$OUT_DIR/release-evidence.json"
|
||||
if [ -n "${CI_PIPELINE_NUMBER:-}" ]; then
|
||||
EVIDENCE_ARGS="$EVIDENCE_ARGS --pipeline-number $CI_PIPELINE_NUMBER"
|
||||
fi
|
||||
if [ -n "${CI_PIPELINE_URL:-}" ]; then
|
||||
EVIDENCE_ARGS="$EVIDENCE_ARGS --pipeline-url $CI_PIPELINE_URL"
|
||||
fi
|
||||
# shellcheck disable=SC2086
|
||||
eval "python3 \"$ROOT/scripts/release/write_evidence.py\" $EVIDENCE_ARGS ${DEP_ARGS:-}"
|
||||
echo "$ARCHIVE"
|
||||
echo "$SHAFILE"
|
||||
echo "$ROOT/$OUT_DIR/release-evidence.json"
|
||||
@@ -0,0 +1,9 @@
|
||||
# Vendored from marqdo scripts/component-release
|
||||
#
|
||||
# Do not edit in place across repositories. Change the root copy, re-test,
|
||||
# then re-run install-vendor.sh and record the hashes below.
|
||||
#
|
||||
# package_source.py sha256=cb18c2f7fbe807f55d49e2cf77720f0d3e57d355177d2b127ac09e119f90c6ae
|
||||
# write_evidence.py sha256=bb194bfd251e39308bc1dd53f46fd9efac181082ea43f668484b067d9e54acfc
|
||||
# publish_gitea.py sha256=a21a84146d9ea826eb8d0632a18a991b0c39f17005d83bd988c92fc608f67523
|
||||
# notify_root.py sha256=8eee83eb2bb31b99d93981f2a97fc2f0f9a486cc3c5c072f7dc12cfb63baf025
|
||||
Executable
+103
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ask the root Marqdo reconcile workflow to scan after a release.
|
||||
|
||||
The payload is only a hint. Correctness comes from the root
|
||||
`scripts/reconcile-releases.py` reading authoritative Gitea releases.
|
||||
Lost notifications are recovered by the root `release-reconcile` cron.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
DEFAULT_URL = "https://ci.cflmy.cn/api/repos/6/pipelines"
|
||||
DEFAULT_BODY = {"branch": "main", "workflow": "reconcile"}
|
||||
|
||||
|
||||
class NotifyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def token() -> str:
|
||||
value = (
|
||||
os.environ.get("WOODPECKER_NOTIFY_TOKEN")
|
||||
or os.environ.get("WOODPECKER_TOKEN")
|
||||
or os.environ.get("woodpecker_token")
|
||||
)
|
||||
if not value:
|
||||
raise NotifyError("WOODPECKER_NOTIFY_TOKEN (or WOODPECKER_TOKEN) is not set")
|
||||
return value
|
||||
|
||||
|
||||
def trigger(url: str, token_value: str, body: dict, attempts: int = 3) -> dict:
|
||||
payload = json.dumps(body).encode()
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
data=payload,
|
||||
method="POST",
|
||||
headers={
|
||||
"Authorization": f"Bearer {token_value}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
raw = response.read()
|
||||
decoded = json.loads(raw) if raw else {}
|
||||
return {
|
||||
"status": "triggered",
|
||||
"http_status": response.status,
|
||||
"pipeline_id": decoded.get("id"),
|
||||
"pipeline_number": decoded.get("number"),
|
||||
"attempt": attempt,
|
||||
}
|
||||
except urllib.error.HTTPError as error:
|
||||
# Auth/permission failures must not retry forever.
|
||||
if error.code in (401, 403, 404):
|
||||
raise NotifyError(f"trigger rejected with HTTP {error.code}") from error
|
||||
last_error = error
|
||||
except urllib.error.URLError as error:
|
||||
last_error = error
|
||||
if attempt < attempts:
|
||||
delay = (2 ** (attempt - 1)) + random.uniform(0, 0.5)
|
||||
time.sleep(delay)
|
||||
raise NotifyError(f"trigger failed after {attempts} attempts: {last_error}")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--url", default=os.environ.get("MARQDO_RECONCILE_TRIGGER_URL", DEFAULT_URL))
|
||||
parser.add_argument("--branch", default="main")
|
||||
parser.add_argument("--workflow", default="reconcile")
|
||||
parser.add_argument("--hint-component", default="")
|
||||
parser.add_argument("--hint-tag", default="")
|
||||
parser.add_argument("--attempts", type=int, default=3)
|
||||
args = parser.parse_args(argv)
|
||||
body = {"branch": args.branch, "workflow": args.workflow}
|
||||
# Hints are informational only; the root reconcile never trusts them as commands.
|
||||
if args.hint_component or args.hint_tag:
|
||||
body["variables"] = {
|
||||
"MARQDO_RELEASE_HINT_COMPONENT": args.hint_component,
|
||||
"MARQDO_RELEASE_HINT_TAG": args.hint_tag,
|
||||
}
|
||||
try:
|
||||
result = trigger(args.url, token(), body, attempts=max(1, args.attempts))
|
||||
except NotifyError as error:
|
||||
print(f"notify_root: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+145
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a deterministic source archive for a Marqdo component release.
|
||||
|
||||
Only allowlisted relative paths are included. The archive uses fixed mtime,
|
||||
uid/gid, and sorted member names so the same tree always yields the same
|
||||
sha256. Output is written under an isolated directory (default: dist/).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_ALLOWLIST = (
|
||||
"modules",
|
||||
"index.mq.md",
|
||||
"marqdo.yaml",
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
)
|
||||
FIXED_MTIME = 0
|
||||
EVIDENCE_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class PackageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
raise PackageError(message)
|
||||
|
||||
|
||||
def is_safe_relative(path: str) -> bool:
|
||||
if not path or path.startswith("/") or path.startswith("\\"):
|
||||
return False
|
||||
parts = Path(path).parts
|
||||
return not any(part in (".", "..") for part in parts)
|
||||
|
||||
|
||||
def collect_files(root: Path, allowlist: list[str]) -> list[tuple[str, Path]]:
|
||||
selected: dict[str, Path] = {}
|
||||
for entry in allowlist:
|
||||
if not is_safe_relative(entry):
|
||||
fail(f"unsafe allowlist entry: {entry!r}")
|
||||
target = root / entry
|
||||
if not target.exists():
|
||||
continue
|
||||
if target.is_file():
|
||||
selected[entry.replace("\\", "/")] = target
|
||||
continue
|
||||
if not target.is_dir():
|
||||
fail(f"allowlist entry is not a regular file or directory: {entry}")
|
||||
for path in sorted(target.rglob("*")):
|
||||
if not path.is_file():
|
||||
continue
|
||||
if path.is_symlink():
|
||||
fail(f"symlinks are not publishable: {path.relative_to(root)}")
|
||||
relative = path.relative_to(root).as_posix()
|
||||
if not is_safe_relative(relative):
|
||||
fail(f"unsafe relative path: {relative}")
|
||||
selected[relative] = path
|
||||
if not selected:
|
||||
fail("allowlist matched no files")
|
||||
return sorted(selected.items(), key=lambda item: item[0])
|
||||
|
||||
|
||||
def archive_bytes(files: list[tuple[str, Path]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w:gz", format=tarfile.PAX_FORMAT, compresslevel=9) as archive:
|
||||
for relative, path in files:
|
||||
data = path.read_bytes()
|
||||
info = tarfile.TarInfo(name=relative)
|
||||
info.size = len(data)
|
||||
info.mtime = FIXED_MTIME
|
||||
info.uid = 0
|
||||
info.gid = 0
|
||||
info.uname = ""
|
||||
info.gname = ""
|
||||
info.mode = 0o644
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def write_outputs(
|
||||
root: Path,
|
||||
out_dir: Path,
|
||||
component_id: str,
|
||||
version: str,
|
||||
allowlist: list[str],
|
||||
) -> dict:
|
||||
files = collect_files(root, allowlist)
|
||||
payload = archive_bytes(files)
|
||||
digest = hashlib.sha256(payload).hexdigest()
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
archive_name = f"marqdo-{component_id}-{version}-source.tar.gz"
|
||||
archive_path = out_dir / archive_name
|
||||
sha_path = out_dir / f"{archive_name}.sha256"
|
||||
archive_path.write_bytes(payload)
|
||||
sha_path.write_text(f"{digest} {archive_name}\n", encoding="utf-8")
|
||||
return {
|
||||
"archive": str(archive_path),
|
||||
"sha256_file": str(sha_path),
|
||||
"name": archive_name,
|
||||
"size": len(payload),
|
||||
"sha256": digest,
|
||||
"files": [relative for relative, _ in files],
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", default=".", help="component repository root")
|
||||
parser.add_argument("--component-id", required=True)
|
||||
parser.add_argument("--version", required=True, help="version without leading v")
|
||||
parser.add_argument("--out-dir", default="dist")
|
||||
parser.add_argument(
|
||||
"--allow",
|
||||
action="append",
|
||||
default=[],
|
||||
help="relative allowlist entry (repeatable); defaults applied when omitted",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
allowlist = args.allow or list(DEFAULT_ALLOWLIST)
|
||||
root = Path(args.root).resolve()
|
||||
out_dir = Path(args.out_dir)
|
||||
if not out_dir.is_absolute():
|
||||
out_dir = root / out_dir
|
||||
try:
|
||||
result = write_outputs(root, out_dir, args.component_id, args.version, allowlist)
|
||||
except PackageError as error:
|
||||
print(f"package_source: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(result["archive"])
|
||||
print(result["sha256_file"])
|
||||
print(f"sha256={result['sha256']} size={result['size']} files={len(result['files'])}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+352
@@ -0,0 +1,352 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish a Gitea release with a draft transaction and immutable public assets.
|
||||
|
||||
Order (issue #10 §4.2):
|
||||
create/reuse draft → upload non-index assets → upload release-evidence.json last
|
||||
→ re-read and verify → mark non-draft → re-confirm.
|
||||
|
||||
Never deletes or replaces assets on an already-published (non-draft) release.
|
||||
Identical published identity is treated as idempotent success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_API = "https://git.cflmy.cn/api/v1"
|
||||
INDEX_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class PublishError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def token() -> str:
|
||||
value = (
|
||||
os.environ.get("GITEA_PUBLISH_TOKEN")
|
||||
or os.environ.get("GITEA_TOKEN")
|
||||
or os.environ.get("gitea_token")
|
||||
)
|
||||
if not value:
|
||||
raise PublishError("GITEA_PUBLISH_TOKEN (or GITEA_TOKEN) is not set")
|
||||
return value
|
||||
|
||||
|
||||
def request(
|
||||
api: str,
|
||||
method: str,
|
||||
path: str,
|
||||
token_value: str,
|
||||
payload: dict | None = None,
|
||||
raw: bytes | None = None,
|
||||
content_type: str = "application/json",
|
||||
) -> tuple[int, bytes]:
|
||||
url = f"{api}{path}"
|
||||
headers = {"Authorization": f"token {token_value}", "Accept": "application/json"}
|
||||
data = None
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = content_type
|
||||
elif raw is not None:
|
||||
data = raw
|
||||
headers["Content-Type"] = content_type
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read()
|
||||
|
||||
|
||||
def decode(body: bytes) -> object:
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def get_release_by_tag(api: str, repo: str, tag: str, token_value: str) -> dict | None:
|
||||
status, body = request(
|
||||
api,
|
||||
"GET",
|
||||
f"/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}",
|
||||
token_value,
|
||||
)
|
||||
if status == 404:
|
||||
return None
|
||||
if status != 200:
|
||||
raise PublishError(f"lookup release {tag} failed with HTTP {status}")
|
||||
release = decode(body)
|
||||
if not isinstance(release, dict) or "id" not in release:
|
||||
raise PublishError("release lookup response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def create_draft(
|
||||
api: str,
|
||||
repo: str,
|
||||
tag: str,
|
||||
body: str,
|
||||
token_value: str,
|
||||
*,
|
||||
prerelease: bool,
|
||||
target: str,
|
||||
) -> dict:
|
||||
payload = {
|
||||
"tag_name": tag,
|
||||
"name": tag,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": prerelease,
|
||||
"target_commitish": target,
|
||||
}
|
||||
status, response = request(api, "POST", f"/repos/{repo}/releases", token_value, payload)
|
||||
if status not in (200, 201):
|
||||
raise PublishError(f"creating draft release failed with HTTP {status}: {response[:200]!r}")
|
||||
release = decode(response)
|
||||
if not isinstance(release, dict) or "id" not in release:
|
||||
raise PublishError("draft create response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def patch_release(api: str, repo: str, release_id: int, token_value: str, payload: dict) -> dict:
|
||||
status, response = request(
|
||||
api, "PATCH", f"/repos/{repo}/releases/{release_id}", token_value, payload
|
||||
)
|
||||
if status != 200:
|
||||
raise PublishError(f"updating release {release_id} failed with HTTP {status}")
|
||||
release = decode(response)
|
||||
if not isinstance(release, dict):
|
||||
raise PublishError("release patch response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def list_assets(api: str, repo: str, release_id: int, token_value: str) -> list[dict]:
|
||||
status, response = request(
|
||||
api, "GET", f"/repos/{repo}/releases/{release_id}/assets", token_value
|
||||
)
|
||||
if status != 200:
|
||||
raise PublishError(f"listing assets failed with HTTP {status}")
|
||||
assets = decode(response)
|
||||
if not isinstance(assets, list):
|
||||
raise PublishError("asset list malformed")
|
||||
return assets
|
||||
|
||||
|
||||
def upload_asset(
|
||||
api: str, repo: str, release_id: int, path: Path, token_value: str
|
||||
) -> dict:
|
||||
name = path.name
|
||||
if not name or "/" in name or name in (".", ".."):
|
||||
raise PublishError(f"unsafe asset name: {name!r}")
|
||||
existing = list_assets(api, repo, release_id, token_value)
|
||||
for asset in existing:
|
||||
if asset.get("name") == name:
|
||||
raise PublishError(
|
||||
f"asset {name} already exists on draft/release {release_id}; "
|
||||
"refusing to overwrite"
|
||||
)
|
||||
boundary = f"----marqdo{uuid.uuid4().hex}"
|
||||
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
||||
body = bytearray()
|
||||
body.extend(f"--{boundary}\r\n".encode())
|
||||
body.extend(
|
||||
f'Content-Disposition: form-data; name="attachment"; filename="{name}"\r\n'.encode()
|
||||
)
|
||||
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode())
|
||||
body.extend(path.read_bytes())
|
||||
body.extend(f"\r\n--{boundary}--\r\n".encode())
|
||||
status, response = request(
|
||||
api,
|
||||
"POST",
|
||||
f"/repos/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(name)}",
|
||||
token_value,
|
||||
raw=bytes(body),
|
||||
content_type=f"multipart/form-data; boundary={boundary}",
|
||||
)
|
||||
if status not in (200, 201):
|
||||
raise PublishError(f"uploading {name} failed with HTTP {status}: {response[:200]!r}")
|
||||
result = decode(response)
|
||||
if not isinstance(result, dict):
|
||||
raise PublishError(f"upload response for {name} malformed")
|
||||
return result
|
||||
|
||||
|
||||
def asset_identity(path: Path) -> dict:
|
||||
return {
|
||||
"name": path.name,
|
||||
"size": path.stat().st_size,
|
||||
"sha256": sha256_file(path),
|
||||
}
|
||||
|
||||
|
||||
def published_matches(release: dict, expected: list[dict]) -> bool:
|
||||
remote = {
|
||||
asset.get("name"): int(asset.get("size") or -1)
|
||||
for asset in (release.get("assets") or [])
|
||||
}
|
||||
if set(remote) != {item["name"] for item in expected}:
|
||||
return False
|
||||
for item in expected:
|
||||
if remote.get(item["name"]) != item["size"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def publish(
|
||||
*,
|
||||
api: str,
|
||||
repo: str,
|
||||
tag: str,
|
||||
body: str,
|
||||
target: str,
|
||||
assets: list[Path],
|
||||
prerelease: bool,
|
||||
token_value: str,
|
||||
) -> dict:
|
||||
if not assets:
|
||||
raise PublishError("no assets to publish")
|
||||
index_assets = [path for path in assets if path.name == INDEX_NAME]
|
||||
other_assets = [path for path in assets if path.name != INDEX_NAME]
|
||||
if len(index_assets) != 1:
|
||||
raise PublishError("exactly one release-evidence.json is required")
|
||||
ordered = other_assets + index_assets
|
||||
expected = [asset_identity(path) for path in ordered]
|
||||
|
||||
existing = get_release_by_tag(api, repo, tag, token_value)
|
||||
if existing and not existing.get("draft"):
|
||||
if published_matches(existing, expected):
|
||||
return {
|
||||
"status": "idempotent",
|
||||
"release_id": existing["id"],
|
||||
"html_url": existing.get("html_url"),
|
||||
"tag": tag,
|
||||
"assets": expected,
|
||||
}
|
||||
raise PublishError(
|
||||
f"published release {tag} already exists with different assets; "
|
||||
"refusing to overwrite"
|
||||
)
|
||||
|
||||
if existing and existing.get("draft"):
|
||||
release = existing
|
||||
# Keep draft body/target aligned when continuing an interrupted publish.
|
||||
release = patch_release(
|
||||
api,
|
||||
repo,
|
||||
int(release["id"]),
|
||||
token_value,
|
||||
{
|
||||
"name": tag,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": prerelease,
|
||||
"target_commitish": target,
|
||||
},
|
||||
)
|
||||
else:
|
||||
release = create_draft(
|
||||
api, repo, tag, body, token_value, prerelease=prerelease, target=target
|
||||
)
|
||||
|
||||
release_id = int(release["id"])
|
||||
remote_names = {asset.get("name") for asset in list_assets(api, repo, release_id, token_value)}
|
||||
for path in ordered:
|
||||
if path.name in remote_names:
|
||||
# Same-name asset already on this draft: require identical size, else fail.
|
||||
match = next(
|
||||
asset
|
||||
for asset in list_assets(api, repo, release_id, token_value)
|
||||
if asset.get("name") == path.name
|
||||
)
|
||||
if int(match.get("size") or -1) != path.stat().st_size:
|
||||
raise PublishError(
|
||||
f"draft asset {path.name} size mismatch; refusing to overwrite"
|
||||
)
|
||||
continue
|
||||
upload_asset(api, repo, release_id, path, token_value)
|
||||
|
||||
refreshed = get_release_by_tag(api, repo, tag, token_value)
|
||||
if not refreshed or not published_matches(refreshed, expected):
|
||||
raise PublishError("post-upload release asset list does not match local files")
|
||||
|
||||
published = patch_release(
|
||||
api,
|
||||
repo,
|
||||
release_id,
|
||||
token_value,
|
||||
{"draft": False, "prerelease": prerelease, "name": tag, "body": body},
|
||||
)
|
||||
if published.get("draft"):
|
||||
raise PublishError("release remained draft after publish")
|
||||
final = get_release_by_tag(api, repo, tag, token_value)
|
||||
if not final or final.get("draft") or not published_matches(final, expected):
|
||||
raise PublishError("final release confirmation failed")
|
||||
return {
|
||||
"status": "published",
|
||||
"release_id": final["id"],
|
||||
"html_url": final.get("html_url"),
|
||||
"tag": tag,
|
||||
"assets": expected,
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", DEFAULT_API))
|
||||
parser.add_argument("--repo", required=True, help="owner/name")
|
||||
parser.add_argument("--tag", required=True)
|
||||
parser.add_argument("--target", required=True, help="full commit SHA for the tag")
|
||||
parser.add_argument("--body-file", default=None)
|
||||
parser.add_argument("--body", default="")
|
||||
parser.add_argument("--asset", action="append", default=[], required=True)
|
||||
parser.add_argument("--prerelease", action="store_true", default=False)
|
||||
parser.add_argument("--evidence-out", default="dist/gitea-publish-result.json")
|
||||
args = parser.parse_args(argv)
|
||||
body = args.body
|
||||
if args.body_file:
|
||||
body = Path(args.body_file).read_text(encoding="utf-8")
|
||||
assets = [Path(item) for item in args.asset]
|
||||
for path in assets:
|
||||
if not path.is_file():
|
||||
print(f"publish_gitea: FAIL: missing asset {path}", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
result = publish(
|
||||
api=args.api_url.rstrip("/"),
|
||||
repo=args.repo,
|
||||
tag=args.tag,
|
||||
body=body,
|
||||
target=args.target,
|
||||
assets=assets,
|
||||
prerelease=args.prerelease,
|
||||
token_value=token(),
|
||||
)
|
||||
except PublishError as error:
|
||||
print(f"publish_gitea: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
out = Path(args.evidence_out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+165
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write the external release-evidence.json index for a component release.
|
||||
|
||||
The index references already-built assets. It never includes itself in
|
||||
`assets[]` (no self-referential digest). Downstream discoverers hash the index
|
||||
bytes separately when they download it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SHA_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
|
||||
MAX_ASSETS = 128
|
||||
MAX_DEPENDENCIES = 256
|
||||
INDEX_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class EvidenceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
while True:
|
||||
chunk = handle.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def parse_dependency(raw: str) -> dict:
|
||||
# id=cli,source_sha=<40hex>[,asset_sha256=<64hex>]
|
||||
fields = {}
|
||||
for part in raw.split(","):
|
||||
if "=" not in part:
|
||||
raise EvidenceError(f"invalid dependency field: {raw!r}")
|
||||
key, value = part.split("=", 1)
|
||||
fields[key.strip()] = value.strip()
|
||||
component_id = fields.get("id")
|
||||
source_sha = fields.get("source_sha")
|
||||
if not component_id or not source_sha or not SHA_RE.match(source_sha):
|
||||
raise EvidenceError(f"dependency requires id and 40-hex source_sha: {raw!r}")
|
||||
entry = {"id": component_id, "source_sha": source_sha}
|
||||
asset = fields.get("asset_sha256")
|
||||
if asset:
|
||||
if not DIGEST_RE.match(asset):
|
||||
raise EvidenceError(f"invalid asset_sha256 in dependency: {raw!r}")
|
||||
entry["asset_sha256"] = asset
|
||||
return entry
|
||||
|
||||
|
||||
def build_evidence(
|
||||
*,
|
||||
component_id: str,
|
||||
repository: str,
|
||||
tag: str,
|
||||
source_sha: str,
|
||||
assets: list[Path],
|
||||
dependencies: list[dict],
|
||||
pipeline_number: int | None,
|
||||
pipeline_url: str | None,
|
||||
) -> dict:
|
||||
if not component_id:
|
||||
raise EvidenceError("component_id is required")
|
||||
if "/" not in repository:
|
||||
raise EvidenceError("repository must be owner/name")
|
||||
if not tag:
|
||||
raise EvidenceError("tag is required")
|
||||
if not SHA_RE.match(source_sha):
|
||||
raise EvidenceError("source_sha must be a 40-hex commit")
|
||||
if not assets:
|
||||
raise EvidenceError("at least one non-index asset is required")
|
||||
if len(assets) > MAX_ASSETS:
|
||||
raise EvidenceError(f"more than {MAX_ASSETS} assets")
|
||||
if len(dependencies) > MAX_DEPENDENCIES:
|
||||
raise EvidenceError(f"more than {MAX_DEPENDENCIES} dependencies")
|
||||
|
||||
asset_entries = []
|
||||
seen_names: set[str] = set()
|
||||
for path in assets:
|
||||
if not path.is_file():
|
||||
raise EvidenceError(f"asset missing: {path}")
|
||||
name = path.name
|
||||
if name == INDEX_NAME:
|
||||
raise EvidenceError("assets must not include release-evidence.json itself")
|
||||
if name in seen_names or "/" in name or name in (".", ".."):
|
||||
raise EvidenceError(f"unsafe or duplicate asset name: {name!r}")
|
||||
seen_names.add(name)
|
||||
target = "source"
|
||||
if name.endswith(".tar.gz") and "linux" in name:
|
||||
target = "x86_64-unknown-linux-gnu"
|
||||
asset_entries.append(
|
||||
{
|
||||
"name": name,
|
||||
"target": target,
|
||||
"size": path.stat().st_size,
|
||||
"sha256": sha256_file(path),
|
||||
}
|
||||
)
|
||||
|
||||
evidence = {
|
||||
"component_id": component_id,
|
||||
"repository": repository,
|
||||
"tag": tag,
|
||||
"source_sha": source_sha,
|
||||
"ci": {
|
||||
"pipeline_number": pipeline_number,
|
||||
"url": pipeline_url,
|
||||
"source_sha": source_sha,
|
||||
},
|
||||
"assets": asset_entries,
|
||||
"dependencies": dependencies,
|
||||
}
|
||||
return evidence
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--component-id", required=True)
|
||||
parser.add_argument("--repository", required=True)
|
||||
parser.add_argument("--tag", required=True)
|
||||
parser.add_argument("--source-sha", required=True)
|
||||
parser.add_argument("--asset", action="append", default=[], required=True)
|
||||
parser.add_argument("--dependency", action="append", default=[])
|
||||
parser.add_argument("--pipeline-number", type=int, default=None)
|
||||
parser.add_argument("--pipeline-url", default=None)
|
||||
parser.add_argument("--out", default=f"dist/{INDEX_NAME}")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
dependencies = [parse_dependency(item) for item in args.dependency]
|
||||
evidence = build_evidence(
|
||||
component_id=args.component_id,
|
||||
repository=args.repository,
|
||||
tag=args.tag,
|
||||
source_sha=args.source_sha,
|
||||
assets=[Path(item) for item in args.asset],
|
||||
dependencies=dependencies,
|
||||
pipeline_number=args.pipeline_number,
|
||||
pipeline_url=args.pipeline_url,
|
||||
)
|
||||
except EvidenceError as error:
|
||||
print(f"write_evidence: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
|
||||
if len(payload.encode()) > 1024 * 1024:
|
||||
print("write_evidence: FAIL: index exceeds 1 MiB", file=sys.stderr)
|
||||
return 1
|
||||
out.write_text(payload, encoding="utf-8")
|
||||
print(out)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
//! Static input snapshot: run the public CLI `check --emit` and validate Analysis 3.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::diagnostic::{span_from, Diagnostic, Diagnostics, LoadError};
|
||||
|
||||
static UNIQUE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Module {
|
||||
/// Canonical physical path.
|
||||
pub path: PathBuf,
|
||||
/// Root-relative path used in diagnostics and source identities.
|
||||
pub relative: String,
|
||||
pub source: String,
|
||||
pub source_digest: String,
|
||||
pub module_id: String,
|
||||
pub units: Vec<Value>,
|
||||
pub anchors: Vec<Value>,
|
||||
pub document: Value,
|
||||
pub references: Vec<Value>,
|
||||
}
|
||||
|
||||
impl Module {
|
||||
pub fn text(&self, span: &Value) -> Option<&str> {
|
||||
let (start, end) = span_from(span)?;
|
||||
let bytes = self.source.as_bytes();
|
||||
if start > end || end > bytes.len() {
|
||||
return None;
|
||||
}
|
||||
std::str::from_utf8(&bytes[start..end]).ok()
|
||||
}
|
||||
|
||||
pub fn text_span(&self, start: usize, end: usize) -> Option<&str> {
|
||||
let bytes = self.source.as_bytes();
|
||||
if start > end || end > bytes.len() {
|
||||
return None;
|
||||
}
|
||||
std::str::from_utf8(&bytes[start..end]).ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir() -> Result<PathBuf, LoadError> {
|
||||
let unique = UNIQUE.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("marqdo-web-design-{}-{unique}", std::process::id()));
|
||||
std::fs::create_dir_all(&path).map_err(|error| {
|
||||
LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.tempdir",
|
||||
format!("cannot create temporary directory: {error}"),
|
||||
)])
|
||||
})?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Analyse one document through the public CLI, returning the single module.
|
||||
pub fn analyze(cli: &Path, document: &Path, root: &Path) -> Result<Module, LoadError> {
|
||||
let canonical = document.canonicalize().map_err(|error| {
|
||||
LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.entry",
|
||||
format!("cannot canonicalize {}: {error}", document.display()),
|
||||
)])
|
||||
})?;
|
||||
let work = temp_dir()?;
|
||||
let emit = work.join("analysis.json");
|
||||
let output = Command::new(cli)
|
||||
.arg("check")
|
||||
.arg(&canonical)
|
||||
.arg("--emit")
|
||||
.arg(&emit)
|
||||
.current_dir(canonical.parent().unwrap_or(root))
|
||||
.output()
|
||||
.map_err(|error| {
|
||||
LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.cli_missing",
|
||||
format!("cannot execute {}: {error}", cli.display()),
|
||||
)])
|
||||
})?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return Err(LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.cli_failed",
|
||||
format!(
|
||||
"`check --emit` failed with exit {:?}: {stderr}",
|
||||
output.status.code()
|
||||
),
|
||||
)
|
||||
.at(
|
||||
relative_path(&canonical, root).unwrap_or_else(|| canonical.display().to_string()),
|
||||
None,
|
||||
)]));
|
||||
}
|
||||
let raw = std::fs::read(&emit).map_err(|error| {
|
||||
LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.analysis",
|
||||
format!("cannot read emitted Analysis: {error}"),
|
||||
)])
|
||||
})?;
|
||||
let analysis: Value = serde_json::from_slice(&raw).map_err(|error| {
|
||||
LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.analysis",
|
||||
format!("emitted Analysis is not valid JSON: {error}"),
|
||||
)])
|
||||
})?;
|
||||
validate_analysis(&analysis, &canonical, root)?;
|
||||
let module = analysis["modules"][0].clone();
|
||||
let source = module["source"].as_str().unwrap_or_default().to_string();
|
||||
let source_digest = module["source_digest"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let module_id = module["id"].as_str().unwrap_or_default().to_string();
|
||||
let units = module["units"].as_array().cloned().unwrap_or_default();
|
||||
let anchors = module["anchors"].as_array().cloned().unwrap_or_default();
|
||||
let document = module["document"].clone();
|
||||
let references = module["references"].as_array().cloned().unwrap_or_default();
|
||||
let relative =
|
||||
relative_path(&canonical, root).unwrap_or_else(|| canonical.display().to_string());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
Ok(Module {
|
||||
path: canonical,
|
||||
relative,
|
||||
source,
|
||||
source_digest,
|
||||
module_id,
|
||||
units,
|
||||
anchors,
|
||||
document,
|
||||
references,
|
||||
})
|
||||
}
|
||||
|
||||
fn relative_path(path: &Path, root: &Path) -> Option<String> {
|
||||
path.strip_prefix(root)
|
||||
.ok()
|
||||
.map(|value| value.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
fn validate_analysis(analysis: &Value, document: &Path, root: &Path) -> Result<(), LoadError> {
|
||||
let engine = |code, message: String| {
|
||||
LoadError::Engine(vec![Diagnostic::error(code, message).at(
|
||||
relative_path(document, root).unwrap_or_else(|| document.display().to_string()),
|
||||
None,
|
||||
)])
|
||||
};
|
||||
if analysis["schema"].as_str() != Some("marqdo.analysis") {
|
||||
return Err(engine(
|
||||
"web.engine.protocol",
|
||||
"CLI output is not marqdo.analysis".to_string(),
|
||||
));
|
||||
}
|
||||
if analysis["schema_version"].as_u64() != Some(3) {
|
||||
return Err(engine(
|
||||
"web.engine.protocol",
|
||||
"Analysis schema_version must be 3".to_string(),
|
||||
));
|
||||
}
|
||||
let modules = analysis["modules"]
|
||||
.as_array()
|
||||
.ok_or_else(|| engine("web.engine.protocol", "Analysis has no modules".to_string()))?;
|
||||
if modules.len() != 1 {
|
||||
return Err(engine(
|
||||
"web.engine.protocol",
|
||||
format!("expected one analyzed module, found {}", modules.len()),
|
||||
));
|
||||
}
|
||||
let module = &modules[0];
|
||||
let digest = module["source_digest"].as_str().unwrap_or_default();
|
||||
if digest.len() != 64 || !digest.chars().all(|ch| ch.is_ascii_hexdigit()) {
|
||||
return Err(engine(
|
||||
"web.engine.protocol",
|
||||
"Analysis module has no valid source_digest".to_string(),
|
||||
));
|
||||
}
|
||||
let source = module["source"].as_str().unwrap_or_default();
|
||||
if source.is_empty() {
|
||||
return Err(engine(
|
||||
"web.engine.protocol",
|
||||
"Analysis module inlines no source; stale/tampered input".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn engine_diagnostics(error: LoadError) -> Diagnostics {
|
||||
error.into_diagnostics()
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Stable diagnostic codes and source locations.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Severity {
|
||||
Error,
|
||||
Warning,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Span {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Diagnostic {
|
||||
pub code: &'static str,
|
||||
pub severity: Severity,
|
||||
pub message: String,
|
||||
pub path: Option<String>,
|
||||
pub anchor: Option<String>,
|
||||
pub span: Option<Span>,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub fn error(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
severity: Severity::Error,
|
||||
message: message.into(),
|
||||
path: None,
|
||||
anchor: None,
|
||||
span: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn at(mut self, path: impl Into<String>, span: Option<(usize, usize)>) -> Self {
|
||||
self.path = Some(path.into());
|
||||
self.span = span.map(|(start, end)| Span { start, end });
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_anchor(mut self, anchor: impl Into<String>) -> Self {
|
||||
self.anchor = Some(anchor.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub type Diagnostics = Vec<Diagnostic>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum LoadError {
|
||||
/// The CLI/engine/protocol failed; hosts map this to exit code 2.
|
||||
Engine(Diagnostics),
|
||||
/// The author document violates the design contract; hosts map this to exit code 1.
|
||||
Design(Diagnostics),
|
||||
}
|
||||
|
||||
impl From<Diagnostic> for LoadError {
|
||||
fn from(diagnostic: Diagnostic) -> Self {
|
||||
LoadError::Design(vec![diagnostic])
|
||||
}
|
||||
}
|
||||
|
||||
impl LoadError {
|
||||
pub fn diagnostics(&self) -> &Diagnostics {
|
||||
match self {
|
||||
Self::Engine(items) | Self::Design(items) => items,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_diagnostics(self) -> Diagnostics {
|
||||
match self {
|
||||
Self::Engine(items) | Self::Design(items) => items,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn span_from(value: &Value) -> Option<(usize, usize)> {
|
||||
Some((
|
||||
value.get("start")?.as_u64()? as usize,
|
||||
value.get("end")?.as_u64()? as usize,
|
||||
))
|
||||
}
|
||||
+434
@@ -0,0 +1,434 @@
|
||||
//! Deterministic selection of the contract's units and GFM tables from Analysis 3.
|
||||
//!
|
||||
//! Only public Analysis facts are consumed: unit ids/paths/spans/anchors and the
|
||||
//! canonical Markdown AST. No Markdown parser is implemented here; cell text is
|
||||
//! read from the analysis-provided source by UTF-8 byte span.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::analysis::Module;
|
||||
use crate::diagnostic::{span_from, Diagnostic};
|
||||
|
||||
pub const COMPONENTS: &str = "组件";
|
||||
pub const COMPONENTS_HEADER: [&str; 4] = ["行", "槽", "组件", "宽度"];
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Unit {
|
||||
pub id: String,
|
||||
pub kind: String,
|
||||
pub mode: String,
|
||||
pub name: String,
|
||||
pub level: u64,
|
||||
pub path: Vec<String>,
|
||||
pub parent_id: Option<String>,
|
||||
pub span: (usize, usize),
|
||||
pub heading_span: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl Unit {
|
||||
pub fn anchor_text(&self) -> &str {
|
||||
self.path.last().map(String::as_str).unwrap_or("")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Link {
|
||||
pub url: String,
|
||||
pub span: (usize, usize),
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Cell {
|
||||
pub span: (usize, usize),
|
||||
pub text: String,
|
||||
pub links: Vec<Link>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Table {
|
||||
pub span: (usize, usize),
|
||||
pub headers: Vec<String>,
|
||||
pub rows: Vec<Vec<Cell>>,
|
||||
}
|
||||
|
||||
fn units(module: &Module) -> Vec<Unit> {
|
||||
module
|
||||
.units
|
||||
.iter()
|
||||
.filter_map(|unit| {
|
||||
let id = unit["id"].as_str()?.to_string();
|
||||
Some(Unit {
|
||||
id,
|
||||
kind: unit["kind"].as_str().unwrap_or("").to_string(),
|
||||
mode: unit["mode"].as_str().unwrap_or("").to_string(),
|
||||
name: unit["name"].as_str().unwrap_or("").to_string(),
|
||||
level: unit["level"].as_u64()?,
|
||||
path: unit["path"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|value| value.as_str().map(ToString::to_string))
|
||||
.collect(),
|
||||
parent_id: unit["parent_id"].as_str().map(ToString::to_string),
|
||||
span: span_from(&unit["span"]).unwrap_or((0, 0)),
|
||||
heading_span: span_from(&unit["heading_span"]),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn text_at(module: &Module, span: (usize, usize)) -> String {
|
||||
module
|
||||
.text_span(span.0, span.1)
|
||||
.unwrap_or_default()
|
||||
.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();
|
||||
for entry in &module.anchors {
|
||||
if entry["anchor"].as_str() != Some(anchor) {
|
||||
continue;
|
||||
}
|
||||
if let Some(unit) = entry["unit_id"]
|
||||
.as_str()
|
||||
.and_then(|unit_id| units(module).into_iter().find(|unit| unit.id == unit_id))
|
||||
{
|
||||
matches.push(unit);
|
||||
}
|
||||
}
|
||||
match matches.len() {
|
||||
0 => Err(Diagnostic::error(
|
||||
"web.unit.anchor_missing",
|
||||
format!("no unit has the exact anchor {anchor:?}"),
|
||||
)
|
||||
.with_anchor(anchor)
|
||||
.at(module.relative.clone(), None)),
|
||||
1 => Ok(matches.remove(0)),
|
||||
_ => Err(Diagnostic::error(
|
||||
"web.unit.anchor_ambiguous",
|
||||
format!("anchor {anchor:?} resolves to more than one unit"),
|
||||
)
|
||||
.with_anchor(anchor)
|
||||
.at(module.relative.clone(), None)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the Knowledge H2 by its exact anchor, never by label/path guessing.
|
||||
pub fn knowledge_h2(module: &Module, anchor: &str) -> Result<Unit, Diagnostic> {
|
||||
let mut matches = Vec::new();
|
||||
for entry in &module.anchors {
|
||||
if entry["anchor"].as_str() != Some(anchor) {
|
||||
continue;
|
||||
}
|
||||
let Some(unit_id) = entry["unit_id"].as_str() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(unit) = units(module).into_iter().find(|unit| unit.id == unit_id) {
|
||||
matches.push(unit);
|
||||
}
|
||||
}
|
||||
if matches.is_empty() {
|
||||
return Err(Diagnostic::error(
|
||||
"web.unit.anchor_missing",
|
||||
format!("no unit has the exact anchor {anchor:?}"),
|
||||
)
|
||||
.with_anchor(anchor)
|
||||
.at(module.relative.clone(), None));
|
||||
}
|
||||
if matches.len() > 1 {
|
||||
return Err(Diagnostic::error(
|
||||
"web.unit.anchor_ambiguous",
|
||||
format!("anchor {anchor:?} resolves to more than one unit"),
|
||||
)
|
||||
.with_anchor(anchor)
|
||||
.at(module.relative.clone(), None));
|
||||
}
|
||||
let unit = matches.remove(0);
|
||||
if unit.kind != "knowledge" || unit.level != 2 || unit.mode != "knowledge" {
|
||||
return Err(Diagnostic::error(
|
||||
"web.unit.not_knowledge_h2",
|
||||
format!(
|
||||
"design component must be a Knowledge H2 (found kind={} level={} mode={})",
|
||||
unit.kind, unit.level, unit.mode
|
||||
),
|
||||
)
|
||||
.with_anchor(anchor)
|
||||
.at(module.relative.clone(), unit.heading_span));
|
||||
}
|
||||
Ok(unit)
|
||||
}
|
||||
|
||||
/// Direct retained H3 sections under one H2.
|
||||
pub fn direct_sections(module: &Module, h2: &Unit) -> Vec<Unit> {
|
||||
units(module)
|
||||
.into_iter()
|
||||
.filter(|unit| {
|
||||
unit.level == 3
|
||||
&& unit.kind == "section"
|
||||
&& unit.parent_id.as_deref() == Some(h2.id.as_str())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn walk_tables<'a>(node: &'a Value, out: &mut Vec<&'a Value>) {
|
||||
if node["kind"].as_str() == Some("table") {
|
||||
out.push(node);
|
||||
}
|
||||
if let Some(children) = node["children"].as_array() {
|
||||
for child in children {
|
||||
walk_tables(child, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_links<'a>(node: &'a Value, out: &mut Vec<&'a Value>) {
|
||||
if node["kind"].as_str() == Some("link") {
|
||||
out.push(node);
|
||||
}
|
||||
if let Some(children) = node["children"].as_array() {
|
||||
for child in children {
|
||||
walk_links(child, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the single table with one exact header inside a direct retained H3.
|
||||
/// `Ok(None)` means the section is absent.
|
||||
pub fn section_table(
|
||||
module: &Module,
|
||||
h2: &Unit,
|
||||
name: &str,
|
||||
header: &[&str],
|
||||
) -> Result<Option<(Unit, Table)>, Diagnostic> {
|
||||
let Some(section) = direct_sections(module, h2)
|
||||
.into_iter()
|
||||
.find(|section| section.name == name)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut tables = Vec::new();
|
||||
walk_tables(&module.document, &mut tables);
|
||||
let mut inside: Vec<&Value> = tables
|
||||
.into_iter()
|
||||
.filter(|table| {
|
||||
span_from(&table["span"])
|
||||
.map(|(start, end)| start >= section.span.0 && end <= section.span.1)
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect();
|
||||
match inside.len() {
|
||||
0 => Err(Diagnostic::error(
|
||||
"web.table.missing",
|
||||
format!("`{name}` section has no GFM table"),
|
||||
)
|
||||
.at(module.relative.clone(), Some(section.span))),
|
||||
1 => {
|
||||
let table = parse_table_with_header(module, inside.remove(0), header, name)?;
|
||||
Ok(Some((section, table)))
|
||||
}
|
||||
_ => Err(Diagnostic::error(
|
||||
"web.table.multiple",
|
||||
format!("`{name}` section must contain exactly one GFM table"),
|
||||
)
|
||||
.at(module.relative.clone(), Some(section.span))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the single retained `组件` table inside its direct H3 section.
|
||||
/// Returns `Ok(None)` when the component declares no component table.
|
||||
pub fn components_table(module: &Module, h2: &Unit) -> Result<Option<(Unit, Table)>, Diagnostic> {
|
||||
let section = direct_sections(module, h2)
|
||||
.into_iter()
|
||||
.find(|section| section.name == COMPONENTS);
|
||||
let Some(section) = section else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut tables = Vec::new();
|
||||
walk_tables(&module.document, &mut tables);
|
||||
let mut inside: Vec<&Value> = tables
|
||||
.into_iter()
|
||||
.filter(|table| {
|
||||
span_from(&table["span"])
|
||||
.map(|(start, end)| start >= section.span.0 && end <= section.span.1)
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect();
|
||||
match inside.len() {
|
||||
0 => Err(
|
||||
Diagnostic::error("web.table.missing", "`组件` section has no GFM table")
|
||||
.at(module.relative.clone(), Some(section.span))
|
||||
.with_anchor(section.anchor_text().to_string()),
|
||||
),
|
||||
1 => Ok(Some((
|
||||
section.clone(),
|
||||
parse_table_with_header(module, inside.remove(0), &COMPONENTS_HEADER, COMPONENTS)?,
|
||||
))),
|
||||
_ => Err(Diagnostic::error(
|
||||
"web.table.multiple",
|
||||
"`组件` section must contain exactly one GFM table",
|
||||
)
|
||||
.at(module.relative.clone(), Some(section.span))),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_table_with_header(
|
||||
module: &Module,
|
||||
table: &Value,
|
||||
expected_header: &[&str],
|
||||
name: &str,
|
||||
) -> Result<Table, Diagnostic> {
|
||||
let span = span_from(&table["span"]).ok_or_else(|| {
|
||||
Diagnostic::error("web.table.span", "table has no source span")
|
||||
.at(module.relative.clone(), None)
|
||||
})?;
|
||||
let mut ast_rows = Vec::new();
|
||||
if let Some(children) = table["children"].as_array() {
|
||||
for child in children {
|
||||
if child["kind"].as_str() == Some("table_row") {
|
||||
ast_rows.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ast_rows.len() < 2 {
|
||||
return Err(Diagnostic::error(
|
||||
"web.table.rows",
|
||||
"`组件` table needs a header and at least one component row",
|
||||
)
|
||||
.at(module.relative.clone(), Some(span)));
|
||||
}
|
||||
let headers: Vec<String> = ast_rows[0]["children"]
|
||||
.as_array()
|
||||
.map(|cells| {
|
||||
cells
|
||||
.iter()
|
||||
.map(|cell| {
|
||||
text_at(module, span_from(&cell["span"]).unwrap_or((0, 0)))
|
||||
.trim()
|
||||
.to_string()
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if headers != expected_header {
|
||||
return Err(Diagnostic::error(
|
||||
"web.table.header",
|
||||
format!(
|
||||
"`{name}` header must be exactly {:?}, found {:?}",
|
||||
expected_header, headers
|
||||
),
|
||||
)
|
||||
.at(module.relative.clone(), Some(span)));
|
||||
}
|
||||
let mut rows = Vec::new();
|
||||
for row in ast_rows.iter().skip(1) {
|
||||
let raw_cells = row["children"].as_array().cloned().unwrap_or_default();
|
||||
if raw_cells.len() != expected_header.len() {
|
||||
return Err(Diagnostic::error(
|
||||
"web.table.columns",
|
||||
format!(
|
||||
"`{name}` row must have {} cells, found {}",
|
||||
expected_header.len(),
|
||||
raw_cells.len()
|
||||
),
|
||||
)
|
||||
.at(module.relative.clone(), span_from(&row["span"])));
|
||||
}
|
||||
let mut cells = Vec::new();
|
||||
for cell in raw_cells {
|
||||
let cell_span = span_from(&cell["span"]).unwrap_or((0, 0));
|
||||
let mut ast_links = Vec::new();
|
||||
walk_links(&cell, &mut ast_links);
|
||||
let links = ast_links
|
||||
.into_iter()
|
||||
.filter_map(|link| {
|
||||
let span = span_from(&link["span"])?;
|
||||
let url = link["url"].as_str()?.to_string();
|
||||
let text = text_at(module, span);
|
||||
Some(Link { url, span, text })
|
||||
})
|
||||
.collect();
|
||||
cells.push(Cell {
|
||||
span: cell_span,
|
||||
text: text_at(module, cell_span),
|
||||
links,
|
||||
});
|
||||
}
|
||||
rows.push(cells);
|
||||
}
|
||||
Ok(Table {
|
||||
span,
|
||||
headers,
|
||||
rows,
|
||||
})
|
||||
}
|
||||
+1618
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,802 @@
|
||||
//! WEB-01 contract tests against the real verified CLI (no mocked Analysis).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use marqdo_web_design::{
|
||||
design_id, drift, graph, handoff, handoff_relative_to, load, slice, statistics, Error,
|
||||
LoadConfig,
|
||||
};
|
||||
|
||||
static UNIQUE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn cli() -> PathBuf {
|
||||
PathBuf::from(
|
||||
std::env::var("MARQDO_BIN")
|
||||
.expect("set MARQDO_BIN to the verified marqdo executable for WEB-01 tests"),
|
||||
)
|
||||
}
|
||||
|
||||
struct TempProject {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempProject {
|
||||
fn new() -> Self {
|
||||
let unique = UNIQUE.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"marqdo-web-design-test-{}-{unique}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn write(&self, relative: &str, text: &str) {
|
||||
let path = self.path.join(relative);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
fn config(&self, entry: &str, unit: &str) -> LoadConfig {
|
||||
LoadConfig::new(cli(), self.path.join(entry), unit, self.path.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempProject {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn design_code(error: Error) -> &'static str {
|
||||
match error {
|
||||
Error::Design(items) => items[0].code,
|
||||
Error::Engine(items) => panic!("expected design error, got engine: {items:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn engine_code(error: Error) -> &'static str {
|
||||
match error {
|
||||
Error::Engine(items) => items[0].code,
|
||||
Error::Design(items) => panic!("expected engine error, got design: {items:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
const INDEX: &str = r#"# 页面
|
||||
|
||||
## @knowledge 工作台
|
||||
|
||||
面向研究人员的页面。
|
||||
|
||||
### 内容
|
||||
|
||||
一些正文。
|
||||
|
||||
### 组件
|
||||
|
||||
| 行 | 槽 | 组件 | 宽度 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | nav | [导航](components/nav.mq.md#导航) | 220px |
|
||||
| 1 | main | [工作区](components/workspace.mq.md#工作区) | 1fr |
|
||||
"#;
|
||||
|
||||
const NAV: &str = r#"# 导航组件
|
||||
|
||||
## @knowledge 导航
|
||||
|
||||
### 内容
|
||||
|
||||
导航正文。
|
||||
|
||||
### 组件
|
||||
|
||||
| 行 | 槽 | 组件 | 宽度 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | leaf | [叶子](leaf.mq.md#叶子) | auto |
|
||||
"#;
|
||||
|
||||
const LEAF: &str = r#"# 叶子组件
|
||||
|
||||
## @knowledge 叶子
|
||||
|
||||
### 内容
|
||||
|
||||
叶子正文。
|
||||
"#;
|
||||
|
||||
fn basic_project() -> TempProject {
|
||||
let project = TempProject::new();
|
||||
project.write("index.mq.md", INDEX);
|
||||
project.write("components/nav.mq.md", NAV);
|
||||
project.write("components/leaf.mq.md", LEAF);
|
||||
project.write(
|
||||
"components/workspace.mq.md",
|
||||
"# 工作区页面\n\n## @knowledge 工作区\n\n### 内容\n\n工作区正文。\n",
|
||||
);
|
||||
project
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loads_recursive_layout_with_stable_source_identity() {
|
||||
let project = basic_project();
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("load");
|
||||
assert_eq!(design.root, "index.mq.md#工作台");
|
||||
assert_eq!(statistics(&design), (4, 4));
|
||||
assert_eq!(design.definitions["index.mq.md#工作台"].slots.len(), 2);
|
||||
let root_slot = &design.definitions["index.mq.md#工作台"].slots[0];
|
||||
assert_eq!(root_slot.slot, "nav");
|
||||
assert_eq!(root_slot.row, 1);
|
||||
assert_eq!(root_slot.width.to_string(), "220px");
|
||||
assert_eq!(root_slot.target, "components/nav.mq.md#导航");
|
||||
assert_eq!(
|
||||
design.definitions["components/nav.mq.md#导航"].slots[0].target,
|
||||
"components/leaf.mq.md#叶子"
|
||||
);
|
||||
assert_eq!(design.sources.len(), 4);
|
||||
for source in &design.sources {
|
||||
assert_eq!(source.source_digest.len(), 64);
|
||||
assert!(!source.module_id.is_empty());
|
||||
}
|
||||
let first = handoff(&design);
|
||||
assert!(first.contains("components/leaf.mq.md#叶子"));
|
||||
assert!(first.contains("sha256:"));
|
||||
let again = load(&project.config("index.mq.md", "工作台")).expect("deterministic load");
|
||||
assert_eq!(first, handoff(&again));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuses_definition_but_keeps_separate_instances() {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | left | [叶子](leaf.mq.md#叶子) | auto |\n| 1 | right | [叶子](leaf.mq.md#叶子) | auto |\n",
|
||||
);
|
||||
project.write("leaf.mq.md", LEAF);
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("load");
|
||||
assert_eq!(design.definitions.len(), 2);
|
||||
let ids: Vec<&str> = design
|
||||
.instances
|
||||
.iter()
|
||||
.map(|item| item.id.as_str())
|
||||
.collect();
|
||||
assert_eq!(ids, vec!["root", "root/left", "root/right"]);
|
||||
assert_eq!(design.instances[1].definition, "leaf.mq.md#叶子");
|
||||
assert_eq!(design.instances[2].definition, "leaf.mq.md#叶子");
|
||||
assert_ne!(design.instances[1].id, design.instances[2].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_content_only_component_and_width_forms() {
|
||||
let project = TempProject::new();
|
||||
project.write("index.mq.md", INDEX);
|
||||
project.write("components/nav.mq.md", &NAV.replace("220px", "1200px"));
|
||||
project.write("components/leaf.mq.md", LEAF);
|
||||
project.write(
|
||||
"components/workspace.mq.md",
|
||||
"# 工作区页面\n\n## @knowledge 工作区\n\n### 内容\n\n正文。\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [叶子](leaf.mq.md#叶子) | 12fr |\n",
|
||||
);
|
||||
load(&project.config("index.mq.md", "工作台")).expect("width forms");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_anchor_and_non_knowledge_units() {
|
||||
let project = basic_project();
|
||||
let error = load(&project.config("index.mq.md", "不存在")).unwrap_err();
|
||||
assert!(matches!(error, Error::Design(_)));
|
||||
assert_eq!(design_code(error), "web.unit.anchor_missing");
|
||||
|
||||
let exec = TempProject::new();
|
||||
exec.write("index.mq.md", "# @exec 页面\n\n## 函数\n\n`return 1`\n");
|
||||
let error = load(&exec.config("index.mq.md", "函数")).unwrap_err();
|
||||
assert_eq!(design_code(error), "web.unit.not_knowledge_h2");
|
||||
|
||||
let hashed = basic_project();
|
||||
let mut config = hashed.config("index.mq.md", "工作台");
|
||||
config.unit = "#工作台".to_string();
|
||||
assert_eq!(
|
||||
design_code(load(&config).unwrap_err()),
|
||||
"web.unit.anchor_invalid"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_component_tables_and_cells() {
|
||||
let cases: &[(&str, &str)] = &[
|
||||
(
|
||||
"| 行 | 槽 | 组件 |\n| --- | --- | --- |\n| 1 | nav | [导航](components/nav.mq.md#导航) |\n",
|
||||
"web.table.header",
|
||||
),
|
||||
(
|
||||
"| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | nav | 纯文本 | 220px |\n",
|
||||
"web.link.none",
|
||||
),
|
||||
(
|
||||
"| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | nav | [导航](components/nav.mq.md#导航) | 50% |\n",
|
||||
"web.layout.width",
|
||||
),
|
||||
(
|
||||
"| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | nav | [导航](components/nav.mq.md#导航) | auto |\n| 1 | nav | [导航](components/nav.mq.md#导航) | auto |\n",
|
||||
"web.layout.slot_duplicate",
|
||||
),
|
||||
(
|
||||
"| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 2 | nav | [导航](components/nav.mq.md#导航) | auto |\n",
|
||||
"web.layout.row_order",
|
||||
),
|
||||
];
|
||||
for (table, expected) in cases {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"index.mq.md",
|
||||
&format!("# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n{table}"),
|
||||
);
|
||||
project.write("components/nav.mq.md", NAV);
|
||||
project.write("components/leaf.mq.md", LEAF);
|
||||
let error = load(&project.config("index.mq.md", "工作台")).unwrap_err();
|
||||
assert_eq!(design_code(error), *expected, "table case: {table}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_scope_anchor_and_cycle_errors() {
|
||||
let outside = TempProject::new();
|
||||
outside.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [外部](../../outside.mq.md#目标) | auto |\n",
|
||||
);
|
||||
outside.write(
|
||||
"outside.mq.md",
|
||||
"# 目标页面\n\n## @knowledge 目标\n\n### 内容\n\nx\n",
|
||||
);
|
||||
// Analysis reports an out-of-scope link without a usable candidate path, so
|
||||
// the deterministic rejection is the candidate diagnostic (never a guess).
|
||||
assert_eq!(
|
||||
design_code(load(&outside.config("index.mq.md", "工作台")).unwrap_err()),
|
||||
"web.link.target_missing"
|
||||
);
|
||||
|
||||
let missing = basic_project();
|
||||
missing.write(
|
||||
"components/nav.mq.md",
|
||||
"# 导航组件\n\n## @knowledge 导航\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | leaf | [缺失](leaf.mq.md#不存在) | auto |\n",
|
||||
);
|
||||
assert_eq!(
|
||||
design_code(load(&missing.config("index.mq.md", "工作台")).unwrap_err()),
|
||||
"web.unit.anchor_missing"
|
||||
);
|
||||
|
||||
let cycle = TempProject::new();
|
||||
cycle.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [甲](components/a.mq.md#甲) | auto |\n",
|
||||
);
|
||||
cycle.write(
|
||||
"components/a.mq.md",
|
||||
"# 甲页面\n\n## @knowledge 甲\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | b | [乙](b.mq.md#乙) | auto |\n",
|
||||
);
|
||||
cycle.write(
|
||||
"components/b.mq.md",
|
||||
"# 乙页面\n\n## @knowledge 乙\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [甲](a.mq.md#甲) | auto |\n",
|
||||
);
|
||||
let cycle_error = load(&cycle.config("index.mq.md", "工作台")).unwrap_err();
|
||||
let cycle_code = match &cycle_error {
|
||||
Error::Design(items) => items[0].code,
|
||||
Error::Engine(items) => items[0].code,
|
||||
};
|
||||
assert_eq!(cycle_code, "web.link.cycle", "{cycle_error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_engine_failures_and_limits() {
|
||||
let project = basic_project();
|
||||
let mut config = project.config("index.mq.md", "工作台");
|
||||
config.cli = PathBuf::from("/nonexistent/marqdo");
|
||||
assert_eq!(
|
||||
engine_code(load(&config).unwrap_err()),
|
||||
"web.engine.cli_missing"
|
||||
);
|
||||
|
||||
let mut limited = project.config("index.mq.md", "工作台");
|
||||
limited.max_modules = 1;
|
||||
assert_eq!(
|
||||
design_code(load(&limited).unwrap_err()),
|
||||
"web.limit.modules"
|
||||
);
|
||||
|
||||
let mut shallow = project.config("index.mq.md", "工作台");
|
||||
shallow.max_depth = 0;
|
||||
assert_eq!(design_code(load(&shallow).unwrap_err()), "web.limit.depth");
|
||||
|
||||
let mut outside_entry = project.config("index.mq.md", "工作台");
|
||||
outside_entry.root = project.path.join("components");
|
||||
assert_eq!(
|
||||
design_code(load(&outside_entry).unwrap_err()),
|
||||
"web.unit.entry_outside_root"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_must_be_mq_md_and_expose_analysis_schema() {
|
||||
let project = basic_project();
|
||||
let config = project.config("index.mq.md", "工作台");
|
||||
// A missing entry is an engine/input failure, not a design violation.
|
||||
let mut missing = config.clone();
|
||||
missing.entry = project.path.join("nope.mq.md");
|
||||
assert_eq!(engine_code(load(&missing).unwrap_err()), "web.engine.entry");
|
||||
}
|
||||
|
||||
const STATES: &str =
|
||||
"# 状态内容\n\n## @knowledge 空状态\n\n暂无数据。\n\n## @knowledge 成功\n\n保存成功。\n";
|
||||
|
||||
#[test]
|
||||
fn loads_full_leaf_contract_inputs_events_scenarios_interactions_dependencies() {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [任务面板](components/a.mq.md#甲) | 1fr |\n| 1 | b | [详情](components/b.mq.md#乙) | 2fr |\n",
|
||||
);
|
||||
project.write(
|
||||
"components/a.mq.md",
|
||||
"# A 组件\n\n## @knowledge 甲\n\n### 输入\n\n| 名称 | 类型 | 说明 |\n| --- | --- | --- |\n| 项目 | Text | 项目名 |\n\n### 事件\n\n| 名称 | 数据 | 说明 |\n| --- | --- | --- |\n| 提交 | Result | 提交结果 |\n\n### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| empty | [空状态](states.mq.md#空状态) | true |\n| done | [成功](states.mq.md#成功) | false |\n\n### 交互\n\n| 当前 | 事件 | 下一状态 |\n| --- | --- | --- |\n| empty | 模拟保存 | done |\n\n### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [详情](b.mq.md#乙) | 提交后展示详情 |\n\n### 验收\n\n- 模拟保存后显示成功状态。\n",
|
||||
);
|
||||
project.write("components/states.mq.md", STATES);
|
||||
project.write(
|
||||
"components/b.mq.md",
|
||||
"# B 组件\n\n## @knowledge 乙\n\n### 内容\n\n详情正文。\n",
|
||||
);
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("full contract load");
|
||||
let a = &design.definitions["components/a.mq.md#甲"];
|
||||
assert_eq!(a.inputs.len(), 1);
|
||||
assert_eq!(a.inputs[0].name, "项目");
|
||||
assert_eq!(a.events.len(), 1);
|
||||
assert_eq!(a.events[0].name, "提交");
|
||||
assert_eq!(a.scenarios.len(), 2);
|
||||
assert_eq!(a.scenarios.iter().filter(|scene| scene.initial).count(), 1);
|
||||
assert_eq!(a.scenarios[0].content.anchor, "空状态");
|
||||
assert_eq!(a.interactions.len(), 1);
|
||||
assert_eq!(a.interactions[0].next, "done");
|
||||
assert_eq!(a.dependencies.len(), 1);
|
||||
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("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 {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"a.mq.md",
|
||||
&format!("# A 组件\n\n## @knowledge 甲\n\n{sections}"),
|
||||
);
|
||||
project.write("states.mq.md", STATES);
|
||||
project
|
||||
}
|
||||
|
||||
fn scene_error(sections: &str) -> &'static str {
|
||||
let project = leaf_project(sections);
|
||||
design_code(load(&project.config("a.mq.md", "甲")).unwrap_err())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_scene_and_interaction_tables() {
|
||||
let cases: &[(&str, &str)] = &[
|
||||
(
|
||||
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n| b | [成](states.mq.md#成功) | true |\n\n### 交互\n\n| 当前 | 事件 | 下一状态 |\n| --- | --- | --- |\n| a | go | b |\n",
|
||||
"web.scene.initial",
|
||||
),
|
||||
(
|
||||
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n| a | [成](states.mq.md#成功) | false |\n",
|
||||
"web.scene.state_duplicate",
|
||||
),
|
||||
(
|
||||
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| Bad | [空](states.mq.md#空状态) | true |\n",
|
||||
"web.scene.state",
|
||||
),
|
||||
(
|
||||
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | 纯文本 | true |\n",
|
||||
"web.link.none",
|
||||
),
|
||||
(
|
||||
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [自己](#甲) | true |\n",
|
||||
"web.scene.content_component",
|
||||
),
|
||||
(
|
||||
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n| b | [成](states.mq.md#成功) | false |\n",
|
||||
"web.interaction.missing",
|
||||
),
|
||||
(
|
||||
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n| b | [成](states.mq.md#成功) | false |\n\n### 交互\n\n| 当前 | 事件 | 下一状态 |\n| --- | --- | --- |\n| b | back | a |\n",
|
||||
"web.interaction.unreachable",
|
||||
),
|
||||
(
|
||||
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n\n### 交互\n\n| 当前 | 事件 | 下一状态 |\n| --- | --- | --- |\n| a | go | missing |\n",
|
||||
"web.interaction.state",
|
||||
),
|
||||
(
|
||||
"### 交互\n\n| 当前 | 事件 | 下一状态 |\n| --- | --- | --- |\n| a | go | b |\n",
|
||||
"web.interaction.without_scene",
|
||||
),
|
||||
];
|
||||
for (sections, expected) in cases {
|
||||
assert_eq!(scene_error(sections), *expected, "case: {sections}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scenes_are_only_allowed_on_leaf_components() {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"a.mq.md",
|
||||
"# A 组件\n\n## @knowledge 甲\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | child | [B](b.mq.md#乙) | auto |\n\n### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n",
|
||||
);
|
||||
project.write("b.mq.md", "# B 组件\n\n## @knowledge 乙\n\n### 内容\n\nx\n");
|
||||
project.write("states.mq.md", STATES);
|
||||
assert_eq!(
|
||||
design_code(load(&project.config("a.mq.md", "甲")).unwrap_err()),
|
||||
"web.scene.not_leaf"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_inputs_dependencies_and_acceptance() {
|
||||
let project = leaf_project(
|
||||
"### 输入\n\n| 名称 | 类型 | 说明 |\n| --- | --- | --- |\n| x | T | d |\n| x | T | d |\n",
|
||||
);
|
||||
assert_eq!(
|
||||
design_code(load(&project.config("a.mq.md", "甲")).unwrap_err()),
|
||||
"web.input.name"
|
||||
);
|
||||
|
||||
let linked = leaf_project(
|
||||
"### 输入\n\n| 名称 | 类型 | 说明 |\n| --- | --- | --- |\n| [x](states.mq.md#空状态) | T | d |\n",
|
||||
);
|
||||
assert_eq!(
|
||||
design_code(load(&linked.config("a.mq.md", "甲")).unwrap_err()),
|
||||
"web.input.text"
|
||||
);
|
||||
|
||||
let unknown = leaf_project(
|
||||
"### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [目标](missing.mq.md#目标) | 需要 |\n",
|
||||
);
|
||||
assert_eq!(
|
||||
design_code(load(&unknown.config("a.mq.md", "甲")).unwrap_err()),
|
||||
"web.dependency.target"
|
||||
);
|
||||
|
||||
let empty = leaf_project("### 验收\n\n \n");
|
||||
assert_eq!(
|
||||
design_code(load(&empty.config("a.mq.md", "甲")).unwrap_err()),
|
||||
"web.acceptance.empty"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_dependency_cycles() {
|
||||
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| 1 | b | [B](b.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\n| 组件 | 原因 |\n| --- | --- |\n| [A](a.mq.md#甲) | 组合 |\n",
|
||||
);
|
||||
assert_eq!(
|
||||
design_code(load(&project.config("index.mq.md", "页面")).unwrap_err()),
|
||||
"web.dependency.cycle"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enforces_per_file_and_slot_limits() {
|
||||
let project = basic_project();
|
||||
let mut per_file = project.config("index.mq.md", "工作台");
|
||||
per_file.max_file_bytes = 16;
|
||||
assert_eq!(
|
||||
design_code(load(&per_file).unwrap_err()),
|
||||
"web.limit.source"
|
||||
);
|
||||
|
||||
let wide = TempProject::new();
|
||||
let mut table = String::from("| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n");
|
||||
for slot in 0..13 {
|
||||
table.push_str(&format!(
|
||||
"| 1 | s{slot} | [叶子](leaf.mq.md#叶子) | auto |\n"
|
||||
));
|
||||
}
|
||||
wide.write(
|
||||
"index.mq.md",
|
||||
&format!("# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n{table}"),
|
||||
);
|
||||
wide.write("leaf.mq.md", LEAF);
|
||||
assert_eq!(
|
||||
design_code(load(&wide.config("index.mq.md", "工作台")).unwrap_err()),
|
||||
"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