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:
marqdo-view dev committed 2026-11-22 11:38:39 +08:00
1 parent 80ce564f09
commit df1cf9ec24
25 files changed
+5724 -62

No files matched your search

+108 -1
View File
@@ -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> {
+1
View File
@@ -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;
+29
View File
@@ -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
View File
@@ -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 &lt;临时文件&gt;</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
View File
@@ -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
View File
@@ -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"
);
}
}