Ship quantum skill=tools tree with call session and ZH package.

Split ext/quantum into index + modules, add marqdo call --effects/--session/--toget,
narrative-ratio checks, and a same-package 量子/ tree so agents can follow a
decision path for Bell demos without inventing a second API.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-11-08 21:50:01 +08:00
1 parent 492790e985
commit 0e389f34ec
65 files changed
+3714 -1036

No files matched your search

+232 -49
View File
@@ -11,6 +11,7 @@ use anyhow::Result;
use crate::ast::Function;
use crate::bytecode::{compile_for_call, Vm};
use crate::diagnostics::{Diagnostic, Span};
use crate::host::json::json_to_value;
use crate::host::{HostCaps, HostContext};
use crate::interp::Interpreter;
use crate::load::load_module;
@@ -18,40 +19,182 @@ use crate::sema::{compile_file_closure, SemanticArtifact, SemanticProject};
use crate::value::Value;
use crate::Backend;
/// Call `function` in `path` with named arguments.
///
/// Non-pure effects are refused before the function runs. Host write, exec, net,
/// and plugin capabilities stay off for the call.
/// Which host side effects `marqdo call` may perform.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CallEffects {
/// Refuse any non-pure artifact (historical default).
#[default]
None,
/// Allow `plugin.call` (and accompanying `output.write` from load helpers).
Plugin,
}
impl CallEffects {
pub fn parse(s: &str) -> Result<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"none" | "" => Ok(Self::None),
"plugin" => Ok(Self::Plugin),
other => Err(call_diag(
None,
0,
"call.bad_effects",
format!("unknown --effects `{other}` (expected none|plugin)"),
)),
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Plugin => "plugin",
}
}
fn host_caps(self) -> HostCaps {
match self {
Self::None => HostCaps {
fs_write: false,
exec: false,
net: false,
plugin: false,
},
Self::Plugin => HostCaps {
fs_write: false,
exec: false,
net: false,
plugin: true,
},
}
}
fn allows(self, effect: &str) -> bool {
match self {
Self::None => effect == "pure",
Self::Plugin => matches!(
effect,
"pure" | "plugin.call" | "output.write" | "time.read" | "random.read"
),
}
}
}
/// Options for one external call.
#[derive(Debug, Clone, Default)]
pub struct CallOptions {
pub effects: CallEffects,
pub session: Option<String>,
pub toget: Option<String>,
}
/// Call `function` in `path` with named arguments (pure-only, no session).
pub fn call_file(
path: &Path,
function: &str,
args: &[(String, Value)],
backend: Backend,
) -> Result<Value> {
call_file_with(path, function, args, backend, CallOptions::default())
}
/// Call with effects / session / toget.
pub fn call_file_with(
path: &Path,
function: &str,
args: &[(String, Value)],
backend: Backend,
opts: CallOptions,
) -> Result<Value> {
let path = path
.canonicalize()
.map_err(|e| call_diag(None, 1, "call.compile", format!("failed to read {}: {e}", path.display())))?;
.map_err(|e| {
call_diag(
None,
1,
"call.compile",
format!("failed to read {}: {e}", path.display()),
)
})?;
let mut session = if opts.session.is_some() || opts.toget.is_some() || args_need_session(args)
{
let id = opts
.session
.clone()
.unwrap_or_else(crate::call_session::default_session_id);
Some(crate::call_session::load_session(&id)?)
} else {
None
};
let resolved = if let Some(ref mut sess) = session {
crate::call_session::resolve_args(sess, args, backend)?
} else {
args.to_vec()
};
// Record uses original arg texts (with $refs) so replay can re-resolve.
let record_args = args.to_vec();
let value = call_file_raw(&path, function, &resolved, opts.effects, backend)?;
if let Some(ref mut sess) = session {
crate::call_session::record_step(
sess,
&path,
function,
&record_args,
opts.effects,
opts.toget.as_deref(),
&value,
)?;
crate::call_session::save_session(sess)?;
}
Ok(value)
}
/// Execute without session bookkeeping (used by journal replay).
pub fn call_file_raw(
path: &Path,
function: &str,
args: &[(String, Value)],
effects: CallEffects,
backend: Backend,
) -> Result<Value> {
let path = if path.is_absolute() {
path.to_path_buf()
} else {
path.canonicalize().map_err(|e| {
call_diag(
None,
1,
"call.compile",
format!("failed to read {}: {e}", path.display()),
)
})?
};
let compilation = compile_file_closure(&path).map_err(|e| preserve_diag(&path, e))?;
let artifact = locate_artifact(&compilation.semantics, &path, function)?;
deny_unsafe(&path, artifact)?;
deny_unsafe(&path, artifact, effects)?;
execute_source_function(
&path,
artifact.source.line,
&artifact.display_name,
args,
tight_caps(),
effects.host_caps(),
backend,
true,
)
.map(|(value, _stdout)| value)
}
fn args_need_session(args: &[(String, Value)]) -> bool {
args.iter().any(|(_, v)| {
matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@'))
})
}
/// Run the function declared at `line` in `path`.
///
/// `display_name` is the declaration path (`计算器.加法`). The query the caller
/// typed is not used as a heading search and is not used as the bytecode path,
/// so a unique short name or SymbolId still executes that function.
/// `caps` are the host capabilities for this run. `call` passes them all off.
pub(crate) fn execute_source_function(
path: &Path,
line: u32,
@@ -70,22 +213,20 @@ pub(crate) fn execute_source_function(
format!("无法在 {}:{} 定位函数 {display_name}", path.display(), line),
)
})?;
let expected = display_name
.rsplit('.')
.next()
.unwrap_or(display_name);
let expected = display_name.rsplit('.').next().unwrap_or(display_name);
if fun.name != expected {
return Err(call_diag(
Some(path),
line,
"artifact.unresolved",
format!("源码行 {line} 上的函数是 `{}`,与 `{display_name}` 不一致", fun.name),
format!(
"源码行 {line} 上的函数是 `{}`,与 `{display_name}` 不一致",
fun.name
),
));
}
let mut interp = Interpreter::with_capture(Some(path), false)
.with_host(HostContext::for_capture(Some(path), caps));
// `call` checks the signature. `artifact.execute` keeps its previous
// environment injection so an input the body reads is not rejected as unknown.
let bound;
let invoke_args: &[(String, Value)] = if strict_args {
bound = interp.bind_external_args(&module, fun, args)?;
@@ -100,27 +241,53 @@ pub(crate) fn execute_source_function(
}
Backend::Bytecode => {
let program = compile_for_call(Some(path), &module)?;
// Source binding is authoritative even when declaration paths repeat.
let idx = program.functions.iter().position(|chunk|
chunk.module_scope == 0 && chunk.declaration_span == fun.span
&& chunk.name == fun.name && chunk.source.sha256 == module.source.sha256
).ok_or_else(|| {
call_diag(
Some(path),
line,
"artifact.unresolved",
format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"),
)
})?;
let mut vm = Vm::with_capture(Some(path))
.with_host(HostContext::for_capture(Some(path), caps));
let idx = program
.functions
.iter()
.position(|chunk| {
chunk.module_scope == 0
&& chunk.declaration_span == fun.span
&& chunk.name == fun.name
&& chunk.source.sha256 == module.source.sha256
})
.ok_or_else(|| {
call_diag(
Some(path),
line,
"artifact.unresolved",
format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"),
)
})?;
let mut vm =
Vm::with_capture(Some(path)).with_host(HostContext::for_capture(Some(path), caps));
let value = vm.call_function(&program, idx, invoke_args)?;
Ok((value, vm.captured_stdout))
}
}
}
/// Parse `name=value` tokens. Values are integers, decimals, quoted text, or True/False/None.
/// Split trailing `toget <name>` from a clap `args` vector.
pub fn split_toget(tokens: &[String]) -> Result<(Vec<String>, Option<String>)> {
if tokens.len() >= 2 {
let n = tokens.len();
if tokens[n - 2] == "toget" {
let name = tokens[n - 1].clone();
if name.contains('=') {
return Err(call_diag(
None,
0,
"call.bad_toget",
"toget 名字不能含 `=`".into(),
));
}
return Ok((tokens[..n - 2].to_vec(), Some(name)));
}
}
Ok((tokens.to_vec(), None))
}
/// Parse `name=value` tokens. Values are integers, decimals, quoted text, True/False/None,
/// or JSON when the raw value starts with `[` or `{`.
pub fn parse_call_args(tokens: &[String]) -> Result<Vec<(String, Value)>> {
let mut out = Vec::new();
for token in tokens {
@@ -148,15 +315,6 @@ pub fn parse_call_args(tokens: &[String]) -> Result<Vec<(String, Value)>> {
Ok(out)
}
fn tight_caps() -> HostCaps {
HostCaps {
fs_write: false,
exec: false,
net: false,
plugin: false,
}
}
fn locate_artifact<'a>(
project: &'a SemanticProject,
entry: &Path,
@@ -191,7 +349,17 @@ fn locate_artifact<'a>(
})
.collect()
} else {
Vec::new()
// Nested sub-tools: `outer.helper` matches display path `main.outer.helper`.
let suffix = format!(".{query}");
in_entry
.iter()
.copied()
.filter(|artifact| {
artifact.kind == "function"
&& (artifact.display_name.ends_with(&suffix)
|| artifact.display_name == query)
})
.collect()
};
match hits.len() {
1 => Ok(hits[0]),
@@ -210,7 +378,7 @@ fn locate_artifact<'a>(
}
}
fn deny_unsafe(path: &Path, artifact: &SemanticArtifact) -> Result<()> {
fn deny_unsafe(path: &Path, artifact: &SemanticArtifact, effects: CallEffects) -> Result<()> {
if artifact.kind != "function" || artifact.callable.as_deref() == Some("instance_method") {
return Err(call_diag(
Some(path),
@@ -219,14 +387,21 @@ fn deny_unsafe(path: &Path, artifact: &SemanticArtifact) -> Result<()> {
"只有非实例函数可由 call 直接执行".to_string(),
));
}
if !artifact.effects.is_pure() {
let denied: Vec<String> = artifact
.effects
.values()
.into_iter()
.filter(|e| !effects.allows(e))
.collect();
if !denied.is_empty() {
return Err(call_diag(
Some(path),
artifact.source.line,
"artifact.effect_denied",
format!(
"call 默认只执行纯函数,拒绝效应 {}",
artifact.effects.values().join(", ")
"call --effects {} 拒绝效应 {}",
effects.as_str(),
denied.join(", ")
),
));
}
@@ -260,6 +435,9 @@ fn parse_literal(raw: &str) -> Result<Value, String> {
"None" | "none" => return Ok(Value::None),
_ => {}
}
if raw.starts_with('$') || raw.starts_with('@') {
return Ok(Value::Text(raw.to_string()));
}
if raw.len() >= 2 {
let bytes = raw.as_bytes();
if (bytes[0] == b'"' && bytes[raw.len() - 1] == b'"')
@@ -268,6 +446,11 @@ fn parse_literal(raw: &str) -> Result<Value, String> {
return Ok(Value::Text(raw[1..raw.len() - 1].to_string()));
}
}
if raw.starts_with('[') || raw.starts_with('{') {
let json: serde_json::Value =
serde_json::from_str(raw).map_err(|e| format!("JSON 解析失败: {e}"))?;
return json_to_value(&json);
}
if let Ok(n) = raw.parse::<i64>() {
return Ok(Value::Int(n));
}
@@ -277,7 +460,7 @@ fn parse_literal(raw: &str) -> Result<Value, String> {
}
}
Err(format!(
"无法解析 `{raw}`(整数、小数、引号文本、True/False/None)"
"无法解析 `{raw}`(整数、小数、引号文本、True/False/None、JSON、`$name`)"
))
}
+286
View File
@@ -0,0 +1,286 @@
//! Call-session journal for `marqdo call … toget` across process boundaries.
//!
//! Plugin handles do not survive a new OS process; replaying the journal rebuilds them.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use crate::call::{self, CallEffects};
use crate::host::json::{json_to_value, value_to_json};
use crate::value::Value;
use crate::Backend;
const SESSION_DIR: &str = ".marqdo/call-sessions";
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CallSession {
pub session: String,
#[serde(default)]
pub steps: Vec<CallStep>,
/// JSON-serializable bindings from `toget` (when the result was V_safe JSON).
#[serde(default)]
pub bindings: BTreeMap<String, serde_json::Value>,
/// Names whose live value must be rebuilt by replaying `steps` (plugin handles / opaque).
#[serde(default)]
pub journal_bindings: BTreeMap<String, usize>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CallStep {
pub file: String,
pub function: String,
pub args: BTreeMap<String, serde_json::Value>,
pub effects: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub toget: Option<String>,
}
fn sessions_root() -> PathBuf {
if let Ok(p) = std::env::var("MARQDO_CALL_SESSION_DIR") {
return PathBuf::from(p);
}
PathBuf::from(SESSION_DIR)
}
pub fn session_path(id: &str) -> PathBuf {
let safe: String = id
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect();
sessions_root().join(format!("{safe}.json"))
}
pub fn load_session(id: &str) -> Result<CallSession> {
let path = session_path(id);
if !path.exists() {
return Ok(CallSession {
session: id.to_string(),
..Default::default()
});
}
let text = fs::read_to_string(&path)
.with_context(|| format!("read call session {}", path.display()))?;
let mut s: CallSession = serde_json::from_str(&text)
.with_context(|| format!("parse call session {}", path.display()))?;
s.session = id.to_string();
Ok(s)
}
pub fn save_session(session: &CallSession) -> Result<()> {
let path = session_path(&session.session);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let text = serde_json::to_string_pretty(session)?;
fs::write(&path, text)?;
Ok(())
}
/// Resolve `$name` / `@name` argument values from the session (replaying journal as needed).
pub fn resolve_args(
session: &mut CallSession,
args: &[(String, Value)],
backend: Backend,
) -> Result<Vec<(String, Value)>> {
let mut live: BTreeMap<String, Value> = BTreeMap::new();
for (k, v) in &session.bindings {
live.insert(k.clone(), json_to_value(v).map_err(|e| anyhow::anyhow!(e))?);
}
let needs_replay = args.iter().any(|(_, v)| {
matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@'))
&& {
let name = v_text_ref(v);
session.journal_bindings.contains_key(name)
|| (!session.bindings.contains_key(name)
&& session.steps.iter().any(|s| s.toget.as_deref() == Some(name)))
}
});
if needs_replay || args.iter().any(|(_, v)| {
matches!(v, Value::Text(t) if (t.starts_with('$') || t.starts_with('@'))
&& session.journal_bindings.contains_key(&t[1..]))
}) {
live = replay_live(session, backend)?;
}
let mut out = Vec::with_capacity(args.len());
for (name, value) in args {
out.push((
name.clone(),
resolve_one(session, &live, value.clone(), backend)?,
));
}
Ok(out)
}
fn v_text_ref(v: &Value) -> &str {
match v {
Value::Text(t) if t.starts_with('$') || t.starts_with('@') => &t[1..],
Value::Text(t) => t.as_str(),
_ => "",
}
}
fn resolve_one(
session: &CallSession,
live: &BTreeMap<String, Value>,
value: Value,
backend: Backend,
) -> Result<Value> {
let Value::Text(t) = &value else {
return Ok(value);
};
if !(t.starts_with('$') || t.starts_with('@')) {
return Ok(value);
}
let key = &t[1..];
if let Some(v) = live.get(key) {
return Ok(v.clone());
}
if let Some(j) = session.bindings.get(key) {
return json_to_value(j).map_err(|e| anyhow::anyhow!(e));
}
// Last resort: full replay
let live = replay_live(session, backend)?;
live.get(key)
.cloned()
.ok_or_else(|| anyhow::anyhow!("call.session_unbound: `${key}` not in session {}", session.session))
}
fn replay_live(session: &CallSession, backend: Backend) -> Result<BTreeMap<String, Value>> {
let mut live: BTreeMap<String, Value> = BTreeMap::new();
for (k, v) in &session.bindings {
// Prefer journal rebuild for names also in journal_bindings
if !session.journal_bindings.contains_key(k) {
live.insert(k.clone(), json_to_value(v).map_err(|e| anyhow::anyhow!(e))?);
}
}
for step in &session.steps {
let mut args = Vec::new();
for (k, jv) in &step.args {
let mut val = json_to_value(jv).map_err(|e| anyhow::anyhow!(e))?;
if let Value::Text(t) = &val {
if t.starts_with('$') || t.starts_with('@') {
let key = &t[1..];
val = live
.get(key)
.cloned()
.ok_or_else(|| anyhow::anyhow!("call.session_replay: missing `${key}`"))?;
}
}
args.push((k.clone(), val));
}
let effects = CallEffects::parse(&step.effects)?;
let value = call::call_file_raw(
Path::new(&step.file),
&step.function,
&args,
effects,
backend,
)?;
if let Some(name) = &step.toget {
live.insert(name.clone(), value);
}
}
Ok(live)
}
pub fn record_step(
session: &mut CallSession,
file: &Path,
function: &str,
args: &[(String, Value)],
effects: CallEffects,
toget: Option<&str>,
result: &Value,
) -> Result<()> {
let mut arg_map = BTreeMap::new();
for (k, v) in args {
// Keep $ refs as text so replay can resolve them.
if let Value::Text(t) = v {
if t.starts_with('$') || t.starts_with('@') {
arg_map.insert(k.clone(), serde_json::Value::String(t.clone()));
continue;
}
}
match value_to_json(v) {
Ok(j) => {
arg_map.insert(k.clone(), j);
}
Err(_) => {
bail!("call.session: argument `{k}` is not JSON-serializable for the journal");
}
}
}
let file_s = file
.canonicalize()
.unwrap_or_else(|_| file.to_path_buf())
.display()
.to_string();
let step = CallStep {
file: file_s,
function: function.to_string(),
args: arg_map,
effects: effects.as_str().to_string(),
toget: toget.map(|s| s.to_string()),
};
session.steps.push(step);
if let Some(name) = toget {
match value_to_json(result) {
Ok(j) if is_json_friendly(result) => {
session.bindings.insert(name.to_string(), j);
session.journal_bindings.remove(name);
}
_ => {
session.bindings.remove(name);
session
.journal_bindings
.insert(name.to_string(), session.steps.len() - 1);
}
}
}
Ok(())
}
fn is_json_friendly(v: &Value) -> bool {
match v {
Value::None | Value::Bool(_) | Value::Int(_) | Value::Num(_) | Value::Text(_) => true,
Value::List(xs) => xs.iter().all(is_json_friendly),
Value::Map(pairs) => {
// Tagged quantum objects need journal replay across processes.
if pairs.iter().any(|(k, _)| k == "_type") {
return false;
}
pairs.iter().all(|(_, v)| is_json_friendly(v))
}
Value::Handle(_) | Value::Formula(_) | Value::Code(_) | Value::Secret(_) => false,
}
}
/// Dump journal steps as a minimal Marqdo script for later `marqdo run`.
pub fn dump_replay_script(session: &CallSession) -> String {
let mut out = String::from("# main\n\n# Replayed from call-session journal. Review before trusting.\n\n");
for (i, step) in session.steps.iter().enumerate() {
out.push_str(&format!(
"> print text=\"step {i}: call {} {} effects={}\"\n",
step.file, step.function, step.effects
));
}
if let Some(last) = session.steps.last().and_then(|s| s.toget.as_ref()) {
out.push_str(&format!("\n> print text=\"last toget was {last}\"\n"));
}
out.push_str("*None*\n");
out
}
pub fn default_session_id() -> String {
std::env::var("MARQDO_CALL_SESSION").unwrap_or_else(|_| "default".into())
}
+46 -1
View File
@@ -44,7 +44,24 @@ pub const CATALOG: &[ExtPackage] = &[
ExtPackage {
id: "quantum",
description: "Quantum circuit simulator (ext/quantum) — gates/state vector",
mq_files: &["quantum/quantum.mq.md", "quantum/量子.mq.md"],
mq_files: &[
"quantum/index.mq.md",
"quantum/_capability/index.mq.md",
"quantum/circuit/index.mq.md",
"quantum/gate/index.mq.md",
"quantum/simulate/index.mq.md",
"quantum/state/index.mq.md",
"quantum/density/index.mq.md",
"quantum/viz/index.mq.md",
"quantum/量子/索引.mq.md",
"quantum/量子/能力/索引.mq.md",
"quantum/量子/电路/索引.mq.md",
"quantum/量子/门/索引.mq.md",
"quantum/量子/模拟/索引.mq.md",
"quantum/量子/态/索引.mq.md",
"quantum/量子/密度/索引.mq.md",
"quantum/量子/可视化/索引.mq.md",
],
native_crate: Some("marqdo_plugin_quantum"),
},
ExtPackage {
@@ -406,6 +423,20 @@ fn ensure_native_plugin(crate_name: &str) -> Result<PathBuf> {
)
}
fn same_path(a: &Path, b: &Path) -> bool {
match (a.canonicalize(), b.canonicalize()) {
(Ok(x), Ok(y)) => x == y,
_ => a == b,
}
}
/// True when `install_root` is also a source `ext/` tree (dev layout). Copying
/// there truncates `.mq.md` on Linux (`fs::copy` same-file) and drops `.plugin`
/// junk into the repo.
fn install_root_is_source_tree(root: &Path) -> bool {
source_ext_roots().iter().any(|s| same_path(root, s))
}
pub fn add_ext(id: &str) -> Result<()> {
let pkg = find_package(id).with_context(|| {
format!(
@@ -418,6 +449,14 @@ pub fn add_ext(id: &str) -> Result<()> {
)
})?;
let root = install_root()?;
if install_root_is_source_tree(&root) {
bail!(
"refusing to install into extension *source* tree {} \
(set MARQDO_EXT to an install directory such as ~/.marqdo/ext, \
and use MARQDO_EXT_SOURCE for the repo ext/ when needed)",
root.display()
);
}
fs::create_dir_all(&root)
.with_context(|| format!("create install root {}", root.display()))?;
@@ -432,6 +471,12 @@ pub fn add_ext(id: &str) -> Result<()> {
for f in pkg.mq_files {
let src = find_source_file(f)?;
let dest = root.join(f);
if same_path(&src, &dest) {
bail!(
"refusing same-file copy {} (install root overlaps source)",
src.display()
);
}
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("create {}", parent.display()))?;
+2
View File
@@ -14,7 +14,9 @@ pub mod browser_session;
pub mod builtin;
pub mod bytecode;
pub mod call;
pub mod call_session;
pub mod capture;
pub mod narrative_ratio;
#[cfg(feature = "cli")]
pub mod catalog;
#[cfg(feature = "cli")]
+58 -6
View File
@@ -142,11 +142,12 @@ enum Commands {
/// Source file.
file: PathBuf,
/// Function display path, for example `计算器.加法`.
/// Function display path, for example `计算器.加法` or nested `parent.child`.
function: String,
/// Named arguments `name=value` (integer, decimal, quoted text, True/False/None).
/// A value may be negative (`a=-2`). `--json` and `--backend` remain flags.
/// Named arguments `name=value` (integer, decimal, quoted text, True/False/None, JSON, `$name`).
/// A value may be negative (`a=-2`). Trailing `toget <name>` stores the result in the session.
/// `--json` and `--backend` remain flags.
args: Vec<String>,
/// Print one JSON object: `{"ok":true,"result":...}` or `{"ok":false,"error":...}`.
@@ -156,6 +157,18 @@ enum Commands {
/// Runtime. Both backends execute the named function.
#[arg(long, value_enum, default_value_t = BackendCli::Tree)]
backend: BackendCli,
/// Side effects this call may perform (`none` = pure only; `plugin` allows ABI plugins).
#[arg(long, default_value = "none")]
effects: String,
/// Call-session id for `toget` / `$name` (default: env `MARQDO_CALL_SESSION` or `default`).
#[arg(long)]
session: Option<String>,
/// Store the return value under this name in the call session (also: trailing `toget NAME`).
#[arg(long)]
toget: Option<String>,
},
/// Static contract cross-check (渐进式契约): drift, unknown types, misplaced tables
Check {
@@ -171,6 +184,10 @@ enum Commands {
#[arg(long)]
implicit_labels: bool,
/// Require narration ≥ 50% in each function unit (ext skill contract).
#[arg(long)]
narrative_ratio: bool,
/// Parse an unmarked file with the legacy grammar for migration review.
#[arg(long)]
legacy_markup: bool,
@@ -810,10 +827,41 @@ fn try_main(cli: Cli) -> Result<i32> {
args,
json,
backend,
effects,
session,
toget,
} => {
let outcome = (|| -> Result<marqdo::value::Value> {
let parsed = marqdo::call::parse_call_args(&args)?;
marqdo::call::call_file(&file, &function, &parsed, backend.into())
let effects = marqdo::call::CallEffects::parse(&effects)?;
let (arg_tokens, trailing_toget) = marqdo::call::split_toget(&args)?;
let toget = toget.or(trailing_toget);
let parsed = marqdo::call::parse_call_args(&arg_tokens)?;
let session = session.or_else(|| {
if toget.is_some()
|| parsed.iter().any(|(_, v)| {
matches!(
v,
marqdo::value::Value::Text(t)
if t.starts_with('$') || t.starts_with('@')
)
})
{
Some(marqdo::call_session::default_session_id())
} else {
None
}
});
marqdo::call::call_file_with(
&file,
&function,
&parsed,
backend.into(),
marqdo::call::CallOptions {
effects,
session,
toget,
},
)
})();
match outcome {
Ok(value) => {
@@ -849,15 +897,19 @@ fn try_main(cli: Cli) -> Result<i32> {
file,
json,
implicit_labels,
narrative_ratio,
legacy_markup,
} => {
let diags = if legacy_markup {
let mut diags = if legacy_markup {
marqdo::parse::expr::with_markup(marqdo::parse::expr::Markup::Classic, || {
marqdo::check::check_path_opts(&file, implicit_labels)
})?
} else {
marqdo::check::check_path_opts(&file, implicit_labels)?
};
if narrative_ratio {
diags.extend(marqdo::narrative_ratio::check_file(&file)?);
}
let mut errors = 0i32;
for d in &diags {
if matches!(d.severity, marqdo::diagnostics::Severity::Error) {
+222
View File
@@ -0,0 +1,222 @@
//! Narration ratio gate: each function unit should be ≥50% narrative text.
//!
//! Used by `marqdo check --narrative-ratio` and extension skill dogfood.
use std::path::Path;
use anyhow::Result;
use crate::ast::Function;
use crate::diagnostics::{Diagnostic, Span};
use crate::load::load_module;
const MIN_RATIO: f64 = 0.5;
#[derive(Debug, Clone)]
pub struct UnitReport {
pub name: String,
pub line: u32,
pub narrative: usize,
pub total: usize,
pub ratio: f64,
pub pass: bool,
}
/// Check one `.mq.md` file; returns Error diagnostics for failing units.
pub fn check_file(path: &Path) -> Result<Vec<Diagnostic>> {
let reports = check_file_source(path)?;
Ok(reports
.iter()
.filter(|r| !r.pass)
.map(|r| {
Diagnostic::new(
Some(path),
Span::new(r.line, 1),
format!(
"narrative ratio {:.0}% < 50% for function `{}` (narrative={}, total={})",
r.ratio * 100.0,
r.name,
r.narrative,
r.total
),
)
.with_code("narrative.ratio")
})
.collect())
}
/// Measure using original file text between this function's line and the next heading.
pub fn check_file_source(path: &Path) -> Result<Vec<UnitReport>> {
let text = std::fs::read_to_string(path)?;
let module = load_module(path)?;
Ok(measure_source_units(&text, &module.functions))
}
pub fn measure_source_units(source: &str, functions: &[Function]) -> Vec<UnitReport> {
let lines: Vec<&str> = source.lines().collect();
let mut starts: Vec<(String, u32, usize)> = Vec::new();
collect_starts(functions, &mut starts);
starts.sort_by_key(|(_, line, _)| *line);
let mut out = Vec::new();
for (i, (name, line, _)) in starts.iter().enumerate() {
let start = (*line as usize).saturating_sub(1);
let end = starts
.get(i + 1)
.map(|(_, l, _)| (*l as usize).saturating_sub(1))
.unwrap_or(lines.len());
let chunk = lines[start..end.min(lines.len())].join("\n");
let (narrative, code) = split_narrative_code(&chunk);
let total = narrative + code;
let ratio = if total == 0 {
1.0
} else {
narrative as f64 / total as f64
};
out.push(UnitReport {
name: name.clone(),
line: *line,
narrative,
total,
ratio,
pass: total == 0 || ratio + f64::EPSILON >= MIN_RATIO,
});
}
out
}
fn collect_starts(fns: &[Function], out: &mut Vec<(String, u32, usize)>) {
for f in fns {
out.push((f.name.clone(), f.span.line, f.body.len()));
collect_starts(&f.children, out);
}
}
/// Split a function unit's source into narrative vs code character counts.
///
/// Code: lines that are primarily executable markers (`>`, `**`, `*…*`, `+`, tables with `|`,
/// fences, `#`/`##` headings themselves). Narrative: remaining prose (including formula fences
/// content is counted as narrative — formulas are documentation).
pub fn split_narrative_code(chunk: &str) -> (usize, usize) {
let mut narrative = 0usize;
let mut code = 0usize;
let mut in_fence = false;
let mut fence_is_formula = false;
for line in chunk.lines() {
let trimmed = line.trim();
if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
in_fence = !in_fence;
fence_is_formula = trimmed.contains("$$") || trimmed == "$$";
// Fence markers themselves are markup/code budget.
code += line.chars().count();
continue;
}
if in_fence {
// Math/display fences count as narration; language fences as code.
if fence_is_formula {
narrative += line.chars().count();
} else {
code += line.chars().count();
}
continue;
}
if trimmed.is_empty() {
continue;
}
// Standalone $$ formula blocks (Marqdo formula assignment bodies).
if trimmed == "$$" || trimmed.starts_with("$$") {
narrative += line.chars().count();
continue;
}
if is_code_line(trimmed) {
code += line.chars().count();
} else {
narrative += line.chars().count();
}
}
(narrative, code)
}
fn is_code_line(trimmed: &str) -> bool {
if trimmed.starts_with('>') {
return true;
}
if trimmed.starts_with("**") && trimmed.ends_with("**") {
return true;
}
if trimmed.starts_with('*') && trimmed.ends_with('*') && !trimmed.starts_with("**") {
// Return line
return true;
}
if trimmed.starts_with("+ `") || trimmed.starts_with("+`") {
return true;
}
// Contract / documentation tables are narration surface (param and return
// tables under skill tools), not executable code budget.
if trimmed.starts_with('|') {
return false;
}
if trimmed.starts_with('#') {
return true;
}
if trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(". ") {
// Branch list `1. …` — executable control
return true;
}
if trimmed.starts_with("- ") && (trimmed.contains('>') || trimmed.contains('`')) {
return true;
}
if trimmed.starts_with("---") {
return true;
}
if trimmed.starts_with("import:") || trimmed.starts_with("导入:") {
return true;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prose_heavy_unit_passes() {
let chunk = r#"
## hadamard
The Hadamard gate creates equal superposition from the computational basis.
It is the unitary matrix shown below and is central to many algorithms.
| 参数 | 类型 | 说明 |
|------|------|------|
| qubit | number | target |
This paragraph keeps narration above half even with a small table.
| 返回 | 类型 | 说明 |
|------|------|------|
| | handle | circuit |
*None*
"#;
let (n, c) = split_narrative_code(chunk);
assert!(
(n as f64) / ((n + c) as f64) >= 0.5,
"n={n} c={c}"
);
}
#[test]
fn api_list_fails() {
let chunk = r#"
## h
+ `qubit`=0
*> quantum_h circuit=`self` qubit=`qubit`*
"#;
let (n, c) = split_narrative_code(chunk);
assert!(
(n as f64) / ((n + c) as f64) < 0.5,
"n={n} c={c}"
);
}
}