P4 验证执行:(a)锚点消融✅/(c)契约消融✅/(d)防漂移✅/(e)守卫演练✅;(b)盲测 deepseek-flash 完成未达标、mimo-v2.6-pro 重跑中

- perf-validation.md:五实验协议/判据/材料(2026-09-23 自设计)
- perf-validation-report-2026-09-23.md:汇总报告(判据逐项对照 + 诚实结论)
- tests/blind_experiment.rs + tests/blind/:盲测 harness(查询通道/修复回路/usage 计量)+ 冻结材料(6 任务书 + docs-bundle)
- tests/contract_ablation.rs:四边界×三情形消融(拦截 100%/误报 0%/零回归)
- tests/drift_drill.rs:9 漂移必报 + 2 负对照
- src/mlsp.rs:syntax 卡片自持化(semantics/rule/sample/doc_quote)
- three-problems.md §5.1 判据矩阵逐行判定(问题 1✅ 2✅ 3❌);three-problems-plan.md Phase 4 落地记录
- 全量干净回归零失败

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-23 05:06:30 +08:00
1 parent 00c763300e
commit 1a729eb9ec
18 files changed
+1848 -11

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
<!--
P4 实验 (b) 材料 · D 臂(全文档背诵组)上下文包。
来源:commit 199b5c5^ 的 `.cursor/skills/marqdo/SKILL.md`(背诵式「压缩操作手册」)
语言部分原样冻结(Markup→meaning / 最小程序 / 函数调用 / 语句分支 / 导入与内建面)。
只读实验材料——**请勿修改**(改了就不是同一个实验)。
-->
## Markup → meaning (v0.3)
| Marker | Meaning |
|--------|---------|
| `#` | **Object / type** (constructor body). `# main` = entry object. `# Child = > Parent` = inherit (**no** implicit parent constructor; call `` `self` = > Parent … `` explicitly when needed). |
| `##` … `######` | **Function / method** (nesting by heading depth). |
| `` + `name` `` under heading | Parameter (optional `` `name`=default ``) |
| `1.` `2.` … in body | Branch arm (condition or `N. *` else). **Same-indent restart at `1.` = new branch statement** (not more arms of the previous list). |
| `- …` inside body | Loop (`while` or `` [item](coll) `` / `` [`item`](`coll`) ``) |
| Line `N. *` | Else arm |
| `> fn args` | Call (named `k=v` or positional) |
| `修饰 [fn] args` | Bracket-marked call; leading words → `名=True` |
| `` > `obj`.method args `` | Method call (`obj` must be a map with `_type`) |
| Frontmatter `import bind:path.mq.md` / `导入` | Import file (bind library name) |
| Frontmatter `import bind:lib.member` / `导入` | Short name for a library member (same keyword; no separate `use`) |
| `> lib.member …` / `> lib.Type.member …` | Call via bare dotted path (instance methods need `` `var`.m ``) |
| `**…**` | **Code** (assign / call) — closing `**` touches last token; bare ids are variables; quote text literals |
| `*…*` | **Return value** — closing `*` touches last token; bare ids are variables |
| `****` / whole-line `**` / `*None*` | Return `None` and end function body |
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` |
| `- [item](coll)` | Foreach (unchanged) |
| `` ```lang `` | Foreign code block (via `lib/foreign`) |
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
| Unmarked prose | Comment |
Entry: load file (often `index.mq.md`) → collect defs → run `# main`.
## Minimal program
```markdown
# main
> print text=Hello World!
```
Chinese builtins (same functions, no import):
```markdown
# main
> 打印 内容=你好
```
## Functions, calls, end-body
```markdown
# main
> greet who=Marqdo
## greet
+ `who`
> print text=Hello, `who`!
*None*
```
- Call: `> name key=value` or `> name value`.
- Nested helpers use deeper `#` (`##`, `###`, …).
- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped).
- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`).
## Statements, returns, branches
```markdown
**x = 1**
**y = x + 2**
## add_one
+ `n`
*n + 1*
```
```markdown
**n = 0**
1. `n` > 0
> print text=positive
2. `n` < 0
> print text=negative
3. *
> print text=zero
```
## Frontmatter imports + stdlib
Imports use `import bind:target` (`导入` equivalent): file (`.mq.md`) or short name (`lib.member`). Members are **not** flattened into the caller. Call with a bare dotted path:
```markdown
---
title: example
import text:lib/text.mq.md
import clock:lib/time.mq.md
---
# main
**xs = > text.str_split s="a,b,c" sep=","**
> print text=`xs`
**t = > clock.now_unix**
```
- Import **English** or **Chinese** library file; call that file's API names via `lib.member` (do not mix languages).
- Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote.
- Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`.
@@ -0,0 +1,36 @@
# Task: claims_reserve_settle (insurance claims reserve)
Implement an **insurance claims reserve settlement** desk.
This is a **business-policy** pipeline (deductible, coinsurance, sublimit, recovery, floor), **not** an algorithms puzzle.
Use **integer arithmetic only**. Hardcode the demo inputs below and **print one integer**: the final reserve.
## Business requirements (authoritative)
1. **After deductible:** `after_deduct = claim - deductible`. If `after_deduct < 0`, set `after_deduct = 0`.
2. **Coinsurance share (insurer):** `coinsured = after_deduct * coinsure_pct / 100` (demo coinsure_pct = 80). Apply coinsurance **before** recovery.
3. **Sublimit cap:** `capped = coinsured` if `coinsured <= sublimit`, else `capped = sublimit` (never enlarge beyond coinsured).
4. **Recovery offset:** `reserved = capped - recovery`. If `reserved < 0`, set `reserved = 0`.
5. **Reserve floor:** if `reserved < reserve_floor`, set `reserved = reserve_floor`.
## Demo inputs (hardcode)
- `claim = 50000`
- `deductible = 5000`
- `coinsure_pct = 80`
- `sublimit = 30000`
- `recovery = 2000`
- `reserve_floor = 1000`
## Requirements
- Provide named helpers (or clear stages) for deductible, coinsurance, sublimit, recovery, and floor — not one opaque expression.
- Print only the final integer (no labels).
- Align to the **business requirements above**; do not invent alternate order or comparison directions.
## Expected output (self-check)
Exactly one line: `28000`
## Deliverable
Write the program as a Marqdo `.mq.md` file. Return the complete source in a single ```markdown fence — no prose outside the fence.
@@ -0,0 +1,42 @@
# Task: contract_milestone_pay (construction milestone payable)
Implement a **contract milestone payment** desk for an EPC / construction settlement.
This is a **business-policy** pipeline (retention, late penalty, change order, tax), **not** an algorithms puzzle.
Use **integer arithmetic only**. Hardcode the demo inputs below and **print one integer**: the final payable.
## Business requirements (authoritative)
1. **Earned value:** `earned = contract_value * progress_pct / 100`.
2. **Retention withhold:** `retention = earned * retain_pct / 100` (demo uses retain_pct = 5).
3. **Net after retention:** `net = earned - retention`.
4. **Late penalty:** if `days_late > grace_days` (grace_days = 7), set `penalty = net * late_rate / 100` (late_rate = 2); otherwise `penalty = 0`. Penalty is always computed from **`net`**, never from `earned`.
5. **After penalty:** `net2 = net - penalty`.
6. **Change order:** `taxed_base = net2 + change_order`. If `taxed_base < 0`, set `taxed_base = 0`.
7. **Tax:** `tax = taxed_base * tax_rate / 100` (tax_rate = 6).
8. **Payable:** `payable = taxed_base + tax`. If `payable < min_pay` (min_pay = 500), set `payable = min_pay`.
## Demo inputs (hardcode)
- `contract_value = 100000`
- `progress_pct = 40`
- `retain_pct = 5`
- `days_late = 10`
- `grace_days = 7`
- `late_rate = 2`
- `change_order = -2000`
- `tax_rate = 6`
- `min_pay = 500`
## Requirements
- Provide named helpers (or clear stages) for earned, retention, penalty, change+tax, and floor — not one opaque expression.
- Print only the final integer (no labels).
- Align to the **business requirements above**; do not invent alternate thresholds or penalty bases.
## Expected output (self-check)
Exactly one line: `37354`
## Deliverable
Write the program as a Marqdo `.mq.md` file. Return the complete source in a single ```markdown fence — no prose outside the fence.
+30
View File
@@ -0,0 +1,30 @@
# Task: qb_gcd (easy) — Greatest Common Divisor
Implement **Greatest Common Divisor** as a function named `gcd` in a Marqdo `.mq.md` program (Euclidean algorithm).
## Requirements
1. Function name `gcd`, taking two integer parameters and returning their greatest common divisor (non-negative; `gcd(0, 5)` is `5`).
2. In `# main`, hardcode the demo calls below and print each result on its own line — exactly four lines, no labels.
## Demo calls (hardcode)
- `gcd(48, 18)`
- `gcd(1071, 462)`
- `gcd(0, 5)`
- `gcd(17, 5)`
## Expected output (self-check)
Four lines:
```
6
21
5
1
```
## Deliverable
Write the program as a Marqdo `.mq.md` file. Return the complete source in a single ```markdown fence — no prose outside the fence.
+28
View File
@@ -0,0 +1,28 @@
# Task: qb_get_factors (hard) — Prime Factorization
Implement **prime factorization** as a function named `get_factors` in a Marqdo `.mq.md` program. The function takes an integer `n ≥ 2` and returns its prime factors in ascending order.
## Requirements
1. Function name `get_factors`.
2. In `# main`, hardcode the demo inputs below and print each result on its own line — factors joined by `*` with no spaces, exactly three lines, no labels.
## Demo inputs (hardcode)
- `12`
- `13`
- `60`
## Expected output (self-check)
Three lines:
```
2*2*3
13
2*2*3*5
```
## Deliverable
Write the program as a Marqdo `.mq.md` file. Return the complete source in a single ```markdown fence — no prose outside the fence.
+28
View File
@@ -0,0 +1,28 @@
# Task: qb_max_sublist_sum (hard) — Maximum Sublist Sum
Implement the **maximum contiguous sublist sum** as a function named `max_sublist_sum` in a Marqdo `.mq.md` program. The function takes a list of integers and returns the maximum sum of any contiguous sublist (at least one element).
## Requirements
1. Function name `max_sublist_sum`.
2. In `# main`, hardcode the demo inputs below and print each result on its own line — exactly three lines, no labels.
## Demo inputs (hardcode)
- `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`
- `[1, 2, 3]`
- `[-3, -1, -2]`
## Expected output (self-check)
Three lines:
```
6
6
-1
```
## Deliverable
Write the program as a Marqdo `.mq.md` file. Return the complete source in a single ```markdown fence — no prose outside the fence.
+37
View File
@@ -0,0 +1,37 @@
# Task: vendor_po_gate (complex procurement business policy)
Implement a **vendor purchase-order payable gate** for an enterprise procurement desk.
This is a **business-policy** task (multi-rule approval economics), **not** an algorithms puzzle.
Use **integer arithmetic only**. Hardcode the demo inputs below and **print one integer**: the final payable.
## Business requirements (authoritative)
1. **Base line:** `base = qty * unit_cost`.
2. **Preferred-vendor discount:** if `vendor_tier >= 2` (tier-2+ preferred suppliers), set `amount = base * 97 / 100`; otherwise `amount = base`.
3. **Rush surcharge:** if `urgency == 1`, set `amount = amount + amount * 5 / 100`; otherwise keep `amount`.
4. **Budget clamp:** if `amount > budget_cap`, set `amount = budget_cap`.
5. **Compliance fee:** if `risk_flag == 1`, `fee = 80`; else `fee = 0`.
6. **Payable floor:** `payable = amount + fee`; if `payable < 200` then `payable = 200`.
## Demo inputs (hardcode)
- `qty = 20`
- `unit_cost = 40`
- `vendor_tier = 2`
- `urgency = 1`
- `budget_cap = 900`
- `risk_flag = 0`
## Requirements
- Provide named helpers (or clear stages) for discount, rush, budget clamp, fee, and assemble — not one opaque expression.
- Print only the final integer (no labels).
- Align the program to the **business requirements above**; do not invent alternate thresholds.
## Expected output (self-check)
Exactly one line: `814`
## Deliverable
Write the program as a Marqdo `.mq.md` file. Return the complete source in a single ```markdown fence — no prose outside the fence.
+585
View File
@@ -0,0 +1,585 @@
//! P4 实验 (b) 盲测——**查询式(Q)vs 全文档背诵(D)**
//! ([perf-validation.md](../../doc/roadmap/perf-validation.md) §2;three-problems.md §3.7 最终判据)。
//!
//! 唯一变量 = 语法知识获取方式:Q 臂只给硬规则 + 契约表形状 + MLSP 查询通道(≤3 次);
//! D 臂给硬规则 + 契约表形状 + 完整 markup 参考(`blind/docs-bundle.md`,背诵式全语法表)。
//! 两臂任务 / 提示词模板 / 修复回路(≤2 次)/ 模型完全相同。
//!
//! 判据:Q 功能通过率不劣于 D;首轮语法错误率 Q ≤ D;token Q ≤ 70% of D;修复轮次不升。
//! 执行:`OPENAI_MODEL=… cargo test --test blind_experiment -- --ignored --nocapture`。
use std::io::Write;
use marqdo::mlsp::handle_line;
use serde_json::{json, Value};
// ---------- 材料(冻结;只读实验材料) ----------
const DOCS_BUNDLE: &str = include_str!("blind/docs-bundle.md");
const T_CLAIMS: &str = include_str!("blind/tasks/claims_reserve_settle.md");
const T_MILESTONE: &str = include_str!("blind/tasks/contract_milestone_pay.md");
const T_VENDOR: &str = include_str!("blind/tasks/vendor_po_gate.md");
const T_GCD: &str = include_str!("blind/tasks/qb_gcd.md");
const T_KADANE: &str = include_str!("blind/tasks/qb_max_sublist_sum.md");
const T_FACTORS: &str = include_str!("blind/tasks/qb_get_factors.md");
struct Task {
id: &'static str,
desc: &'static str,
oracle: &'static str,
}
fn tasks() -> Vec<Task> {
vec![
Task { id: "claims_reserve_settle", desc: T_CLAIMS, oracle: "28000" },
Task { id: "contract_milestone_pay", desc: T_MILESTONE, oracle: "37354" },
Task { id: "vendor_po_gate", desc: T_VENDOR, oracle: "814" },
Task { id: "qb_gcd", desc: T_GCD, oracle: "6\n21\n5\n1" },
Task { id: "qb_max_sublist_sum", desc: T_KADANE, oracle: "6\n6\n-1" },
Task { id: "qb_get_factors", desc: T_FACTORS, oracle: "2*2*3\n13\n2*2*3*5" },
]
}
// ---------- 提示词(受控:硬规则与契约形状两臂同文) ----------
const HARD_RULES: &str = "\
## Hard rules (do not violate)\n\
1. **File suffix** must be `.mq.md`.\n\
2. **`**…**` = code** (assign / call). **`*…*` = return value**. Output is **not** either marker — use `> print text=…` / `**print text=\"…\"**` / `> 打印 内容=…`.\n\
3. **Prose:** unmarked narrative may contain `` `名` `` (declare/ref), inline `**code**`, and `*return*`. Soft Markdown emphasis that is not code-shaped is ignored. Dead `` `名` `` (never read) is OK and does not become a param.\n\
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**. Params: prefer prose `` `名` `` / `` `名`=默认 `` (inferred); `` + `名` `` still accepted.\n\
5. **Identifiers:** `` `名` `` in prose; inside `*…*` / `**…**`, bare ids are **variables**. **Text literals must be quoted** in bold/italic: `**print text=\"hi\"**`. Standalone `>` calls: bare words = text; vars need ticks: `` > str `n` ``.\n\
6. **Structure lines** (`#` `>` `+` `-` `|` `1.`) need not be wrapped in bold.\n\
7. **Paths:** In bare expressions `/` is division. In call args / defaults / table cells, unspaced `a/b` and quoted paths are text.\n\
8. Prefer ending side-effect-only bodies with `*None*` / `*无*` / whole-line `**` / `****` when the next lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped everywhere), not function end.\n\
9. **`ext/**` never calls `host_*`.**\n\
10. **Code-as-documentation:** prefer GFM tables for maps/lists; prefer named helpers over `json.set` / `json.append` chains.\n\
11. **Table element access has two spellings** — `[键](集合)` is the recommended one (e.g. `[name](`用户`)`, `[1](`xs`)`); footnote form `` `集合`[^键] `` is legacy-compat only.\n\
12. **Bracket-marked calls:** function name may be marked with `[函数名]`; bare words before `[` are boolean modifiers. `]` immediately followed by `(` is **index** `[key](coll)`, not a call.\n";
const CONTRACT_SHAPES: &str = "\
## 渐进式契约表(可选校验元数据)\n\
函数契约 = `##` 函数体内**首个可执行行之前**的未绑定文档表,两种列头:\n\
\n\
| 参数 | 类型 | 说明 |\n\
|------|------|------|\n\
| `n` | number | 输入值 |\n\
\n\
| 返回 | 类型 | 说明 |\n\
|------|------|------|\n\
| | number | 返回说明 |\n\
\n\
集合契约 = `` `名` = `` 绑定**之前**的 `| 字段 | 类型 | 可空 |` 表。\n\
对象契约 = `# 对象` 体内首个成员之前的 `| 字段 | 类型 |` 表。\n\
规则:**被绑定的表是数据,永不视为契约**;类型词表 = `text` / `number` / `bool` / `list` / `map` / `any` / 对象名;\n\
契约表一经出现即为完整声明(写全参数行,否则报 param_drift 警告)。\n";
const QUERY_PROTOCOL: &str = "\
## On-demand syntax queries(你的唯一语法来源)\n\
你**没有** Marqdo 语法参考。对任何不确定的语法细节,先查询再写码:单独输出一行\n\
`QUERY: <关键字>`(如 `QUERY: 返回`、`QUERY: 表`、`QUERY: 调用`),我会回给你对应构造卡片(语义/戒律/样例原文)。\n\
最多 3 次查询。**不要凭 Markdown/Python 习惯猜语法。**\n";
fn system_prompt(arm: &str) -> String {
let intro = "你是 Marqdo 语言(`.mq.md`:Markdown 标记即语法)的程序作者。写完整可运行程序(含 `# main`)。\n\n";
let mut s = String::from(intro);
s.push_str(HARD_RULES);
s.push('\n');
s.push_str(CONTRACT_SHAPES);
s.push('\n');
if arm == "docs" {
s.push_str("## Markup reference (v0.3, complete)\n\n");
s.push_str(DOCS_BUNDLE);
} else {
s.push_str(QUERY_PROTOCOL);
}
s
}
// ---------- LLM 接入(OpenAI 兼容;curl 免依赖;带 usage 计量) ----------
struct Llm {
key: String,
base: String,
model: String,
}
struct Reply {
text: String,
ptok: u32,
ctok: u32,
}
fn llm_cfg() -> Llm {
fn env_of(keys: &[&str]) -> Option<String> {
keys.iter()
.find_map(|k| std::env::var(k).ok())
.filter(|s| !s.is_empty())
}
let mut key = env_of(&["OPENAI_API_KEY", "MARQDO_LLM_API_KEY", "USTC_LLM_API_KEY"]);
let mut base = env_of(&["OPENAI_BASE_URL", "MARQDO_LLM_BASE_URL"]);
let mut model = env_of(&["OPENAI_MODEL", "MARQDO_LLM_MODEL"]);
let env_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".env");
if let Ok(txt) = std::fs::read_to_string(&env_path) {
for line in txt.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some((k, v)) = line.split_once('=') {
let v = v.trim().trim_matches('"').to_string();
match k.trim() {
"OPENAI_API_KEY" | "MARQDO_LLM_API_KEY" => key = key.or(Some(v)),
"OPENAI_BASE_URL" | "MARQDO_LLM_BASE_URL" => base = base.or(Some(v)),
"OPENAI_MODEL" | "MARQDO_LLM_MODEL" => model = model.or(Some(v)),
_ => {}
}
}
}
}
Llm {
key: key.expect("未找到 API 密钥:请设置 OPENAI_API_KEY 或仓库根 .env"),
base: base.unwrap_or_else(|| "https://llm.cflmy.cn/v1".to_string()),
model: model.unwrap_or_else(|| "cflmy".to_string()),
}
}
/// 多轮对话一次;空体/非 JSON/瞬时错误自动重试(容错重试),仍失败 ⇒ Err(基础设施失败)。
fn chat(llm: &Llm, msgs: &[(String, String)]) -> Result<Reply, String> {
let messages: Vec<Value> = msgs
.iter()
.map(|(r, c)| json!({"role": r, "content": c}))
.collect();
let url = format!("{}/chat/completions", llm.base.trim_end_matches('/'));
let auth = format!("Authorization: Bearer {}", llm.key);
let mut last = String::new();
let mut max_tokens = 12000u64; // reasoning 模型先思考后作答;截断时自适应加倍
for _ in 0..12 {
let req = json!({
"model": llm.model,
"temperature": 0,
"max_tokens": max_tokens,
"messages": messages
});
let mut child = std::process::Command::new("curl")
.args(["-sS", "-m", "180", "--retry", "2", "--retry-all-errors", "--retry-delay", "2", &url, "-H", &auth, "-H", "Content-Type: application/json", "--data-binary", "@-"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("启动 curl");
child
.stdin
.as_mut()
.unwrap()
.write_all(req.to_string().as_bytes())
.unwrap();
let out = child.wait_with_output().unwrap();
let text = String::from_utf8_lossy(&out.stdout).to_string();
match serde_json::from_str::<Value>(&text) {
Ok(v) if v["error"].is_object() => {
last = format!("LLM 报错: {}", v["error"]);
}
Ok(v) => {
let reply = v["choices"][0]["message"]["content"].as_str().unwrap_or("");
if !reply.is_empty() {
return Ok(Reply {
text: reply.to_string(),
ptok: v["usage"]["prompt_tokens"].as_u64().unwrap_or(0) as u32,
ctok: v["usage"]["completion_tokens"].as_u64().unwrap_or(0) as u32,
});
}
if v["choices"][0]["finish_reason"] == "length" && max_tokens < 32000 {
max_tokens *= 2; // reasoning 吃满额度 ⇒ 加倍后重试
last = format!("截断(finish=length,content 空),max_tokens 加倍至 {max_tokens}");
} else {
last = format!("响应缺 content: {}", truncate(&text, 120));
}
}
Err(_) => {
let err = String::from_utf8_lossy(&out.stderr).to_string();
last = format!("非 JSON / 空体: {} {}", truncate(&text, 80), truncate(&err, 80));
}
}
std::thread::sleep(std::time::Duration::from_secs(15));
}
Err(last)
}
fn truncate(s: &str, n: usize) -> String {
let t: String = s.chars().take(n).collect();
if s.chars().count() > n {
format!("{t}…")
} else {
t
}
}
// ---------- 程序提取 / 查询 / 执行 ----------
/// 从回复中提取程序源:优先含 `# main` 的围栏,其次最长围栏,再次裸文含 `# main`。
fn extract_program(reply: &str) -> Option<String> {
let mut best: Option<String> = None;
let mut rest = reply;
while let Some(a) = rest.find("```") {
let after = &rest[a + 3..];
let after = after.strip_prefix("markdown").unwrap_or(after);
let after = after.strip_prefix('\n').unwrap_or(after);
if let Some(b) = after.find("```") {
let block = &after[..b];
if block.contains("# main") {
return Some(dedent(block));
}
if best.as_ref().map(|s: &String| s.len() < block.len()).unwrap_or(true) {
best = Some(block.to_string());
}
rest = &after[b + 3..];
} else {
break;
}
}
if let Some(b) = best {
return Some(dedent(&b));
}
if reply.contains("# main") {
return Some(reply.trim().to_string());
}
None
}
fn dedent(block: &str) -> String {
let lines: Vec<&str> = block.lines().collect();
let indent = lines
.iter()
.filter(|l| !l.trim().is_empty())
.map(|l| l.len() - l.trim_start().len())
.min()
.unwrap_or(0);
let out: String = lines
.iter()
.map(|l| l.get(indent..).unwrap_or(l))
.collect::<Vec<_>>()
.join("\n");
format!("{}\n", out.trim_end())
}
/// QUERY 行 → 查询关键字列表。
fn extract_queries(reply: &str) -> Vec<String> {
reply
.lines()
.filter_map(|l| {
let t = l.trim();
let rest = t.strip_prefix("QUERY:").or_else(|| t.strip_prefix("QUERY:"))?;
let q = rest.trim();
if q.is_empty() {
None
} else {
Some(q.to_string())
}
})
.collect()
}
fn mlp_syntax(query: &str) -> String {
handle_line(&json!({"id": 1, "method": "syntax", "params": {"query": query}}).to_string())
}
fn validate_codes(src: &str) -> (bool, Vec<String>, String) {
let resp: Value =
serde_json::from_str(&handle_line(&json!({"id": 1, "method": "validate", "params": {"source": src}}).to_string()))
.expect("MLSP 响应必须是合法 JSON");
if resp["ok"] != true {
let code = resp["error"]["code"].as_str().unwrap_or("?").to_string();
return (false, vec![code], resp.to_string());
}
let diags = resp["result"]["diagnostics"].as_array().cloned().unwrap_or_default();
let codes: Vec<String> = diags
.iter()
.filter_map(|d| d["code"].as_str().map(String::from))
.collect();
(true, codes, diags.iter().map(|d| d.to_string()).collect::<Vec<_>>().join("\n"))
}
fn run_src(task_id: &str, arm: &str, src: &str) -> (i32, String, String) {
let p = std::env::temp_dir().join(format!(
"marqdo_blind_{}_{}_{}.mq.md",
std::process::id(),
arm,
task_id
));
std::fs::write(&p, src).unwrap();
let out = std::process::Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", p.to_str().unwrap()])
.output()
.expect("运行 marqdo");
let _ = std::fs::remove_file(&p);
(
out.status.code().unwrap_or(1),
String::from_utf8_lossy(&out.stdout).to_string(),
String::from_utf8_lossy(&out.stderr).to_string(),
)
}
// ---------- 单例执行 ----------
struct Outcome {
task: &'static str,
arm: &'static str,
result: String, // pass / load-fail / run-fail / wrong-output / infra
rounds: u32, // 通过前的修复次数(首轮通过 = 0)
first_load_fail: bool,
first_contract_diag: bool,
ptok: u32,
ctok: u32,
queries: u32,
note: String,
}
fn run_case(llm: &Llm, task: &Task, arm: &'static str) -> Outcome {
let mut msgs: Vec<(String, String)> = vec![
("system".into(), system_prompt(arm)),
("user".into(), format!("{}\n\n开始写程序。", task.desc)),
];
let (mut ptok, mut ctok) = (0u32, 0u32);
let mut queries = 0u32;
// 查询阶段(Q 臂协议;D 臂模型不被教导 QUERY,自然不会发)
let mut text = String::new();
let mut infra: Option<String> = None;
for _ in 0..6 {
match chat(llm, &msgs) {
Ok(r) => {
ptok += r.ptok;
ctok += r.ctok;
text = r.text;
}
Err(e) => {
infra = Some(e);
break;
}
}
if extract_program(&text).is_some() {
break; // 已带程序(即便附带 QUERY 行也直接用)
}
let qs = extract_queries(&text);
if qs.is_empty() {
break; // 无程序无查询 ⇒ 交给修复回路要程序
}
let mut answer = String::new();
for q in qs.iter().take(3usize.saturating_sub(queries as usize)) {
answer.push_str(&format!("QUERY {} → {}\n", q, mlp_syntax(q)));
queries += 1;
}
if answer.is_empty() {
answer.push_str("查询额度已用完(最多 3 次)。不要再查询,直接写完整程序。\n");
}
msgs.push(("assistant".into(), text.clone()));
msgs.push((
"user".into(),
format!("{answer}\n继续;完成后把完整程序放在**单个** ```markdown 围栏里。"),
));
}
if let Some(e) = infra {
return Outcome {
task: task.id,
arm,
result: "infra".into(),
rounds: 0,
first_load_fail: false,
first_contract_diag: false,
ptok,
ctok,
queries,
note: truncate(&e, 140),
};
}
let mut out = Outcome {
task: task.id,
arm,
result: "infra".into(),
rounds: 0,
first_load_fail: false,
first_contract_diag: false,
ptok,
ctok,
queries,
note: String::new(),
};
for attempt in 0..3u32 {
let src_opt = extract_program(&text);
let (load_ok, codes, diag_txt) = match &src_opt {
Some(src) => validate_codes(src),
None => (false, vec!["harness.no_program".to_string()], String::new()),
};
let contract_diag = codes.iter().any(|c| c.starts_with("contract."));
if attempt == 0 {
out.first_load_fail = src_opt.is_none() || !load_ok;
out.first_contract_diag = contract_diag;
}
let (code, stdout, stderr) = match &src_opt {
Some(src) => run_src(task.id, arm, src),
None => (
1,
String::new(),
"回复中没有 ```markdown 围栏程序(或不含 # main)。".to_string(),
),
};
if code == 0 && stdout.trim_end() == task.oracle.trim() {
out.result = "pass".into();
out.rounds = attempt;
out.note = format!("queries={queries}");
break;
}
out.result = if src_opt.is_none() || !load_ok {
"load-fail".into()
} else if code != 0 {
"run-fail".into()
} else {
"wrong-output".into()
};
out.note = if src_opt.is_none() {
format!("回复中无程序 | 开头: {}", truncate(&text.replace('\n', " "), 160))
} else {
truncate(&format!("{diag_txt} | stderr={stderr}"), 300)
};
if attempt == 2 {
break;
}
msgs.push(("assistant".into(), text.clone()));
msgs.push((
"user".into(),
format!(
"程序未通过。\nvalidate 诊断:\n{diag_txt}\n\n运行 stderr:\n{}\n\n运行 stdout:\n{}\n\n请修复问题,把**完整**程序放在**单个** ```markdown 围栏里(围栏内是纯 Marqdo 源码,含 `# main`)。",
truncate(&stderr, 500),
truncate(&stdout, 200)
),
));
match chat(llm, &msgs) {
Ok(r) => {
ptok += r.ptok;
ctok += r.ctok;
text = r.text;
}
Err(e) => {
out.note = format!("infra: {}", truncate(&e, 100));
break;
}
}
}
out.ptok = ptok;
out.ctok = ctok;
out
}
// ---------- 实验入口 ----------
#[test]
#[ignore]
fn exp_b_blind_query_vs_docs() {
let llm = llm_cfg();
let limit: usize = std::env::var("MARQDO_EXP_LIMIT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(usize::MAX);
let mut outs: Vec<Outcome> = Vec::new();
for arm in ["query", "docs"] {
for t in tasks().iter().take(limit) {
let o = run_case(&llm, t, arm);
eprintln!(
"[{}] {:<24} {:<12} rounds={} tok=({},{}) q={} | {}",
o.arm, o.task, o.result, o.rounds, o.ptok, o.ctok, o.queries, o.note
);
outs.push(o);
}
}
// 汇总(按判据口径:infra 例从比率中剔除并单列)
let mut md = String::new();
md.push_str(&format!(
"# 盲测实验(§5.2(b) 查询式 vs 全文档背诵)—— {}\n\n| | |\n|---|---|\n| 模型 | `{}` @ `{}` |\n| 样本 | 6 任务(业务 3 + QuixBugs 改写 3),oracle = stdout 精确匹配 |\n| 协议 | 系统提示词 = 硬规则 12 条 + 契约表三形状(两臂同文);**唯一变量 = 语法来源**:`query` 臂 MLSP 查询通道(≤3 次)vs `docs` 臂完整 markup 参考(背诵) |\n| 修复 | validate 诊断 + stderr 回喂,≤2 次修复;temperature=0,max_tokens=8000 |\n\n",
chrono_date(),
llm.model,
llm.base
));
md.push_str("## 汇总(判据:Q 通过率不劣于 D;首轮语法错误率 Q≤D;token Q≤70%%D;轮次不升)\n\n");
md.push_str("| 臂 | 通过(一轮) | 通过(最终≤3) | 首轮语法错误 | 首轮契约诊断 | 平均修复轮(过例) | token 合计(prompt+completion) | 弃权/基础设施 |\n");
md.push_str("|---|---|---|---|---|---|---|---|\n");
for arm in ["query", "docs"] {
let os: Vec<&Outcome> = outs.iter().filter(|o| o.arm == arm).collect();
let n = os.len();
let infra = os.iter().filter(|o| o.result == "infra").count();
let denom = n - infra;
let pass1 = os.iter().filter(|o| o.result == "pass" && o.rounds == 0).count();
let passf = os.iter().filter(|o| o.result == "pass").count();
let lf0 = os.iter().filter(|o| o.first_load_fail).count();
let cd0 = os.iter().filter(|o| o.first_contract_diag).count();
let rounds: f64 = {
let p: Vec<u32> = os.iter().filter(|o| o.result == "pass").map(|o| o.rounds).collect();
if p.is_empty() {
0.0
} else {
p.iter().sum::<u32>() as f64 / p.len() as f64
}
};
let ptok: u32 = os.iter().map(|o| o.ptok).sum();
let ctok: u32 = os.iter().map(|o| o.ctok).sum();
md.push_str(&format!(
"| {arm} | {pass1}/{denom} | {passf}/{denom} | {lf0}/{denom} | {cd0}/{denom} | {rounds:.2} | {}({}+{}) | {infra} |\n",
ptok + ctok,
ptok,
ctok
));
}
md.push_str("\n## 逐例\n\n| 例 | 臂 | 结果 | 修复轮 | 首轮语法错 | 首轮契约诊断 | token(p+c) | 查询 | 备注 |\n|---|---|---|---|---|---|---|---|---|\n");
for o in &outs {
md.push_str(&format!(
"| {} | {} | {} | {} | {} | {} | {}+{} | {} | {} |\n",
o.task,
o.arm,
o.result,
o.rounds,
if o.first_load_fail { "是" } else { "否" },
if o.first_contract_diag { "是" } else { "否" },
o.ptok,
o.ctok,
o.queries,
o.note.replace('|', "\\|").replace('\n', " ")
));
}
md.push_str("\n报告由 `tests/blind_experiment.rs` 生成;材料冻结于 `tests/blind/`(任务书 + docs-bundle),判据见 `doc/roadmap/perf-validation.md` §2。\n");
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("doc/roadmap")
.join(format!("blind-experiment-{}-{}.md", chrono_date(), llm.model));
std::fs::write(&path, md).unwrap();
eprintln!("报告已写入 {}", path.display());
}
fn chrono_date() -> String {
if let Ok(d) = std::env::var("MARQDO_EXP_DATE") {
return d;
}
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
let (y, m, d) = civil_from_days((secs / 86400) as i64);
format!("{y:04}-{m:02}-{d:02}")
}
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719468;
let era = if z >= 0 { z } else { z - 146096 } / 146097;
let doe = (z - era * 146097) as u64;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
+279
View File
@@ -0,0 +1,279 @@
//! P4 实验 (c) 契约消融([perf-validation.md](../../doc/roadmap/perf-validation.md) §3):
//! 契约**只在有契约处**拦截错误值(P1:无契约 = 全动态),且不误报。
//!
//! 四边界(调用实参 / 返回 / 表绑定 / 字段访问)× 三形态:
//! ① 带契约 + 错值 → 必拦(`contract.*`);② 带契约 + 对值 → 零误报(跑通);
//! ③ 同程序**删契约表** + 错值 → 零 `contract.*`(动态语义原样——零回归)。
mod common;
use common::{diagnose, static_diags, Verify};
/// (边界, 形态源)——每个边界的三形态共享同一程序骨架,只动契约表与值。
struct Boundary {
name: &'static str,
wrong: &'static str, // ① 带契约 + 错值
code: &'static str, // ① 期望拦截码
right: &'static str, // ② 带契约 + 对值
bare: &'static str, // ③ 无契约 + 错值(同程序删契约表)
}
const ARG_WRONG: &str = "\
# main
**结果 = > 回显 \"7\"**
*结果*
## 回显
对于输入变量`n`,原样回显。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | number | 输入值 |
*n*
";
const ARG_RIGHT: &str = "\
# main
**结果 = > 回显 3**
*结果*
## 回显
对于输入变量`n`,原样回显。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | number | 输入值 |
*n*
";
const ARG_BARE: &str = "\
# main
**结果 = > 回显 \"7\"**
*结果*
## 回显
对于输入变量`n`,原样回显。
*n*
";
const RET_WRONG: &str = "\
# main
**结果 = > 整 \"hi\"**
*结果*
## 整
对于输入变量`n`,原样返回。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | any | 输入值 |
| 返回 | 类型 | 说明 |
|------|------|------|
| | number | 固定值 |
*n*
";
const RET_RIGHT: &str = "\
# main
**结果 = > 整 7**
*结果*
## 整
对于输入变量`n`,原样返回。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | any | 输入值 |
| 返回 | 类型 | 说明 |
|------|------|------|
| | number | 固定值 |
*n*
";
const RET_BARE: &str = "\
# main
**结果 = > 整 \"hi\"**
*结果*
## 整
对于输入变量`n`,原样返回。
*n*
";
const BIND_WRONG: &str = "\
# main
| 字段 | 类型 | 可空 |
|------|------|------|
| id | number | |
| name | text | 是 |
`用户` =
| id | name |
|------|------|
| abc | 小明 |
*[name](`用户`)*
";
const BIND_RIGHT: &str = "\
# main
| 字段 | 类型 | 可空 |
|------|------|------|
| id | number | |
| name | text | 是 |
`用户` =
| id | name |
|------|------|
| 1 | 小明 |
*[name](`用户`)*
";
const BIND_BARE: &str = "\
# main
`用户` =
| id | name |
|------|------|
| abc | 小明 |
*[name](`用户`)*
";
const KEY_WRONG: &str = "\
# main
| 字段 | 类型 | 可空 |
|------|------|------|
| id | number | |
| name | text | 是 |
`用户` =
| id | name |
|------|------|
| 1 | 小明 |
*[email](`用户`)*
";
const KEY_RIGHT: &str = "\
# main
| 字段 | 类型 | 可空 |
|------|------|------|
| id | number | |
| name | text | 是 |
`用户` =
| id | name |
|------|------|
| 1 | 小明 |
*[name](`用户`)*
";
const KEY_BARE: &str = "\
# main
`用户` =
| id | name |
|------|------|
| 1 | 小明 |
*[email](`用户`)*
";
fn boundaries() -> Vec<Boundary> {
vec![
Boundary { name: "call-arg", wrong: ARG_WRONG, code: "contract.arg_mismatch", right: ARG_RIGHT, bare: ARG_BARE },
Boundary { name: "return", wrong: RET_WRONG, code: "contract.return_mismatch", right: RET_RIGHT, bare: RET_BARE },
Boundary { name: "bind", wrong: BIND_WRONG, code: "contract.field_mismatch", right: BIND_RIGHT, bare: BIND_BARE },
Boundary { name: "key-access", wrong: KEY_WRONG, code: "contract.unknown_key", right: KEY_RIGHT, bare: KEY_BARE },
]
}
#[test]
fn ablation_interception_rate_100() {
let all = boundaries();
let total = all.len();
let mut caught = 0;
for b in &all {
let diags = diagnose(Verify::Run(b.code), b.wrong, &format!("abl_wrong_{}", b.name));
assert!(
diags.iter().any(|v| v["code"].as_str() == Some(b.code)),
"[{}] 带契约 + 错值必须被拦截(期望 {}): {:?}",
b.name, b.code, diags
);
caught += 1;
}
eprintln!("契约拦截率 = {caught}/{total} = 100%");
}
#[test]
fn ablation_false_positive_rate_0() {
let all = boundaries();
let total = all.len();
for b in &all {
let run_diags = diagnose(Verify::Run(""), b.right, &format!("abl_right_{}", b.name));
assert!(run_diags.is_empty(), "[{}] 对值被误报(运行): {:?}", b.name, run_diags);
let static_diags = static_diags(b.right);
assert!(
static_diags.is_empty(),
"[{}] 对值被误报(静态): {:?}",
b.name,
static_diags
);
}
eprintln!("契约误报率 = 0/{total} = 0%");
}
#[test]
fn ablation_no_contract_zero_regression() {
// 无契约路径:同程序删掉契约表 + 错值 ⇒ 零 contract.*(动态语义原样)。
// key-access 的动态语义是经典 `missing map key` 运行错——也必须是非契约诊断。
let all = boundaries();
let total = all.len();
for b in &all {
let diags = diagnose(Verify::Run(""), b.bare, &format!("abl_bare_{}", b.name));
assert!(
diags.iter().all(|v| !v["code"].as_str().unwrap_or("").starts_with("contract.")),
"[{}] 无契约路径出现契约诊断(P1 违例): {:?}",
b.name,
diags
);
if b.name == "key-access" {
// 动态基线:经典 missing map key 错误照旧(错误不是被契约吞掉或改写)。
assert!(
diags.iter().any(|v| v["message"]
.as_str()
.unwrap_or("")
.contains("missing map key")),
"key-access 动态基线应为经典 missing map key: {diags:?}"
);
}
}
eprintln!("无契约零回归 = {total}/{total}");
}
+254
View File
@@ -0,0 +1,254 @@
//! P4 实验 (d) 防漂移演练([perf-validation.md](../../doc/roadmap/perf-validation.md) §4):
//! **故意写错契约必报率 = 100%**——契约错了必被机器抓,绝不静默信任契约
//! (three-problems.md §2.8「故意写错契约的金样必红」)。
//!
//! 9 例故意漂移(类型 typo ×2 / 参数名漂移 / 错位表 / 重复表 / 四边界错值)
//! 必须全部产出 `contract.*` 诊断(静态或运行时);
//! 2 例负对照(被绑定的数据表 / 干净契约)**零误报**。
mod common;
use common::{diagnose, static_diags, Verify};
struct Drill {
name: &'static str,
src: &'static str,
/// true = 运行期诊断;false = 静态(mlsp validate = parse + check)。
runtime: bool,
code: &'static str,
}
/// 类型 typo(参数表 `nubmer`)→ 静态 `contract.unknown_type`。
const SRC_TYPO_PARAM: &str = "\
# main
## 加一
对于输入变量`n`,执行加一。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | nubmer | 输入值 |
*n+1*
";
/// 类型 typo(字段表未知对象名 `巨龙`)→ 静态 `contract.unknown_type`。
const SRC_TYPO_FIELD: &str = "\
# main
| 字段 | 类型 | 可空 |
|------|------|------|
| id | 巨龙 | |
`用户` =
| id |
|------|
| 1 |
*[id](`用户`)*
";
/// 契约参数名 ≠ 升参名(`nn` vs `n`)→ 静态 `contract.param_drift`。
const SRC_PARAM_DRIFT: &str = "\
# main
## 加一
对于输入变量`n`,执行加一。
| 参数 | 类型 | 说明 |
|------|------|------|
| nn | number | 输入值 |
*n+1*
";
/// 错位契约表(出现在可执行语句之后)→ 静态 `contract.misplaced`。
const SRC_MISPLACED: &str = "\
# main
**x=1**
| 参数 | 类型 | 说明 |
|------|------|------|
| n | number | 输入值 |
*x*
";
/// 重复契约表(两份参数表打架)→ 装载期 `contract.duplicate`。
const SRC_DUPLICATE: &str = "\
# main
## 加一
对于输入变量`n`,执行加一。
| 参数 | 类型 |
|------|------|
| n | number |
| 参数 | 类型 |
|------|------|
| n | number |
*n+1*
";
/// 实参越约(参数契约 number,实参 text)→ 运行期 `contract.arg_mismatch`。
const SRC_ARG: &str = "\
# main
**结果 = > 回显 \"7\"**
*结果*
## 回显
对于输入变量`n`,原样回显。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | number | 输入值 |
*n*
";
/// 返回越约(返回契约 number,实际返回 text)→ 运行期 `contract.return_mismatch`。
const SRC_RETURN: &str = "\
# main
**结果 = > 整 \"hi\"**
*结果*
## 整
对于输入变量`n`,原样返回。
| 返回 | 类型 | 说明 |
|------|------|------|
| | number | 固定值 |
*n*
";
/// 表绑定越约(字段 id 契约 number,单元格 abc)→ 运行期 `contract.field_mismatch`。
const SRC_FIELD: &str = "\
# main
| 字段 | 类型 | 可空 |
|------|------|------|
| id | number | |
| name | text | 是 |
`用户` =
| id | name |
|------|------|
| abc | 小明 |
*[name](`用户`)*
";
/// 缺键访问(契约有 email,集合没有)→ 运行期 `contract.unknown_key`。
const SRC_UNKNOWN_KEY: &str = "\
# main
| 字段 | 类型 | 可空 |
|------|------|------|
| id | number | |
| name | text | 是 |
`用户` =
| id | name |
|------|------|
| 1 | 小明 |
*[email](`用户`)*
";
/// 负对照 1:**被绑定**的 `字段|类型|可空` 数据表(web_db_migration 式)= 数据,不是契约。
const SRC_BOUND_DATA: &str = "\
# main
`列说明` =
| 字段 | 类型 | 可空 |
|------|------|------|
| id | number | |
| name | text | 是 |
*[字段]([1](`列说明`))*
";
/// 负对照 2:干净契约 + 对值。
const SRC_OK: &str = "\
# main
**结果 = > 加一 3**
*结果*
## 加一
对于输入变量`n`,期望是数字。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | number | 输入值 |
| 返回 | 类型 | 说明 |
|------|------|------|
| | number | 加一结果 |
*n+1*
";
fn drills() -> Vec<Drill> {
vec![
Drill { name: "type-typo-param", src: SRC_TYPO_PARAM, runtime: false, code: "contract.unknown_type" },
Drill { name: "type-typo-field", src: SRC_TYPO_FIELD, runtime: false, code: "contract.unknown_type" },
Drill { name: "param-name-drift", src: SRC_PARAM_DRIFT, runtime: false, code: "contract.param_drift" },
Drill { name: "misplaced-table", src: SRC_MISPLACED, runtime: false, code: "contract.misplaced" },
Drill { name: "duplicate-table", src: SRC_DUPLICATE, runtime: true, code: "contract.duplicate" },
Drill { name: "arg-mismatch", src: SRC_ARG, runtime: true, code: "contract.arg_mismatch" },
Drill { name: "return-mismatch", src: SRC_RETURN, runtime: true, code: "contract.return_mismatch" },
Drill { name: "field-mismatch", src: SRC_FIELD, runtime: true, code: "contract.field_mismatch" },
Drill { name: "unknown-key", src: SRC_UNKNOWN_KEY, runtime: true, code: "contract.unknown_key" },
]
}
#[test]
fn drift_cases_all_reported() {
let all = drills();
let total = all.len();
let mut caught = 0;
for d in &all {
let diags = if d.runtime {
diagnose(Verify::Run(d.code), d.src, &format!("drift_{}", d.name))
} else {
static_diags(d.src)
};
let hit = diags.iter().any(|v| v["code"].as_str() == Some(d.code));
assert!(
hit,
"[{}] 故意写错的契约必须被诊断(期望 {}): {:?}",
d.name, d.code, diags
);
caught += 1;
}
eprintln!("防漂移必报率 = {caught}/{total} = 100%");
}
#[test]
fn negative_controls_zero_false_positives() {
// 1. 被绑定的 `字段|类型|可空` 数据表 = 数据(web_db_migration 式)——绝不能被当契约吃掉。
let diags = diagnose(Verify::Run(""), SRC_BOUND_DATA, "drill_neg_bound");
assert!(
diags.iter().all(|v| !v["code"].as_str().unwrap_or("").starts_with("contract.")),
"绑定数据表被误当契约: {diags:?}"
);
// 2. 干净契约 + 对值 ⇒ 静态零诊断、运行零诊断。
let diags = static_diags(SRC_OK);
assert!(diags.is_empty(), "干净契约被误报(静态): {diags:?}");
let diags = diagnose(Verify::Run(""), SRC_OK, "drill_neg_ok");
assert!(diags.is_empty(), "干净契约被误报(运行): {diags:?}");
eprintln!("负对照误报 = 0/2 = 0%");
}
+28
View File
@@ -33,6 +33,34 @@ fn syntax_unknown_query_structured_error() {
assert_eq!(resp["error"]["code"], "mlsp.no_match");
}
#[test]
fn syntax_cards_carry_rule_text_self_sufficient() {
// 「AI 不必学语法」的前提:卡片自带语义/戒律/样例原文(不必回读文档),
// 且空查询列出全部核心构造(three-problems.md §3.2「单构造戒律」)。
let resp = call(r#"{"id":9,"method":"syntax","params":{}}"#);
assert_eq!(resp["ok"], true, "{resp}");
let cards = resp["result"]["cards"].as_array().unwrap();
assert_eq!(
cards.len(),
marqdo::parse::CORE_CONSTRUCTS.len(),
"空查询应列出全部核心构造: {resp}"
);
for c in cards {
assert!(
c["rule"].as_str().unwrap_or("").len() > 2,
"卡片缺戒律原文(不可自持): {c}"
);
assert!(
c["doc_quote"].as_str().unwrap_or("").starts_with('|'),
"卡片缺行原文: {c}"
);
assert!(
!c["semantics"].as_str().unwrap_or("").is_empty(),
"卡片缺语义: {c}"
);
}
}
#[test]
fn locate_symbol_returns_span_and_contract() {
let src = "# main\n\n## 加一\n\n对于输入变量`n`,执行加一。\n\n| 参数 | 类型 | 说明 |\n|------|------|------|\n| n | number | 输入值 |\n\n*n+1*\n";