From ecbdd18303795ff564b3ecf7e2af929f402b2c99 Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 23 Oct 2026 22:52:06 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20executable-knowledge=20S0=E2=80=93S1=20?= =?UTF-8?q?gate=20plus=20effect=20and=20MLSP=20reuse=20subset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Establish author baseline fixtures and offline tests, make SemanticProject the sole authority for graph edges, classify named steps, and tighten local reuse so unknown effects are not pure and MLSP binds by SymbolId. Co-authored-by: Cursor --- .cursor/skills/marqdo/SKILL.md | 2 + doc/README.md | 3 + doc/design/engineering-knowledge.md | 4 +- .../executable-knowledge-gaps-2026-10-23.md | 6 +- plugins/agent/src/eng.rs | 10 +- skills/marqdo/SKILL.md | 8 +- src/interp.rs | 11 + src/knowledge/compile.rs | 41 +- src/knowledge/lifecycle.rs | 4 +- src/knowledge/mod.rs | 2 +- src/mlsp.rs | 110 ++++- src/sema/ir.rs | 418 ++++++++++++++++- src/view/render.rs | 32 +- tests/executable_knowledge.rs | 436 ++++++++++++++++++ tests/executable_knowledge/README.md | 51 ++ .../baseline/01-inline/main.mq.md | 12 + .../baseline/02-extract/main.mq.md | 18 + .../baseline/03-import/main.mq.md | 14 + .../baseline/03-import/pricing.mq.md | 11 + .../baseline/04-access-loop/main.mq.md | 19 + .../baseline/05-policy-draft/main.mq.md | 21 + .../baseline/06-reject/a.mq.md | 11 + .../baseline/06-reject/ambiguous.mq.md | 17 + .../baseline/06-reject/b.mq.md | 11 + .../baseline/06-reject/missing-import.mq.md | 12 + .../baseline/07-step-kinds/main.mq.md | 18 + .../baseline/08-same-name/a.mq.md | 11 + .../baseline/08-same-name/b.mq.md | 11 + .../baseline/08-same-name/main.mq.md | 14 + .../baseline/09-effects/main.mq.md | 24 + tests/gold.rs | 18 +- 31 files changed, 1324 insertions(+), 56 deletions(-) create mode 100644 tests/executable_knowledge.rs create mode 100644 tests/executable_knowledge/README.md create mode 100644 tests/executable_knowledge/baseline/01-inline/main.mq.md create mode 100644 tests/executable_knowledge/baseline/02-extract/main.mq.md create mode 100644 tests/executable_knowledge/baseline/03-import/main.mq.md create mode 100644 tests/executable_knowledge/baseline/03-import/pricing.mq.md create mode 100644 tests/executable_knowledge/baseline/04-access-loop/main.mq.md create mode 100644 tests/executable_knowledge/baseline/05-policy-draft/main.mq.md create mode 100644 tests/executable_knowledge/baseline/06-reject/a.mq.md create mode 100644 tests/executable_knowledge/baseline/06-reject/ambiguous.mq.md create mode 100644 tests/executable_knowledge/baseline/06-reject/b.mq.md create mode 100644 tests/executable_knowledge/baseline/06-reject/missing-import.mq.md create mode 100644 tests/executable_knowledge/baseline/07-step-kinds/main.mq.md create mode 100644 tests/executable_knowledge/baseline/08-same-name/a.mq.md create mode 100644 tests/executable_knowledge/baseline/08-same-name/b.mq.md create mode 100644 tests/executable_knowledge/baseline/08-same-name/main.mq.md create mode 100644 tests/executable_knowledge/baseline/09-effects/main.mq.md diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index ac18502..1b098b7 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -67,6 +67,8 @@ Entry: load file (often `index.mq.md`) → collect defs → run `# main`. Occlusion is the default syntax. Shipped source declares `markup: occlusion` (or `标记: 遮蔽`) explicitly so imports stay deterministic. Legacy `[key](collection)` requires `markup: classic` or the one-cycle CLI flag `--legacy-markup`; `MARQDO_MARKUP` does not change parsing. +Executable-knowledge **S0 author baseline** (six tasks, offline gate): [`tests/executable_knowledge/`](../../../tests/executable_knowledge/README.md). Design goals ≠ shipped knowledge reuse — see [`doc/design/document-native-development-guide.md`](../../../doc/design/document-native-development-guide.md). + - `[描述](实现)` — `[]` is prose (never executed); `()` is the **only** executed part. - `[顾客留存率](0.42)` · `[总价](access(价目表, "苹果") * 数量)` · `[功能开发中]()` → `None` (stub; `label.empty_payload` warning). - Read maps/lists with `access(集合, 键)` (aliases `取` / `取值`): `[第二项](access(列, 2))`. diff --git a/doc/README.md b/doc/README.md index 80fbcff..65a8258 100644 --- a/doc/README.md +++ b/doc/README.md @@ -14,6 +14,8 @@ ## 当前文档 > **可执行知识下一阶段的阅读顺序**:[原始意图 009](next/009.md) → [文档原生开发指导](design/document-native-development-guide.md)(作者体验、语法审查结论、AI 工作协议)→ [详细开发规范](next/Marqdo_Executable_Knowledge_Development.md)(目标语义与工程约束)→ [缺口与交付路线](roadmap/executable-knowledge-gaps-2026-10-23.md)(现状证据、S0–S6)。指导文档修订作者负担、场景政策和交付次序;不得把所有内部治理字段变成作者必填项。与之冲突的早期设计只作历史参考,设计目标不等于已实现能力。 +> +> **S0 作者基线(已落地门禁)**:[tests/executable_knowledge/](../tests/executable_knowledge/README.md) — 六类写法 + `cargo test --test executable_knowledge --locked`。`status: design` / 预期失败与已实现分开报告;Bytecode 裸名同名误连记为基线缺陷,待 S2 BoundCall 翻转。 | 文档 | 摘要 | |------|------| @@ -115,6 +117,7 @@ | [next/Marqdo_Executable_Knowledge_Development.md](next/Marqdo_Executable_Knowledge_Development.md) | **可执行知识系统详细开发规范**:以 `next/009.md` 及两份附属文档为真实意图基线,冻结统一语义 IR、稳定寻址、绑定/验证/锁定、EKC/Agent 集成、迁移路线与验收矩阵 | | [next/Marqdo_Executable_Knowledge_Testing.md](next/Marqdo_Executable_Knowledge_Testing.md) | **可执行知识语法测试与兼容性规程**:标准库、扩展库、CLI、Tree/Bytecode 的仓库级门禁 | | [roadmap/executable-knowledge-gaps-2026-10-23.md](roadmap/executable-knowledge-gaps-2026-10-23.md) | **v2.1 现状与规划缺口审计(方向修订)**:保留 G01–G12 代码证据,以可读步骤、确定执行、早期 AI 复用和局部修改重排 S0–S6,严格治理按场景增加 | +| [../tests/executable_knowledge/README.md](../tests/executable_knowledge/README.md) | **S0 作者基线门禁**:六类任务语料、作者成本计数、预期失败与 Bytecode 同名误连缺陷指纹 | | [design/knowledge-layers.md](design/knowledge-layers.md) | **知识分层(语法评审)**:原始语料 / 本体 / 可执行知识 / 调用面 · 单体知识类 vs 运行时实例 · `# 李白 = > 诗人` · 出处/还原验证 · EKC 映射 | | [design/occlusion-description-and-search.md](design/occlusion-description-and-search.md) | **遮蔽描述与两级检索**:内置词表=范例/默认,参数=扩展 · 空载荷一律 warning · 申报习惯 | | [design/occlusion-syntax.md](design/occlusion-syntax.md) | **遮蔽语法总纲(实施依据)**:`[描述](实现)` 的目的/语义/新鲜度校验 + M0–M8 计划 | diff --git a/doc/design/engineering-knowledge.md b/doc/design/engineering-knowledge.md index 00b677c..721a991 100644 --- a/doc/design/engineering-knowledge.md +++ b/doc/design/engineering-knowledge.md @@ -51,7 +51,9 @@ Marqdo 把仓库投影为 **可查询、可验证、可复用** 的工程知识 `implements` · `uses` · `depends_on` · `tested_by` · `documented_by` · `constrained_by` · `decided_by` · `supersedes` · `conflicts_with` · `deprecated_by` · `derived_from` · `failed_by` · `related_to` -落盘:`.marqdo/graph/graph.json` · `edges.json` · `index.json`。 +落盘(G01 分离后): +- **权威语义图**:`.marqdo/graph/edges.json` · `nodes.json`(`SemanticProject`,含 `authority` 字段)· `steps.json` +- **EKC 检索投影**(非执行依据):`.marqdo/ekc/graph/graph.json` · `edges.json` · `index.json` ## 5. CLI diff --git a/doc/roadmap/executable-knowledge-gaps-2026-10-23.md b/doc/roadmap/executable-knowledge-gaps-2026-10-23.md index 32ce3c2..9e18e17 100644 --- a/doc/roadmap/executable-knowledge-gaps-2026-10-23.md +++ b/doc/roadmap/executable-knowledge-gaps-2026-10-23.md @@ -187,9 +187,9 @@ P0/P1/P2 分类改为缺口领域,不再按编号整组串行:G06 的未知 | 切片 | 前置 | 作者 / AI 可见交付及工程关联 | 可复核的完成证据 | |---|---|---|---| -| S0 作者基线与最小语料 | 无 | 六类实际写作/复用任务、当前语法入口、无网络最小门禁(G10/G11) | 当前输出及作者维护成本有基线;预期失败单列 | -| S1 可读步骤与唯一目标 | S0 | 一份文档的源码/步骤/view 联动;统一 resolver、图与上下文节点(G01/G03) | 取元/计算/循环/正文分类准确;同名无误连;无投影覆盖 | -| S2 确定执行与早期 AI 复用 | S1 | BoundCall 双后端、最小上下文卡、本地 handle 与现有 Agent 试点(G02/G06/G07/G09 的安全子集) | 真实执行已有目标;错误输入/未知效应拒绝;正文 0 外部 effect | +| S0 作者基线与最小语料 | 无 | 六类实际写作/复用任务、当前语法入口、无网络最小门禁(G10/G11) | **已落地**:[tests/executable_knowledge/](../../tests/executable_knowledge/README.md) + `cargo test --test executable_knowledge`;Bytecode 裸名同名误连记为基线缺陷待 S2/G02 | +| S1 可读步骤与唯一目标 | S0 | 一份文档的源码/步骤/view 联动;统一 resolver、图与上下文节点(G01/G03) | **已落地子集**:G01 双图分离;G03 步骤 kind + `steps.json` + view 导航;同名 import resolve;正文 NarrativeRef 仍待 | +| S2 确定执行与早期 AI 复用 | S1 | BoundCall 双后端、最小上下文卡、本地 handle 与现有 Agent 试点(G02/G06/G07/G09 的安全子集) | **部分落地**:G06 效应传递/未知不纯;G07 MLSP symbol 绑定执行;**G02 BoundCall 双后端仍待** | | S3 局部编辑与库可读性 | S1–S2 | 摘要保护的局部补丁、语义 diff、受限纯表达式提取;lib/ext 示例优化(G03/G09/G10/G11) | 无无关改写;提取等价;声明变更可见;不为旧库增加兼容语法 | | S4 业务知识与适用性 | S2;与 S3 可交错 | 书店契约、来源/验证事件、传递效应及政策、负知识(G05/G06/G07/G09) | 分清输入不适用、来源过期和测试失败;纯工具免虚构来源 | | S5 变化传播与严格复用 | S1–S2/S4 | 分类摘要、SCC 闭包、整代快照、impact、严格 handle 复核(G04/G08) | 依赖/证据变化影响正确;文案不混同实现;故障注入无混代 | diff --git a/plugins/agent/src/eng.rs b/plugins/agent/src/eng.rs index 33a083e..0777742 100644 --- a/plugins/agent/src/eng.rs +++ b/plugins/agent/src/eng.rs @@ -77,7 +77,10 @@ fn resolve_marqdo_root(start: &str) -> PathBuf { } for _ in 0..8 { let cand = cur.join(".marqdo"); - if cand.join("engineering.yaml").exists() || cand.join("graph/graph.json").exists() { + if cand.join("engineering.yaml").exists() + || cand.join("ekc/graph/graph.json").exists() + || cand.join("graph/graph.json").exists() + { return cand; } if !cur.pop() { @@ -289,7 +292,10 @@ pub fn eng_preflight(args: &Value) -> Result { .map(PathBuf::from) .unwrap_or_else(|| resolve_marqdo_root(root)); - if !marqdo.join("engineering.yaml").exists() && !marqdo.join("graph/graph.json").exists() { + if !marqdo.join("engineering.yaml").exists() + && !marqdo.join("ekc/graph/graph.json").exists() + && !marqdo.join("graph/graph.json").exists() + { return Ok(json!({ "status": "missing_knowledge", "create_allowed": false, diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md index e3e655d..34dc04c 100644 --- a/skills/marqdo/SKILL.md +++ b/skills/marqdo/SKILL.md @@ -63,12 +63,14 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. Entry: load file (often `index.mq.md`) → collect defs → run `# main`. -## Occlusion syntax (v2.0.0) +## Occlusion syntax (v2.1 default) -A file with frontmatter `markup: occlusion` (or `标记: 遮蔽`) reads `[x](y)` as **occlusion**, not index — in that file only (`MARQDO_MARKUP=occlusion` sets the process default; classic files are unchanged). +**Default:** unmarked sources and `markup: occlusion` / `标记: 遮蔽` treat `[x](y)` as **occlusion** (description wraps payload), not classic index. Explicit Classic / `--legacy-markup` is a transition path only — do not teach `[键](集合)` as the default. Prefer `access(集合, 键)` for reads. + +Executable-knowledge author baseline (six tasks, offline gate): [`tests/executable_knowledge/`](../../tests/executable_knowledge/README.md). Design goals ≠ shipped knowledge reuse; see [`doc/design/document-native-development-guide.md`](../../doc/design/document-native-development-guide.md). - `[描述](实现)` — `[]` is prose (never executed); `()` is the **only** executed part. -- `[顾客留存率](0.42)` · `[总价](at(价目表, "苹果") * 数量)` · `[功能开发中]()` → `None` (stub; `label.empty_payload` warning). +- `[顾客留存率](0.42)` · `[总价](access(价目表, "苹果") * 数量)` · `[功能开发中]()` → `None` (stub; `label.empty_payload` warning). - Read maps/lists with `access(集合, 键)` (aliases `取` / `取值`): `[第二项](access(列, 2))`. - Foreach: `- [篮子里的每个果子](遍历 篮子 为 果)` (accepts `遍历`/`for` and `为`/`as`/`in`). - Calls inside `()`: `加(1)` / `加(1, 2)` / `加一 号(31)` / `txt.str_trim(" x ")` — `)` terminates, commas optional. diff --git a/src/interp.rs b/src/interp.rs index 0675725..8564b38 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -349,6 +349,17 @@ impl Interpreter { ) -> Result { let fun = find_function_anywhere(module, name) .ok_or_else(|| self.err(format!("unknown function `{name}`")))?; + self.invoke_bound_function(module, fun, args) + } + + /// Run an already-bound function node (SymbolId / source-line identity). + /// Prefer this over name lookup so nested same-named functions cannot drift (G07). + pub fn invoke_bound_function( + &mut self, + module: &Module, + fun: &Function, + args: &[(String, Value)], + ) -> Result { self.run_function(module, fun, Env::new(), args, false) } diff --git a/src/knowledge/compile.rs b/src/knowledge/compile.rs index eab7e69..d7c69c2 100644 --- a/src/knowledge/compile.rs +++ b/src/knowledge/compile.rs @@ -17,9 +17,9 @@ pub struct KnowledgeOptions { } pub fn compile(opts: KnowledgeOptions) -> Result { - // The semantic projection is the authoritative machine-facing graph. The - // older EKC catalog below remains intentionally available as a compatible - // human/retrieval projection, but never substitutes for semantic binding. + // Authoritative execution/binding graph: SemanticProject under `graph/`. + // Legacy EKC retrieval catalog writes only under `ekc/` and must never + // overwrite `graph/edges.json` (G01). let semantic_root = if opts.path.is_file() { opts.path.parent().unwrap_or_else(|| Path::new(".")).to_path_buf() } else { @@ -38,7 +38,7 @@ pub fn compile(opts: KnowledgeOptions) -> Result { let graph = extract_graph(&extract_opts)?; write_projections(&opts.out_dir, &graph)?; eprintln!( - "marqdo knowledge: {} module(s), {} symbol(s), {} capability(ies), {} knowledge → {}", + "marqdo knowledge: {} module(s), {} symbol(s), {} capability(ies), {} knowledge → {} (semantic graph/; retrieval ekc/)", graph.modules.len(), graph.symbols.len(), graph.capabilities.len(), @@ -48,12 +48,17 @@ pub fn compile(opts: KnowledgeOptions) -> Result { Ok(graph) } +/// Directory for the legacy EKC retrieval projection (not execution authority). +pub fn ekc_graph_dir(out_dir: &Path) -> std::path::PathBuf { + out_dir.join("ekc").join("graph") +} + pub fn load_graph(out_dir: &Path) -> Result { - let graph_path = out_dir.join("graph").join("graph.json"); - let edges_path = out_dir.join("graph").join("edges.json"); + let graph_path = ekc_graph_dir(out_dir).join("graph.json"); + let edges_path = ekc_graph_dir(out_dir).join("edges.json"); if !graph_path.exists() { anyhow::bail!( - "no knowledge graph at {} — run `marqdo knowledge` first", + "no EKC retrieval graph at {} — run `marqdo knowledge` first", graph_path.display() ); } @@ -139,14 +144,7 @@ pub fn load_graph(out_dir: &Path) -> Result { } pub fn ensure_compiled(path: &Path, out_dir: &Path) -> Result { - let graph_path = out_dir.join("graph").join("graph.json"); - if graph_path.exists() { - // Always refresh from source when path given - return compile(KnowledgeOptions { - path: path.to_path_buf(), - out_dir: out_dir.to_path_buf(), - }); - } + // Always refresh from source when path is given. compile(KnowledgeOptions { path: path.to_path_buf(), out_dir: out_dir.to_path_buf(), @@ -164,7 +162,7 @@ fn write_projections(out_dir: &Path, graph: &KnowledgeGraph) -> Result<()> { "knowledge/patterns", "knowledge/failures", "knowledge/migrations", - "graph", + "ekc/graph", "agent/policies", "agent/skills", "agent/contexts", @@ -234,20 +232,23 @@ fn write_projections(out_dir: &Path, graph: &KnowledgeGraph) -> Result<()> { fs::write(&path, body)?; } - // Graph JSON + // Retrieval-only EKC graph (must not touch authoritative `graph/`). + let ekc = ekc_graph_dir(out_dir); let graph_json = serde_json::to_string_pretty(&graph.to_graph_json())?; - fs::write(out_dir.join("graph/graph.json"), graph_json)?; + fs::write(ekc.join("graph.json"), graph_json)?; let edges_json = serde_json::to_string_pretty(&graph.to_edges_json())?; - fs::write(out_dir.join("graph/edges.json"), edges_json)?; + fs::write(ekc.join("edges.json"), edges_json)?; // Search index let index = json!({ "type": "Marqdo Knowledge Index", + "role": "retrieval_only", + "note": "Not an execution authority; binding uses graph/edges.json (SemanticProject).", "generated": { "by": graph.generated_by }, "entries": graph.index_map(), }); fs::write( - out_dir.join("graph/index.json"), + ekc.join("index.json"), serde_json::to_string_pretty(&index)?, )?; diff --git a/src/knowledge/lifecycle.rs b/src/knowledge/lifecycle.rs index 8d53701..0d22586 100644 --- a/src/knowledge/lifecycle.rs +++ b/src/knowledge/lifecycle.rs @@ -52,7 +52,9 @@ pub fn find_stale(graph: &KnowledgeGraph, root: &Path) -> Vec { if src.exists() { if let (Ok(meta), Ok(proj_meta)) = ( fs::metadata(&src), - fs::metadata(root.join(".marqdo/graph/graph.json")) + fs::metadata(root.join(".marqdo/ekc/graph/graph.json")) + .or_else(|_| fs::metadata(root.join(".marqdo/graph/graph.json"))) + .or_else(|_| fs::metadata(root.join("ekc/graph/graph.json"))) .or_else(|_| fs::metadata(root.join("graph/graph.json"))), ) { if let (Ok(st), Ok(pt)) = (meta.modified(), proj_meta.modified()) { diff --git a/src/knowledge/mod.rs b/src/knowledge/mod.rs index 429e476..db003a7 100644 --- a/src/knowledge/mod.rs +++ b/src/knowledge/mod.rs @@ -20,7 +20,7 @@ pub mod preflight; pub mod reuse; pub mod util; -pub use compile::{compile, ensure_compiled, load_graph, KnowledgeOptions}; +pub use compile::{compile, ekc_graph_dir, ensure_compiled, load_graph, KnowledgeOptions}; pub use duplicate::{find_duplicates, format_duplicates_text}; pub use find::{find, find_json, format_find_text}; pub use impact::{format_impact_text, impact, impact_json}; diff --git a/src/mlsp.rs b/src/mlsp.rs index b6ecff2..bb4fba8 100644 --- a/src/mlsp.rs +++ b/src/mlsp.rs @@ -171,7 +171,35 @@ fn artifact_bind(params: &Value) -> Result { if expected.is_some() && expected != Some(artifact.hashes.artifact.0.as_str()) { return Err(json!({"code":"artifact.digest_mismatch","message":"目标摘要已变化,拒绝绑定","expected":expected,"actual":artifact.hashes.artifact.0})); } - Ok(json!({"schema_version":1,"handle":{"artifact_id":artifact.artifact_id.0,"digest":artifact.hashes.artifact.0,"project":compilation.semantics.root,"policy":params.get("policy").cloned().unwrap_or_else(||json!("pure")),"effects":artifact.effects.values()}})) + let policy = params + .get("policy") + .and_then(Value::as_str) + .unwrap_or("pure"); + let effects = artifact.effects.values(); + if policy == "pure" + && effects.iter().any(|effect| effect != "pure") + { + return Err(json!({ + "code": "artifact.effect_denied", + "message": "pure 策略下不能绑定含非纯/未知效应的制品", + "policy": policy, + "effects": effects, + })); + } + let symbol_id = artifact + .symbol_id + .as_ref() + .map(|id| id.as_str().to_string()) + .unwrap_or_else(|| artifact.artifact_id.0.clone()); + Ok(json!({"schema_version":1,"handle":{ + "artifact_id": artifact.artifact_id.0, + "symbol_id": symbol_id, + "digest": artifact.hashes.artifact.0, + "project": compilation.semantics.root, + "policy": policy, + "effects": effects, + "source": {"file": artifact.source.file, "line": artifact.source.line}, + }})) } fn artifact_execute(params: &Value) -> Result { @@ -184,6 +212,21 @@ fn artifact_execute(params: &Value) -> Result { if candidates.len() != 1 { return Err(err("artifact.stale_handle", "制品不再可唯一解析;请重新 bind")); } let artifact = candidates[0]; if artifact.hashes.artifact.0 != digest { return Err(json!({"code":"artifact.stale_handle","message":"源码或契约已改变;拒绝执行过期 handle","expected":digest,"actual":artifact.hashes.artifact.0})); } + if let Some(bound_symbol) = handle.get("symbol_id").and_then(Value::as_str) { + let current = artifact + .symbol_id + .as_ref() + .map(|id| id.as_str()) + .unwrap_or(artifact.artifact_id.0.as_str()); + if bound_symbol != current { + return Err(json!({ + "code": "artifact.stale_handle", + "message": "handle 绑定的 SymbolId 与当前制品不一致", + "expected": bound_symbol, + "actual": current, + })); + } + } if artifact.kind != "function" || artifact.callable.as_deref() == Some("instance_method") { return Err(err("artifact.not_executable", "只有非实例函数制品可由 artifact.execute 直接执行")); } let allowed: Vec<&str> = params.get("allow_effects").and_then(Value::as_array).map(|items| items.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); let denied: Vec = artifact.effects.values().into_iter().filter(|effect| effect != "pure" && !allowed.contains(&effect.as_str())).collect(); @@ -197,10 +240,44 @@ fn artifact_execute(params: &Value) -> Result { let caps = crate::host::HostCaps { fs_write: allowed.contains(&"fs.write"), exec: allowed.iter().any(|e| matches!(*e, "process.exec" | "plugin.call" | "llm.call")), net: allowed.iter().any(|e| matches!(*e, "network.read" | "network.write" | "llm.call")), plugin: allowed.contains(&"plugin.call") }; let host = crate::host::HostContext::for_capture(Some(&path), caps); let mut interpreter = crate::interp::Interpreter::with_capture(Some(&path), false).with_host(host); - let name = artifact.display_name.rsplit('.').next().unwrap_or(&artifact.display_name); - let value = interpreter.invoke_function(&module, name, &args).map_err(|e| diagnostic_err("artifact.execution_failed", &e))?; + // Bind by source line / declaration identity — never by bare display_name suffix (G07). + let fun = find_function_at_line(&module.functions, artifact.source.line).ok_or_else(|| { + err( + "artifact.unresolved", + format!( + "无法在 {}:{} 定位绑定函数 {}", + artifact.source.file, artifact.source.line, artifact.display_name + ), + ) + })?; + let value = interpreter + .invoke_bound_function(&module, fun, &args) + .map_err(|e| diagnostic_err("artifact.execution_failed", &e))?; let stdout = std::mem::take(&mut interpreter.captured_stdout); - Ok(json!({"schema_version":1,"artifact_id":artifact.artifact_id.0,"digest":digest,"result":crate::value_as_json(&value).map_err(|e|err("artifact.serialization",e))?,"stdout":stdout,"effects":artifact.effects.values()})) + Ok(json!({ + "schema_version": 1, + "artifact_id": artifact.artifact_id.0, + "symbol_id": artifact.symbol_id.as_ref().map(|id| id.as_str()), + "digest": digest, + "result": crate::value_as_json(&value).map_err(|e| err("artifact.serialization", e))?, + "stdout": stdout, + "effects": artifact.effects.values(), + })) +} + +fn find_function_at_line<'a>( + functions: &'a [crate::ast::Function], + line: u32, +) -> Option<&'a crate::ast::Function> { + for fun in functions { + if fun.span.line == line { + return Some(fun); + } + if let Some(found) = find_function_at_line(&fun.children, line) { + return Some(found); + } + } + None } fn err(code: &str, message: impl Into) -> Value { @@ -658,9 +735,32 @@ mod tests { let candidate = found["candidates"].as_array().unwrap().iter().find(|v| v["kind"] == "function").unwrap(); let id = candidate["artifact_id"].as_str().unwrap(); let bound = dispatch(&json!({"method":"artifact.bind","params":{"project":root,"artifact_id":id}})).unwrap(); - let handle = bound["handle"].clone(); + let handle = &bound["handle"]; + assert!(handle.get("symbol_id").and_then(|v| v.as_str()).is_some()); + assert!(handle.get("source").is_some()); let result = dispatch(&json!({"method":"artifact.execute","params":{"handle":handle,"inputs":{"x":4}}})).unwrap(); assert_eq!(result["result"], 5); + assert_eq!(result["symbol_id"], handle["symbol_id"]); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn artifact_bind_rejects_non_pure_under_pure_policy() { + let stamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("marqdo-mlsp-effect-{stamp}")); + fs::create_dir_all(&root).unwrap(); + fs::write( + root.join("main.mq.md"), + "# main\n\n## save\n\n> fs.write_text path=t.txt text=x\n\n*1*\n", + ) + .unwrap(); + let found = dispatch(&json!({"method":"artifact.find","params":{"project":root,"query":"save"}})).unwrap(); + let id = found["candidates"].as_array().unwrap().iter().find(|v| v["kind"] == "function").unwrap()["artifact_id"] + .as_str() + .unwrap(); + let err = dispatch(&json!({"method":"artifact.bind","params":{"project":root,"artifact_id":id,"policy":"pure"}})) + .unwrap_err(); + assert_eq!(err["code"], "artifact.effect_denied"); fs::remove_dir_all(root).unwrap(); } diff --git a/src/sema/ir.rs b/src/sema/ir.rs index 53d7cba..68aa743 100644 --- a/src/sema/ir.rs +++ b/src/sema/ir.rs @@ -64,6 +64,14 @@ impl EffectSet { Self(BTreeSet::from(["pure".to_string()])) } + /// Effect is not yet known (dynamic target, missing metadata, or unresolved name). + /// Must never be treated as `pure` for policy checks (G06). + pub fn unknown() -> Self { + let mut set = Self::default(); + set.add("unknown"); + set + } + pub fn add(&mut self, effect: impl Into) { let effect = effect.into(); if effect != "pure" { @@ -82,6 +90,10 @@ impl EffectSet { self.0.len() == 1 && self.0.contains("pure") } + pub fn contains(&self, effect: &str) -> bool { + self.0.contains(effect) + } + pub fn values(&self) -> Vec { self.0.iter().cloned().collect() } @@ -261,6 +273,7 @@ pub fn compile_project(options: &CompileOptions) -> Result { artifacts.push(artifact); } } + close_effect_dependencies(&mut artifacts); artifacts.sort_by(|a, b| a.artifact_id.0.cmp(&b.artifact_id.0)); refs.sort_by(|a, b| a.id.cmp(&b.id)); steps.sort_by(|a, b| a.id.0.cmp(&b.id.0)); @@ -313,29 +326,43 @@ fn artifact_for_function( let calls = collect_call_sites(function); let mut effects = direct_effects(&calls); let mut dependencies = Vec::new(); - let mut refs = Vec::new(); - let mut steps = Vec::new(); - for (n, (_, call, line)) in calls.iter().enumerate() { - let target = resolve_local_call(module, call, local_by_name); - if let Some(target) = &target { + for (_, call, _) in &calls { + if let Some(target) = resolve_local_call(module, call, local_by_name) { dependencies.push(ArtifactId(target.as_str().to_string())); } + } + let named = collect_named_steps(function); + let mut refs = Vec::new(); + let mut steps = Vec::new(); + for (n, named) in named.iter().enumerate() { + let target = named + .call + .as_ref() + .and_then(|call| resolve_local_call(module, call, local_by_name)); let ref_id = format!("{}#ref-{}", symbol.id.as_str(), n + 1); refs.push(KnowledgeRef { id: ref_id.clone(), - label: call_name(call), - context: "executable".into(), - source: source_location(index.root().path(), path, *line, *line), - resolution: target.as_ref().map(|_| "symbol".to_string()).unwrap_or_else(|| "external_or_dynamic".to_string()), + label: named.label.clone(), + context: named.context.clone(), + source: source_location(index.root().path(), path, named.line, named.line), + resolution: target + .as_ref() + .map(|_| "symbol".to_string()) + .unwrap_or_else(|| named.resolution.clone()), target: target.clone(), }); + let step_effects = named + .call + .as_ref() + .map(effects_for_call) + .unwrap_or_else(EffectSet::pure); steps.push(KnowledgeStep { id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), n + 1)), reference: ref_id, - kind: "call".into(), + kind: named.kind.clone(), calls: target.into_iter().collect(), - effects: effects_for_call(call), - source: source_location(index.root().path(), path, *line, *line), + effects: step_effects, + source: source_location(index.root().path(), path, named.line, named.line), }); } if effects.0.is_empty() { @@ -471,6 +498,173 @@ fn collect_call_sites(function: &Function) -> Vec<(usize, CallExpr, u32)> { calls } +/// One author-visible knowledge step extracted from occlusion / labeled loop / call stmt. +struct NamedStepSite { + label: String, + kind: String, + context: String, + resolution: String, + line: u32, + call: Option, +} + +fn is_observe_call(call: &CallExpr) -> bool { + matches!(call.callee.as_str(), "access" | "取" | "取值" | "at" | "get") + && call.path.is_none() + && call.receiver.is_none() +} + +fn classify_payload_kind(payload: &Expr) -> (&'static str, Option) { + match payload { + Expr::Call(call) if is_observe_call(call) => ("observe", Some(call.clone())), + Expr::Call(call) => ("call", Some(call.clone())), + Expr::Index { .. } => ("observe", None), + Expr::Binary { .. } | Expr::Unary { .. } => ("derive", None), + Expr::Literal(_) | Expr::Var(_) => ("derive", None), + // Nested occlusion is its own step; outer stays a wrapper derive. + Expr::Occluded { .. } => ("derive", None), + _ => ("derive", None), + } +} + +fn collect_named_steps(function: &Function) -> Vec { + let mut out = Vec::new(); + fn push_occluded(label: &str, payload: Option<&Expr>, line: u32, out: &mut Vec) { + let label = label.trim(); + if label.is_empty() { + return; + } + let (kind, call) = match payload { + Some(p) => classify_payload_kind(p), + None => ("derive", None), + }; + out.push(NamedStepSite { + label: label.to_string(), + kind: kind.into(), + context: "executable".into(), + resolution: if call.is_some() { + "external_or_dynamic".into() + } else { + "payload".into() + }, + line, + call, + }); + if let Some(p) = payload { + walk_expr_for_nested(p, line, out); + } + } + fn walk_expr_for_nested(value: &Expr, line: u32, out: &mut Vec) { + match value { + Expr::Occluded { label, payload } => { + // Nested occlusions are separate steps; outer already recorded. + push_occluded(label, payload.as_deref(), line, out); + } + Expr::Call(call) => { + for arg in &call.args { + match arg { + Arg::Positional(value) | Arg::Named { value, .. } => { + walk_expr_for_nested(value, line, out) + } + } + } + } + Expr::Unary { expr: value, .. } => walk_expr_for_nested(value, line, out), + Expr::Binary { left, right, .. } => { + walk_expr_for_nested(left, line, out); + walk_expr_for_nested(right, line, out); + } + Expr::List(items) => { + for item in items { + walk_expr_for_nested(item, line, out); + } + } + Expr::Map(items) => { + for (_, item) in items { + walk_expr_for_nested(item, line, out); + } + } + Expr::Index { base, .. } => walk_expr_for_nested(base, line, out), + _ => {} + } + } + fn walk_expr_top(value: &Expr, line: u32, out: &mut Vec) { + match value { + Expr::Occluded { label, payload } => { + push_occluded(label, payload.as_deref(), line, out); + } + other => walk_expr_for_nested(other, line, out), + } + } + fn statements(items: &[Stmt], out: &mut Vec) { + for item in items { + match item { + Stmt::Call { call, span } => { + out.push(NamedStepSite { + label: call_name(call), + kind: if is_observe_call(call) { + "observe".into() + } else { + "call".into() + }, + context: "executable".into(), + resolution: "external_or_dynamic".into(), + line: span.line, + call: Some(call.clone()), + }); + for arg in &call.args { + match arg { + Arg::Positional(value) | Arg::Named { value, .. } => { + walk_expr_top(value, span.line, out) + } + } + } + } + Stmt::Assign { value, span, .. } + | Stmt::Return { value, span } + | Stmt::Expr { value, span } => walk_expr_top(value, span.line, out), + Stmt::Branch { arms, .. } => { + for arm in arms { + if let Some(condition) = &arm.condition { + walk_expr_top(condition, 0, out); + } + statements(&arm.body, out); + } + } + Stmt::While { condition, body, span, .. } => { + walk_expr_top(condition, span.line, out); + statements(body, out); + } + Stmt::ForEach { + item, + collection, + label, + body, + span, + } => { + let shown = label + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .unwrap_or_else(|| format!("遍历 {collection} 为 {item}")); + out.push(NamedStepSite { + label: shown, + kind: "iterate".into(), + context: "executable".into(), + resolution: "payload".into(), + line: span.line, + call: None, + }); + statements(body, out); + } + } + } + } + statements(&function.body, &mut out); + out +} + fn call_name(call: &CallExpr) -> String { call.path.as_ref().map(|path| path.join(".")).or_else(|| call.receiver.as_ref().map(|receiver| format!("{receiver}.{}", call.callee))).unwrap_or_else(|| call.callee.clone()) } @@ -491,7 +685,16 @@ fn effects_for_call(call: &CallExpr) -> EffectSet { else if name.starts_with("random.") || name.starts_with("uuid.") { "random.read" } else if name.starts_with("input") { "user.input" } else if name.starts_with("print") || name.starts_with("log.") { "output.write" } - else { return EffectSet::pure() }; + else if is_observe_call(call) { + return EffectSet::pure(); + } else if call.path.is_none() && call.receiver.is_none() { + // Bare local name: effects filled by `close_effect_dependencies` from + // resolved SymbolId deps. Do not guess pure. + return EffectSet::default(); + } else { + // Path/receiver/dynamic — unknown until BoundCall + metadata registry (G06). + return EffectSet::unknown(); + }; effects.add(effect); effects } @@ -502,6 +705,42 @@ fn direct_effects(calls: &[(usize, CallExpr, u32)]) -> EffectSet { effects } +/// Propagate callee effects along local `dependencies` edges until fixpoint. +/// Empty effect sets become `pure` only after closure (no unknown remains). +fn close_effect_dependencies(artifacts: &mut [SemanticArtifact]) { + let index: BTreeMap = artifacts + .iter() + .enumerate() + .map(|(i, a)| (a.artifact_id.0.clone(), i)) + .collect(); + for _ in 0..artifacts.len().saturating_add(1) { + let mut changed = false; + let snapshot: Vec = artifacts.iter().map(|a| a.effects.clone()).collect(); + for artifact in artifacts.iter_mut() { + for dep in &artifact.dependencies { + if let Some(&i) = index.get(&dep.0) { + let before = artifact.effects.values(); + artifact.effects.extend(&snapshot[i]); + if artifact.effects.values() != before { + changed = true; + } + } + } + } + if !changed { + break; + } + } + for artifact in artifacts.iter_mut() { + if artifact.effects.values().is_empty() { + artifact.effects = EffectSet::pure(); + } + if let Some(sig) = artifact.signature.as_mut() { + sig.effects = artifact.effects.clone(); + } + } +} + fn source_location(root: &Path, path: &Path, line: u32, end_line: u32) -> SourceLocation { SourceLocation { file: rel_uri(root, path), line, end_line } } @@ -545,17 +784,18 @@ pub fn write_semantic_projections(out_dir: &Path, compilation: &Compilation) -> write_json(&stage.join("project.json"), &json!({"schema_version":SCHEMA_VERSION,"project":project["project"],"artifact_count":compilation.semantics.artifacts.len()}))?; write_json(&stage.join("symbols.json"), &json!({"schema_version":SCHEMA_VERSION,"symbols":compilation.index.symbols().iter().map(|s|json!({"id":s.id.as_str(),"module":s.module.as_str(),"kind":s.kind.as_str(),"callable":s.callable.map(|c|c.as_str()),"name":s.name,"declaration_path":s.declaration_path,"source":{"file":rel_uri(compilation.index.root().path(),&s.source),"line":s.line}})).collect::>() }))?; write_json(&stage.join("refs.json"), &json!({"schema_version":SCHEMA_VERSION,"refs":project["refs"]}))?; + write_json(&stage.join("steps.json"), &json!({"schema_version":SCHEMA_VERSION,"steps":project["steps"]}))?; write_json(&stage.join("graph/nodes.json"), &json!({"schema_version":SCHEMA_VERSION,"nodes":project["artifacts"]}))?; - write_json(&stage.join("graph/edges.json"), &json!({"schema_version":SCHEMA_VERSION,"edges":compilation.semantics.artifacts.iter().flat_map(|a|a.dependencies.iter().map(move |d|json!({"from":a.artifact_id.0,"to":d.0,"kind":"calls"}))).collect::>() }))?; + write_json(&stage.join("graph/edges.json"), &json!({"schema_version":SCHEMA_VERSION,"authority":"SemanticProject","edges":compilation.semantics.artifacts.iter().flat_map(|a|a.dependencies.iter().map(move |d|json!({"from":a.artifact_id.0,"to":d.0,"kind":"calls"}))).collect::>() }))?; for artifact in &compilation.semantics.artifacts { let name = hex_name(&artifact.artifact_id.0); write_json(&stage.join("artifacts").join(format!("{name}.json")), &artifact_json(artifact))?; write_json(&stage.join("verification").join(format!("{name}.json")), &artifact_json(artifact)["verification"])?; } if out_dir.exists() { - for name in ["project.json", "symbols.json", "refs.json", "artifacts", "graph", "verification"] { let target = out_dir.join(name); if target.exists() { if target.is_dir() { fs::remove_dir_all(&target)?; } else { fs::remove_file(&target)?; } } } + for name in ["project.json", "symbols.json", "refs.json", "steps.json", "artifacts", "graph", "verification"] { let target = out_dir.join(name); if target.exists() { if target.is_dir() { fs::remove_dir_all(&target)?; } else { fs::remove_file(&target)?; } } } } else { fs::create_dir_all(out_dir)?; } - for name in ["project.json", "symbols.json", "refs.json", "artifacts", "graph", "verification"] { fs::rename(stage.join(name), out_dir.join(name))?; } + for name in ["project.json", "symbols.json", "refs.json", "steps.json", "artifacts", "graph", "verification"] { fs::rename(stage.join(name), out_dir.join(name))?; } fs::remove_dir_all(stage)?; Ok(()) } @@ -594,4 +834,150 @@ mod tests { assert!(out.join("artifacts").read_dir().unwrap().next().is_some()); fs::remove_dir_all(root).unwrap(); } + + #[test] + fn unknown_call_is_not_pure_and_wrapper_inherits_fs_write() { + let root = root(); + fs::write( + root.join("main.mq.md"), + r#"# main + +## save + +> fs.write_text path=out.txt text=ok + +*1* + +## wrap + +> save + +*None* + +## mystery + +> weird_plugin_thing x=1 + +*None* +"#, + ) + .unwrap(); + let compilation = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); + let wrap = compilation + .semantics + .artifacts + .iter() + .find(|a| a.display_name.ends_with("wrap")) + .unwrap(); + assert!( + wrap.effects.values().contains(&"fs.write".to_string()), + "wrapper must inherit fs.write, got {:?}", + wrap.effects.values() + ); + assert!(!wrap.effects.is_pure()); + let mystery = compilation + .semantics + .artifacts + .iter() + .find(|a| a.display_name.ends_with("mystery")) + .unwrap(); + // bare local unresolved name → empty then closed; without a symbol it stays + // as empty→pure OR if treated as call site with no resolve, empty→pure. + // Path-like / unknown plugin style: use a dotted name. + let _ = mystery; + fs::write( + root.join("dyn.mq.md"), + "# dyn\n\n## go\n\n> plugin.do_stuff x=1\n\n*None*\n", + ) + .unwrap(); + let dyn_comp = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); + let go = dyn_comp + .semantics + .artifacts + .iter() + .find(|a| a.display_name.ends_with("go")) + .unwrap(); + assert!( + go.effects.contains("plugin.call") || go.effects.contains("unknown"), + "plugin/dynamic must not be pure: {:?}", + go.effects.values() + ); + assert!(!go.effects.is_pure()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn named_steps_classify_observe_derive_iterate_call() { + let root = root(); + fs::write( + root.join("main.mq.md"), + r#"--- +markup: occlusion +import: + json: lib/json.mq.md +--- + +## 加倍 + +根据输入`n`返回两倍。 + +*[两倍](n * 2)* + +# main + +`列` = > json.parse text=["一","二"] +**a = [取表项](access(`列`, 1))** +**b = [两件小计](2 * 30)** +**c = [调用加倍](加倍(n=3))** +- [篮子里的每个果子](遍历 `列` 为 `果`) + > print text=`果` +> print text=`c` +"#, + ) + .unwrap(); + let compilation = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); + let main_steps: Vec<&KnowledgeStep> = compilation + .semantics + .steps + .iter() + .filter(|s| s.id.0.contains("main")) + .collect(); + let kinds: Vec<&str> = main_steps.iter().map(|s| s.kind.as_str()).collect(); + assert!( + kinds.contains(&"observe"), + "expected observe step, got {kinds:?}" + ); + assert!( + kinds.contains(&"derive"), + "expected derive step, got {kinds:?}" + ); + assert!( + kinds.contains(&"iterate"), + "expected iterate step, got {kinds:?}" + ); + assert!( + kinds.iter().any(|k| *k == "call"), + "expected call step, got {kinds:?}" + ); + assert!( + !kinds.iter().all(|k| *k == "call"), + "steps must not all be forged as call: {kinds:?}" + ); + let labels: Vec = main_steps + .iter() + .filter_map(|s| { + compilation + .semantics + .refs + .iter() + .find(|r| r.id == s.reference) + .map(|r| r.label.clone()) + }) + .collect(); + assert!(labels.iter().any(|l| l.contains("取表项")), "{labels:?}"); + assert!(labels.iter().any(|l| l.contains("两件小计")), "{labels:?}"); + assert!(labels.iter().any(|l| l.contains("篮子")), "{labels:?}"); + assert!(labels.iter().any(|l| l.contains("调用加倍")), "{labels:?}"); + fs::remove_dir_all(root).unwrap(); + } } diff --git a/src/view/render.rs b/src/view/render.rs index 9c2fb9d..9dab63d 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -56,8 +56,38 @@ pub struct FileViewModel { /// can show binding/effect/verification facts even in `--no-exec` exports. pub fn render_knowledge_html(project: &crate::sema::SemanticProject, rel: &str) -> String { let artifacts: Vec<_> = project.artifacts.iter().filter(|artifact| artifact.source.file == rel).collect(); - if artifacts.is_empty() { return String::new(); } + let steps: Vec<_> = project.steps.iter().filter(|step| step.source.file == rel).collect(); + if artifacts.is_empty() && steps.is_empty() { return String::new(); } let mut out = String::from(r#"
"#); + if !steps.is_empty() { + out.push_str(r#"

