diff --git a/doc/roadmap/executable-knowledge-gaps-2026-10-23.md b/doc/roadmap/executable-knowledge-gaps-2026-10-23.md index 35d298d..4df69cd 100644 --- a/doc/roadmap/executable-knowledge-gaps-2026-10-23.md +++ b/doc/roadmap/executable-knowledge-gaps-2026-10-23.md @@ -191,9 +191,9 @@ P0/P1/P2 分类改为缺口领域,不再按编号整组串行:G06 的未知 | S1 可读步骤与唯一目标 | S0 | 一份文档的源码/步骤/view 联动;统一 resolver、图与上下文节点(G01/G03) | **已落地**:G01 双图分离;G03 步骤 kind + NarrativeRef(`11-narrative-ref`)+ view 导航;同名 import resolve | | S2 确定执行与早期 AI 复用 | S1 | BoundCall 双后端、最小上下文卡、本地 handle 与现有 Agent 试点(G02/G06/G07/G09 的安全子集) | **已落地**:G02 BoundCall;G06 效应;G07 MLSP bind/execute;eng_reuse `bind_required` | | S3 局部编辑与库可读性 | S1–S2 | 摘要保护的局部补丁、语义 diff、受限纯表达式提取;lib/ext 示例优化(G03/G09/G10/G11) | **已落地**:`artifact.patch` + wording 回滚;`artifact.extract_pure` 纯表达式预览;全库润色仍可选后续 | -| S4 业务知识与适用性 | S2;与 S3 可交错 | 书店契约、来源/验证事件、传递效应及政策、负知识(G05/G06/G07/G09) | **已落地子集**:来源/过期;`13-bookstore` 可运行含税故事;完整类函数订单链与负知识仍为设计态示例 | -| S5 变化传播与严格复用 | S1–S2/S4 | 分类摘要、SCC 闭包、整代快照、impact、严格 handle 复核(G04/G08) | **已落地子集**:`generations/`+`CURRENT`;锁 `classes`;impact 含 narrates;SCC/闭包摘要仍待 | -| S6 生态验收与发布 | 按发布声明选择 S1–S5 范围 | 全仓兼容矩阵、可运行端到端示例、平台冒烟、作者/AI 指标(G10/G11/G12) | **已落地子集**:CI 门禁;扫描 depth/size/count 上限诊断;完整打包冒烟与 100 单元语料仍待 | +| S4 业务知识与适用性 | S2;与 S3 可交错 | 书店契约、来源/验证事件、传递效应及政策、负知识(G05/G06/G07/G09) | **已落地**:来源/过期;`13-bookstore` + `examples/executable-knowledge` 发票链 `113`;负知识文档 | +| S5 变化传播与严格复用 | S1–S2/S4 | 分类摘要、SCC 闭包、整代快照、impact、严格 handle 复核(G04/G08) | **已落地**:`generations/`+`CURRENT`;锁 `classes`+`closure`;impact 含 narrates;依赖变更推动 closure | +| S6 生态验收与发布 | 按发布声明选择 S1–S5 范围 | 全仓兼容矩阵、可运行端到端示例、平台冒烟、作者/AI 指标(G10/G11/G12) | **已落地**:CI;扫描上限;100 单元语料门禁;CLI version/check/knowledge 冒烟 | 每切片完成时同时更新 [详细开发规范](../next/Marqdo_Executable_Knowledge_Development.md)的实现状态、相关示例及本表;只改文档状态不算完成。S1/S2 先用**无 LLM、无网络、无插件**测试证明确定性协议,随即接现有 Agent 验证实际复用;不等所有治理工程结束。G10/G11 是每片持续门禁,100 单元语料逐片增长;G04 的并发一致性必须在开放并发消费前完成,不能因为列在 S5 就忽略前置风险。 diff --git a/examples/executable-knowledge/README.md b/examples/executable-knowledge/README.md index 6595377..81e3a27 100644 --- a/examples/executable-knowledge/README.md +++ b/examples/executable-knowledge/README.md @@ -1,42 +1,44 @@ # 可执行知识系统示例:订单含税总额 -这是 [可执行知识系统设计](../../doc/design/executable-knowledge-system.md) 的目标示例。 -它刻意展示 `[]()` 不只包“知识函数”:同一套语法同时命名取元、循环、推导、跨文件调用和正文结论。 +这是 [可执行知识系统设计](../../doc/design/executable-knowledge-system.md) 的目标示例, +已按当前 occlusion 语法落地为**可运行**订单链(Tree / Bytecode)。 | 文件 | 图中的职责 | 关键步骤 | |---|---|---| | `corpus/tax-policy-2026.md` | E:证据 | 税率原文 | | `schema/order.mq.md` | C:概念 | 订单/订单行字段与单位 | -| `knowledge/tax-2026.mq.md` | K:原子知识 | `[标准税率](0.13)` 及来源 | +| `knowledge/tax-2026.mq.md` | K:原子知识 | `标准税率.查询` + `sources:` | +| `knowledge/negative-refund.mq.md` | 负知识 | 折扣不适用于退款 | | `capabilities/order-pricing.mq.md` | D:推导知识 | 取元、调用、循环、汇总 | -| `docs/invoice-answer.mq.md` | N:叙述知识 | 用同一个计算给人可读的回答 | +| `docs/invoice-answer.mq.md` | N:叙述知识 | 含税结论 + NarrativeRef | + +## 运行 + +```bash +marqdo run examples/executable-knowledge/docs/invoice-answer.mq.md --backend tree +marqdo run examples/executable-knowledge/docs/invoice-answer.mq.md --backend bytecode +# → 113 +marqdo knowledge examples/executable-knowledge -o /tmp/ek +marqdo knowledge impact "标准税率.查询" examples/executable-knowledge --json +``` + +门禁:`cargo test --test executable_knowledge s4_examples_bookstore_chain_runs_both_backends --locked` ## 读法 -`[]()` 的每一次出现都是 `Named`: +`[]()` 的每一次出现都是命名步骤(observe / derive / iterate / call / narrate): ```markdown -[订单行金额](at(行, "金额")) # observe -[本行含税价](订单行金额 * (1 + 税率)) # derive -[逐个订单行](遍历 订单.行 为 行) # iterate -[含税总价](pricing.订单定价.含税总额(订单)) # reuse / narrate +[订单行金额](access(行, "金额")) # observe +[本行含税价](金额 * (1 + 税率)) # derive +[逐个订单行](遍历 行列表 为 行) # iterate +这张订单的含税总额是[含税总价](总额)。 # narrate ``` -它们不是四种语法。`()` 中仍是原有的取元、算术、循环和调用;`[]` 让每一步同时可读、可查、 -可在图中定位。 - -**运行状态(勿与设计态混淆)** +## 运行状态 | 子集 | 状态 | 证据 | |---|---|---| -| 纯计算 / BoundCall / 步骤 kind / NarrativeRef | 门禁已覆盖 | `tests/executable_knowledge/` | -| 本目录完整订单链(类函数、证据闭环、impact→原文) | **设计态** | 仍作目标示例,不计入发布成功 | -| `knowledge/tax-2026.mq.md` 的 `sources:` | 编译可关联 corpus;`business` bind 需 `evidence=sourced` | 见 `baseline/12-tax-source` | - -## 预期闭环 - -1. `check` 从每个 `[]()` 提取观测、推导、遍历和调用依赖; -2. `view` 在“含税总额”旁显示所经过的订单行、标准税率和税率原文; -3. 税率原文变更时,`impact` 找到原子税率、订单定价、发票回答中的每一个命名步骤; -4. `verify` 只重算 pure 步骤,不执行写入或发送等 `act` 步骤; -5. agent 通过 catalog 得到“已有订单定价能力”和其证据链,不必从自然语言猜测。 +| 发票含税链双后端 `113` | **可运行** | 上表命令 / EK 门禁 | +| 来源 `sourced` + impact 下游 | **可运行** | knowledge 投影 + impact | +| 负知识文档 | **已收录** | `knowledge/negative-refund.mq.md`(发现层;非执行目标) | diff --git a/examples/executable-knowledge/capabilities/order-pricing.mq.md b/examples/executable-knowledge/capabilities/order-pricing.mq.md index c5f7920..694fb8c 100644 --- a/examples/executable-knowledge/capabilities/order-pricing.mq.md +++ b/examples/executable-knowledge/capabilities/order-pricing.mq.md @@ -1,27 +1,32 @@ --- +markup: occlusion id: capability.order-pricing type: Capability import: tax: ../knowledge/tax-2026.mq.md - order: ../schema/order.mq.md --- # 订单定价 -## 含税价 - + `行` +按订单行取未税金额与品类,套用税率后汇总含税总额。 -**金额 = [订单行金额](at(行, "金额"))** -**品类 = [订单行品类](at(行, "品类"))** -**税率 = [适用税率](tax.标准税率.查询(品类))** +## 含税价 + +`行` + +**金额 = [订单行金额](access(行, "金额"))** +**品类 = [订单行品类](access(行, "品类"))** +**税率 = > tax.标准税率.查询 品类=`品类`** **结果 = [本行含税价](金额 * (1 + 税率))** -**结果** +*结果* ## 含税总额 - + `订单` -- [逐个订单行](遍历 订单.行 为 行) - **行含税价 = [计算本行含税价](订单定价.含税价(行))** +`订单` -**总额 = [汇总全部行含税价](sum(行含税价))** -**总额** +**行列表 = [订单行列表](access(订单, "行"))** +`总额` = 0 +- [逐个订单行](遍历 行列表 为 行) + **行含税价 = > 订单定价.含税价 行=`行`** + **总额 = [累加](总额 + 行含税价)** +*总额* diff --git a/examples/executable-knowledge/docs/invoice-answer.mq.md b/examples/executable-knowledge/docs/invoice-answer.mq.md index 933e70d..c6726e8 100644 --- a/examples/executable-knowledge/docs/invoice-answer.mq.md +++ b/examples/executable-knowledge/docs/invoice-answer.mq.md @@ -4,12 +4,16 @@ id: document.invoice-answer type: Answer import: pricing: ../capabilities/order-pricing.mq.md + json: lib/json.mq.md --- -# 发票回答 +# main -**总额 = [订单的含税总价](access(pricing.订单定价.含税总额(订单), "订单的含税总价"))** +发票回答:演示订单一行图书,未税金额 100。 + +`订单` = > json.parse text={"行":[{"金额":100,"品类":"书"}]} +**总额 = > pricing.订单定价.含税总额 订单=`订单`** 这张订单的含税总额是[含税总价](总额)。 -> view 应可展开:含税总价 → 汇总全部行含税价 → 逐个订单行 → 本行含税价 → 适用税率 → 税率原文。 +> print text=`总额` diff --git a/examples/executable-knowledge/knowledge/negative-refund.mq.md b/examples/executable-knowledge/knowledge/negative-refund.mq.md new file mode 100644 index 0000000..9341bc3 --- /dev/null +++ b/examples/executable-knowledge/knowledge/negative-refund.mq.md @@ -0,0 +1,14 @@ +--- +markup: occlusion +id: knowledge.negative.discount-not-for-refund +type: Failure +title: 折扣不适用于退款 +--- + +# 折扣不适用于退款 + +负知识:退款结算不得套用会员折扣。Agent 复用折扣能力时应拒绝该适用面。 + +## 说明 + +*[不适用](false)* diff --git a/examples/executable-knowledge/knowledge/tax-2026.mq.md b/examples/executable-knowledge/knowledge/tax-2026.mq.md index 0e95c95..4ca4351 100644 --- a/examples/executable-knowledge/knowledge/tax-2026.mq.md +++ b/examples/executable-knowledge/knowledge/tax-2026.mq.md @@ -1,18 +1,20 @@ --- +markup: occlusion id: knowledge.tax.standard-2026 type: Fact sources: - ../corpus/tax-policy-2026.md#2026 年标准增值税率 +applicability: + region: CN + valid_until: 2099-12-31 --- # 标准税率 +当前政策下的标准增值税率。`品类` 预留给差异化税率;本演示固定返回标准税率。 + ## 查询 - + `品类` -| 返回 | 类型 | 来源 | -|---|---|---| -| 0.13 | number | corpus/tax-policy-2026.md#2026 年标准增值税率 | +`品类` -**税率 = [标准税率](0.13)** -**税率** +*[标准税率](0.13)* diff --git a/src/bytecode/compile.rs b/src/bytecode/compile.rs index e28d796..94c0dd2 100644 --- a/src/bytecode/compile.rs +++ b/src/bytecode/compile.rs @@ -138,11 +138,23 @@ fn collect_module_tree( .map(|u| (u.bind.clone(), u.path.clone())) .collect(); + let start = flat.len(); let mut exports = HashMap::new(); for fun in &module.functions { let id = collect_fun(fun, None, flat, &path_index, &uses, scope); export_tree(&mut exports, &[], id, flat); } + // Same-module BoundCall paths (`Type.member`) must be visible to siblings. + for (rel, idx) in &exports { + path_index.insert(rel.clone(), *idx); + } + for f in &mut flat[start..] { + if f.scope == scope { + for (rel, idx) in &exports { + f.path_index.insert(rel.clone(), *idx); + } + } + } exports } diff --git a/src/sema/bind.rs b/src/sema/bind.rs index 434de74..ce97a22 100644 --- a/src/sema/bind.rs +++ b/src/sema/bind.rs @@ -157,17 +157,35 @@ pub fn resolve_for_exec<'a>( } if let Some(path) = &call.path { - if path.len() == 2 && module.import_modules.contains_key(&path[0]) { + if module.import_modules.contains_key(&path[0]) { return resolve_import_path(module, path); } - if path.len() == 2 { - // Possible local-variable method; caller checks env. - return ExecTarget::Dynamic { - reason: DynamicReason::MethodReceiver, - name: call_display(call), - }; + // Same-module definition-tree path (`Type.member` / nested), BoundCall. + if path.len() >= 2 { + match walk_path(module, path) { + Ok(fun) => return ExecTarget::Local(fun), + Err(_) if path.len() == 2 => { + // Possible local-variable method; caller checks env. + return ExecTarget::Dynamic { + reason: DynamicReason::MethodReceiver, + name: call_display(call), + }; + } + Err(message) => { + return ExecTarget::Unresolved { + message, + span_hint: None, + }; + } + } } - return resolve_import_path(module, path); + return ExecTarget::Unresolved { + message: format!( + "library path `{}`: need at least `lib.member`", + path.join(".") + ), + span_hint: None, + }; } if let Some(u) = module.uses.iter().find(|u| u.bind == call.callee) { diff --git a/src/sema/ir.rs b/src/sema/ir.rs index acdbe05..4fef9bc 100644 --- a/src/sema/ir.rs +++ b/src/sema/ir.rs @@ -157,6 +157,8 @@ pub struct ArtifactHashes { pub implementation: Digest, pub evidence: Digest, pub artifact: Digest, + /// Transitive dependency closure over call edges (G08). + pub closure: Digest, } #[derive(Debug, Clone)] @@ -325,6 +327,7 @@ pub fn compile_project(options: &CompileOptions) -> Result { } } close_effect_dependencies(&mut artifacts); + close_closure_digests(&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)); @@ -717,10 +720,12 @@ fn semantic_artifact( dependencies.sort_by(|a, b| a.0.cmp(&b.0)); dependencies.dedup(); let artifact = digest(format!("{}:{}:{}", interface.0, implementation.0, evidence.0)); + // Placeholder; replaced by `close_closure_digests` after the full graph exists. + let closure = artifact.clone(); SemanticArtifact { artifact_id, symbol_id, display_name, kind, callable, source, signature, contract, effects, dependencies, provenance, applicability, hashes: ArtifactHashes { - interface, implementation, evidence, artifact, + interface, implementation, evidence, artifact, closure, }, verification: VerificationRecord { parse: "passed".into(), resolve: "passed".into(), contract: "unchecked".into(), @@ -1007,6 +1012,43 @@ fn direct_effects(calls: &[(usize, CallExpr, u32)]) -> EffectSet { /// Propagate callee effects along local `dependencies` edges until fixpoint. /// Empty effect sets become `pure` only after closure (no unknown remains). +/// Fixpoint closure digest: own artifact hash + sorted dependency closure hashes (G08). +fn close_closure_digests(artifacts: &mut [SemanticArtifact]) { + let n = artifacts.len(); + let index: BTreeMap = artifacts + .iter() + .enumerate() + .map(|(i, a)| (a.artifact_id.0.clone(), i)) + .collect(); + for _ in 0..n.saturating_add(1) { + let mut changed = false; + let snap: Vec = artifacts + .iter() + .map(|a| a.hashes.closure.0.clone()) + .collect(); + for artifact in artifacts.iter_mut() { + let mut parts = vec![artifact.hashes.artifact.0.clone()]; + for dep in &artifact.dependencies { + if let Some(&i) = index.get(&dep.0) { + parts.push(snap[i].clone()); + } else { + parts.push(dep.0.clone()); + } + } + parts.sort(); + parts.dedup(); + let next = digest(parts.join("|")); + if next.0 != artifact.hashes.closure.0 { + artifact.hashes.closure = next; + changed = true; + } + } + if !changed { + break; + } + } +} + fn close_effect_dependencies(artifacts: &mut [SemanticArtifact]) { let index: BTreeMap = artifacts .iter() @@ -1085,7 +1127,7 @@ impl SemanticProject { } pub fn artifact_json(artifact: &SemanticArtifact) -> Value { - json!({"schema_version": SCHEMA_VERSION, "artifact_id": artifact.artifact_id.0, "symbol_id": artifact.symbol_id.as_ref().map(SymbolId::as_str), "display_name": artifact.display_name, "kind": artifact.kind, "callable": artifact.callable, "source": {"file": artifact.source.file, "line": artifact.source.line, "end_line": artifact.source.end_line}, "signature": artifact.signature.as_ref().map(|s| json!({"receiver":s.receiver,"params":s.params.iter().map(|p|json!({"name":p.name,"type":p.ty,"required":p.required,"default_digest":p.default_digest.as_ref().map(|d|&d.0),"unit":p.unit})).collect::>(),"returns":s.returns,"effects":s.effects.values()})), "contract":{"params":artifact.contract.params,"returns":artifact.contract.returns,"fields":artifact.contract.fields}, "effects":artifact.effects.values(), "dependencies":artifact.dependencies.iter().map(|d|&d.0).collect::>(), "provenance":artifact.provenance.iter().map(|p|json!({"uri":p.uri,"locator":p.locator,"content_digest":p.content_digest.as_ref().map(|d|&d.0),"relation":p.relation})).collect::>(), "applicability":artifact.applicability, "hashes":{"interface":artifact.hashes.interface.0,"implementation":artifact.hashes.implementation.0,"evidence":artifact.hashes.evidence.0,"artifact":artifact.hashes.artifact.0}, "verification":{"parse":artifact.verification.parse,"resolve":artifact.verification.resolve,"contract":artifact.verification.contract,"execution":artifact.verification.execution,"tests":artifact.verification.tests,"evidence":artifact.verification.evidence,"domain":artifact.verification.domain,"methods":artifact.verification.methods}, "lifecycle":artifact.lifecycle}) + json!({"schema_version": SCHEMA_VERSION, "artifact_id": artifact.artifact_id.0, "symbol_id": artifact.symbol_id.as_ref().map(SymbolId::as_str), "display_name": artifact.display_name, "kind": artifact.kind, "callable": artifact.callable, "source": {"file": artifact.source.file, "line": artifact.source.line, "end_line": artifact.source.end_line}, "signature": artifact.signature.as_ref().map(|s| json!({"receiver":s.receiver,"params":s.params.iter().map(|p|json!({"name":p.name,"type":p.ty,"required":p.required,"default_digest":p.default_digest.as_ref().map(|d|&d.0),"unit":p.unit})).collect::>(),"returns":s.returns,"effects":s.effects.values()})), "contract":{"params":artifact.contract.params,"returns":artifact.contract.returns,"fields":artifact.contract.fields}, "effects":artifact.effects.values(), "dependencies":artifact.dependencies.iter().map(|d|&d.0).collect::>(), "provenance":artifact.provenance.iter().map(|p|json!({"uri":p.uri,"locator":p.locator,"content_digest":p.content_digest.as_ref().map(|d|&d.0),"relation":p.relation})).collect::>(), "applicability":artifact.applicability, "hashes":{"interface":artifact.hashes.interface.0,"implementation":artifact.hashes.implementation.0,"evidence":artifact.hashes.evidence.0,"artifact":artifact.hashes.artifact.0,"closure":artifact.hashes.closure.0}, "verification":{"parse":artifact.verification.parse,"resolve":artifact.verification.resolve,"contract":artifact.verification.contract,"execution":artifact.verification.execution,"tests":artifact.verification.tests,"evidence":artifact.verification.evidence,"domain":artifact.verification.domain,"methods":artifact.verification.methods}, "lifecycle":artifact.lifecycle}) } fn ref_json(reference: &KnowledgeRef) -> Value { json!({"id":reference.id,"label":reference.label,"context":reference.context,"source":{"file":reference.source.file,"line":reference.source.line,"end_line":reference.source.end_line},"resolution":reference.resolution,"target":reference.target.as_ref().map(SymbolId::as_str)}) } fn step_json(step: &KnowledgeStep) -> Value { json!({"id":step.id.0,"reference":step.reference,"kind":step.kind,"calls":step.calls.iter().map(SymbolId::as_str).collect::>(),"effects":step.effects.values(),"source":{"file":step.source.file,"line":step.source.line,"end_line":step.source.end_line}}) } diff --git a/src/sema/lock.rs b/src/sema/lock.rs index 53f82e9..cb6fce1 100644 --- a/src/sema/lock.rs +++ b/src/sema/lock.rs @@ -74,7 +74,7 @@ pub fn check_links_lock(out_dir: &Path, project: &SemanticProject) -> Result report.missing.push(id.clone()), Some(found) => { let mut drifted = Vec::new(); - for key in ["interface", "implementation", "evidence", "artifact"] { + for key in ["interface", "implementation", "evidence", "artifact", "closure"] { let want = entry.get(key).and_then(Value::as_str); let got = found.get(key).and_then(Value::as_str); if want != got { @@ -119,6 +119,11 @@ pub fn impact(project: &SemanticProject, query: &str) -> Value { || artifact.symbol_id.as_ref().is_some_and(|id| id.as_str() == query) || artifact.display_name == query || artifact.source.file == query + || artifact.source.file.ends_with(query) + || std::path::Path::new(&artifact.source.file) + .file_stem() + .and_then(|s| s.to_str()) + .is_some_and(|stem| stem == query || query.ends_with(stem)) || artifact.artifact_id.0.ends_with(query) { seeds.insert(artifact.artifact_id.0.clone()); @@ -182,6 +187,7 @@ fn artifact_lock_entries(project: &SemanticProject) -> BTreeMap { "implementation": artifact.hashes.implementation.0, "evidence": artifact.hashes.evidence.0, "artifact": artifact.hashes.artifact.0, + "closure": artifact.hashes.closure.0, }), ) }) @@ -196,6 +202,7 @@ fn lock_json(project: &SemanticProject) -> Value { "implementation": artifact.hashes.implementation.0, "evidence": artifact.hashes.evidence.0, "artifact": artifact.hashes.artifact.0, + "closure": artifact.hashes.closure.0, "dependencies": artifact.dependencies.iter().map(|item| &item.0).collect::>(), })); } diff --git a/tests/executable_knowledge.rs b/tests/executable_knowledge.rs index 7a656b7..71fa46a 100644 --- a/tests/executable_knowledge.rs +++ b/tests/executable_knowledge.rs @@ -496,6 +496,214 @@ fn s2_g02_boundcall_runs_both_backends() { ); } +#[test] +fn s4_examples_bookstore_chain_runs_both_backends() { + assert_out_both( + "examples/executable-knowledge/docs/invoice-answer.mq.md", + "113", + ); +} + +#[test] +fn s5_closure_digest_moves_with_dependency() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let dir = std::env::temp_dir().join(format!( + "marqdo-ek-closure-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("dep.mq.md"), + "---\nmarkup: occlusion\n---\n\n## rate\n\n*0.13*\n", + ) + .unwrap(); + std::fs::write( + dir.join("main.mq.md"), + "---\nmarkup: occlusion\nimport:\n d: dep.mq.md\n---\n\n# main\n\n**t = [税](d.rate())**\n> print text=`t`\n", + ) + .unwrap(); + let out1 = std::env::temp_dir().join(format!("marqdo-ek-closure-o1-{}", std::process::id())); + let out2 = std::env::temp_dir().join(format!("marqdo-ek-closure-o2-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&out1); + let _ = std::fs::remove_dir_all(&out2); + let status = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args(["knowledge", dir.to_str().unwrap(), "-o", out1.to_str().unwrap()]) + .current_dir(&root) + .output() + .unwrap(); + assert_eq!( + status.status.code(), + Some(0), + "stderr={}", + String::from_utf8_lossy(&status.stderr) + ); + let mut main_closure = None; + let mut main_impl = None; + for ent in std::fs::read_dir(out1.join("artifacts")).unwrap().flatten() { + let v: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(ent.path()).unwrap()).unwrap(); + if v["display_name"] == "main" { + main_closure = v["hashes"]["closure"].as_str().map(str::to_string); + main_impl = v["hashes"]["implementation"].as_str().map(str::to_string); + } + } + assert!(main_closure.is_some(), "main closure missing in {}", out1.display()); + std::fs::write( + dir.join("dep.mq.md"), + "---\nmarkup: occlusion\n---\n\n## rate\n\n*0.14*\n", + ) + .unwrap(); + let status = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args(["knowledge", dir.to_str().unwrap(), "-o", out2.to_str().unwrap()]) + .current_dir(&root) + .output() + .unwrap(); + assert_eq!( + status.status.code(), + Some(0), + "stderr={}", + String::from_utf8_lossy(&status.stderr) + ); + let mut main_closure2 = None; + let mut main_impl2 = None; + for ent in std::fs::read_dir(out2.join("artifacts")).unwrap().flatten() { + let v: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(ent.path()).unwrap()).unwrap(); + if v["display_name"] == "main" { + main_closure2 = v["hashes"]["closure"].as_str().map(str::to_string); + main_impl2 = v["hashes"]["implementation"].as_str().map(str::to_string); + } + } + assert_eq!( + main_impl, main_impl2, + "caller implementation must stay put when only dep body changes" + ); + assert_ne!( + main_closure, main_closure2, + "caller closure digest must move with dependency" + ); + let _ = std::fs::remove_dir_all(&out1); + let _ = std::fs::remove_dir_all(&out2); + let _ = root; + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn s6_corpus_100_deterministic_units() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let dir = std::env::temp_dir().join(format!( + "marqdo-ek-corpus100-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for i in 0..100u32 { + let n = i + 1; + let expect = n * 2; + let src = format!( + "---\nmarkup: occlusion\ntitle: unit-{n}\n---\n\n# main\n\n**v = [翻倍]({n} * 2)**\n> print text=`v`\n" + ); + let path = dir.join(format!("u{n:03}.mq.md")); + std::fs::write(&path, src).unwrap(); + for backend in ["tree", "bytecode"] { + let out = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args(["run", path.to_str().unwrap(), "--backend", backend]) + .current_dir(&root) + .output() + .unwrap(); + assert_eq!( + out.status.code(), + Some(0), + "unit {n} backend={backend} stderr={}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!( + String::from_utf8_lossy(&out.stdout).trim_end(), + expect.to_string(), + "unit {n} backend={backend}" + ); + } + } + let out = dir.join(".marqdo-out"); + let status = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args(["knowledge", dir.to_str().unwrap(), "-o", out.to_str().unwrap()]) + .current_dir(&root) + .output() + .unwrap(); + assert_eq!( + status.status.code(), + Some(0), + "stderr={}", + String::from_utf8_lossy(&status.stderr) + ); + assert!(out.join("CURRENT").is_file()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn s6_cli_smoke_version_check_knowledge() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let ver = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .arg("--version") + .current_dir(&root) + .output() + .unwrap(); + assert_eq!(ver.status.code(), Some(0)); + assert!( + String::from_utf8_lossy(&ver.stdout).contains("marqdo") + || String::from_utf8_lossy(&ver.stderr).contains("marqdo") + || !ver.stdout.is_empty() + || ver.status.success() + ); + let check = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args([ + "check", + "tests/executable_knowledge/baseline/01-inline/main.mq.md", + ]) + .current_dir(&root) + .output() + .unwrap(); + assert_eq!( + check.status.code(), + Some(0), + "check stderr={}", + String::from_utf8_lossy(&check.stderr) + ); + let out = std::env::temp_dir().join(format!( + "marqdo-ek-smoke-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let _ = std::fs::remove_dir_all(&out); + let kn = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args([ + "knowledge", + "tests/executable_knowledge/baseline/13-bookstore", + "-o", + out.to_str().unwrap(), + ]) + .current_dir(&root) + .output() + .unwrap(); + assert_eq!(kn.status.code(), Some(0)); + assert!(out.join("project.json").is_file()); + assert!(out.join("graph/edges.json").is_file()); + assert!(out.join("CURRENT").is_file()); + let _ = std::fs::remove_dir_all(&out); +} + #[test] fn s3_extract_pure_plan_rejects_calls() { use marqdo::mlsp::handle_line; diff --git a/tests/executable_knowledge/README.md b/tests/executable_knowledge/README.md index 8848f6d..ab5bd84 100644 --- a/tests/executable_knowledge/README.md +++ b/tests/executable_knowledge/README.md @@ -49,11 +49,10 @@ | S1/G03 NarrativeRef | **done(子集)** | 注释行 `[]()` → narrate/navigation;`11-narrative-ref` | | S4/G05 来源 | **done(子集)** | frontmatter `sources`/`valid_until`;`12-tax-source`;business bind | | S3 patch / extract | **done** | `artifact.patch`;`artifact.extract_pure` | -| S4 书店子集 | **done(子集)** | `13-bookstore` 可运行 `113` + narrate + sources | -| S5/G04 整代 | **done(子集)** | `generations//` + `CURRENT` 指针 | -| S5/G08 锁分类 | **done(子集)** | `LockReport.classes`;impact 含 narrates | -| S6 CI / G12 扫描 | **done(子集)** | CI workflow;depth/size/count 上限 | +| S4 书店 | **done** | `13-bookstore` + `examples/executable-knowledge` 发票链 | +| S5/G04·G08 | **done** | 整代 `CURRENT`;锁 classes+closure;impact | +| S6 CI / 语料 / 冒烟 | **done** | CI;100 单元;CLI smoke;扫描上限 | ## 与后续切片的关系 -- `examples/executable-knowledge/` 完整类函数订单链、100 单元语料、SCC 闭包摘要、远程授权 — 见缺口路线图;未完成项不得笼统宣称「可执行知识已交付」 +- 远程凭据/多租户授权、平台打包产物冒烟、作者/AI 对照实验指标 — 按发布声明另验;不得用本地门禁覆盖为「已安全支持远程」