feat(PR-02): DocumentModel, Analysis v2 projection, single renderer and Live browsing

- document.rs: comrak marqdo.md.v1 parse -> DocBlock/Inline with exact UTF-8 spans
- semantic.rs: typed Analysis v2 validation (schema/profile/root_id/source_digest,
  units/functions/statements/resources/imports/references/calls/diagnostics,
  per-span UTF-8 checks with explicit view.source_span_invalid warnings)
- presentation.rs: one PresentationModel/Outline with source status matrix
- render.rs: one ReaderRenderer; sanitized GFM, statement anchors, heading mode
  badges (display-only prefix strip), source pane, docs/Live|Static link policy,
  CSP meta, no inline scripts, no raw HTML execution
- server.rs: loopback-only Live reader with Host/DNS-rebinding checks, strict
  percent decoding, project path boundary, security headers, read-only APIs
- app.rs: AppContext degradation (core missing -> prose-only, check error ->
  diagnostics + revoked semantics, protocol mismatch -> hard error)
- assets: single reader.css/reader.js + embedded SHA-256 AssetBundle, copied
  legacy logo/blossom/feather with provenance
- examples + frozen-CLI Analysis goldens + rendering/HTTP/asset/no-coupling tests
- ADR-0003 heading prefix/anchor identity; docs updated
This commit is contained in:
marqdo-view dev committed 2026-11-22 11:19:11 +08:00
1 parent 8ba20a5c67
commit 80ce564f09
47 files changed
+26127 -203

No files matched your search

+28 -5
View File
@@ -22,10 +22,33 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately.
stderr preservation, missing emit, timeout, invalid JSON) and architectural
coupling gates.
### Added (PR-02)
- Reader-oriented `DocumentModel` over the frozen `marqdo.md.v1` Comrak profile:
headings, GFM tables/task lists, blockquotes, code fences, math literals,
exact UTF-8 byte spans, source line index.
- Typed `SemanticProjection` with full Analysis v2 validation: schema/product/
profile checks, project identity, exact `source_digest`, unit/function/
statement/resource/import/reference/call/diagnostic projection and
per-span UTF-8 boundary validation with explicit warnings.
- One `PresentationModel` + one `ReaderRenderer`; Live and Export share the same
bytes and differ only by `LinkPolicy` and control availability.
- Single `assets/reader.css` + `assets/reader.js` theme (layered tokens, warm
paper, serif prose, gold/olive semantics, source pane, dialogs, responsive,
print, reduced motion) and `src/assets.rs` SHA-256 asset bundle.
- Local Live reader: loopback Host validation, strict request limits,
single-pass percent decoding, safe project paths, CSP/security headers,
read-only `/`, `/file`, `/assets/*`, `/api/document`, `/api/health`.
- `AppContext` degradation: missing core → prose-only with `CORE_UNAVAILABLE`;
failed check → diagnostics + revoked semantics; protocol mismatch → hard error.
- Examples (`welcome`, `mixed-modes`, `control-flow`, `tables-math`,
`diagnostics`) and real Analysis v2 goldens generated from the frozen CLI.
- Tests: rendering contracts, XSS/URL sanitization, Live/Export link parity,
raw HTTP server security tests, asset integrity, architectural gates.
### Known limitations
- `browse` and `export` currently return `view.unsupported`; they land in
PR-02/PR-03 (reader) and PR-05 (export).
- The single `assets/reader.css` + `assets/reader.js` theme is not present yet.
- `verify` uses a structural binding check; the typed `SemanticProjection`
replaces it in PR-02 with the same external result.
- `export` still returns `view.unsupported` (PR-05); the run control is
explicitly disabled (PR-04) and never fakes execution.
- Variables/memory/proof states remain `UNSUPPORTED`.
- Browser screenshot/geometry acceptance is scheduled for PR-06.
+3 -3
View File
@@ -25,9 +25,9 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3.
| 能力 | 状态 |
|---|---|
| 原始 Markdown 只读浏览(GFM 表/列表/引用/代码围栏/数学文本) | 计划 PR-02 |
| Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | 计划 PR-02 |
| 文档态 / 源码态切换 | 计划 PR-02 |
| 原始 Markdown 只读浏览(GFM 表/列表/引用/代码围栏/数学文本) | **已实现**(PR-02) |
| Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | **已实现**(PR-02) |
| 文档态 / 源码态切换 | **已实现**(PR-02) |
| 暖纸 Reader 视觉(单一 CSS/JS) | 计划 PR-03 |
| 用户显式触发运行 + Trace v2 事件可视化 | 计划 PR-04 |
| Live 本机安全 API | 计划 PR-05 |
+8 -1
View File
@@ -10,7 +10,7 @@ Marqdo View 是一个独立的可执行文档阅读器:以**原始 Markdown
## 当前状态
**开发中,尚未可运行。** PR-00(基线、旧 View 静态取证、视觉/状态设计基准)已完成;后续按 PR-01→PR-06 交付 Tool Protocol v1 安装闭环、只读浏览、Reader 视觉、Trace 可视化、Live/Export 安全与端到端验收。任何未完成能力都必须在 `docs/STATUS.md` 与 CHANGELOG 明确标注,不以占位功能冒充已实现。
**开发中。** PR-00(基线/取证/设计基准)、PR-01(Tool Protocol v1 + verify)、PR-02(DocumentModel/Analysis v2 只读浏览 + 单一渲染器 + 本机 Live 阅读)已完成。`marqdo view [PATH]` 当前提供本机只读浏览;`export` 与显式运行入口按 PR-05/PR-04 顺序交付。任何未完成能力都在 `docs/STATUS.md` 与 CHANGELOG 明确标注,不以占位功能冒充已实现。
## 架构约束(摘要)
@@ -43,6 +43,13 @@ cargo test --locked
cargo build --release --locked
```
本机浏览(默认只绑定 127.0.0.1,不自动执行):
```bash
MARQDO_BIN=/absolute/path/to/marqdo cargo run -- examples/welcome --no-open
# 或用已安装 bundle:marqdo view examples/welcome --no-open
```
安装到冻结 CLI(开发期):
```bash
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

+22
View File
@@ -0,0 +1,22 @@
# Third-party and reused visual assets
The three visual assets in `assets/` were selected from the legacy `cflmy/marqdo`
repository at commit `1c55baabd570e18b9da8f9057cef2f848e176690`, which is licensed
under the Apache License 2.0. They are reused as static decorative artwork only;
no legacy CSS/JS/code is copied. Source hashes were verified before copying
(see `docs/audits/legacy-render-paths.md` §6).
| File | Legacy path | SHA-256 | License |
|---|---|---|---|
| `assets/logo.svg` | `src/view/assets/logo.svg` | `52b2338468c62a7da86178ecec86cbb7ea44a996cd1bc4275ebb56f16f2244fe` | Apache-2.0 (legacy marqdo) |
| `assets/blossom.webp` | `src/view/assets/blossom.webp` | `901fd6b37ebb20d1dfc3bf4d265a063308605350fd317e41914fa35b06f46e00` | Apache-2.0 (legacy marqdo) |
| `assets/feather.webp` | `src/view/assets/feather.webp` | `fbd787174be1e8027ae4661b99f7f2cc01b824d8fc875a1d2d39cbd0c052e5de` | Apache-2.0 (legacy marqdo) |
The legacy `assets/README.md` states the blossom and feather artwork was generated
for the reader redesign (original transparent artwork), and the logo is a
project-native geometric M/book mark. No KaTeX or other vendored third-party
assets are carried into this repository.
Bundling: `src/assets.rs` embeds these files with SHA-256 digests; Live and
Export serve the exact same bytes (ADR-0002). Replacing an asset requires
updating this file and the hashes asserted by `tests/rendering/asset_tests.rs`.
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#343f22" d="M8 8v45l9-5V27l15 12 15-12v21l9 5V8L32 28z"/><path fill="#c59a55" d="m8 8 24 20L56 8 32 38z"/><path fill="#fcf9f4" d="m19 17 13 11 13-11-13 17z"/><path fill="#c59a55" d="m27 49 5-5 5 5-5 7z"/></svg>

After

Width:  |  Height:  |  Size: 282 B

