Refactor executable library handbooks and improve document reading

This commit is contained in:
cflmy committed 2026-11-08 22:19:11 +08:00
1 parent 16c44588d5
commit c50c515c4a
191 files changed
+29572 -7816

No files matched your search

@@ -2,6 +2,8 @@
markup: occlusion
title: S2 G06 效应传递与未知不纯
status: implemented
import:
fs: lib/fs.mq.md
---
## save
+40 -18
View File
@@ -198,7 +198,24 @@ fn assert_import_err(path: &str, library: &str, origin: &str, caller: &str, subs
for backend in ["tree", "bytecode"] {
let (code, stdout, stderr) = run(&["run", path, "--backend", backend]);
assert_ne!(code, 0, "{path} backend={backend} unexpectedly succeeded stdout={stdout}");
let origin = format!("{library}:{origin}:");
let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(library);
let module = marqdo::load::load_module(&source).expect("load actual library origin");
let mut lines = Vec::new();
for function in &module.functions {
marqdo::ast::walk_stmts(function, &mut |statement| {
if let marqdo::ast::Stmt::Return { value, span } = statement {
let mut payload = value;
while let marqdo::ast::Expr::Occluded { payload: Some(inner), .. } = payload {
payload = inner;
}
if let marqdo::ast::Expr::Call(call) = payload {
if call.callee == origin { lines.push(span.line); }
}
}
});
}
assert_eq!(lines.len(), 1, "expected one instruction {origin} in {library}");
let origin = format!("{library}:{}:1:", lines[0]);
assert!(stderr.lines().next().unwrap_or("").contains(&origin),
"{path} backend={backend} missing actual library origin {origin:?}: {stderr}");
let caller = format!(" from {path}:{caller}");
@@ -1575,16 +1592,21 @@ fn ext_mq_md_never_calls_host() {
#[test]
fn catalog_includes_agent_kb_concepts() {
let dir = tempfile_dir("mq-cat-kb");
// Ensure a concept exists under tests/ext agent-kb (offline reuse test leaves one).
let (code, _, stderr) = run(&[
"run",
"tests/ext/agent-kb-reuse.mq.md",
]);
// Own the seed and scan root: other agent tests may create/delete their
// private .marqdo files concurrently under tests/ext.
ensure_agent_plugin_built();
let scan = tempfile_dir("mq-cat-kb-source");
let seed = scan.join("seed.mq.md");
std::fs::copy(
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/ext/agent-kb-reuse.mq.md"),
&seed,
).unwrap();
let (code, _, stderr) = run(&["run", seed.to_str().unwrap()]);
assert_eq!(code, 0, "seed kb via reuse test: {stderr}");
let (code, _, stderr) = run(&[
"catalog",
"tests/ext",
scan.to_str().unwrap(),
"-o",
dir.to_str().unwrap(),
"--no-knowledge",
@@ -1922,7 +1944,7 @@ fn lib_json_vsafe_refuse() {
assert_import_err(
"tests/lib/json-vsafe-refuse.mq.md",
"lib/json.mq.md",
"16:1",
"host_json_parse",
"10:1",
"json: integer outside V_safe",
);
@@ -1933,7 +1955,7 @@ fn lib_json_vsafe_stringify_refuse() {
assert_import_err(
"tests/lib/json-vsafe-stringify-refuse.mq.md",
"lib/json.mq.md",
"24:1",
"host_json_stringify",
"11:1",
"json: integer outside V_safe",
);
@@ -3671,7 +3693,7 @@ fn lib_foreign_session_vsafe_refuse() {
assert_import_err(
"tests/lib/foreign-session-vsafe-refuse.mq.md",
"lib/foreign.mq.md",
"207:1",
"host_foreign_session_set",
"12:1",
"json: integer outside V_safe",
);
@@ -3686,7 +3708,7 @@ fn lib_foreign_session_use_after_close() {
assert_import_err(
"tests/lib/foreign-session-use-after-close.mq.md",
"lib/foreign.mq.md",
"198:1",
"host_foreign_session_eval",
"12:1",
"foreign session",
);
@@ -3701,7 +3723,7 @@ fn lib_foreign_session_double_close() {
assert_import_err(
"tests/lib/foreign-session-double-close.mq.md",
"lib/foreign.mq.md",
"231:1",
"host_foreign_session_close",
"12:1",
"foreign session",
);
@@ -3713,7 +3735,7 @@ fn lib_foreign_session_use_before_open() {
assert_import_err(
"tests/lib/foreign-session-use-before-open.mq.md",
"lib/foreign.mq.md",
"198:1",
"host_foreign_session_eval",
"10:1",
"session id must be a handle",
);
@@ -3728,7 +3750,7 @@ fn lib_foreign_session_handle_no_serialize() {
assert_import_err(
"tests/lib/foreign-session-handle-no-serialize.mq.md",
"lib/json.mq.md",
"24:1",
"host_json_stringify",
"12:1",
"session handle cannot be serialized",
);
@@ -3743,7 +3765,7 @@ fn lib_foreign_session_result_vsafe_refuse() {
assert_import_err(
"tests/lib/foreign-session-result-vsafe-refuse.mq.md",
"lib/foreign.mq.md",
"198:1",
"host_foreign_session_eval",
"11:1",
"json: integer outside V_safe",
);
@@ -3767,7 +3789,7 @@ fn lib_foreign_session_cold_replay_empty() {
assert_import_err(
"tests/lib/foreign-session-cold-replay-empty.mq.md",
"lib/foreign.mq.md",
"198:1",
"host_foreign_session_eval",
"13:1",
"foreign session",
);
@@ -3782,7 +3804,7 @@ fn lib_foreign_vsafe_refuse() {
assert_import_err(
"tests/lib/foreign-vsafe-refuse.mq.md",
"lib/json.mq.md",
"16:1",
"host_json_parse",
"21:1",
"json: integer outside V_safe",
);
@@ -3797,7 +3819,7 @@ fn lib_foreign_vsafe_postarith_refuse() {
assert_import_err(
"tests/lib/foreign-vsafe-postarith-refuse.mq.md",
"lib/json.mq.md",
"16:1",
"host_json_parse",
"22:1",
"json: integer outside V_safe",
);
+461
View File
@@ -0,0 +1,461 @@
//! Exercise the authoring rules and actual package workflows, including repaired old paths.
use serde_json::Value;
use std::{
fs,
path::{Path, PathBuf},
process::Command,
sync::OnceLock,
};
fn root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
for e in fs::read_dir(dir).unwrap() {
let p = e.unwrap().path();
if p.is_dir() {
sources(&p, out)
} else if p.to_string_lossy().ends_with(".mq.md") {
out.push(p)
}
}
}
fn native() {
static READY: OnceLock<()> = OnceLock::new();
READY.get_or_init(|| {
let out = Command::new("cargo")
.current_dir(root())
.args([
"build",
"--offline",
"-p",
"marqdo_plugin_agent",
"-p",
"marqdo_plugin_linalg",
])
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let out = Command::new("bash")
.current_dir(root())
.arg("scripts/build-web-plugin.sh")
.env("GOFLAGS", "-buildvcs=false")
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
});
}
fn command() -> Command {
let mut c = Command::new(env!("CARGO_BIN_EXE_marqdo"));
c.current_dir(root())
.env("MARQDO_EXT", root().join("ext"))
.env("MARQDO_LIB", root().join("lib"));
for (name, file) in [
("WEB", "plugins/web/build/libweb.so"),
("AGENT", "target/debug/libagent.so"),
("LINALG", "target/debug/liblinalg.so"),
] {
c.env(format!("MARQDO_{name}_PLUGIN"), root().join(file));
}
c
}
fn call(backend: &str, file: &str, function: &str, args: &[&str], effects: &str) -> Value {
let mut cmd = command();
let mut root_arg = None;
if effects.contains("fs.write") {
let work = std::env::temp_dir().join(format!("mq-authoring-data-{}", std::process::id()));
fs::create_dir_all(&work).unwrap();
root_arg = Some(format!("root=\"{}\"", work.display()));
cmd.arg("call").arg("--fs-root").arg(work);
} else {
cmd.arg("call");
}
let out = cmd
.args([
"--backend",
backend,
"--json",
"--effects",
effects,
file,
function,
])
.args(args)
.args(root_arg)
.output()
.unwrap();
let v: Value = serde_json::from_slice(&out.stdout).unwrap_or_else(|_| {
panic!(
"{file} {function}: {} {}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
)
});
assert!(out.status.success(), "{backend} {file} {function}: {v}");
assert_eq!(v["ok"], true, "{v}");
v["result"].clone()
}
#[test]
fn all_library_units_follow_the_single_source_guide() {
let mut paths = Vec::new();
sources(&root().join("lib"), &mut paths);
sources(&root().join("ext"), &mut paths);
assert!(paths.len() >= 125);
let mut gaps = Vec::new();
for path in paths {
let source = fs::read_to_string(&path).unwrap();
let module = marqdo::load::load_module(&path)
.unwrap_or_else(|e| panic!("{}: {e:#}", path.display()));
let diagnostics = marqdo::check::check_path(&path).unwrap();
if !diagnostics.is_empty() {
gaps.push(format!("{}: {diagnostics:?}", path.display()))
}
for report in marqdo::narrative_ratio::measure_source_units(&source, &module.functions) {
if report.ratio <= 0.5 {
gaps.push(format!(
"{} {} narrative {:.1}%",
path.display(),
report.name,
report.ratio * 100.0
))
}
}
fn units(
functions: &[marqdo::ast::Function],
source: &str,
path: &Path,
gaps: &mut Vec<String>,
) {
for f in functions {
let c = f
.contract
.as_ref()
.unwrap_or_else(|| panic!("{} {} missing contract", path.display(), f.name));
assert!(
c.returns.is_some(),
"{} {} no return contract",
path.display(),
f.name
);
assert_eq!(
c.params.len(),
f.params.len(),
"{} {} parameter mismatch",
path.display(),
f.name
);
assert!(
f.params.iter().all(|p| p.inferred),
"{} {} legacy parameter",
path.display(),
f.name
);
let first = source
.lines()
.skip(f.span.line as usize)
.find(|l| !l.trim().is_empty())
.unwrap();
if !first.starts_with(if f.params.is_empty() {
"| 返回 |"
} else {
"| 参数 |"
}) {
gaps.push(format!(
"{} {} contracts are not directly below heading",
path.display(),
f.name
))
}
units(&f.children, source, path, gaps);
}
}
units(&module.functions, &source, &path, &mut gaps);
let mut fence = false;
for (line, text) in source.lines().enumerate() {
let t = text.trim();
if t.starts_with("```") {
fence = !fence;
continue;
}
if fence {
continue;
}
if t.starts_with("+ `") {
gaps.push(format!("{}:{} legacy parameters", path.display(), line + 1))
}
if t.starts_with('>') {
gaps.push(format!("{}:{} isolated call", path.display(), line + 1))
}
if t.starts_with('*')
&& t.ends_with('*')
&& !t.starts_with("**_ =")
&& !t.trim_matches('*').trim_end().ends_with('=')
{
gaps.push(format!(
"{}:{} isolated statement/return",
path.display(),
line + 1
))
}
}
}
assert!(
gaps.is_empty(),
"{} authoring gaps:\n{}",
gaps.len(),
gaps.join("\n")
);
}
#[test]
fn new_package_workflows_return_real_results_on_both_backends() {
native();
for backend in ["tree", "bytecode"] {
let cached = call(
backend,
"ext/data/index.mq.md",
"memory_cache",
&["key=\"manual-test\"", "value=\"retained\""],
"plugin",
);
assert_eq!(cached["value"], "retained");
let tx = call(
backend,
"ext/data/index.mq.md",
"transaction_roundtrip",
&[],
"plugin,fs.write",
);
assert_eq!(tx["rows"].as_array().unwrap().len(), 1);
assert_eq!(tx["rows"][0]["title"], "committed");
fs::remove_dir_all(tx["work_dir"].as_str().unwrap()).unwrap();
for (held, allowed) in [("notes:read", true), ("notes:write", false)] {
let arg = format!("held=\"{held}\"");
let result = call(
backend,
"ext/security/index.mq.md",
"check_permission",
&[&arg, "needed=\"notes:read\""],
"plugin",
);
assert_eq!(result["ok"], true);
assert_eq!(result["allowed"], allowed);
}
assert_eq!(
call(
backend,
"ext/net/index.mq.md",
"encode",
&["text=\"Marqdo notes/one\""],
"none"
),
"Marqdo%20notes%2Fone"
);
for (file, entry) in [
("ext/linalg/index.mq.md", "solve_example"),
("ext/linalg/索引.mq.md", "求解示例"),
] {
let result = call(backend, file, entry, &[], "plugin");
let rows = &result["x"]["data"];
assert!(
(rows[0][0].as_f64().unwrap() - 2.0).abs() < 1e-9,
"{result}"
);
assert!(
(rows[1][0].as_f64().unwrap() - 1.0).abs() < 1e-9,
"{result}"
);
}
for (file, entry) in [
("ext/ai/index.mq.md", "offline_example"),
("ext/ai/索引.mq.md", "离线示例"),
] {
assert_eq!(call(backend, file, entry, &[], "none"), "Hello world");
}
let usage = call(
backend,
"ext/ai/llm/index.mq.md",
"usage",
&["data={\"usage\":{\"prompt_tokens\":2,\"completion_tokens\":3,\"total_tokens\":5}}"],
"none",
);
assert_eq!(usage["total_tokens"], 5);
let policy = call(
backend,
"ext/ai/policies/step-route.mq.md",
"routes",
&[],
"none",
);
assert_eq!(policy["kind"][0], "lookup");
assert_eq!(policy["backend"][4], "auto");
}
}
#[test]
fn chinese_step_runs_its_body_instead_of_returning_a_prose_word() {
native();
let path = std::env::temp_dir().join(format!(
"mq-authoring-chinese-step-{}.mq.md",
std::process::id()
));
fs::write(
&path,
r#"---
markup: occlusion
import:
智能: ext/ai/智能体.mq.md
表: lib/表.mq.md
json: lib/json.mq.md
---
# 回复器
*None*
## 运行
根据上下文`提示`生成离线固定回答;本例不连接模型服务。
**字符数 = len value=`提示`**
*"deterministic answer"*
# main
**模型 = 回复器()**
**工具 = 表.空表()**
**执行器 = 智能.智能体(大模型=`模型`, 工具=`工具`, 站立提示="")**
**结果 = > `执行器`.单步 任务="offline step" 写回=False**
**wire = json.stringify value=`结果`**
> print text=`wire`
"#,
)
.unwrap();
for backend in ["tree", "bytecode"] {
let output = command()
.args(["run", path.to_str().unwrap(), "--backend", backend])
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let v: Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(v["status"], "ok");
assert_eq!(v["task"], "offline step");
assert_eq!(v["result"], "deterministic answer");
}
fs::remove_file(path).unwrap();
}
#[test]
fn pair_records_preserve_nulls_last_value_and_source_rows() {
for backend in ["tree", "bytecode"] {
for (file, entry, argument) in [
("lib/table.mq.md", "from_pairs", "pairs"),
("lib/表.mq.md", "键值转记录", "键值对"),
] {
assert_eq!(
call(backend, file, entry, &[&format!("{argument}=[]")], "none"),
serde_json::json!({})
);
let rows = format!("{argument}=[{{\"key\":\"first\",\"value\":1}},{{\"key\":\"null\",\"value\":null}},{{\"key\":\"first\",\"value\":3,\"ignored\":true}}]");
assert_eq!(
call(backend, file, entry, &[&rows], "none"),
serde_json::json!({"first":3,"null":null})
);
}
let path =
std::env::temp_dir().join(format!("mq-pair-records-{}.mq.md", std::process::id()));
fs::write(
&path,
r#"---
import:
table: lib/table.mq.md
json: lib/json.mq.md
---
# main
`rows` =
| @ | key | value |
|---|---|---|
| 1 | first | 1 |
| 2 | second | None |
| 3 | first | 3 |
**original = json.stringify(value=`rows`)**
**record = table.from_pairs(pairs=`rows`)**
**after = json.stringify(value=`rows`)**
**keys = table.keys(map=`record`)**
`out` =
| original | after | keys |
|---|---|---|
| `original` | `after` | `keys` |
**wire = json.stringify(value=`out`)**
> print text=`wire`
"#,
)
.unwrap();
let output = command()
.args(["run", path.to_str().unwrap(), "--backend", backend])
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let value: Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(value["original"], value["after"]);
assert_eq!(value["keys"], serde_json::json!(["first", "second"]));
fs::remove_file(path).unwrap();
}
}
#[test]
fn shipped_package_sources_include_their_runtime_imports_and_entries() {
use std::collections::BTreeSet;
let catalog = marqdo::ext_cli::CATALOG;
let files: BTreeSet<_> = catalog
.iter()
.flat_map(|p| p.mq_files.iter().copied())
.collect();
for package in catalog {
for file in package.mq_files {
let path = root().join("ext").join(file);
let module = marqdo::load::load_module(&path).unwrap();
for import in &module.imports {
if let Some(dependency) = import.path.strip_prefix("ext/") {
assert!(
files.contains(dependency),
"{} imports an unshipped source {}",
path.display(),
import.path
);
}
}
}
}
for entry in [
"ai/index.mq.md",
"ai/索引.mq.md",
"ai/llm/index.mq.md",
"ai/policies/step-route.mq.md",
"data/index.mq.md",
"net/index.mq.md",
"security/index.mq.md",
"linalg/index.mq.md",
"linalg/索引.mq.md",
] {
assert!(files.contains(entry), "unshipped entry {entry}");
}
}
File diff suppressed because it is too large. Load diff
+79
View File
@@ -0,0 +1,79 @@
// Exercise actual reader DOM, side-note geometry, accessibility and offline export.
const assert = require('node:assert/strict');
const { chromium } = require(process.env.MARQDO_PLAYWRIGHT_MODULE || 'playwright');
let browser;
(async()=>{
browser=await chromium.launch({headless:true,executablePath:process.env.MARQDO_CHROMIUM||undefined,args:['--no-sandbox']});
const page=await browser.newPage({viewport:{width:1440,height:1000}}), errors=[];
page.on('pageerror',e=>errors.push(e.message));
await page.route('https://**/*',route=>route.abort());
await page.goto(process.argv[2]);await page.waitForTimeout(300);
const surface=page.locator('#structure');
assert.deepEqual(await surface.locator('.occl-label').allTextContents(),['按件数计算金额','由作者补充具体业务','购买两件商品','使用默认件数','依次累计数量','输出累计值','说明输入为空']);
assert.equal(await surface.locator('.occl-stub').count(),1);
assert.match(await surface.locator('.occl-stub').textContent(),/待补充实际逻辑/);
const sentence=surface.locator('.doc-prose-line').filter({hasText:'先第一笔'});
const text=await sentence.innerText();
assert(text.includes('购买两件商品')&&text.includes('使用默认件数'));
assert(!text.includes('计算小计(')&&!text.includes('单价=12'));
const actions=await surface.locator('.occl-label').evaluateAll(nodes=>nodes.map(n=>({id:n.dataset.logicId,label:n.textContent})));
for(const a of actions){
assert.equal(await page.locator('#'+a.id+'-note').count(),1,'one note for '+a.label);
assert.equal(await page.locator('#'+a.id+'-source').count(),1,'unique source '+a.label);
}
for(const width of [1920,1440,1100,1024,1000,800,390]){
await page.setViewportSize({width,height:1000});await page.waitForTimeout(120);
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),'horizontal overflow '+width);
const notes=await surface.locator('.annot-implementation.is-margin-note').count();
if(width>=1440) assert(notes>0,'wide logic notes');
if(width<=1000) assert.equal(notes,0,'mobile must use native disclosures');
assert.deepEqual(await page.locator('.is-margin-note').evaluateAll(nodes=>{
const rects=nodes.map(n=>n.getBoundingClientRect()),issues=[];
for(let i=0;i<rects.length;i++){
const a=rects[i];if(a.left<0||a.right>innerWidth)issues.push('offscreen');
for(let j=i+1;j<rects.length;j++){const b=rects[j];if(a.left<b.right&&b.left<a.right&&a.top<b.bottom&&b.top<a.bottom)issues.push('overlap');}
}return issues;
}),[],'note geometry '+width);
}
await page.setViewportSize({width:1440,height:1000});await page.waitForTimeout(100);
const source=surface.locator('.occl-label').filter({hasText:'购买两件商品'});
await source.hover();
const noteId=await source.getAttribute('data-logic-id');
assert(await page.locator('#'+noteId+'-note').evaluate(n=>n.classList.contains('is-focus')),'source highlights actual implementation');
await source.click();
assert(await page.locator('#reader-dialog').evaluate(n=>n.open));
assert((await page.locator('#reader-dialog-content pre').textContent()).includes('计算小计(单价=12, 数量=2)'));
await page.keyboard.press('Escape');
await surface.locator('.knowledge-explain').first().click();
assert(await page.locator('.knowledge-block').evaluate(n=>n.open));
assert((await page.locator('.knowledge-card[open]').first().innerText()).includes('每件商品的价格'));
const technical=page.locator('.knowledge-card[open] .knowledge-technical').first();
assert.equal(await technical.evaluate(n=>n.open),false,'identities folded initially');
for(const href of await page.locator('.knowledge-step a,.knowledge-source-link,.knowledge-explain').evaluateAll(nodes=>nodes.map(n=>n.getAttribute('href')))){
assert(await page.evaluate(href=>!!document.getElementById(href.slice(1)),href),'broken source link '+href);
}
assert.equal(await page.locator('.knowledge-error').count(),0,'knowledge must load for one example');
await page.locator('[data-reader-action="more"]').click();
await page.getByRole('button',{name:'可执行知识',exact:true}).click();
assert.equal(await page.locator('#reader-dialog-content .knowledge-panel').count(),1);
await page.keyboard.press('Escape');
await page.waitForFunction(()=>!!document.querySelector('.knowledge-block .knowledge-panel'));
assert.equal(await page.locator('.knowledge-block .knowledge-panel').count(),1,'restore actual panel');
await page.locator('#reader-syntax-guide summary').click();
assert.equal(await page.locator('[data-construct-id]').count(),19);
// Read-only no-script fallback still exposes native details and real source text.
const context=await browser.newContext({javaScriptEnabled:false,viewport:{width:390,height:900}});
const plain=await context.newPage();await plain.goto(process.argv[2]);
const note=plain.locator('.annot-implementation').first();await note.locator('summary').click();
assert(await note.locator('.annot-value').isVisible());
assert.equal(await plain.locator('.occl-stub').count(),1);
await context.close();
if(process.env.MARQDO_SCREENSHOT_DIR){
const fs=require('node:fs');fs.mkdirSync(process.env.MARQDO_SCREENSHOT_DIR,{recursive:true});
await page.locator('#reader-syntax-guide').evaluate(n=>n.open=false);
await page.screenshot({path:process.env.MARQDO_SCREENSHOT_DIR+'/reading-desktop.png',fullPage:true});
await page.setViewportSize({width:390,height:900});await page.screenshot({path:process.env.MARQDO_SCREENSHOT_DIR+'/reading-mobile.png',fullPage:true});
}
assert.deepEqual(errors,[]);
await browser.close();console.log('reader readability: actions, logic notes, knowledge, source links, responsive and no-JS passed');
})().catch(async error=>{console.error(error);if(browser)await browser.close();process.exitCode=1;});
+127
View File
@@ -0,0 +1,127 @@
//! Reader exports must remain faithful to source facts without evaluating them.
use std::{
fs,
path::PathBuf,
process::Command,
sync::atomic::{AtomicU64, Ordering},
};
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
struct Scratch(PathBuf);
impl Scratch {
fn new() -> Self {
let path = std::env::temp_dir().join(format!(
"mq-view-reading-{}-{}",
std::process::id(),
SEQUENCE.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&path).unwrap();
Self(path)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn html_files(path: &std::path::Path, files: &mut Vec<PathBuf>) {
for entry in fs::read_dir(path).unwrap() {
let p = entry.unwrap().path();
if p.is_dir() {
html_files(&p, files)
} else if p.extension().is_some_and(|e| e == "html") {
files.push(p)
}
}
}
fn export(source: &std::path::Path, out: &std::path::Path) -> String {
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.current_dir(env!("CARGO_MANIFEST_DIR"))
.args(["view", "output", "--no-exec", "--out"])
.arg(out)
.arg(source)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let mut files = Vec::new();
html_files(out, &mut files);
files
.iter()
.map(|p| fs::read_to_string(p).unwrap())
.find(|s| s.contains("id=\"structure\""))
.unwrap()
}
#[test]
fn single_file_reading_ignores_unrelated_name_collisions_and_never_runs_logic() {
let temp = Scratch::new();
for dir in ["one", "two"] {
let dir = temp.0.join(dir);
fs::create_dir(&dir).unwrap();
fs::write(dir.join("same.mq.md"), "# main\n\n*1*\n").unwrap();
}
let marker = temp.0.join("must-not-exist");
let source = temp.0.join("entry.mq.md");
let text=format!("---\nimport:\n fs: lib/fs.mq.md\n---\n# main\n\n**[写入标记](fs.write_text(path={}, text=\"read must not execute\"))**\n",serde_json::to_string(&marker.to_string_lossy()).unwrap());
fs::write(&source, &text).unwrap();
let html = export(&source, &temp.0.join("out"));
assert!(!marker.exists(), "--no-exec performed the occluded write");
assert!(
html.contains("class=\"knowledge-panel\""),
"knowledge failed: {html}"
);
assert!(!html.contains("knowledge-error\""));
let structure = html
.split("<div class=\"structure\" id=\"structure\">")
.nth(1)
.unwrap()
.split("class=\"knowledge-panel\"")
.next()
.unwrap();
assert!(structure.contains("写入标记</button>"));
assert!(structure.contains("class=\"annot-chip annot-implementation\""));
assert!(
!structure.contains("class=\"annot-chip annot-bind"),
"unrun source acquired a runtime result"
);
}
#[test]
fn knowledge_cards_use_real_contracts_and_keep_verification_states_separate() {
let temp = Scratch::new();
let source = temp.0.join("reading.mq.md");
fs::write(&source, include_str!("../examples/view-reading.mq.md")).unwrap();
let html = export(&source, &temp.0.join("out"));
let panel = html
.split("aria-label=\"可执行知识\"")
.nth(1)
.unwrap()
.split("id=\"mq-knowledge-presentation\"")
.next()
.unwrap();
for label in [
"需要什么输入",
"返回什么",
"调用边界",
"当前有哪些依据",
"测试记录",
"内容来源",
"领域审阅",
"技术详情",
] {
assert!(panel.contains(label), "missing {label}");
}
assert!(panel.contains("每件商品的价格"));
assert!(panel.contains("不包含额外税费或优惠"));
assert!(panel.contains("没有可用记录") && panel.contains("尚未进行领域审阅"));
assert!(!panel.contains("Signature</dt>") && !panel.contains("Verification</dt>"));
assert!(panel.contains("未检查锁定状态"));
let structure = html
.split("<div class=\"structure\" id=\"structure\">")
.nth(1)
.unwrap();
assert!(
structure.contains("由作者补充具体业务</button><span class=\"occl-stub\">待补充实际逻辑")
);
}
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env node
// Exercise current embedded libraries through the public browser ABI.
import fs from 'node:fs';
import assert from 'node:assert/strict';
const {instance}=await WebAssembly.instantiate(fs.readFileSync(process.argv[2]),{});
const e=instance.exports, enc=new TextEncoder(),dec=new TextDecoder();
function boot(source,expectedOk=true){
const bytes=enc.encode(source),p=e.mq_alloc(bytes.length);
new Uint8Array(e.memory.buffer,p,bytes.length).set(bytes);
const out=e.mq_boot(p,bytes.length);e.mq_dealloc(p,bytes.length);
const length=new DataView(e.memory.buffer).getUint32(out,true);
const value=JSON.parse(dec.decode(new Uint8Array(e.memory.buffer,out+4,length)));
e.mq_dealloc(out,length+4);assert.equal(value.ok,expectedOk,JSON.stringify(value));return expectedOk?value.value:value;
}
const summary=boot(`---
markup: occlusion
import:
table: lib/table.mq.md
---
# main
\`rows\` =
| @ | team | n |
|---|---|---|
| 1 | a | 1 |
| 2 | b | 4 |
| 3 | a | 2 |
*> table.summarize list=\`rows\` key="team" field="n"*
`);
assert.deepEqual(summary,[{key:'a',count:2,value:3},{key:'b',count:1,value:4}]);
const bytes=boot(`---
markup: occlusion
import:
bytes: lib/bytes.mq.md
---
# main
*> bytes.from_base64 text="AP+A"*
`);
assert.deepEqual(bytes,{_type:'bytes',base64:'AP+A'});
const doc=boot(`---
markup: occlusion
import:
document: lib/document.mq.md
---
# main
*> document.sections text="# Notes"*
`);
assert.equal(doc.length,1);assert.equal(doc[0].title,'Notes');
const config=boot(`---
markup: occlusion
import:
toml: lib/toml.mq.md
---
# main
*> toml.parse text="name='Marqdo'"*
`);
assert.equal(config.name,'Marqdo');
const moment=boot(`---
markup: occlusion
import:
dt: lib/datetime.mq.md
---
# main
*> dt.parse_local text="2024-11-03 01:30:00" zone="America/New_York" ambiguity="earliest"*
`);
assert.equal(moment.ok,true);assert.equal(moment.value.iso,'2024-11-03T01:30:00-04:00');
console.log('wasm stdlib ok: collection, bytes, document, TOML, IANA/DST');
const chunk=boot(`---
markup: occlusion
import:
table: lib/table.mq.md
---
# main
\`values\` =
| n |
|---|
| 1 |
| 2 |
*> table.chunk list=\`values\` size=4294967296*
`);
assert.deepEqual(chunk,[[1,2]]);
const sliced=boot(`---
markup: occlusion
import:
bytes: lib/bytes.mq.md
---
# main
**data = bytes.from_base64 text="AP+A"**
*> bytes.slice data=\`data\` start=4294967296 end=4294967298*
`);
assert.equal(sliced.base64,'');
console.log('wasm 32-bit large-index semantics ok');
const badPut=boot(`---
markup: occlusion
import:
table: lib/table.mq.md
---
# main
\`values\` =
| n |
|---|
| 1 |
| 2 |
\`indices\` =
| index |
|---|
| 4294967296 |
| 1 |
*> table.put in=\`values\` at=\`indices\` value=9*
`,false);
assert.equal(badPut.ok,false);
console.log('wasm nested index overflow is a diagnostic, not a trap');
for (const [module, entry, parameter] of [
['lib/table.mq.md', 'from_pairs', 'pairs'],
['lib/表.mq.md', '键值转记录', '键值对'],
]) {
const result = boot(`---
markup: occlusion
import:
records: ${module}
---
# main
\`fields\` =
| @ | key | value |
|---|---|---|
| 1 | channel | old |
| 2 | empty | None |
| 3 | channel | "source\\|skill" |
The ordered fields retain real nulls. Return *[Build the record from the visible rows](records.${entry}(${parameter}=\`fields\`))*.
`);
assert.deepEqual(result, {channel: 'source|skill', empty: null});
}
assert.equal(boot(`# main\n\nReturn *[multiply x*y and retain the product](2 * (3 + 1))* after calculation.\n`), 8);
console.log('wasm narrative libraries ok: bilingual pair records, escaped GFM pipe, inline occlusion product');