feat: executable-knowledge S0–S1 gate plus effect and MLSP reuse subset

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 <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-23 22:52:06 +08:00
1 parent bedd53e212
commit ecbdd18303
31 files changed
+1324 -56

No files matched your search

+11
View File
@@ -349,6 +349,17 @@ impl Interpreter {
) -> Result<Value> {
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<Value> {
self.run_function(module, fun, Env::new(), args, false)
}
+21 -20
View File
@@ -17,9 +17,9 @@ pub struct KnowledgeOptions {
}
pub fn compile(opts: KnowledgeOptions) -> Result<KnowledgeGraph> {
// 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<KnowledgeGraph> {
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<KnowledgeGraph> {
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<KnowledgeGraph> {
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<KnowledgeGraph> {
}
pub fn ensure_compiled(path: &Path, out_dir: &Path) -> Result<KnowledgeGraph> {
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)?,
)?;
+3 -1
View File
@@ -52,7 +52,9 @@ pub fn find_stale(graph: &KnowledgeGraph, root: &Path) -> Vec<StaleItem> {
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()) {
+1 -1
View File
@@ -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};
+105 -5
View File
@@ -171,7 +171,35 @@ fn artifact_bind(params: &Value) -> Result<Value, Value> {
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<Value, Value> {
@@ -184,6 +212,21 @@ fn artifact_execute(params: &Value) -> Result<Value, Value> {
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<String> = 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<Value, Value> {
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<String>) -> 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();
}
+402 -16
View File
@@ -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<String>) {
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<String> {
self.0.iter().cloned().collect()
}
@@ -261,6 +273,7 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
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<CallExpr>,
}
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<CallExpr>) {
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<NamedStepSite> {
let mut out = Vec::new();
fn push_occluded(label: &str, payload: Option<&Expr>, line: u32, out: &mut Vec<NamedStepSite>) {
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<NamedStepSite>) {
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<NamedStepSite>) {
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<NamedStepSite>) {
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<String, usize> = 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<EffectSet> = 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::<Vec<_>>() }))?;
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::<Vec<_>>() }))?;
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::<Vec<_>>() }))?;
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<String> = 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();
}
}
+31 -1
View File
@@ -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#"<div class="knowledge-panel" aria-label="Executable knowledge">"#);
if !steps.is_empty() {
out.push_str(r#"<article class="knowledge-card knowledge-steps"><h3>Steps</h3><ol class="knowledge-step-list">"#);
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#" <span class="knowledge-step-targets">→ {}</span>"#,
escape(&step.calls.iter().map(|id| id.as_str()).collect::<Vec<_>>().join(", "))
)
};
// Structure pane uses #stmt-{line}; jump there for source navigation.
out.push_str(&format!(
"<li class=\"knowledge-step\" data-step-kind=\"{0}\" data-line=\"{1}\"><a href=\"#stmt-{1}\"><code class=\"ks-kind\">{0}</code> {2}</a>{3}</li>",
escape(&step.kind),
line,
escape(label),
target_ids,
));
}
out.push_str("</ol></article>");
}
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| {