feat(PR-04): explicit-run flow, Trace v2 validation and run visualization
- trace.rs: strict Trace v2 validation (schema/product/root_id/analysis_digest, known module ids, increasing seq, span bounds) + run states and anchor summaries - POST /api/run: explicit confirm, CSRF token, Origin/Host checks, JSON limits, pure-only mode, one active run, process-group timeout, in-memory run cache - POST /api/clear-run: session cache cleanup without touching project files - server-rendered run panel (escaped stdout/stderr, Core error code, public final value only, capped event list, truncation/stale/failure states) and inline chips anchored to real statement spans; no per-assignment values or memory claims - page refresh/open never invokes run (tested 10x); rejected requests never spawn - real Trace v2 goldens (ok/truncated/arity error) from frozen CLI + contract and raw-HTTP tests; ADR-0004; docs updated
This commit is contained in:
1 parent
80ce564f09
commit
df1cf9ec24
25 files changed
+5724
-62
No files matched your search
+21
-4
@@ -46,9 +46,26 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately.
|
||||
- Tests: rendering contracts, XSS/URL sanitization, Live/Export link parity,
|
||||
raw HTTP server security tests, asset integrity, architectural gates.
|
||||
|
||||
### Added (PR-04)
|
||||
|
||||
- `trace.rs`: Trace v2 validation (schema/product, `analysis_digest`,
|
||||
`root_id`, module references, strictly increasing seq, span bounds) and
|
||||
projection with explicit `NOT_RUN/STATIC_ONLY/RUNNING/SUCCEEDED/FAILED/
|
||||
STALE/TRUNCATED/UNSUPPORTED` states.
|
||||
- Explicit-run flow: in-page confirmation, CSRF token + strict Origin check,
|
||||
JSON body limits, one active run per session, `pure`-only mode, process-group
|
||||
timeout, run cache keyed by validated Analysis digest.
|
||||
- Server-rendered run panel (stdout/stderr escaped, Core error code, public
|
||||
final value only, event list capped with explicit truncation) and inline
|
||||
run chips anchored to real statement spans; never per-assignment values.
|
||||
- Real Trace v2 goldens from the frozen CLI (success, truncated, failed arity)
|
||||
and contract/HTTP tests proving refresh never runs and rejected requests
|
||||
never spawn a process.
|
||||
- ADR-0004 for the run/CSRF/cache design.
|
||||
|
||||
### Known limitations
|
||||
|
||||
- `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.
|
||||
- `export` still returns `view.unsupported` (PR-05).
|
||||
- `project`/`strict` grant UI, streaming output, cancellation and debugger are
|
||||
not implemented; variables/memory/proof states remain `UNSUPPORTED`.
|
||||
- Browser screenshot/geometry acceptance is scheduled for PR-03/PR-06.
|
||||
+2
-2
@@ -29,8 +29,8 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3.
|
||||
| Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | **已实现**(PR-02) |
|
||||
| 文档态 / 源码态切换 | **已实现**(PR-02) |
|
||||
| 暖纸 Reader 视觉(单一 CSS/JS) | 计划 PR-03 |
|
||||
| 用户显式触发运行 + Trace v2 事件可视化 | 计划 PR-04 |
|
||||
| Live 本机安全 API | 计划 PR-05 |
|
||||
| 用户显式触发运行 + Trace v2 事件可视化 | **已实现**(PR-04,仅 `pure` 模式,需页面内确认 + CSRF) |
|
||||
| Live 本机安全 API | 部分实现(PR-02 只读 + PR-04 run;PR-05 强化/导出) |
|
||||
| 静态离线导出(纯只读) | 计划 PR-05 |
|
||||
| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) |
|
||||
| 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) |
|
||||
|
||||
@@ -10,7 +10,7 @@ Marqdo View 是一个独立的可执行文档阅读器:以**原始 Markdown
|
||||
|
||||
## 当前状态
|
||||
|
||||
**开发中。** 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 明确标注,不以占位功能冒充已实现。
|
||||
**开发中。** PR-00(基线/取证/设计基准)、PR-01(Tool Protocol v1 + verify)、PR-02(DocumentModel/Analysis v2 只读浏览 + 单一渲染器 + 本机 Live 阅读)与 PR-04(显式确认后运行 + Trace v2 可视化)已完成。`marqdo view [PATH]` 提供本机只读浏览;在 Live 页面点击“运行”并确认后,才会调用冻结核心执行 `pure` 模式并展示真实 Trace;`export` 按 PR-05 交付。任何未完成能力都在 `docs/STATUS.md` 与 CHANGELOG 明确标注,不以占位功能冒充已实现。
|
||||
|
||||
## 架构约束(摘要)
|
||||
|
||||
|
||||
@@ -884,6 +884,96 @@
|
||||
}
|
||||
}
|
||||
|
||||
.mq-run-chip {
|
||||
display: inline-block;
|
||||
margin: 0 2px 0 6px;
|
||||
padding: 0 7px;
|
||||
border: 1px solid color-mix(in srgb, var(--mq-olive) 35%, var(--mq-line));
|
||||
border-radius: 999px;
|
||||
vertical-align: 0.1em;
|
||||
background: color-mix(in srgb, var(--mq-olive) 8%, var(--mq-surface));
|
||||
font: 11px/1.6 var(--mq-mono);
|
||||
color: var(--mq-olive);
|
||||
white-space: nowrap;
|
||||
cursor: help;
|
||||
}
|
||||
body[data-annotations="off"] .mq-run-chip {
|
||||
display: none;
|
||||
}
|
||||
.mq-run-status[data-run-state="succeeded"] {
|
||||
color: var(--mq-ok);
|
||||
}
|
||||
.mq-run-status[data-run-state="failed"] {
|
||||
color: var(--mq-error);
|
||||
}
|
||||
.mq-run-status[data-run-state="truncated"],
|
||||
.mq-run-status[data-run-state="stale"] {
|
||||
color: var(--mq-warn);
|
||||
}
|
||||
.mq-run-warning {
|
||||
margin: 8px 0;
|
||||
font: 13px/1.6 var(--mq-sans);
|
||||
color: var(--mq-warn);
|
||||
}
|
||||
.mq-run-error {
|
||||
margin: 8px 0;
|
||||
font: 13px/1.6 var(--mq-sans);
|
||||
color: var(--mq-error);
|
||||
}
|
||||
.mq-run-result {
|
||||
margin: 10px 0;
|
||||
font: 14px/1.6 var(--mq-sans);
|
||||
}
|
||||
.mq-run-events-wrap {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.mq-run-events-wrap > summary {
|
||||
cursor: pointer;
|
||||
font: 12px/1.6 var(--mq-sans);
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mq-muted);
|
||||
}
|
||||
.mq-run-events .mq-event-loc {
|
||||
display: inline-block;
|
||||
min-width: 130px;
|
||||
color: var(--mq-muted);
|
||||
}
|
||||
.mq-run-actions {
|
||||
margin-top: 14px;
|
||||
}
|
||||
.mq-menu-action {
|
||||
padding: 7px 14px;
|
||||
border: 1px solid var(--mq-line-strong);
|
||||
border-radius: 999px;
|
||||
background: var(--mq-surface-2);
|
||||
font: 12px/1.5 var(--mq-sans);
|
||||
color: var(--mq-ink);
|
||||
cursor: pointer;
|
||||
}
|
||||
.mq-dialog-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
.mq-dialog-actions .mq-primary,
|
||||
.mq-dialog-actions .mq-secondary {
|
||||
padding: 9px 18px;
|
||||
border-radius: 999px;
|
||||
font: 13px/1.5 var(--mq-sans);
|
||||
cursor: pointer;
|
||||
}
|
||||
.mq-dialog-actions .mq-primary {
|
||||
border: 1px solid var(--mq-gold);
|
||||
background: var(--mq-gold);
|
||||
color: #fffdf8;
|
||||
}
|
||||
.mq-dialog-actions .mq-secondary {
|
||||
border: 1px solid var(--mq-line-strong);
|
||||
background: var(--mq-surface-2);
|
||||
color: var(--mq-ink);
|
||||
}
|
||||
@layer overlays {
|
||||
/* source pane: exact bytes as preformatted text with line numbers */
|
||||
.mq-source {
|
||||
|
||||
+117
-5
@@ -288,11 +288,20 @@
|
||||
openDialog("mq-dialog-about");
|
||||
break;
|
||||
case "run":
|
||||
// Until the explicit-run flow is implemented, never pretend to run.
|
||||
showUnsupported(
|
||||
"运行文档",
|
||||
"首版运行入口需要显式的风险评估与 CSRF 会话确认;在实现前该按钮不会执行任何文档。"
|
||||
);
|
||||
if (reader.dataset.runAvailable === "true") {
|
||||
openDialog("mq-dialog-run-confirm");
|
||||
} else {
|
||||
showUnsupported(
|
||||
"运行文档",
|
||||
"当前页面没有可用的冻结核心或可执行入口;View 不会在缺少确认的情况下执行任何文档。"
|
||||
);
|
||||
}
|
||||
break;
|
||||
case "run-confirm":
|
||||
confirmRun();
|
||||
break;
|
||||
case "clear-run":
|
||||
clearRun();
|
||||
break;
|
||||
case "clear":
|
||||
var panel = $("#mq-run-panel");
|
||||
@@ -304,6 +313,93 @@
|
||||
}
|
||||
}
|
||||
|
||||
function csrfToken() {
|
||||
var meta = document.querySelector('meta[name="mq-csrf-token"]');
|
||||
return meta ? meta.getAttribute("content") : "";
|
||||
}
|
||||
|
||||
function setRunBusy(busy) {
|
||||
var button = document.querySelector('.mq-dock-btn[data-action="run"]');
|
||||
if (!button) return;
|
||||
if (busy) {
|
||||
button.setAttribute("aria-busy", "true");
|
||||
button.dataset.busy = "true";
|
||||
button.disabled = true;
|
||||
reader.dataset.runState = "running";
|
||||
} else {
|
||||
button.removeAttribute("aria-busy");
|
||||
delete button.dataset.busy;
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function confirmRun() {
|
||||
var dialog = $("#mq-dialog-run-confirm");
|
||||
var path = dialog ? dialog.dataset.path : "";
|
||||
var token = csrfToken();
|
||||
if (!path || !token) {
|
||||
toast("缺少运行上下文或 CSRF 令牌,已拒绝运行");
|
||||
return;
|
||||
}
|
||||
setRunBusy(true);
|
||||
fetch("/api/run", {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-MQ-CSRF": token
|
||||
},
|
||||
body: JSON.stringify({ path: path, mode: "pure", confirm: true })
|
||||
})
|
||||
.then(function (response) {
|
||||
return response.json().then(function (data) {
|
||||
return { ok: response.ok, data: data };
|
||||
});
|
||||
})
|
||||
.then(function (result) {
|
||||
if (!result.ok || !result.data || !result.data.ok) {
|
||||
setRunBusy(false);
|
||||
var reason = result.data && result.data.message
|
||||
? result.data.message
|
||||
: "运行被拒绝或失败";
|
||||
toast("运行未完成:" + reason);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
window.sessionStorage.setItem(
|
||||
"marqdo.view.scroll",
|
||||
String(window.scrollY || 0)
|
||||
);
|
||||
} catch (error) {
|
||||
/* storage is optional */
|
||||
}
|
||||
window.location.assign(result.data.redirect);
|
||||
})
|
||||
.catch(function (error) {
|
||||
setRunBusy(false);
|
||||
toast("运行请求失败:" + error.message);
|
||||
});
|
||||
}
|
||||
|
||||
function clearRun() {
|
||||
closeAllDialogs();
|
||||
try {
|
||||
var url = new URL(window.location.href);
|
||||
if (url.searchParams.has("run")) {
|
||||
url.searchParams.delete("run");
|
||||
window.location.assign(url.toString());
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
/* fall through */
|
||||
}
|
||||
var panel = $("#mq-run-panel");
|
||||
if (panel) panel.hidden = true;
|
||||
toast("已清理本地展示状态(源文件与缓存未修改)");
|
||||
}
|
||||
|
||||
document.addEventListener("click", function (event) {
|
||||
var trigger = event.target.closest ? event.target.closest("[data-action]") : null;
|
||||
if (!trigger) return;
|
||||
@@ -370,6 +466,22 @@
|
||||
setMode("document");
|
||||
}
|
||||
|
||||
// Restore reading position after a run reload, without faking any result.
|
||||
try {
|
||||
var scroll = window.sessionStorage.getItem("marqdo.view.scroll");
|
||||
if (scroll && new URLSearchParams(window.location.search).has("run")) {
|
||||
window.sessionStorage.removeItem("marqdo.view.scroll");
|
||||
var target = parseInt(scroll, 10);
|
||||
if (!isNaN(target)) {
|
||||
window.requestAnimationFrame(function () {
|
||||
window.scrollTo(0, target);
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
/* storage is optional */
|
||||
}
|
||||
|
||||
// Keep dock buttons visible above the last line on small screens.
|
||||
function syncDockInset() {
|
||||
var dock = $(".mq-dock");
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# ADR-0004:显式运行、CSRF/Origin 与运行缓存
|
||||
|
||||
- 状态:Accepted
|
||||
- 日期:2026-11-22
|
||||
- 关联:RFC-VIEW-0001 §10.3、§11.2、§12;PR-04
|
||||
|
||||
## 背景
|
||||
|
||||
旧 View 的 `POST /api/run` 只解析 JSON body 就执行文档,没有 CSRF、Origin、Host 或显式确认。新 View 必须在“文档始终可读”和“运行可能产生真实副作用”之间划出可审计的边界,同时保持单一渲染器:运行结果不能由 JS 拼 HTML 或伪造。
|
||||
|
||||
## 决策
|
||||
|
||||
1. **只允许显式确认**:页面加载、刷新、搜索、导出、`GET /api/document` 永不调用 `run`。只有页面内确认对话框的 `POST /api/run` 可以执行;请求体必须含 `confirm:true`。
|
||||
2. **CSRF + Origin + Host 三重校验**:随机 256-bit 会话令牌由 `/dev/urandom` 生成,通过 meta 注入页面,POST 必须带 `X-MQ-CSRF`;若请求带 `Origin`,必须是本机允许源;Host 仍使用既有 DNS-rebinding 校验。缺 token/错 token/跨站 Origin 一律 403 且不启动子进程。
|
||||
3. **权限最小化**:首版只接受 `mode:"pure"`;`project`/`strict` 及 grants 需要未来独立授权 UI。View 不读取 `marqdo.yaml` 的 capabilities 来推导授权。
|
||||
4. **单活动运行**:进程内 `AtomicBool` 保证同一 View 会话只有一个运行;第二次请求返回 409。子进程使用独立进程组与超时,超时杀整个进程树。
|
||||
5. **服务端运行缓存而非 JSON 拼 HTML**:运行成功后服务器把 `{相对路径, source_digest, VerifiedRun}` 存入进程内缓存,返回 `redirect=/?run=<id>`;浏览器重载后同一 `ReaderRenderer` 用缓存渲染运行面板与锚点 chip。JS 不解析 Trace、不生成结果 HTML。
|
||||
6. **重新绑定**:渲染运行页时重新 `check` 并重新校验 Analysis digest;源码或 Analysis 字节变化 ⇒ `STALE`,事件不贴到新正文。运行缓存只在进程内,重启/清理即丢弃。
|
||||
7. **诚实字段**:只展示 Trace v2 公开字段和 `run --json` 公开的 stdout/stderr/最终值;不展示参数实际值、逐语句赋值、内存快照或证明状态。事件列表有上限并显式标注截断。
|
||||
|
||||
## 后果
|
||||
|
||||
- 正面:运行路径可被 HTTP 层测试完整覆盖(拒绝路径不产生 `run` 进程;页面加载 10 次为 0 次运行);Live 与 Export 继续共用唯一的 Reader 渲染字节。
|
||||
- 负面:运行完成后整页重载(保留阅读位置);首版无流式输出/取消/多运行历史;这些属于后续 PR,不得伪造。
|
||||
- 门禁:`tests/http_live.rs` 覆盖 token/Origin/confirm/mode/单活动/清缓存/源码变化 stale;`tests/trace_contract.rs` 覆盖 digest、module、seq、truncated、failed。
|
||||
+4
-3
@@ -24,7 +24,7 @@
|
||||
| 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 浏览 | **完成** | `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-04 Trace v2 运行可视化 | **完成** | `src/trace.rs`、`POST /api/run`(CSRF/Origin/确认/并发)、`tests/trace_contract.rs`、`tests/http_live.rs`、`tests/golden/trace-v2/`(冻结 CLI 生成)、ADR-0004 |
|
||||
| PR-05 Live 安全 + 静态导出 | 未开始 | — |
|
||||
| PR-06 冻结 CLI 端到端验收 | 未开始 | — |
|
||||
|
||||
@@ -32,9 +32,10 @@
|
||||
|
||||
- 旧 View 运行时状态:`LEGACY_RUNTIME_UNVERIFIED`(旧仓库无预编译产物,且任务禁止修改/编译旧仓库;只做只读静态审计)。
|
||||
- PR-01 起 `marqdo view --help/--version/verify` 由本程序提供;PR-02 起 `marqdo view [PATH]` 提供本机只读浏览。
|
||||
- `export` 仍返回 `view.unsupported`(PR-05 落地);运行入口仍显式“未启用”(PR-04)。
|
||||
- `export` 仍返回 `view.unsupported`(PR-05 落地);运行入口在 PR-04 起可用,但必须经过页面内显式确认 + CSRF 校验,且只允许 `pure` 模式。
|
||||
- 冻结 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。
|
||||
- 已知限制:逐语句变量值/参数值/内存快照/证明状态仍不可用且标为 UNSUPPORTED;`project`/`strict` 运行授权界面、SSE 流式输出、调试器未实现;`export` 未实现;浏览器截图验收在 PR-03/PR-06。
|
||||
- 运行安全:首版只提供 `--mode pure`;POST `/api/run` 要求同源 Origin(若提供)、CSRF token、`confirm:true`、单活动运行;运行缓存仅保存在进程内,重启即清空。
|
||||
- 已核对旧视觉资产许可(旧仓库 Apache-2.0):logo/blossom/feather 可复用,KaTeX 不引入。
|
||||
- 已知非目标:变量运行值、内存快照、调试器、Prove/Knowledge/Lint 引擎(均标 `UNSUPPORTED`)。
|
||||
+108
-1
@@ -4,12 +4,15 @@
|
||||
//! (later) Export call the same `load` + one `ReaderRenderer`.
|
||||
|
||||
use crate::cli::{ExportArgs, RuntimeOpts, VerifyArgs};
|
||||
use crate::core_client::{CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic};
|
||||
use crate::core_client::{
|
||||
CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic, RunOptions, SandboxMode,
|
||||
};
|
||||
use crate::document::{DocumentIdentity, DocumentModel};
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::presentation::{self, BuildInput, Navigation, PresentationModel, SourceStatus};
|
||||
use crate::project::{Project, SafeRelativePath, ViewConfig};
|
||||
use crate::semantic::{self, CoreDiagnostic};
|
||||
use crate::trace::{self, TraceVerificationInput, VerifiedRun};
|
||||
use crate::version;
|
||||
|
||||
/// Process-wide context for one browsed project: root, optional site config and
|
||||
@@ -70,6 +73,18 @@ impl AppContext {
|
||||
/// Read + parse + (optionally) check one document into the one presentation
|
||||
/// model. Never executes the document.
|
||||
pub fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
|
||||
self.load_with_run(relative, None)
|
||||
}
|
||||
|
||||
/// Same pipeline, optionally attaching an already-verified run projection.
|
||||
/// The run is re-bound to freshly checked Analysis bytes; if the source or
|
||||
/// analysis changed meanwhile the result becomes `STALE` instead of being
|
||||
/// attached to the wrong text.
|
||||
pub fn load_with_run(
|
||||
&self,
|
||||
relative: &SafeRelativePath,
|
||||
run: Option<&VerifiedRun>,
|
||||
) -> 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}"),
|
||||
@@ -140,6 +155,31 @@ impl AppContext {
|
||||
}
|
||||
}
|
||||
|
||||
let attached_run: Option<VerifiedRun> = match (run, verified.as_ref()) {
|
||||
(Some(run), Some(analysis)) => {
|
||||
let expected = format!("sha256:{}", analysis.projection.analysis_sha256);
|
||||
if expected == run.projection.analysis_digest {
|
||||
Some(VerifiedRun {
|
||||
projection: run.projection.clone(),
|
||||
})
|
||||
} else {
|
||||
Some(VerifiedRun {
|
||||
projection: trace::stale_projection(
|
||||
&run.projection.analysis_digest,
|
||||
&document.source_index,
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
(Some(run), None) => Some(VerifiedRun {
|
||||
projection: trace::stale_projection(
|
||||
&run.projection.analysis_digest,
|
||||
&document.source_index,
|
||||
),
|
||||
}),
|
||||
(None, _) => None,
|
||||
};
|
||||
|
||||
Ok(presentation::build(BuildInput {
|
||||
document,
|
||||
analysis: verified.as_ref(),
|
||||
@@ -148,8 +188,75 @@ impl AppContext {
|
||||
diagnostics,
|
||||
navigation,
|
||||
core_version: self.core_version.clone(),
|
||||
run: attached_run.as_ref(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Execute one document through the public Core `run` channel after the
|
||||
/// caller has obtained explicit user confirmation and a CSRF token. Never
|
||||
/// called from page loads or exports.
|
||||
pub fn run_document(&self, relative: &SafeRelativePath) -> ViewResult<ExecutedRun> {
|
||||
let client = self.core.as_ref().ok_or_else(|| ViewError::RunDenied {
|
||||
detail: "没有可用的冻结核心(MARQDO_BIN),运行被拒绝".to_string(),
|
||||
})?;
|
||||
let source_bytes = self.project.read_source(relative)?;
|
||||
let source_digest = crate::source_map::sha256_hex(&source_bytes);
|
||||
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
||||
detail: format!("{relative} is not valid UTF-8: {err}"),
|
||||
})?;
|
||||
let source_index = crate::source_map::SourceIndex::new(&source);
|
||||
|
||||
let run = client.run(
|
||||
&self.project,
|
||||
relative,
|
||||
&RunOptions {
|
||||
mode: SandboxMode::Pure,
|
||||
view_timeout: Some(std::time::Duration::from_secs(120)),
|
||||
timeout_seconds: Some(90),
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
let trace_bytes = run
|
||||
.trace_bytes
|
||||
.clone()
|
||||
.ok_or_else(|| ViewError::RunDenied {
|
||||
detail: "Core 未写出 Trace v2 文件,运行结果不可绑定".to_string(),
|
||||
})?;
|
||||
|
||||
// Re-check after the run so the digest binds to the exact Analysis of
|
||||
// the source that was executed and is still current.
|
||||
let response = client.check(&self.project, relative, &CheckOptions::default())?;
|
||||
let check = response.analysis.ok_or_else(|| ViewError::AnalysisFailed {
|
||||
detail: "运行后的静态检查失败,无法绑定 Trace".to_string(),
|
||||
})?;
|
||||
let verified = semantic::verify_analysis(
|
||||
&check.analysis_bytes,
|
||||
&source,
|
||||
&source_index,
|
||||
relative.as_str(),
|
||||
)?;
|
||||
let verified_run = trace::verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace_bytes,
|
||||
analysis_bytes: &check.analysis_bytes,
|
||||
semantic: &verified.projection,
|
||||
modules: &verified.projection.modules,
|
||||
source: &source,
|
||||
source_index: &source_index,
|
||||
run_json: &run.json,
|
||||
exit_code: run.exit_code,
|
||||
})?;
|
||||
Ok(ExecutedRun {
|
||||
verified: verified_run,
|
||||
source_digest,
|
||||
analysis_digest: check.analysis_digest,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ExecutedRun {
|
||||
pub verified: VerifiedRun,
|
||||
pub source_digest: String,
|
||||
pub analysis_digest: String,
|
||||
}
|
||||
|
||||
pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod render;
|
||||
pub mod semantic;
|
||||
pub mod server;
|
||||
pub mod source_map;
|
||||
pub mod trace;
|
||||
pub mod version;
|
||||
|
||||
pub use cli::Cli;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use crate::document::{DocumentIdentity, DocumentModel};
|
||||
use crate::project::{Project, SafeRelativePath, ViewConfig};
|
||||
use crate::semantic::{CoreDiagnostic, SemanticProjection, ViewWarning};
|
||||
use crate::trace::{RunDisplayState, RunProjection};
|
||||
|
||||
/// Private View presentation-model version. Not a public protocol.
|
||||
pub const PRESENTATION_VERSION: u32 = 1;
|
||||
@@ -101,6 +102,8 @@ pub struct PresentationModel {
|
||||
pub outline: Vec<OutlineEntry>,
|
||||
/// Frozen core product version used for this page, when one was consulted.
|
||||
pub core_version: Option<String>,
|
||||
/// Present only after an explicit user-triggered run whose trace verified.
|
||||
pub run: Option<RunProjection>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -119,6 +122,29 @@ pub enum OutlineKind {
|
||||
}
|
||||
|
||||
impl PresentationModel {
|
||||
pub fn run_state(&self) -> RunDisplayState {
|
||||
match &self.run {
|
||||
Some(run) => run.state,
|
||||
None => RunDisplayState::NotRun,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when a run button may be offered (explicit confirmation still
|
||||
/// required). Never true for exports or without a verified core.
|
||||
pub fn can_offer_run(&self) -> bool {
|
||||
self.source_status.semantics_usable()
|
||||
&& self
|
||||
.semantic
|
||||
.as_ref()
|
||||
.map(|semantic| {
|
||||
semantic
|
||||
.functions
|
||||
.iter()
|
||||
.any(|function| function.local_name == "main")
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn functions(&self) -> impl Iterator<Item = &OutlineEntry> {
|
||||
self.outline
|
||||
.iter()
|
||||
@@ -141,6 +167,7 @@ pub struct BuildInput<'a> {
|
||||
pub diagnostics: Vec<CoreDiagnostic>,
|
||||
pub navigation: Navigation,
|
||||
pub core_version: Option<String>,
|
||||
pub run: Option<&'a crate::trace::VerifiedRun>,
|
||||
}
|
||||
|
||||
pub fn build(input: BuildInput<'_>) -> PresentationModel {
|
||||
@@ -152,6 +179,7 @@ pub fn build(input: BuildInput<'_>) -> PresentationModel {
|
||||
mut diagnostics,
|
||||
navigation,
|
||||
core_version,
|
||||
run,
|
||||
} = input;
|
||||
|
||||
let semantic = analysis.map(|verified| verified.projection.clone());
|
||||
@@ -190,6 +218,7 @@ pub fn build(input: BuildInput<'_>) -> PresentationModel {
|
||||
navigation,
|
||||
outline,
|
||||
core_version,
|
||||
run: run.map(|verified| verified.projection.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+190
-1
@@ -145,7 +145,7 @@ impl ReaderRenderer {
|
||||
<link rel="stylesheet" href="{css}"/>
|
||||
<script defer src="{js}"></script>
|
||||
</head>
|
||||
<body class="mq-reader" data-mode="document" data-annotations="on" data-size="normal" data-source-status="{status}" data-run-state="not-run" data-live="{live}">
|
||||
<body class="mq-reader" data-mode="document" data-annotations="on" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-live="{live}">
|
||||
<a class="mq-skip" href="#mq-main">跳到正文</a>
|
||||
"##,
|
||||
presentation_version = model.version,
|
||||
@@ -156,6 +156,8 @@ impl ReaderRenderer {
|
||||
css = escape_attr(&format!("{asset_prefix}{css_name}")),
|
||||
js = escape_attr(&format!("{asset_prefix}{js_name}")),
|
||||
status = model.source_status.data_value(),
|
||||
run_state = model.run_state().data_value(),
|
||||
run_available = if ctx.run_available { "true" } else { "false" },
|
||||
live = if ctx.live { "true" } else { "false" },
|
||||
);
|
||||
|
||||
@@ -170,6 +172,7 @@ impl ReaderRenderer {
|
||||
self.render_diagnostics(&mut html, model);
|
||||
self.render_functions(&mut html, model);
|
||||
self.render_document(&mut html, model, ctx);
|
||||
self.render_run_panel(&mut html, model, ctx);
|
||||
self.render_source_pane(&mut html, model, ctx);
|
||||
self.render_footer(&mut html, model);
|
||||
let _ = write!(html, "</main>\n");
|
||||
@@ -265,6 +268,14 @@ impl ReaderRenderer {
|
||||
status_value = status.data_value(),
|
||||
label = escape_text(status.label()),
|
||||
);
|
||||
if let Some(run) = &model.run {
|
||||
let _ = write!(
|
||||
html,
|
||||
"<span class=\"mq-status mq-run-status\" data-run-state=\"{}\">本次:{}</span>\n",
|
||||
run.state.data_value(),
|
||||
escape_text(run.state_label())
|
||||
);
|
||||
}
|
||||
if let Some(projection) = &model.semantic {
|
||||
if !projection.imports.is_empty() {
|
||||
html.push_str("<ul class=\"mq-shares\" aria-label=\"导入的模块\">\n");
|
||||
@@ -511,6 +522,7 @@ impl ReaderRenderer {
|
||||
<div class="mq-dialog-head"><h2 id="mq-unsupported-title">当前版本不支持</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭说明">×</button></div>
|
||||
<div id="mq-unsupported-body"></div>
|
||||
</dialog>
|
||||
{run_dialog}
|
||||
<dialog class="mq-dialog" id="mq-dialog-about" aria-labelledby="mq-about-title">
|
||||
<div class="mq-dialog-head"><h2 id="mq-about-title">关于 Marqdo View</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭关于">×</button></div>
|
||||
<p>版本 {view_version} · Tool Protocol v1 · Analysis v2 · Trace v2。</p>
|
||||
@@ -520,11 +532,126 @@ impl ReaderRenderer {
|
||||
"##,
|
||||
csrf = csrf,
|
||||
files = self.render_file_list(model, ctx),
|
||||
run_dialog = if ctx.run_available {
|
||||
render_run_confirm_dialog(model)
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
view_version = env!("CARGO_PKG_VERSION"),
|
||||
core = escape_text(model.core_version.as_deref().unwrap_or("未检测到可用核心")),
|
||||
);
|
||||
}
|
||||
|
||||
fn render_run_panel(&self, html: &mut String, model: &PresentationModel, _ctx: &RenderContext) {
|
||||
let Some(run) = &model.run else {
|
||||
return;
|
||||
};
|
||||
let counts = &run.counts;
|
||||
let _ = write!(
|
||||
html,
|
||||
r##"<section class="mq-run-panel" id="mq-run-panel" data-run-state="{state}" data-run-id="{run_id}" aria-labelledby="mq-run-title">
|
||||
<h2 id="mq-run-title">本次运行 · {label}</h2>
|
||||
<p class="mq-colophon">入口 {entry} · 模式 pure · 退出码 {exit_code} · 事件 {total}(本文 {entry_count} / 其他模块 {other_count})</p>
|
||||
"##,
|
||||
state = run.state.data_value(),
|
||||
run_id = escape_attr(&run.run_id),
|
||||
label = escape_text(run.state_label()),
|
||||
entry = escape_text(run.entry.as_deref().unwrap_or("(未知入口)")),
|
||||
exit_code = run.exit_code,
|
||||
total = counts.total(),
|
||||
entry_count = run.entry_event_count,
|
||||
other_count = run.other_event_count,
|
||||
);
|
||||
if let Some(truncated) = &run.truncated {
|
||||
let _ = write!(
|
||||
html,
|
||||
"<p class=\"mq-run-warning\" role=\"note\">Trace 被截断:{}</p>\n",
|
||||
escape_text(&truncated.label())
|
||||
);
|
||||
}
|
||||
if let Some(code) = &run.error_code {
|
||||
let _ = write!(
|
||||
html,
|
||||
"<p class=\"mq-run-error\">Core 错误码:<code>{}</code></p>\n",
|
||||
escape_text(code)
|
||||
);
|
||||
}
|
||||
for warning in &run.warnings {
|
||||
let _ = write!(
|
||||
html,
|
||||
"<p class=\"mq-run-warning\" role=\"note\">{}</p>\n",
|
||||
escape_text(warning)
|
||||
);
|
||||
}
|
||||
if let Some(value) = &run.result_value {
|
||||
let _ = write!(
|
||||
html,
|
||||
"<p class=\"mq-run-result\">Core 本次返回值(公开 JSON):<code>{}</code> <span class=\"mq-colophon\">类型 {}</span></p>\n",
|
||||
escape_text(&value.display),
|
||||
escape_text(&value.ty)
|
||||
);
|
||||
}
|
||||
if !run.stdout.is_empty() {
|
||||
let _ = write!(
|
||||
html,
|
||||
"<pre class=\"mq-stdout\" aria-label=\"程序标准输出\">{}</pre>\n",
|
||||
escape_text(&run.stdout)
|
||||
);
|
||||
}
|
||||
if !run.stderr.is_empty() {
|
||||
let _ = write!(
|
||||
html,
|
||||
"<pre class=\"mq-stdout mq-stderr\" aria-label=\"程序标准错误\">{}</pre>\n",
|
||||
escape_text(&run.stderr)
|
||||
);
|
||||
}
|
||||
if !run.events.is_empty() {
|
||||
html.push_str("<details class=\"mq-run-events-wrap\" open><summary>真实 Trace v2 事件</summary>\n<ol class=\"mq-run-events\">\n");
|
||||
for event in run.events.iter().take(200) {
|
||||
let location = match event.span {
|
||||
Some(span) => {
|
||||
let (line, column) =
|
||||
model.document.source_index.line_col(span.start as usize);
|
||||
format!("第 {line} 行第 {column} 列")
|
||||
}
|
||||
None => {
|
||||
let module = event
|
||||
.module_id
|
||||
.as_deref()
|
||||
.and_then(|module| module.rsplit("::").next())
|
||||
.unwrap_or("(无模块)");
|
||||
module.to_string()
|
||||
}
|
||||
};
|
||||
let detail = event.detail.as_deref().unwrap_or("");
|
||||
let operation = event
|
||||
.operation
|
||||
.as_deref()
|
||||
.map(|operation| format!(" · {operation}"))
|
||||
.unwrap_or_default();
|
||||
let _ = write!(
|
||||
html,
|
||||
"<li data-seq=\"{seq}\"><span class=\"mq-event-kind\">{kind}</span><span class=\"mq-event-loc\">{location}</span> {detail}{operation}</li>\n",
|
||||
seq = event.seq,
|
||||
kind = escape_text(event.kind_label()),
|
||||
location = escape_text(&location),
|
||||
detail = escape_text(detail),
|
||||
operation = escape_text(&operation)
|
||||
);
|
||||
}
|
||||
html.push_str("</ol>\n");
|
||||
if run.events.len() > 200 {
|
||||
let _ = write!(
|
||||
html,
|
||||
"<p class=\"mq-colophon\">仅显示前 200 条(共 {} 条);完整数据保留在本地会话缓存中。</p>\n",
|
||||
run.events.len()
|
||||
);
|
||||
}
|
||||
html.push_str("</details>\n");
|
||||
}
|
||||
html.push_str("<div class=\"mq-run-actions\"><button type=\"button\" class=\"mq-menu-action\" data-action=\"clear-run\">清理本次结果展示</button></div>\n</section>\n");
|
||||
}
|
||||
|
||||
fn render_file_list(&self, model: &PresentationModel, ctx: &RenderContext) -> String {
|
||||
if model.navigation.documents.len() <= 1 {
|
||||
return String::new();
|
||||
@@ -920,6 +1047,9 @@ fn render_inline(
|
||||
html.push('>');
|
||||
html.push_str(&escape_text(literal));
|
||||
html.push_str("</code>");
|
||||
if let Some((_, statement)) = anchor {
|
||||
render_run_chips(html, model, statement.span);
|
||||
}
|
||||
}
|
||||
Inline::Strong { span, children } => {
|
||||
let anchor = projection.and_then(|projection| projection.statement_for_inline(*span));
|
||||
@@ -941,6 +1071,9 @@ fn render_inline(
|
||||
html.push('>');
|
||||
render_inlines(html, children, model, ctx, current, assets_placeholder());
|
||||
html.push_str("</strong>");
|
||||
if let Some((_, statement)) = anchor {
|
||||
render_run_chips(html, model, statement.span);
|
||||
}
|
||||
}
|
||||
Inline::Emph { span, children } => {
|
||||
let anchor = projection.and_then(|projection| projection.statement_for_inline(*span));
|
||||
@@ -962,6 +1095,9 @@ fn render_inline(
|
||||
html.push('>');
|
||||
render_inlines(html, children, model, ctx, current, assets_placeholder());
|
||||
html.push_str("</em>");
|
||||
if let Some((_, statement)) = anchor {
|
||||
render_run_chips(html, model, statement.span);
|
||||
}
|
||||
}
|
||||
Inline::Strikethrough { children, .. } => {
|
||||
html.push_str("<del>");
|
||||
@@ -1160,3 +1296,56 @@ fn resolve_link(raw: &str, current: &SafeRelativePath, policy: &LinkPolicy) -> O
|
||||
}
|
||||
Some(url.to_string())
|
||||
}
|
||||
|
||||
fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span: SourceSpan) {
|
||||
let Some(run) = &model.run else {
|
||||
return;
|
||||
};
|
||||
let Some(summary) = run.anchor_summary(statement_span) else {
|
||||
return;
|
||||
};
|
||||
let suffix = if summary.count > 1 {
|
||||
format!(" ×{}", summary.count)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let _ = write!(
|
||||
html,
|
||||
"<span class=\"mq-run-chip\" data-run-seq=\"{seq}\" data-run-kind=\"{kinds}\" title=\"真实 Trace 事件:{count} 条({kinds})\">{detail}{suffix}</span>",
|
||||
seq = summary.last_seq,
|
||||
kinds = escape_attr(&summary.kinds.join(",")),
|
||||
count = summary.count,
|
||||
detail = escape_text(&summary.detail),
|
||||
suffix = escape_text(&suffix)
|
||||
);
|
||||
}
|
||||
|
||||
fn render_run_confirm_dialog(model: &PresentationModel) -> String {
|
||||
let function = model
|
||||
.semantic
|
||||
.as_ref()
|
||||
.and_then(|semantic| {
|
||||
semantic
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.local_name == "main")
|
||||
})
|
||||
.map(|function| function.local_name.clone())
|
||||
.unwrap_or_else(|| "main".to_string());
|
||||
format!(
|
||||
r##"<dialog class="mq-dialog" id="mq-dialog-run-confirm" aria-labelledby="mq-run-confirm-title" data-path="{path}">
|
||||
<div class="mq-dialog-head"><h2 id="mq-run-confirm-title">确认运行本文档</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="取消运行">×</button></div>
|
||||
<p>即将通过冻结核心执行入口函数 <code>{function}</code>,沙箱模式 <code>pure</code>(无文件、网络、环境变量、进程权限)。</p>
|
||||
<p>等价命令:<code>marqdo run {path} --mode pure --json --trace-file <临时文件></code></p>
|
||||
<p>运行会在你的机器上真实执行文档中的 <code>@exec</code> 代码。Trace v2 不记录参数实际值、文件内容或敏感数据;View 不继承项目声明的 capabilities。</p>
|
||||
<p class="mq-colophon">打开、刷新、搜索、导出都不会触发运行;只有本确认按钮会。</p>
|
||||
<div class="mq-dialog-actions">
|
||||
<button type="button" class="mq-secondary" data-action="close-dialog">取消</button>
|
||||
<button type="button" class="mq-primary" data-action="run-confirm">确认运行(pure)</button>
|
||||
</div>
|
||||
</dialog>
|
||||
"##,
|
||||
function = escape_text(&function),
|
||||
path = escape_text(&model.document.identity.relative_path)
|
||||
)
|
||||
}
|
||||
+415
-25
@@ -12,12 +12,15 @@ use crate::presentation::PresentationModel;
|
||||
use crate::project::SafeRelativePath;
|
||||
use crate::render::{ReaderRenderer, RenderContext};
|
||||
use crate::source_map::sha256_hex;
|
||||
use crate::trace::VerifiedRun;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
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;
|
||||
const MAX_BODY_BYTES: usize = 16 * 1024;
|
||||
|
||||
pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult<i32> {
|
||||
let address = format!("{}:{}", opts.host, opts.port);
|
||||
@@ -62,6 +65,9 @@ pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult<i32> {
|
||||
renderer: ReaderRenderer::new(),
|
||||
cache: Mutex::new(HashMap::new()),
|
||||
allowed_hosts: allowed_hosts(port),
|
||||
running: AtomicBool::new(false),
|
||||
run_cache: Mutex::new(HashMap::new()),
|
||||
run_seq: AtomicU64::new(1),
|
||||
});
|
||||
|
||||
loop {
|
||||
@@ -87,6 +93,16 @@ struct ServerState {
|
||||
renderer: ReaderRenderer,
|
||||
cache: Mutex<HashMap<String, CacheEntry>>,
|
||||
allowed_hosts: Vec<String>,
|
||||
/// One active run per View session.
|
||||
running: AtomicBool,
|
||||
run_cache: Mutex<HashMap<String, CachedRun>>,
|
||||
run_seq: AtomicU64,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CachedRun {
|
||||
relative: String,
|
||||
verified: VerifiedRun,
|
||||
}
|
||||
|
||||
struct CacheEntry {
|
||||
@@ -97,6 +113,28 @@ struct CacheEntry {
|
||||
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).
|
||||
/// Load a page and attach a cached run when the URL names one. The run is
|
||||
/// re-bound against freshly checked Analysis inside `load_with_run`.
|
||||
fn load_for_page(
|
||||
&self,
|
||||
relative: &SafeRelativePath,
|
||||
run_id: Option<&str>,
|
||||
) -> ViewResult<PresentationModel> {
|
||||
if let Some(run_id) = run_id {
|
||||
let cached = self
|
||||
.run_cache
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|cache| cache.get(run_id).cloned());
|
||||
if let Some(cached) = cached {
|
||||
if cached.relative == relative.as_str() {
|
||||
return self.ctx.load_with_run(relative, Some(&cached.verified));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.load(relative)
|
||||
}
|
||||
|
||||
fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
|
||||
let digest = self.ctx.project().source_digest(relative)?;
|
||||
if let Ok(cache) = self.cache.lock() {
|
||||
@@ -124,26 +162,8 @@ impl ServerState {
|
||||
|
||||
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 is_get = method == Method::Get;
|
||||
|
||||
let raw_url = request.url().to_string();
|
||||
if raw_url.len() > MAX_URL_BYTES {
|
||||
@@ -166,14 +186,48 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
if method == Method::Post {
|
||||
return match path_part {
|
||||
"/api/run" => handle_run_post(state, request),
|
||||
"/api/clear-run" => handle_clear_run_post(state, request),
|
||||
_ => respond_text(
|
||||
request,
|
||||
StatusCode(405),
|
||||
"text/plain; charset=utf-8",
|
||||
"method not allowed\n".as_bytes().to_vec(),
|
||||
CacheKind::NoStore,
|
||||
),
|
||||
};
|
||||
}
|
||||
if !is_get && !is_head {
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(405),
|
||||
"text/plain; charset=utf-8",
|
||||
"method not allowed\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);
|
||||
}
|
||||
|
||||
let run_id = query_param(query, "run");
|
||||
match path_part {
|
||||
"/" | "/index.html" => {
|
||||
let entry = state.ctx.project().entry().relative.clone();
|
||||
match state.load(&entry) {
|
||||
match state.load_for_page(&entry, run_id.as_deref()) {
|
||||
Ok(model) => serve_page(state, request, &model, is_head),
|
||||
Err(err) => serve_error_page(request, &err, is_head),
|
||||
}
|
||||
@@ -218,7 +272,7 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
|
||||
CacheKind::NoStore,
|
||||
);
|
||||
}
|
||||
match state.load(&relative) {
|
||||
match state.load_for_page(&relative, run_id.as_deref()) {
|
||||
Ok(model) => serve_page(state, request, &model, is_head),
|
||||
Err(err) => serve_error_page(request, &err, is_head),
|
||||
}
|
||||
@@ -234,7 +288,7 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
|
||||
}
|
||||
None => state.ctx.project().entry().relative.clone(),
|
||||
};
|
||||
match state.load(&relative) {
|
||||
match state.load_for_page(&relative, query_param(query, "run").as_deref()) {
|
||||
Ok(model) => serve_document_json(request, &model),
|
||||
Err(err) => respond_json_error(request, StatusCode(500), &err),
|
||||
}
|
||||
@@ -263,7 +317,7 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
|
||||
"trace": crate::version::TRACE_PROTOCOL,
|
||||
},
|
||||
"documents": documents,
|
||||
"run_api": false,
|
||||
"run_api": true,
|
||||
});
|
||||
respond_json(request, StatusCode(200), &health)
|
||||
}
|
||||
@@ -277,6 +331,330 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_run_post(state: &ServerState, mut request: Request) -> ViewResult<()> {
|
||||
if !origin_is_allowed(&request, state) {
|
||||
return respond_json_error(
|
||||
request,
|
||||
StatusCode(403),
|
||||
&ViewError::RunDenied {
|
||||
detail: "跨站来源被拒绝(Origin 校验失败)".to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
if !content_type_is_json(&request) {
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(415),
|
||||
"text/plain; charset=utf-8",
|
||||
"expected application/json\n".as_bytes().to_vec(),
|
||||
CacheKind::NoStore,
|
||||
);
|
||||
}
|
||||
let Some(token) = header_value(&request, "X-MQ-CSRF") else {
|
||||
return respond_json_error(
|
||||
request,
|
||||
StatusCode(403),
|
||||
&ViewError::RunDenied {
|
||||
detail: "缺少 CSRF 令牌,运行被拒绝".to_string(),
|
||||
},
|
||||
);
|
||||
};
|
||||
if !constant_time_eq(token.as_bytes(), state.csrf_token.as_bytes()) {
|
||||
return respond_json_error(
|
||||
request,
|
||||
StatusCode(403),
|
||||
&ViewError::RunDenied {
|
||||
detail: "CSRF 令牌无效,运行被拒绝".to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let body = match read_body(&mut request, MAX_BODY_BYTES) {
|
||||
Ok(body) => body,
|
||||
Err(err) => return respond_json_error(request, StatusCode(413), &err),
|
||||
};
|
||||
#[derive(serde::Deserialize)]
|
||||
struct RunRequest {
|
||||
#[serde(default)]
|
||||
path: Option<String>,
|
||||
#[serde(default)]
|
||||
mode: Option<String>,
|
||||
#[serde(default)]
|
||||
confirm: Option<bool>,
|
||||
}
|
||||
let parsed: RunRequest = match serde_json::from_slice(&body) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(err) => {
|
||||
return respond_json_error(
|
||||
request,
|
||||
StatusCode(400),
|
||||
&ViewError::RunDenied {
|
||||
detail: format!("运行请求不是合法 JSON: {err}"),
|
||||
},
|
||||
)
|
||||
}
|
||||
};
|
||||
if parsed.confirm != Some(true) {
|
||||
return respond_json_error(
|
||||
request,
|
||||
StatusCode(400),
|
||||
&ViewError::RunDenied {
|
||||
detail: "缺少显式用户确认,拒绝运行".to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(mode) = parsed.mode.as_deref() {
|
||||
if mode != "pure" {
|
||||
return respond_json_error(
|
||||
request,
|
||||
StatusCode(403),
|
||||
&ViewError::RunDenied {
|
||||
detail: format!(
|
||||
"当前版本只允许最低权限 pure 模式(收到 {mode:?});project/strict grants 需要单独的授权界面"
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
let relative = match parsed.path.as_deref() {
|
||||
Some(path) => match SafeRelativePath::parse(path) {
|
||||
Ok(relative) => relative,
|
||||
Err(err) => return respond_json_error(request, StatusCode(403), &err),
|
||||
},
|
||||
None => state.ctx.project().entry().relative.clone(),
|
||||
};
|
||||
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,
|
||||
);
|
||||
}
|
||||
if state.running.swap(true, Ordering::SeqCst) {
|
||||
return respond_json_error(
|
||||
request,
|
||||
StatusCode(409),
|
||||
&ViewError::RunDenied {
|
||||
detail: "已有一次运行正在进行;首版每个 View 会话只允许一个活动运行".to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let guard = RunningGuard(&state.running);
|
||||
let outcome = state.ctx.run_document(&relative);
|
||||
drop(guard);
|
||||
let executed = match outcome {
|
||||
Ok(executed) => executed,
|
||||
Err(err) => {
|
||||
return respond_json_error(request, run_error_status(&err), &err);
|
||||
}
|
||||
};
|
||||
let seq = state.run_seq.fetch_add(1, Ordering::Relaxed);
|
||||
let sanitized = executed
|
||||
.verified
|
||||
.projection
|
||||
.run_id
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
ch
|
||||
} else {
|
||||
'-'
|
||||
}
|
||||
})
|
||||
.take(40)
|
||||
.collect::<String>();
|
||||
let run_id = format!("{seq}-{sanitized}");
|
||||
let entry = state.ctx.project().entry().relative.clone();
|
||||
let redirect = if relative == entry {
|
||||
format!("/?run={run_id}")
|
||||
} else {
|
||||
format!("/file?path={}&run={run_id}", encode_path(relative.as_str()))
|
||||
};
|
||||
let cached = CachedRun {
|
||||
relative: relative.as_str().to_string(),
|
||||
verified: executed.verified,
|
||||
};
|
||||
if let Ok(mut cache) = state.run_cache.lock() {
|
||||
if cache.len() >= 8 {
|
||||
let oldest = cache
|
||||
.keys()
|
||||
.min_by_key(|key| {
|
||||
key.split('-')
|
||||
.next()
|
||||
.and_then(|seq| seq.parse::<u64>().ok())
|
||||
.unwrap_or(u64::MAX)
|
||||
})
|
||||
.cloned();
|
||||
if let Some(oldest) = oldest {
|
||||
cache.remove(&oldest);
|
||||
}
|
||||
}
|
||||
cache.insert(run_id.clone(), cached.clone());
|
||||
}
|
||||
let projection = &cached.verified.projection;
|
||||
let response = serde_json::json!({
|
||||
"ok": true,
|
||||
"run_id": run_id,
|
||||
"redirect": redirect,
|
||||
"state": projection.state.data_value(),
|
||||
"label": projection.state.label(),
|
||||
"run_status": projection.run_status,
|
||||
"exit_code": projection.exit_code,
|
||||
"events": projection.counts.total(),
|
||||
"entry_events": projection.entry_event_count,
|
||||
"truncated": projection.truncated.as_ref().map(|truncated| truncated.label()),
|
||||
"note": "本响应只来自冻结核心 run --json 与 Trace v2;参数值/内存/证明状态不提供。",
|
||||
});
|
||||
respond_json(request, StatusCode(200), &response)
|
||||
}
|
||||
|
||||
fn handle_clear_run_post(state: &ServerState, mut request: Request) -> ViewResult<()> {
|
||||
if !origin_is_allowed(&request, state) {
|
||||
return respond_json_error(
|
||||
request,
|
||||
StatusCode(403),
|
||||
&ViewError::RunDenied {
|
||||
detail: "跨站来源被拒绝(Origin 校验失败)".to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
if !content_type_is_json(&request) {
|
||||
return respond_text(
|
||||
request,
|
||||
StatusCode(415),
|
||||
"text/plain; charset=utf-8",
|
||||
"expected application/json\n".as_bytes().to_vec(),
|
||||
CacheKind::NoStore,
|
||||
);
|
||||
}
|
||||
let Some(token) = header_value(&request, "X-MQ-CSRF") else {
|
||||
return respond_json_error(
|
||||
request,
|
||||
StatusCode(403),
|
||||
&ViewError::RunDenied {
|
||||
detail: "缺少 CSRF 令牌,清理缓存被拒绝".to_string(),
|
||||
},
|
||||
);
|
||||
};
|
||||
if !constant_time_eq(token.as_bytes(), state.csrf_token.as_bytes()) {
|
||||
return respond_json_error(
|
||||
request,
|
||||
StatusCode(403),
|
||||
&ViewError::RunDenied {
|
||||
detail: "CSRF 令牌无效,清理缓存被拒绝".to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let body = match read_body(&mut request, MAX_BODY_BYTES) {
|
||||
Ok(body) => body,
|
||||
Err(err) => return respond_json_error(request, StatusCode(413), &err),
|
||||
};
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ClearRequest {
|
||||
#[serde(default)]
|
||||
run_id: Option<String>,
|
||||
}
|
||||
let parsed: ClearRequest =
|
||||
serde_json::from_slice(&body).unwrap_or(ClearRequest { run_id: None });
|
||||
if let Some(run_id) = parsed.run_id {
|
||||
if let Ok(mut cache) = state.run_cache.lock() {
|
||||
cache.remove(&run_id);
|
||||
}
|
||||
}
|
||||
respond_json(
|
||||
request,
|
||||
StatusCode(200),
|
||||
&serde_json::json!({ "ok": true, "note": "仅清理本 View 会话的运行展示缓存;未修改项目文件。" }),
|
||||
)
|
||||
}
|
||||
|
||||
struct RunningGuard<'a>(&'a AtomicBool);
|
||||
|
||||
impl Drop for RunningGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
fn run_error_status(err: &ViewError) -> StatusCode {
|
||||
match err.code() {
|
||||
"view.run_denied" => StatusCode(403),
|
||||
"view.trace_stale" => StatusCode(409),
|
||||
"view.core_timeout" => StatusCode(504),
|
||||
"view.protocol_incompatible" => StatusCode(502),
|
||||
_ => StatusCode(500),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_body(request: &mut Request, max: usize) -> Result<Vec<u8>, ViewError> {
|
||||
use std::io::Read as _;
|
||||
let mut body = Vec::new();
|
||||
let mut reader = request.as_reader().take(max as u64 + 1);
|
||||
reader.read_to_end(&mut body).map_err(|err| ViewError::Io {
|
||||
detail: format!("read request body: {err}"),
|
||||
})?;
|
||||
if body.len() > max {
|
||||
return Err(ViewError::ResourceLimit {
|
||||
detail: format!("request body above {max} bytes"),
|
||||
});
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn header_value(request: &Request, name: &'static str) -> Option<String> {
|
||||
request
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|header| header.field.equiv(name))
|
||||
.map(|header| header.value.as_str().to_string())
|
||||
}
|
||||
|
||||
fn content_type_is_json(request: &Request) -> bool {
|
||||
header_value(request, "Content-Type")
|
||||
.map(|value| value.to_ascii_lowercase().starts_with("application/json"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn origin_is_allowed(request: &Request, state: &ServerState) -> bool {
|
||||
let Some(origin) = header_value(request, "Origin") else {
|
||||
// Non-browser clients and same-origin `fetch` may omit Origin; the
|
||||
// CSRF token is still mandatory in every case.
|
||||
return true;
|
||||
};
|
||||
let origin = origin.trim_end_matches('/').to_ascii_lowercase();
|
||||
state.allowed_hosts.iter().any(|host| {
|
||||
let http = format!("http://{}", host.to_ascii_lowercase());
|
||||
origin == http
|
||||
})
|
||||
}
|
||||
|
||||
fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
|
||||
if left.len() != right.len() {
|
||||
return false;
|
||||
}
|
||||
let mut diff = 0u8;
|
||||
for (a, b) in left.iter().zip(right.iter()) {
|
||||
diff |= a ^ b;
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
fn encode_path(raw: &str) -> String {
|
||||
let mut out = String::with_capacity(raw.len());
|
||||
for byte in raw.as_bytes() {
|
||||
let unreserved =
|
||||
byte.is_ascii_alphanumeric() || matches!(*byte, b'-' | b'_' | b'.' | b'~' | b'/');
|
||||
if unreserved {
|
||||
out.push(*byte as char);
|
||||
} else {
|
||||
use std::fmt::Write as _;
|
||||
let _ = write!(out, "%{byte:02X}");
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn serve_page(
|
||||
state: &ServerState,
|
||||
request: Request,
|
||||
@@ -287,7 +665,7 @@ fn serve_page(
|
||||
links: crate::render::LinkPolicy::LocalServer,
|
||||
live: true,
|
||||
csrf_token: Some(state.csrf_token.clone()),
|
||||
run_available: false,
|
||||
run_available: state.ctx.core().is_some() && model.can_offer_run(),
|
||||
};
|
||||
let page = state.renderer.render(model, &ctx);
|
||||
respond_html(request, page.html.into_bytes(), is_head)
|
||||
@@ -338,7 +716,19 @@ fn serve_document_json(request: Request, model: &PresentationModel) -> ViewResul
|
||||
"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.",
|
||||
"run": model.run.as_ref().map(|run| serde_json::json!({
|
||||
"state": run.state.data_value(),
|
||||
"label": run.state.label(),
|
||||
"run_id": run.run_id,
|
||||
"run_status": run.run_status,
|
||||
"exit_code": run.exit_code,
|
||||
"event_count": run.counts.total(),
|
||||
"entry_event_count": run.entry_event_count,
|
||||
"truncated": run.truncated.as_ref().map(|truncated| truncated.label()),
|
||||
"has_result_value": run.result_value.is_some(),
|
||||
})),
|
||||
"can_offer_run": model.can_offer_run(),
|
||||
"note": "Read-only PresentationModel summary; this page load never executes the document.",
|
||||
});
|
||||
respond_json(request, StatusCode(200), &doc)
|
||||
}
|
||||
|
||||
+627
@@ -0,0 +1,627 @@
|
||||
//! Trace v2 validation and run projection.
|
||||
//!
|
||||
//! Trace data is observed execution, not execution itself. Validation is hard:
|
||||
//! the trace must bind to the exact Analysis bytes and project identity, and
|
||||
//! every event module id must exist in Analysis. Missing capabilities (per
|
||||
//! assignment values, memory snapshots, proofs) are explicit `UNSUPPORTED`
|
||||
//! states, never invented (RFC-VIEW-0001 §4.4, §12).
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::semantic::{ModuleSummary, SemanticProjection};
|
||||
use crate::source_map::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunDisplayState {
|
||||
NotRun,
|
||||
StaticOnly,
|
||||
Running,
|
||||
Succeeded,
|
||||
Failed,
|
||||
Stale,
|
||||
Truncated,
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
impl RunDisplayState {
|
||||
pub fn data_value(&self) -> &'static str {
|
||||
match self {
|
||||
RunDisplayState::NotRun => "not-run",
|
||||
RunDisplayState::StaticOnly => "static-only",
|
||||
RunDisplayState::Running => "running",
|
||||
RunDisplayState::Succeeded => "succeeded",
|
||||
RunDisplayState::Failed => "failed",
|
||||
RunDisplayState::Stale => "stale",
|
||||
RunDisplayState::Truncated => "truncated",
|
||||
RunDisplayState::Unsupported => "unsupported",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
RunDisplayState::NotRun => "未运行",
|
||||
RunDisplayState::StaticOnly => "仅静态检查",
|
||||
RunDisplayState::Running => "运行中",
|
||||
RunDisplayState::Succeeded => "运行成功",
|
||||
RunDisplayState::Failed => "运行失败",
|
||||
RunDisplayState::Stale => "结果已过期",
|
||||
RunDisplayState::Truncated => "Trace 已截断",
|
||||
RunDisplayState::Unsupported => "当前协议不支持",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum TraceKind {
|
||||
CallEnter,
|
||||
CallExit,
|
||||
BranchEval,
|
||||
LoopIteration,
|
||||
Return,
|
||||
Effect,
|
||||
Truncated,
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl TraceKind {
|
||||
pub fn data_value(&self) -> &str {
|
||||
match self {
|
||||
TraceKind::CallEnter => "call.enter",
|
||||
TraceKind::CallExit => "call.exit",
|
||||
TraceKind::BranchEval => "branch.eval",
|
||||
TraceKind::LoopIteration => "loop.iteration",
|
||||
TraceKind::Return => "return",
|
||||
TraceKind::Effect => "effect",
|
||||
TraceKind::Truncated => "trace.truncated",
|
||||
TraceKind::Other(kind) => kind,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(raw: &str) -> TraceKind {
|
||||
match raw {
|
||||
"call.enter" => TraceKind::CallEnter,
|
||||
"call.exit" => TraceKind::CallExit,
|
||||
"branch.eval" => TraceKind::BranchEval,
|
||||
"loop.iteration" => TraceKind::LoopIteration,
|
||||
"return" => TraceKind::Return,
|
||||
"effect" => TraceKind::Effect,
|
||||
"trace.truncated" => TraceKind::Truncated,
|
||||
other => TraceKind::Other(other.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TraceEvent {
|
||||
pub seq: u64,
|
||||
pub kind: TraceKind,
|
||||
pub function_id: Option<String>,
|
||||
pub module_id: Option<String>,
|
||||
/// Validated span in the entry module; `None` for other modules or invalid
|
||||
/// spans (which are reported as warnings).
|
||||
pub span: Option<SourceSpan>,
|
||||
/// Presentation-only span in an event's own module, kept for the panel.
|
||||
pub raw_span: Option<SourceSpan>,
|
||||
/// Statement span in the entry document this event attaches to, if any.
|
||||
pub anchor_span: Option<SourceSpan>,
|
||||
pub detail: Option<String>,
|
||||
pub operation: Option<String>,
|
||||
pub duration_micros: Option<u64>,
|
||||
}
|
||||
|
||||
impl TraceEvent {
|
||||
pub fn kind_label(&self) -> &str {
|
||||
self.kind.data_value()
|
||||
}
|
||||
|
||||
pub fn is_entry_module(&self, entry_module: &str) -> bool {
|
||||
self.module_id.as_deref() == Some(entry_module)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Truncation {
|
||||
pub reason: String,
|
||||
pub limit: u64,
|
||||
pub written: u64,
|
||||
}
|
||||
|
||||
impl Truncation {
|
||||
pub fn label(&self) -> String {
|
||||
let reason = match self.reason.as_str() {
|
||||
"event_budget" => "事件数量上限",
|
||||
"byte_budget" => "字节上限",
|
||||
other => other,
|
||||
};
|
||||
format!("{reason}(上限 {},已写入 {})", self.limit, self.written)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunValue {
|
||||
pub ty: String,
|
||||
pub display: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct EventCounts {
|
||||
pub call_enter: usize,
|
||||
pub call_exit: usize,
|
||||
pub branch_eval: usize,
|
||||
pub loop_iteration: usize,
|
||||
pub return_events: usize,
|
||||
pub effect: usize,
|
||||
pub other: usize,
|
||||
}
|
||||
|
||||
impl EventCounts {
|
||||
pub fn total(&self) -> usize {
|
||||
self.call_enter
|
||||
+ self.call_exit
|
||||
+ self.branch_eval
|
||||
+ self.loop_iteration
|
||||
+ self.return_events
|
||||
+ self.effect
|
||||
+ self.other
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunProjection {
|
||||
pub run_id: String,
|
||||
pub entry: Option<String>,
|
||||
/// Raw `run.status` from the Core (`ok` or a stable runtime error code).
|
||||
pub run_status: String,
|
||||
pub state: RunDisplayState,
|
||||
pub error_code: Option<String>,
|
||||
pub analysis_digest: String,
|
||||
pub events: Vec<TraceEvent>,
|
||||
pub truncated: Option<Truncation>,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub exit_code: i32,
|
||||
pub result_value: Option<RunValue>,
|
||||
pub counts: EventCounts,
|
||||
/// Counts per event module: entry document vs other modules.
|
||||
pub entry_event_count: usize,
|
||||
pub other_event_count: usize,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl RunProjection {
|
||||
pub fn state_label(&self) -> &'static str {
|
||||
self.state.label()
|
||||
}
|
||||
|
||||
pub fn is_success(&self) -> bool {
|
||||
matches!(
|
||||
self.state,
|
||||
RunDisplayState::Succeeded | RunDisplayState::Truncated
|
||||
)
|
||||
}
|
||||
|
||||
/// Events whose statement anchor is exactly `span`, in sequence order.
|
||||
pub fn events_for_anchor(&self, span: SourceSpan) -> Vec<&TraceEvent> {
|
||||
self.events
|
||||
.iter()
|
||||
.filter(|event| event.anchor_span == Some(span))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Compact inline summary for one statement anchor, or `None` when the
|
||||
/// statement has no sourced run event.
|
||||
pub fn anchor_summary(&self, span: SourceSpan) -> Option<RunAnchorSummary> {
|
||||
let events = self.events_for_anchor(span);
|
||||
if events.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let last = events.last().expect("non-empty");
|
||||
let mut kinds: Vec<&str> = Vec::new();
|
||||
for event in &events {
|
||||
if !kinds.contains(&event.kind_label()) {
|
||||
kinds.push(event.kind_label());
|
||||
}
|
||||
}
|
||||
let detail = match last.kind {
|
||||
TraceKind::BranchEval => format!("if → {}", last.detail.as_deref().unwrap_or("?")),
|
||||
TraceKind::LoopIteration => {
|
||||
let outcome = match last.detail.as_deref() {
|
||||
Some("continue") => "continue",
|
||||
Some("exit") => "exit",
|
||||
other => other.unwrap_or("?"),
|
||||
};
|
||||
format!("loop {outcome}")
|
||||
}
|
||||
TraceKind::Return => format!("return {}", last.detail.as_deref().unwrap_or("Unit")),
|
||||
TraceKind::CallEnter => "call".to_string(),
|
||||
TraceKind::CallExit => "call exit".to_string(),
|
||||
TraceKind::Effect => format!("effect {}", last.operation.as_deref().unwrap_or("ok")),
|
||||
_ => last.kind_label().to_string(),
|
||||
};
|
||||
Some(RunAnchorSummary {
|
||||
count: events.len(),
|
||||
detail,
|
||||
kinds: kinds.into_iter().map(str::to_string).collect(),
|
||||
last_seq: last.seq,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunAnchorSummary {
|
||||
pub count: usize,
|
||||
pub detail: String,
|
||||
pub kinds: Vec<String>,
|
||||
pub last_seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct VerifiedRun {
|
||||
pub projection: RunProjection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawTrace {
|
||||
schema: String,
|
||||
schema_version: u32,
|
||||
run: RawRun,
|
||||
source: RawTraceSource,
|
||||
#[serde(default)]
|
||||
truncated: Option<RawTruncation>,
|
||||
#[serde(default)]
|
||||
events: Vec<RawEvent>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawRun {
|
||||
#[serde(default)]
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
entry: Option<String>,
|
||||
#[serde(default)]
|
||||
status: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawTraceSource {
|
||||
#[serde(default)]
|
||||
root_id: String,
|
||||
#[serde(default)]
|
||||
analysis_digest: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawTruncation {
|
||||
#[serde(default)]
|
||||
reason: String,
|
||||
#[serde(default)]
|
||||
limit: u64,
|
||||
#[serde(default)]
|
||||
written: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawEvent {
|
||||
#[serde(default)]
|
||||
seq: u64,
|
||||
#[serde(default)]
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
function_id: Option<String>,
|
||||
#[serde(default)]
|
||||
module_id: Option<String>,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
#[serde(default)]
|
||||
detail: Option<String>,
|
||||
#[serde(default)]
|
||||
operation: Option<String>,
|
||||
#[serde(default)]
|
||||
duration_micros: Option<u64>,
|
||||
}
|
||||
|
||||
pub struct TraceVerificationInput<'a> {
|
||||
pub trace_bytes: &'a [u8],
|
||||
pub analysis_bytes: &'a [u8],
|
||||
pub semantic: &'a SemanticProjection,
|
||||
pub modules: &'a [ModuleSummary],
|
||||
pub source: &'a str,
|
||||
pub source_index: &'a SourceIndex,
|
||||
pub run_json: &'a Value,
|
||||
pub exit_code: i32,
|
||||
}
|
||||
|
||||
/// Verify Trace v2 against the current Analysis and project it for the reader.
|
||||
pub fn verify_trace(input: TraceVerificationInput<'_>) -> ViewResult<VerifiedRun> {
|
||||
let raw: RawTrace =
|
||||
serde_json::from_slice(input.trace_bytes).map_err(|err| ViewError::TraceStale {
|
||||
detail: format!("Trace v2 is not valid JSON: {err}"),
|
||||
})?;
|
||||
if raw.schema != "marqdo.trace" {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!("unexpected Trace schema {:?}", raw.schema),
|
||||
});
|
||||
}
|
||||
if raw.schema_version != crate::version::TRACE_PROTOCOL {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"Trace schema_version {} is not supported (View implements v{})",
|
||||
raw.schema_version,
|
||||
crate::version::TRACE_PROTOCOL
|
||||
),
|
||||
});
|
||||
}
|
||||
let expected_digest = sha256_prefixed(input.analysis_bytes);
|
||||
if raw.source.analysis_digest != expected_digest {
|
||||
return Err(ViewError::TraceStale {
|
||||
detail: format!(
|
||||
"trace.source.analysis_digest {} does not match current Analysis {}",
|
||||
raw.source.analysis_digest, expected_digest
|
||||
),
|
||||
});
|
||||
}
|
||||
if raw.source.root_id != input.semantic.project_root_id {
|
||||
return Err(ViewError::TraceStale {
|
||||
detail: format!(
|
||||
"trace.source.root_id {} does not match Analysis project {}",
|
||||
raw.source.root_id, input.semantic.project_root_id
|
||||
),
|
||||
});
|
||||
}
|
||||
let known_modules: std::collections::HashSet<&str> = input
|
||||
.modules
|
||||
.iter()
|
||||
.map(|module| module.id.as_str())
|
||||
.collect();
|
||||
for event in &raw.events {
|
||||
if let Some(module) = event.module_id.as_deref() {
|
||||
if !known_modules.contains(module) {
|
||||
return Err(ViewError::TraceStale {
|
||||
detail: format!(
|
||||
"trace event seq {} references unknown module {module}",
|
||||
event.seq
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let entry_module = input.semantic.module_id.as_str();
|
||||
let statements = input.semantic.all_statements();
|
||||
let mut warnings = Vec::new();
|
||||
let mut counts = EventCounts::default();
|
||||
let mut entry_event_count = 0usize;
|
||||
let mut other_event_count = 0usize;
|
||||
let mut events = Vec::with_capacity(raw.events.len());
|
||||
for event in raw.events {
|
||||
let kind = TraceKind::parse(&event.kind);
|
||||
match kind {
|
||||
TraceKind::CallEnter => counts.call_enter += 1,
|
||||
TraceKind::CallExit => counts.call_exit += 1,
|
||||
TraceKind::BranchEval => counts.branch_eval += 1,
|
||||
TraceKind::LoopIteration => counts.loop_iteration += 1,
|
||||
TraceKind::Return => counts.return_events += 1,
|
||||
TraceKind::Effect => counts.effect += 1,
|
||||
_ => counts.other += 1,
|
||||
}
|
||||
let is_entry = event.module_id.as_deref() == Some(entry_module);
|
||||
if is_entry {
|
||||
entry_event_count += 1;
|
||||
} else {
|
||||
other_event_count += 1;
|
||||
}
|
||||
// Only entry-module spans can be anchored to the rendered document.
|
||||
let (span, anchor_span) = if is_entry {
|
||||
match event.span {
|
||||
Some(span)
|
||||
if input
|
||||
.source_index
|
||||
.validate_span_bytes(input.source.as_bytes(), span) =>
|
||||
{
|
||||
let anchor = statements
|
||||
.iter()
|
||||
.filter(|(_, statement)| {
|
||||
statement.span == span
|
||||
|| statement.condition_span == Some(span)
|
||||
|| statement
|
||||
.arms
|
||||
.iter()
|
||||
.any(|arm| arm.condition_span == Some(span))
|
||||
})
|
||||
.min_by_key(|(_, statement)| statement.span.len())
|
||||
.map(|(_, statement)| statement.span)
|
||||
.or_else(|| {
|
||||
statements
|
||||
.iter()
|
||||
.filter(|(_, statement)| statement.span.contains(span))
|
||||
.min_by_key(|(_, statement)| statement.span.len())
|
||||
.map(|(_, statement)| statement.span)
|
||||
});
|
||||
(Some(span), anchor)
|
||||
}
|
||||
other => {
|
||||
if other.is_some() {
|
||||
warnings.push(format!(
|
||||
"事件 seq {} 的 span 超出当前源码或不在 UTF-8 边界,已取消位置绑定",
|
||||
event.seq
|
||||
));
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
events.push(TraceEvent {
|
||||
seq: event.seq,
|
||||
kind,
|
||||
function_id: event.function_id,
|
||||
module_id: event.module_id,
|
||||
span,
|
||||
raw_span: event.span,
|
||||
anchor_span,
|
||||
detail: event.detail,
|
||||
operation: event.operation,
|
||||
duration_micros: event.duration_micros,
|
||||
});
|
||||
}
|
||||
// Sequence numbers must be strictly increasing; a broken trace is stale.
|
||||
for pair in events.windows(2) {
|
||||
if pair[1].seq <= pair[0].seq {
|
||||
return Err(ViewError::TraceStale {
|
||||
detail: format!(
|
||||
"trace seq is not strictly increasing ({} then {})",
|
||||
pair[0].seq, pair[1].seq
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let truncated = raw.truncated.map(|truncated| Truncation {
|
||||
reason: truncated.reason,
|
||||
limit: truncated.limit,
|
||||
written: truncated.written,
|
||||
});
|
||||
let run_status = if raw.run.status.is_empty() {
|
||||
"ok".to_string()
|
||||
} else {
|
||||
raw.run.status.clone()
|
||||
};
|
||||
let success = input
|
||||
.run_json
|
||||
.get("success")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let error_code = input
|
||||
.run_json
|
||||
.get("error")
|
||||
.and_then(|error| error.get("code"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.or_else(|| {
|
||||
if run_status == "ok" {
|
||||
None
|
||||
} else {
|
||||
Some(run_status.clone())
|
||||
}
|
||||
});
|
||||
let state = if truncated.is_some() {
|
||||
RunDisplayState::Truncated
|
||||
} else if success && run_status == "ok" {
|
||||
RunDisplayState::Succeeded
|
||||
} else {
|
||||
RunDisplayState::Failed
|
||||
};
|
||||
let stdout = bounded_text(input.run_json, "stdout", 64 * 1024);
|
||||
let stderr = bounded_text(input.run_json, "stderr", 64 * 1024);
|
||||
let result_value = input.run_json.get("value").and_then(|value| {
|
||||
let ty = value.get("type").and_then(Value::as_str)?;
|
||||
let display = value
|
||||
.get("decimal")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| value.get("text").and_then(Value::as_str))
|
||||
.or_else(|| value.get("value").and_then(Value::as_str))
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| compact_json(value));
|
||||
Some(RunValue {
|
||||
ty: ty.to_string(),
|
||||
display,
|
||||
})
|
||||
});
|
||||
let _ = sha256_hex(input.trace_bytes);
|
||||
Ok(VerifiedRun {
|
||||
projection: RunProjection {
|
||||
run_id: raw.run.id,
|
||||
entry: raw.run.entry,
|
||||
run_status,
|
||||
state,
|
||||
error_code,
|
||||
analysis_digest: expected_digest,
|
||||
events,
|
||||
truncated,
|
||||
stdout,
|
||||
stderr,
|
||||
exit_code: input.exit_code,
|
||||
result_value,
|
||||
counts,
|
||||
entry_event_count,
|
||||
other_event_count,
|
||||
warnings,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn bounded_text(run_json: &Value, key: &str, limit: usize) -> String {
|
||||
let text = run_json
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if text.len() <= limit {
|
||||
text
|
||||
} else {
|
||||
let mut truncated: String = text.chars().take(limit).collect();
|
||||
truncated.push_str("\n…(输出已截断)");
|
||||
truncated
|
||||
}
|
||||
}
|
||||
|
||||
fn compact_json(value: &Value) -> String {
|
||||
let text = value.to_string();
|
||||
if text.chars().count() > 80 {
|
||||
format!("{}…", text.chars().take(80).collect::<String>())
|
||||
} else {
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a stale run projection that keeps the raw result accessible without
|
||||
/// binding any event to the current document.
|
||||
pub fn stale_projection(analysis_digest: &str, source: &SourceIndex) -> RunProjection {
|
||||
let _ = source;
|
||||
RunProjection {
|
||||
run_id: String::new(),
|
||||
entry: None,
|
||||
run_status: "stale".to_string(),
|
||||
state: RunDisplayState::Stale,
|
||||
error_code: Some("view.trace_stale".to_string()),
|
||||
analysis_digest: analysis_digest.to_string(),
|
||||
events: Vec::new(),
|
||||
truncated: None,
|
||||
stdout: String::new(),
|
||||
stderr: String::new(),
|
||||
exit_code: 0,
|
||||
result_value: None,
|
||||
counts: EventCounts::default(),
|
||||
entry_event_count: 0,
|
||||
other_event_count: 0,
|
||||
warnings: vec!["Trace 与当前 Analysis 字节摘要不匹配,未绑定任何事件。".to_string()],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn state_values_are_stable() {
|
||||
assert_eq!(RunDisplayState::Succeeded.data_value(), "succeeded");
|
||||
assert_eq!(RunDisplayState::Truncated.data_value(), "truncated");
|
||||
assert_eq!(RunDisplayState::Failed.data_value(), "failed");
|
||||
assert_eq!(RunDisplayState::Stale.label(), "结果已过期");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_kinds_are_additive_safe() {
|
||||
assert_eq!(TraceKind::parse("branch.eval"), TraceKind::BranchEval);
|
||||
assert_eq!(
|
||||
TraceKind::parse("future.event"),
|
||||
TraceKind::Other("future.event".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
TraceKind::parse("future.event").data_value(),
|
||||
"future.event"
|
||||
);
|
||||
}
|
||||
}
|
||||
Generated
+62
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"name": "marqdo-view-browser-tests",
|
||||
"version": "0.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "marqdo-view-browser-tests",
|
||||
"version": "0.0.0",
|
||||
"devDependencies": {
|
||||
"playwright": "1.49.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.49.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.49.0.tgz",
|
||||
"integrity": "sha512-eKpmys0UFDnfNb3vfsf8Vx2LEOtflgRebl0Im2eQQnYMA4Aqd+Zw8bEOB+7ZKvN76901mRnqdsiOGKxzVTbi7A==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.49.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.49.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.49.0.tgz",
|
||||
"integrity": "sha512-R+3KKTQF3npy5GTiKH/T+kdhoJfJojjHESR1YEWhYuEKRVfVaxH3+4+GvXE5xyCngCxhxnykk0Vlah9v8fs3jA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "marqdo-view-browser-tests",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"description": "Playwright browser acceptance tests for marqdo-view",
|
||||
"scripts": {
|
||||
"test": "node reader.browser.cjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"playwright": "1.49.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"command": "run",
|
||||
"diagnostics": [],
|
||||
"stderr": "",
|
||||
"stdout": "0\n0\n2\n",
|
||||
"success": true,
|
||||
"trace": [
|
||||
{
|
||||
"duration_micros": 17,
|
||||
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
|
||||
"op": "resource.open",
|
||||
"result": "ok",
|
||||
"seq": 66,
|
||||
"span": {
|
||||
"end": 1581,
|
||||
"start": 1538
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_micros": 2,
|
||||
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
|
||||
"op": "resource.write",
|
||||
"result": "kind=stdio count=2",
|
||||
"seq": 70,
|
||||
"span": {
|
||||
"end": 730,
|
||||
"start": 678
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_micros": 1,
|
||||
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
|
||||
"op": "resource.close",
|
||||
"result": "flushed_bytes=0",
|
||||
"seq": 85,
|
||||
"span": {
|
||||
"end": 1666,
|
||||
"start": 1647
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_micros": 2,
|
||||
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
|
||||
"op": "resource.open",
|
||||
"result": "ok",
|
||||
"seq": 160,
|
||||
"span": {
|
||||
"end": 1581,
|
||||
"start": 1538
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_micros": 0,
|
||||
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
|
||||
"op": "resource.write",
|
||||
"result": "kind=stdio count=2",
|
||||
"seq": 164,
|
||||
"span": {
|
||||
"end": 730,
|
||||
"start": 678
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_micros": 0,
|
||||
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
|
||||
"op": "resource.close",
|
||||
"result": "flushed_bytes=0",
|
||||
"seq": 179,
|
||||
"span": {
|
||||
"end": 1666,
|
||||
"start": 1647
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_micros": 0,
|
||||
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
|
||||
"op": "resource.open",
|
||||
"result": "ok",
|
||||
"seq": 253,
|
||||
"span": {
|
||||
"end": 1581,
|
||||
"start": 1538
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_micros": 0,
|
||||
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
|
||||
"op": "resource.write",
|
||||
"result": "kind=stdio count=2",
|
||||
"seq": 257,
|
||||
"span": {
|
||||
"end": 730,
|
||||
"start": 678
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_micros": 0,
|
||||
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
|
||||
"op": "resource.close",
|
||||
"result": "flushed_bytes=0",
|
||||
"seq": 272,
|
||||
"span": {
|
||||
"end": 1666,
|
||||
"start": 1647
|
||||
}
|
||||
}
|
||||
],
|
||||
"value": {
|
||||
"decimal": "3",
|
||||
"type": "int"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"command": "run",
|
||||
"diagnostics": [],
|
||||
"stderr": "",
|
||||
"stdout": "0\n0\n2\n",
|
||||
"success": true,
|
||||
"trace": [],
|
||||
"value": {
|
||||
"decimal": "3",
|
||||
"type": "int"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"events": [
|
||||
{
|
||||
"detail": null,
|
||||
"function_id": "root:control-flow@0.1.0::index.mq.md::演示.main",
|
||||
"kind": "call.enter",
|
||||
"module_id": "root:control-flow@0.1.0::index.mq.md",
|
||||
"seq": 0,
|
||||
"span": null
|
||||
},
|
||||
{
|
||||
"detail": "continue",
|
||||
"function_id": "root:control-flow@0.1.0::index.mq.md::演示.main",
|
||||
"kind": "loop.iteration",
|
||||
"module_id": "root:control-flow@0.1.0::index.mq.md",
|
||||
"seq": 1,
|
||||
"span": {
|
||||
"end": 197,
|
||||
"start": 182
|
||||
}
|
||||
},
|
||||
{
|
||||
"detail": "false",
|
||||
"function_id": "root:control-flow@0.1.0::index.mq.md::演示.main",
|
||||
"kind": "branch.eval",
|
||||
"module_id": "root:control-flow@0.1.0::index.mq.md",
|
||||
"seq": 2,
|
||||
"span": {
|
||||
"end": 211,
|
||||
"start": 199
|
||||
}
|
||||
},
|
||||
{
|
||||
"detail": "true",
|
||||
"function_id": "root:control-flow@0.1.0::index.mq.md::演示.main",
|
||||
"kind": "branch.eval",
|
||||
"module_id": "root:control-flow@0.1.0::index.mq.md",
|
||||
"seq": 3,
|
||||
"span": {
|
||||
"end": 211,
|
||||
"start": 199
|
||||
}
|
||||
},
|
||||
{
|
||||
"detail": null,
|
||||
"function_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io.mq.md::io.写值",
|
||||
"kind": "call.enter",
|
||||
"module_id": "root:control-flow@0.1.0::index.mq.md",
|
||||
"seq": 4,
|
||||
"span": {
|
||||
"end": 247,
|
||||
"start": 239
|
||||
}
|
||||
},
|
||||
{
|
||||
"detail": "event_budget",
|
||||
"kind": "trace.truncated",
|
||||
"module_id": null,
|
||||
"seq": 5,
|
||||
"span": null
|
||||
}
|
||||
],
|
||||
"limits": {
|
||||
"max_bytes": 33554432,
|
||||
"max_events": 5
|
||||
},
|
||||
"run": {
|
||||
"entry": "root:control-flow@0.1.0::index.mq.md::main",
|
||||
"id": "6-1795317753027990146",
|
||||
"status": "ok"
|
||||
},
|
||||
"schema": "marqdo.trace",
|
||||
"schema_version": 2,
|
||||
"source": {
|
||||
"analysis_digest": "sha256:e2aca5a1a0c9fa073a21b5af7deb8ef493ac981b97c788b721347c24c94f48ab",
|
||||
"root_id": "root:control-flow@0.1.0"
|
||||
},
|
||||
"truncated": {
|
||||
"limit": 5,
|
||||
"reason": "event_budget",
|
||||
"written": 5
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"command": "run",
|
||||
"error": {
|
||||
"code": "call.arity",
|
||||
"column": null,
|
||||
"file": null,
|
||||
"frames": [],
|
||||
"line": null,
|
||||
"message": "`演示.main` is missing required argument `n`",
|
||||
"module_id": null,
|
||||
"origin": "source",
|
||||
"relative_path": null,
|
||||
"span": null
|
||||
},
|
||||
"stderr": "",
|
||||
"stdout": "",
|
||||
"success": false,
|
||||
"trace": []
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"events": [
|
||||
{
|
||||
"detail": null,
|
||||
"function_id": "root:mixed-modes@0.1.0::index.mq.md::演示.main",
|
||||
"kind": "call.enter",
|
||||
"module_id": "root:mixed-modes@0.1.0::index.mq.md",
|
||||
"seq": 0,
|
||||
"span": null
|
||||
}
|
||||
],
|
||||
"limits": {
|
||||
"max_bytes": 33554432,
|
||||
"max_events": 100000
|
||||
},
|
||||
"run": {
|
||||
"entry": "root:mixed-modes@0.1.0::index.mq.md::main",
|
||||
"id": "12-1795317753068595848",
|
||||
"status": "call.arity"
|
||||
},
|
||||
"schema": "marqdo.trace",
|
||||
"schema_version": 2,
|
||||
"source": {
|
||||
"analysis_digest": "sha256:5b13d0cd2044cbe3d5d5f51145a9dd0015e2992400f803dad5f0e42214ce4959",
|
||||
"root_id": "root:mixed-modes@0.1.0"
|
||||
},
|
||||
"truncated": null
|
||||
}
|
||||
+324
-20
@@ -1,6 +1,6 @@
|
||||
//! 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.
|
||||
//! Live server tests over a raw TCP HTTP/1.1 client (no extra deps).
|
||||
//! The server is a real child process so startup, URL output, routing, security
|
||||
//! headers, CSRF and the explicit-run flow are exercised end to end.
|
||||
|
||||
mod common;
|
||||
|
||||
@@ -24,23 +24,37 @@ impl Drop for LiveServer {
|
||||
}
|
||||
|
||||
fn start_server() -> LiveServer {
|
||||
start_server_with(
|
||||
"examples/welcome",
|
||||
"tests/golden/analysis-v2/welcome.json",
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
fn start_server_with(
|
||||
project: &str,
|
||||
analysis_golden: &str,
|
||||
run_golden: Option<&str>,
|
||||
trace_golden: Option<&str>,
|
||||
) -> 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();
|
||||
let golden = std::fs::read(repo_root.join(analysis_golden)).unwrap();
|
||||
core.set_analysis(std::str::from_utf8(&golden).unwrap());
|
||||
if let Some(run_golden) = run_golden {
|
||||
let run = std::fs::read_to_string(repo_root.join(run_golden)).unwrap();
|
||||
let trace =
|
||||
trace_golden.map(|trace| std::fs::read_to_string(repo_root.join(trace)).unwrap());
|
||||
core.set_run(0, &run, trace.as_deref());
|
||||
}
|
||||
|
||||
let mut child = Command::new(common::view_bin())
|
||||
.current_dir(&repo_root)
|
||||
.args([
|
||||
"examples/welcome",
|
||||
"--port",
|
||||
"0",
|
||||
"--no-open",
|
||||
"--marqdo-bin",
|
||||
])
|
||||
.args([project, "--port", "0", "--no-open", "--marqdo-bin"])
|
||||
.arg(&core.script)
|
||||
.env_remove("MARQDO_BIN")
|
||||
.env_remove("MARQDO_TOOL_PROTOCOL")
|
||||
@@ -93,12 +107,37 @@ struct HttpResponse {
|
||||
}
|
||||
|
||||
fn http_get(port: u16, host: Option<&str>, path: &str) -> HttpResponse {
|
||||
http_request(port, host, "GET", path, &[], None)
|
||||
}
|
||||
|
||||
fn http_post(port: u16, path: &str, headers: &[(&str, String)], body: &str) -> HttpResponse {
|
||||
http_request(port, None, "POST", path, headers, Some(body))
|
||||
}
|
||||
|
||||
fn http_request(
|
||||
port: u16,
|
||||
host: Option<&str>,
|
||||
method: &str,
|
||||
path: &str,
|
||||
headers: &[(&str, String)],
|
||||
body: Option<&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");
|
||||
let mut request =
|
||||
format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nAccept: */*\r\n");
|
||||
for (name, value) in headers {
|
||||
request.push_str(&format!("{name}: {value}\r\n"));
|
||||
}
|
||||
if let Some(body) = body {
|
||||
request.push_str(&format!("Content-Length: {}\r\n", body.len()));
|
||||
}
|
||||
request.push_str("\r\n");
|
||||
if let Some(body) = body {
|
||||
request.push_str(body);
|
||||
}
|
||||
stream.write_all(request.as_bytes()).expect("write request");
|
||||
let mut raw = Vec::new();
|
||||
stream.read_to_end(&mut raw).expect("read response");
|
||||
@@ -117,6 +156,18 @@ fn http_get(port: u16, host: Option<&str>, path: &str) -> HttpResponse {
|
||||
}
|
||||
}
|
||||
|
||||
fn csrf_token(page: &str) -> String {
|
||||
page.split("name=\"mq-csrf-token\" content=\"")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('"').next())
|
||||
.expect("csrf meta token")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn json_body(page: &str) -> serde_json::Value {
|
||||
serde_json::from_str(page).expect("json body")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_server_serves_pages_assets_and_health() {
|
||||
let server = start_server();
|
||||
@@ -127,9 +178,9 @@ fn live_server_serves_pages_assets_and_health() {
|
||||
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("data-live=\"true\""));
|
||||
assert!(page.body.contains("mq-csrf-token"));
|
||||
assert!(page.body.contains("data-run-available=\"false\""));
|
||||
|
||||
let css_path = page
|
||||
.body
|
||||
@@ -145,8 +196,10 @@ fn live_server_serves_pages_assets_and_health() {
|
||||
|
||||
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 health = json_body(&health.body);
|
||||
assert_eq!(health["schema"], "marqdo.view-health");
|
||||
assert_eq!(health["protocols"]["analysis"], 2);
|
||||
assert_eq!(health["run_api"], true);
|
||||
|
||||
let document = http_get(server.port, None, "/file?path=guide.mq.md");
|
||||
assert_eq!(document.status, 200);
|
||||
@@ -175,7 +228,6 @@ fn live_server_rejects_dns_rebinding_and_path_escape() {
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -183,10 +235,9 @@ fn live_server_rejects_dns_rebinding_and_path_escape() {
|
||||
#[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{{}}",
|
||||
"PUT /api/run HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}",
|
||||
server.port
|
||||
);
|
||||
stream.write_all(request.as_bytes()).unwrap();
|
||||
@@ -199,6 +250,259 @@ fn live_server_rejects_unknown_methods_and_bad_assets() {
|
||||
assert_eq!(bad_asset.status, 404);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_and_refreshing_never_runs_the_document() {
|
||||
// R-01: ten page loads must produce zero Core `run` invocations.
|
||||
let server = start_server_with(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
);
|
||||
for _ in 0..10 {
|
||||
let page = http_get(server.port, None, "/");
|
||||
assert_eq!(page.status, 200);
|
||||
assert!(page.body.contains("data-run-state=\"not-run\""));
|
||||
assert!(!page.body.contains("mq-run-panel"));
|
||||
}
|
||||
let args = server._core.argv_lines();
|
||||
let run_calls = args
|
||||
.iter()
|
||||
.filter(|line| line.as_str() == "arg=run")
|
||||
.count();
|
||||
assert_eq!(run_calls, 0, "page loads must never call Core run");
|
||||
}
|
||||
|
||||
fn run_and_get_page(server: &LiveServer) -> (String, String) {
|
||||
let page = http_get(server.port, None, "/");
|
||||
let token = csrf_token(&page.body);
|
||||
let response = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
],
|
||||
r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#,
|
||||
);
|
||||
assert_eq!(response.status, 200, "body: {}", response.body);
|
||||
let json = json_body(&response.body);
|
||||
assert_eq!(json["ok"], true);
|
||||
let redirect = json["redirect"].as_str().expect("redirect").to_string();
|
||||
let run_page = http_get(server.port, None, &redirect);
|
||||
assert_eq!(run_page.status, 200);
|
||||
(token, run_page.body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_run_requires_csrf_and_confirm_then_renders_real_trace() {
|
||||
let server = start_server_with(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
);
|
||||
let (_, page) = run_and_get_page(&server);
|
||||
assert!(page.contains("mq-run-panel"));
|
||||
assert!(page.contains("data-run-state=\"succeeded\""));
|
||||
assert!(page.contains("真实 Trace v2 事件"));
|
||||
assert!(page.contains("mq-run-chip"), "inline run chips expected");
|
||||
assert!(
|
||||
page.contains("0\n0\n2"),
|
||||
"Core stdout must be shown escaped"
|
||||
);
|
||||
// Public JSON final value is allowed; per-statement values are not claimed.
|
||||
assert!(page.contains("Core 本次返回值"));
|
||||
assert!(page.contains("<code>3</code>"));
|
||||
assert!(
|
||||
!page.contains("变量值"),
|
||||
"must not claim per-assignment values"
|
||||
);
|
||||
|
||||
let args = server._core.argv_lines();
|
||||
let run_calls = args
|
||||
.iter()
|
||||
.filter(|line| line.as_str() == "arg=run")
|
||||
.count();
|
||||
assert_eq!(run_calls, 1, "exactly one explicit run expected");
|
||||
assert!(args.iter().any(|line| line == "arg=pure"));
|
||||
assert!(args.iter().any(|line| line == "arg=--trace-file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_api_rejects_missing_token_wrong_origin_and_bad_requests() {
|
||||
let server = start_server_with(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
);
|
||||
let body = r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#;
|
||||
|
||||
let no_token = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[("Content-Type", "application/json".to_string())],
|
||||
body,
|
||||
);
|
||||
assert_eq!(no_token.status, 403);
|
||||
assert!(no_token.body.contains("view.run_denied"));
|
||||
|
||||
let page = http_get(server.port, None, "/");
|
||||
let token = csrf_token(&page.body);
|
||||
let wrong_origin = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
("Origin", "https://attacker.example".to_string()),
|
||||
],
|
||||
body,
|
||||
);
|
||||
assert_eq!(wrong_origin.status, 403);
|
||||
|
||||
let no_confirm = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
],
|
||||
r#"{"path":"index.mq.md","mode":"pure","confirm":false}"#,
|
||||
);
|
||||
assert_eq!(no_confirm.status, 400);
|
||||
|
||||
let project_mode = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
],
|
||||
r#"{"path":"index.mq.md","mode":"project","confirm":true}"#,
|
||||
);
|
||||
assert_eq!(project_mode.status, 403);
|
||||
assert!(project_mode.body.contains("pure"));
|
||||
|
||||
let args = server._core.argv_lines();
|
||||
let run_calls = args
|
||||
.iter()
|
||||
.filter(|line| line.as_str() == "arg=run")
|
||||
.count();
|
||||
assert_eq!(run_calls, 0, "rejected requests must never spawn a run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_cache_can_be_cleared_and_stales_after_source_change() {
|
||||
// Use a temporary copy so the test never mutates committed examples while
|
||||
// other test binaries read them.
|
||||
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let project = common::TempProject::new("stale-run-project");
|
||||
project.write(
|
||||
"marqdo.yaml",
|
||||
"project:\n name: control-flow\n version: 0.1.0\n",
|
||||
);
|
||||
let source =
|
||||
std::fs::read_to_string(repo_root.join("examples/control-flow/index.mq.md")).unwrap();
|
||||
let source_path = project.write("index.mq.md", &source);
|
||||
let project_path = project.dir.to_str().unwrap().to_string();
|
||||
let server = start_server_with(
|
||||
&project_path,
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.trace.json"),
|
||||
);
|
||||
|
||||
let page = http_get(server.port, None, "/");
|
||||
let token = csrf_token(&page.body);
|
||||
let response = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
],
|
||||
r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#,
|
||||
);
|
||||
let json = json_body(&response.body);
|
||||
let run_id = json["run_id"].as_str().unwrap().to_string();
|
||||
let redirect = json["redirect"].as_str().unwrap().to_string();
|
||||
let run_page = http_get(server.port, None, &redirect);
|
||||
assert!(run_page.body.contains("mq-run-panel"));
|
||||
|
||||
let clear = http_post(
|
||||
server.port,
|
||||
"/api/clear-run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token.clone()),
|
||||
],
|
||||
&format!(r#"{{"run_id":"{run_id}"}}"#),
|
||||
);
|
||||
assert_eq!(clear.status, 200);
|
||||
let after_clear = http_get(server.port, None, &redirect);
|
||||
assert!(!after_clear.body.contains("mq-run-panel"));
|
||||
|
||||
// Run again, then change the source bytes.
|
||||
let rerun = http_post(
|
||||
server.port,
|
||||
"/api/run",
|
||||
&[
|
||||
("Content-Type", "application/json".to_string()),
|
||||
("X-MQ-CSRF", token),
|
||||
],
|
||||
r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#,
|
||||
);
|
||||
let rerun_json = json_body(&rerun.body);
|
||||
let stale_redirect = rerun_json["redirect"].as_str().unwrap().to_string();
|
||||
std::fs::write(
|
||||
&source_path,
|
||||
format!("{source}\n<!-- changed after run -->\n"),
|
||||
)
|
||||
.unwrap();
|
||||
let stale_page = http_get(server.port, None, &stale_redirect);
|
||||
assert_eq!(stale_page.status, 200);
|
||||
assert!(
|
||||
stale_page.body.contains("data-run-state=\"stale\"")
|
||||
|| stale_page
|
||||
.body
|
||||
.contains("data-source-status=\"source-mismatch\""),
|
||||
"expected stale/source-mismatch marker"
|
||||
);
|
||||
assert!(!stale_page.body.contains("mq-run-chip"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_trace_is_marked_not_claimed_complete() {
|
||||
let server = start_server_with(
|
||||
"examples/control-flow",
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
Some("tests/golden/trace-v2/control-flow.truncated.run.json"),
|
||||
Some("tests/golden/trace-v2/control-flow.truncated.trace.json"),
|
||||
);
|
||||
let (_, page) = run_and_get_page(&server);
|
||||
assert!(page.contains("data-run-state=\"truncated\""));
|
||||
assert!(page.contains("Trace 被截断"));
|
||||
assert!(!page.contains("data-run-state=\"succeeded\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_run_reports_core_error_code_without_fake_success() {
|
||||
let server = start_server_with(
|
||||
"examples/mixed-modes",
|
||||
"tests/golden/analysis-v2/mixed-modes.json",
|
||||
Some("tests/golden/trace-v2/mixed-modes.arity.run.json"),
|
||||
Some("tests/golden/trace-v2/mixed-modes.arity.trace.json"),
|
||||
);
|
||||
// The fake core exits 0 for run, but the run JSON reports failure with the
|
||||
// Core error code; View must surface that instead of a success state.
|
||||
let (_, page) = run_and_get_page(&server);
|
||||
assert!(page.contains("data-run-state=\"failed\""));
|
||||
assert!(page.contains("call.arity"));
|
||||
assert!(!page.contains("data-run-state=\"succeeded\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_verify_output_contract_still_holds_for_installed_style_invocation() {
|
||||
// Regression guard: `view verify` must remain a pure static check.
|
||||
|
||||
@@ -37,6 +37,7 @@ fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String)
|
||||
diagnostics: Vec::new(),
|
||||
navigation,
|
||||
core_version: Some("3.0.0-beta.1".to_string()),
|
||||
run: None,
|
||||
});
|
||||
(model, source)
|
||||
}
|
||||
@@ -210,6 +211,7 @@ fn malicious_markdown_cannot_inject_markup_or_scripts() {
|
||||
diagnostics: Vec::new(),
|
||||
navigation,
|
||||
core_version: None,
|
||||
run: None,
|
||||
});
|
||||
let html = render_live(&model);
|
||||
assert!(!html.contains("<script>alert"));
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Trace v2 contract tests against goldens emitted by the frozen CLI. The
|
||||
//! goldens bind to the committed Analysis v2 bytes by digest, so a changed
|
||||
//! source cannot silently reuse an old trace.
|
||||
|
||||
use marqdo_view::semantic;
|
||||
use marqdo_view::source_map::{sha256_prefixed, SourceIndex};
|
||||
use marqdo_view::trace::{verify_trace, RunDisplayState, TraceVerificationInput};
|
||||
use serde_json::Value;
|
||||
|
||||
struct Fixture {
|
||||
source: String,
|
||||
index: SourceIndex,
|
||||
analysis: Vec<u8>,
|
||||
semantic: semantic::VerifiedAnalysis,
|
||||
}
|
||||
|
||||
fn fixture(analysis_golden: &str, source_path: &str) -> Fixture {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let source = std::fs::read_to_string(root.join(source_path)).unwrap();
|
||||
let index = SourceIndex::new(&source);
|
||||
let analysis = std::fs::read(root.join(analysis_golden)).unwrap();
|
||||
let semantic = semantic::verify_analysis(&analysis, &source, &index, "index.mq.md").unwrap();
|
||||
Fixture {
|
||||
source,
|
||||
index,
|
||||
analysis,
|
||||
semantic,
|
||||
}
|
||||
}
|
||||
|
||||
fn golden_json(path: &str) -> Value {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
serde_json::from_slice(&std::fs::read(root.join(path)).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn golden_bytes(path: &str) -> Vec<u8> {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
std::fs::read(root.join(path)).unwrap()
|
||||
}
|
||||
|
||||
fn verify(
|
||||
fixture: &Fixture,
|
||||
trace_golden: &str,
|
||||
run_golden: &str,
|
||||
exit_code: i32,
|
||||
) -> marqdo_view::trace::VerifiedRun {
|
||||
let trace = golden_bytes(trace_golden);
|
||||
let run_json = golden_json(run_golden);
|
||||
verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace,
|
||||
analysis_bytes: &fixture.analysis,
|
||||
semantic: &fixture.semantic.projection,
|
||||
modules: &fixture.semantic.projection.modules,
|
||||
source: &fixture.source,
|
||||
source_index: &fixture.index,
|
||||
run_json: &run_json,
|
||||
exit_code,
|
||||
})
|
||||
.expect("trace verifies")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_control_flow_trace_binds_and_projects_events() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let run = verify(
|
||||
&fixture,
|
||||
"tests/golden/trace-v2/control-flow.trace.json",
|
||||
"tests/golden/trace-v2/control-flow.run.json",
|
||||
0,
|
||||
);
|
||||
let projection = &run.projection;
|
||||
assert_eq!(projection.state, RunDisplayState::Succeeded);
|
||||
assert_eq!(projection.counts.total(), 285);
|
||||
assert_eq!(projection.entry_event_count, 18);
|
||||
assert_eq!(projection.other_event_count, 267);
|
||||
assert_eq!(projection.run_status, "ok");
|
||||
assert!(projection.truncated.is_none());
|
||||
assert_eq!(projection.stdout, "0\n0\n2\n");
|
||||
let value = projection.result_value.as_ref().expect("return value");
|
||||
assert_eq!(value.ty, "int");
|
||||
assert_eq!(value.display, "3");
|
||||
// Public JSON final value only; never a per-assignment value claim.
|
||||
assert!(projection.analysis_digest.starts_with("sha256:"));
|
||||
|
||||
// The loop header is evaluated four times (three iterations + exit).
|
||||
let loop_span = projection
|
||||
.events
|
||||
.iter()
|
||||
.find(|event| event.anchor_span.is_some() && event.detail.as_deref() == Some("exit"))
|
||||
.and_then(|event| event.anchor_span)
|
||||
.expect("loop anchor");
|
||||
let summary = projection.anchor_summary(loop_span).expect("loop summary");
|
||||
assert_eq!(summary.count, 4);
|
||||
assert_eq!(summary.detail, "loop exit");
|
||||
assert!(summary.kinds.contains(&"loop.iteration".to_string()));
|
||||
|
||||
let return_anchors: Vec<_> = projection
|
||||
.events
|
||||
.iter()
|
||||
.filter(|event| event.anchor_span.is_some())
|
||||
.collect();
|
||||
assert!(!return_anchors.is_empty());
|
||||
// Only entry-module events ever get statement anchors.
|
||||
for event in &projection.events {
|
||||
if event.anchor_span.is_some() {
|
||||
assert_eq!(
|
||||
event.module_id.as_deref(),
|
||||
Some(fixture.semantic.projection.module_id.as_str())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_trace_is_explicitly_marked() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let run = verify(
|
||||
&fixture,
|
||||
"tests/golden/trace-v2/control-flow.truncated.trace.json",
|
||||
"tests/golden/trace-v2/control-flow.truncated.run.json",
|
||||
0,
|
||||
);
|
||||
let projection = &run.projection;
|
||||
assert_eq!(projection.state, RunDisplayState::Truncated);
|
||||
let truncated = projection.truncated.as_ref().expect("truncation");
|
||||
assert_eq!(truncated.reason, "event_budget");
|
||||
assert_eq!(truncated.limit, 5);
|
||||
assert_eq!(truncated.written, 5);
|
||||
assert!(truncated.label().contains("事件数量上限"));
|
||||
assert_ne!(projection.state, RunDisplayState::Succeeded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_run_keeps_the_core_error_code() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/mixed-modes.json",
|
||||
"examples/mixed-modes/index.mq.md",
|
||||
);
|
||||
let run = verify(
|
||||
&fixture,
|
||||
"tests/golden/trace-v2/mixed-modes.arity.trace.json",
|
||||
"tests/golden/trace-v2/mixed-modes.arity.run.json",
|
||||
1,
|
||||
);
|
||||
let projection = &run.projection;
|
||||
assert_eq!(projection.state, RunDisplayState::Failed);
|
||||
assert_eq!(projection.error_code.as_deref(), Some("call.arity"));
|
||||
assert_eq!(projection.run_status, "call.arity");
|
||||
assert!(projection.result_value.is_none());
|
||||
assert_eq!(projection.state.label(), "运行失败");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_analysis_bytes_are_rejected() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let mut tampered = fixture.analysis.clone();
|
||||
tampered.push(b' ');
|
||||
let trace = golden_bytes("tests/golden/trace-v2/control-flow.trace.json");
|
||||
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
|
||||
let err = verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace,
|
||||
analysis_bytes: &tampered,
|
||||
semantic: &fixture.semantic.projection,
|
||||
modules: &fixture.semantic.projection.modules,
|
||||
source: &fixture.source,
|
||||
source_index: &fixture.index,
|
||||
run_json: &run_json,
|
||||
exit_code: 0,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.trace_stale");
|
||||
assert_eq!(err.exit_code(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_event_module_is_rejected() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
|
||||
trace["events"][0]["module_id"] = Value::String("rogue::module.mq.md".to_string());
|
||||
let trace_bytes = serde_json::to_vec(&trace).unwrap();
|
||||
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
|
||||
let err = verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace_bytes,
|
||||
analysis_bytes: &fixture.analysis,
|
||||
semantic: &fixture.semantic.projection,
|
||||
modules: &fixture.semantic.projection.modules,
|
||||
source: &fixture.source,
|
||||
source_index: &fixture.index,
|
||||
run_json: &run_json,
|
||||
exit_code: 0,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.trace_stale");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_monotonic_sequence_is_rejected() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
|
||||
trace["events"][1]["seq"] = Value::Number(0.into());
|
||||
let trace_bytes = serde_json::to_vec(&trace).unwrap();
|
||||
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
|
||||
let err = verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace_bytes,
|
||||
analysis_bytes: &fixture.analysis,
|
||||
semantic: &fixture.semantic.projection,
|
||||
modules: &fixture.semantic.projection.modules,
|
||||
source: &fixture.source,
|
||||
source_index: &fixture.index,
|
||||
run_json: &run_json,
|
||||
exit_code: 0,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.trace_stale");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_schema_major_is_a_protocol_error_not_a_stale_trace() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
|
||||
trace["schema_version"] = Value::Number(3.into());
|
||||
let trace_bytes = serde_json::to_vec(&trace).unwrap();
|
||||
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
|
||||
let err = verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace_bytes,
|
||||
analysis_bytes: &fixture.analysis,
|
||||
semantic: &fixture.semantic.projection,
|
||||
modules: &fixture.semantic.projection.modules,
|
||||
source: &fixture.source,
|
||||
source_index: &fixture.index,
|
||||
run_json: &run_json,
|
||||
exit_code: 0,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.protocol_incompatible");
|
||||
assert_eq!(err.exit_code(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn golden_digest_is_really_sha256_of_analysis_bytes() {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let analysis = std::fs::read(root.join("tests/golden/analysis-v2/control-flow.json")).unwrap();
|
||||
let trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
|
||||
assert_eq!(
|
||||
trace["source"]["analysis_digest"].as_str().unwrap(),
|
||||
sha256_prefixed(&analysis)
|
||||
);
|
||||
assert_eq!(
|
||||
trace["source"]["root_id"].as_str().unwrap(),
|
||||
"root:control-flow@0.1.0"
|
||||
);
|
||||
}
|
||||
@@ -20,6 +20,18 @@ mkdir -p "$out"
|
||||
"$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"
|
||||
# Trace v2 goldens come from the same frozen binary (pure mode, no grants).
|
||||
out_trace="tests/golden/trace-v2"
|
||||
mkdir -p "$out_trace"
|
||||
( cd examples/control-flow \
|
||||
&& "$MARQDO_BIN" run index.mq.md --mode pure --json --trace-file "$repo_root/$out_trace/control-flow.trace.json" > "$repo_root/$out_trace/control-flow.run.json" )
|
||||
( cd examples/control-flow \
|
||||
&& "$MARQDO_BIN" run index.mq.md --mode pure --json --trace-max-events 5 --trace-file "$repo_root/$out_trace/control-flow.truncated.trace.json" > "$repo_root/$out_trace/control-flow.truncated.run.json" )
|
||||
if ( cd examples/mixed-modes \
|
||||
&& "$MARQDO_BIN" run index.mq.md --mode pure --json --trace-file "$repo_root/$out_trace/mixed-modes.arity.trace.json" > "$repo_root/$out_trace/mixed-modes.arity.run.json" ); then
|
||||
echo "error: mixed-modes without params unexpectedly ran" >&2
|
||||
exit 1
|
||||
fi
|
||||
# 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
|
||||
|
||||
Reference in new issue
Block a user