+1171
View File
File diff suppressed because it is too large. Load diff
+386
View File
@@ -0,0 +1,386 @@
/* Marqdo View — the single reader interaction script.
*
* Boundaries: this file only manipulates DOM state, layout and accessibility.
* It never parses @exec/@knowledge, never invents Analysis/Trace facts and
* never executes anything. All content is rendered by the one server-side
* ReaderRenderer (RFC-VIEW-0001 §7.1, §14.3). */
(function () {
"use strict";
var reader = document.querySelector(".mq-reader");
if (!reader) return;
function $(selector, root) {
return (root || document).querySelector(selector);
}
function $$(selector, root) {
return Array.prototype.slice.call((root || document).querySelectorAll(selector));
}
var toastTimer = null;
function toast(message) {
var el = $("#mq-toast");
if (!el) return;
el.textContent = message;
el.hidden = false;
clearTimeout(toastTimer);
toastTimer = setTimeout(function () {
el.hidden = true;
}, 3800);
}
function openDialog(id) {
var dialog = document.getElementById(id);
if (!dialog) return null;
if (typeof dialog.showModal === "function") {
if (!dialog.open) dialog.showModal();
} else {
dialog.setAttribute("open", "");
}
var focusTarget = dialog.querySelector("[autofocus], input, button");
if (focusTarget) focusTarget.focus();
return dialog;
}
function closeDialog(dialog) {
if (!dialog) return;
if (typeof dialog.close === "function" && dialog.open) dialog.close();
else dialog.removeAttribute("open");
}
function closeAllDialogs() {
$$("dialog[open]").forEach(closeDialog);
}
function setMode(mode) {
reader.dataset.mode = mode === "source" ? "source" : "document";
$$("[data-action='mode-document'], [data-action='mode-source']").forEach(function (button) {
var active = button.dataset.action === "mode-" + reader.dataset.mode;
button.setAttribute("aria-current", active ? "page" : "false");
});
if (reader.dataset.mode === "source") {
var source = $(".mq-source");
if (source) source.focus({ preventScroll: true });
}
try {
var url = new URL(window.location.href);
if (reader.dataset.mode === "document") url.searchParams.delete("mode");
else url.searchParams.set("mode", "source");
window.history.replaceState(null, "", url.toString());
} catch (error) {
/* history is optional */
}
}
function gotoAnchor(target) {
if (!target) return;
var heading = document.getElementById(target);
if (heading) {
closeAllDialogs();
heading.scrollIntoView({ block: "start" });
heading.classList.add("is-focus");
setTimeout(function () {
heading.classList.remove("is-focus");
}, 1600);
return true;
}
return false;
}
function gotoSourceLine(line) {
var row = document.querySelector(".mq-source-lines li[data-line='" + line + "']");
if (!row) return false;
closeAllDialogs();
setMode("source");
row.scrollIntoView({ block: "center" });
row.classList.add("is-focus");
setTimeout(function () {
row.classList.remove("is-focus");
}, 1600);
return true;
}
function showFunctions() {
var items = $$(".mq-functions li");
var body = $("#mq-functions-body");
if (!body) return;
body.textContent = "";
if (!items.length) {
var empty = document.createElement("p");
empty.textContent = "本文没有 Analysis 可见的 @exec 函数。";
body.appendChild(empty);
} else {
var list = document.createElement("ul");
list.className = "mq-annotation-list";
items.forEach(function (item) {
var clone = item.cloneNode(true);
list.appendChild(clone);
});
body.appendChild(list);
}
openDialog("mq-dialog-functions");
}
function showSearch() {
openDialog("mq-dialog-search");
var input = $("#mq-search-input");
if (input) {
input.value = "";
input.focus();
renderSearch("");
}
}
function collectSearchNodes() {
var nodes = [];
var walker = document.createTreeWalker(
$(".mq-document") || reader,
NodeFilter.SHOW_TEXT,
null
);
while (walker.nextNode()) {
var text = walker.currentNode;
if (!text.nodeValue || !text.nodeValue.trim()) continue;
if (text.parentElement && text.parentElement.closest("script, style")) continue;
nodes.push(text);
}
return nodes;
}
var searchNodes = null;
function renderSearch(query) {
var results = $("#mq-search-results");
if (!results) return;
results.textContent = "";
var needle = query.trim().toLowerCase();
if (needle.length < 2) {
var hint = document.createElement("li");
hint.textContent = "输入至少两个字符以搜索当前文档正文。";
hint.className = "mq-search-hint";
results.appendChild(hint);
return;
}
if (!searchNodes) searchNodes = collectSearchNodes();
var shown = 0;
searchNodes.forEach(function (node) {
if (shown >= 40) return;
var value = node.nodeValue;
var index = value.toLowerCase().indexOf(needle);
if (index < 0) return;
var start = Math.max(0, index - 28);
var end = Math.min(value.length, index + needle.length + 34);
var li = document.createElement("li");
var button = document.createElement("button");
button.type = "button";
var before = document.createTextNode(
(start > 0 ? "…" : "") + value.slice(start, index)
);
var mark = document.createElement("mark");
mark.textContent = value.slice(index, index + needle.length);
var after = document.createTextNode(
value.slice(index + needle.length, end) + (end < value.length ? "…" : "")
);
button.appendChild(before);
button.appendChild(mark);
button.appendChild(after);
button.addEventListener("click", function () {
closeAllDialogs();
var el = node.parentElement;
if (el) {
el.scrollIntoView({ block: "center" });
el.classList.add("is-focus");
setTimeout(function () {
el.classList.remove("is-focus");
}, 1600);
}
});
li.appendChild(button);
results.appendChild(li);
shown += 1;
});
if (!shown) {
var none = document.createElement("li");
none.textContent = "没有匹配的正文文本。";
none.className = "mq-search-hint";
results.appendChild(none);
}
}
function toggleAnnotationVisibility() {
var off = reader.dataset.annotations === "off";
reader.dataset.annotations = off ? "on" : "off";
toast(off ? "已显示语义标注" : "已隐藏语义标注");
closeAllDialogs();
}
function cycleTextSize() {
var order = ["normal", "large", "small"];
var current = reader.dataset.size || "normal";
var next = order[(order.indexOf(current) + 1) % order.length];
reader.dataset.size = next;
toast("正文字号:" + (next === "large" ? "大" : next === "small" ? "小" : "标准"));
}
function showUnsupported(what, why) {
var body = $("#mq-unsupported-body");
if (body) {
body.textContent = "";
var title = document.createElement("p");
title.textContent = what + ":当前版本不支持。";
var reason = document.createElement("p");
reason.className = "mq-colophon";
reason.textContent = why;
body.appendChild(title);
body.appendChild(reason);
}
openDialog("mq-dialog-unsupported");
}
function handleAction(action) {
switch (action) {
case "mode-document":
setMode("document");
break;
case "mode-source":
setMode("source");
break;
case "search":
showSearch();
break;
case "functions":
showFunctions();
break;
case "reload":
window.location.reload();
break;
case "settings":
openDialog("mq-dialog-settings");
break;
case "more":
openDialog("mq-dialog-more");
break;
case "close-dialog":
closeAllDialogs();
break;
case "print":
closeAllDialogs();
window.print();
break;
case "size":
cycleTextSize();
break;
case "annotations":
toggleAnnotationVisibility();
break;
case "variables":
showUnsupported(
"变量快照",
"Trace v2 不提供逐语句赋值后的实际值;View 只能展示 Analysis 中的静态参数与赋值目标,绝不猜测运行时数据。"
);
break;
case "memory":
showUnsupported(
"内存快照",
"当前公开协议没有内存观测通道;该能力需等待未来独立、受权限审计的调试协议。"
);
break;
case "about":
openDialog("mq-dialog-about");
break;
case "run":
// Until the explicit-run flow is implemented, never pretend to run.
showUnsupported(
"运行文档",
"首版运行入口需要显式的风险评估与 CSRF 会话确认;在实现前该按钮不会执行任何文档。"
);
break;
case "clear":
var panel = $("#mq-run-panel");
if (panel) panel.hidden = true;
toast("已清理本地展示状态(源文件与缓存未修改)");
break;
default:
break;
}
}
document.addEventListener("click", function (event) {
var trigger = event.target.closest ? event.target.closest("[data-action]") : null;
if (!trigger) return;
event.preventDefault();
handleAction(trigger.dataset.action);
});
document.addEventListener("click", function (event) {
var link = event.target.closest ? event.target.closest("[data-goto-anchor]") : null;
if (link) {
event.preventDefault();
gotoAnchor(link.dataset.gotoAnchor);
return;
}
var lineLink = event.target.closest ? event.target.closest("[data-goto-line]") : null;
if (lineLink) {
event.preventDefault();
var line = parseInt(lineLink.dataset.gotoLine, 10);
if (!isNaN(line)) gotoSourceLine(line);
}
});
document.addEventListener("input", function (event) {
if (event.target && event.target.id === "mq-search-input") {
renderSearch(event.target.value);
}
});
document.addEventListener("keydown", function (event) {
var isMac = /Mac|iPhone|iPad/.test(navigator.platform || "");
var modifier = isMac ? event.metaKey : event.ctrlKey;
if (modifier && (event.key === "k" || event.key === "K")) {
event.preventDefault();
showSearch();
return;
}
if (event.key === "Escape") {
closeAllDialogs();
}
});
document.addEventListener("toggle", function (event) {
if (event.target && event.target.classList.contains("mq-diagnostics")) {
try {
window.localStorage.setItem("marqdo.view.diagnostics", event.target.open ? "1" : "0");
} catch (error) {
/* storage is optional */
}
}
}, true);
// Restore a URL-selected mode, then honour the persisted diagnostics state.
try {
var params = new URLSearchParams(window.location.search);
if (params.get("mode") === "source") setMode("source");
else setMode("document");
var diagnosticsState = window.localStorage.getItem("marqdo.view.diagnostics");
if (diagnosticsState === "1") {
$$(".mq-diagnostics").forEach(function (details) {
details.open = true;
});
}
} catch (error) {
setMode("document");
}
// Keep dock buttons visible above the last line on small screens.
function syncDockInset() {
var dock = $(".mq-dock");
if (!dock) return;
var height = dock.getBoundingClientRect().height + 36;
reader.style.setProperty("--mq-dock-h", Math.round(height) + "px");
}
if (typeof ResizeObserver !== "undefined") {
var dock = $(".mq-dock");
if (dock) new ResizeObserver(syncDockInset).observe(dock);
}
window.addEventListener("resize", syncDockInset);
syncDockInset();
})();
@@ -0,0 +1,27 @@
# ADR-0003:显示层标题前缀剥离与文档内锚点身份
- 状态:Accepted
- 日期:2026-11-22
- 关联:RFC-VIEW-0001 §5.2、§8.2、§8.3;PR-02
## 背景
`@exec` / `@knowledge` 是标题语义声明,但 Markdown 标题的**显示文本**不应把声明前缀当作正文主标题重复展示。与此同时,语义标注必须能稳定指向源码位置,而且不能在标题重名时产生重复 DOM id。Analysis v2 公开字段中:
- `units[]` 没有单独的“本标题的 mode”字段(RFC §4.3 已警告不得把 `kind=section` 当成 Exec/Knowledge);
- `functions[].heading_span` 与 `units[].span` 对 ATX 标题精确对应,可作为锚点来源;
- 继承模式无法从公开 JSON 直接读出。
## 决策
1. **标题前缀只在显示层剥离**:仅当标题文本以精确的 `@exec ` 或 `@knowledge ` 开头,且剥离后的空白折叠结果等于 Analysis `units[].name` 时,才视为合法声明并剥离;同时输出 `mq-mode-badge`。`@Exec`、拼写变体、`**@exec**` 等一律原样显示(Core 会给出诊断)。Source 态永远显示原始字节,因此剥离是可逆的显示规则,不是改写源文件。
2. **不猜测继承模式**:没有显式声明前缀的 H3–H6 不渲染 EXEC/KNOWLEDGE 徽标,`data-semantic="document"`;H2 function 由 `functions[]` 精确映射为 `exec`,H2 knowledge 由 `units[].kind=knowledge` 映射为 `knowledge`。
3. **锚点 id 来自源码 span**:`id="mq-h-<start-hex>-<end-hex>"`,由标题自身的 UTF-8 半开区间派生;函数大纲使用同一条 `heading_span`,保证“函数列表跳转”与正文标题命中同一个 id。禁止用标题文本、序号或随机数生成 id(重名会跳错)。
4. **语义装饰锚点 id** 使用 RFC §8.3 的 `sha256(module_id + "\0" + start + ":" + end + ":" + kind)[0..16]`;它只在本页 DOM 内有效,不跨编辑/跨运行复用。
5. 任何无法通过 `SourceIndex` 验证的 span(越界、非 UTF-8 边界)直接丢弃该条装饰并产生 `view.source_span_invalid` 警告,绝不把它吸附到相邻文字。
## 后果
- 同页多个 H2/H3 永远得到不同 id;`tests/rendering.rs::semantic_annotations_come_from_analysis_and_are_unique` 断言唯一性。
- Setext 标题没有合法前缀声明,会被原样显示并沿用自身 span 锚点;如果未来需要更精确的继承模式标注,必须通过新的公开协议字段实现,不能在 JS/CSS 里猜。
- 标题显示与源码态自动保持一致;无需额外“复制原文”逻辑。
+6 -3
View File
@@ -22,8 +22,8 @@
|---|---|---|
| PR-00 基线与旧 View 取证 | **完成** | `docs/audits/legacy-render-paths.md`、`docs/design/visual-tokens.md`、`docs/design/state-matrix.md`、ADR-0001/0002 |
| PR-01 Tool v1 安装闭环 | **完成** | `tool.json`、`tools/package.sh`、`tools/install-smoke.sh`、`tests/core_contract.rs`、`tests/no_coupling.rs` |
| PR-02 DocumentModel + Analysis v2 浏览 | 未开始 | — |
| PR-03 Reader 视觉重建 | 未开始 | — |
| PR-02 DocumentModel + Analysis v2 浏览 | **完成** | `src/document.rs`、`src/semantic.rs`、`src/presentation.rs`、`src/render.rs`、`src/server.rs`、`tests/rendering.rs`、`tests/http_live.rs`、`tests/golden/analysis-v2/`(冻结 CLI 生成) |
| PR-03 Reader 视觉重建 | 进行中(基础主题已就绪) | `assets/reader.css`/`assets/reader.js` 单一入口,`tests/asset_integrity.rs`;完整欢迎页/响应式截图待补 |
| PR-04 Trace v2 运行可视化 | 未开始 | — |
| PR-05 Live 安全 + 静态导出 | 未开始 | — |
| PR-06 冻结 CLI 端到端验收 | 未开始 | — |
@@ -31,7 +31,10 @@
## 证据与限制
- 旧 View 运行时状态:`LEGACY_RUNTIME_UNVERIFIED`(旧仓库无预编译产物,且任务禁止修改/编译旧仓库;只做只读静态审计)。
- PR-01 起 `marqdo view --help/--version/verify` 由本程序提供;`browse`/`export` 仍返回 `view.unsupported`(PR-02/PR-05 落地)。
- PR-01 起 `marqdo view --help/--version/verify` 由本程序提供;PR-02 起 `marqdo view [PATH]` 提供本机只读浏览。
- `export` 仍返回 `view.unsupported`(PR-05 落地);运行入口仍显式“未启用”(PR-04)。
- 冻结 CLI 安装烟测通过前不得声称 Tool v1 闭环可用;证据由 `tools/install-smoke.sh` 生成。
- PR-02 的 Analysis golden 全部由冻结 CLI `check --emit` 生成(见 `tests/golden/README.md`);`examples/diagnostics` 故意 check 失败且没有 golden。
- 已知限制:运行/变量值/内存/证明状态仍不可用且标为 UNSUPPORTED;`export` 未实现;浏览器截图验收在 PR-06。
- 已核对旧视觉资产许可(旧仓库 Apache-2.0):logo/blossom/feather 可复用,KaTeX 不引入。
- 已知非目标:变量运行值、内存快照、调试器、Prove/Knowledge/Lint 引擎(均标 `UNSUPPORTED`)。
+27
View File
@@ -0,0 +1,27 @@
# @knowledge 控制流演示
下面的函数没有任何必需参数,因此可以在 `pure` 模式下显式运行并产生真实 Trace。
# @exec 演示
## @exec main
`x = 0`
**while x < 3**
**if x > 1**
**print(x)**
**else**
**print(0)**
**end**
**x = x + 1**
**end**
`return 3`
+3
View File
@@ -0,0 +1,3 @@
project:
name: control-flow
version: 0.1.0
+11
View File
@@ -0,0 +1,11 @@
# @knowledge 诊断演示
这份源码故意不合法:`if` 没有在同一个标题段落内闭合,Core `check` 会给出诊断。
# @exec 演示
## @exec main
**if x > 0**
`return 1`
+3
View File
@@ -0,0 +1,3 @@
project:
name: diagnostics-demo
version: 0.1.0
+31
View File
@@ -0,0 +1,31 @@
# @knowledge 计算笔记
这是一份关于简单运算的知识说明。**此处加粗是知识内容,不执行。**
## @knowledge 算法说明
下面描述算法的含义和适用范围;此处的 `n` 是惰性正文。
# @exec 演示
## @exec main
`params(n: Int)`
### @knowledge 用法
调用方提供整数 `n`。这一小节不应该执行任何语句。
### @exec 计算
**if n > 0**
`result = n * 2`
*return result*
**else**
`return 0`
**end**
+3
View File
@@ -0,0 +1,3 @@
project:
name: mixed-modes
version: 0.1.0
+21
View File
@@ -0,0 +1,21 @@
# @knowledge 表格、公式与惰性资源
| 名称 | 值 | 说明 |
| --- | ---: | --- |
| 甲 | 1 | 第一行 |
| 乙 | 2 | 第二行 |
行内公式 $E = mc^2$;块公式:
$$
\sum_{i=1}^{n} i = \frac{n(n+1)}{2}
$$
```python
print("代码围栏永远是惰性资源")
```
- [x] 任务列表可读
- [ ] 不会触发任何执行
外部链接:[Marqdo CLI](https://github.com/cflmy/marqdo-cli)。
+3
View File
@@ -0,0 +1,3 @@
project:
name: tables-math
version: 0.1.0
+15
View File
@@ -0,0 +1,15 @@
# @knowledge 欢迎来到 Marqdo
Marqdo 把 Markdown 当作可执行文档的语言:标题声明 `@exec` / `@knowledge` 模式,
强调、斜体与行内代码是**等价的单语句载体**,而 `if` / `else` / `while` / `end` /
`return` 决定真正的操作。
| 阅读态 | 内容 | 是否执行 |
| --- | --- | --- |
| 文档 | 原始 Markdown 排版 | 否 |
| 源码 | 逐行原文,包含全部标记 | 否 |
| 运行 | 用户显式确认后才出现 | 是(需要确认) |
继续阅读:[语法演示](./guide.mq.md)。
> 这份欢迎页只是 `view.json` 显式指定的站点首页,普通 `welcome` 文件名不会自动变成 Hero。
+17
View File
@@ -0,0 +1,17 @@
# @knowledge 阅读指南
## @knowledge 三种视图
文档态是默认视图;源码态保留原文字节;运行态只在用户点击“运行”并确认后出现。
## @knowledge 公式与代码
行内公式 $a^2 + b^2 = c^2$ 是惰性资源;围栏代码同样从不自动执行:
```rust
fn main() {
println!("这段代码只是文档内容");
}
```
回到[欢迎页](./00-welcome.mq.md)。
+3
View File
@@ -0,0 +1,3 @@
project:
name: welcome-demo
version: 0.1.0
+7
View File
@@ -0,0 +1,7 @@
{
"schema": "marqdo.view-config",
"schema_version": 1,
"welcome": "./00-welcome.mq.md",
"site_title": "Marqdo",
"theme": "botanical"
}
+263 -142
View File
@@ -1,16 +1,157 @@
//! Application layer: turns parsed commands into use cases.
//!
//! No HTML is built here; no Markdown is parsed here. Browse uses the single
//! renderer (PR-02+), verify only checks bindings, export only writes static
//! files through the same renderer (PR-05).
//! No HTML is built here and no Markdown semantics are decided here. Browse and
//! (later) Export call the same `load` + one `ReaderRenderer`.
use crate::cli::{ExportArgs, RuntimeOpts, VerifyArgs};
use crate::core_client::{CheckOptions, CoreClient};
use crate::core_client::{CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic};
use crate::document::{DocumentIdentity, DocumentModel};
use crate::error::{ViewError, ViewResult};
use crate::project::Project;
use crate::source_map::sha256_hex;
use crate::presentation::{self, BuildInput, Navigation, PresentationModel, SourceStatus};
use crate::project::{Project, SafeRelativePath, ViewConfig};
use crate::semantic::{self, CoreDiagnostic};
use crate::version;
/// Process-wide context for one browsed project: root, optional site config and
/// an optional negotiated frozen core. A missing core degrades to prose only;
/// an incompatible protocol is a hard error (RFC §4).
pub struct AppContext {
project: Project,
config: ViewConfig,
core: Option<CoreClient>,
core_version: Option<String>,
core_note: Option<String>,
}
impl AppContext {
pub fn open(path: &std::path::Path, marqdo_bin: Option<&std::path::Path>) -> ViewResult<Self> {
let project = Project::open(path)?;
let config = ViewConfig::load(project.root())?;
let (core, core_version, core_note) = match CoreClient::from_env(marqdo_bin) {
Ok(client) => match client.negotiate() {
Ok(version) => (Some(client), Some(version.version.to_string()), None),
Err(err) if err.code() == "view.protocol_incompatible" => return Err(err),
Err(err) => (None, None, Some(generic_core_note(&err))),
},
Err(err) if err.code() == "view.core_missing" => {
(None, None, Some(generic_core_note(&err)))
}
Err(err) => return Err(err),
};
Ok(Self {
project,
config,
core,
core_version,
core_note,
})
}
pub fn project(&self) -> &Project {
&self.project
}
pub fn config(&self) -> &ViewConfig {
&self.config
}
pub fn core(&self) -> Option<&CoreClient> {
self.core.as_ref()
}
pub fn core_version(&self) -> Option<&str> {
self.core_version.as_deref()
}
pub fn core_note(&self) -> Option<&str> {
self.core_note.as_deref()
}
/// Read + parse + (optionally) check one document into the one presentation
/// model. Never executes the document.
pub fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
let source_bytes = self.project.read_source(relative)?;
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
detail: format!("{relative} is not valid UTF-8: {err}"),
})?;
let document = DocumentModel::parse(source, DocumentIdentity::placeholder(relative));
let navigation = Navigation::from_project(&self.project, &self.config, relative);
let mut status = SourceStatus::CoreUnavailable;
let mut status_note = self.core_note.clone();
let mut diagnostics = Vec::new();
let mut verified = None;
if let Some(client) = &self.core {
match client.check(&self.project, relative, &CheckOptions::default())? {
CheckResponse {
success: false,
diagnostics: raw_diagnostics,
exit_code,
..
} => {
status = SourceStatus::CoreError;
status_note = Some(format!(
"Core 检查失败(exit {exit_code}):语义标注已撤销,正文仍可阅读。"
));
diagnostics = raw_diagnostics
.iter()
.map(|diagnostic| diagnostic_to_view(diagnostic, relative))
.collect();
}
CheckResponse {
success: true,
analysis: Some(check),
..
} => match semantic::verify_analysis(
&check.analysis_bytes,
&document.source,
&document.source_index,
relative.as_str(),
) {
Ok(verified_analysis) => {
status = SourceStatus::StaticOk;
status_note = None;
verified = Some(verified_analysis);
}
Err(err) if err.code() == "view.source_mismatch" => {
status = SourceStatus::SourceMismatch;
status_note = Some(
"当前源码字节与 Analysis 的 source_digest 不一致,语义标注已禁用。"
.to_string(),
);
}
Err(err) if err.code() == "view.protocol_incompatible" => {
return Err(err);
}
Err(err) => {
status = SourceStatus::CoreError;
status_note = Some(generic_core_note(&err));
}
},
CheckResponse {
success: true,
analysis: None,
..
} => {
status = SourceStatus::CoreError;
status_note = Some("Core 声称检查成功但没有产出 Analysis。".to_string());
}
}
}
Ok(presentation::build(BuildInput {
document,
analysis: verified.as_ref(),
status,
status_note,
diagnostics,
navigation,
core_version: self.core_version.clone(),
}))
}
}
pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
let path = args
.path
@@ -20,14 +161,14 @@ pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
let project = Project::open(&path)?;
let entry = project.entry().relative.clone();
let source_bytes = project.read_source(&entry)?;
let source_text = String::from_utf8(source_bytes.clone()).map_err(|err| ViewError::Io {
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
detail: format!("{entry} is not valid UTF-8: {err}"),
})?;
let _ = source_text;
let source_index = crate::source_map::SourceIndex::new(&source);
let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?;
let core_version = client.negotiate()?;
let check = client.check(
let response = client.check(
&project,
&entry,
&CheckOptions {
@@ -35,12 +176,51 @@ pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
timeout: None,
},
)?;
let analysis: serde_json::Value =
serde_json::from_slice(&check.analysis_bytes).map_err(|err| ViewError::AnalysisFailed {
detail: format!("emitted Analysis is not JSON: {err}"),
})?;
let summary = validate_static_binding(&analysis, entry.as_str(), &source_bytes)?;
let check = match response {
CheckResponse {
success: false,
diagnostics,
exit_code,
..
} => {
let first = diagnostics
.first()
.map(|diagnostic| {
format!(
"{}: {}",
if diagnostic.code.is_empty() {
"diagnostic"
} else {
&diagnostic.code
},
diagnostic.message
)
})
.unwrap_or_else(|| "no diagnostic detail".to_string());
return Err(ViewError::AnalysisFailed {
detail: format!(
"`marqdo check` failed with exit code {exit_code} ({} diagnostic(s)); first: {first}",
diagnostics.len()
),
});
}
CheckResponse {
analysis: Some(check),
..
} => check,
CheckResponse { analysis: None, .. } => {
return Err(ViewError::AnalysisFailed {
detail: "`marqdo check` succeeded but emitted no Analysis".to_string(),
})
}
};
let verified = semantic::verify_analysis(
&check.analysis_bytes,
&source,
&source_index,
entry.as_str(),
)?;
let projection = &verified.projection;
if args.json {
let doc = serde_json::json!({
@@ -53,17 +233,24 @@ pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
},
"analysis": {
"schema": "marqdo.analysis",
"schema_version": 2,
"digest": check.analysis_digest,
"producer_version": summary.producer_version,
"schema_version": version::ANALYSIS_PROTOCOL,
"digest": projection.analysis_digest,
"producer_version": projection.producer_version,
"markdown_profile": projection.markdown_profile,
"functions": projection.functions.len(),
"units": projection.units.len(),
"diagnostics": projection.diagnostics.len(),
},
"project": {
"root_id": summary.root_id,
"identity_kind": summary.identity_kind,
"root_id": projection.project_root_id,
"identity_kind": projection.identity_kind,
"lock_digest": projection.lock_digest,
"stdlib_version": projection.stdlib_version,
},
"document": {
"relative_path": entry.as_str(),
"source_digest": summary.source_digest,
"module_id": projection.module_id,
"source_digest": projection.source_digest,
"source_digest_matches": true,
},
"result": "PASS",
@@ -80,11 +267,16 @@ pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
core_version.version,
version::PRODUCT_RANGE
);
println!("project: {} ({})", summary.root_id, summary.identity_kind);
println!("document: {}", entry);
println!(
"analysis: schema=marqdo.analysis v2 modules={} digest={}",
summary.module_count, check.analysis_digest
"project: {} ({})",
projection.project_root_id, projection.identity_kind
);
println!("document: {entry}");
println!(
"analysis: schema=marqdo.analysis v2 modules={} functions={} digest={}",
projection.modules.len(),
projection.functions.len(),
projection.analysis_digest
);
println!("source digest: match");
println!("result: PASS (static only; document not executed)");
@@ -92,130 +284,59 @@ pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
Ok(0)
}
pub fn browse(opts: &RuntimeOpts) -> ViewResult<i32> {
let path = opts
.path
.clone()
.unwrap_or_else(|| std::path::PathBuf::from("."));
let context = AppContext::open(&path, opts.marqdo_bin.as_deref())?;
crate::server::serve(context, opts)
}
pub fn export(_opts: &RuntimeOpts, _args: &ExportArgs) -> ViewResult<i32> {
Err(ViewError::Unsupported {
detail: "static export lands with PR-05; this build teaches Tool Protocol and statics only"
detail: "static export lands with PR-05; browse and verify are available in this build"
.to_string(),
})
}
pub fn browse(_opts: &RuntimeOpts) -> ViewResult<i32> {
Err(ViewError::Unsupported {
detail: "the Live reader lands with PR-02/PR-03; this build teaches Tool Protocol and statics only"
.to_string(),
})
fn generic_core_note(err: &ViewError) -> String {
match err.code() {
"view.core_missing" => {
"未找到可用的冻结核心(MARQDO_BIN);当前为无语义标注的纯 Markdown 阅读模式。"
.to_string()
}
"view.analysis_failed" => "Core 检查失败;语义标注已撤销,正文仍可阅读。".to_string(),
other => format!("{other}:语义标注不可用,正文仍可阅读。"),
}
}
struct BindingSummary {
root_id: String,
identity_kind: String,
producer_version: String,
module_count: usize,
source_digest: String,
}
/// Structural binding checks that do not need the full typed projection yet
/// (the typed `SemanticProjection` replaces this in PR-02 without changing the
/// externally visible `verify` result).
fn validate_static_binding(
analysis: &serde_json::Value,
relative_path: &str,
source_bytes: &[u8],
) -> ViewResult<BindingSummary> {
let schema = analysis
.get("schema")
.and_then(|v| v.as_str())
.unwrap_or("");
if schema != "marqdo.analysis" {
return Err(ViewError::ProtocolIncompatible {
detail: format!("unexpected Analysis schema {schema:?}"),
});
fn diagnostic_to_view(
diagnostic: &RawCheckDiagnostic,
relative: &SafeRelativePath,
) -> CoreDiagnostic {
let belongs_to_entry = diagnostic
.module
.as_deref()
.map(|module| module.ends_with(relative.as_str()))
.unwrap_or(true);
CoreDiagnostic {
module: diagnostic.module.clone(),
relative_path: if belongs_to_entry {
Some(relative.as_str().to_string())
} else {
None
},
span: None,
line: diagnostic.line,
column: diagnostic.column,
severity: if diagnostic.severity.is_empty() {
"error".to_string()
} else {
diagnostic.severity.clone()
},
code: diagnostic.code.clone(),
message: diagnostic.message.clone(),
hints: diagnostic.hints.clone(),
}
match analysis.get("schema_version").and_then(|v| v.as_u64()) {
Some(2) => {}
other => {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis schema_version {other:?} is not supported (View implements v{})",
version::ANALYSIS_PROTOCOL
),
})
}
}
let producer = analysis
.get("producer")
.ok_or_else(|| ViewError::AnalysisFailed {
detail: "Analysis is missing producer".to_string(),
})?;
let producer_version = producer
.get("version")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let markdown_profile = producer
.get("markdown_profile")
.and_then(|v| v.as_str())
.unwrap_or("");
if markdown_profile != "marqdo.md.v1" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unexpected Markdown profile {markdown_profile:?}; this View targets marqdo.md.v1"
),
});
}
let project = analysis
.get("project")
.ok_or_else(|| ViewError::AnalysisFailed {
detail: "Analysis is missing project".to_string(),
})?;
let root_id = project
.get("root_id")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if root_id.is_empty() {
return Err(ViewError::AnalysisFailed {
detail: "Analysis project.root_id is empty".to_string(),
});
}
let identity_kind = project
.get("identity_kind")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let modules = analysis
.get("modules")
.and_then(|v| v.as_array())
.ok_or_else(|| ViewError::AnalysisFailed {
detail: "Analysis is missing modules[]".to_string(),
})?;
let expected_digest = sha256_hex(source_bytes);
let mut matches = 0usize;
for module in modules {
if module.get("relative_path").and_then(|v| v.as_str()) == Some(relative_path) {
matches += 1;
let digest = module
.get("source_digest")
.and_then(|v| v.as_str())
.unwrap_or("");
if digest != expected_digest {
return Err(ViewError::SourceMismatch {
expected: digest.to_string(),
actual: expected_digest,
});
}
}
}
if matches == 0 {
return Err(ViewError::AnalysisFailed {
detail: format!("Analysis has no module for {relative_path}"),
});
}
Ok(BindingSummary {
root_id,
identity_kind,
producer_version,
module_count: modules.len(),
source_digest: expected_digest,
})
}
+238
View File
@@ -0,0 +1,238 @@
//! The single embedded asset bundle.
//!
//! Live serving and static export both read these exact bytes (ADR-0002). Every
//! asset carries its SHA-256; browser URLs use a hash prefix so a changed asset
//! can never be confused with a cached older one.
use crate::source_map::sha256_hex;
use std::collections::HashMap;
use std::sync::OnceLock;
#[derive(Clone)]
pub struct Asset {
pub name: &'static str,
pub extension: &'static str,
pub mime: &'static str,
pub bytes: &'static [u8],
/// Lowercase hex SHA-256 of `bytes`.
pub sha256: String,
}
impl Asset {
/// Hashed file name, e.g. `reader.1a2b3c4d5e6f7788.css`.
pub fn hashed_name(&self) -> String {
format!("{}.{}.{}", self.name, &self.sha256[..16], self.extension)
}
pub fn data_uri(&self) -> String {
format!("data:{};base64,{}", self.mime, base64(self.bytes))
}
}
pub struct AssetBundle {
assets: Vec<Asset>,
by_hashed_name: HashMap<String, usize>,
/// CSS with the two image placeholders replaced by data URIs, so there is
/// still exactly one stylesheet and no extra network request.
css_with_images: String,
css_served_sha256: String,
}
impl AssetBundle {
fn new() -> Self {
let assets = vec![
asset(
"reader",
"css",
"text/css; charset=utf-8",
include_bytes!("../assets/reader.css"),
),
asset(
"reader",
"js",
"text/javascript; charset=utf-8",
include_bytes!("../assets/reader.js"),
),
asset(
"logo",
"svg",
"image/svg+xml",
include_bytes!("../assets/logo.svg"),
),
asset(
"blossom",
"webp",
"image/webp",
include_bytes!("../assets/blossom.webp"),
),
asset(
"feather",
"webp",
"image/webp",
include_bytes!("../assets/feather.webp"),
),
];
let mut by_hashed_name = HashMap::new();
for (index, asset) in assets.iter().enumerate() {
by_hashed_name.insert(asset.hashed_name(), index);
}
let css_text = std::str::from_utf8(assets[0].bytes).expect("reader.css is UTF-8");
let css_with_images = css_text
.replace("__BLOSSOM__", &assets[3].data_uri())
.replace("__FEATHER__", &assets[4].data_uri());
let css_served_sha256 = sha256_hex(css_with_images.as_bytes());
Self {
assets,
by_hashed_name,
css_with_images,
css_served_sha256,
}
}
pub fn get() -> &'static AssetBundle {
static BUNDLE: OnceLock<AssetBundle> = OnceLock::new();
BUNDLE.get_or_init(AssetBundle::new)
}
pub fn all(&self) -> &[Asset] {
&self.assets
}
pub fn css(&self) -> &Asset {
&self.assets[0]
}
pub fn js(&self) -> &Asset {
&self.assets[1]
}
pub fn logo(&self) -> &Asset {
&self.assets[2]
}
pub fn by_path(&self, hashed_name: &str) -> Option<&Asset> {
self.by_hashed_name
.get(hashed_name)
.map(|index| &self.assets[*index])
}
pub fn css_bytes(&self) -> &[u8] {
self.css_with_images.as_bytes()
}
/// SHA-256 of the served CSS (after image substitution).
pub fn css_served_sha256(&self) -> &str {
&self.css_served_sha256
}
pub fn hashed_css_name(&self) -> String {
format!("reader.{}.css", &self.css_served_sha256[..16])
}
pub fn hashed_js_name(&self) -> String {
self.js().hashed_name()
}
}
fn asset(
name: &'static str,
extension: &'static str,
mime: &'static str,
bytes: &'static [u8],
) -> Asset {
Asset {
name,
extension,
mime,
bytes,
sha256: sha256_hex(bytes),
}
}
/// Minimal standard base64 (RFC 4648) encoder for data URIs.
fn base64(bytes: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
let triple = (b0 << 16) | (b1 << 8) | b2;
out.push(TABLE[(triple >> 18) as usize & 0x3f] as char);
out.push(TABLE[(triple >> 12) as usize & 0x3f] as char);
out.push(if chunk.len() > 1 {
TABLE[(triple >> 6) as usize & 0x3f] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
TABLE[triple as usize & 0x3f] as char
} else {
'='
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bundle_digests_match_source_files() {
let bundle = AssetBundle::get();
assert_eq!(
bundle.css().sha256,
sha256_hex(include_bytes!("../assets/reader.css"))
);
assert_eq!(
bundle.js().sha256,
sha256_hex(include_bytes!("../assets/reader.js"))
);
assert_eq!(
bundle.logo().sha256,
sha256_hex(include_bytes!("../assets/logo.svg"))
);
assert_eq!(bundle.assets[3].sha256.len(), 64);
assert!(bundle.by_path(&bundle.logo().hashed_name()).is_some());
assert!(bundle.by_path("missing.css").is_none());
// Exactly one theme and one script entry.
let css_count = bundle
.all()
.iter()
.filter(|asset| asset.extension == "css")
.count();
let js_count = bundle
.all()
.iter()
.filter(|asset| asset.extension == "js")
.count();
assert_eq!(css_count, 1);
assert_eq!(js_count, 1);
}
#[test]
fn css_substitutes_images_and_keeps_one_asset() {
let bundle = AssetBundle::get();
let css = std::str::from_utf8(bundle.css_bytes()).unwrap();
assert!(!css.contains("__BLOSSOM__"));
assert!(!css.contains("__FEATHER__"));
assert!(css.contains("data:image/webp;base64,"));
assert!(bundle.hashed_css_name().starts_with("reader."));
assert_eq!(
bundle.hashed_css_name().len(),
"reader.".len() + 16 + ".css".len()
);
}
#[test]
fn base64_matches_known_vectors() {
assert_eq!(base64(b""), "");
assert_eq!(base64(b"f"), "Zg==");
assert_eq!(base64(b"fo"), "Zm8=");
assert_eq!(base64(b"foo"), "Zm9v");
assert_eq!(base64(b"foob"), "Zm9vYg==");
assert_eq!(base64(b"fooba"), "Zm9vYmE=");
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
}
}
+74 -17
View File
@@ -106,6 +106,37 @@ pub struct CheckOutput {
pub stderr: String,
}
/// One compile diagnostic from `check --json`, normalized so no absolute
/// machine path can leak into pages, exports or logs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawCheckDiagnostic {
#[serde(default)]
pub code: String,
#[serde(default)]
pub severity: String,
#[serde(default)]
pub message: String,
#[serde(default)]
pub line: Option<u64>,
#[serde(default)]
pub column: Option<u64>,
#[serde(default)]
pub module: Option<String>,
#[serde(default)]
pub hints: Vec<String>,
}
/// Result of one `check` invocation. A failed check is **not** an I/O error:
/// the prose stays readable and diagnostics must be shown (RFC §12.3).
#[derive(Debug)]
pub struct CheckResponse {
pub success: bool,
pub analysis: Option<CheckOutput>,
pub diagnostics: Vec<RawCheckDiagnostic>,
pub exit_code: i32,
pub stderr: String,
}
#[derive(Debug)]
pub struct RunOutput {
/// Exactly one JSON document emitted on stdout by the Core.
@@ -267,19 +298,20 @@ impl CoreClient {
Ok(version)
}
/// `check --emit`; on success returns the exact Analysis v2 bytes.
/// `check --json --emit`. On success the exact Analysis v2 bytes are
/// returned; on failure the structured diagnostics are returned without
/// any absolute path. Only spawn/timeout/IO failures are hard errors.
pub fn check(
&self,
project: &Project,
relative: &SafeRelativePath,
options: &CheckOptions,
) -> ViewResult<CheckOutput> {
) -> ViewResult<CheckResponse> {
let entry = project.absolute_for(relative)?;
let scratch = ScratchDir::create("check")?;
let emit = scratch.file("analysis.json");
let mut args = build_check_args(&entry);
// Scratch path is ours; the argument vector is explicit, no shell.
args.push(OsString::from("--json"));
args.push(OsString::from("--emit"));
args.push(emit.clone().into_os_string());
if options.refs {
@@ -291,13 +323,32 @@ impl CoreClient {
project.root(),
options.timeout.unwrap_or(DEFAULT_CHECK_TIMEOUT),
)?;
if output.exit_code != 0 {
return Err(ViewError::AnalysisFailed {
detail: format!(
"`marqdo check` failed with exit code {}: {}",
output.exit_code,
summarize_stderr(&output.stderr)
),
let check_json: Option<serde_json::Value> =
serde_json::from_slice(&output.stdout_bytes).ok();
let success = output.exit_code == 0
&& check_json
.as_ref()
.and_then(|json| json.get("success"))
.and_then(serde_json::Value::as_bool)
.unwrap_or(true);
let diagnostics = check_json
.as_ref()
.and_then(|json| json.get("diagnostics"))
.and_then(serde_json::Value::as_array)
.map(|items| {
items
.iter()
.filter_map(|item| serde_json::from_value(item.clone()).ok())
.collect::<Vec<RawCheckDiagnostic>>()
})
.unwrap_or_default();
if !success {
return Ok(CheckResponse {
success: false,
analysis: None,
diagnostics,
exit_code: output.exit_code,
stderr: output.stderr,
});
}
let analysis_bytes = std::fs::read(&emit).map_err(|err| ViewError::AnalysisFailed {
@@ -311,12 +362,18 @@ impl CoreClient {
detail: "`marqdo check` emitted an empty Analysis file".to_string(),
});
}
Ok(CheckOutput {
analysis_sha256: sha256_hex(&analysis_bytes),
analysis_digest: sha256_prefixed(&analysis_bytes),
analysis_bytes,
stdout: output.stdout,
stderr: output.stderr,
Ok(CheckResponse {
success: true,
analysis: Some(CheckOutput {
analysis_sha256: sha256_hex(&analysis_bytes),
analysis_digest: sha256_prefixed(&analysis_bytes),
analysis_bytes,
stdout: output.stdout,
stderr: output.stderr,
}),
diagnostics,
exit_code: 0,
stderr: String::new(),
})
}
+681
View File
@@ -0,0 +1,681 @@
//! Reader-oriented Markdown document model.
//!
//! Comrak (the same parser version as the frozen Markdown profile) parses the
//! source for **typography only**; the resulting tree is converted into a
//! View-owned `DocBlock`/`Inline` model that keeps exact UTF-8 byte spans.
//! No semantic decision (which node is executable) is taken here — that comes
//! exclusively from validated Analysis v2 (`semantic.rs`).
use crate::project::SafeRelativePath;
use crate::source_map::{sha256_hex, SourceIndex, SourceSpan};
use comrak::nodes::{ListType, NodeValue, Sourcepos, TableAlignment};
use comrak::{parse_document, Arena, Options};
/// Class of a table column.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TableAlign {
None,
Left,
Center,
Right,
}
#[derive(Debug, Clone)]
pub enum Inline {
Text {
span: SourceSpan,
literal: String,
},
Code {
span: SourceSpan,
literal: String,
ticks: usize,
},
Strong {
span: SourceSpan,
children: Vec<Inline>,
},
Emph {
span: SourceSpan,
children: Vec<Inline>,
},
Strikethrough {
span: SourceSpan,
children: Vec<Inline>,
},
Link {
span: SourceSpan,
url: String,
title: String,
children: Vec<Inline>,
},
Image {
span: SourceSpan,
url: String,
title: String,
alt: String,
},
Math {
span: SourceSpan,
literal: String,
display: bool,
},
HtmlInline {
span: SourceSpan,
raw: String,
},
SoftBreak {
span: SourceSpan,
},
LineBreak {
span: SourceSpan,
},
Other {
span: SourceSpan,
},
}
impl Inline {
pub fn span(&self) -> SourceSpan {
match self {
Inline::Text { span, .. }
| Inline::Code { span, .. }
| Inline::Strong { span, .. }
| Inline::Emph { span, .. }
| Inline::Strikethrough { span, .. }
| Inline::Link { span, .. }
| Inline::Image { span, .. }
| Inline::Math { span, .. }
| Inline::HtmlInline { span, .. }
| Inline::SoftBreak { span }
| Inline::LineBreak { span }
| Inline::Other { span } => *span,
}
}
pub fn plain_text(&self) -> String {
let mut out = String::new();
self.push_plain_text(&mut out);
out
}
fn push_plain_text(&self, out: &mut String) {
match self {
Inline::Text { literal, .. } | Inline::Code { literal, .. } => out.push_str(literal),
Inline::Strong { children, .. }
| Inline::Emph { children, .. }
| Inline::Strikethrough { children, .. }
| Inline::Link { children, .. } => {
for child in children {
child.push_plain_text(out);
}
}
Inline::Image { alt, .. } => out.push_str(alt),
Inline::Math { literal, .. } => out.push_str(literal),
Inline::SoftBreak { .. } | Inline::LineBreak { .. } => out.push(' '),
Inline::HtmlInline { .. } | Inline::Other { .. } => {}
}
}
}
#[derive(Debug, Clone)]
pub enum DocBlock {
Heading {
level: u8,
span: SourceSpan,
content: Vec<Inline>,
},
Paragraph {
span: SourceSpan,
content: Vec<Inline>,
},
List {
ordered: bool,
start: Option<usize>,
tight: bool,
span: SourceSpan,
items: Vec<DocBlock>,
},
ListItem {
span: SourceSpan,
task: Option<bool>,
children: Vec<DocBlock>,
},
BlockQuote {
span: SourceSpan,
children: Vec<DocBlock>,
},
CodeBlock {
span: SourceSpan,
info: String,
literal: String,
},
Table {
span: SourceSpan,
alignments: Vec<TableAlign>,
header: Vec<Vec<Inline>>,
rows: Vec<Vec<Vec<Inline>>>,
},
MathBlock {
span: SourceSpan,
literal: String,
},
ThematicBreak {
span: SourceSpan,
},
HtmlBlock {
span: SourceSpan,
literal: String,
},
Other {
span: SourceSpan,
},
}
impl DocBlock {
pub fn span(&self) -> SourceSpan {
match self {
DocBlock::Heading { span, .. }
| DocBlock::Paragraph { span, .. }
| DocBlock::List { span, .. }
| DocBlock::ListItem { span, .. }
| DocBlock::BlockQuote { span, .. }
| DocBlock::CodeBlock { span, .. }
| DocBlock::Table { span, .. }
| DocBlock::MathBlock { span, .. }
| DocBlock::ThematicBreak { span }
| DocBlock::HtmlBlock { span, .. }
| DocBlock::Other { span } => *span,
}
}
pub fn heading_text(&self) -> Option<String> {
match self {
DocBlock::Heading { content, .. } => {
Some(content.iter().map(Inline::plain_text).collect::<String>())
}
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct DocumentIdentity {
pub project_root_id: String,
pub module_id: String,
pub relative_path: String,
pub source_sha256: String,
}
impl DocumentIdentity {
pub fn placeholder(relative_path: &SafeRelativePath) -> Self {
Self {
project_root_id: String::new(),
module_id: String::new(),
relative_path: relative_path.as_str().to_string(),
source_sha256: String::new(),
}
}
}
#[derive(Debug, Clone)]
pub struct DocumentModel {
pub identity: DocumentIdentity,
pub source: String,
pub blocks: Vec<DocBlock>,
pub source_index: SourceIndex,
/// Number of leading BOM bytes stripped before parsing.
pub bom_len: usize,
}
impl DocumentModel {
/// Parse the exact source for display. Never decides executable semantics.
pub fn parse(source: String, identity: DocumentIdentity) -> Self {
let (bom_len, body) = strip_bom(&source);
let options = markdown_options();
let arena = Arena::new();
let root = parse_document(&arena, body, &options);
let lines = line_starts(body);
let body_len = body.len();
let blocks = root
.children()
.filter_map(|child| convert_block(child, &lines, bom_len, body_len))
.collect();
let source_index = SourceIndex::new(&source);
Self {
identity,
source,
blocks,
source_index,
bom_len,
}
}
/// First level-1 heading text, else the document stem.
pub fn title(&self) -> String {
for block in &self.blocks {
if let DocBlock::Heading {
level: 1, content, ..
} = block
{
let raw = content
.iter()
.map(Inline::plain_text)
.collect::<String>()
.trim()
.to_string();
// Display-only: strip a legal mode declaration prefix. Source
// view still shows the exact original text.
let text = raw
.strip_prefix("@exec ")
.or_else(|| raw.strip_prefix("@knowledge "))
.unwrap_or(&raw)
.trim()
.to_string();
if !text.is_empty() {
return text;
}
}
}
let name = self
.identity
.relative_path
.rsplit('/')
.next()
.unwrap_or(&self.identity.relative_path);
name.trim_end_matches(".mq.md").to_string()
}
/// Plain text of the whole document (search/alt helpers).
pub fn plain_text(&self) -> String {
let mut out = String::new();
collect_block_text(&self.blocks, &mut out);
out
}
pub fn source_digest(&self) -> String {
sha256_hex(self.source.as_bytes())
}
}
/// The frozen `marqdo.md.v1` parser options (same set as the Core profile).
pub fn markdown_options() -> Options<'static> {
let mut options = Options::default();
options.extension.table = true;
options.extension.strikethrough = true;
options.extension.tasklist = true;
options.extension.math_dollars = true;
options.extension.math_dollars_block = true;
options.extension.front_matter_delimiter = Some("---".to_string());
options
}
fn collect_block_text(blocks: &[DocBlock], out: &mut String) {
for block in blocks {
match block {
DocBlock::Heading { content, .. } | DocBlock::Paragraph { content, .. } => {
for inline in content {
out.push_str(&inline.plain_text());
}
out.push('\n');
}
DocBlock::List { items, .. } => collect_block_text(items, out),
DocBlock::ListItem { children, .. } => collect_block_text(children, out),
DocBlock::BlockQuote { children, .. } => collect_block_text(children, out),
DocBlock::CodeBlock { literal, .. } | DocBlock::MathBlock { literal, .. } => {
out.push_str(literal);
out.push('\n');
}
DocBlock::Table { header, rows, .. } => {
for cell in header {
for inline in cell {
out.push_str(&inline.plain_text());
}
}
for row in rows {
for cell in row {
for inline in cell {
out.push_str(&inline.plain_text());
}
}
}
out.push('\n');
}
DocBlock::ThematicBreak { .. }
| DocBlock::HtmlBlock { .. }
| DocBlock::Other { .. } => {}
}
}
}
fn strip_bom(source: &str) -> (usize, &str) {
match source.strip_prefix('\u{feff}') {
Some(rest) => (source.len() - rest.len(), rest),
None => (0, source),
}
}
fn line_starts(text: &str) -> Vec<usize> {
let bytes = text.as_bytes();
let mut starts = vec![0usize];
for (index, byte) in bytes.iter().enumerate() {
if *byte == b'\n' {
starts.push(index + 1);
}
}
starts
}
fn span_of(pos: Sourcepos, lines: &[usize], shift: usize, body_len: usize) -> SourceSpan {
fn offset_of(line: usize, column: usize, lines: &[usize], inclusive: bool) -> Option<usize> {
if line == 0 {
return None;
}
let line_start = *lines.get(line - 1)?;
Some(line_start + column.saturating_sub(1) + usize::from(inclusive))
}
let start = offset_of(pos.start.line, pos.start.column, lines, false)
.map(|offset| offset.min(body_len))
.unwrap_or(0);
let end = offset_of(pos.end.line, pos.end.column, lines, true)
.map(|offset| offset.min(body_len))
.unwrap_or(start)
.max(start);
SourceSpan::new((start + shift) as u64, (end + shift) as u64)
}
fn convert_block<'a>(
node: &'a comrak::nodes::AstNode<'a>,
lines: &[usize],
shift: usize,
body_len: usize,
) -> Option<DocBlock> {
let data = node.data();
let span = span_of(data.sourcepos, lines, shift, body_len);
let value = &data.value;
let block = match value {
NodeValue::Document => return None,
NodeValue::FrontMatter(_) => return None,
NodeValue::Paragraph => DocBlock::Paragraph {
span,
content: convert_inlines(node, lines, shift, body_len),
},
NodeValue::Heading(heading) => DocBlock::Heading {
level: heading.level,
span,
content: convert_inlines(node, lines, shift, body_len),
},
NodeValue::List(list) => {
let ordered = list.list_type == ListType::Ordered;
let items = node
.children()
.filter_map(|child| convert_block(child, lines, shift, body_len))
.collect();
DocBlock::List {
ordered,
start: if ordered { Some(list.start) } else { None },
tight: list.tight,
span,
items,
}
}
NodeValue::Item(_) => DocBlock::ListItem {
span,
task: None,
children: node
.children()
.filter_map(|child| convert_block(child, lines, shift, body_len))
.collect(),
},
NodeValue::TaskItem(item) => DocBlock::ListItem {
span,
task: Some(item.symbol.is_some()),
children: node
.children()
.filter_map(|child| convert_block(child, lines, shift, body_len))
.collect(),
},
NodeValue::BlockQuote | NodeValue::MultilineBlockQuote(_) => DocBlock::BlockQuote {
span,
children: node
.children()
.filter_map(|child| convert_block(child, lines, shift, body_len))
.collect(),
},
NodeValue::CodeBlock(code) => DocBlock::CodeBlock {
span,
info: code.info.clone(),
literal: code.literal.clone(),
},
NodeValue::HtmlBlock(html) => DocBlock::HtmlBlock {
span,
literal: html.literal.clone(),
},
NodeValue::ThematicBreak(_) => DocBlock::ThematicBreak { span },
NodeValue::MathBlock(math) => DocBlock::MathBlock {
span,
literal: math.literal.clone(),
},
NodeValue::Table(table) => {
let alignments = table
.alignments
.iter()
.map(|alignment| match alignment {
TableAlignment::None => TableAlign::None,
TableAlignment::Left => TableAlign::Left,
TableAlignment::Center => TableAlign::Center,
TableAlignment::Right => TableAlign::Right,
})
.collect();
let mut header = Vec::new();
let mut rows = Vec::new();
for row in node.children() {
let row_data = row.data();
let is_header = match &row_data.value {
NodeValue::TableRow(table_row) => table_row.header,
_ => false,
};
let mut cells = Vec::new();
for cell in row.children() {
cells.push(convert_inlines(cell, lines, shift, body_len));
}
if is_header {
header = cells;
} else {
rows.push(cells);
}
}
DocBlock::Table {
span,
alignments,
header,
rows,
}
}
_ => {
// Unknown block kinds are inert. If they carry block children, keep
// them so future additive nodes cannot hide readable content.
let children: Vec<DocBlock> = node
.children()
.filter_map(|child| convert_block(child, lines, shift, body_len))
.collect();
if children.is_empty() {
DocBlock::Other { span }
} else {
DocBlock::BlockQuote { span, children }
}
}
};
Some(block)
}
fn convert_inlines<'a>(
node: &'a comrak::nodes::AstNode<'a>,
lines: &[usize],
shift: usize,
body_len: usize,
) -> Vec<Inline> {
node.children()
.filter_map(|child| convert_inline(child, lines, shift, body_len))
.collect()
}
fn convert_inline<'a>(
node: &'a comrak::nodes::AstNode<'a>,
lines: &[usize],
shift: usize,
body_len: usize,
) -> Option<Inline> {
let data = node.data();
let span = span_of(data.sourcepos, lines, shift, body_len);
let inline = match &data.value {
NodeValue::Text(text) => Inline::Text {
span,
literal: text.to_string(),
},
NodeValue::Code(code) => Inline::Code {
span,
literal: code.literal.clone(),
ticks: code.num_backticks,
},
NodeValue::SoftBreak => Inline::SoftBreak { span },
NodeValue::LineBreak => Inline::LineBreak { span },
NodeValue::Strong(_) => Inline::Strong {
span,
children: convert_inlines(node, lines, shift, body_len),
},
NodeValue::Emph(_) => Inline::Emph {
span,
children: convert_inlines(node, lines, shift, body_len),
},
NodeValue::Strikethrough(_) => Inline::Strikethrough {
span,
children: convert_inlines(node, lines, shift, body_len),
},
NodeValue::Link(link) => Inline::Link {
span,
url: link.url.clone(),
title: link.title.clone(),
children: convert_inlines(node, lines, shift, body_len),
},
NodeValue::Image(link) => {
let children = convert_inlines(node, lines, shift, body_len);
Inline::Image {
span,
url: link.url.clone(),
title: link.title.clone(),
alt: children.iter().map(Inline::plain_text).collect(),
}
}
NodeValue::Math(math) => Inline::Math {
span,
literal: math.literal.clone(),
display: math.display_math,
},
NodeValue::HtmlInline(raw) => Inline::HtmlInline {
span,
raw: raw.clone(),
},
_ => Inline::Other { span },
};
Some(inline)
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(source: &str) -> DocumentModel {
DocumentModel::parse(
source.to_string(),
DocumentIdentity {
project_root_id: "root:t@0.1.0".into(),
module_id: "root:t@0.1.0::index.mq.md".into(),
relative_path: "index.mq.md".into(),
source_sha256: String::new(),
},
)
}
#[test]
fn parses_gfm_and_preserves_utf8_spans() {
let source =
"# @knowledge 标题\n\n| 名称 | 值 |\n| --- | --- |\n| 甲 | 1 |\n\n**加粗** 和 `代码`\n";
let document = parse(source);
// Display title drops a legal mode prefix; the source keeps it.
assert_eq!(document.title(), "标题");
assert!(document.source.starts_with("# @knowledge 标题"));
assert!(document
.blocks
.iter()
.any(|block| matches!(block, DocBlock::Table { .. })));
// Every block span slices valid UTF-8.
for block in &document.blocks {
let span = block.span();
assert!(
document
.source_index
.source_text(&document.source, span)
.is_some(),
"invalid span {span:?}"
);
}
}
#[test]
fn parses_math_and_code_as_inert_literals() {
let source = "行内 $a^2$ 与\n\n$$\n\\sum i\n$$\n\n```rust\nfn x() {}\n```\n";
let document = parse(source);
assert!(document.plain_text().contains("a^2"));
assert!(document.plain_text().contains("sum i"));
assert!(document.plain_text().contains("fn x()"));
}
#[test]
fn parses_lists_quotes_and_task_items() {
let source = "- [x] 完成\n- [ ] 未完成\n\n> 引用\n\n1. 一\n2. 二\n";
let document = parse(source);
let has_task = document.blocks.iter().any(|block| match block {
DocBlock::List { items, .. } => items.iter().any(|item| {
matches!(
item,
DocBlock::ListItem {
task: Some(true),
..
}
)
}),
_ => false,
});
assert!(has_task);
assert!(document
.blocks
.iter()
.any(|block| matches!(block, DocBlock::BlockQuote { .. })));
assert_eq!(document.blocks.len(), 3);
}
#[test]
fn heading_spans_are_exact() {
let source = "# 数学 #\n\n正文\n";
let document = parse(source);
match &document.blocks[0] {
DocBlock::Heading { span, .. } => {
let text = document
.source_index
.source_text(&document.source, *span)
.unwrap();
assert_eq!(text, "# 数学 #");
}
other => panic!("expected heading, got {other:?}"),
}
}
#[test]
fn front_matter_is_not_rendered_as_a_block() {
let source = "---\nimport:\n lib: \"./lib.mq.md\"\n---\n\n# hi\n";
let document = parse(source);
assert_eq!(document.blocks.len(), 1);
assert!(matches!(document.blocks[0], DocBlock::Heading { .. }));
}
}
+6
View File
@@ -7,10 +7,16 @@
//! this library so there is never a second renderer or a second parser.
pub mod app;
pub mod assets;
pub mod cli;
pub mod core_client;
pub mod document;
pub mod error;
pub mod presentation;
pub mod project;
pub mod render;
pub mod semantic;
pub mod server;
pub mod source_map;
pub mod version;
+275
View File
@@ -0,0 +1,275 @@
//! Presentation model: the one intermediate form between verified domain data
//! and the one `ReaderRenderer`.
//!
//! Nothing here spawns processes, builds HTML or parses Markdown semantics. It
//! only composes already-verified pieces (RFC-VIEW-0001 §6.3, §14.2).
use crate::document::{DocumentIdentity, DocumentModel};
use crate::project::{Project, SafeRelativePath, ViewConfig};
use crate::semantic::{CoreDiagnostic, SemanticProjection, ViewWarning};
/// Private View presentation-model version. Not a public protocol.
pub const PRESENTATION_VERSION: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceStatus {
/// No usable `MARQDO_BIN`; prose only, semantics explicitly unverified.
CoreUnavailable,
/// `check` succeeded and Analysis v2 was verified.
StaticOk,
/// `check` failed; diagnostics shown, semantics revoked.
CoreError,
/// Analysis/source digest mismatch or an outdated artifact.
Stale,
/// Unknown Analysis/Tool major or product range.
ProtocolIncompatible,
/// Analysis `source_digest` differs from the current source bytes.
SourceMismatch,
}
impl SourceStatus {
pub fn data_value(&self) -> &'static str {
match self {
SourceStatus::CoreUnavailable => "core-unavailable",
SourceStatus::StaticOk => "static-ok",
SourceStatus::CoreError => "core-error",
SourceStatus::Stale => "stale",
SourceStatus::ProtocolIncompatible => "protocol-incompatible",
SourceStatus::SourceMismatch => "source-mismatch",
}
}
pub fn label(&self) -> &'static str {
match self {
SourceStatus::CoreUnavailable => "核心不可用 · 语义未验证",
SourceStatus::StaticOk => "静态检查已通过 · 未运行",
SourceStatus::CoreError => "Core 检查失败 · 语义不可用",
SourceStatus::Stale => "语义结果已过期",
SourceStatus::ProtocolIncompatible => "核心协议不兼容",
SourceStatus::SourceMismatch => "源码与分析不一致",
}
}
pub fn semantics_usable(&self) -> bool {
matches!(self, SourceStatus::StaticOk)
}
}
#[derive(Debug, Clone)]
pub struct Navigation {
pub site_title: String,
pub documents: Vec<SafeRelativePath>,
pub active: Option<SafeRelativePath>,
/// True only when an explicit `view.json` names this document as welcome.
pub welcome: bool,
}
impl Navigation {
pub fn from_project(project: &Project, config: &ViewConfig, active: &SafeRelativePath) -> Self {
let documents = project.list_documents().unwrap_or_default();
let welcome = config
.welcome
.as_ref()
.map(|welcome| welcome == active)
.unwrap_or(false);
Self {
site_title: config
.site_title
.clone()
.unwrap_or_else(|| "Marqdo".to_string()),
documents,
active: Some(active.clone()),
welcome,
}
}
}
#[derive(Debug, Clone)]
pub struct PresentationModel {
pub version: u32,
pub title: String,
pub document: DocumentModel,
pub semantic: Option<SemanticProjection>,
pub source_status: SourceStatus,
/// Human-readable reason for a degraded status (already normalized: no
/// absolute paths from the Core).
pub status_note: Option<String>,
pub diagnostics: Vec<CoreDiagnostic>,
pub warnings: Vec<ViewWarning>,
pub navigation: Navigation,
/// Function/section outline entries rendered from verified Analysis only.
pub outline: Vec<OutlineEntry>,
/// Frozen core product version used for this page, when one was consulted.
pub core_version: Option<String>,
}
#[derive(Debug, Clone)]
pub struct OutlineEntry {
pub label: String,
pub anchor: String,
pub detail: String,
pub kind: OutlineKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutlineKind {
Function,
Knowledge,
Section,
}
impl PresentationModel {
pub fn functions(&self) -> impl Iterator<Item = &OutlineEntry> {
self.outline
.iter()
.filter(|entry| entry.kind == OutlineKind::Function)
}
pub fn error_diagnostics(&self) -> impl Iterator<Item = &CoreDiagnostic> {
self.diagnostics
.iter()
.filter(|diagnostic| diagnostic.severity == "error")
}
}
/// Input to the one builder. `analysis` is already protocol/byte verified.
pub struct BuildInput<'a> {
pub document: DocumentModel,
pub analysis: Option<&'a crate::semantic::VerifiedAnalysis>,
pub status: SourceStatus,
pub status_note: Option<String>,
pub diagnostics: Vec<CoreDiagnostic>,
pub navigation: Navigation,
pub core_version: Option<String>,
}
pub fn build(input: BuildInput<'_>) -> PresentationModel {
let BuildInput {
mut document,
analysis,
status,
status_note,
mut diagnostics,
navigation,
core_version,
} = input;
let semantic = analysis.map(|verified| verified.projection.clone());
if let Some(projection) = &semantic {
document.identity = DocumentIdentity {
project_root_id: projection.project_root_id.clone(),
module_id: projection.module_id.clone(),
relative_path: projection.relative_path.clone(),
source_sha256: projection.source_digest.clone(),
};
for diagnostic in &projection.diagnostics {
if !diagnostics.iter().any(|existing| {
existing.code == diagnostic.code
&& existing.message == diagnostic.message
&& existing.span == diagnostic.span
}) {
diagnostics.push(diagnostic.clone());
}
}
}
let warnings = semantic
.as_ref()
.map(|projection| projection.warnings.clone())
.unwrap_or_default();
let outline = semantic.as_ref().map(build_outline).unwrap_or_default();
PresentationModel {
version: PRESENTATION_VERSION,
title: document.title(),
document,
semantic,
source_status: status,
status_note,
diagnostics,
warnings,
navigation,
outline,
core_version,
}
}
fn build_outline(projection: &SemanticProjection) -> Vec<OutlineEntry> {
let mut entries = Vec::new();
for function in &projection.functions {
let params = if function.signature.params.is_empty() {
String::new()
} else {
function
.signature
.params
.iter()
.map(|param| {
if param.ty.is_empty() {
param.name.clone()
} else {
format!("{}: {}", param.name, param.ty)
}
})
.collect::<Vec<_>>()
.join(", ")
};
let detail = if params.is_empty() {
"无参数".to_string()
} else {
format!("params({params})")
};
entries.push(OutlineEntry {
label: function.local_name.clone(),
anchor: anchor_for_span(function.heading_span.start, function.heading_span.end),
detail,
kind: OutlineKind::Function,
});
}
for unit in &projection.units {
let kind = match unit.kind {
crate::semantic::UnitKind::Knowledge if unit.level >= 2 => OutlineKind::Knowledge,
crate::semantic::UnitKind::Section => OutlineKind::Section,
_ => continue,
};
if unit.name.is_empty() {
continue;
}
entries.push(OutlineEntry {
label: unit.name.clone(),
anchor: anchor_for_span(unit.span.start, unit.span.end),
detail: if unit.level == 2 {
"知识单元".to_string()
} else {
"章节".to_string()
},
kind,
});
}
entries
}
/// Deterministic heading anchor derived from the heading byte span. It never
/// depends on rendered text, so duplicate headings cannot collide.
pub fn anchor_for_span(start: u64, end: u64) -> String {
format!("mq-h-{start:x}-{end:x}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn status_values_are_stable() {
assert_eq!(SourceStatus::StaticOk.data_value(), "static-ok");
assert_eq!(SourceStatus::CoreError.data_value(), "core-error");
assert!(SourceStatus::StaticOk.semantics_usable());
assert!(!SourceStatus::CoreUnavailable.semantics_usable());
assert!(!SourceStatus::SourceMismatch.semantics_usable());
}
#[test]
fn heading_anchors_are_deterministic_and_collision_free() {
assert_eq!(anchor_for_span(1, 2), "mq-h-1-2");
assert_ne!(anchor_for_span(1, 2), anchor_for_span(1, 3));
}
}
+80
View File
@@ -306,6 +306,86 @@ impl Project {
}
}
/// Optional View-only site configuration (`view.json`).
///
/// This is **not** a Marqdo language protocol and cannot grant execution: only
/// the fields below are read, and the welcome path is still subject to the same
/// project-root boundary (RFC-VIEW-0001 §9.4).
#[derive(Debug, Clone, Default)]
pub struct ViewConfig {
pub welcome: Option<SafeRelativePath>,
pub site_title: Option<String>,
pub theme: Option<String>,
}
impl ViewConfig {
pub fn load(root: &Path) -> ViewResult<Self> {
let path = root.join("view.json");
let metadata = match std::fs::metadata(&path) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
Err(err) => return Err(ViewError::io(&format!("stat {}", path.display()), err)),
};
if !metadata.is_file() || metadata.len() > 64 * 1024 {
return Err(ViewError::PathForbidden {
detail: "view.json must be a regular file under 64 KiB".to_string(),
});
}
let bytes = std::fs::read(&path)
.map_err(|err| ViewError::io(&format!("read {}", path.display()), err))?;
#[derive(serde::Deserialize)]
struct RawConfig {
#[serde(default)]
schema: String,
#[serde(default)]
schema_version: u32,
#[serde(default)]
welcome: Option<String>,
#[serde(default)]
site_title: Option<String>,
#[serde(default)]
theme: Option<String>,
}
let raw: RawConfig = serde_json::from_slice(&bytes).map_err(|err| ViewError::Io {
detail: format!("view.json is not valid JSON: {err}"),
})?;
if raw.schema != "marqdo.view-config" || raw.schema_version != 1 {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unsupported view.json schema {:?} version {}; expected marqdo.view-config v1",
raw.schema, raw.schema_version
),
});
}
let welcome = match raw.welcome {
Some(path) => Some(SafeRelativePath::parse(&path)?),
None => None,
};
if let Some(welcome) = &welcome {
if !root.join(welcome.to_path()).is_file() {
return Err(ViewError::PathForbidden {
detail: format!(
"view.json welcome file {welcome} does not exist under the project root"
),
});
}
}
let site_title = raw
.site_title
.map(|title| title.trim().to_string())
.filter(|title| !title.is_empty() && title.chars().count() <= 80);
let theme = raw
.theme
.map(|theme| theme.trim().to_string())
.filter(|theme| theme == "botanical" || theme == "paper");
Ok(Self {
welcome,
site_title,
theme,
})
}
}
/// Discover the project root for a source file: nearest ancestor with
/// `marqdo.yaml`, else the file's directory. The file itself is canonical.
pub fn discover_project_root(file: &Path) -> PathBuf {
+1162
View File
File diff suppressed because it is too large. Load diff
+941
View File
@@ -0,0 +1,941 @@
//! Analysis v2 validation and static semantic projection.
//!
//! This module is the only consumer of the public Analysis JSON. It verifies
//! protocol identity first, then projects functions/units/statements/diagnostics
//! into View-owned types with **validated** source spans. A span that is out of
//! range or not on a UTF-8 boundary is dropped with an explicit View warning
//! instead of being pointed at nearby text (RFC-VIEW-0001 §4.3, §8.2).
use crate::error::{ViewError, ViewResult};
use crate::source_map::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
use crate::version;
use serde::Deserialize;
use serde_json::Value;
/// Stable DOM identity for one source-bound annotation, local to this document
/// and run. It is not a cross-edit identity.
pub fn source_id(module_id: &str, span: SourceSpan, kind: &str) -> String {
let material = format!("{module_id}\0{}:{}:{}", span.start, span.end, kind);
sha256_hex(material.as_bytes())[..16].to_string()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnitKind {
Root,
Namespace,
Function,
Knowledge,
Section,
Other,
}
#[derive(Debug, Clone)]
pub struct SemanticUnit {
pub id: String,
pub name: String,
pub level: u8,
pub kind: UnitKind,
pub function: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct FunctionParam {
pub name: String,
pub ty: String,
pub required: bool,
pub default: Option<String>,
pub span: Option<SourceSpan>,
}
#[derive(Debug, Clone)]
pub struct FunctionSignature {
pub kind: String,
pub params: Vec<FunctionParam>,
}
#[derive(Debug, Clone)]
pub struct SemanticFunction {
pub id: String,
pub unit_id: String,
pub local_name: String,
pub namespace: Option<String>,
pub span: SourceSpan,
pub heading_span: SourceSpan,
pub signature: FunctionSignature,
pub effects: Vec<String>,
pub statements: Vec<SemanticStatement>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatementKind {
Assign,
Expression,
Branch,
Loop,
Return,
Other,
}
impl StatementKind {
pub fn label(&self) -> &'static str {
match self {
StatementKind::Assign => "赋值",
StatementKind::Expression => "表达式",
StatementKind::Branch => "条件分支",
StatementKind::Loop => "循环",
StatementKind::Return => "返回",
StatementKind::Other => "语句",
}
}
pub fn data_value(&self) -> &'static str {
match self {
StatementKind::Assign => "assign",
StatementKind::Expression => "expression",
StatementKind::Branch => "branch",
StatementKind::Loop => "loop",
StatementKind::Return => "return",
StatementKind::Other => "other",
}
}
}
#[derive(Debug, Clone)]
pub struct SemanticStatement {
pub kind: StatementKind,
/// Header span for control flow, payload span for simple statements.
pub span: SourceSpan,
/// For `if` arms and `while` conditions: the condition text span as the
/// compiler recorded it.
pub condition_span: Option<SourceSpan>,
pub arms: Vec<SemanticArm>,
pub body: Vec<SemanticStatement>,
/// Target name for assignments (local name or `index` form), for static
/// outline display only. Never a runtime value.
pub target: Option<String>,
}
#[derive(Debug, Clone)]
pub struct SemanticArm {
pub span: Option<SourceSpan>,
pub condition_span: Option<SourceSpan>,
pub body: Vec<SemanticStatement>,
}
impl SemanticFunction {
/// Depth-first statement walk in source order.
pub fn flattened_statements(&self) -> Vec<&SemanticStatement> {
let mut out = Vec::new();
for statement in &self.statements {
collect_statements(statement, &mut out);
}
out
}
}
fn collect_statements<'a>(statement: &'a SemanticStatement, out: &mut Vec<&'a SemanticStatement>) {
out.push(statement);
for arm in &statement.arms {
for child in &arm.body {
collect_statements(child, out);
}
}
for child in &statement.body {
collect_statements(child, out);
}
}
#[derive(Debug, Clone)]
pub struct StaticResource {
pub id: String,
pub kind: String,
pub span: SourceSpan,
pub content_digest: String,
pub language: Option<String>,
pub display: bool,
}
#[derive(Debug, Clone)]
pub struct StaticImport {
pub alias: String,
pub target: String,
pub resolved: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct StaticReference {
pub url: String,
pub span: SourceSpan,
pub state: String,
pub target_module: Option<String>,
pub target_unit: Option<String>,
}
#[derive(Debug, Clone)]
pub struct StaticCall {
pub state: String,
pub target: Option<String>,
pub function: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct CoreDiagnostic {
pub module: Option<String>,
pub relative_path: Option<String>,
pub span: Option<SourceSpan>,
pub line: Option<u64>,
pub column: Option<u64>,
pub severity: String,
pub code: String,
pub message: String,
pub hints: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct ViewWarning {
pub code: String,
pub message: String,
pub span: Option<SourceSpan>,
}
#[derive(Debug, Clone)]
pub struct ModuleSummary {
pub id: String,
pub package_instance_id: String,
pub relative_path: String,
pub source_digest: String,
}
#[derive(Debug, Clone)]
pub struct SemanticProjection {
pub analysis_sha256: String,
pub analysis_digest: String,
pub producer_version: String,
pub markdown_profile: String,
pub project_root_id: String,
pub identity_kind: String,
pub lock_digest: String,
pub stdlib_version: Option<String>,
pub module_id: String,
pub package_instance_id: String,
pub relative_path: String,
pub source_digest: String,
pub units: Vec<SemanticUnit>,
pub functions: Vec<SemanticFunction>,
pub resources: Vec<StaticResource>,
pub imports: Vec<StaticImport>,
pub references: Vec<StaticReference>,
pub calls: Vec<StaticCall>,
pub diagnostics: Vec<CoreDiagnostic>,
pub warnings: Vec<ViewWarning>,
pub modules: Vec<ModuleSummary>,
}
#[derive(Debug)]
pub struct VerifiedAnalysis {
pub projection: SemanticProjection,
}
impl SemanticProjection {
pub fn unit_for_heading(&self, span: SourceSpan, level: u8) -> Option<&SemanticUnit> {
self.units
.iter()
.filter(|unit| unit.level == level && unit.span.contains(span))
.min_by_key(|unit| unit.span.len())
}
pub fn function_by_heading(&self, span: SourceSpan) -> Option<&SemanticFunction> {
self.functions
.iter()
.find(|function| function.heading_span == span)
.or_else(|| {
self.functions
.iter()
.find(|function| function.span.contains(span))
})
}
/// All statements of all functions, flattened in deterministic order.
pub fn all_statements(&self) -> Vec<(&SemanticFunction, &SemanticStatement)> {
let mut out = Vec::new();
for function in &self.functions {
for statement in function.flattened_statements() {
out.push((function, statement));
}
}
out
}
/// The innermost statement whose span is contained in `inline_span`.
pub fn statement_for_inline(
&self,
inline_span: SourceSpan,
) -> Option<(&SemanticFunction, &SemanticStatement)> {
self.all_statements()
.into_iter()
.filter(|(_, statement)| {
statement.span.start >= inline_span.start
&& statement.span.end <= inline_span.end
&& !statement.span.is_empty()
})
.max_by_key(|(_, statement)| statement.span.start)
}
pub fn resource_for_span(&self, span: SourceSpan) -> Option<&StaticResource> {
self.resources
.iter()
.find(|resource| resource.span == span || resource.span.contains(span))
}
pub fn reference_for_span(&self, span: SourceSpan) -> Option<&StaticReference> {
self.references
.iter()
.find(|reference| reference.span == span || reference.span.contains(span))
}
}
// ---------------------------------------------------------------------------
// Raw protocol types (additive fields are tolerated and ignored).
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
struct RawAnalysis {
schema: String,
schema_version: u32,
producer: RawProducer,
project: RawProject,
modules: Vec<RawModule>,
#[serde(default)]
diagnostics: Vec<RawDiagnostic>,
}
#[derive(Debug, Deserialize)]
struct RawProducer {
#[serde(default)]
name: String,
#[serde(default)]
version: String,
#[serde(default)]
markdown_profile: String,
}
#[derive(Debug, Deserialize)]
struct RawProject {
#[serde(default)]
root_id: String,
#[serde(default)]
identity_kind: String,
#[serde(default)]
lock_digest: String,
#[serde(default)]
stdlib: Option<RawStdlib>,
}
#[derive(Debug, Deserialize)]
struct RawStdlib {
#[serde(default)]
version: String,
}
#[derive(Debug, Deserialize)]
struct RawModule {
#[serde(default)]
id: String,
#[serde(default)]
package_instance_id: String,
#[serde(default)]
relative_path: String,
#[serde(default)]
source_digest: String,
#[serde(default)]
units: Vec<RawUnit>,
#[serde(default)]
functions: Vec<RawFunction>,
#[serde(default)]
imports: Vec<RawImport>,
#[serde(default)]
references: Vec<RawReference>,
#[serde(default)]
calls: Vec<RawCall>,
#[serde(default)]
resources: Vec<RawResource>,
}
#[derive(Debug, Deserialize)]
struct RawUnit {
#[serde(default)]
id: String,
#[serde(default)]
name: String,
#[serde(default)]
level: u8,
#[serde(default)]
kind: String,
#[serde(default)]
function: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawFunction {
#[serde(default)]
id: String,
#[serde(default)]
unit_id: String,
#[serde(default)]
local_name: String,
#[serde(default)]
namespace: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
heading_span: Option<SourceSpan>,
#[serde(default)]
signature: Option<RawSignature>,
#[serde(default)]
effects: Vec<String>,
#[serde(default)]
body: Vec<RawStatement>,
}
#[derive(Debug, Deserialize)]
struct RawSignature {
#[serde(default)]
kind: String,
#[serde(default)]
params: Vec<RawParam>,
}
#[derive(Debug, Deserialize)]
struct RawParam {
#[serde(default)]
name: String,
#[serde(default, rename = "type")]
ty: Option<String>,
#[serde(default)]
required: bool,
#[serde(default)]
default: Option<Value>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawStatement {
#[serde(default)]
kind: String,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
condition_span: Option<SourceSpan>,
#[serde(default)]
arms: Vec<RawArm>,
#[serde(default)]
body: Vec<RawStatement>,
#[serde(default)]
target: Option<Value>,
}
#[derive(Debug, Deserialize)]
struct RawArm {
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
condition_span: Option<SourceSpan>,
#[serde(default)]
body: Vec<RawStatement>,
}
#[derive(Debug, Deserialize)]
struct RawResource {
#[serde(default)]
id: String,
#[serde(default)]
kind: String,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
content_digest: String,
#[serde(default)]
language: Option<String>,
#[serde(default)]
display: bool,
}
#[derive(Debug, Deserialize)]
struct RawImport {
#[serde(default)]
alias: String,
#[serde(default)]
target: String,
#[serde(default)]
resolved: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawReference {
#[serde(default)]
url: String,
#[serde(default)]
state: String,
#[serde(default)]
target_module: Option<String>,
#[serde(default)]
target_unit: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawCall {
#[serde(default)]
state: String,
#[serde(default)]
target: Option<String>,
#[serde(default)]
function: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawDiagnostic {
#[serde(default)]
module: Option<String>,
#[serde(default)]
relative_path: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
line: Option<u64>,
#[serde(default)]
column: Option<u64>,
#[serde(default)]
severity: String,
#[serde(default)]
code: String,
#[serde(default)]
message: String,
#[serde(default)]
hints: Vec<String>,
}
// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------
/// Verify Analysis bytes against the exact source and project the static facts.
///
/// Rejects protocol incompatibility and source-digest mismatch as errors; drops
/// individual invalid spans as warnings so the prose stays readable.
pub fn verify_analysis(
analysis_bytes: &[u8],
source: &str,
source_index: &SourceIndex,
expected_relative_path: &str,
) -> ViewResult<VerifiedAnalysis> {
let raw: RawAnalysis =
serde_json::from_slice(analysis_bytes).map_err(|err| ViewError::AnalysisFailed {
detail: format!("Analysis v2 is not valid JSON: {err}"),
})?;
if raw.schema != "marqdo.analysis" {
return Err(ViewError::ProtocolIncompatible {
detail: format!("unexpected Analysis schema {:?}", raw.schema),
});
}
if raw.schema_version != version::ANALYSIS_PROTOCOL {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis schema_version {} is not supported (View implements v{})",
raw.schema_version,
version::ANALYSIS_PROTOCOL
),
});
}
if raw.producer.name != "marqdo" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis producer.name {:?} is not `marqdo`",
raw.producer.name
),
});
}
if raw.producer.markdown_profile != "marqdo.md.v1" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unexpected Markdown profile {:?}; this View targets marqdo.md.v1",
raw.producer.markdown_profile
),
});
}
if raw.project.root_id.is_empty() {
return Err(ViewError::AnalysisFailed {
detail: "Analysis project.root_id is empty".to_string(),
});
}
let actual_digest = sha256_hex(source.as_bytes());
let module = raw
.modules
.iter()
.find(|module| module.relative_path == expected_relative_path)
.ok_or_else(|| ViewError::AnalysisFailed {
detail: format!("Analysis has no module for {expected_relative_path}"),
})?;
if module.source_digest != actual_digest {
return Err(ViewError::SourceMismatch {
expected: module.source_digest.clone(),
actual: actual_digest,
});
}
let mut warnings = Vec::new();
let mut valid_span = |span: Option<SourceSpan>, what: &str| -> Option<SourceSpan> {
let span = span?;
if source_index.validate_span_bytes(source.as_bytes(), span) {
Some(span)
} else {
warnings.push(ViewWarning {
code: "view.source_span_invalid".to_string(),
message: format!("{what} 的字节区间超出源码或不在 UTF-8 边界,已跳过该标注"),
span: Some(span),
});
None
}
};
let units: Vec<SemanticUnit> = module
.units
.iter()
.filter_map(|unit| {
let span = valid_span(unit.span, "语义单元")?;
Some(SemanticUnit {
id: unit.id.clone(),
name: unit.name.clone(),
level: unit.level,
kind: match unit.kind.as_str() {
"root" => UnitKind::Root,
"namespace" => UnitKind::Namespace,
"function" => UnitKind::Function,
"knowledge" => UnitKind::Knowledge,
"section" => UnitKind::Section,
_ => UnitKind::Other,
},
function: unit.function.clone(),
span,
})
})
.collect();
let functions: Vec<SemanticFunction> = module
.functions
.iter()
.filter_map(|function| {
let span = valid_span(function.span, "函数范围")?;
let heading_span = valid_span(function.heading_span, "函数标题")?;
let statements = function
.body
.iter()
.filter_map(|statement| convert_statement(statement, &mut valid_span))
.collect();
Some(SemanticFunction {
id: function.id.clone(),
unit_id: function.unit_id.clone(),
local_name: function.local_name.clone(),
namespace: function.namespace.clone(),
span,
heading_span,
signature: FunctionSignature {
kind: function
.signature
.as_ref()
.map(|signature| signature.kind.clone())
.unwrap_or_default(),
params: function
.signature
.as_ref()
.map(|signature| {
signature
.params
.iter()
.map(|param| FunctionParam {
name: param.name.clone(),
ty: param.ty.clone().unwrap_or_default(),
required: param.required,
default: param.default.as_ref().map(compact_value),
span: param.span.filter(|span| {
source_index.validate_span_bytes(source.as_bytes(), *span)
}),
})
.collect()
})
.unwrap_or_default(),
},
effects: function.effects.clone(),
statements,
})
})
.collect();
let resources: Vec<StaticResource> = module
.resources
.iter()
.filter(|resource| matches!(resource.kind.as_str(), "formula" | "code"))
.filter_map(|resource| {
let span = valid_span(resource.span, "资源")?;
Some(StaticResource {
id: resource.id.clone(),
kind: resource.kind.clone(),
span,
content_digest: resource.content_digest.clone(),
language: resource.language.clone(),
display: resource.display,
})
})
.collect();
let imports: Vec<StaticImport> = module
.imports
.iter()
.filter_map(|import| {
Some(StaticImport {
alias: import.alias.clone(),
target: import.target.clone(),
resolved: import.resolved.clone(),
span: valid_span(import.span, "导入声明")?,
})
})
.collect();
let references: Vec<StaticReference> = module
.references
.iter()
.filter_map(|reference| {
Some(StaticReference {
url: reference.url.clone(),
state: reference.state.clone(),
target_module: reference.target_module.clone(),
target_unit: reference.target_unit.clone(),
span: valid_span(reference.span, "Markdown 引用")?,
})
})
.collect();
let calls: Vec<StaticCall> = module
.calls
.iter()
.filter_map(|call| {
Some(StaticCall {
state: call.state.clone(),
target: call.target.clone(),
function: call.function.clone(),
span: valid_span(call.span, "调用点")?,
})
})
.collect();
let diagnostics: Vec<CoreDiagnostic> = raw
.diagnostics
.iter()
.map(|diagnostic| {
let span = diagnostic
.span
.filter(|span| source_index.validate_span_bytes(source.as_bytes(), *span));
CoreDiagnostic {
module: diagnostic.module.clone(),
relative_path: diagnostic.relative_path.clone(),
span,
line: diagnostic.line,
column: diagnostic.column,
severity: if diagnostic.severity.is_empty() {
"error".to_string()
} else {
diagnostic.severity.clone()
},
code: diagnostic.code.clone(),
message: diagnostic.message.clone(),
hints: diagnostic.hints.clone(),
}
})
.collect();
let modules = raw
.modules
.iter()
.map(|module| ModuleSummary {
id: module.id.clone(),
package_instance_id: module.package_instance_id.clone(),
relative_path: module.relative_path.clone(),
source_digest: module.source_digest.clone(),
})
.collect();
Ok(VerifiedAnalysis {
projection: SemanticProjection {
analysis_sha256: sha256_hex(analysis_bytes),
analysis_digest: sha256_prefixed(analysis_bytes),
producer_version: raw.producer.version.clone(),
markdown_profile: raw.producer.markdown_profile.clone(),
project_root_id: raw.project.root_id.clone(),
identity_kind: raw.project.identity_kind.clone(),
lock_digest: raw.project.lock_digest.clone(),
stdlib_version: raw.project.stdlib.as_ref().map(|s| s.version.clone()),
module_id: module.id.clone(),
package_instance_id: module.package_instance_id.clone(),
relative_path: module.relative_path.clone(),
source_digest: module.source_digest.clone(),
units,
functions,
resources,
imports,
references,
calls,
diagnostics,
warnings,
modules,
},
})
}
fn convert_statement(
raw: &RawStatement,
valid_span: &mut impl FnMut(Option<SourceSpan>, &str) -> Option<SourceSpan>,
) -> Option<SemanticStatement> {
let span = valid_span(raw.span, "语句")?;
let kind = match raw.kind.as_str() {
"assign" => StatementKind::Assign,
"expression" => StatementKind::Expression,
"branch" => StatementKind::Branch,
"loop" => StatementKind::Loop,
"return" => StatementKind::Return,
_ => StatementKind::Other,
};
let body = raw
.body
.iter()
.filter_map(|child| convert_statement(child, valid_span))
.collect();
let arms = raw
.arms
.iter()
.map(|arm| SemanticArm {
span: valid_span(arm.span, "分支臂"),
condition_span: valid_span(arm.condition_span, "分支条件"),
body: arm
.body
.iter()
.filter_map(|child| convert_statement(child, valid_span))
.collect(),
})
.collect();
Some(SemanticStatement {
kind,
span,
condition_span: valid_span(raw.condition_span, "控制条件"),
arms,
body,
target: raw.target.as_ref().and_then(assignment_target_label),
})
}
fn assignment_target_label(target: &Value) -> Option<String> {
match target {
Value::String(name) => Some(name.clone()),
Value::Object(map) => {
if map.get("kind").and_then(Value::as_str) == Some("index") {
Some("索引赋值".to_string())
} else {
None
}
}
_ => None,
}
}
fn compact_value(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
other => {
let text = other.to_string();
if text.chars().count() > 40 {
format!("{}…", text.chars().take(40).collect::<String>())
} else {
text
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn analysis(schema_version: u32, digest: &str) -> Vec<u8> {
serde_json::json!({
"schema": "marqdo.analysis",
"schema_version": schema_version,
"producer": {"name": "marqdo", "version": "3.0.0-beta.1", "markdown_profile": "marqdo.md.v1"},
"project": {"root_id": "root:t@0.1.0", "identity_kind": "manifest", "lock_digest": "", "stdlib": null},
"modules": [{
"id": "root:t@0.1.0::index.mq.md",
"package_instance_id": "root:t@0.1.0",
"relative_path": "index.mq.md",
"source_digest": digest,
"units": [],
"functions": [],
"imports": [],
"references": [],
"calls": [],
"resources": []
}],
"diagnostics": []
})
.to_string()
.into_bytes()
}
#[test]
fn rejects_unknown_schema_major_and_profile() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let digest = sha256_hex(source.as_bytes());
let err =
verify_analysis(&analysis(3, &digest), source, &index, "index.mq.md").unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
}
#[test]
fn rejects_digest_mismatch() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let err = verify_analysis(&analysis(2, &"0".repeat(64)), source, &index, "index.mq.md")
.unwrap_err();
assert_eq!(err.code(), "view.source_mismatch");
}
#[test]
fn projects_valid_analysis() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let digest = sha256_hex(source.as_bytes());
let verified =
verify_analysis(&analysis(2, &digest), source, &index, "index.mq.md").unwrap();
assert_eq!(verified.projection.project_root_id, "root:t@0.1.0");
assert_eq!(verified.projection.relative_path, "index.mq.md");
}
#[test]
fn source_id_is_deterministic_and_bounded() {
let span = SourceSpan::new(1, 5);
let id = source_id("mod", span, "statement");
assert_eq!(id.len(), 16);
assert_eq!(id, source_id("mod", span, "statement"));
assert_ne!(id, source_id("mod", span, "resource"));
}
}
+663
View File
@@ -0,0 +1,663 @@
//! Localhost Live reader.
//!
//! Minimal, loopback-only surface (RFC-VIEW-0001 §11.1). Only read APIs are
//! exposed until the explicit-run flow lands; every response carries a strict
//! CSP and the Host header is validated to blunt DNS-rebinding.
use crate::app::AppContext;
use crate::assets::AssetBundle;
use crate::cli::RuntimeOpts;
use crate::error::{ViewError, ViewResult};
use crate::presentation::PresentationModel;
use crate::project::SafeRelativePath;
use crate::render::{ReaderRenderer, RenderContext};
use crate::source_map::sha256_hex;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
const MAX_URL_BYTES: usize = 2048;
const MAX_QUERY_BYTES: usize = 4096;
pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult<i32> {
let address = format!("{}:{}", opts.host, opts.port);
let server = Server::http(&address).map_err(|err| ViewError::Io {
detail: format!("listen on {address}: {err}"),
})?;
let bound = server.server_addr().to_ip().ok_or_else(|| ViewError::Io {
detail: "server address is not an IP socket".to_string(),
})?;
let port = bound.port();
let display_host = match opts.host.as_str() {
"localhost" => "localhost".to_string(),
"::1" | "[::1]" => "[::1]".to_string(),
_ => "127.0.0.1".to_string(),
};
let url = format!("http://{display_host}:{port}/");
eprintln!("marqdo view: {url}");
eprintln!("root: {}", ctx.project().root().display());
eprintln!(
"{} .mq.md document(s). Ctrl+C to stop.",
ctx.project()
.list_documents()
.map(|docs| docs.len())
.unwrap_or(0)
);
if ctx.core_version().is_some() {
eprintln!(
"core: marqdo {} (Analysis v2, Trace v2)",
ctx.core_version().unwrap_or_default()
);
} else if let Some(note) = ctx.core_note() {
eprintln!("core: unavailable ({note})");
}
if !opts.no_open {
open_browser(&url);
}
let state = Arc::new(ServerState {
ctx,
csrf_token: random_token(),
renderer: ReaderRenderer::new(),
cache: Mutex::new(HashMap::new()),
allowed_hosts: allowed_hosts(port),
});
loop {
let request = match server.recv() {
Ok(request) => request,
Err(err) => {
eprintln!("view: accept failed: {err}");
continue;
}
};
let state = Arc::clone(&state);
std::thread::spawn(move || {
if let Err(err) = handle(&state, request) {
eprintln!("view request error: {err}");
}
});
}
}
struct ServerState {
ctx: AppContext,
csrf_token: String,
renderer: ReaderRenderer,
cache: Mutex<HashMap<String, CacheEntry>>,
allowed_hosts: Vec<String>,
}
struct CacheEntry {
source_digest: String,
model: PresentationModel,
}
impl ServerState {
/// Load one document, reusing a cached model only while the exact source
/// bytes are unchanged (no path-only cache identity, RFC §6.5).
fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
let digest = self.ctx.project().source_digest(relative)?;
if let Ok(cache) = self.cache.lock() {
if let Some(entry) = cache.get(relative.as_str()) {
if entry.source_digest == digest {
return Ok(entry.model.clone());
}
}
}
let model = self.ctx.load(relative)?;
if let Ok(mut cache) = self.cache.lock() {
if cache.len() < 64 {
cache.insert(
relative.as_str().to_string(),
CacheEntry {
source_digest: digest,
model: model.clone(),
},
);
}
}
Ok(model)
}
}
fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
let method = request.method().clone();
if !matches!(method, Method::Get | Method::Head) {
return respond_text(
request,
StatusCode(405),
"text/plain; charset=utf-8",
"method not allowed\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
}
let is_head = method == Method::Head;
if !host_is_allowed(&request, &state.allowed_hosts) {
return respond_text(
request,
StatusCode(400),
"text/plain; charset=utf-8",
"invalid Host header\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
}
let raw_url = request.url().to_string();
if raw_url.len() > MAX_URL_BYTES {
return respond_text(
request,
StatusCode(414),
"text/plain; charset=utf-8",
"request target too long\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
}
let (path_part, query) = split_url(&raw_url);
if query.len() > MAX_QUERY_BYTES {
return respond_text(
request,
StatusCode(414),
"text/plain; charset=utf-8",
"query too long\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
}
if let Some(hashed_name) = path_part.strip_prefix("/assets/") {
return serve_asset(request, hashed_name, is_head);
}
match path_part {
"/" | "/index.html" => {
let entry = state.ctx.project().entry().relative.clone();
match state.load(&entry) {
Ok(model) => serve_page(state, request, &model, is_head),
Err(err) => serve_error_page(request, &err, is_head),
}
}
"/file" => {
let Some(raw_path) = query_param(query, "path") else {
return respond_text(
request,
StatusCode(400),
"text/plain; charset=utf-8",
"missing path\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
};
let Some(decoded) = percent_decode(&raw_path) else {
return respond_text(
request,
StatusCode(400),
"text/plain; charset=utf-8",
"malformed path\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
};
let relative = match SafeRelativePath::parse(&decoded) {
Ok(relative) => relative,
Err(err) => {
return respond_text(
request,
StatusCode(403),
"text/plain; charset=utf-8",
format!("{}\n", err.code()).into_bytes(),
CacheKind::NoStore,
)
}
};
if state.ctx.project().read_source(&relative).is_err() {
return respond_text(
request,
StatusCode(404),
"text/plain; charset=utf-8",
"document not found\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
}
match state.load(&relative) {
Ok(model) => serve_page(state, request, &model, is_head),
Err(err) => serve_error_page(request, &err, is_head),
}
}
"/api/document" => {
let relative = match query_param(query, "path")
.and_then(|raw| percent_decode(&raw))
.map(|decoded| SafeRelativePath::parse(&decoded))
{
Some(Ok(relative)) => relative,
Some(Err(err)) => {
return respond_json_error(request, StatusCode(400), &err);
}
None => state.ctx.project().entry().relative.clone(),
};
match state.load(&relative) {
Ok(model) => serve_document_json(request, &model),
Err(err) => respond_json_error(request, StatusCode(500), &err),
}
}
"/api/health" => {
let documents = state
.ctx
.project()
.list_documents()
.map(|documents| documents.len())
.unwrap_or(0);
let health = serde_json::json!({
"schema": "marqdo.view-health",
"schema_version": 1,
"ok": true,
"view": {
"name": "marqdo-view",
"version": env!("CARGO_PKG_VERSION"),
},
"core": {
"version": state.ctx.core_version(),
},
"protocols": {
"tool": crate::version::TOOL_PROTOCOL,
"analysis": crate::version::ANALYSIS_PROTOCOL,
"trace": crate::version::TRACE_PROTOCOL,
},
"documents": documents,
"run_api": false,
});
respond_json(request, StatusCode(200), &health)
}
_ => respond_text(
request,
StatusCode(404),
"text/plain; charset=utf-8",
"not found\n".as_bytes().to_vec(),
CacheKind::NoStore,
),
}
}
fn serve_page(
state: &ServerState,
request: Request,
model: &PresentationModel,
is_head: bool,
) -> ViewResult<()> {
let ctx = RenderContext {
links: crate::render::LinkPolicy::LocalServer,
live: true,
csrf_token: Some(state.csrf_token.clone()),
run_available: false,
};
let page = state.renderer.render(model, &ctx);
respond_html(request, page.html.into_bytes(), is_head)
}
fn serve_error_page(request: Request, err: &ViewError, is_head: bool) -> ViewResult<()> {
let html = format!(
"<!DOCTYPE html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"/><title>Marqdo View · 错误</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/></head><body style=\"font:16px/1.6 system-ui,serif;background:#fcf9f5;color:#29251f;padding:2rem;max-width:46rem;margin:auto\"><h1>无法生成阅读页面</h1><p><code>{code}</code></p><p>{message}</p><p><a href=\"/\">返回入口</a></p></body></html>",
code = escape_html(err.code()),
message = escape_html(&err.to_string()),
);
respond_html(request, html.into_bytes(), is_head)
}
fn serve_document_json(request: Request, model: &PresentationModel) -> ViewResult<()> {
let semantic = model.semantic.as_ref();
let doc = serde_json::json!({
"schema": "marqdo.view-document",
"schema_version": 1,
"title": model.title,
"document": {
"relative_path": model.document.identity.relative_path,
"module_id": model.document.identity.module_id,
"source_sha256": sha256_hex(model.document.source.as_bytes()),
},
"source_status": model.source_status.data_value(),
"semantics_usable": model.source_status.semantics_usable(),
"analysis": semantic.map(|projection| serde_json::json!({
"digest": projection.analysis_digest,
"schema_version": crate::version::ANALYSIS_PROTOCOL,
"producer_version": projection.producer_version,
"project_root_id": projection.project_root_id,
"functions": projection.functions.len(),
"units": projection.units.len(),
"diagnostics": projection.diagnostics.len(),
})),
"outline": model.outline.iter().map(|entry| serde_json::json!({
"label": entry.label,
"anchor": entry.anchor,
"detail": entry.detail,
"kind": match entry.kind {
crate::presentation::OutlineKind::Function => "function",
crate::presentation::OutlineKind::Knowledge => "knowledge",
crate::presentation::OutlineKind::Section => "section",
},
})).collect::<Vec<_>>(),
"navigation": {
"documents": model.navigation.documents.iter().map(|doc| doc.as_str()).collect::<Vec<_>>(),
"welcome": model.navigation.welcome,
},
"note": "Read-only PresentationModel summary; the document was not executed.",
});
respond_json(request, StatusCode(200), &doc)
}
fn serve_asset(request: Request, hashed_name: &str, is_head: bool) -> ViewResult<()> {
let bundle = AssetBundle::get();
if hashed_name == bundle.hashed_css_name() {
return respond_asset(
request,
bundle.css_bytes().to_vec(),
"text/css; charset=utf-8",
is_head,
);
}
let Some(asset) = bundle.by_path(hashed_name) else {
return respond_text(
request,
StatusCode(404),
"text/plain; charset=utf-8",
"asset not found\n".as_bytes().to_vec(),
CacheKind::NoStore,
);
};
respond_asset(request, asset.bytes.to_vec(), asset.mime, is_head)
}
enum CacheKind {
NoStore,
Immutable,
}
fn respond_html(request: Request, body: Vec<u8>, is_head: bool) -> ViewResult<()> {
respond_with(
request,
StatusCode(200),
"text/html; charset=utf-8",
if is_head { Vec::new() } else { body },
CacheKind::NoStore,
)
}
fn respond_asset(
request: Request,
body: Vec<u8>,
content_type: &str,
is_head: bool,
) -> ViewResult<()> {
respond_with(
request,
StatusCode(200),
content_type,
if is_head { Vec::new() } else { body },
CacheKind::Immutable,
)
}
fn respond_json(request: Request, status: StatusCode, value: &serde_json::Value) -> ViewResult<()> {
let body = serde_json::to_vec_pretty(value).unwrap_or_else(|_| b"{}".to_vec());
respond_with(
request,
status,
"application/json; charset=utf-8",
body,
CacheKind::NoStore,
)
}
fn respond_json_error(request: Request, status: StatusCode, err: &ViewError) -> ViewResult<()> {
respond_json(request, status, &err.to_json())
}
fn respond_text(
request: Request,
status: StatusCode,
content_type: &str,
body: Vec<u8>,
cache: CacheKind,
) -> ViewResult<()> {
respond_with(request, status, content_type, body, cache)
}
fn respond_with(
request: Request,
status: StatusCode,
content_type: &str,
body: Vec<u8>,
cache: CacheKind,
) -> ViewResult<()> {
let length = body.len();
let mut response = Response::from_data(body).with_status_code(status);
if let Ok(header) = Header::from_bytes(&b"Content-Type"[..], content_type.as_bytes()) {
response.add_header(header);
}
for (name, value) in security_headers() {
if let Ok(header) = Header::from_bytes(name.as_bytes(), value.as_bytes()) {
response.add_header(header);
}
}
let cache_value = match cache {
CacheKind::NoStore => "no-store",
CacheKind::Immutable => "public, max-age=31536000, immutable",
};
if let Ok(header) = Header::from_bytes(&b"Cache-Control"[..], cache_value.as_bytes()) {
response.add_header(header);
}
let _ = length;
request.respond(response).map_err(|err| ViewError::Io {
detail: format!("write response: {err}"),
})
}
fn security_headers() -> Vec<(&'static str, &'static str)> {
vec![
(
"Content-Security-Policy",
"default-src 'none'; style-src 'self'; script-src 'self' file:; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; object-src 'none'",
),
("X-Content-Type-Options", "nosniff"),
("Referrer-Policy", "no-referrer"),
("X-Frame-Options", "DENY"),
("Cross-Origin-Resource-Policy", "same-origin"),
("Cross-Origin-Opener-Policy", "same-origin"),
]
}
fn split_url(url: &str) -> (&str, &str) {
match url.split_once('?') {
Some((path, query)) => (path, query),
None => (url, ""),
}
}
fn query_param(query: &str, key: &str) -> Option<String> {
for pair in query.split('&') {
let (name, value) = match pair.split_once('=') {
Some(parts) => parts,
None => (pair, ""),
};
if name == key {
return Some(value.to_string());
}
}
None
}
/// Decode `%XX` exactly once. Rejects malformed escapes, NUL, other control
/// characters and non-UTF-8 results (RFC §11.2.4).
fn percent_decode(raw: &str) -> Option<String> {
let bytes = raw.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
match bytes[index] {
b'%' => {
if index + 2 >= bytes.len() {
return None;
}
let high = hex_value(*bytes.get(index + 1)?)?;
let low = hex_value(*bytes.get(index + 2)?)?;
out.push(high * 16 + low);
index += 3;
}
b'+' => {
// Query strings here are paths, not form data: keep a literal +.
out.push(b'+');
index += 1;
}
byte => {
out.push(byte);
index += 1;
}
}
}
if out.contains(&0) || out.iter().any(|byte| *byte < 0x20 || *byte == 0x7f) {
return None;
}
String::from_utf8(out).ok()
}
fn hex_value(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn allowed_hosts(port: u16) -> Vec<String> {
vec![
format!("127.0.0.1:{port}"),
format!("localhost:{port}"),
format!("[::1]:{port}"),
]
}
fn host_is_allowed(request: &Request, allowed: &[String]) -> bool {
let mut host: Option<&str> = None;
for header in request.headers() {
if header.field.equiv("Host") {
host = Some(header.value.as_str());
break;
}
}
match host {
Some(value) => allowed
.iter()
.any(|allowed| allowed.eq_ignore_ascii_case(value)),
None => false,
}
}
fn escape_html(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for ch in raw.chars() {
match ch {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
_ => out.push(ch),
}
}
out
}
fn random_token() -> String {
#[cfg(unix)]
{
use std::io::Read as _;
if let Ok(mut file) = std::fs::File::open("/dev/urandom") {
let mut bytes = [0u8; 32];
if file.read_exact(&mut bytes).is_ok() {
return hex_encode(&bytes);
}
}
}
// Fallback: still unique per process/session, never a constant.
let material = format!(
"{}-{}-{:?}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0),
std::thread::current().id()
);
sha256_hex(material.as_bytes())
}
fn hex_encode(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
}
out
}
fn open_browser(url: &str) {
let program = if cfg!(target_os = "macos") {
"open"
} else if cfg!(target_os = "windows") {
"cmd"
} else {
"xdg-open"
};
let mut command = std::process::Command::new(program);
if cfg!(target_os = "windows") {
command.args(["/C", "start", ""]);
}
command.arg(url);
command
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
if command.spawn().is_err() {
eprintln!("view: could not open a browser; open {url} manually");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn percent_decode_is_single_pass_and_strict() {
assert_eq!(percent_decode("a%20b").as_deref(), Some("a b"));
assert_eq!(percent_decode("100%25").as_deref(), Some("100%"));
assert_eq!(percent_decode("a+b").as_deref(), Some("a+b"));
assert!(percent_decode("%2e%2e%2fsecret").is_some());
assert!(percent_decode("%zz").is_none());
assert!(percent_decode("%2").is_none());
assert!(percent_decode("a%00b").is_none());
assert!(percent_decode("%0a").is_none());
assert!(percent_decode("%ff").is_none());
}
#[test]
fn query_params_are_parsed_without_form_plus_rules() {
assert_eq!(query_param("path=a%2Fb", "path").as_deref(), Some("a%2Fb"));
assert_eq!(query_param("x=1&path=y", "path").as_deref(), Some("y"));
assert_eq!(query_param("", "path"), None);
}
#[test]
fn allowed_hosts_include_loopback_and_port() {
let hosts = allowed_hosts(7429);
assert!(hosts.contains(&"127.0.0.1:7429".to_string()));
assert!(hosts.contains(&"localhost:7429".to_string()));
assert!(!hosts.contains(&"127.0.0.1:7428".to_string()));
}
#[test]
fn random_token_is_64_hex_chars_and_unique() {
let a = random_token();
let b = random_token();
assert_eq!(a.len(), 64);
assert_ne!(a, b);
}
}
+28
View File
@@ -127,6 +127,34 @@ impl SourceIndex {
is_char_boundary(bytes, start) && is_char_boundary(bytes, end)
}
/// Byte offset of the start of a 1-based line.
pub fn line_start(&self, line: usize) -> Option<usize> {
if line == 0 {
return None;
}
self.line_starts.get(line - 1).copied()
}
/// Number of lines in the source.
pub fn line_count(&self) -> usize {
self.line_starts.len()
}
/// Text of a 1-based line without its trailing newline.
pub fn line_text<'a>(&self, source: &'a str, line: usize) -> Option<&'a str> {
let start = self.line_start(line)?;
let end = self.line_starts.get(line).copied().unwrap_or(self.len);
let bytes = source.as_bytes();
let mut end = end.min(bytes.len());
if end > start && bytes.get(end - 1) == Some(&b'\n') {
end -= 1;
if end > start && bytes.get(end - 1) == Some(&b'\r') {
end -= 1;
}
}
source.get(start..end)
}
/// 1-based line and 1-based byte column for a byte offset, clamped to the
/// file length. Column counts bytes, matching Core's presentation fields.
pub fn line_col(&self, byte: usize) -> (usize, usize) {
+87
View File
@@ -0,0 +1,87 @@
//! Asset provenance and integrity: the three reused legacy visual assets are
//! pinned by SHA-256 in `assets/licenses/ASSETS.md` and embedded by
//! `src/assets.rs` (ADR-0002).
use sha2::{Digest, Sha256};
fn sha256_hex(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
let mut out = String::with_capacity(64);
for byte in hasher.finalize() {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
}
out
}
#[test]
fn reused_assets_match_their_recorded_hashes() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
for (file, expected) in [
(
"assets/logo.svg",
"52b2338468c62a7da86178ecec86cbb7ea44a996cd1bc4275ebb56f16f2244fe",
),
(
"assets/blossom.webp",
"901fd6b37ebb20d1dfc3bf4d265a063308605350fd317e41914fa35b06f46e00",
),
(
"assets/feather.webp",
"fbd787174be1e8027ae4661b99f7f2cc01b824d8fc875a1d2d39cbd0c052e5de",
),
] {
let bytes =
std::fs::read(root.join(file)).unwrap_or_else(|err| panic!("read {file}: {err}"));
assert_eq!(sha256_hex(&bytes), expected, "{file} digest changed");
}
let licenses = std::fs::read_to_string(root.join("assets/licenses/ASSETS.md")).unwrap();
for expected in [
"52b2338468c62a7da86178ecec86cbb7ea44a996cd1bc4275ebb56f16f2244fe",
"901fd6b37ebb20d1dfc3bf4d265a063308605350fd317e41914fa35b06f46e00",
"fbd787174be1e8027ae4661b99f7f2cc01b824d8fc875a1d2d39cbd0c052e5de",
"Apache-2.0",
] {
assert!(licenses.contains(expected), "ASSETS.md misses {expected}");
}
}
#[test]
fn embedded_asset_bundle_matches_disk_and_has_one_theme() {
let bundle = marqdo_view::assets::AssetBundle::get();
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let css = std::fs::read(root.join("assets/reader.css")).unwrap();
assert_eq!(sha256_hex(&css), bundle.css().sha256);
let js = std::fs::read(root.join("assets/reader.js")).unwrap();
assert_eq!(sha256_hex(&js), bundle.js().sha256);
assert_eq!(
bundle
.all()
.iter()
.filter(|asset| asset.extension == "css" || asset.extension == "js")
.count(),
2
);
}
#[test]
fn theme_has_one_token_layer_and_no_legacy_skin() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let css = std::fs::read_to_string(root.join("assets/reader.css")).unwrap();
assert_eq!(css.matches("@layer tokens").count(), 1);
assert!(css.contains(
"@layer reset, tokens, layout, typography, semantics, overlays, interactions, responsive;"
));
for banned in ["notebook-page", "reader-page", "legacy.css", "new.css"] {
assert!(!css.contains(banned), "legacy skin marker {banned} in CSS");
}
assert!(
!css.contains("!important"),
"the theme must not rely on !important overrides"
);
// No remote font/CDN requests.
for banned in ["@font-face", "fonts.googleapis", "https://"] {
assert!(!css.contains(banned), "remote resource marker {banned}");
}
}
+22 -9
View File
@@ -57,17 +57,30 @@ fn non_loopback_bind_is_refused_by_default() {
}
#[test]
fn browse_without_core_reports_core_missing() {
// Browse is not implemented yet, but the reader must still fail with a
// stable View code and exit class rather than pretending to work.
fn browse_on_missing_path_fails_without_starting_a_server() {
let cwd = std::env::current_dir().unwrap();
let output = run_view(&[], &cwd, &clean_env());
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "stderr: {stderr}");
assert!(
stderr.contains("view.unsupported") || stderr.contains("view.core_missing"),
"unexpected diagnostic: {stderr}"
let output = run_view(
&["definitely-missing.mq.md", "--no-open"],
&cwd,
&clean_env(),
);
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("view.io"));
}
#[test]
fn degradation_without_core_keeps_prose_readable() {
// The reader must degrade to prose-only with an explicit status, never
// invent semantic annotations or a fake run state.
let project = common::TempProject::new("cli-degrade-no-core");
project.marqdo_project("# @knowledge 标题\n\n正文 **加粗**。\n");
let context = marqdo_view::app::AppContext::open(&project.dir, None).unwrap();
let relative = context.project().entry().relative.clone();
let model = context.load(&relative).unwrap();
assert_eq!(model.source_status.data_value(), "core-unavailable");
assert!(model.semantic.is_none());
assert!(model.document.plain_text().contains("正文"));
assert!(model.status_note.is_some());
}
#[test]
+10 -1
View File
@@ -13,7 +13,11 @@ pub fn view_bin() -> &'static str {
}
pub fn temp_root(name: &str) -> PathBuf {
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name);
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let seq = NEXT.fetch_add(1, Ordering::Relaxed);
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
.join(format!("{name}-{}-{seq}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("create test temp dir");
dir
@@ -79,6 +83,7 @@ case "$1" in
;;
check)
if [ -f "$dir/check_stderr" ]; then cat "$dir/check_stderr" >&2; fi
if [ -f "$dir/check_json" ]; then cat "$dir/check_json"; fi
emit=""
prev=""
for a in "$@"; do
@@ -126,6 +131,10 @@ esac
std::fs::write(self.dir.join("check_stderr"), stderr).expect("write stderr");
}
pub fn set_check_json(&self, json: &str) {
std::fs::write(self.dir.join("check_json"), json).expect("write check json");
}
pub fn set_analysis(&self, analysis: &str) {
std::fs::write(self.dir.join("analysis.json"), analysis).expect("write analysis");
}
+50 -20
View File
@@ -7,7 +7,7 @@
mod common;
use common::{minimal_analysis, sha256_hex, FakeCore, TempProject};
use marqdo_view::core_client::{CheckOptions, CoreClient, RunOptions};
use marqdo_view::core_client::{CheckOptions, CheckResponse, CoreClient, RunOptions};
use marqdo_view::project::Project;
fn fixture(name: &str) -> (TempProject, FakeCore) {
@@ -27,9 +27,11 @@ fn check_returns_exact_analysis_bytes_and_digest() {
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let output = client
.check(&project, &entry, &CheckOptions::default())
.unwrap();
let output = expect_check_ok(
client
.check(&project, &entry, &CheckOptions::default())
.unwrap(),
);
assert_eq!(output.analysis_bytes, analysis.as_bytes());
assert_eq!(output.analysis_sha256, sha256_hex(analysis.as_bytes()));
@@ -52,16 +54,18 @@ fn check_refs_is_forwarded_as_a_stricter_flag() {
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
client
.check(
&project,
&entry,
&CheckOptions {
refs: true,
timeout: None,
},
)
.unwrap();
expect_check_ok(
client
.check(
&project,
&entry,
&CheckOptions {
refs: true,
timeout: None,
},
)
.unwrap(),
);
assert!(core.last_args().contains(&"--refs".to_string()));
}
@@ -72,13 +76,12 @@ fn check_failure_preserves_core_stderr_and_code() {
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let err = client
let response = client
.check(&project, &entry, &CheckOptions::default())
.unwrap_err();
assert_eq!(err.code(), "view.analysis_failed");
assert_eq!(err.exit_code(), 1);
let text = err.to_string();
assert!(text.contains("sem.unclosed_control"), "{text}");
.unwrap();
assert!(!response.success);
assert_eq!(response.exit_code, 1);
assert!(response.stderr.contains("sem.unclosed_control"));
}
#[test]
@@ -193,6 +196,33 @@ fn missing_emit_after_success_is_an_analysis_failure() {
assert_eq!(err.code(), "view.analysis_failed");
}
fn expect_check_ok(response: CheckResponse) -> marqdo_view::core_client::CheckOutput {
assert!(response.success, "check failed: {:?}", response.diagnostics);
response.analysis.expect("analysis on success")
}
#[test]
fn failed_check_normalizes_diagnostics_without_absolute_paths() {
let (project, core) = fixture("check_diagnostics");
core.set_check(1, "");
core.set_check_json(
r#"{"command":"check","success":false,"errors":1,"diagnostics":[{"code":"sem.unclosed_control","column":1,"file":"/home/secret/project/index.mq.md","hints":[],"line":5,"message":"`if` is not closed by `end`","module":"root:fixture@0.1.0::index.mq.md","severity":"error"}]}"#,
);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let response = client
.check(&project, &entry, &CheckOptions::default())
.unwrap();
assert!(!response.success);
assert_eq!(response.diagnostics.len(), 1);
assert_eq!(response.diagnostics[0].code, "sem.unclosed_control");
assert_eq!(response.diagnostics[0].line, Some(5));
// The raw absolute `file` field is not part of the normalized type at all.
let rendered = serde_json::to_string(&response.diagnostics).unwrap();
assert!(!rendered.contains("/home/secret"), "{rendered}");
}
#[test]
fn cli_verify_end_to_end_against_fake_core() {
let (project, core) = fixture("verify_cli");
+29
View File
@@ -0,0 +1,29 @@
# Protocol goldens
These Analysis v2 files were emitted by the **frozen** `marqdo` CLI release
binary, not hand-written:
| Binary | SHA-256 |
|---|---|
| `marqdo 3.0.0-beta.1` | `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f` |
| CLI source SHA | `2c7c4f31e7a388d3fcfa717a77067e696ed13854` |
Command shape used for every golden:
```bash
"$MARQDO_BIN" check <example> --emit tests/golden/analysis-v2/<name>.json
```
| Golden | Input |
|---|---|
| `mixed-modes.json` | `examples/mixed-modes/index.mq.md` |
| `control-flow.json` | `examples/control-flow/index.mq.md` |
| `tables-math.json` | `examples/tables-math/index.mq.md` |
| `welcome.json` | `examples/welcome/00-welcome.mq.md` |
`tools/gen-golden.sh` regenerates them from a frozen binary. If an example's
bytes change, its `source_digest` changes too and the tests will fail until the
golden is regenerated — that is intentional evidence, not a test bug.
`examples/diagnostics/index.mq.md` is deliberately invalid and has **no**
golden; its failure path is covered with `check --json` output.
File diff suppressed because it is too large. Load diff
+278
View File
@@ -0,0 +1,278 @@
{
"diagnostics": [],
"modules": [
{
"calls": [],
"functions": [
{
"body": [
{
"arms": [
{
"body": [
{
"kind": "assign",
"span": {
"end": 422,
"start": 406
},
"target": "result",
"value": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "n",
"span": {
"end": 417,
"start": 416
}
},
"op": "mul",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "2"
},
"span": {
"end": 421,
"start": 416
}
}
},
{
"kind": "return",
"span": {
"end": 439,
"start": 424
},
"value": {
"kind": "variable",
"name": "result",
"span": {
"end": 438,
"start": 432
}
}
}
],
"condition": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "n",
"span": {
"end": 398,
"start": 397
}
},
"op": "gt",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "0"
},
"span": {
"end": 402,
"start": 397
}
},
"condition_span": {
"end": 404,
"start": 392
},
"span": {
"end": 404,
"start": 392
}
},
{
"body": [
{
"kind": "return",
"span": {
"end": 461,
"start": 451
},
"value": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "0"
}
}
],
"condition": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "bool",
"value": true
},
"condition_span": {
"end": 404,
"start": 392
},
"span": {
"end": 404,
"start": 392
}
}
],
"kind": "branch",
"span": {
"end": 404,
"start": 392
}
}
],
"effects": [
"unknown"
],
"heading_span": {
"end": 259,
"start": 246
},
"id": "root:mixed-modes@0.1.0::index.mq.md::演示.main",
"local_name": "main",
"namespace": "演示",
"signature": {
"kind": "explicit",
"params": [
{
"default": null,
"name": "n",
"required": true,
"span": {
"end": 274,
"start": 268
},
"type": "Int"
}
]
},
"span": {
"end": 470,
"start": 246
},
"unit_id": "root:mixed-modes@0.1.0::index.mq.md#演示/main"
}
],
"id": "root:mixed-modes@0.1.0::index.mq.md",
"imports": [],
"package_instance_id": "root:mixed-modes@0.1.0",
"references": [],
"relative_path": "index.mq.md",
"resources": [],
"source_digest": "c5fed57a716e06a29b669c334d475ec03bf08442e27983451ec8dd791dc999ea",
"units": [
{
"function": null,
"id": "root:mixed-modes@0.1.0::index.mq.md#",
"kind": "root",
"level": 0,
"name": "",
"span": {
"end": 470,
"start": 0
}
},
{
"function": null,
"id": "root:mixed-modes@0.1.0::index.mq.md#计算笔记",
"kind": "namespace",
"level": 1,
"name": "计算笔记",
"span": {
"end": 25,
"start": 0
}
},
{
"function": null,
"id": "root:mixed-modes@0.1.0::index.mq.md#计算笔记/算法说明",
"kind": "knowledge",
"level": 2,
"name": "算法说明",
"span": {
"end": 149,
"start": 123
}
},
{
"function": null,
"id": "root:mixed-modes@0.1.0::index.mq.md#演示",
"kind": "namespace",
"level": 1,
"name": "演示",
"span": {
"end": 244,
"start": 230
}
},
{
"function": "root:mixed-modes@0.1.0::index.mq.md::演示.main",
"id": "root:mixed-modes@0.1.0::index.mq.md#演示/main",
"kind": "function",
"level": 2,
"name": "main",
"span": {
"end": 259,
"start": 246
}
},
{
"function": null,
"id": "root:mixed-modes@0.1.0::index.mq.md#演示/main/用法",
"kind": "section",
"level": 3,
"name": "用法",
"span": {
"end": 300,
"start": 279
}
},
{
"function": "root:mixed-modes@0.1.0::index.mq.md::演示.main",
"id": "root:mixed-modes@0.1.0::index.mq.md#演示/main/计算",
"kind": "section",
"level": 3,
"name": "计算",
"span": {
"end": 390,
"start": 374
}
}
]
}
],
"producer": {
"markdown_profile": "marqdo.md.v1",
"name": "marqdo",
"version": "3.0.0-beta.1"
},
"project": {
"identity_kind": "manifest",
"lock_digest": "",
"root_id": "root:mixed-modes@0.1.0",
"stdlib": {
"digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"version": "0.1.0"
}
},
"schema": "marqdo.analysis",
"schema_version": 2
}
+108
View File
@@ -0,0 +1,108 @@
{
"diagnostics": [],
"modules": [
{
"calls": [],
"functions": [],
"id": "root:tables-math@0.1.0::index.mq.md",
"imports": [],
"package_instance_id": "root:tables-math@0.1.0",
"references": [
{
"source": "root:tables-math@0.1.0::index.mq.md",
"span": {
"end": 403,
"start": 354
},
"state": "external",
"target_module": null,
"target_unit": null,
"url": "https://github.com/cflmy/marqdo-cli"
}
],
"relative_path": "index.mq.md",
"resources": [
{
"content_digest": "2820951a377c18ce3e89093ca7c31c204b1196a7e571781c6080f8207524a8dc",
"display": false,
"id": "root:tables-math@0.1.0::index.mq.md#resource:formula-1",
"kind": "formula",
"language": null,
"module_id": "root:tables-math@0.1.0::index.mq.md",
"span": {
"end": 164,
"start": 154
},
"unit_id": "root:tables-math@0.1.0::index.mq.md#表格、公式与惰性资源"
},
{
"content_digest": "8b1e8a7ed159e8223af79e768681907870ae7143f0b16001091377f9ff018db2",
"display": true,
"id": "root:tables-math@0.1.0::index.mq.md#resource:formula-2",
"kind": "formula",
"language": null,
"module_id": "root:tables-math@0.1.0::index.mq.md",
"span": {
"end": 222,
"start": 181
},
"unit_id": "root:tables-math@0.1.0::index.mq.md#表格、公式与惰性资源"
},
{
"content_digest": "a0d49e456637468d7f594f4e2bb513321875855c1fe85d28e0ca62f1e9180d15",
"id": "root:tables-math@0.1.0::index.mq.md#resource:code-1",
"kind": "code",
"language": "python",
"module_id": "root:tables-math@0.1.0::index.mq.md",
"span": {
"end": 280,
"start": 224
},
"unit_id": "root:tables-math@0.1.0::index.mq.md#表格、公式与惰性资源"
}
],
"source_digest": "66ce180252d201ff0f3f831d47f7a58d7f6804cb9655898cc80ef6d2262f1ce6",
"units": [
{
"function": null,
"id": "root:tables-math@0.1.0::index.mq.md#",
"kind": "root",
"level": 0,
"name": "",
"span": {
"end": 406,
"start": 0
}
},
{
"function": null,
"id": "root:tables-math@0.1.0::index.mq.md#表格、公式与惰性资源",
"kind": "namespace",
"level": 1,
"name": "表格、公式与惰性资源",
"span": {
"end": 43,
"start": 0
}
}
]
}
],
"producer": {
"markdown_profile": "marqdo.md.v1",
"name": "marqdo",
"version": "3.0.0-beta.1"
},
"project": {
"identity_kind": "manifest",
"lock_digest": "",
"root_id": "root:tables-math@0.1.0",
"stdlib": {
"digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"version": "0.1.0"
}
},
"schema": "marqdo.analysis",
"schema_version": 2
}
+69
View File
@@ -0,0 +1,69 @@
{
"diagnostics": [],
"modules": [
{
"calls": [],
"functions": [],
"id": "root:welcome-demo@0.1.0::00-welcome.mq.md",
"imports": [],
"package_instance_id": "root:welcome-demo@0.1.0",
"references": [
{
"source": "root:welcome-demo@0.1.0::00-welcome.mq.md",
"span": {
"end": 536,
"start": 507
},
"state": "resolved",
"target_module": "root:welcome-demo@0.1.0::guide.mq.md",
"target_unit": null,
"url": "./guide.mq.md"
}
],
"relative_path": "00-welcome.mq.md",
"resources": [],
"source_digest": "879215bf0dc432b78924800a08eac37d353a9694652c5542294f4ce7fe6da173",
"units": [
{
"function": null,
"id": "root:welcome-demo@0.1.0::00-welcome.mq.md#",
"kind": "root",
"level": 0,
"name": "",
"span": {
"end": 659,
"start": 0
}
},
{
"function": null,
"id": "root:welcome-demo@0.1.0::00-welcome.mq.md#欢迎来到 Marqdo",
"kind": "namespace",
"level": 1,
"name": "欢迎来到 Marqdo",
"span": {
"end": 32,
"start": 0
}
}
]
}
],
"producer": {
"markdown_profile": "marqdo.md.v1",
"name": "marqdo",
"version": "3.0.0-beta.1"
},
"project": {
"identity_kind": "manifest",
"lock_digest": "",
"root_id": "root:welcome-demo@0.1.0",
"stdlib": {
"digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"version": "0.1.0"
}
},
"schema": "marqdo.analysis",
"schema_version": 2
}
+230
View File
@@ -0,0 +1,230 @@
//! Live server smoke tests over a raw TCP HTTP/1.1 client (no extra deps).
//! The server is a real child process so startup, URL output, routing and
//! security headers are all exercised end to end.
mod common;
use common::{run_view, FakeCore};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpStream;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
struct LiveServer {
child: Child,
port: u16,
_core: FakeCore,
}
impl Drop for LiveServer {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn start_server() -> LiveServer {
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT: AtomicUsize = AtomicUsize::new(0);
let seq = NEXT.fetch_add(1, Ordering::Relaxed);
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let core = FakeCore::new(&format!("live-core-{seq}"));
let golden = std::fs::read(repo_root.join("tests/golden/analysis-v2/welcome.json")).unwrap();
core.set_analysis(std::str::from_utf8(&golden).unwrap());
let mut child = Command::new(common::view_bin())
.current_dir(&repo_root)
.args([
"examples/welcome",
"--port",
"0",
"--no-open",
"--marqdo-bin",
])
.arg(&core.script)
.env_remove("MARQDO_BIN")
.env_remove("MARQDO_TOOL_PROTOCOL")
.env_remove("MARQDO_PROTOCOL_ANALYSIS")
.env_remove("MARQDO_PROTOCOL_TRACE")
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.expect("spawn marqdo-view");
let stderr = child.stderr.take().expect("piped stderr");
let mut reader = BufReader::new(stderr);
let deadline = Instant::now() + Duration::from_secs(10);
let mut url: Option<String> = None;
while Instant::now() < deadline {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
break;
}
if let Some(rest) = line.trim().strip_prefix("marqdo view: ") {
url = Some(rest.to_string());
break;
}
}
let url = url.expect("server printed its URL");
let port: u16 = url
.trim_end_matches('/')
.rsplit(':')
.next()
.expect("port in url")
.parse()
.expect("numeric port");
// Keep draining stderr so the child never blocks on a full pipe.
std::thread::spawn(move || {
let mut sink = String::new();
let _ = reader.read_to_string(&mut sink);
});
LiveServer {
child,
port,
_core: core,
}
}
struct HttpResponse {
status: u16,
headers: String,
body: String,
}
fn http_get(port: u16, host: Option<&str>, path: &str) -> HttpResponse {
let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect");
let host = host
.map(str::to_string)
.unwrap_or_else(|| format!("127.0.0.1:{port}"));
let request =
format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nAccept: */*\r\n\r\n");
stream.write_all(request.as_bytes()).expect("write request");
let mut raw = Vec::new();
stream.read_to_end(&mut raw).expect("read response");
let text = String::from_utf8_lossy(&raw).to_string();
let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, ""));
let status = head
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.and_then(|code| code.parse().ok())
.unwrap_or(0);
HttpResponse {
status,
headers: head.to_string(),
body: body.to_string(),
}
}
#[test]
fn live_server_serves_pages_assets_and_health() {
let server = start_server();
let page = http_get(server.port, None, "/");
assert_eq!(page.status, 200);
assert!(page.headers.contains("Content-Type: text/html"));
assert!(page.headers.contains("Content-Security-Policy"));
assert!(page.headers.contains("X-Content-Type-Options: nosniff"));
assert!(page.body.contains("mq-reader"));
assert!(page.body.contains("欢迎来到 Marqdo"));
assert!(!page.body.contains("data-live=\"false\""));
// CSRF token meta is present for the future explicit-run API.
assert!(page.body.contains("mq-csrf-token"));
let css_path = page
.body
.split("href=\"/assets/")
.nth(1)
.and_then(|rest| rest.split('"').next())
.expect("css link");
let css = http_get(server.port, None, &format!("/assets/{css_path}"));
assert_eq!(css.status, 200);
assert!(css.headers.contains("text/css"));
assert!(css.body.contains("@layer tokens"));
assert!(css.headers.contains("immutable"));
let health = http_get(server.port, None, "/api/health");
assert_eq!(health.status, 200);
assert!(health.body.contains("\"schema\": \"marqdo.view-health\""));
assert!(health.body.contains("\"analysis\": 2"));
let document = http_get(server.port, None, "/file?path=guide.mq.md");
assert_eq!(document.status, 200);
assert!(document.body.contains("阅读指南"));
}
#[test]
fn live_server_rejects_dns_rebinding_and_path_escape() {
let server = start_server();
let bad_host = http_get(server.port, Some("attacker.example"), "/");
assert_eq!(bad_host.status, 400);
for path in [
"/file?path=../secret.mq.md",
"/file?path=%2e%2e%2fsecret.mq.md",
"/file?path=/etc/passwd",
"/file?path=..%2f..%2fetc%2fpasswd",
] {
let response = http_get(server.port, None, path);
assert!(
response.status == 403 || response.status == 404,
"path {path} returned {}",
response.status
);
}
let missing = http_get(server.port, None, "/file?path=missing.mq.md");
assert_eq!(missing.status, 404);
let unknown = http_get(server.port, None, "/api/run");
assert_eq!(unknown.status, 404);
}
#[test]
fn live_server_rejects_unknown_methods_and_bad_assets() {
let server = start_server();
// POST is not exposed yet.
let mut stream = TcpStream::connect(("127.0.0.1", server.port)).expect("connect");
let request = format!(
"POST /api/run HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}",
server.port
);
stream.write_all(request.as_bytes()).unwrap();
let mut raw = Vec::new();
stream.read_to_end(&mut raw).unwrap();
let text = String::from_utf8_lossy(&raw);
assert!(text.starts_with("HTTP/1.1 405"), "{text}");
let bad_asset = http_get(server.port, None, "/assets/../../etc/passwd");
assert_eq!(bad_asset.status, 404);
}
#[test]
fn cli_verify_output_contract_still_holds_for_installed_style_invocation() {
// Regression guard: `view verify` must remain a pure static check.
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let core = FakeCore::new("verify-core-contract");
let golden = std::fs::read(repo_root.join("tests/golden/analysis-v2/welcome.json")).unwrap();
core.set_analysis(std::str::from_utf8(&golden).unwrap());
let output = run_view(
&[
"verify",
"examples/welcome/00-welcome.mq.md",
"--json",
"--marqdo-bin",
core.script.to_str().unwrap(),
],
&repo_root,
&[("MARQDO_BIN", None)],
);
assert_eq!(
output.status.code(),
Some(0),
"stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let json: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(json["result"], "PASS");
assert_eq!(json["executed"], false);
assert_eq!(json["analysis"]["schema_version"], 2);
}
+2 -2
View File
@@ -135,8 +135,8 @@ fn exactly_one_reader_theme_and_script_entry() {
let mut js = Vec::new();
collect_files(&assets, "css", &mut css);
collect_files(&assets, "js", &mut js);
assert!(css.len() <= 1, "more than one CSS entry: {css:?}");
assert!(js.len() <= 1, "more than one JS entry: {js:?}");
assert_eq!(css.len(), 1, "exactly one CSS entry: {css:?}");
assert_eq!(js.len(), 1, "exactly one JS entry: {js:?}");
for path in &css {
assert_eq!(
path.file_name().and_then(|n| n.to_str()),
+250
View File
@@ -0,0 +1,250 @@
//! Rendering contract tests: one renderer, safe Markdown, exact source view,
//! verified semantic annotations and Live/Export link differences.
mod common;
use marqdo_view::document::{DocumentIdentity, DocumentModel};
use marqdo_view::presentation::{self, BuildInput, Navigation, SourceStatus};
use marqdo_view::project::{Project, SafeRelativePath, ViewConfig};
use marqdo_view::render::{ReaderRenderer, RenderContext};
use marqdo_view::semantic;
fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String) {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("examples")
.join(name);
let project = Project::open(&root).unwrap();
let entry = project.entry().relative.clone();
let source = project.read_source_text(&entry).unwrap();
let document = DocumentModel::parse(source.clone(), DocumentIdentity::placeholder(&entry));
let golden_name = name;
let golden = std::fs::read(
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests/golden/analysis-v2")
.join(format!("{golden_name}.json")),
)
.unwrap_or_else(|err| panic!("missing golden for {name}: {err}"));
let verified =
semantic::verify_analysis(&golden, &source, &document.source_index, entry.as_str())
.unwrap_or_else(|err| panic!("golden does not verify for {name}: {err}"));
let config = ViewConfig::load(project.root()).unwrap_or_default();
let navigation = Navigation::from_project(&project, &config, &entry);
let model = presentation::build(BuildInput {
document,
analysis: Some(&verified),
status: SourceStatus::StaticOk,
status_note: None,
diagnostics: Vec::new(),
navigation,
core_version: Some("3.0.0-beta.1".to_string()),
});
(model, source)
}
fn render_live(model: &marqdo_view::presentation::PresentationModel) -> String {
ReaderRenderer::new()
.render(model, &RenderContext::live())
.html
}
fn render_static(model: &marqdo_view::presentation::PresentationModel, depth: usize) -> String {
ReaderRenderer::new()
.render(model, &RenderContext::static_site(depth))
.html
}
fn heading_ids(html: &str) -> Vec<String> {
let mut ids = Vec::new();
for part in html.split("<h").skip(1) {
let Some(after_tag) = part.split_once(' ') else {
continue;
};
let rest = after_tag.1;
if let Some(id_part) = rest.split_once("id=\"") {
if let Some((id, _)) = id_part.1.split_once('"') {
ids.push(id.to_string());
}
}
}
ids
}
#[test]
fn page_has_exactly_one_theme_and_one_script() {
let (model, _) = example("mixed-modes");
let html = render_live(&model);
assert_eq!(html.matches("<link rel=\"stylesheet\"").count(), 1);
assert_eq!(
html.matches("<script").count(),
1,
"no inline scripts allowed"
);
assert!(html.contains("<script defer src=\"/assets/reader."));
assert!(html.contains("Content-Security-Policy"));
assert!(html.contains("default-src 'none'"));
assert!(html.contains("data-live=\"true\""));
// The one source of prose is the Markdown document itself.
assert!(html.contains("计算笔记"));
assert!(html.contains("静态阅读"));
}
#[test]
fn semantic_annotations_come_from_analysis_and_are_unique() {
let (model, _) = example("mixed-modes");
let html = render_live(&model);
assert!(html.contains("data-source-status=\"static-ok\""));
assert!(html.contains("data-statement-kind=\"return\""));
assert!(html.contains("data-statement-kind=\"branch\""));
assert!(html.contains("data-statement-kind=\"assign\""));
assert!(html.contains("mq-mode-badge"));
assert!(html.contains("EXEC"));
assert!(html.contains("params(n: Int)"));
let ids = heading_ids(&html);
let mut deduped = ids.clone();
deduped.sort();
deduped.dedup();
assert_eq!(ids.len(), deduped.len(), "duplicate heading ids: {ids:?}");
}
#[test]
fn tables_math_and_code_are_inert_and_readable() {
let (model, source) = example("tables-math");
let html = render_live(&model);
assert!(html.contains("<table>"));
assert!(html.contains("mq-table-wrap"));
assert!(html.contains("mq-math-block"));
assert!(html.contains("代码围栏永远是惰性资源"));
assert!(html.contains("mq-codeblock"));
// Inert resources are never executed: no run controls are enabled.
assert!(html.contains("data-live=\"true\""));
assert!(!html.contains("RUNNING"));
// Source is preserved exactly in the textarea (escaped only).
assert!(source.contains("```python"));
assert!(html.contains("mq-raw-source"));
}
#[test]
fn welcome_hero_only_when_configured() {
let (welcome, _) = example("welcome");
let html = render_live(&welcome);
assert!(welcome.navigation.welcome);
assert!(html.contains("mq-welcome"));
assert!(html.contains("WELCOME TO"));
assert!(html.contains("代码即文档 · 文档即知识库 · 知识即可执行"));
let (ordinary, _) = example("tables-math");
let html = render_live(&ordinary);
assert!(!ordinary.navigation.welcome);
assert!(!html.contains("mq-welcome"));
}
#[test]
fn live_and_static_share_content_but_rewrite_links() {
let (model, _) = example("welcome");
let live = render_live(&model);
let static_site = render_static(&model, 0);
assert!(live.contains("/file?path=guide.mq.md"));
assert!(static_site.contains("pages/guide.mq.md.html"));
assert!(!static_site.contains("/file?path="));
// Same prose and semantics.
for needle in ["欢迎来到 Marqdo", "代码即文档", "mq-document"] {
assert!(live.contains(needle));
assert!(static_site.contains(needle));
}
// Assets are relative from the site root.
assert!(static_site.contains("href=\"assets/reader."));
assert!(live.contains("href=\"/assets/reader."));
}
#[test]
fn static_pages_use_parent_relative_assets_and_links() {
let (model, _) = example("welcome");
let html = render_static(&model, 1);
assert!(html.contains("href=\"../assets/reader."));
assert!(html.contains("../pages/guide.mq.md.html"));
}
#[test]
fn malicious_markdown_cannot_inject_markup_or_scripts() {
let source = r#"# 安全测试
<script>alert('xss')</script>
<img src=x onerror="alert(1)">
[危险链接](javascript:alert(1))
[数据链接](data:text/html;base64,PHNjcmlwdD4=)
[正常链接](https://example.com/ok)
<svg onload="alert(1)"></svg>
正常 **正文** 与 `代码`。
"#
.to_string();
let document = DocumentModel::parse(
source,
DocumentIdentity {
project_root_id: String::new(),
module_id: String::new(),
relative_path: "index.mq.md".into(),
source_sha256: String::new(),
},
);
let project = Project::open(
&std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/tables-math"),
)
.unwrap();
let config = ViewConfig::default();
let navigation = Navigation::from_project(
&project,
&config,
&SafeRelativePath::parse("index.mq.md").unwrap(),
);
let model = presentation::build(BuildInput {
document,
analysis: None,
status: SourceStatus::CoreUnavailable,
status_note: Some("test".into()),
diagnostics: Vec::new(),
navigation,
core_version: None,
});
let html = render_live(&model);
assert!(!html.contains("<script>alert"));
assert!(!html.contains("<img src=x"));
assert!(!html.contains("<svg onload"));
assert!(!html.contains("href=\"javascript:"));
assert!(!html.contains("href=\"data:text/html"));
// Ordinary page chrome (logo, dock icons) is allowed, but no tag carries an
// attacker-supplied event handler.
assert!(!html.contains("onerror=\"") && !html.contains("onload=\""));
// The exact source is still available in the source pane, safely escaped.
assert!(html.contains("&lt;script&gt;alert"));
assert!(html.contains("https://example.com/ok"));
assert!(html.contains("已忽略原始 HTML"));
assert!(html.contains("正文"));
}
#[test]
fn rendering_is_deterministic() {
let (model, _) = example("control-flow");
let first = render_live(&model);
let second = render_live(&model);
assert_eq!(first, second);
}
#[test]
fn run_controls_are_explicitly_unavailable_before_pr04() {
let (model, _) = example("control-flow");
let html = render_live(&model);
assert!(html.contains("data-live=\"true\""));
assert!(
html.contains("data-disabled=\"true\"") || html.contains("aria-disabled"),
"run control must have an explicit disabled marker"
);
// No fake RUNNING/SUCCEEDED marker on a freshly opened document.
assert!(!html.contains("data-run-state=\"running\""));
assert!(!html.contains("data-run-state=\"succeeded\""));
}
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Regenerate committed Analysis v2 goldens from the frozen CLI release binary.
#
# Usage: MARQDO_BIN=/abs/path/marqdo tools/gen-golden.sh
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"
: "${MARQDO_BIN:?set MARQDO_BIN to the frozen marqdo binary}"
if [[ ! -x "$MARQDO_BIN" ]]; then
echo "error: MARQDO_BIN is not executable: $MARQDO_BIN" >&2
exit 1
fi
echo "golden core sha256: $(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
out="tests/golden/analysis-v2"
mkdir -p "$out"
"$MARQDO_BIN" check examples/mixed-modes/index.mq.md --emit "$out/mixed-modes.json"
"$MARQDO_BIN" check examples/control-flow/index.mq.md --emit "$out/control-flow.json"
"$MARQDO_BIN" check examples/tables-math/index.mq.md --emit "$out/tables-math.json"
"$MARQDO_BIN" check examples/welcome/00-welcome.mq.md --emit "$out/welcome.json"
# Diagnostics fixture must fail: verify the failure shape stays as expected.
if "$MARQDO_BIN" check examples/diagnostics/index.mq.md --json >/dev/null 2>&1; then
echo "error: examples/diagnostics unexpectedly passed check" >&2
exit 1
fi
echo "goldens: PASS"