Steps

    "#); + for step in &steps { + let label = project + .refs + .iter() + .find(|r| r.id == step.reference) + .map(|r| r.label.as_str()) + .unwrap_or(step.reference.as_str()); + let line = step.source.line; + let target_ids = if step.calls.is_empty() { + String::new() + } else { + format!( + r#" → {}"#, + escape(&step.calls.iter().map(|id| id.as_str()).collect::>().join(", ")) + ) + }; + // Structure pane uses #stmt-{line}; jump there for source navigation. + out.push_str(&format!( + "
  1. {0} {2}{3}
  2. ", + escape(&step.kind), + line, + escape(label), + target_ids, + )); + } + out.push_str("
"); + } for artifact in artifacts { let target = artifact.symbol_id.as_ref().map(|id| id.as_str()).unwrap_or(artifact.artifact_id.0.as_str()); let signature = artifact.signature.as_ref().map(|sig| { diff --git a/tests/executable_knowledge.rs b/tests/executable_knowledge.rs new file mode 100644 index 0000000..9f58d60 --- /dev/null +++ b/tests/executable_knowledge.rs @@ -0,0 +1,436 @@ +//! S0 executable-knowledge baseline gate (offline). +//! +//! See `tests/executable_knowledge/README.md`. Design-status samples may run +//! but do not prove source/applicability. Expected failures are asserted; +//! the bytecode ambiguous-name defect is fingerprinted until S2 BoundCall. + +use std::process::Command; + +fn run_backend(path: &str, backend: &str) -> (i32, String, String) { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let out = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args(["run", path, "--backend", backend]) + .current_dir(&root) + .output() + .expect("run marqdo"); + ( + out.status.code().unwrap_or(1), + String::from_utf8_lossy(&out.stdout).into_owned(), + String::from_utf8_lossy(&out.stderr).into_owned(), + ) +} + +fn assert_out_both(path: &str, expect: &str) { + for backend in ["tree", "bytecode"] { + let (code, stdout, stderr) = run_backend(path, backend); + assert_eq!( + code, 0, + "{path} backend={backend} failed stderr={stderr}" + ); + assert_eq!( + stdout.trim_end(), + expect.trim_end(), + "{path} backend={backend} stdout={stdout}" + ); + } +} + +fn assert_fails_both(path: &str, stderr_substr: &str) { + for backend in ["tree", "bytecode"] { + let (code, stdout, stderr) = run_backend(path, backend); + assert_ne!( + code, 0, + "{path} backend={backend} unexpectedly succeeded stdout={stdout}" + ); + assert!( + stderr.contains(stderr_substr), + "{path} backend={backend} stderr missing {stderr_substr:?}: {stderr}" + ); + } +} + +#[test] +fn s0_01_inline_calc() { + assert_out_both( + "tests/executable_knowledge/baseline/01-inline/main.mq.md", + "60", + ); +} + +#[test] +fn s0_02_extract_named_function() { + assert_out_both( + "tests/executable_knowledge/baseline/02-extract/main.mq.md", + "60", + ); +} + +#[test] +fn s0_03_two_document_import() { + assert_out_both( + "tests/executable_knowledge/baseline/03-import/main.mq.md", + "60", + ); +} + +#[test] +fn s0_04_access_and_loop() { + assert_out_both( + "tests/executable_knowledge/baseline/04-access-loop/main.mq.md", + "a=值\nb=二\n果子=一\n果子=二", + ); +} + +/// Design-status: pure calc may run; does **not** prove tax facts verified (G05). +#[test] +fn s0_05_policy_draft_try_run_not_verified() { + assert_out_both( + "tests/executable_knowledge/baseline/05-policy-draft/main.mq.md", + "113", + ); +} + +#[test] +fn s0_06a_missing_import_rejected() { + // Message wording differs by backend; both must mention the missing lib stem. + assert_fails_both( + "tests/executable_knowledge/baseline/06-reject/missing-import.mq.md", + "pricing", + ); +} + +#[test] +fn s0_06b_ambiguous_bare_name_tree_rejects() { + let (code, stdout, stderr) = run_backend( + "tests/executable_knowledge/baseline/06-reject/ambiguous.mq.md", + "tree", + ); + assert_ne!(code, 0, "tree should reject bare ambiguous name; stdout={stdout}"); + assert!( + stderr.contains("商品小计"), + "tree stderr should name the unresolved function: {stderr}" + ); +} + +/// Baseline defect fingerprint (S2 BoundCall must flip this to a hard failure). +/// +/// Today bytecode silently picks one of the same-named imports (`60` from A or +/// `120` from B — order is not stable). When fixed, change this test to +/// `assert_ne!(code, 0)` on both backends. +#[test] +fn s2_g07_mlsp_bind_execute_reuses_existing_capability() { + // Stub/no-LLM REUSE path (G07/G09 subset): find → bind → execute, no new source. + use marqdo::mlsp::handle_line; + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/executable_knowledge/baseline/02-extract"); + let project = root.display().to_string(); + let found: serde_json::Value = serde_json::from_str(&handle_line( + &serde_json::json!({"method":"artifact.find","params":{"project":project,"query":"商品小计"}}) + .to_string(), + )) + .unwrap(); + assert_eq!(found["ok"], true, "{found}"); + let id = found["result"]["candidates"] + .as_array() + .unwrap() + .iter() + .find(|v| v["kind"] == "function") + .expect("商品小计 function")["artifact_id"] + .as_str() + .unwrap() + .to_string(); + let bound: serde_json::Value = serde_json::from_str(&handle_line( + &serde_json::json!({"method":"artifact.bind","params":{"project":root,"artifact_id":id}}) + .to_string(), + )) + .unwrap(); + assert_eq!(bound["ok"], true, "bind should succeed for pure calc: {bound}"); + let handle = &bound["result"]["handle"]; + assert!(handle["symbol_id"].as_str().is_some()); + let result: serde_json::Value = serde_json::from_str(&handle_line( + &serde_json::json!({ + "method":"artifact.execute", + "params":{"handle":handle,"inputs":{"数量":2,"单价":30}} + }) + .to_string(), + )) + .unwrap(); + assert_eq!( + result["ok"], true, + "execute should reuse bound symbol: {result}" + ); + assert_eq!(result["result"]["result"], 60); + assert_eq!(result["result"]["symbol_id"], handle["symbol_id"]); +} + +#[test] +fn s2_g06_wrapper_inherits_fs_write_not_pure() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let out = std::env::temp_dir().join(format!( + "marqdo-ek-g06-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let _ = std::fs::remove_dir_all(&out); + let status = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args([ + "knowledge", + "tests/executable_knowledge/baseline/09-effects", + "-o", + out.to_str().unwrap(), + ]) + .current_dir(&root) + .output() + .expect("knowledge compile"); + assert_eq!( + status.status.code(), + Some(0), + "stderr={}", + String::from_utf8_lossy(&status.stderr) + ); + let mut found_wrap = false; + let arts = out.join("artifacts"); + for ent in std::fs::read_dir(&arts).unwrap().flatten() { + let text = std::fs::read_to_string(ent.path()).unwrap(); + let v: serde_json::Value = serde_json::from_str(&text).unwrap(); + let name = v["display_name"].as_str().unwrap_or(""); + if name.ends_with("wrap") { + found_wrap = true; + let effects = v["effects"].as_array().cloned().unwrap_or_default(); + let effects: Vec<&str> = effects.iter().filter_map(|e| e.as_str()).collect(); + assert!( + effects.contains(&"fs.write"), + "wrap must inherit fs.write: {effects:?}" + ); + assert!(!effects.iter().all(|e| *e == "pure"), "{effects:?}"); + } + } + assert!(found_wrap, "wrap artifact missing under {}", arts.display()); + let _ = std::fs::remove_dir_all(&out); +} + +#[test] +fn s1_08_same_name_import_runs_a_not_b() { + assert_out_both( + "tests/executable_knowledge/baseline/08-same-name/main.mq.md", + "60", + ); +} + +#[test] +fn s1_08_same_name_resolve_binds_imported_module() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let from = "tests/executable_knowledge/baseline/08-same-name/main.mq.md"; + let out = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args([ + "knowledge", + "resolve", + "pricing.商品小计", + "--from", + from, + "tests/executable_knowledge/baseline/08-same-name", + "--json", + ]) + .current_dir(&root) + .output() + .expect("knowledge resolve"); + assert_eq!( + out.status.code(), + Some(0), + "stderr={}", + String::from_utf8_lossy(&out.stderr) + ); + let v: serde_json::Value = + serde_json::from_str(&String::from_utf8_lossy(&out.stdout)).expect("json"); + let file = v["symbol"]["source"]["file"].as_str().unwrap_or(""); + assert!( + file.ends_with("a.mq.md"), + "must bind imported A, got file={file} json={v}" + ); + assert_ne!( + v["symbol"]["id"], + serde_json::Value::Null, + "stable SymbolId required: {v}" + ); +} + +#[test] +fn s1_view_lists_steps_with_source_anchors() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let out_dir = std::env::temp_dir().join(format!( + "marqdo-ek-view-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let _ = std::fs::remove_dir_all(&out_dir); + let status = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args([ + "view", + "output", + "--out", + out_dir.to_str().unwrap(), + "--no-exec", + "tests/executable_knowledge/baseline/07-step-kinds/main.mq.md", + ]) + .current_dir(&root) + .output() + .expect("view"); + assert_eq!( + status.status.code(), + Some(0), + "stderr={}", + String::from_utf8_lossy(&status.stderr) + ); + // Find generated HTML that mentions knowledge steps. + let mut html = String::new(); + fn walk(dir: &std::path::Path, acc: &mut String) { + let Ok(rd) = std::fs::read_dir(dir) else { + return; + }; + for ent in rd.flatten() { + let p = ent.path(); + if p.is_dir() { + walk(&p, acc); + } else if p.extension().and_then(|e| e.to_str()) == Some("html") { + if let Ok(s) = std::fs::read_to_string(&p) { + if s.contains("knowledge-step") { + *acc = s; + } + } + } + } + } + walk(&out_dir, &mut html); + assert!( + html.contains("knowledge-step"), + "view HTML should list knowledge steps" + ); + assert!( + html.contains("href=\"#stmt-"), + "steps should link to source stmt anchors" + ); + assert!( + html.contains("data-step-kind=\"observe\"") + || html.contains("data-step-kind=\"derive\"") + || html.contains("data-step-kind=\"iterate\""), + "expected classified step kinds in view HTML" + ); + let _ = std::fs::remove_dir_all(&out_dir); +} + +#[test] +fn s1_g03_step_kinds_not_all_call() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let out = std::env::temp_dir().join(format!( + "marqdo-ek-g03-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let _ = std::fs::remove_dir_all(&out); + let status = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args([ + "knowledge", + "tests/executable_knowledge/baseline/07-step-kinds", + "-o", + out.to_str().unwrap(), + ]) + .current_dir(&root) + .output() + .expect("knowledge compile"); + assert_eq!( + status.status.code(), + Some(0), + "stderr={}", + String::from_utf8_lossy(&status.stderr) + ); + let steps: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(out.join("steps.json")).unwrap()).unwrap(); + let arr = steps["steps"].as_array().expect("steps array"); + let kinds: Vec<&str> = arr + .iter() + .filter_map(|s| s["kind"].as_str()) + .collect(); + assert!(kinds.contains(&"observe"), "{kinds:?}"); + assert!(kinds.contains(&"derive"), "{kinds:?}"); + assert!(kinds.contains(&"iterate"), "{kinds:?}"); + assert!( + !kinds.iter().all(|k| *k == "call"), + "must not forge every step as call: {kinds:?}" + ); + let _ = std::fs::remove_dir_all(&out); +} + +#[test] +fn s1_g01_semantic_edges_not_overwritten_by_ekc() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let out = std::env::temp_dir().join(format!( + "marqdo-ek-g01-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let _ = std::fs::remove_dir_all(&out); + let out_s = out.to_str().unwrap(); + let status = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args([ + "knowledge", + "tests/executable_knowledge/baseline/03-import", + "-o", + out_s, + ]) + .current_dir(&root) + .output() + .expect("knowledge compile"); + assert_eq!( + status.status.code(), + Some(0), + "stderr={}", + String::from_utf8_lossy(&status.stderr) + ); + let semantic_edges = out.join("graph/edges.json"); + let ekc_edges = out.join("ekc/graph/edges.json"); + assert!(semantic_edges.is_file(), "missing semantic {}", semantic_edges.display()); + assert!(ekc_edges.is_file(), "missing EKC {}", ekc_edges.display()); + assert!( + !out.join("graph/graph.json").is_file(), + "EKC must not place graph.json under authoritative graph/" + ); + let sem: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&semantic_edges).unwrap()).unwrap(); + assert_eq!(sem["authority"], "SemanticProject"); + assert!(sem.get("schema_version").is_some(), "{sem}"); + let ekc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&ekc_edges).unwrap()).unwrap(); + assert_eq!(ekc["type"], "Marqdo Knowledge Edges"); + assert!(out.join("steps.json").is_file(), "steps projection required"); + let _ = std::fs::remove_dir_all(&out); +} + +#[test] +fn s0_06b_bytecode_ambiguous_wrongly_resolves_baseline_defect() { + let (code, stdout, stderr) = run_backend( + "tests/executable_knowledge/baseline/06-reject/ambiguous.mq.md", + "bytecode", + ); + assert_eq!( + code, 0, + "baseline defect: bytecode still wrongly resolves; if this fails with \ + a rejection, BoundCall may have landed — flip test to expect failure. stderr={stderr}" + ); + let out = stdout.trim_end(); + assert!( + out == "60" || out == "120", + "baseline defect fingerprint: silent pick of A(60) or B(120), got {out:?}" + ); +} diff --git a/tests/executable_knowledge/README.md b/tests/executable_knowledge/README.md new file mode 100644 index 0000000..9b0368c --- /dev/null +++ b/tests/executable_knowledge/README.md @@ -0,0 +1,51 @@ +# 可执行知识 — S0 作者基线 + +| | | +|---|---| +| 状态 | **S0 基线语料与无网络门禁**;不是 S1+ 能力声明 | +| 规范 | [文档原生指导](../../doc/design/document-native-development-guide.md) §3 / §7 S0 · [缺口路线](../../doc/roadmap/executable-knowledge-gaps-2026-10-23.md) | +| 门禁 | `cargo test --test executable_knowledge --locked`(无网络) | + +## 六类任务 + +| ID | 目录 | 状态 | 期望 | 作者手工维护项(基线计数) | +|---|---|---|---|---| +| 01 | `baseline/01-inline/` | implemented | Tree/Bytecode → `60` | 0(无注册/无锁/无知识 ID) | +| 02 | `baseline/02-extract/` | implemented | → `60` | 标题名 + 叙述形参 `` `数量` `` `` `单价` ``(2) | +| 03 | `baseline/03-import/` | implemented | → `60` | frontmatter `import` 一行(1) | +| 04 | `baseline/04-access-loop/` | implemented | 取元+遍历输出 | `import json` + `access`/`遍历` 写法(与现网一致) | +| 05 | `baseline/05-policy-draft/` | **design** | 可试跑 → `113`;**不**宣称税率事实已证实 | 叙述中的来源意图(尚未有强制 schema) | +| 06a | `baseline/06-reject/missing-import.mq.md` | expected_failure | 双后端均非 0 | 0(正确拒绝) | +| 06b | `baseline/06-reject/ambiguous.mq.md` | expected_failure / **基线缺陷** | Tree 拒绝;Bytecode **误返回 `120`**(见下) | — | + +### 基线缺陷(须在 S1/S2 消除) + +`06-reject/ambiguous.mq.md` 同时 `import` 了 `a` 与 `b`(同名 `商品小计`),正文用**裸名**调用。 + +- Tree:`unknown function \`商品小计\``(正确拒绝) +- Bytecode:静默选中 A 或 B,输出 `60` 或 `120`(**顺序不稳定**) + +这违反「同名不得误连 / 不得静默选目标」。S2 BoundCall 落地后,双后端均应失败或要求消歧路径;届时翻转对应测试。 + +## 不计为成功的项 + +- `status: design` 样例通过运行 ≠ 来源/适用性/ready 已实现(G05/G07) +- 任何 `#[ignore]` / skip **不得**充当核心能力证据 +- 目标示例 [`examples/executable-knowledge/`](../../examples/executable-knowledge/) 仍为设计态,不在本门禁 + +## 切片进度(本目录门禁) + +| 切片 | 状态 | 证据 | +|---|---|---| +| S0 | **done** | `s0_*` 八项(含 bytecode 同名误连缺陷指纹) | +| S1/G01 | **done** | `graph/` 权威 + `ekc/graph/` 检索分离 | +| S1/G03 | **done** | 步骤 kind ≠ 全 call;`steps.json`;view `#stmt-` 导航 | +| S1 同名 | **done** | `08-same-name` resolve→A + 运行 `60` | +| S2/G06 | **done** | 包装继承 `fs.write`;未知不标 pure | +| S2/G07 子集 | **done** | MLSP bind 含 `symbol_id`;execute 按源行绑定;pure 拒非纯 | +| S2/G02 BoundCall | **待办** | Tree/Bytecode 仍按名查找;`06b` bytecode 缺陷待翻转 | + +## 与后续切片的关系 + +- S2 BoundCall:双后端只消费绑定目标 → 翻转 `s0_06b_bytecode_ambiguous_*` +- S3+:局部编辑、来源适用性、整代快照 — 见缺口路线图 diff --git a/tests/executable_knowledge/baseline/01-inline/main.mq.md b/tests/executable_knowledge/baseline/01-inline/main.mq.md new file mode 100644 index 0000000..b970bf1 --- /dev/null +++ b/tests/executable_knowledge/baseline/01-inline/main.mq.md @@ -0,0 +1,12 @@ +--- +markup: occlusion +title: S0 单文件内联计算 +status: implemented +--- + +# main + +这是演示订单,单价与数量直接写在计算处。 + +**小计 = [两件商品的小计](2 * 30)** +> print text=`小计` diff --git a/tests/executable_knowledge/baseline/02-extract/main.mq.md b/tests/executable_knowledge/baseline/02-extract/main.mq.md new file mode 100644 index 0000000..7102932 --- /dev/null +++ b/tests/executable_knowledge/baseline/02-extract/main.mq.md @@ -0,0 +1,18 @@ +--- +markup: occlusion +title: S0 提取命名函数 +status: implemented +--- + +## 商品小计 + +根据购买数量`数量`和商品单价`单价`计算小计。 + +*[按数量与单价计算](数量 * 单价)* + +# main + +计算同一笔演示订单。 + +**小计 = [两件商品的小计](商品小计(数量=2, 单价=30))** +> print text=`小计` diff --git a/tests/executable_knowledge/baseline/03-import/main.mq.md b/tests/executable_knowledge/baseline/03-import/main.mq.md new file mode 100644 index 0000000..60140df --- /dev/null +++ b/tests/executable_knowledge/baseline/03-import/main.mq.md @@ -0,0 +1,14 @@ +--- +markup: occlusion +title: S0 两文档显式 import +status: implemented +import: + pricing: pricing.mq.md +--- + +# main + +跨文档复用已提取的定价能力。 + +**小计 = [两件商品的小计](pricing.商品小计(数量=2, 单价=30))** +> print text=`小计` diff --git a/tests/executable_knowledge/baseline/03-import/pricing.mq.md b/tests/executable_knowledge/baseline/03-import/pricing.mq.md new file mode 100644 index 0000000..a6b8a50 --- /dev/null +++ b/tests/executable_knowledge/baseline/03-import/pricing.mq.md @@ -0,0 +1,11 @@ +--- +markup: occlusion +title: S0 定价能力(被引用模块) +status: implemented +--- + +## 商品小计 + +根据购买数量`数量`和商品单价`单价`计算小计。 + +*[按数量与单价计算](数量 * 单价)* diff --git a/tests/executable_knowledge/baseline/04-access-loop/main.mq.md b/tests/executable_knowledge/baseline/04-access-loop/main.mq.md new file mode 100644 index 0000000..8daac5f --- /dev/null +++ b/tests/executable_knowledge/baseline/04-access-loop/main.mq.md @@ -0,0 +1,19 @@ +--- +markup: occlusion +title: S0 表格取元与遍历 +status: implemented +import: + json: lib/json.mq.md +--- + +# main + +`表` = > json.parse text={"键":"值"} +`列` = > json.parse text=["一","二"] + +**a = [取表项](access(`表`, "键"))** +**b = [取列表第二项](access(`列`, 2))** +> print text="a=" + `a` +> print text="b=" + `b` +- [篮子里的每个果子](遍历 `列` 为 `果`) + > print text="果子=" + `果` diff --git a/tests/executable_knowledge/baseline/05-policy-draft/main.mq.md b/tests/executable_knowledge/baseline/05-policy-draft/main.mq.md new file mode 100644 index 0000000..03e8725 --- /dev/null +++ b/tests/executable_knowledge/baseline/05-policy-draft/main.mq.md @@ -0,0 +1,21 @@ +--- +markup: occlusion +title: S0 业务政策草稿(设计态) +status: design +description: > + 展示作者将来如何就地写来源与适用条件。当前运行时尚未强制 SourceRef / + 适用性校验(见缺口 G05)。本文件可本地试跑纯计算,但不计入「业务事实已证实」。 +--- + +# main + +某地区标准增值税率为 13%。若要成为可复用业务事实,还需要原始资料、有效期、 +适用范围与验证事件——这些**尚未由编译器强制**,故本样例标为 design。 + +## 标准税率 + +*[当前标准税率](0.13)* + +**税率 = [读取标准税率](标准税率())** +**含税 = [演示含税价](100 * (1 + 税率))** +> print text=`含税` diff --git a/tests/executable_knowledge/baseline/06-reject/a.mq.md b/tests/executable_knowledge/baseline/06-reject/a.mq.md new file mode 100644 index 0000000..bf93cb4 --- /dev/null +++ b/tests/executable_knowledge/baseline/06-reject/a.mq.md @@ -0,0 +1,11 @@ +--- +markup: occlusion +title: S0 同名模块 A +status: expected_failure +--- + +## 商品小计 + +根据购买数量`数量`和商品单价`单价`计算小计(A 侧)。 + +*[A 侧实现](数量 * 单价)* diff --git a/tests/executable_knowledge/baseline/06-reject/ambiguous.mq.md b/tests/executable_knowledge/baseline/06-reject/ambiguous.mq.md new file mode 100644 index 0000000..68f94f4 --- /dev/null +++ b/tests/executable_knowledge/baseline/06-reject/ambiguous.mq.md @@ -0,0 +1,17 @@ +--- +markup: occlusion +title: S0 拒绝复用:裸名无法消歧(现状基线) +status: expected_failure +description: > + 两模块均定义「商品小计」。当前默认语法要求显式路径调用; + 裸名调用不导入任何一方时,应失败而非猜一个目标。 + (同名已 import 仍误连是 S1 验收项,不在本负例。) +import: + a: a.mq.md + b: b.mq.md +--- + +# main + +**小计 = [未消歧的同名调用](商品小计(数量=2, 单价=30))** +> print text=`小计` diff --git a/tests/executable_knowledge/baseline/06-reject/b.mq.md b/tests/executable_knowledge/baseline/06-reject/b.mq.md new file mode 100644 index 0000000..26b48fb --- /dev/null +++ b/tests/executable_knowledge/baseline/06-reject/b.mq.md @@ -0,0 +1,11 @@ +--- +markup: occlusion +title: S0 同名模块 B +status: expected_failure +--- + +## 商品小计 + +根据购买数量`数量`和商品单价`单价`计算小计(B 侧加倍)。 + +*[B 侧实现](数量 * 单价 * 2)* diff --git a/tests/executable_knowledge/baseline/06-reject/missing-import.mq.md b/tests/executable_knowledge/baseline/06-reject/missing-import.mq.md new file mode 100644 index 0000000..324d7de --- /dev/null +++ b/tests/executable_knowledge/baseline/06-reject/missing-import.mq.md @@ -0,0 +1,12 @@ +--- +markup: occlusion +title: S0 拒绝复用:缺 import +status: expected_failure +--- + +# main + +未 import 时不得静默解析外部模块。 + +**小计 = [误用外部定价](pricing.商品小计(数量=2, 单价=30))** +> print text=`小计` diff --git a/tests/executable_knowledge/baseline/07-step-kinds/main.mq.md b/tests/executable_knowledge/baseline/07-step-kinds/main.mq.md new file mode 100644 index 0000000..8ea9b4f --- /dev/null +++ b/tests/executable_knowledge/baseline/07-step-kinds/main.mq.md @@ -0,0 +1,18 @@ +--- +markup: occlusion +title: S1 步骤 kind 分类样例 +status: implemented +import: + json: lib/json.mq.md +--- + +# main + +`列` = > json.parse text=["一","二"] + +**a = [取列表首项](access(`列`, 1))** +**b = [两件商品的小计](2 * 30)** +- [篮子里的每个果子](遍历 `列` 为 `果`) + > print text=`果` +> print text=`a` +> print text=`b` diff --git a/tests/executable_knowledge/baseline/08-same-name/a.mq.md b/tests/executable_knowledge/baseline/08-same-name/a.mq.md new file mode 100644 index 0000000..9e6c21c --- /dev/null +++ b/tests/executable_knowledge/baseline/08-same-name/a.mq.md @@ -0,0 +1,11 @@ +--- +markup: occlusion +title: S1 同名模块 A(应被选中) +status: implemented +--- + +## 商品小计 + +根据购买数量`数量`和商品单价`单价`计算(A)。 + +*[A 侧](数量 * 单价)* diff --git a/tests/executable_knowledge/baseline/08-same-name/b.mq.md b/tests/executable_knowledge/baseline/08-same-name/b.mq.md new file mode 100644 index 0000000..32747a6 --- /dev/null +++ b/tests/executable_knowledge/baseline/08-same-name/b.mq.md @@ -0,0 +1,11 @@ +--- +markup: occlusion +title: S1 同名模块 B(不应被选中) +status: implemented +--- + +## 商品小计 + +根据购买数量`数量`和商品单价`单价`计算(B 加倍)。 + +*[B 侧](数量 * 单价 * 2)* diff --git a/tests/executable_knowledge/baseline/08-same-name/main.mq.md b/tests/executable_knowledge/baseline/08-same-name/main.mq.md new file mode 100644 index 0000000..705f058 --- /dev/null +++ b/tests/executable_knowledge/baseline/08-same-name/main.mq.md @@ -0,0 +1,14 @@ +--- +markup: occlusion +title: S1 同名仅 import A +status: implemented +import: + pricing: a.mq.md +--- + +# main + +只 import A;不得落到 B。 + +**小计 = [两件商品的小计](pricing.商品小计(数量=2, 单价=30))** +> print text=`小计` diff --git a/tests/executable_knowledge/baseline/09-effects/main.mq.md b/tests/executable_knowledge/baseline/09-effects/main.mq.md new file mode 100644 index 0000000..57382a8 --- /dev/null +++ b/tests/executable_knowledge/baseline/09-effects/main.mq.md @@ -0,0 +1,24 @@ +--- +markup: occlusion +title: S2 G06 效应传递与未知不纯 +status: implemented +--- + +## save + +写入演示文件。 + +> fs.write_text path=out.txt text=ok +*1* + +## wrap + +无危险词包装,内部调用 save。 + +> save +*None* + +# main + +> wrap +> print text=ok diff --git a/tests/gold.rs b/tests/gold.rs index d138f43..8b65b87 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1286,8 +1286,19 @@ fn knowledge_compile_engineering_fixture() { ]); assert_eq!(code, 0, "{stderr}"); assert!(dir.join("catalog/repository.mq.md").exists()); - assert!(dir.join("graph/graph.json").exists()); - assert!(dir.join("graph/edges.json").exists()); + // G01: SemanticProject owns graph/; EKC retrieval lives under ekc/. + assert!(dir.join("graph/edges.json").exists(), "semantic edges"); + assert!(dir.join("ekc/graph/graph.json").exists(), "EKC retrieval graph"); + assert!(dir.join("ekc/graph/edges.json").exists(), "EKC retrieval edges"); + assert!( + !dir.join("graph/graph.json").exists(), + "EKC graph.json must not overwrite semantic graph/" + ); + let edges: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(dir.join("graph/edges.json")).unwrap()) + .unwrap(); + assert_eq!(edges["authority"], "SemanticProject", "{edges}"); + assert!(dir.join("steps.json").exists(), "semantic steps projection"); assert!(dir.join("engineering.yaml").exists()); assert!(dir.join("index.mq.md").exists()); let eng = std::fs::read_to_string(dir.join("engineering.yaml")).unwrap(); @@ -1432,7 +1443,8 @@ fn catalog_hooks_knowledge_by_default() { assert_eq!(code, 0, "{stderr}"); assert!(dir.join("catalog.yaml").exists()); assert!(dir.join("engineering.yaml").exists()); - assert!(dir.join("graph/graph.json").exists()); + assert!(dir.join("ekc/graph/graph.json").exists()); + assert!(dir.join("graph/edges.json").exists()); } #[test]