feat(view): capture live snapshots for static export
Add view capture to record per-cell outputs and session summary with source hashes. view output --snapshot consumes the capture without re-executing and rejects source drift. Includes snapshot parsing tests.
This commit is contained in:
1 parent
0f852593bc
commit
74908ebf04
5 files changed
+159
-4
No files matched your search
+1
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
### Added
|
||||
|
||||
- **外联 v3 P0/P1**:session eval 支持 raw stdin(Python/Node 持久内核);`foreign.session inputs=` 支持每 cell 独立 stdin;view 增加每卡 stdin 字段与 Interrupt;静态导出使用 inputs 表;新增 plan generation/add/remove/value API 与 snapshot export/import/replay。
|
||||
- **外联 v3 P0/P1**:session eval 支持 raw stdin(Python/Node 持久内核);`foreign.session inputs=` 支持每 cell 独立 stdin;view 增加每卡 stdin 字段与 Interrupt;静态导出使用 inputs 表;新增 plan generation/add/remove/value API、snapshot export/import/replay,以及 `view capture` / `view output --snapshot`。
|
||||
|
||||
### Fixed
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ v3 必须继续满足以下约束,否则不进入实现:
|
||||
| G5 | ✅ 基本实现 | `session_interrupt` + view Interrupt;Python SIGINT 保留会话;Node 进程可能被终止 |
|
||||
| G4 | ✅ 已实现(API) | add/remove/set-value + generation;view 尚未提供 add/remove UI |
|
||||
| G6 | ✅ 已实现(API) | export/import/replay JSON snapshot;view/CLI 尚未做文件封装 |
|
||||
| G9 | ✅ 已实现(CLI/API 基础) | `view capture` + `view output --snapshot`;source hash 校验 |
|
||||
| G3/G7/G8/G9/G10 | ⏳ 设计已定,未实现 | 见对应章节 |
|
||||
|
||||
## 3. 缺口清单
|
||||
|
||||
+23
-1
@@ -16,7 +16,7 @@ use marqdo::knowledge::{
|
||||
resolve, reuse_json, stale_json, verify, verify_json, write_knowledge, KnowledgeOptions,
|
||||
LearnInput, ReuseBudget,
|
||||
};
|
||||
use marqdo::view::{serve, serve_debug, write_static, DebugOptions, OutputOptions, ViewOptions};
|
||||
use marqdo::view::{serve, serve_debug, write_capture, write_static, CaptureOptions, DebugOptions, OutputOptions, ViewOptions};
|
||||
use marqdo::{Backend, RunOptions};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
@@ -374,6 +374,17 @@ enum ViewAction {
|
||||
|
||||
#[arg(long)]
|
||||
no_exec: bool,
|
||||
|
||||
#[arg(long, value_name = "FILE")]
|
||||
snapshot: Option<PathBuf>,
|
||||
},
|
||||
/// Capture live cell results for `view output --snapshot`
|
||||
Capture {
|
||||
#[arg(value_name = "PATH")]
|
||||
path: Option<PathBuf>,
|
||||
|
||||
#[arg(short = 'o', long = "out", required = true)]
|
||||
out: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -509,6 +520,7 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
path: out_path,
|
||||
out,
|
||||
no_exec,
|
||||
snapshot,
|
||||
}) => {
|
||||
write_static(OutputOptions {
|
||||
path: out_path
|
||||
@@ -516,6 +528,16 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
.unwrap_or_else(|| PathBuf::from(".")),
|
||||
out_dir: out,
|
||||
no_exec,
|
||||
snapshot,
|
||||
})?;
|
||||
Ok(0)
|
||||
}
|
||||
Some(ViewAction::Capture { path: out_path, out }) => {
|
||||
write_capture(CaptureOptions {
|
||||
path: out_path
|
||||
.or(path)
|
||||
.unwrap_or_else(|| PathBuf::from(".")),
|
||||
out,
|
||||
})?;
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ mod notebook_api;
|
||||
mod output;
|
||||
mod render;
|
||||
|
||||
pub use output::{write_static, OutputOptions};
|
||||
pub use output::{write_capture, write_static, CaptureOptions, OutputOptions};
|
||||
|
||||
use std::fs;
|
||||
use std::io::{self, Read};
|
||||
|
||||
+133
-1
@@ -5,8 +5,10 @@ use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::host::foreign_doc::DocumentSession;
|
||||
use crate::host::json::json_to_value;
|
||||
use crate::value::Value;
|
||||
use crate::view::html::{escape, page_file, page_index, LinkMode};
|
||||
use crate::view::{build_file_view, build_root, ViewRoot};
|
||||
@@ -15,6 +17,12 @@ pub struct OutputOptions {
|
||||
pub path: PathBuf,
|
||||
pub out_dir: PathBuf,
|
||||
pub no_exec: bool,
|
||||
pub snapshot: Option<PathBuf>,
|
||||
}
|
||||
|
||||
pub struct CaptureOptions {
|
||||
pub path: PathBuf,
|
||||
pub out: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -23,6 +31,12 @@ struct StaticCellOutput {
|
||||
text: String,
|
||||
}
|
||||
|
||||
fn source_hash(source: &str) -> String {
|
||||
let mut h = Sha256::new();
|
||||
h.update(source.as_bytes());
|
||||
format!("{:x}", h.finalize())
|
||||
}
|
||||
|
||||
fn value_text(v: &Value) -> Option<String> {
|
||||
match v {
|
||||
Value::Text(s) => Some(s.clone()),
|
||||
@@ -171,7 +185,91 @@ fn inject_static_session(html: &str, summary: Option<&Value>) -> String {
|
||||
html.replace("window.MARQDO_VIEW_LIVE = false;", &line)
|
||||
}
|
||||
|
||||
/// Capture live-cell results into a snapshot consumed by `view output --snapshot`.
|
||||
pub fn write_capture(opts: CaptureOptions) -> Result<()> {
|
||||
let root = build_root(&opts.path)?;
|
||||
let mut pages = serde_json::Map::new();
|
||||
for rel_pb in &root.files {
|
||||
let rel = rel_pb.to_string_lossy().replace('\\', "/");
|
||||
let abs = resolve_abs(&root, &rel)?;
|
||||
let vm = build_file_view(&root, &abs, &rel, &[], false)?;
|
||||
let (outputs, summary) = static_page_data(&root, &abs, &vm.preset_stdin);
|
||||
let mut out_map = serde_json::Map::new();
|
||||
for (name, output) in outputs {
|
||||
out_map.insert(
|
||||
name,
|
||||
serde_json::json!({ "ok": output.ok, "text": output.text }),
|
||||
);
|
||||
}
|
||||
let summary_json = summary
|
||||
.as_ref()
|
||||
.and_then(|v| crate::host::json::value_to_json(v).ok())
|
||||
.unwrap_or(serde_json::Value::Null);
|
||||
pages.insert(
|
||||
rel.clone(),
|
||||
serde_json::json!({
|
||||
"source_hash": source_hash(&vm.source),
|
||||
"summary": summary_json,
|
||||
"outputs": out_map,
|
||||
}),
|
||||
);
|
||||
}
|
||||
let doc = serde_json::json!({ "version": 1, "pages": pages });
|
||||
if let Some(parent) = opts.out.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(&opts.out, serde_json::to_string_pretty(&doc)?)
|
||||
.with_context(|| format!("write {}", opts.out.display()))?;
|
||||
eprintln!("marqdo view capture: {} page(s) → {}", root.files.len(), opts.out.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn snapshot_page(
|
||||
snapshot: &serde_json::Value,
|
||||
rel: &str,
|
||||
source: &str,
|
||||
) -> Result<(HashMap<String, StaticCellOutput>, Option<Value>)> {
|
||||
let page = snapshot
|
||||
.get("pages")
|
||||
.and_then(|p| p.get(rel))
|
||||
.ok_or_else(|| anyhow::anyhow!("snapshot has no page `{rel}`"))?;
|
||||
let expected = page
|
||||
.get("source_hash")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
if expected != source_hash(source) {
|
||||
anyhow::bail!("snapshot source hash mismatch for `{rel}`");
|
||||
}
|
||||
let mut outputs = HashMap::new();
|
||||
if let Some(map) = page.get("outputs").and_then(|v| v.as_object()) {
|
||||
for (name, value) in map {
|
||||
outputs.insert(
|
||||
name.clone(),
|
||||
StaticCellOutput {
|
||||
ok: value.get("ok").and_then(|v| v.as_bool()).unwrap_or(false),
|
||||
text: value
|
||||
.get("text")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
let summary = page
|
||||
.get("summary")
|
||||
.filter(|v| !v.is_null())
|
||||
.and_then(|v| json_to_value(v).ok());
|
||||
Ok((outputs, summary))
|
||||
}
|
||||
|
||||
pub fn write_static(opts: OutputOptions) -> Result<()> {
|
||||
let snapshot = match &opts.snapshot {
|
||||
Some(path) => Some(serde_json::from_str::<serde_json::Value>(
|
||||
&fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?,
|
||||
)?),
|
||||
None => None,
|
||||
};
|
||||
let root = build_root(&opts.path)?;
|
||||
fs::create_dir_all(&opts.out_dir)
|
||||
.with_context(|| format!("create {}", opts.out_dir.display()))?;
|
||||
@@ -205,7 +303,9 @@ pub fn write_static(opts: OutputOptions) -> Result<()> {
|
||||
let links = LinkMode::Static {
|
||||
from: Some(rel.clone()),
|
||||
};
|
||||
let (cell_outputs, static_summary) = if opts.no_exec {
|
||||
let (cell_outputs, static_summary) = if let Some(snapshot) = &snapshot {
|
||||
snapshot_page(snapshot, &rel, &vm.source)?
|
||||
} else if opts.no_exec {
|
||||
(HashMap::new(), None)
|
||||
} else {
|
||||
static_page_data(&root, &abs, &vm.preset_stdin)
|
||||
@@ -264,6 +364,38 @@ fn resolve_abs(root: &ViewRoot, rel: &str) -> Result<PathBuf> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn snapshot_page_rejects_source_hash_mismatch() {
|
||||
let snap = serde_json::json!({
|
||||
"pages": {
|
||||
"a.mq.md": {
|
||||
"source_hash": "bad",
|
||||
"summary": null,
|
||||
"outputs": {}
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(snapshot_page(&snap, "a.mq.md", "# main\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_page_reads_outputs_and_summary() {
|
||||
let source = "# main\n";
|
||||
let hash = source_hash(source);
|
||||
let snap = serde_json::json!({
|
||||
"pages": {
|
||||
"a.mq.md": {
|
||||
"source_hash": hash,
|
||||
"summary": {"persistent": false, "cells": [], "kernels": []},
|
||||
"outputs": {"a": {"ok": true, "text": "42"}}
|
||||
}
|
||||
}
|
||||
});
|
||||
let (outputs, summary) = snapshot_page(&snap, "a.mq.md", source).unwrap();
|
||||
assert_eq!(outputs["a"].text, "42");
|
||||
assert!(summary.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn injects_visible_static_cell_outputs() {
|
||||
let html = r#"<div class="card" data-code-name="a"></div><pre class="code-out" hidden></pre>"#;
|
||||
|
||||
Reference in new issue
Block a user