refactor: convert Marqdo into the ecosystem integration repository
This commit is contained in:
1 parent
1c55baabd5
commit
4c5c102593
1880 files changed
+998
-308724
No files matched your search
@@ -1,22 +0,0 @@
|
||||
# 测试夹具(金样例)
|
||||
|
||||
金样例与集成测试同处 `tests/`,用子目录区分类别。设计见 [examples-and-tests.md](../doc/design/examples-and-tests.md)。
|
||||
|
||||
| 路径 | 内容 |
|
||||
|------|------|
|
||||
| [`structure/`](structure/) | 函数、调用、分支、循环、表、导入、位置实参 |
|
||||
| [`keywords/`](keywords/) | `print`、布尔与 `and`/`or`/`not` |
|
||||
| [`markup-v03/`](markup-v03/) | **Markup v0.3 草案金样例**(`#[ignore]` 至旗标落地;见目录 README) |
|
||||
| [`errors/`](errors/) | 期望失败(诊断文案) |
|
||||
| [`web_handbook.rs`](web_handbook.rs) | 直接执行双语 Web 手册,验证递归布局参考工程的离线/在线一致性;先构建 Web 插件 |
|
||||
| [`quantum_handbook.rs`](quantum_handbook.rs) | 直接执行 Quantum 双语手册围栏,校验科学期望、真实契约及双后端;先构建量子插件 |
|
||||
| [`gold.rs`](gold.rs) | 集成测试:跑上述夹具并比对 stdout / stderr |
|
||||
|
||||
```bash
|
||||
cargo test
|
||||
marqdo run tests/structure/hello.mq.md
|
||||
marqdo view tests
|
||||
marqdo catalog tests -o .marqdo
|
||||
```
|
||||
|
||||
面向访客的可执行介绍在 [`public/`](../public/)(不含 `errors/`),见 [user-site.md](../doc/design/user-site.md)。
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,34 +0,0 @@
|
||||
# Application composition corpus
|
||||
|
||||
Four authored tasks exercise the actual document loader, tree/bytecode evaluators
|
||||
and interactive history API. Each has separate Python and Node implementations
|
||||
of the producer and consumer. `CASES.json` is the eight-case regression subset;
|
||||
the reviewer driver generates 80 size/seed/direction instances before execution.
|
||||
They are four application families, not 80 independent real-user applications.
|
||||
|
||||
- Invoice ledger: discard void rows, first-posted invoice deduplication, integer
|
||||
cents/discount accounting, signed refunds with floor division, regional totals.
|
||||
- Routes: minimum nonnegative parallel edge, zero-cost edges, disconnected nodes
|
||||
and weighted single-source distances. Python uses heap-based Dijkstra, Node a
|
||||
linear frontier; independent reference uses SQL and all-pairs Floyd-Warshall.
|
||||
- Concordance: NFC plus **ASCII** lowercase, explicit space/tab/LF/CR/NBSP
|
||||
separators, occurrence/document frequencies, UTF-8 byte order. This is not
|
||||
Unicode full case folding. Wide IDs remain strings; special object-key text,
|
||||
combining marks, BMP and astral characters are included.
|
||||
- Wine: UCI red-wine CSV, exact decimal density/pH scaling to integers and
|
||||
quality-group count/sum/min/max. Full input contains 1599 rows; no predictor
|
||||
accuracy or general machine-learning performance is claimed.
|
||||
|
||||
Independent SQL/Fraction/Floyd references live in the reviewer experiment
|
||||
`application_cases.py`; no foreign program output supplies expected answers.
|
||||
The raw/public-data digest, citation, license and retrieval source are preserved
|
||||
in `data/PROVENANCE.json`. Wine Quality is by Cortez, Cerdeira, Almeida, Matos and
|
||||
Reis (2009), UCI, DOI 10.24432/C56S3T, CC BY 4.0. CSV text fixture generation
|
||||
normalizes physical line endings and uses the requested first N data rows.
|
||||
|
||||
The composition copies input into a producer, gets a normalized value, copies it
|
||||
into the consumer, records an expected ordinary exception after saving `answer`,
|
||||
recovers it, replaces the consumer's bridge with null, verifies the producer's
|
||||
copy and answer remain, and closes both sessions. Interactive recordings repeat
|
||||
these actions and strictly replay both raw and losslessly packed history.
|
||||
Native and independent checks distinguish explicit null from display stdout.
|
||||
@@ -1,10 +0,0 @@
|
||||
var index = new Map();
|
||||
for (var row of bridge) {
|
||||
for (var word of row.tokens) {
|
||||
var value = index.get(word) || {count:0,docs:new Set()};
|
||||
value.count++; value.docs.add(row.id); index.set(word,value);
|
||||
}
|
||||
}
|
||||
var answer = [...index].sort((a,b)=>Buffer.compare(Buffer.from(a[0]),Buffer.from(b[0])))
|
||||
.map(([word,v])=>({word,occurrences:v.count,documents:v.docs.size}));
|
||||
answer;
|
||||
@@ -1,10 +0,0 @@
|
||||
from collections import Counter, defaultdict
|
||||
occurrences = Counter()
|
||||
documents = defaultdict(set)
|
||||
for row in bridge:
|
||||
for word in row['tokens']:
|
||||
occurrences[word] += 1
|
||||
documents[word].add(row['id'])
|
||||
answer = [{'word':word,'occurrences':occurrences[word],'documents':len(documents[word])}
|
||||
for word in sorted(occurrences,key=lambda s:s.encode('utf-8'))]
|
||||
answer
|
||||
@@ -1,3 +0,0 @@
|
||||
var bridge = data.map(row=>({id:row.id,tokens:row.text.normalize('NFC').replace(/[A-Z]/g,c=>c.toLowerCase()).split(/[ \n\t\r\u00a0]+/).filter(t=>t.length)}));
|
||||
bridge.sort((a,b)=>Buffer.compare(Buffer.from(a.id),Buffer.from(b.id)));
|
||||
bridge;
|
||||
@@ -1,6 +0,0 @@
|
||||
import re, unicodedata
|
||||
ascii_lower = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')
|
||||
bridge = [{'id': row['id'], 'tokens': [t for t in re.split('[ \n\t\r\u00a0]+',unicodedata.normalize('NFC',row['text']).translate(ascii_lower)) if t]}
|
||||
for row in data]
|
||||
bridge.sort(key=lambda row:row['id'].encode('utf-8'))
|
||||
bridge
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"source": "https://archive.ics.uci.edu/static/public/186/wine+quality.zip",
|
||||
"landing_page": "https://archive.ics.uci.edu/dataset/186/wine%2Bquality",
|
||||
"doi": "10.24432/C56S3T",
|
||||
"authors": [
|
||||
"Paulo Cortez",
|
||||
"A. Cerdeira",
|
||||
"F. Almeida",
|
||||
"T. Matos",
|
||||
"J. Reis"
|
||||
],
|
||||
"year": 2009,
|
||||
"license": "CC BY 4.0",
|
||||
"license_url": "https://creativecommons.org/licenses/by/4.0/",
|
||||
"retrieved": "2026-11-03",
|
||||
"files": {
|
||||
"winequality.names": "15d215e73b39105952380fd487e4ce1bf5a6b83a425abb285c2ec55193d3ca92",
|
||||
"winequality-red.csv": "4a402cf041b025d4566d954c3b9ba8635a3a8a01e039005d97d6a710278cf05e",
|
||||
"wine-quality.zip": "3ed56667f4b828242bd732d7d1dd7f2861e54432239d7fa63877014cbb0304d4"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -1,72 +0,0 @@
|
||||
Citation Request:
|
||||
This dataset is public available for research. The details are described in [Cortez et al., 2009].
|
||||
Please include this citation if you plan to use this database:
|
||||
|
||||
P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis.
|
||||
Modeling wine preferences by data mining from physicochemical properties.
|
||||
In Decision Support Systems, Elsevier, 47(4):547-553. ISSN: 0167-9236.
|
||||
|
||||
Available at: [@Elsevier] http://dx.doi.org/10.1016/j.dss.2009.05.016
|
||||
[Pre-press (pdf)] http://www3.dsi.uminho.pt/pcortez/winequality09.pdf
|
||||
[bib] http://www3.dsi.uminho.pt/pcortez/dss09.bib
|
||||
|
||||
1. Title: Wine Quality
|
||||
|
||||
2. Sources
|
||||
Created by: Paulo Cortez (Univ. Minho), Antonio Cerdeira, Fernando Almeida, Telmo Matos and Jose Reis (CVRVV) @ 2009
|
||||
|
||||
3. Past Usage:
|
||||
|
||||
P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis.
|
||||
Modeling wine preferences by data mining from physicochemical properties.
|
||||
In Decision Support Systems, Elsevier, 47(4):547-553. ISSN: 0167-9236.
|
||||
|
||||
In the above reference, two datasets were created, using red and white wine samples.
|
||||
The inputs include objective tests (e.g. PH values) and the output is based on sensory data
|
||||
(median of at least 3 evaluations made by wine experts). Each expert graded the wine quality
|
||||
between 0 (very bad) and 10 (very excellent). Several data mining methods were applied to model
|
||||
these datasets under a regression approach. The support vector machine model achieved the
|
||||
best results. Several metrics were computed: MAD, confusion matrix for a fixed error tolerance (T),
|
||||
etc. Also, we plot the relative importances of the input variables (as measured by a sensitivity
|
||||
analysis procedure).
|
||||
|
||||
4. Relevant Information:
|
||||
|
||||
The two datasets are related to red and white variants of the Portuguese "Vinho Verde" wine.
|
||||
For more details, consult: http://www.vinhoverde.pt/en/ or the reference [Cortez et al., 2009].
|
||||
Due to privacy and logistic issues, only physicochemical (inputs) and sensory (the output) variables
|
||||
are available (e.g. there is no data about grape types, wine brand, wine selling price, etc.).
|
||||
|
||||
These datasets can be viewed as classification or regression tasks.
|
||||
The classes are ordered and not balanced (e.g. there are munch more normal wines than
|
||||
excellent or poor ones). Outlier detection algorithms could be used to detect the few excellent
|
||||
or poor wines. Also, we are not sure if all input variables are relevant. So
|
||||
it could be interesting to test feature selection methods.
|
||||
|
||||
5. Number of Instances: red wine - 1599; white wine - 4898.
|
||||
|
||||
6. Number of Attributes: 11 + output attribute
|
||||
|
||||
Note: several of the attributes may be correlated, thus it makes sense to apply some sort of
|
||||
feature selection.
|
||||
|
||||
7. Attribute information:
|
||||
|
||||
For more information, read [Cortez et al., 2009].
|
||||
|
||||
Input variables (based on physicochemical tests):
|
||||
1 - fixed acidity
|
||||
2 - volatile acidity
|
||||
3 - citric acid
|
||||
4 - residual sugar
|
||||
5 - chlorides
|
||||
6 - free sulfur dioxide
|
||||
7 - total sulfur dioxide
|
||||
8 - density
|
||||
9 - pH
|
||||
10 - sulphates
|
||||
11 - alcohol
|
||||
Output variable (based on sensory data):
|
||||
12 - quality (score between 0 and 10)
|
||||
|
||||
8. Missing Attribute Values: None
|
||||
@@ -1,10 +0,0 @@
|
||||
var totals = new Map();
|
||||
for (var row of bridge) {
|
||||
var value = totals.get(row.region) || [0, 0];
|
||||
value[0] += 1;
|
||||
value[1] += Math.floor(row.units * row.cents * (10000-row.discount) / 10000);
|
||||
totals.set(row.region, value);
|
||||
}
|
||||
var answer = [...totals].sort((a,b) => Buffer.compare(Buffer.from(a[0]),Buffer.from(b[0])))
|
||||
.map(([region, value]) => ({region, invoices: value[0], net_cents: value[1]}));
|
||||
answer;
|
||||
@@ -1,8 +0,0 @@
|
||||
from collections import defaultdict
|
||||
totals = defaultdict(lambda: [0, 0])
|
||||
for row in bridge:
|
||||
totals[row['region']][0] += 1
|
||||
totals[row['region']][1] += row['units'] * row['cents'] * (10000-row['discount']) // 10000
|
||||
answer = [{'region': k, 'invoices': v[0], 'net_cents': v[1]}
|
||||
for k, v in sorted(totals.items(), key=lambda kv: kv[0].encode('utf-8'))]
|
||||
answer
|
||||
@@ -1,10 +0,0 @@
|
||||
var seen = new Set();
|
||||
var bridge = [];
|
||||
for (var row of data) {
|
||||
if (row.status === 'posted' && !seen.has(row.id)) {
|
||||
seen.add(row.id);
|
||||
bridge.push({id: row.id, region: row.region, units: row.units, cents: row.cents, discount: row.discount});
|
||||
}
|
||||
}
|
||||
bridge.sort((a, b) => Buffer.compare(Buffer.from(a.id), Buffer.from(b.id)));
|
||||
bridge;
|
||||
@@ -1,8 +0,0 @@
|
||||
seen = set()
|
||||
bridge = []
|
||||
for row in data:
|
||||
if row['status'] == 'posted' and row['id'] not in seen:
|
||||
seen.add(row['id'])
|
||||
bridge.append({k: row[k] for k in ('id', 'region', 'units', 'cents', 'discount')})
|
||||
bridge.sort(key=lambda r: r['id'].encode('utf-8'))
|
||||
bridge
|
||||
@@ -1,14 +0,0 @@
|
||||
var distance = new Map(bridge.nodes.map(n=>[n,Infinity]));
|
||||
distance.set(bridge.source,0);
|
||||
var unvisited = new Set(bridge.nodes);
|
||||
while (unvisited.size) {
|
||||
var best = [...unvisited].reduce((a,b)=>distance.get(a)<=distance.get(b)?a:b);
|
||||
unvisited.delete(best);
|
||||
if (!Number.isFinite(distance.get(best))) break;
|
||||
for (var edge of bridge.edges) {
|
||||
if (edge.from === best && distance.get(best)+edge.weight < distance.get(edge.to))
|
||||
distance.set(edge.to,distance.get(best)+edge.weight);
|
||||
}
|
||||
}
|
||||
var answer = bridge.nodes.map(node=>({node,distance:Number.isFinite(distance.get(node))?distance.get(node):null}));
|
||||
answer;
|
||||
@@ -1,17 +0,0 @@
|
||||
import heapq
|
||||
adjacency = {node: [] for node in bridge['nodes']}
|
||||
for edge in bridge['edges']:
|
||||
adjacency[edge['from']].append((edge['to'], edge['weight']))
|
||||
distance = {bridge['source']: 0}
|
||||
pending = [(0, bridge['source'])]
|
||||
while pending:
|
||||
cost, node = heapq.heappop(pending)
|
||||
if distance[node] != cost:
|
||||
continue
|
||||
for target, weight in adjacency[node]:
|
||||
candidate = cost + weight
|
||||
if target not in distance or candidate < distance[target]:
|
||||
distance[target] = candidate
|
||||
heapq.heappush(pending, (candidate, target))
|
||||
answer = [{'node': n, 'distance': distance.get(n)} for n in bridge['nodes']]
|
||||
answer
|
||||
@@ -1,11 +0,0 @@
|
||||
var minimum = new Map();
|
||||
for (var edge of data.edges) {
|
||||
if (edge.weight >= 0) {
|
||||
var key = JSON.stringify([edge.from, edge.to]);
|
||||
minimum.set(key, Math.min(minimum.has(key) ? minimum.get(key) : edge.weight, edge.weight));
|
||||
}
|
||||
}
|
||||
var edges = [...minimum].map(([key,weight]) => ({from: JSON.parse(key)[0], to: JSON.parse(key)[1], weight}));
|
||||
edges.sort((a,b) => Buffer.compare(Buffer.from(a.from),Buffer.from(b.from)) || Buffer.compare(Buffer.from(a.to),Buffer.from(b.to)));
|
||||
var bridge = {source:data.source, nodes:[...data.nodes].sort((a,b)=>Buffer.compare(Buffer.from(a),Buffer.from(b))), edges};
|
||||
bridge;
|
||||
@@ -1,8 +0,0 @@
|
||||
minimum = {}
|
||||
for edge in data['edges']:
|
||||
if edge['weight'] >= 0:
|
||||
key = (edge['from'], edge['to'])
|
||||
minimum[key] = min(minimum.get(key, edge['weight']), edge['weight'])
|
||||
bridge = {'source': data['source'], 'nodes': sorted(data['nodes'], key=lambda n:n.encode('utf-8')),
|
||||
'edges': [{'from': a, 'to': b, 'weight': w} for (a,b), w in sorted(minimum.items(), key=lambda kv: (kv[0][0].encode('utf-8'), kv[0][1].encode('utf-8')))]}
|
||||
bridge
|
||||
@@ -1,9 +0,0 @@
|
||||
var groups = new Map();
|
||||
for (var row of bridge) {
|
||||
var g=groups.get(row.quality) || {quality:row.quality,count:0,sum_density_ppm:0,min_ph_cent:row.ph_cent,max_ph_cent:row.ph_cent};
|
||||
g.count++;g.sum_density_ppm+=row.density_ppm;
|
||||
g.min_ph_cent=Math.min(g.min_ph_cent,row.ph_cent);g.max_ph_cent=Math.max(g.max_ph_cent,row.ph_cent);
|
||||
groups.set(row.quality,g);
|
||||
}
|
||||
var answer=[...groups.values()].sort((a,b)=>a.quality-b.quality);
|
||||
answer;
|
||||
@@ -1,7 +0,0 @@
|
||||
from itertools import groupby
|
||||
answer = []
|
||||
for quality, group in groupby(sorted(bridge,key=lambda r:r['quality']),key=lambda r:r['quality']):
|
||||
rows = list(group)
|
||||
answer.append({'quality':quality,'count':len(rows),'sum_density_ppm':sum(r['density_ppm'] for r in rows),
|
||||
'min_ph_cent':min(r['ph_cent'] for r in rows),'max_ph_cent':max(r['ph_cent'] for r in rows)})
|
||||
answer
|
||||
@@ -1,13 +0,0 @@
|
||||
function scaledDecimal(s, digits) {
|
||||
var parts = s.split('.');
|
||||
var tail = parts.length > 1 ? parts[1] : '';
|
||||
if (tail.length > digits) throw Error('unsupported decimal precision');
|
||||
return Number(parts[0])*10**digits + Number(tail.padEnd(digits,'0'));
|
||||
}
|
||||
var lines = data.trim().split(/\r?\n/);
|
||||
var header = lines[0].split(';').map(s=>s.replaceAll('"',''));
|
||||
var bridge = lines.slice(1).map(line=>{
|
||||
var fields=line.split(';');
|
||||
return {quality:Number(fields[header.indexOf('quality')]),density_ppm:scaledDecimal(fields[header.indexOf('density')],6),ph_cent:scaledDecimal(fields[header.indexOf('pH')],2)};
|
||||
});
|
||||
bridge;
|
||||
@@ -1,5 +0,0 @@
|
||||
import csv, io
|
||||
from decimal import Decimal
|
||||
bridge = [{'quality':int(row['quality']), 'density_ppm':int(Decimal(row['density'])*1000000), 'ph_cent':int(Decimal(row['pH'])*100)}
|
||||
for row in csv.DictReader(io.StringIO(data),delimiter=';')]
|
||||
bridge
|
||||
@@ -1,117 +0,0 @@
|
||||
<!--
|
||||
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 nested `import:` / `导入:` map | Import file (`bind: path.mq.md`) or short name (`bind: lib.member`) |
|
||||
| `> 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 nested YAML `import:` (`导入` 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
|
||||
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`/`非`.
|
||||
@@ -1,36 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,42 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,30 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,28 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,28 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,37 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,585 +0,0 @@
|
||||
//! 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)
|
||||
}
|
||||
@@ -1,416 +0,0 @@
|
||||
// Real-browser validation; development orchestration is skills/marqdo-dev/browser.mq.md.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { createServer } from "node:net";
|
||||
import { once } from "node:events";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { chromium } from "../.marqdo/browser-tests/node_modules/playwright/index.mjs";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
async function freePort() {
|
||||
const listener = createServer();
|
||||
listener.listen(0, "127.0.0.1");
|
||||
await once(listener, "listening");
|
||||
const port = listener.address().port;
|
||||
await new Promise(resolve => listener.close(resolve));
|
||||
return port;
|
||||
}
|
||||
async function serve(project, t, options = {}) {
|
||||
const port = await freePort();
|
||||
const child = spawn(root + "target/debug/marqdo", [
|
||||
"call", project + "/index.mq.md", "serve", "--args-json", "-",
|
||||
"--effects", options.effects || "plugin,fs.read,network.write", "--fs-root", project, "--json"
|
||||
], {
|
||||
cwd: root,
|
||||
env: {
|
||||
...process.env,
|
||||
MARQDO_EXT: root + "ext",
|
||||
MARQDO_LIB: root + "lib",
|
||||
MARQDO_WEB_PLUGIN: root + "plugins/web/build/libweb.so"
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"]
|
||||
});
|
||||
child.stdin.end(JSON.stringify({...options.args, port}));
|
||||
let logs = "";
|
||||
child.stdout.on("data", data => { logs = (logs + data).slice(-65536); });
|
||||
child.stderr.on("data", data => { logs = (logs + data).slice(-65536); });
|
||||
t.after(async () => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
child.kill("SIGTERM");
|
||||
await Promise.race([once(child, "exit"), pause(1000)]);
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
child.kill("SIGKILL");
|
||||
await once(child, "exit");
|
||||
}
|
||||
}
|
||||
if (options.cleanup) await options.cleanup();
|
||||
});
|
||||
const url = "http://127.0.0.1:" + port;
|
||||
const deadline = Date.now() + 15000;
|
||||
while (Date.now() < deadline) {
|
||||
assert.equal(child.exitCode, null, "Marqdo call exited: " + logs);
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
if (response.ok) return { url, logs: () => logs };
|
||||
} catch (_) {}
|
||||
await pause(40);
|
||||
}
|
||||
assert.fail("Marqdo call did not listen: " + logs);
|
||||
}
|
||||
async function openBrowser(t) {
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
t.after(() => browser.close());
|
||||
return browser;
|
||||
}
|
||||
async function waitText(page, selector, text) {
|
||||
await page.waitForFunction(({selector,text}) => document.querySelector(selector)?.textContent === text, {selector,text});
|
||||
}
|
||||
async function waitValue(page, selector, value) {
|
||||
await page.waitForFunction(({selector,value}) => document.querySelector(selector)?.value === value, {selector,value});
|
||||
}
|
||||
test("SPA uses current WASM for list/detail/edit and browser history", {timeout: 60000}, async t => {
|
||||
const server = await serve("examples/web-spa-app", t);
|
||||
const browser = await openBrowser(t);
|
||||
const page = await browser.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(String(error)));
|
||||
try {
|
||||
await page.goto(server.url);
|
||||
await page.waitForSelector('#items li[data-id="1"]');
|
||||
assert.equal(await page.locator("#items li").count(), 2);
|
||||
await page.locator('#items li[data-id="1"]').click();
|
||||
await waitText(page, "#title", "Detail");
|
||||
await waitText(page, "#detail-body", "Alpha");
|
||||
await page.locator("#btn-edit").click();
|
||||
await waitValue(page, "#edit-title", "Alpha");
|
||||
const title = 'A <tag> "quoted" & literal';
|
||||
await page.locator("#edit-title").fill(title);
|
||||
await page.locator("#btn-save").click();
|
||||
await waitText(page, "#detail-body", title);
|
||||
assert.equal(await page.locator('#items li[data-id="1"]').textContent(), title);
|
||||
assert.equal(await page.locator("#items tag, #items script").count(), 0);
|
||||
await page.locator("#nav-new").click();
|
||||
await page.locator("#edit-title").fill("Gamma");
|
||||
await page.locator("#btn-save").click();
|
||||
await page.waitForSelector('#items li[data-id="3"]', {state:"attached"});
|
||||
assert.equal(await page.locator("#items li").count(), 3);
|
||||
await page.goBack();
|
||||
await page.waitForFunction(() => location.pathname === "/edit" && !document.querySelector("#view-edit").hidden);
|
||||
await page.goBack();
|
||||
await page.waitForFunction(() => location.pathname === "/item" && !document.querySelector("#view-detail").hidden);
|
||||
await page.setViewportSize({width:380, height:780});
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.goto(server.url + "/item");
|
||||
await page.waitForSelector('#items li[data-id="1"]');
|
||||
assert.equal(new URL(page.url()).pathname, "/");
|
||||
} catch (error) {
|
||||
error.message += "\nBrowser: " + errors.join("\n") + "\nPage: " + await page.locator("body").innerText() + "\nServer: " + server.logs();
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
test("two real browser tabs exchange text, empty snapshots and presence", {timeout:60000}, async t => {
|
||||
const server = await serve("examples/web-collab-doc", t);
|
||||
const browser = await openBrowser(t);
|
||||
const first = await browser.newPage();
|
||||
const second = await browser.newPage();
|
||||
const errors = [];
|
||||
for (const page of [first,second]) page.on("pageerror", error => errors.push(String(error)));
|
||||
try {
|
||||
await first.goto(server.url);
|
||||
await first.waitForFunction(() => document.querySelector("#log")?.textContent.includes("ws open"));
|
||||
await second.goto(server.url);
|
||||
await second.waitForFunction(() => document.querySelector("#log")?.textContent.includes("ws open"));
|
||||
await first.waitForFunction(() => document.querySelector("#presence")?.textContent.includes('"type":"presence"'));
|
||||
const text = 'First <tag> "text" & 中文';
|
||||
await first.locator("#doc").fill(text);
|
||||
await waitValue(second, "#doc", text);
|
||||
await second.locator("#doc").fill("the next local edit after a remote update");
|
||||
await waitValue(first, "#doc", "the next local edit after a remote update");
|
||||
await second.locator("#doc").fill("");
|
||||
await waitValue(first, "#doc", "");
|
||||
await first.setViewportSize({width:380,height:780});
|
||||
const viewport = await first.evaluate(() => ({
|
||||
width: innerWidth, scroll: document.documentElement.scrollWidth,
|
||||
overflowing: [...document.querySelectorAll("body *")].filter(el => el.getBoundingClientRect().right > innerWidth + 1).map(el => ({
|
||||
tag:el.tagName, id:el.id, width:el.getBoundingClientRect().width, text:el.textContent.slice(0,120)
|
||||
}))
|
||||
}));
|
||||
assert.equal(viewport.scroll <= viewport.width, true, JSON.stringify(viewport));
|
||||
assert.deepEqual(errors, []);
|
||||
} catch (error) {
|
||||
error.message += "\nBrowser: " + errors.join("\n") + "\nPage: " + await first.locator("body").innerText() + "\nServer: " + server.logs();
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
async function nativeFileTask(functionName, args, effects, project) {
|
||||
const child = spawn(root + "target/debug/marqdo", [
|
||||
"call", "lib/fs.mq.md", functionName, "--args-json", "-", "--effects", effects,
|
||||
"--fs-root", project, "--require-ok", "--json"
|
||||
], {cwd: root, stdio:["pipe","pipe","pipe"]});
|
||||
let stdout="", stderr="";
|
||||
child.stdout.on("data", chunk => { stdout += chunk; });
|
||||
child.stderr.on("data", chunk => { stderr += chunk; });
|
||||
child.stdin.end(JSON.stringify(args));
|
||||
const [code] = await once(child,"exit");
|
||||
assert.equal(code,0,"native file task failed: "+stdout+" "+stderr);
|
||||
const envelope=JSON.parse(stdout);
|
||||
assert.equal(envelope.ok,true);
|
||||
return envelope.result;
|
||||
}
|
||||
for (const [site, requiredCopy] of [["web-net-site", "Title is required"], ["web-net-site-zh", "标题不能为空"]]) {
|
||||
test(site+" keeps native echo, current data, form retry and authenticated administration", {timeout:60000}, async t => {
|
||||
const project="examples/"+site;
|
||||
const owned=await nativeFileTask("temp_dir",{prefix:".browser-network"},"fs.write",project);
|
||||
const filename=await nativeFileTask("resolve",{path:owned+"/site.db"},"fs.read",project);
|
||||
const server=await serve(project,t,{
|
||||
args:{url:"sqlite:"+filename},
|
||||
effects:"plugin,fs.write,network.write",
|
||||
cleanup:()=>nativeFileTask("remove_tree",{path:owned},"fs.write",project)
|
||||
});
|
||||
const browser=await openBrowser(t);
|
||||
const page=await browser.newPage();
|
||||
const errors=[];
|
||||
page.on("pageerror",error=>errors.push(String(error)));
|
||||
try {
|
||||
await page.goto(server.url);
|
||||
await waitText(page,"#live-status","connected");
|
||||
const echoed='echo <tag> "quoted" & literal';
|
||||
await page.locator("#live-msg").fill(echoed);
|
||||
await page.locator("#live-send").click();
|
||||
await waitText(page,"#live-out","echo: "+echoed+"\n");
|
||||
await page.locator("#live-msg").fill(" again ");
|
||||
await page.locator("#live-msg").press("Enter");
|
||||
await waitText(page,"#live-out","echo: "+echoed+"\necho: again\n");
|
||||
await page.locator("#live-msg").fill(" ");
|
||||
await page.locator("#live-msg").press("Enter");
|
||||
await page.waitForTimeout(120);
|
||||
assert.equal(await page.locator("#live-out").textContent(),"echo: "+echoed+"\necho: again\n");
|
||||
assert.equal(await page.locator("#live-out tag").count(),0);
|
||||
await page.goto(server.url+"/tools");
|
||||
const tools=await page.locator("body").innerText();
|
||||
assert.ok(tools.includes("http_only") && tools.includes("pic.png") && tools.includes("image/png"));
|
||||
await page.goto(server.url+"/new");
|
||||
await page.locator('form[action="/_form/article"]').evaluate(form=>{form.noValidate=true;});
|
||||
await page.locator('form[action="/_form/article"] button[type="submit"]').click();
|
||||
await page.waitForFunction(copy=>document.body.textContent.includes(copy),requiredCopy);
|
||||
assert.ok(await page.locator('input[name="_csrf"]').inputValue());
|
||||
const title='Browser article <strong>literal</strong>';
|
||||
await page.locator('input[name="title"]').fill(title);
|
||||
await page.locator('textarea[name="body"]').fill("Actual submitted body");
|
||||
await page.locator('form[action="/_form/article"] button[type="submit"]').click();
|
||||
await page.waitForFunction(title=>document.body.textContent.includes(title),title);
|
||||
assert.equal(await page.locator(".cards h2 strong").count(),0);
|
||||
await page.goto(server.url+"/admin");
|
||||
await page.locator('input[name="username"]').fill("admin");
|
||||
await page.locator('input[name="password"]').fill("secret");
|
||||
await page.locator('form[action="/admin/login"] button[type="submit"]').click();
|
||||
await page.waitForFunction(()=>document.querySelector("h1")?.textContent==="Admin");
|
||||
assert.ok((await page.locator("body").innerText()).includes(title));
|
||||
await page.goto(server.url);
|
||||
await waitText(page,"#live-status","connected");
|
||||
await page.setViewportSize({width:380,height:780});
|
||||
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
assert.deepEqual(errors,[]);
|
||||
} catch(error) {
|
||||
error.message += "\nBrowser: "+errors.join("\n")+"\nPage: "+await page.locator("body").innerText()+"\nServer: "+server.logs();
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
for (const [site, requiredCopy] of [["web-site", "Title is required"], ["web-site-zh", "标题不能为空"]]) {
|
||||
test(site+" preserves the literary theme, slug detail, session navigation and gated desk", {timeout:60000}, async t => {
|
||||
const project="examples/"+site;
|
||||
const owned=await nativeFileTask("temp_dir",{prefix:".browser-literary"},"fs.write",project);
|
||||
const filename=await nativeFileTask("resolve",{path:owned+"/site.db"},"fs.read",project);
|
||||
const server=await serve(project,t,{
|
||||
args:{url:"sqlite:"+filename},effects:"plugin,fs.write,network.write",
|
||||
cleanup:()=>nativeFileTask("remove_tree",{path:owned},"fs.write",project)
|
||||
});
|
||||
const browser=await openBrowser(t),page=await browser.newPage(),errors=[];
|
||||
page.on("pageerror",error=>errors.push(String(error)));
|
||||
// Resource declarations remain real, but this local acceptance uses font
|
||||
// fallbacks and makes no claim about external font-service availability.
|
||||
await page.route("https://fonts.googleapis.com/**",route=>route.abort());
|
||||
await page.route("https://fonts.gstatic.com/**",route=>route.abort());
|
||||
try {
|
||||
await page.goto(server.url);
|
||||
assert.equal(await page.locator(".cards article.card").count(),8);
|
||||
assert.equal(await page.locator('head meta[property="og:type"]').getAttribute("content"),"website");
|
||||
assert.equal(await page.locator('head link[rel="stylesheet"][href*="fonts.googleapis.com"]').count(),1);
|
||||
assert.equal(await page.locator('header.topnav a[href="/login"]').count(),1);
|
||||
assert.equal(await page.locator('header.topnav a[href="/admin"]').count(),0);
|
||||
const wide=await page.evaluate(()=>{
|
||||
const css=selector=>getComputedStyle(document.querySelector(selector));
|
||||
return {
|
||||
ink:css("body").backgroundColor,gold:css(".topnav a").color,
|
||||
display:css(".site-layout").display,columns:css(".site-layout").gridTemplateColumns,
|
||||
titleFont:css(".main-intro h1").fontFamily,titleSize:parseFloat(css(".main-intro h1").fontSize),
|
||||
nav:document.querySelector(".topnav").getBoundingClientRect().top,
|
||||
side:document.querySelector("aside.side").getBoundingClientRect().left,
|
||||
main:document.querySelector("section.main").getBoundingClientRect().left,
|
||||
claims:css(".main-intro ul").display,stepPanel:css(".main-intro ol").borderLeftWidth
|
||||
};
|
||||
});
|
||||
assert.equal(wide.ink,"rgb(10, 8, 9)");
|
||||
assert.equal(wide.gold,"rgb(212, 175, 55)");
|
||||
assert.equal(wide.display,"grid");
|
||||
assert.ok(wide.main>wide.side+150,JSON.stringify(wide));
|
||||
assert.ok(wide.titleFont.includes("Great Vibes") && wide.titleSize>=48,JSON.stringify(wide));
|
||||
assert.equal(wide.claims,"flex");
|
||||
assert.equal(wide.stepPanel,"2px");
|
||||
await page.locator(".cards a.card-link").first().click();
|
||||
assert.ok(new URL(page.url()).pathname.startsWith("/post/"));
|
||||
assert.equal(await page.locator(".article .article-body.md").count(),1);
|
||||
const created='Published <strong>literal</strong>';
|
||||
const summary="A short current summary",body="## Actual full Markdown body\n\nDistinct from summary.";
|
||||
await page.goto(server.url+"/new");
|
||||
await page.locator('form[action="/_form/article"]').evaluate(form=>{form.noValidate=true;});
|
||||
await page.locator('form[action="/_form/article"] button[type="submit"]').click();
|
||||
await page.waitForFunction(copy=>document.body.textContent.includes(copy),requiredCopy);
|
||||
assert.ok(await page.locator('input[name="_csrf"]').inputValue());
|
||||
await page.locator('input[name="title"]').fill(created);
|
||||
await page.locator('input[name="slug"]').fill("after-startup");
|
||||
await page.locator('textarea[name="summary"]').fill(summary);
|
||||
await page.locator('textarea[name="body"]').fill(body);
|
||||
await page.locator('form[action="/_form/article"] button[type="submit"]').click();
|
||||
await page.waitForFunction(()=>document.querySelectorAll(".cards article.card").length===9);
|
||||
assert.equal(await page.locator(".cards h2 strong").count(),0);
|
||||
assert.ok((await page.locator(".cards").innerText()).includes(summary));
|
||||
assert.ok(!(await page.locator(".cards").innerText()).includes("Actual full Markdown body"));
|
||||
await page.goto(server.url+"/post/after-startup?slug=other");
|
||||
assert.equal(await page.locator(".article-body h2").textContent(),"Actual full Markdown body");
|
||||
assert.ok(!(await page.locator(".article").innerText()).includes(summary));
|
||||
await page.goto(server.url+"/admin");
|
||||
assert.equal(new URL(page.url()).pathname,"/login");
|
||||
await page.locator('input[name="username"]').fill("admin");
|
||||
await page.locator('input[name="password"]').fill("demo");
|
||||
await page.locator('form[action="/login"] button[type="submit"]').click();
|
||||
await page.waitForURL(server.url+"/admin");
|
||||
assert.equal(await page.locator("aside.side").count(),0);
|
||||
assert.equal(await page.locator(".is-desk").count(),1);
|
||||
assert.equal(await page.locator(".cards article.card").count(),9);
|
||||
assert.equal(await page.locator('form[action="/_form/article"]').count(),1);
|
||||
await page.goto(server.url);
|
||||
assert.equal(await page.locator('header.topnav a[href="/login"]').count(),0);
|
||||
assert.equal(await page.locator('header.topnav a[href="/admin"]').count(),1);
|
||||
await page.setViewportSize({width:380,height:780});
|
||||
const narrow=await page.evaluate(()=>({
|
||||
width:innerWidth,scroll:document.documentElement.scrollWidth,
|
||||
side:document.querySelector("aside.side").getBoundingClientRect().top,
|
||||
main:document.querySelector("section.main").getBoundingClientRect().top,
|
||||
columns:getComputedStyle(document.querySelector(".site-layout")).gridTemplateColumns
|
||||
}));
|
||||
assert.ok(narrow.scroll<=narrow.width && narrow.side>narrow.main,JSON.stringify(narrow));
|
||||
await page.goto(server.url+"/admin/logout");
|
||||
assert.equal(await page.locator('header.topnav a[href="/login"]').count(),1);
|
||||
await page.goto(server.url+"/admin");
|
||||
assert.equal(new URL(page.url()).pathname,"/login");
|
||||
assert.deepEqual(errors,[]);
|
||||
} catch(error) {
|
||||
error.message+="\nBrowser: "+errors.join("\n")+"\nPage: "+await page.locator("body").innerText()+"\nServer: "+server.logs();
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("browser effects preserve literal duplicate rows, history, storage and local transports", {timeout:60000}, async t => {
|
||||
const server = await serve("examples/browser-app", t, {effects:"plugin,fs.write,network.write"});
|
||||
const browser = await openBrowser(t);
|
||||
const context = await browser.newContext({permissions:["clipboard-read", "clipboard-write"],acceptDownloads:true});
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(String(error)));
|
||||
let requests = 0;
|
||||
await page.route("https://httpbin.org/uuid", route => {
|
||||
requests++;
|
||||
return route.fulfill({status:requests === 1 ? 200 : 503,body:requests === 1 ? "controlled-success" : "controlled-failure",headers:{"access-control-allow-origin":"*"}});
|
||||
});
|
||||
try {
|
||||
await page.goto(server.url);
|
||||
await page.waitForFunction(() => !document.querySelector("#draft")?.disabled);
|
||||
const literal = 'A <tag> "quoted" & literal';
|
||||
for (let i=0;i<2;i++) {
|
||||
await page.locator("#draft").fill(literal);
|
||||
await page.locator("#add").click();
|
||||
await page.waitForFunction(n => document.querySelectorAll("#items li").length === n, i+1);
|
||||
}
|
||||
assert.deepEqual(await page.locator("#items li span").allTextContents(), [literal,literal]);
|
||||
assert.equal(await page.locator("#items tag, #items script").count(), 0);
|
||||
await page.locator('#items button[data-id="1"]').click();
|
||||
assert.equal(await page.locator("#items li").count(), 1);
|
||||
assert.equal(await page.locator("#items li span").textContent(), literal);
|
||||
await page.locator("#draft").fill("third");
|
||||
await page.locator("#add").click();
|
||||
await page.waitForSelector('#items button[data-id="3"]');
|
||||
assert.equal(await page.locator("#items li").count(), 2);
|
||||
await page.locator("#copy-log").click();
|
||||
await page.waitForFunction(expected => navigator.clipboard.readText().then(actual=>actual===expected), literal+"\nthird");
|
||||
const downloadEvent = page.waitForEvent("download");
|
||||
await page.locator("#dl-list").click();
|
||||
const download = await downloadEvent;
|
||||
assert.equal(download.suggestedFilename(),"items.txt");
|
||||
const stream = await download.createReadStream();
|
||||
const chunks = [];
|
||||
for await (const chunk of stream) chunks.push(chunk);
|
||||
assert.equal(Buffer.concat(chunks).toString(),literal+"\nthird");
|
||||
await page.locator("#start-tick").click();
|
||||
await waitText(page,"#tick","1");
|
||||
await page.locator("#stop-tick").click();
|
||||
await page.waitForTimeout(1200);
|
||||
await waitText(page,"#tick","1");
|
||||
await page.locator("#draft").fill('saved <draft> "text"');
|
||||
await page.locator("#save").click();
|
||||
await waitText(page,"#log","draft saved");
|
||||
assert.equal(await page.evaluate(()=>localStorage.getItem("mq-draft")),'saved <draft> "text"');
|
||||
await page.locator("#draft").fill("changed");
|
||||
await page.locator("#load").click();
|
||||
await waitValue(page,"#draft",'saved <draft> "text"');
|
||||
const initialHistory = await page.evaluate(()=>history.length);
|
||||
await page.locator("#nav-about").click();
|
||||
await page.waitForFunction(()=>location.pathname==="/about" && !document.querySelector("#panel-about").hidden);
|
||||
await page.locator("#nav-net").click();
|
||||
await page.waitForFunction(()=>location.pathname==="/net" && !document.querySelector("#panel-net").hidden);
|
||||
assert.equal(await page.evaluate(()=>history.length),initialHistory+2);
|
||||
await page.goBack();
|
||||
await page.waitForFunction(()=>location.pathname==="/about" && !document.querySelector("#panel-about").hidden);
|
||||
await page.goBack();
|
||||
await page.waitForFunction(()=>location.pathname==="/" && !document.querySelector("#panel-home").hidden);
|
||||
await page.goForward();
|
||||
await page.goForward();
|
||||
await page.waitForFunction(()=>location.pathname==="/net" && !document.querySelector("#panel-net").hidden);
|
||||
assert.equal(await page.evaluate(()=>history.length),initialHistory+2);
|
||||
await page.locator("#fetch-all").click();
|
||||
await page.waitForFunction(()=> {
|
||||
const text=document.querySelector("#net-out").textContent;
|
||||
return text.includes("controlled-success") && text.includes("503") && text.includes("controlled-failure");
|
||||
});
|
||||
await page.locator("#ws-open").click();
|
||||
await waitText(page,"#net-out","ws open");
|
||||
const message='local <echo> "message"';
|
||||
await page.locator("#ws-msg").fill(message);
|
||||
await page.locator("#ws-send").click();
|
||||
await waitText(page,"#net-out","ws ← "+message);
|
||||
await page.locator("#ws-close").click();
|
||||
await waitText(page,"#net-out","ws closed");
|
||||
const styles = await page.evaluate(()=>({body:getComputedStyle(document.body).color,button:getComputedStyle(document.querySelector("#fetch-all")).backgroundColor}));
|
||||
assert.equal(styles.body,"rgb(26, 31, 28)");
|
||||
assert.equal(styles.button,"rgb(47, 111, 78)");
|
||||
await page.setViewportSize({width:380,height:780});
|
||||
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
await page.goto(server.url+"/about");
|
||||
await page.waitForFunction(()=>!document.querySelector("#draft")?.disabled);
|
||||
assert.equal(new URL(page.url()).pathname,"/");
|
||||
await waitValue(page,"#draft",'saved <draft> "text"');
|
||||
assert.equal(await page.locator("#items li").count(),0);
|
||||
assert.deepEqual(errors,[]);
|
||||
} catch(error) {
|
||||
error.message+="\nBrowser: "+errors.join("\n")+"\nPage: "+await page.locator("body").innerText()+"\nServer: "+server.logs();
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
# 甲
|
||||
|
||||
## 加法
|
||||
|
||||
*[计算结果](1)*
|
||||
|
||||
# 乙
|
||||
|
||||
## 加法
|
||||
|
||||
*[计算结果](2)*
|
||||
@@ -1,11 +0,0 @@
|
||||
# 校验
|
||||
|
||||
## 加一
|
||||
|
||||
对于输入变量`n`,期望是数字。
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| n | 数值 | 输入值 |
|
||||
|
||||
*[结果](n + 1)*
|
||||
@@ -1,13 +0,0 @@
|
||||
# 危险
|
||||
|
||||
## 写入
|
||||
|
||||
> fs.write_text path=sent.txt text=no
|
||||
|
||||
*None*
|
||||
|
||||
## 联网
|
||||
|
||||
> net.http_post url="http://127.0.0.1:9/nope" body="{}"
|
||||
|
||||
*None*
|
||||
@@ -1,5 +0,0 @@
|
||||
## 加一
|
||||
|
||||
给定`n`。
|
||||
|
||||
*[结果](n + 1)*
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
import:
|
||||
inc: inc.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*0*
|
||||
|
||||
# 包装
|
||||
|
||||
## 再加一
|
||||
|
||||
给定`n`。
|
||||
|
||||
**结果 = [调用增量](inc.加一(n=n))**
|
||||
*结果*
|
||||
@@ -1,11 +0,0 @@
|
||||
# main
|
||||
|
||||
*0*
|
||||
|
||||
# 计算器
|
||||
|
||||
## 加法
|
||||
|
||||
计算两个数字`a`和`b`的和。
|
||||
|
||||
*[计算结果](a + b)*
|
||||
@@ -1,14 +0,0 @@
|
||||
---
|
||||
runtime: markdown
|
||||
tools: 计算器.加法
|
||||
---
|
||||
|
||||
# 计算器
|
||||
|
||||
这份文件不是 SKILL。`runtime` 和 `tools` 不参与调用。
|
||||
|
||||
## 加法
|
||||
|
||||
计算两个数字`a`和`b`的和。
|
||||
|
||||
*[计算结果](a + b)*
|
||||
@@ -1,7 +0,0 @@
|
||||
# 点
|
||||
|
||||
## 横坐标
|
||||
|
||||
读取`self`。
|
||||
|
||||
*[结果](self)*
|
||||
@@ -1,41 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: nested ### sub-tool call
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*None*
|
||||
|
||||
## outer
|
||||
|
||||
Parent tool. Agents may call this path or the finer nested helper.
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| n | number | seed value |
|
||||
|
||||
This paragraph is narration so the unit stays readable. The nested
|
||||
`### helper` is the sub-tool that does the arithmetic. Call path
|
||||
`outer.helper` selects the child without running the parent body.
|
||||
|
||||
### helper
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| n | number | value to double |
|
||||
|
||||
Sub-tool under `outer`. Doubles `n` without side effects so default
|
||||
`marqdo call` may run it. Prefer this when only the doubling step is needed.
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| | number | two times n |
|
||||
|
||||
*[result](n * 2)*
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| | number | parent returns n unchanged |
|
||||
|
||||
*n*
|
||||
@@ -1,513 +0,0 @@
|
||||
//! `marqdo call` runs one function. These tests start the real binary.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
fn bin() -> &'static str {
|
||||
env!("CARGO_BIN_EXE_marqdo")
|
||||
}
|
||||
|
||||
fn root() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
}
|
||||
|
||||
fn run(args: &[&str]) -> std::process::Output {
|
||||
Command::new(bin())
|
||||
.args(args)
|
||||
.current_dir(root())
|
||||
.output()
|
||||
.expect("spawn marqdo")
|
||||
}
|
||||
|
||||
fn text(bytes: &[u8]) -> String {
|
||||
String::from_utf8_lossy(bytes).trim().to_string()
|
||||
}
|
||||
|
||||
fn assert_value(file: &Path, function: &str, args: &[&str], backend: &str, expect: &str) {
|
||||
let file = file.to_str().unwrap();
|
||||
let mut cmd = vec!["call", "--backend", backend, file, function];
|
||||
cmd.extend_from_slice(args);
|
||||
let out = run(&cmd);
|
||||
assert_eq!(
|
||||
out.status.code(),
|
||||
Some(0),
|
||||
"backend={backend} stdout={} stderr={}",
|
||||
text(&out.stdout),
|
||||
text(&out.stderr)
|
||||
);
|
||||
assert_eq!(text(&out.stdout), expect, "backend={backend}");
|
||||
}
|
||||
|
||||
fn assert_code(file: &Path, function: &str, args: &[&str], code: &str) {
|
||||
let file = file.to_str().unwrap();
|
||||
let mut cmd = vec!["call", "--json", file, function];
|
||||
cmd.extend_from_slice(args);
|
||||
let out = run(&cmd);
|
||||
assert_ne!(out.status.code(), Some(0), "stdout={}", text(&out.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap_or_else(|e| {
|
||||
panic!("json stdout: {e}\n{}", text(&out.stdout));
|
||||
});
|
||||
assert_eq!(body["ok"], false, "{body}");
|
||||
assert_eq!(body["error"]["code"], code, "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculator_matches_the_documented_examples() {
|
||||
let file = root().join("examples/calculator.mq.md");
|
||||
for backend in ["tree", "bytecode"] {
|
||||
assert_value(&file, "计算器.加法", &["a=2", "b=3"], backend, "5");
|
||||
assert_value(&file, "计算器.加法", &["a=-2", "b=3"], backend, "1");
|
||||
assert_value(&file, "计算器.乘法", &["a=4", "b=6"], backend, "24");
|
||||
assert_value(&file, "计算器.乘法", &["a=0", "b=100"], backend, "0");
|
||||
assert_value(&file, "加法", &["a=2", "b=3"], backend, "5");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_id_selects_the_same_function_on_both_backends() {
|
||||
let file = root().join("examples/calculator.mq.md");
|
||||
let compiled = marqdo::sema::compile_file_closure(&file).expect("compile calculator");
|
||||
let artifact = compiled
|
||||
.semantics
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|artifact| artifact.display_name == "计算器.加法")
|
||||
.expect("加法 artifact");
|
||||
let id = artifact
|
||||
.symbol_id
|
||||
.as_ref()
|
||||
.expect("symbol id")
|
||||
.as_str()
|
||||
.to_string();
|
||||
let args = vec![
|
||||
("a".to_string(), marqdo::value::Value::Int(2)),
|
||||
("b".to_string(), marqdo::value::Value::Int(3)),
|
||||
];
|
||||
for backend in [marqdo::Backend::Tree, marqdo::Backend::Bytecode] {
|
||||
let value = marqdo::call::call_file(&file, &id, &args, backend).unwrap_or_else(|err| {
|
||||
panic!("symbol id call failed on {backend:?}: {err:#}")
|
||||
});
|
||||
assert_eq!(value, marqdo::value::Value::Int(5));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_envelope_and_metadata_are_not_a_skill_gate() {
|
||||
let file = root().join("tests/call/metadata.mq.md");
|
||||
let out = run(&[
|
||||
"call",
|
||||
"--json",
|
||||
file.to_str().unwrap(),
|
||||
"计算器.加法",
|
||||
"a=2",
|
||||
"b=3",
|
||||
]);
|
||||
assert_eq!(out.status.code(), Some(0), "{}", text(&out.stderr));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
|
||||
assert_eq!(body, serde_json::json!({"ok": true, "result": 5}));
|
||||
|
||||
let trailing = run(&[
|
||||
"call",
|
||||
file.to_str().unwrap(),
|
||||
"计算器.加法",
|
||||
"a=2",
|
||||
"b=3",
|
||||
"--backend",
|
||||
"bytecode",
|
||||
"--json",
|
||||
]);
|
||||
assert_eq!(trailing.status.code(), Some(0), "{}", text(&trailing.stderr));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&trailing.stdout)).unwrap();
|
||||
assert_eq!(body, serde_json::json!({"ok": true, "result": 5}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytecode_does_not_run_main() {
|
||||
let file = root().join("tests/call/main-split.mq.md");
|
||||
for backend in ["tree", "bytecode"] {
|
||||
assert_value(&file, "计算器.加法", &["a=2", "b=3"], backend, "5");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_unknown_and_contract_args_are_structured() {
|
||||
let calc = root().join("examples/calculator.mq.md");
|
||||
assert_code(&calc, "没有这个函数", &[], "artifact.unresolved");
|
||||
assert_code(&calc, "计算器.加法", &["a=2"], "call.missing_arg");
|
||||
assert_code(
|
||||
&calc,
|
||||
"计算器.加法",
|
||||
&["a=2", "b=3", "c=1"],
|
||||
"call.unknown_arg",
|
||||
);
|
||||
let contract = root().join("tests/call/contract.mq.md");
|
||||
assert_code(&contract, "校验.加一", &["n=True"], "contract.arg_mismatch");
|
||||
assert_value(&contract, "校验.加一", &["n=3"], "tree", "4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_short_name_is_ambiguous() {
|
||||
let file = root().join("tests/call/ambiguous.mq.md");
|
||||
assert_code(&file, "加法", &[], "artifact.ambiguous");
|
||||
assert_value(&file, "甲.加法", &[], "tree", "1");
|
||||
assert_value(&file, "乙.加法", &[], "bytecode", "2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_method_is_refused() {
|
||||
let file = root().join("tests/call/method.mq.md");
|
||||
assert_code(&file, "点.横坐标", &[], "artifact.not_executable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_is_executed_and_call_lib_path_stays_on_bytecode() {
|
||||
let site = root().join("tests/call/import/site.mq.md");
|
||||
for backend in ["tree", "bytecode"] {
|
||||
assert_value(&site, "包装.再加一", &["n=4"], backend, "5");
|
||||
}
|
||||
let tmp = std::env::temp_dir().join(format!("mq-call-lib-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&tmp);
|
||||
fs::create_dir_all(&tmp).unwrap();
|
||||
let args = tmp.join("args.json");
|
||||
let emit = tmp.join("out.json");
|
||||
fs::write(&args, r#"{"n":4}"#).unwrap();
|
||||
let out = Command::new(bin())
|
||||
.args([
|
||||
"run",
|
||||
site.to_str().unwrap(),
|
||||
"--backend",
|
||||
"bytecode",
|
||||
"--call-lib-path",
|
||||
"inc.加一",
|
||||
"--args-json",
|
||||
args.to_str().unwrap(),
|
||||
"--emit-result",
|
||||
emit.to_str().unwrap(),
|
||||
])
|
||||
.current_dir(root())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
out.status.code(),
|
||||
Some(0),
|
||||
"stderr={} stdout={}",
|
||||
text(&out.stderr),
|
||||
text(&out.stdout)
|
||||
);
|
||||
assert_eq!(fs::read_to_string(&emit).unwrap().trim(), "5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn impure_calls_do_not_run() {
|
||||
let src = root().join("tests/call/effects.mq.md");
|
||||
let dir = std::env::temp_dir().join(format!("mq-call-fx-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("effects.mq.md");
|
||||
fs::copy(&src, &file).unwrap();
|
||||
for function in ["危险.写入", "危险.联网"] {
|
||||
let out = run(&["call", "--json", file.to_str().unwrap(), function]);
|
||||
assert_ne!(out.status.code(), Some(0), "{function} {}", text(&out.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
|
||||
assert_eq!(body["error"]["code"], "artifact.effect_denied", "{body}");
|
||||
}
|
||||
assert!(
|
||||
!dir.join("sent.txt").exists(),
|
||||
"denied write must not create sent.txt"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_subtool_path_resolves() {
|
||||
let file = root().join("tests/call/nested.mq.md");
|
||||
for backend in ["tree", "bytecode"] {
|
||||
assert_value(&file, "outer.helper", &["n=3"], backend, "6");
|
||||
assert_value(&file, "helper", &["n=4"], backend, "8");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_effects_flag_allows_quantum_ensure() {
|
||||
let file = root().join("ext/quantum/_capability/index.mq.md");
|
||||
let out = run(&[
|
||||
"call",
|
||||
"--effects",
|
||||
"plugin",
|
||||
"--json",
|
||||
file.to_str().unwrap(),
|
||||
"load",
|
||||
]);
|
||||
assert_eq!(out.status.code(), Some(0), "{}", text(&out.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
|
||||
assert_eq!(body["ok"], true, "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_layout_rules_via_call() {
|
||||
let file = root().join("ext/web/layout/index.mq.md");
|
||||
let out = run(&["call", "--json", file.to_str().unwrap(), "rules"]);
|
||||
assert_eq!(out.status.code(), Some(0), "{}", text(&out.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
|
||||
assert_eq!(body["ok"], true, "{body}");
|
||||
let keys = body["result"]["key"].as_array().expect("key list");
|
||||
assert!(
|
||||
keys.iter().any(|k| k.as_str() == Some("paradigm")),
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_index_site_playbook_via_call() {
|
||||
let file = root().join("ext/web/index.mq.md");
|
||||
let out = run(&["call", "--json", file.to_str().unwrap(), "site_playbook"]);
|
||||
assert_eq!(out.status.code(), Some(0), "{}", text(&out.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
|
||||
assert_eq!(body["ok"], true, "{body}");
|
||||
let keys = body["result"]["key"].as_array().expect("key list");
|
||||
assert!(
|
||||
keys.iter().any(|k| k.as_str() == Some("step_F")),
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_zh_layout_rules_via_call() {
|
||||
let file = root().join("ext/web/网页/索引.mq.md");
|
||||
let out = run(&["call", "--json", file.to_str().unwrap(), "布局规则"]);
|
||||
assert_eq!(out.status.code(), Some(0), "{}", text(&out.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
|
||||
assert_eq!(body["ok"], true, "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_component_merge_via_call() {
|
||||
let file = root().join("ext/web/component/index.mq.md");
|
||||
let a = r#"[{"type":"text","slot":"main","value":"A","attrs":"","style":""}]"#;
|
||||
let b = r#"[{"type":"text","slot":"main","value":"B","attrs":"","style":""}]"#;
|
||||
let out = run(&[
|
||||
"call",
|
||||
"--json",
|
||||
file.to_str().unwrap(),
|
||||
"merge",
|
||||
&format!("a={a}"),
|
||||
&format!("b={b}"),
|
||||
]);
|
||||
assert_eq!(out.status.code(), Some(0), "{}", text(&out.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
|
||||
assert_eq!(body["ok"], true, "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_page_new_render_session_via_call() {
|
||||
let dir = std::env::temp_dir().join(format!("mq-call-web-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let page = root().join("ext/web/page/index.mq.md");
|
||||
let sess = "web-page";
|
||||
let out_new = Command::new(bin())
|
||||
.env("MARQDO_CALL_SESSION_DIR", &dir)
|
||||
.args([
|
||||
"call",
|
||||
"--effects",
|
||||
"plugin",
|
||||
"--session",
|
||||
sess,
|
||||
"--toget",
|
||||
"pg",
|
||||
"--json",
|
||||
page.to_str().unwrap(),
|
||||
"new",
|
||||
"title=\"Demo\"",
|
||||
"body=\"# Hi\"",
|
||||
])
|
||||
.current_dir(root())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(out_new.status.code(), Some(0), "{}", text(&out_new.stdout));
|
||||
let body_new: serde_json::Value = serde_json::from_str(&text(&out_new.stdout)).unwrap();
|
||||
assert_eq!(body_new["ok"], true, "{body_new}");
|
||||
let out_render = Command::new(bin())
|
||||
.env("MARQDO_CALL_SESSION_DIR", &dir)
|
||||
.args([
|
||||
"call",
|
||||
"--effects",
|
||||
"plugin",
|
||||
"--session",
|
||||
sess,
|
||||
"--json",
|
||||
page.to_str().unwrap(),
|
||||
"render",
|
||||
"page=$pg",
|
||||
])
|
||||
.current_dir(root())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
out_render.status.code(),
|
||||
Some(0),
|
||||
"{}",
|
||||
text(&out_render.stdout)
|
||||
);
|
||||
let body_render: serde_json::Value =
|
||||
serde_json::from_str(&text(&out_render.stdout)).unwrap();
|
||||
assert_eq!(body_render["ok"], true, "{body_render}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantum_index_bell_via_call() {
|
||||
let file = root().join("ext/quantum/index.mq.md");
|
||||
let out = run(&[
|
||||
"call",
|
||||
"--effects",
|
||||
"plugin",
|
||||
"--json",
|
||||
file.to_str().unwrap(),
|
||||
"bell_phi_plus",
|
||||
]);
|
||||
assert_eq!(out.status.code(), Some(0), "{}", text(&out.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
|
||||
assert_eq!(body["ok"], true, "{body}");
|
||||
let p00 = body["result"]["00"].as_f64().unwrap();
|
||||
let p11 = body["result"]["11"].as_f64().unwrap();
|
||||
assert!((p00 - 0.5).abs() < 0.05, "{body}");
|
||||
assert!((p11 - 0.5).abs() < 0.05, "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantum_zh_index_bell_via_call() {
|
||||
let file = root().join("ext/quantum/量子/索引.mq.md");
|
||||
let out = run(&[
|
||||
"call",
|
||||
"--effects",
|
||||
"plugin",
|
||||
"--json",
|
||||
file.to_str().unwrap(),
|
||||
"贝尔态",
|
||||
]);
|
||||
assert_eq!(out.status.code(), Some(0), "{}", text(&out.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
|
||||
assert_eq!(body["ok"], true, "{body}");
|
||||
let p00 = body["result"]["00"].as_f64().unwrap();
|
||||
let p11 = body["result"]["11"].as_f64().unwrap();
|
||||
assert!((p00 - 0.5).abs() < 0.05, "{body}");
|
||||
assert!((p11 - 0.5).abs() < 0.05, "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantum_bell_stepwise_session_matches_index() {
|
||||
let dir = std::env::temp_dir().join(format!("mq-call-bell-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let circuit = root().join("ext/quantum/circuit/index.mq.md");
|
||||
let simulate = root().join("ext/quantum/simulate/index.mq.md");
|
||||
let sess = "bell-steps";
|
||||
let steps: &[(&str, &str, &[&str])] = &[
|
||||
(
|
||||
circuit.to_str().unwrap(),
|
||||
"new",
|
||||
&["qubits=2", "--toget", "qc"],
|
||||
),
|
||||
(
|
||||
circuit.to_str().unwrap(),
|
||||
"hadamard",
|
||||
&["circuit=$qc", "qubit=0", "--toget", "qc"],
|
||||
),
|
||||
(
|
||||
circuit.to_str().unwrap(),
|
||||
"cnot",
|
||||
&["circuit=$qc", "control=0", "target=1", "--toget", "qc"],
|
||||
),
|
||||
];
|
||||
for (file, function, extra) in steps {
|
||||
let mut args = vec![
|
||||
"call",
|
||||
"--effects",
|
||||
"plugin",
|
||||
"--session",
|
||||
sess,
|
||||
"--json",
|
||||
file,
|
||||
function,
|
||||
];
|
||||
args.extend_from_slice(extra);
|
||||
let out = Command::new(bin())
|
||||
.env("MARQDO_CALL_SESSION_DIR", &dir)
|
||||
.args(&args)
|
||||
.current_dir(root())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
out.status.code(),
|
||||
Some(0),
|
||||
"{function} {}",
|
||||
text(&out.stdout)
|
||||
);
|
||||
}
|
||||
let out = Command::new(bin())
|
||||
.env("MARQDO_CALL_SESSION_DIR", &dir)
|
||||
.args([
|
||||
"call",
|
||||
"--effects",
|
||||
"plugin",
|
||||
"--session",
|
||||
sess,
|
||||
"--json",
|
||||
simulate.to_str().unwrap(),
|
||||
"probabilities",
|
||||
"circuit=$qc",
|
||||
])
|
||||
.current_dir(root())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(out.status.code(), Some(0), "{}", text(&out.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
|
||||
assert_eq!(body["ok"], true, "{body}");
|
||||
let p00 = body["result"]["00"].as_f64().unwrap();
|
||||
let p11 = body["result"]["11"].as_f64().unwrap();
|
||||
assert!((p00 - 0.5).abs() < 0.05, "{body}");
|
||||
assert!((p11 - 0.5).abs() < 0.05, "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toget_persists_serializable_value() {
|
||||
let dir = std::env::temp_dir().join(format!("mq-call-sess-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let file = root().join("tests/call/nested.mq.md");
|
||||
let sess = "toget-demo";
|
||||
let out1 = Command::new(bin())
|
||||
.env("MARQDO_CALL_SESSION_DIR", &dir)
|
||||
.args([
|
||||
"call",
|
||||
"--session",
|
||||
sess,
|
||||
"--toget",
|
||||
"x",
|
||||
"--json",
|
||||
file.to_str().unwrap(),
|
||||
"helper",
|
||||
"n=5",
|
||||
])
|
||||
.current_dir(root())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(out1.status.code(), Some(0), "{}", text(&out1.stdout));
|
||||
let out2 = Command::new(bin())
|
||||
.env("MARQDO_CALL_SESSION_DIR", &dir)
|
||||
.args([
|
||||
"call",
|
||||
"--session",
|
||||
sess,
|
||||
"--json",
|
||||
file.to_str().unwrap(),
|
||||
"helper",
|
||||
"n=$x",
|
||||
])
|
||||
.current_dir(root())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(out2.status.code(), Some(0), "{}", text(&out2.stdout));
|
||||
let body: serde_json::Value = serde_json::from_str(&text(&out2.stdout)).unwrap();
|
||||
assert_eq!(body["result"], 20, "{body}");
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
//! Phase A: `marqdo run --call-lib-path` writes `--emit-result` without parent INVOKE_LOCK.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn call_lib_path_emits_json_result() {
|
||||
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let site = root.join("tests/ext/isolated-execute-site");
|
||||
let entry = site.join("serve.mq.md");
|
||||
let tmp = std::env::temp_dir().join(format!("mq-clp-{}", std::process::id()));
|
||||
let _ = std::fs::create_dir_all(&tmp);
|
||||
let args = tmp.join("args.json");
|
||||
let emit = tmp.join("out.json");
|
||||
std::fs::write(&args, r#"{"payload":null}"#).unwrap();
|
||||
|
||||
let bin = env!("CARGO_BIN_EXE_marqdo");
|
||||
let out = Command::new(bin)
|
||||
.arg("run")
|
||||
.arg(&entry)
|
||||
.arg("--call-lib-path")
|
||||
.arg("site.models") // entry is serve.mq.md which imports site
|
||||
.arg("--fs-root")
|
||||
.arg(&site)
|
||||
.arg("--args-json")
|
||||
.arg(&args)
|
||||
.arg("--emit-result")
|
||||
.arg(&emit)
|
||||
.current_dir(&site)
|
||||
.env("MARQDO_EXT", root.join("ext"))
|
||||
.output()
|
||||
.expect("spawn worker");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(
|
||||
out.status.code().unwrap_or(1),
|
||||
0,
|
||||
"stderr={stderr}\nstdout={}",
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
);
|
||||
let body = std::fs::read_to_string(&emit).expect("emit-result");
|
||||
assert!(
|
||||
body.contains("list") || body.contains("ok"),
|
||||
"emit={body}"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
}
|
||||
@@ -1,288 +0,0 @@
|
||||
//! 修复循环测试共享件:MLSP 调用、统一诊断、金修复行编辑推导、golden 20 例。
|
||||
//!
|
||||
//! 被 `tests/repair_loop.rs`(确定性护栏/golden)与 `tests/repair_experiment.rs`
|
||||
//! (模型在环实验)共用——同一批 20 例、同一套诊断与应用路径。
|
||||
#![allow(dead_code)]
|
||||
|
||||
use marqdo::diagnostics::Diagnostic;
|
||||
use marqdo::mlsp::handle_line;
|
||||
use marqdo::repair::Edit;
|
||||
use marqdo::{run_file, RunOptions};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// 调一次 MLSP(进程内)。
|
||||
pub fn mcall(req: Value) -> Value {
|
||||
serde_json::from_str(&handle_line(&req.to_string())).expect("MLSP 响应必须是合法 JSON")
|
||||
}
|
||||
|
||||
/// 验证方式:运行期契约错走 run;静态错(check / parse)走 validate。
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Verify {
|
||||
Run(&'static str),
|
||||
Static(&'static str),
|
||||
}
|
||||
|
||||
pub struct Case {
|
||||
pub name: String,
|
||||
pub broken: String,
|
||||
pub gold: String,
|
||||
pub verify: Verify,
|
||||
}
|
||||
|
||||
impl Case {
|
||||
pub fn code(&self) -> &'static str {
|
||||
match self.verify {
|
||||
Verify::Run(c) | Verify::Static(c) => c,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn static_diags(src: &str) -> Vec<Value> {
|
||||
let resp = mcall(json!({"id": 1, "method": "validate", "params": {"source": src}}));
|
||||
if resp["ok"] == false {
|
||||
return vec![resp["error"].clone()];
|
||||
}
|
||||
resp["result"]["diagnostics"]
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn temp_path(tag: &str) -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!("marqdo_repair_{}_{}.mq.md", std::process::id(), tag))
|
||||
}
|
||||
|
||||
/// 统一诊断入口:**干净 ⇒ 空数组**(Run 成功 / validate 零诊断)。
|
||||
pub fn diagnose(verify: Verify, src: &str, tag: &str) -> Vec<Value> {
|
||||
match verify {
|
||||
Verify::Run(_) => {
|
||||
let p = temp_path(tag);
|
||||
std::fs::write(&p, src).unwrap();
|
||||
match run_file(&p, &RunOptions::default()) {
|
||||
Ok(_) => vec![],
|
||||
Err(e) => vec![match Diagnostic::find(&e) {
|
||||
Some(d) => d.to_json(),
|
||||
None => json!({"code": "?", "message": format!("{e:#}")}),
|
||||
}],
|
||||
}
|
||||
}
|
||||
Verify::Static(_) => static_diags(src),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_ok(src: &str, tag: &str) {
|
||||
let p = temp_path(tag);
|
||||
std::fs::write(&p, src).unwrap();
|
||||
run_file(&p, &RunOptions::default()).expect("修复后必须运行成功");
|
||||
let _ = std::fs::remove_file(&p);
|
||||
}
|
||||
|
||||
/// 诊断 JSON → 靶点范围(span 行 + doc_anchor 的 L 范围)。
|
||||
pub fn ranges_of(v: &Value) -> Vec<(u32, u32)> {
|
||||
let mut rs = Vec::new();
|
||||
if let Some(l) = v["span"]["line"].as_u64() {
|
||||
rs.push((l as u32, l as u32));
|
||||
}
|
||||
if let Some(a) = v["doc_anchor"].as_str() {
|
||||
if let Some(rest) = a.split('#').nth(1) {
|
||||
if let Some(rest) = rest.strip_prefix('L') {
|
||||
if let Some((s, e)) = rest.split_once("-L") {
|
||||
if let (Ok(s), Ok(e)) = (s.parse(), e.parse()) {
|
||||
rs.push((s, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rs
|
||||
}
|
||||
|
||||
/// 金修复 → 行编辑(前缀/后缀 diff 自动推导)。
|
||||
pub fn derive_edits(broken: &str, gold: &str) -> Vec<Edit> {
|
||||
let b: Vec<&str> = broken.lines().collect();
|
||||
let g: Vec<&str> = gold.lines().collect();
|
||||
let mut p = 0usize;
|
||||
while p < b.len() && p < g.len() && b[p] == g[p] {
|
||||
p += 1;
|
||||
}
|
||||
let mut s = 0usize;
|
||||
while s < b.len() - p && s < g.len() - p && b[b.len() - 1 - s] == g[g.len() - 1 - s] {
|
||||
s += 1;
|
||||
}
|
||||
let mut edits = Vec::new();
|
||||
for l in (p + 1)..=(b.len() - s) {
|
||||
edits.push(Edit::Delete { line: l as u32 });
|
||||
}
|
||||
let at = (b.len() - s + 1) as u32;
|
||||
for text in &g[p..(g.len() - s)] {
|
||||
edits.push(Edit::InsertBefore {
|
||||
line: at,
|
||||
text: (*text).to_string(),
|
||||
});
|
||||
}
|
||||
edits
|
||||
}
|
||||
|
||||
/// 经 `mlsp repair_apply` 应用(护栏所在)。
|
||||
pub fn apply_via_mlsp(src: &str, ranges: &[(u32, u32)], edits: &[Edit]) -> Value {
|
||||
mcall(json!({
|
||||
"id": 2,
|
||||
"method": "repair_apply",
|
||||
"params": {
|
||||
"source": src,
|
||||
"ranges": ranges.iter().map(|(s, e)| json!([s, e])).collect::<Vec<_>>(),
|
||||
"edits": edits.iter().map(|e| match e {
|
||||
Edit::Replace { line, text } => json!({"op": "replace", "line": line, "text": text}),
|
||||
Edit::Delete { line } => json!({"op": "delete", "line": line}),
|
||||
Edit::InsertBefore { line, text } => json!({"op": "insert", "line": line, "text": text}),
|
||||
}).collect::<Vec<_>>(),
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/// golden 20 例(10 骨架 × 2 变体)。
|
||||
pub fn cases() -> Vec<Case> {
|
||||
let mut out: Vec<Case> = Vec::new();
|
||||
let push = |out: &mut Vec<Case>, name: &str, broken: String, gold: String, verify: Verify| {
|
||||
out.push(Case {
|
||||
name: name.to_string(),
|
||||
broken,
|
||||
gold,
|
||||
verify,
|
||||
});
|
||||
};
|
||||
|
||||
// 1–2 调用实参:数字形参传了文本(金修复改调用行 = span 侧)
|
||||
for (v, lit, n) in [("a", "七", 7), ("b", "八", 8)] {
|
||||
let broken = format!(
|
||||
"# main\n\n> 加一 \"{lit}\"\n\n## 加一\n\n对于输入变量`n`,期望是数字。\n\n\
|
||||
| 参数 | 类型 | 说明 |\n|------|------|------|\n| n | number | 输入值 |\n\n\
|
||||
| 返回 | 类型 | 说明 |\n|------|------|------|\n| | number | 结果 |\n\n*n+1*\n"
|
||||
);
|
||||
let gold = broken.replace(&format!("> 加一 \"{lit}\""), &format!("> 加一 {n}"));
|
||||
push(&mut out, &format!("arg-num-{v}"), broken, gold, Verify::Run("contract.arg_mismatch"));
|
||||
}
|
||||
|
||||
// 3–4 调用实参:文本形参传了裸数(金修复加引号 = span 侧)
|
||||
for (v, n) in [("a", 7), ("b", 8)] {
|
||||
let broken = format!(
|
||||
"# main\n\n> 转换 {n}\n\n## 转换\n\n对于输入变量`s`,期望是文本。\n\n\
|
||||
| 参数 | 类型 | 说明 |\n|------|------|------|\n| s | text | 输入 |\n\n\
|
||||
| 返回 | 类型 | 说明 |\n|------|------|------|\n| | text | 结果 |\n\n*s*\n"
|
||||
);
|
||||
let gold = broken.replace(&format!("> 转换 {n}"), &format!("> 转换 \"{n}\""));
|
||||
push(&mut out, &format!("arg-text-{v}"), broken, gold, Verify::Run("contract.arg_mismatch"));
|
||||
}
|
||||
|
||||
// 5–6 返回契约:返回文本却声明 number(金修复改契约行 = anchor 侧)
|
||||
for (v, lit) in [("a", "七"), ("b", "你好")] {
|
||||
let broken = format!(
|
||||
"# main\n\n**结果 = > 转换 \"{lit}\"**\n*结果*\n\n## 转换\n\n对于输入变量`s`,期望是文本。\n\n\
|
||||
| 参数 | 类型 | 说明 |\n|------|------|------|\n| s | text | 输入 |\n\n\
|
||||
| 返回 | 类型 | 说明 |\n|------|------|------|\n| | number | 结果 |\n\n*s*\n"
|
||||
);
|
||||
let gold = broken.replace("| | number | 结果 |", "| | text | 结果 |");
|
||||
push(&mut out, &format!("ret-type-{v}"), broken, gold, Verify::Run("contract.return_mismatch"));
|
||||
}
|
||||
|
||||
// 7–8 字段类型:数据与字段契约不符(金修复改契约行 = anchor 侧)
|
||||
{
|
||||
let broken = "# main\n\n| 字段 | 类型 | 可空 |\n|------|------|------|\n| id | number | |\n| name | text | 是 |\n\n\
|
||||
`用户` =\n| id | name |\n|------|------|\n| abc | 小明 |\n\n*`用户`[^name]*\n"
|
||||
.to_string();
|
||||
let gold = broken.replace("| id | number | |", "| id | text | |");
|
||||
push(&mut out, "field-type-a", broken, gold, Verify::Run("contract.field_mismatch"));
|
||||
|
||||
let broken = "# main\n\n| 字段 | 类型 | 可空 |\n|------|------|------|\n| id | number | |\n| name | number | 是 |\n\n\
|
||||
`用户` =\n| id | name |\n|------|------|\n| 1 | 小明 |\n\n*`用户`[^name]*\n"
|
||||
.to_string();
|
||||
let gold = broken.replace("| name | number | 是 |", "| name | text | 是 |");
|
||||
push(&mut out, "field-type-b", broken, gold, Verify::Run("contract.field_mismatch"));
|
||||
}
|
||||
|
||||
// 9–10 缺字段:数据没有契约要求的非空字段(金修复标可空 = anchor 侧)
|
||||
{
|
||||
let broken = "# main\n\n| 字段 | 类型 | 可空 |\n|------|------|------|\n| id | number | |\n| name | text | |\n\n\
|
||||
`用户` =\n| id | qq |\n|------|------|\n| 1 | 5 |\n\n*`用户`[^id]*\n"
|
||||
.to_string();
|
||||
let gold = broken.replace("| name | text | |", "| name | text | 是 |");
|
||||
push(&mut out, "field-nullable-a", broken, gold, Verify::Run("contract.field_mismatch"));
|
||||
|
||||
let broken = "# main\n\n| 字段 | 类型 | 可空 |\n|------|------|------|\n| id | number | |\n| name | text | |\n\n\
|
||||
`用户` =\n| name | qq |\n|------|------|\n| 小明 | 5 |\n\n*`用户`[^name]*\n"
|
||||
.to_string();
|
||||
let gold = broken.replace("| id | number | |", "| id | number | 是 |");
|
||||
push(&mut out, "field-nullable-b", broken, gold, Verify::Run("contract.field_mismatch"));
|
||||
}
|
||||
|
||||
// 11–12 未知键:访问不在契约里的字段(金修复改索引键 = span 侧)
|
||||
{
|
||||
let broken = "# main\n\n| 字段 | 类型 | 可空 |\n|------|------|------|\n| id | number | |\n| name | text | 是 |\n\n\
|
||||
`用户` =\n| id | name |\n|------|------|\n| 1 | 小明 |\n\n*`用户`[^email]*\n"
|
||||
.to_string();
|
||||
let gold = broken.replace("[^email]", "[^name]");
|
||||
let broken_b = broken.replace("[^email]", "[^phone]");
|
||||
let gold_b = broken_b.replace("[^phone]", "[^id]");
|
||||
push(&mut out, "key-fix-a", broken, gold, Verify::Run("contract.unknown_key"));
|
||||
push(&mut out, "key-fix-b", broken_b, gold_b, Verify::Run("contract.unknown_key"));
|
||||
}
|
||||
|
||||
// 13–14 类型名拼错(金修复改正拼写 = anchor 侧)
|
||||
for (v, typo, fix) in [("a", "nubmer", "number"), ("b", "txt", "text")] {
|
||||
let broken = format!(
|
||||
"# main\n\n## 加一\n\n对于输入变量`n`,执行加一。\n\n\
|
||||
| 参数 | 类型 | 说明 |\n|------|------|------|\n| n | {typo} | 输入值 |\n\n*n+1*\n"
|
||||
);
|
||||
let gold = broken.replace(typo, fix);
|
||||
push(&mut out, &format!("type-typo-{v}"), broken, gold, Verify::Static("contract.unknown_type"));
|
||||
}
|
||||
|
||||
// 15–16 契约行名字错位(金修复改行名 = anchor 侧)
|
||||
for (v, wrong) in [("a", "nn"), ("b", "nm")] {
|
||||
let broken = format!(
|
||||
"# main\n\n## 加一\n\n对于输入变量`n`,执行加一。\n\n\
|
||||
| 参数 | 类型 | 说明 |\n|------|------|------|\n| {wrong} | number | 输入值 |\n\n*n+1*\n"
|
||||
);
|
||||
let gold = broken.replace(&format!("| {wrong} | number | 输入值 |"), "| n | number | 输入值 |");
|
||||
push(&mut out, &format!("drift-rename-{v}"), broken, gold, Verify::Static("contract.param_drift"));
|
||||
}
|
||||
|
||||
// 17–18 新升参未被契约覆盖(金修复补契约行 = anchor 侧,插入表尾)
|
||||
for (v, extra) in [("a", "m"), ("b", "k")] {
|
||||
let broken = format!(
|
||||
"# main\n\n## 加一\n\n对于输入变量`n`,临时量`{extra}`。\n\n\
|
||||
| 参数 | 类型 | 说明 |\n|------|------|------|\n| n | number | 输入值 |\n\n*n + {extra}*\n"
|
||||
);
|
||||
let gold = broken.replace(
|
||||
"| n | number | 输入值 |",
|
||||
&format!("| n | number | 输入值 |\n| {extra} | number | 临时 |"),
|
||||
);
|
||||
push(&mut out, &format!("drift-cover-{v}"), broken, gold, Verify::Static("contract.param_drift"));
|
||||
}
|
||||
|
||||
// 19–20 两份契约打架(金修复删第二张表 = anchor 侧,纯删除)
|
||||
{
|
||||
let broken = "# main\n\n## 加一\n\n对于输入变量`n`,执行加一。\n\n\
|
||||
| 参数 | 类型 | 说明 |\n|------|------|------|\n| n | number | 输入值 |\n\n\
|
||||
| 参数 | 类型 | 说明 |\n|------|------|------|\n| n | number | 重复 |\n\n*n+1*\n"
|
||||
.to_string();
|
||||
let gold = broken.replace(
|
||||
"\n| 参数 | 类型 | 说明 |\n|------|------|------|\n| n | number | 重复 |",
|
||||
"",
|
||||
);
|
||||
push(&mut out, "dup-delete-a", broken, gold, Verify::Static("contract.duplicate"));
|
||||
|
||||
let broken = "# main\n\n## 转换\n\n对于输入变量`s`,期望是文本。\n\n\
|
||||
| 参数 | 类型 | 说明 |\n|------|------|------|\n| s | text | 输入 |\n\n\
|
||||
| 返回 | 类型 | 说明 |\n|------|------|------|\n| | text | 结果 |\n\n\
|
||||
| 返回 | 类型 | 说明 |\n|------|------|------|\n| | text | 同上 |\n\n*s*\n"
|
||||
.to_string();
|
||||
let gold = broken.replace(
|
||||
"\n| 返回 | 类型 | 说明 |\n|------|------|------|\n| | text | 同上 |",
|
||||
"",
|
||||
);
|
||||
push(&mut out, "dup-delete-b", broken, gold, Verify::Static("contract.duplicate"));
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
Submodule
+1
Submodule tests/conformance added at 015ff8ac15.
@@ -1,481 +0,0 @@
|
||||
//! T4 差分一致性(roadmap §6 B 组):解释器求值 == Lean 生成语义。
|
||||
//!
|
||||
//! 对每个纯函数语料:
|
||||
//! 1. 解释器跑 `marqdo run --call-lib-path` 拿到真实返回值;
|
||||
//! 2. `prove emit` 生成 Lean 定义,追加 `example : … = «期望» := by simp`;
|
||||
//! 3. 真 Lean 校验通过 ⇒ 生成器的 Val 语义与解释器一致(B1/B3/B4/B5)。
|
||||
//!
|
||||
//! 已记录偏差(不进本测试):除零/模零——解释器为运行时错误,P1 库模型
|
||||
//! `mqDiv`/`mqMod` 返回 `.int 0`(MarqdoProof.lean 注释与设计 §12 偏差表)。
|
||||
//! 无 Lean 工具链时整组 SKIP(MARQDO_PROOF_REQUIRE_LEAN=1 则失败)。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// 语料:模块名 / 函数名 / 参数 JSON / 期望 Val 的 Lean 字面。
|
||||
struct Case {
|
||||
module: &'static str,
|
||||
function: &'static str,
|
||||
source: &'static str,
|
||||
args: &'static str,
|
||||
/// Lean 期望值(`Val.*` 构造)。
|
||||
expected: &'static str,
|
||||
/// 额外 simp 引理(默认集之外)。
|
||||
extra_simp: &'static [&'static str],
|
||||
}
|
||||
|
||||
const CASES: &[Case] = &[
|
||||
Case {
|
||||
module: "算术",
|
||||
function: "加倍",
|
||||
source: r#"---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
## 加倍
|
||||
+ `x`
|
||||
|
||||
**y = `x` + `x`**
|
||||
|
||||
*y*
|
||||
"#,
|
||||
args: r#"{"x": 21}"#,
|
||||
expected: "Val.int 42",
|
||||
extra_simp: &[],
|
||||
},
|
||||
Case {
|
||||
module: "计算器",
|
||||
function: "加法",
|
||||
source: r#"---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
## 加法
|
||||
+ `甲`
|
||||
+ `乙`
|
||||
|
||||
**和 = `甲` + `乙`**
|
||||
|
||||
*和*
|
||||
"#,
|
||||
args: r#"{"甲": -5, "乙": 2}"#,
|
||||
expected: "Val.int (-3)",
|
||||
extra_simp: &[],
|
||||
},
|
||||
Case {
|
||||
module: "比较",
|
||||
function: "判断",
|
||||
source: r#"---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
## 判断
|
||||
+ `x`
|
||||
|
||||
1. `x` > 10
|
||||
**结论 = "大"**
|
||||
2. *
|
||||
**结论 = "小"**
|
||||
|
||||
*结论*
|
||||
"#,
|
||||
args: r#"{"x": 11}"#,
|
||||
expected: r#"Val.text "大""#,
|
||||
extra_simp: &[],
|
||||
},
|
||||
Case {
|
||||
module: "工单",
|
||||
function: "创建",
|
||||
source: r#"---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
## 创建
|
||||
+ `id`
|
||||
|
||||
**单号 = "T-" + `id`**
|
||||
|
||||
*单号*
|
||||
"#,
|
||||
args: r#"{"id": 7}"#,
|
||||
expected: r#"Val.text "T-7""#,
|
||||
extra_simp: &[],
|
||||
},
|
||||
Case {
|
||||
module: "边界",
|
||||
function: "极限",
|
||||
source: r#"---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
## 极限
|
||||
+ `x`
|
||||
|
||||
**y = `x` + 1**
|
||||
|
||||
*y*
|
||||
"#,
|
||||
args: r#"{"x": 9223372036854775806}"#,
|
||||
expected: "Val.int 9223372036854775807",
|
||||
extra_simp: &[],
|
||||
},
|
||||
];
|
||||
|
||||
/// 直接驱动解释器调用 `模块.函数`(run_file_capture 不处理 call_lib_path)。
|
||||
fn call_function(file: &Path, lib_path: &str, args_json: &str) -> marqdo::value::Value {
|
||||
let module = marqdo::load::load_module(file).expect("load module");
|
||||
let mut host = marqdo::host::HostContext::for_capture(Some(file), marqdo::host::HostCaps {
|
||||
fs_write: false,
|
||||
exec: false,
|
||||
net: false,
|
||||
plugin: false,
|
||||
});
|
||||
let mut interp = marqdo::interp::Interpreter::with_capture(Some(file), false).with_host(host);
|
||||
let args: marqdo::value::Value = serde_json::from_str(args_json)
|
||||
.map(|v: serde_json::Value| json_to_value(&v))
|
||||
.expect("args json");
|
||||
interp
|
||||
.run_site_lib_path(&module, lib_path, Some(&args))
|
||||
.expect("interpreter call")
|
||||
}
|
||||
|
||||
/// JSON → Value(T4 语料只用到 int/text/bool/map)。
|
||||
fn json_to_value(v: &serde_json::Value) -> marqdo::value::Value {
|
||||
use marqdo::value::Value;
|
||||
match v {
|
||||
serde_json::Value::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
Value::Int(i)
|
||||
} else {
|
||||
Value::Num(n.as_f64().unwrap_or(0.0))
|
||||
}
|
||||
}
|
||||
serde_json::Value::String(s) => Value::Text(s.clone()),
|
||||
serde_json::Value::Bool(b) => Value::Bool(*b),
|
||||
serde_json::Value::Object(m) => Value::Map(
|
||||
m.iter()
|
||||
.map(|(k, v)| (k.clone(), json_to_value(v)))
|
||||
.collect(),
|
||||
),
|
||||
_ => Value::None,
|
||||
}
|
||||
}
|
||||
|
||||
fn lean_binary() -> Option<PathBuf> {
|
||||
if let Ok(p) = std::env::var("MARQDO_PROOF_LEAN") {
|
||||
let p = PathBuf::from(p);
|
||||
if p.exists() {
|
||||
return Some(p);
|
||||
}
|
||||
}
|
||||
let path = std::env::var_os("PATH")?;
|
||||
std::env::split_paths(&path).map(|d| d.join("lean")).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
fn require_lean_enforced() -> bool {
|
||||
std::env::var("MARQDO_PROOF_REQUIRE_LEAN").is_ok_and(|v| v == "1")
|
||||
}
|
||||
|
||||
fn target_dir() -> PathBuf {
|
||||
std::env::var_os("CARGO_TARGET_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target"))
|
||||
}
|
||||
|
||||
/// 源文件中的函数体生成的 Lean 定义名(与 emit 一致)。
|
||||
fn def_name(_module: &str, function: &str) -> String {
|
||||
format!("«{function}»")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t4_interpreter_matches_lean_semantics() {
|
||||
let Some(lean) = lean_binary() else {
|
||||
if require_lean_enforced() {
|
||||
panic!("MARQDO_PROOF_REQUIRE_LEAN=1 但没有 Lean 工具链");
|
||||
}
|
||||
println!("SKIP conformance(无 Lean 工具链)");
|
||||
return;
|
||||
};
|
||||
let root = target_dir().join("conformance");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).expect("scratch");
|
||||
|
||||
let toolchain = marqdo::prove::driver::Toolchain::discover(Some(&lean))
|
||||
.expect("toolchain discover")
|
||||
.expect("lean present");
|
||||
let (library_dir, _sha) = marqdo::prove::driver::ensure_library(&root, &toolchain)
|
||||
.expect("build library");
|
||||
let mut lean_env = std::env::split_paths(&std::env::var_os("LEAN_PATH").unwrap_or_default())
|
||||
.collect::<Vec<_>>();
|
||||
lean_env.push(library_dir);
|
||||
|
||||
let mut failures: Vec<String> = Vec::new();
|
||||
for case in CASES {
|
||||
let dir = root.join(case.module);
|
||||
std::fs::create_dir_all(&dir).expect("case dir");
|
||||
let lib_file = dir.join(format!("{}.mq.md", case.module));
|
||||
std::fs::write(&lib_file, case.source).expect("write source");
|
||||
// 主文件只做导入:解释器经 import bind 调库函数。
|
||||
let main_file = dir.join("主.mq.md");
|
||||
std::fs::write(
|
||||
&main_file,
|
||||
format!(
|
||||
"---\nmarkup: occlusion\nimport:\n {}: {}.mq.md\n---\n\n# 主\n",
|
||||
case.module, case.module
|
||||
),
|
||||
)
|
||||
.expect("write main");
|
||||
let file = main_file;
|
||||
let args_file = dir.join("args.json");
|
||||
std::fs::write(&args_file, case.args).expect("write args");
|
||||
|
||||
// ① 解释器求值。
|
||||
let lib_path = format!("{}.{}", case.module, case.function);
|
||||
let value = match std::panic::catch_unwind(|| {
|
||||
call_function(&file, &lib_path, case.args)
|
||||
}) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
failures.push(format!("{}: 解释器调用失败", case.function));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// ② 生成 Lean 定义。
|
||||
let emit_dir = dir.join("out");
|
||||
let prove_opts = marqdo::prove::ProveOptions {
|
||||
emit_dir: Some(emit_dir.clone()),
|
||||
judge: false,
|
||||
report_only: false,
|
||||
..Default::default()
|
||||
};
|
||||
if let Err(e) = marqdo::prove::prove_path(&lib_file, &prove_opts) {
|
||||
failures.push(format!("{}: 生成失败:{e}", case.function));
|
||||
continue;
|
||||
}
|
||||
// 文件名与 emit 一致:非 ASCII 字符确定性编码为 uXXXX。
|
||||
let stem: String = case
|
||||
.module
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || c == '_' {
|
||||
c.to_string()
|
||||
} else if !c.is_ascii() {
|
||||
format!("u{:04X}", c as u32)
|
||||
} else {
|
||||
"_".to_string()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let generated = emit_dir.join("Generated").join(format!("{stem}_mq.lean"));
|
||||
let module_src = std::fs::read_to_string(&generated).expect("generated module");
|
||||
|
||||
let simp_set = {
|
||||
let mut base = "mqTruth, Op.name, mqAccess, mqResultOk, mqResultError, mqValueOr, mqAnd, mqOr, mqNot, mqAdd, mqSub, mqMul, mqEq".to_string();
|
||||
for e in case.extra_simp {
|
||||
base.push_str(", ");
|
||||
base.push_str(e);
|
||||
}
|
||||
base
|
||||
};
|
||||
// 实参按生成定义的形参顺序(扫描 def 签名的顶层括号组)。
|
||||
let def_line = module_src
|
||||
.lines()
|
||||
.find(|l| {
|
||||
l.starts_with(&format!("def {} ", def_name(case.module, case.function)))
|
||||
&& l.contains('(')
|
||||
})
|
||||
.unwrap_or("");
|
||||
let mut params: Vec<String> = Vec::new();
|
||||
let mut depth = 0usize;
|
||||
let mut cur = String::new();
|
||||
for ch in def_line.chars() {
|
||||
match ch {
|
||||
'(' => {
|
||||
depth += 1;
|
||||
cur.clear();
|
||||
}
|
||||
')' => {
|
||||
depth = depth.saturating_sub(1);
|
||||
if depth == 0 {
|
||||
let inner = cur.trim();
|
||||
let name = inner.split(':').next().unwrap_or("").trim();
|
||||
let bare = name
|
||||
.strip_prefix("«")
|
||||
.and_then(|s| s.strip_suffix("»"))
|
||||
.unwrap_or(name);
|
||||
if bare != "env" && bare != "轨迹" && !bare.is_empty() {
|
||||
params.push(bare.to_string());
|
||||
}
|
||||
}
|
||||
cur.clear();
|
||||
}
|
||||
_ => {
|
||||
if depth > 0 {
|
||||
cur.push(ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let args_map: serde_json::Map<String, serde_json::Value> =
|
||||
serde_json::from_str(case.args).expect("args object");
|
||||
let arg_terms = params
|
||||
.iter()
|
||||
.map(|name| {
|
||||
let v = args_map.get(name).cloned().unwrap_or(serde_json::Value::Null);
|
||||
match v.as_i64() {
|
||||
Some(i) if i < 0 => format!("(Val.int ({i}))"),
|
||||
Some(i) => format!("(Val.int {i})"),
|
||||
None => match v.as_str() {
|
||||
Some(s) => format!("(Val.text \"{s}\")"),
|
||||
None => "(Val.none)".to_string(),
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
// ③ 期望 = 语料声明的 Lean 字面(与解释器求值在 ① 已对照)。
|
||||
let expected = case.expected.to_string();
|
||||
let mut conformance = module_src.clone();
|
||||
let example = format!(
|
||||
"\n-- T4:解释器期望值({} 返回 {:?})\nexample : ({} env [] {arg_terms}).1 = {expected} := by\n simp [{}, {}]\n try rfl\n",
|
||||
case.function,
|
||||
value,
|
||||
def_name(case.module, case.function),
|
||||
def_name(case.module, case.function),
|
||||
simp_set,
|
||||
);
|
||||
if let Some(pos) = conformance.rfind("\nend Generated") {
|
||||
conformance.insert_str(pos, &example);
|
||||
} else {
|
||||
conformance.push_str(&example);
|
||||
}
|
||||
let conformance_file = dir.join("Conformance.lean");
|
||||
std::fs::write(&conformance_file, &conformance).expect("write conformance");
|
||||
|
||||
// ④ Lean 校验。
|
||||
let out = Command::new(&lean)
|
||||
.current_dir(&dir)
|
||||
.env(
|
||||
"LEAN_PATH",
|
||||
std::env::join_paths(&lean_env).expect("lean path"),
|
||||
)
|
||||
.arg(conformance_file.strip_prefix(&dir).unwrap_or(&conformance_file))
|
||||
.output()
|
||||
.expect("run lean");
|
||||
if !out.status.success() {
|
||||
failures.push(format!(
|
||||
"{}: Lean 不接受解释器期望值({:?}):\n-- stderr:\n{}\n-- stdout:\n{}",
|
||||
case.function,
|
||||
value,
|
||||
String::from_utf8_lossy(&out.stderr),
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"T4 差分不一致 {} 项:\n{}",
|
||||
failures.len(),
|
||||
failures.join("\n----------------------------------------\n")
|
||||
);
|
||||
println!("conformance: {} 例全部一致(解释器 == Lean)", CASES.len());
|
||||
}
|
||||
|
||||
/// B4 补充:结果结构(result.ok)字段读取与解释器一致。
|
||||
#[test]
|
||||
fn t4_result_struct_field_access() {
|
||||
let Some(lean) = lean_binary() else {
|
||||
if require_lean_enforced() {
|
||||
panic!("MARQDO_PROOF_REQUIRE_LEAN=1 但没有 Lean 工具链");
|
||||
}
|
||||
println!("SKIP conformance(无 Lean 工具链)");
|
||||
return;
|
||||
};
|
||||
let root = target_dir().join("conformance-result");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).expect("scratch");
|
||||
|
||||
let source = r#"---
|
||||
markup: occlusion
|
||||
import:
|
||||
result: lib/result.mq.md
|
||||
---
|
||||
|
||||
## 登记
|
||||
+ `金额`
|
||||
|
||||
**回执 = [登记](result.ok(value=`金额`))**
|
||||
|
||||
*access(回执, "value")*
|
||||
"#;
|
||||
let dir = &root;
|
||||
let lib_file = dir.join("台.mq.md");
|
||||
std::fs::write(&lib_file, source).expect("write");
|
||||
let file = dir.join("主.mq.md");
|
||||
std::fs::write(
|
||||
&file,
|
||||
"---\nmarkup: occlusion\nimport:\n 台: 台.mq.md\n---\n\n# 主\n",
|
||||
)
|
||||
.expect("write main");
|
||||
std::fs::create_dir_all(dir.join("lib")).expect("lib");
|
||||
std::fs::write(
|
||||
dir.join("lib/result.mq.md"),
|
||||
std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("lib/result.mq.md"))
|
||||
.expect("repo result lib"),
|
||||
)
|
||||
.expect("write result lib");
|
||||
let args_file = dir.join("args.json");
|
||||
std::fs::write(&args_file, r#"{"金额": 5}"#).expect("args");
|
||||
|
||||
let value = call_function(&file, "台.登记", r#"{"金额": 5}"#);
|
||||
// access(回执, "value") 应取回 5(ok/value 字段结构在 Lean 侧由
|
||||
// mqAccess (mqResultOk …) 方程锁定,两侧一致即 B4)。
|
||||
assert!(
|
||||
matches!(&value, marqdo::value::Value::Int(5)),
|
||||
"access(result.ok(5), \"value\") 应为 Int(5),实际 {value:?}"
|
||||
);
|
||||
|
||||
// Lean 侧同一表达式:mqResultOk 5 的 value 字段 == 5。
|
||||
let prove_opts = marqdo::prove::ProveOptions {
|
||||
emit_dir: Some(dir.join("out")),
|
||||
judge: false,
|
||||
report_only: false,
|
||||
..Default::default()
|
||||
};
|
||||
marqdo::prove::prove_path(&lib_file, &prove_opts).expect("emit");
|
||||
let generated = dir.join("out/Generated/u53F0_mq.lean"); // 台 → u53F0
|
||||
let module_src = std::fs::read_to_string(&generated).expect("generated");
|
||||
let mut conformance = module_src;
|
||||
conformance.push_str(
|
||||
"\n-- T4 B4:结构字段与解释器一致\nexample : (mqResultOk (Val.int 5)).2.1 ≡ Val.int 5 := rfl\n",
|
||||
);
|
||||
// mqResultOk 的 map 字段顺序依赖库实现,直接用 mqAccess 更稳:
|
||||
let conformance = conformance.replace(
|
||||
"example : (mqResultOk (Val.int 5)).2.1 ≡ Val.int 5 := rfl\n",
|
||||
"example : mqAccess (mqResultOk (Val.int 5)) \"value\" = Val.int 5 := by\n simp [mqResultOk, mqAccess]\n",
|
||||
);
|
||||
let conformance_file = dir.join("Conformance.lean");
|
||||
std::fs::write(&conformance_file, &conformance).expect("write");
|
||||
|
||||
let toolchain = marqdo::prove::driver::Toolchain::discover(Some(&lean))
|
||||
.expect("discover")
|
||||
.expect("lean");
|
||||
let (library_dir, _) =
|
||||
marqdo::prove::driver::ensure_library(&root, &toolchain).expect("library");
|
||||
let mut lean_env = vec![library_dir];
|
||||
if let Some(p) = std::env::var_os("LEAN_PATH") {
|
||||
lean_env.extend(std::env::split_paths(&p));
|
||||
}
|
||||
let out = Command::new(&lean)
|
||||
.current_dir(dir)
|
||||
.env("LEAN_PATH", std::env::join_paths(&lean_env).expect("paths"))
|
||||
.arg("Conformance.lean")
|
||||
.output()
|
||||
.expect("run lean");
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"B4 结构字段不一致:\n{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
//! 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 = "\
|
||||
---
|
||||
markup: classic
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
| 字段 | 类型 | 可空 |
|
||||
|------|------|------|
|
||||
| id | number | |
|
||||
| name | text | 是 |
|
||||
|
||||
`用户` =
|
||||
| id | name |
|
||||
|------|------|
|
||||
| 1 | 小明 |
|
||||
|
||||
*[email](`用户`)*
|
||||
";
|
||||
|
||||
const KEY_RIGHT: &str = "\
|
||||
---
|
||||
markup: classic
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
| 字段 | 类型 | 可空 |
|
||||
|------|------|------|
|
||||
| id | number | |
|
||||
| name | text | 是 |
|
||||
|
||||
`用户` =
|
||||
| id | name |
|
||||
|------|------|
|
||||
| 1 | 小明 |
|
||||
|
||||
*[name](`用户`)*
|
||||
";
|
||||
|
||||
const KEY_BARE: &str = "\
|
||||
---
|
||||
markup: classic
|
||||
---
|
||||
|
||||
# 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}");
|
||||
}
|
||||
@@ -1,319 +0,0 @@
|
||||
//! 渐进式契约(Phase 2 · T2.1–T2.5):契约提取、四边界运行时校验、`check` 静态互查。
|
||||
//!
|
||||
//! 验收对照 `doc/roadmap/three-problems-plan.md` 的完成定义:
|
||||
//! P1 零回归(绑定表/普通文档表不吃)、P2 锚点诊断、契约漂移必产诊断。
|
||||
//! 升参推断 = 散文声明(`` `名` ``)+ 体读取;契约提取在其**之前**执行。
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use marqdo::ast::{Expr, Function, Module, Stmt};
|
||||
use marqdo::check::check_module;
|
||||
use marqdo::contract::Ty;
|
||||
use marqdo::diagnostics::Diagnostic;
|
||||
use marqdo::load::load_module_from_source;
|
||||
use marqdo::{run_file, RunOptions};
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/contracts")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
fn find_fn<'a>(module: &'a Module, name: &str) -> &'a Function {
|
||||
fn walk<'a>(funs: &'a [Function], name: &str) -> Option<&'a Function> {
|
||||
for f in funs {
|
||||
if f.name == name {
|
||||
return Some(f);
|
||||
}
|
||||
if let Some(c) = walk(&f.children, name) {
|
||||
return Some(c);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
walk(&module.functions, name).unwrap_or_else(|| panic!("function `{name}` not found"))
|
||||
}
|
||||
|
||||
/// anyhow 错误链 → 结构化 Diagnostic(load 的 context 包裹也不丢)。
|
||||
fn structured(err: anyhow::Error) -> Diagnostic {
|
||||
match err.downcast::<Diagnostic>() {
|
||||
Ok(d) => d,
|
||||
Err(e) => Diagnostic::find(&e)
|
||||
.cloned()
|
||||
.expect("错误必须是结构化 Diagnostic(AI/MLSP 面)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// 运行夹具并断言失败的错误是结构化 Diagnostic。
|
||||
fn run_err_code(name: &str) -> Diagnostic {
|
||||
let err = run_file(&fixture(name), &RunOptions::default())
|
||||
.expect_err(&format!("{name}: 期望契约报错,实际运行通过"));
|
||||
structured(err)
|
||||
}
|
||||
|
||||
// ---------- T2.1 提取 ----------
|
||||
|
||||
#[test]
|
||||
fn extracts_param_and_return_contract() {
|
||||
let src = "\
|
||||
# main
|
||||
|
||||
## 加一
|
||||
|
||||
对于输入变量`n`,执行加一。
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| n | number | 输入值 |
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| | number | 加一结果 |
|
||||
|
||||
*n+1*
|
||||
";
|
||||
let module = load_module_from_source(src).unwrap();
|
||||
let fun = find_fn(&module, "加一");
|
||||
let c = fun.contract.as_ref().expect("应提取到函数契约");
|
||||
assert_eq!(c.params.len(), 1);
|
||||
assert_eq!(c.params[0].name, "n");
|
||||
assert_eq!(c.params[0].ty, Ty::Number);
|
||||
assert_eq!(c.params[0].desc, "输入值");
|
||||
assert_eq!(c.returns.as_ref().unwrap().ty, Ty::Number);
|
||||
// 契约表从 body 移除(元数据永不执行)
|
||||
assert!(
|
||||
!fun.body
|
||||
.iter()
|
||||
.any(|s| matches!(s, Stmt::Expr { value: Expr::Map(_), .. })),
|
||||
"契约表应从 body 移除,剩余 body: {:?}", fun.body
|
||||
);
|
||||
// 升参(散文声明 `n` + 体读取)恰好覆盖契约
|
||||
assert_eq!(
|
||||
fun.params.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(),
|
||||
["n"]
|
||||
);
|
||||
// T2.4:锚点 + 原文行
|
||||
assert_eq!(c.start_line, 7);
|
||||
assert!(c.quote.iter().any(|q| q.contains("| 参数 | 类型 | 说明 |")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contract_cells_do_not_pollute_inference() {
|
||||
// 契约说明列里的 `` `x` `` 只是文档提及——提取先于升参推断,`x` 不得被升参。
|
||||
let src = "\
|
||||
# main
|
||||
|
||||
## 加一
|
||||
|
||||
对于输入变量`n`,临时量`x`。
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| n | number | 与 `x` 相加 |
|
||||
|
||||
*n+1*
|
||||
";
|
||||
let module = load_module_from_source(src).unwrap();
|
||||
let fun = find_fn(&module, "加一");
|
||||
assert_eq!(fun.contract.as_ref().unwrap().params[0].name, "n");
|
||||
assert_eq!(
|
||||
fun.params.iter().map(|p| p.name.clone()).collect::<Vec<_>>(),
|
||||
["n"],
|
||||
"契约单元格的名不得被升参(提取先于推断)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bound_data_table_never_contract() {
|
||||
// P1 零回归反例:**绑定**的 `字段|类型|可空` 数据表(web_db_migration 风格)不吃。
|
||||
let module = load_module_from_source(
|
||||
&std::fs::read_to_string(fixture("bound_data_table.mq.md")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let fun = find_fn(&module, "main");
|
||||
assert!(fun.contract.is_none());
|
||||
assert!(fun.var_contracts.is_empty());
|
||||
run_file(&fixture("bound_data_table.mq.md"), &RunOptions::default())
|
||||
.expect("绑定数据表必须照常运行");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_contract_tables_diagnosed() {
|
||||
// 两份契约打架 ⇒ 必产诊断(防漂移的一部分)。
|
||||
let src = "\
|
||||
# main
|
||||
|
||||
## 加一
|
||||
|
||||
对于输入变量`n`,执行加一。
|
||||
|
||||
| 参数 | 类型 |
|
||||
|------|------|
|
||||
| n | number |
|
||||
|
||||
| 参数 | 类型 |
|
||||
|------|------|
|
||||
| n | number |
|
||||
|
||||
*n+1*
|
||||
";
|
||||
let err = load_module_from_source(src).expect_err("重复契约必须报错");
|
||||
let d = structured(err);
|
||||
assert_eq!(d.to_json()["code"], "contract.duplicate");
|
||||
}
|
||||
|
||||
// ---------- T2.2 四边界运行时校验 ----------
|
||||
|
||||
#[test]
|
||||
fn call_arg_mismatch_reports_contract_diagnostic() {
|
||||
let d = run_err_code("arg_mismatch.mq.md");
|
||||
let v = d.to_json();
|
||||
assert_eq!(v["code"], "contract.arg_mismatch");
|
||||
assert!(
|
||||
v["message"].as_str().unwrap().contains("参数 `n` 期望 number,实际 text"),
|
||||
"{v}"
|
||||
);
|
||||
assert_eq!(v["severity"], "error");
|
||||
// T2.4:锚点能回溯到出错表,且带原文行
|
||||
assert!(v["doc_anchor"].as_str().unwrap().contains("#L"));
|
||||
assert!(
|
||||
v["doc_quote"].as_str().unwrap().contains("| 参数 | 类型 | 说明 |"),
|
||||
"doc_quote 应含契约表原文: {v}"
|
||||
);
|
||||
// contract_ref 指向声明
|
||||
assert!(
|
||||
v["contract_ref"]["declared"].as_str().unwrap().contains("number"),
|
||||
"{v}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn return_mismatch_reports_contract_diagnostic() {
|
||||
let d = run_err_code("return_mismatch.mq.md");
|
||||
let v = d.to_json();
|
||||
assert_eq!(v["code"], "contract.return_mismatch");
|
||||
assert!(
|
||||
v["message"].as_str().unwrap().contains("返回值期望 number,实际 text"),
|
||||
"{v}"
|
||||
);
|
||||
assert!(v["doc_anchor"].as_str().unwrap().contains("#L"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_mismatch_at_binding_reports_contract_diagnostic() {
|
||||
// 字段表紧邻绑定之前 ⇒ 集合契约(T2.1);绑定时校验(边界 3)。
|
||||
let module = load_module_from_source(
|
||||
&std::fs::read_to_string(fixture("field_mismatch.mq.md")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let fun = find_fn(&module, "main");
|
||||
let c = fun.var_contracts.get("用户").expect("应提取到集合契约");
|
||||
assert_eq!(c.fields.len(), 2);
|
||||
assert_eq!(c.fields[0].name, "id");
|
||||
assert_eq!(c.fields[0].ty, Ty::Number);
|
||||
assert!(!c.fields[0].nullable);
|
||||
assert!(c.fields[1].nullable);
|
||||
|
||||
let d = run_err_code("field_mismatch.mq.md");
|
||||
let v = d.to_json();
|
||||
assert_eq!(v["code"], "contract.field_mismatch");
|
||||
assert!(
|
||||
v["doc_quote"].as_str().unwrap().contains("| 字段 | 类型 | 可空 |"),
|
||||
"{v}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_key_at_index_reports_contract_diagnostic() {
|
||||
let d = run_err_code("unknown_key.mq.md");
|
||||
let v = d.to_json();
|
||||
assert_eq!(v["code"], "contract.unknown_key");
|
||||
assert!(v["message"].as_str().unwrap().contains("email"), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ok_contract_runs_unchanged() {
|
||||
run_file(&fixture("ok_contract.mq.md"), &RunOptions::default())
|
||||
.expect("合法契约必须照常运行(P1/P2:不改变正常执行)");
|
||||
}
|
||||
|
||||
// ---------- T2.3/T2.5 `check` 静态互查 ----------
|
||||
|
||||
#[test]
|
||||
fn check_catches_param_drift() {
|
||||
let src = "\
|
||||
# main
|
||||
|
||||
## 加一
|
||||
|
||||
对于输入变量`n`,执行加一。
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| nn | number | 输入值 |
|
||||
|
||||
*n+1*
|
||||
";
|
||||
let module = load_module_from_source(src).unwrap();
|
||||
let diags = check_module(&module, None);
|
||||
let jsons: Vec<serde_json::Value> = diags.iter().map(|d| d.to_json()).collect();
|
||||
assert!(
|
||||
jsons.iter().any(|v| v["code"] == "contract.param_drift" && v["severity"] == "error"),
|
||||
"契约行名字错位 ⇒ Error: {jsons:?}"
|
||||
);
|
||||
assert!(
|
||||
jsons.iter().any(|v| v["code"] == "contract.param_drift" && v["severity"] == "warning"),
|
||||
"新升参未被契约覆盖 ⇒ Warning: {jsons:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_catches_unknown_type_with_suggestion() {
|
||||
let src = "\
|
||||
# main
|
||||
|
||||
## 加一
|
||||
|
||||
对于输入变量`n`,执行加一。
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| n | nubmer | 输入值 |
|
||||
|
||||
*n+1*
|
||||
";
|
||||
let module = load_module_from_source(src).unwrap();
|
||||
let diags = check_module(&module, None);
|
||||
let d = diags
|
||||
.iter()
|
||||
.find(|d| d.to_json()["code"] == "contract.unknown_type")
|
||||
.expect("未知类型名必产诊断(防 nubmer 拼错)");
|
||||
let v = d.to_json();
|
||||
assert!(
|
||||
v["suggestion"].as_str().unwrap().contains("number"),
|
||||
"应给出最近建议: {v}"
|
||||
);
|
||||
assert!(v["doc_anchor"].as_str().unwrap().contains("#L"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_catches_misplaced_contract_table() {
|
||||
let src = "\
|
||||
# main
|
||||
|
||||
**x=1**
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| n | number | 输入值 |
|
||||
|
||||
*x*
|
||||
";
|
||||
let module = load_module_from_source(src).unwrap();
|
||||
let diags = check_module(&module, None);
|
||||
assert!(
|
||||
diags.iter().any(|d| d.to_json()["code"] == "contract.misplaced"),
|
||||
"错位契约必产诊断: {:?}",
|
||||
diags.iter().map(|d| d.to_json()).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
> 加一 "七"
|
||||
|
||||
## 加一
|
||||
|
||||
对于输入变量`n`,期望是数字。
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| n | number | 输入值 |
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| | number | 加一结果 |
|
||||
|
||||
*n+1*
|
||||
@@ -1,13 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`列说明` =
|
||||
| 字段 | 类型 | 可空 |
|
||||
|------|------|------|
|
||||
| id | number | |
|
||||
| name | text | 是 |
|
||||
|
||||
*`列说明`[^字段]*
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
| 字段 | 类型 | 可空 |
|
||||
|------|------|------|
|
||||
| id | number | |
|
||||
| name | text | 是 |
|
||||
|
||||
`用户` =
|
||||
| id | name |
|
||||
|------|------|
|
||||
| abc | 小明 |
|
||||
|
||||
*`用户`[^name]*
|
||||
@@ -1,22 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**结果 = > 加一 3**
|
||||
*结果*
|
||||
|
||||
## 加一
|
||||
|
||||
对于输入变量`n`,期望是数字。
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| n | number | 输入值 |
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| | number | 加一结果 |
|
||||
|
||||
*n+1*
|
||||
@@ -1,22 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**结果 = > 转换 "七"**
|
||||
*结果*
|
||||
|
||||
## 转换
|
||||
|
||||
对于输入变量`s`,期望是文本。
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| s | text | 输入 |
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| | number | 转换结果 |
|
||||
|
||||
*s*
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
| 字段 | 类型 | 可空 |
|
||||
|------|------|------|
|
||||
| id | number | |
|
||||
| name | text | 是 |
|
||||
|
||||
`用户` =
|
||||
| id | name |
|
||||
|------|------|
|
||||
| 1 | 小明 |
|
||||
|
||||
*`用户`[^email]*
|
||||
@@ -1,96 +0,0 @@
|
||||
//! T1.3 核心表面守卫:`doc/design/core-surface.md` ⇄ `marqdo::parse::CORE_CONSTRUCTS`。
|
||||
//!
|
||||
//! 三重断言(反遮盖):
|
||||
//! 1. 文档 id 列与代码注册表**双向集合相等**——改任一侧不同步 → 红;
|
||||
//! 2. id 不重复;
|
||||
//! 3. 每行「样例」列指向的文件真实存在——删/改名样例 → 红。
|
||||
//!
|
||||
//! 任何新增核心标记都必须同步文档 + 本注册表 + 样例(`doc/design/layers.md` 准入戒律)。
|
||||
|
||||
use marqdo::parse::CORE_CONSTRUCTS;
|
||||
|
||||
/// 解析构造表:首格为 kebab-case 反引号 id 的行 → `(id, 样例路径)`。
|
||||
fn construct_rows(doc: &str) -> Vec<(String, String)> {
|
||||
let mut rows = Vec::new();
|
||||
for line in doc.lines() {
|
||||
let line = line.trim();
|
||||
if !line.starts_with("| `") {
|
||||
continue;
|
||||
}
|
||||
let cells: Vec<&str> = line.split('|').collect();
|
||||
if cells.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let id = cells[1].trim().trim_matches('`').to_string();
|
||||
if id.is_empty() || !id.chars().all(|c| c.is_ascii_lowercase() || c == '-') {
|
||||
continue; // 非构造行(如 LineKind 大类名首字母大写,天然排除)
|
||||
}
|
||||
let sample = line
|
||||
.split('`')
|
||||
.find_map(|s| {
|
||||
let s = s.trim();
|
||||
if s.starts_with("tests/") || s.starts_with("examples/") {
|
||||
Some(s.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
rows.push((id, sample));
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_surface_doc_matches_registry() {
|
||||
let doc = include_str!("../doc/design/core-surface.md");
|
||||
let mut doc_ids: Vec<String> = construct_rows(doc).into_iter().map(|(id, _)| id).collect();
|
||||
doc_ids.sort();
|
||||
let mut code_ids: Vec<String> = CORE_CONSTRUCTS
|
||||
.iter()
|
||||
.map(|(id, _)| (*id).to_string())
|
||||
.collect();
|
||||
code_ids.sort();
|
||||
assert_eq!(
|
||||
doc_ids, code_ids,
|
||||
"core-surface.md 与 CORE_CONSTRUCTS 不一致(T1.3 守卫)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_surface_ids_unique() {
|
||||
let doc = include_str!("../doc/design/core-surface.md");
|
||||
let ids: Vec<String> = construct_rows(doc).into_iter().map(|(id, _)| id).collect();
|
||||
let mut sorted = ids.clone();
|
||||
sorted.sort();
|
||||
sorted.dedup();
|
||||
assert_eq!(ids.len(), sorted.len(), "core-surface.md 存在重复 id");
|
||||
let mut code: Vec<&str> = CORE_CONSTRUCTS.iter().map(|(id, _)| *id).collect();
|
||||
let before = code.len();
|
||||
code.sort_unstable();
|
||||
code.dedup();
|
||||
assert_eq!(before, code.len(), "CORE_CONSTRUCTS 存在重复 id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_surface_samples_exist() {
|
||||
let doc = include_str!("../doc/design/core-surface.md");
|
||||
for (id, sample) in construct_rows(doc) {
|
||||
assert!(!sample.is_empty(), "构造 `{id}` 缺「样例」列");
|
||||
assert!(
|
||||
std::path::Path::new(&sample).exists(),
|
||||
"构造 `{id}` 样例不存在:{sample}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_surface_registry_ids_are_kebab() {
|
||||
for (id, shape) in CORE_CONSTRUCTS {
|
||||
assert!(
|
||||
id.chars().all(|c| c.is_ascii_lowercase() || c == '-'),
|
||||
"CORE_CONSTRUCTS id 非 kebab:{id}"
|
||||
);
|
||||
assert!(!shape.is_empty(), "CORE_CONSTRUCTS `{id}` 缺外形描述");
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
//! T1.4 诊断机器面:真实错误路径产出的 Diagnostic 可序列化(`run --json` 出口)。
|
||||
//!
|
||||
//! 验收(three-problems-plan.md T1.4):人类文本零回归 + JSON `code`/`span` 非空。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use marqdo::diagnostics::Diagnostic;
|
||||
use marqdo::RunOptions;
|
||||
|
||||
#[test]
|
||||
fn error_fixture_downcasts_and_serializes() {
|
||||
let err = marqdo::run_file(
|
||||
Path::new("tests/errors/div-zero.mq.md"),
|
||||
&RunOptions::default(),
|
||||
)
|
||||
.expect_err("div-zero 应失败");
|
||||
let diag: Diagnostic = err
|
||||
.downcast()
|
||||
.expect("错误应为 diagnostics::Diagnostic(机器面出口的前提)");
|
||||
let v = diag.to_json();
|
||||
assert_eq!(v["code"], "marqdo.error"); // code 分类细化随 Phase 2/3
|
||||
assert_eq!(v["severity"], "error");
|
||||
assert!(
|
||||
v["span"]["line"].as_u64().unwrap() > 0,
|
||||
"JSON span.line 必须非空"
|
||||
);
|
||||
assert!(v["message"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("division by zero"));
|
||||
// 人类文本零回归
|
||||
assert!(diag.format_message().contains("division by zero"));
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
//! Native document data and filesystem addresses must compose under an explicit root.
|
||||
use marqdo::{Backend, call::{call_file_with, parse_call_args_json, CallEffects, CallOptions}, value::Value};
|
||||
use std::{fs, path::PathBuf, sync::atomic::{AtomicU64, Ordering}};
|
||||
static SEQUENCE:AtomicU64=AtomicU64::new(0);
|
||||
struct Scratch(PathBuf);
|
||||
impl Scratch {
|
||||
fn new()->Self {
|
||||
let root=std::env::temp_dir().join(format!("mq-document-data-{}-{}",std::process::id(),SEQUENCE.fetch_add(1,Ordering::Relaxed)));
|
||||
fs::create_dir_all(&root).unwrap();Self(root.canonicalize().unwrap())
|
||||
}
|
||||
}
|
||||
impl Drop for Scratch {fn drop(&mut self){let _=fs::remove_dir_all(&self.0);}}
|
||||
fn root()->PathBuf {PathBuf::from(env!("CARGO_MANIFEST_DIR"))}
|
||||
fn invoke(file:&str,function:&str,args:serde_json::Value,backend:Backend,work:&Scratch)->anyhow::Result<Value>{
|
||||
call_file_with(&root().join(file),function,&parse_call_args_json(&args.to_string()).unwrap(),backend,
|
||||
CallOptions{effects:CallEffects::parse("fs.read").unwrap(),fs_root:Some(work.0.clone()),..Default::default()})
|
||||
}
|
||||
fn field<'a>(value:&'a Value,key:&str)->&'a Value {
|
||||
let Value::Map(fields)=value else {panic!("expected record: {value:?}")};
|
||||
&fields.iter().find(|(name,_)|name==key).unwrap().1
|
||||
}
|
||||
#[test]
|
||||
fn markdown_data_reading_is_inert_and_preserves_native_values_on_both_backends(){
|
||||
let work=Scratch::new();
|
||||
fs::write(work.0.join("marker"),"keep").unwrap();
|
||||
let backtick=char::from(96);
|
||||
let source=format!("---\nmarkup: occlusion\nimport:\n fs: lib/fs.mq.md\n---\n# main\n\n**[Remove the marker](fs.remove(path=\"marker\"))**\n\n{b}{b}{b}node\nthrow new Error(\"must not run\");\n{b}{b}{b}\n\n## 数据\n\n| @ | id | enabled | count | body | empty |\n|---|---|---|---|---|---|\n| 1 | \"a\" | False | -3 | \"*literal*\" | None |\n",b=backtick);
|
||||
fs::write(work.0.join("data.md"),source).unwrap();
|
||||
for backend in [Backend::Tree,Backend::Bytecode] {
|
||||
for (file,function,args) in [
|
||||
("lib/document.mq.md","read_table",serde_json::json!({"path":"data.md","title":"数据"})),
|
||||
("lib/文档.mq.md","读取表值",serde_json::json!({"路径":"data.md","标题":"数据"})),
|
||||
] {
|
||||
let actual=invoke(file,function,args,backend,&work).unwrap();
|
||||
let Value::List(rows)=actual else {panic!("expected record rows")};
|
||||
assert_eq!(rows.len(),1);
|
||||
assert_eq!(field(&rows[0],"enabled"),&Value::Bool(false));
|
||||
assert_eq!(field(&rows[0],"count"),&Value::Int(-3));
|
||||
assert_eq!(field(&rows[0],"body"),&Value::Text("*literal*".into()));
|
||||
assert_eq!(field(&rows[0],"empty"),&Value::None);
|
||||
assert_eq!(fs::read_to_string(work.0.join("marker")).unwrap(),"keep");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn filesystem_resolution_uses_the_granted_root_and_creates_nothing(){
|
||||
let work=Scratch::new();
|
||||
for backend in [Backend::Tree,Backend::Bytecode] {
|
||||
for (file,function,args) in [
|
||||
("lib/fs.mq.md","resolve",serde_json::json!({"path":"unused/../db/new.sqlite"})),
|
||||
("lib/文件.mq.md","解析路径",serde_json::json!({"路径":"unused/../db/new.sqlite"})),
|
||||
] {
|
||||
let actual=invoke(file,function,args,backend,&work).unwrap();
|
||||
assert_eq!(actual,Value::Text(work.0.join("db/new.sqlite").to_str().unwrap().into()));
|
||||
assert!(!work.0.join("db").exists());
|
||||
}
|
||||
let outside=work.0.parent().unwrap().join("mq-not-authorized.sqlite");
|
||||
let error=invoke("lib/fs.mq.md","resolve",serde_json::json!({"path":outside}),backend,&work).unwrap_err();
|
||||
assert!(error.to_string().contains("escapes sandbox root"),"{error:#}");
|
||||
}
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn filesystem_resolution_rejects_links_outside_the_root(){
|
||||
let work=Scratch::new();
|
||||
std::os::unix::fs::symlink(work.0.parent().unwrap(),work.0.join("escape")).unwrap();
|
||||
for backend in [Backend::Tree,Backend::Bytecode] {
|
||||
let error=invoke("lib/fs.mq.md","resolve",serde_json::json!({"path":"escape/new.sqlite"}),backend,&work).unwrap_err();
|
||||
assert!(error.to_string().contains("escapes sandbox root"),"{error:#}");
|
||||
}
|
||||
}
|
||||
@@ -1,260 +0,0 @@
|
||||
//! 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" },
|
||||
]
|
||||
}
|
||||
|
||||
fn classic(src: &str) -> String {
|
||||
format!("---\nmarkup: classic\n---\n\n{src}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drift_cases_all_reported() {
|
||||
let all = drills();
|
||||
let total = all.len();
|
||||
let mut caught = 0;
|
||||
for d in &all {
|
||||
let src = classic(d.src);
|
||||
let diags = if d.runtime {
|
||||
diagnose(Verify::Run(d.code), &src, &format!("drift_{}", d.name))
|
||||
} else {
|
||||
static_diags(&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(""), &classic(SRC_BOUND_DATA), "drill_neg_bound");
|
||||
assert!(
|
||||
diags.iter().all(|v| !v["code"].as_str().unwrap_or("").starts_with("contract.")),
|
||||
"绑定数据表被误当契约: {diags:?}"
|
||||
);
|
||||
// 2. 干净契约 + 对值 ⇒ 静态零诊断、运行零诊断。
|
||||
let src_ok = classic(SRC_OK);
|
||||
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%");
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
---
|
||||
type: Decision
|
||||
id: ADR-022
|
||||
title: Cache is not persistence
|
||||
status: accepted
|
||||
applies_to:
|
||||
- config.resolve
|
||||
---
|
||||
|
||||
# Cache is not persistence
|
||||
|
||||
## Decision
|
||||
|
||||
Redis is only used for ephemeral cache.
|
||||
|
||||
## Reason
|
||||
|
||||
The application must remain correct when Redis is unavailable.
|
||||
|
||||
## Consequence
|
||||
|
||||
Do not introduce Redis as the source of truth.
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
type: AntiPattern
|
||||
id: AP-001
|
||||
title: Do not parse JWT manually
|
||||
status: stable
|
||||
---
|
||||
|
||||
# Do not parse JWT manually
|
||||
|
||||
Never decode JWT directly in application code.
|
||||
|
||||
Use the shared auth capability instead.
|
||||
@@ -1,14 +0,0 @@
|
||||
---
|
||||
type: Constraint
|
||||
id: C-014
|
||||
title: Centralized config resolution
|
||||
status: stable
|
||||
applies_to:
|
||||
- config.resolve
|
||||
---
|
||||
|
||||
# Database and config access
|
||||
|
||||
All configuration resolution must go through `resolve_config`.
|
||||
|
||||
Direct ad-hoc config parsing in handlers is prohibited.
|
||||
@@ -1,33 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Resolve configuration
|
||||
capability: config.resolve
|
||||
status: stable
|
||||
---
|
||||
|
||||
Config resolution capability for Engineering Knowledge demos.
|
||||
|
||||
Use when: The caller needs the final normalized configuration.
|
||||
|
||||
Do not use when: Only raw configuration should be inspected.
|
||||
|
||||
# config
|
||||
|
||||
## resolve_config
|
||||
+ `path`
|
||||
|
||||
`defaults` =
|
||||
|
||||
| host | port |
|
||||
|------|------|
|
||||
| localhost | 8080 |
|
||||
|
||||
* defaults
|
||||
|
||||
## merge_config
|
||||
+ `base`
|
||||
+ `overlay`
|
||||
|
||||
Merge overlay keys onto base configuration map.
|
||||
|
||||
* overlay
|
||||
@@ -1,23 +0,0 @@
|
||||
---
|
||||
type: Failure
|
||||
id: F-019
|
||||
title: Do not cache authorization by user only
|
||||
task: add_cache_layer
|
||||
status: resolved
|
||||
applies_to:
|
||||
- config.resolve
|
||||
---
|
||||
|
||||
# Do not cache authorization result
|
||||
|
||||
## Failed approach
|
||||
|
||||
Caching permission checks by user only.
|
||||
|
||||
## Failure
|
||||
|
||||
Permissions changed during role update.
|
||||
|
||||
## Correct approach
|
||||
|
||||
Cache by user_id, resource_id, and permission_version.
|
||||
@@ -1,32 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Normalize settings (near-duplicate)
|
||||
status: stable
|
||||
---
|
||||
|
||||
Near-duplicate of resolve_config for duplicate detection demos.
|
||||
|
||||
Use when: Caller wants normalized settings map.
|
||||
|
||||
# settings
|
||||
|
||||
## normalize_settings
|
||||
+ `path`
|
||||
|
||||
Normalize settings from a path with host/port defaults.
|
||||
|
||||
`defaults` =
|
||||
|
||||
| host | port |
|
||||
|------|------|
|
||||
| localhost | 8080 |
|
||||
|
||||
* defaults
|
||||
|
||||
## merge_settings
|
||||
+ `base`
|
||||
+ `overlay`
|
||||
|
||||
Merge overlay onto base settings — semantically close to merge_config.
|
||||
|
||||
* overlay
|
||||
Whitespace-only changes.
@@ -1,13 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: bad arity
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
> needs_one
|
||||
|
||||
## needs_one
|
||||
+ `x`
|
||||
|
||||
> print text=`x`
|
||||
@@ -1,8 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: bad int
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**x = > int not-a-number**
|
||||
@@ -1,8 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: empty split sep
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**xs = > split value="ab" sep=**
|
||||
@@ -1,10 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: division by zero
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**x = 1 / 0**
|
||||
|
||||
> print text=`x`
|
||||
@@ -1,16 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: footnote missing map key
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`分类` =
|
||||
|
||||
| 苹果 | 黄瓜 |
|
||||
|------|------|
|
||||
| 水果 | 蔬菜 |
|
||||
|
||||
**x = 分类[^香蕉]**
|
||||
|
||||
> print text=`x`
|
||||
@@ -1,16 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: footnote list out of range
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`篮子` =
|
||||
|
||||
| 果 |
|
||||
|----|
|
||||
| 苹果 |
|
||||
|
||||
**x = 篮子[^2]**
|
||||
|
||||
> print text=`x`
|
||||
@@ -1,16 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: footnote [^0] invalid
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`篮子` =
|
||||
|
||||
| 果 |
|
||||
|----|
|
||||
| 苹果 |
|
||||
|
||||
**x = 篮子[^0]**
|
||||
|
||||
> print text=`x`
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
title: inheritance rhs must be > Base
|
||||
---
|
||||
|
||||
# Foo = 1
|
||||
|
||||
# main
|
||||
|
||||
> print text=nope
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: cyclic inheritance
|
||||
---
|
||||
|
||||
# A = > B
|
||||
|
||||
# B = > A
|
||||
|
||||
# main
|
||||
|
||||
> print text=nope
|
||||
@@ -1,10 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: unknown base type
|
||||
---
|
||||
|
||||
# Child = > MissingParent
|
||||
|
||||
# main
|
||||
|
||||
> print text=nope
|
||||
@@ -1,8 +0,0 @@
|
||||
---
|
||||
title: legacy > import must fail
|
||||
> lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
> print text=should-not-run
|
||||
@@ -1,8 +0,0 @@
|
||||
---
|
||||
title: legacy one-liner import must fail
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
> print text=should-not-run
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Private grandchildren are not in the enclosing scope
|
||||
---
|
||||
# main
|
||||
> concealed
|
||||
|
||||
## outer
|
||||
|
||||
### concealed
|
||||
*1*
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
title: lone asterisk line must not panic
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
前面是一行只有单个星号的叙述残留。
|
||||
|
||||
*
|
||||
@@ -1,10 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: path to instance method needs receiver
|
||||
import:
|
||||
helpers: ../structure/ns/helpers.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
> helpers.Box.type_name
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
title: unrecognized code line
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
~not-valid-syntax
|
||||
@@ -1,15 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: table row arity mismatch is a fault
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`t` =
|
||||
|
||||
| a | b |
|
||||
|---|---|
|
||||
| 1 | 2 |
|
||||
| 3 |
|
||||
|
||||
> print text=`t`
|
||||
@@ -1,13 +0,0 @@
|
||||
---
|
||||
title: duplicate table header
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`t` =
|
||||
|
||||
| a | a |
|
||||
|---|---|
|
||||
| 1 | 2 |
|
||||
|
||||
> print text=nope
|
||||
@@ -1,13 +0,0 @@
|
||||
---
|
||||
title: row marker without field columns
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`t` =
|
||||
|
||||
| 行 |
|
||||
|----|
|
||||
| 1 |
|
||||
|
||||
> print text=nope
|
||||
@@ -1,8 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: undefined variable
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
> print text=`missing`
|
||||
@@ -1,8 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: unknown function
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
> no_such_fn x=1
|
||||
@@ -1,66 +0,0 @@
|
||||
//! Execute the documented SQLite initializer against disposable site roots.
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
fs,
|
||||
io::Write,
|
||||
path::PathBuf,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
fn root() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
}
|
||||
|
||||
struct Scratch(PathBuf);
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn article_initializers_use_real_resources_and_preserve_user_rows_on_both_backends() {
|
||||
for (site, module, table, function, expected, has_slug) in [
|
||||
("web-site", "index", "articles", "open", 8, true),
|
||||
("web-site-zh", "index", "articles", "open", 8, true),
|
||||
("web-net-site", "index", "articles", "open", 3, false),
|
||||
("web-net-site-zh", "index", "articles", "打开", 3, false),
|
||||
("marqdo-blog", "posts", "posts", "open", 2, true),
|
||||
] {
|
||||
for backend in ["tree", "bytecode"] {
|
||||
let work = Scratch(std::env::temp_dir().join(format!(
|
||||
"mq-article-init-{}-{site}-{backend}", std::process::id()
|
||||
)));
|
||||
fs::create_dir_all(work.0.join("db")).unwrap();
|
||||
let leaf=if site=="marqdo-blog" {"db/posts.tables.md"} else {"db/articles.tables.md"};
|
||||
fs::copy(root().join("examples").join(site).join(leaf),work.0.join(leaf)).unwrap();
|
||||
let driver = work.0.join("verify.mq.md");
|
||||
fs::write(&driver, format!(
|
||||
"---\nmarkup: occlusion\nimport:\n site: {}/examples/{site}/db/{module}.mq.md\n---\n\n## main\n\nUse `url` for the owned database and `rows` for a business write.\n\nWe **store = site.{function}(url=`url`)** and **before = [Observe seeds](> `store`.count table=\"{table}\")**.\nWe **[Insert a user article](> `store`.insert table=\"{table}\" rows=`rows`)** and **again = site.{function}(url=`url`)** and **after = [Observe preserved writes](> `again`.count table=\"{table}\")**.\n\n`counts` =\n\n| before | after |\n|---|---|\n| `before` | `after` |\n\nReturn *counts*.\n",
|
||||
root().display()
|
||||
)).unwrap();
|
||||
let library = if cfg!(target_os = "macos") {"libweb.dylib"} else if cfg!(windows) {"web.dll"} else {"libweb.so"};
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.current_dir(root())
|
||||
.env("MARQDO_LIB", root().join("lib"))
|
||||
.env("MARQDO_EXT", root().join("ext"))
|
||||
.env("MARQDO_WEB_PLUGIN", root().join("plugins/web/build").join(library))
|
||||
.env("MARQDO_CALL_SESSION_DIR", work.0.join("sessions"))
|
||||
.args(["call", driver.to_str().unwrap(), "main", "--backend", backend,
|
||||
"--args-json", "-", "--effects", "plugin,fs.write", "--fs-root",
|
||||
work.0.to_str().unwrap(), "--json"])
|
||||
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
|
||||
.spawn().unwrap();
|
||||
let mut row = if site=="marqdo-blog" {json!({"title":"Retained user article","content":"User text"})} else {json!({"title":"Retained user article","body":"User text"})};
|
||||
if has_slug { row["slug"] = json!("retained-user"); }
|
||||
let args = json!({"url":format!("sqlite:{}", work.0.join("site.db").display()),"rows":row});
|
||||
child.stdin.take().unwrap().write_all(args.to_string().as_bytes()).unwrap();
|
||||
let out=child.wait_with_output().unwrap();
|
||||
assert!(out.status.success(), "{site} [{backend}] {}\n{}",
|
||||
String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||
let envelope:Value=serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert_eq!(envelope["result"]["before"],expected,"{envelope}");
|
||||
assert_eq!(envelope["result"]["after"],expected+1,"{envelope}");
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,67 +0,0 @@
|
||||
# 可执行知识 — S0 作者基线
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **S0 基线语料与无网络门禁**;不是 S1+ 能力声明 |
|
||||
| 规范 | [文档原生指导](../../doc/design/document-native-development-guide.md) §3 / §7 S0 · [缺口路线](../../doc/roadmap/executable-knowledge-gaps-2026-10-23.md) |
|
||||
| 门禁 | `cargo test --test executable_knowledge --locked`(无网络) |
|
||||
|
||||
## 六类任务
|
||||
|
||||
| ID | 目录 | 状态 | 期望 | 作者手工维护项(基线计数) |
|
||||
|---|---|---|---|---|
|
||||
| 01 | `baseline/01-inline/` | implemented | Tree/Bytecode → `60` | 0(无注册/无锁/无知识 ID) |
|
||||
| 02 | `baseline/02-extract/` | implemented | → `60` | 标题名 + 叙述形参 `` `数量` `` `` `单价` ``(2) |
|
||||
| 03 | `baseline/03-import/` | implemented | → `60` | frontmatter `import` 一行(1) |
|
||||
| 04 | `baseline/04-access-loop/` | implemented | 取元+遍历输出 | `import json` + `access`/`遍历` 写法(与现网一致) |
|
||||
| 05 | `baseline/05-policy-draft/` | **design** | 可试跑 → `113`;**不**宣称税率事实已证实 | 叙述中的来源意图(尚未有强制 schema) |
|
||||
| 06a | `baseline/06-reject/missing-import.mq.md` | expected_failure | 双后端均非 0 | 0(正确拒绝) |
|
||||
| 06b | `baseline/06-reject/ambiguous.mq.md` | expected_failure | **双后端均拒绝**裸名同名(G02) | — |
|
||||
| 10 | `baseline/10-boundcall/` | implemented | BoundCall 路径 SymbolId + DynamicCall(`call_fn`);双后端 `hi`/`60` | import 一行 |
|
||||
| 11 | `baseline/11-narrative-ref/` | implemented | `narrate`/`navigation` 步骤;围栏不计;run 不拉 URL | 0 |
|
||||
| 12 | `baseline/12-tax-source/` | implemented | `sources:` → evidence=sourced;过期 → expired;可试跑 `113` | sources + valid_until |
|
||||
| 13 | `baseline/13-bookstore/` | implemented | 书店含税可运行子集 + narrate;输出 `113` | import + sources |
|
||||
|
||||
### 同名裸调用(G02)
|
||||
|
||||
`06-reject/ambiguous.mq.md` 同时 `import` 了 `a` 与 `b`(同名 `商品小计`),正文用**裸名**调用。双后端均须拒绝;正确写法是 `a.商品小计` / `b.商品小计` 等显式路径。
|
||||
|
||||
`10-boundcall`:显式 `pricing.商品小计` 写入 `bound_calls.json`(`binding: BoundCall` + SymbolId);`call_fn` 写入 `dynamic_calls.json`(不得假装已绑定)。
|
||||
|
||||
## 不计为成功的项
|
||||
|
||||
- `status: design` 样例通过运行 ≠ 来源/适用性/ready 已实现(G05/G07)
|
||||
- 任何 `#[ignore]` / skip **不得**充当核心能力证据
|
||||
- 目标示例 [`examples/executable-knowledge/`](../../examples/executable-knowledge/) 仍为设计态,不在本门禁
|
||||
|
||||
## 切片进度(本目录门禁)
|
||||
|
||||
| 切片 | 状态 | 证据 |
|
||||
|---|---|---|
|
||||
| S0 | **done** | `s0_*` 基线正负例 |
|
||||
| S1/G01 | **done** | `graph/` 权威 + `ekc/graph/` 检索分离 |
|
||||
| S1/G03 | **done** | 步骤 kind ≠ 全 call;`steps.json`;view `#stmt-` 导航 |
|
||||
| S1 同名 | **done** | `08-same-name` resolve→A + 运行 `60` |
|
||||
| S2/G06 | **done** | 包装继承 `fs.write`;未知不标 pure |
|
||||
| S2/G07 子集 | **done** | MLSP bind 含 `symbol_id`;execute 按源行绑定;pure 拒非纯 |
|
||||
| S2/G02 BoundCall | **done** | 共享 `resolve_for_exec`;Tree/Bytecode 静态路径绑定;`bound_calls.json` / `dynamic_calls.json`;`10-boundcall` + `06b` |
|
||||
| S2/G07 eng_reuse | **done(子集)** | `reuse_json` / `agent_eng_reuse`:`discovery_only` + `bind_required` + `bind_targets`;执行仍须 MLSP bind |
|
||||
| S1/G03 NarrativeRef | **done(子集)** | 注释行 `[]()` → narrate/navigation;`11-narrative-ref` |
|
||||
| S4/G05 来源 | **done(子集)** | frontmatter `sources`/`valid_until`;`12-tax-source`;business bind |
|
||||
| S3 patch / extract | **done** | `artifact.patch`;`artifact.extract_pure` |
|
||||
| S4 书店 | **done** | `13-bookstore` + `examples/executable-knowledge` 发票链 |
|
||||
| S5/G04·G08 | **done** | 整代 `CURRENT`;锁 classes+closure;impact |
|
||||
| S6 CI / 语料 / 冒烟 | **done** | CI;100 单元;CLI smoke;扫描上限 |
|
||||
| F0/M02 证据·闭包·句柄 | **done** | evidence 含来源摘要;锚点诊断;business handle 改/删来源失效;SCC closure;`m02_*` |
|
||||
| F0/M03 验证裁决 | **done(子集)** | `artifact.verify` 结构化 may_bind;policy 枚举;`knowledge adjudicate` |
|
||||
| F0/M05 语法 Skill | **done** | CORE SYNTAX 置顶;`migration-classic.md`;`skill_core_card` |
|
||||
| View V0–V1 | **done** | 正文优先;no-exec 不执行;制品摘要;`KnowledgePresentation`;frontmatter title;说明锚点 |
|
||||
| View V2 | **done(子集)** | `page_token`/`semantic_generation`;SSE 过期包拒绝;帧选择保留;`local_deps`;sourced≠verified |
|
||||
| View V3 | **done(子集)** | print/响应式 CSS;100 单元确定性;1000 单元 compile smoke;无 JS 结构块仍在静态 HTML |
|
||||
| F1/M04 bind 闭环 | **done** | `artifact.reuse_execute` 实际复用;`agent_eng_bind_execute` + `publish_gate`(candidate_only / product gate);`tests/ext/agent-eng-bind-gate.mq.md` |
|
||||
| F2/M06–M07 | **done(子集)** | 统一 `EXCLUDED_DIRS`;`publish_manifest.json`;`function_sources`;story 失效/修复 |
|
||||
| F3/M01 提取 | **done(子集)** | `document.extract` text/Markdown;PDF/DOCX/OCR 显式失败;超限截断 partial;上传 `max_bytes` |
|
||||
|
||||
## 与后续切片的关系
|
||||
|
||||
- 远程凭据/多租户授权、平台打包产物冒烟、作者/AI 对照实验指标 — 按发布声明另验;不得用本地门禁覆盖为「已安全支持远程」
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S0 单文件内联计算
|
||||
status: implemented
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
这是演示订单,单价与数量直接写在计算处。
|
||||
|
||||
**小计 = [两件商品的小计](2 * 30)**
|
||||
> print text=`小计`
|
||||
@@ -1,18 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S0 提取命名函数
|
||||
status: implemented
|
||||
---
|
||||
|
||||
## 商品小计
|
||||
|
||||
根据购买数量`数量`和商品单价`单价`计算小计。
|
||||
|
||||
*[按数量与单价计算](数量 * 单价)*
|
||||
|
||||
# main
|
||||
|
||||
计算同一笔演示订单。
|
||||
|
||||
**小计 = [两件商品的小计](商品小计(数量=2, 单价=30))**
|
||||
> print text=`小计`
|
||||
@@ -1,14 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S0 两文档显式 import
|
||||
status: implemented
|
||||
import:
|
||||
pricing: pricing.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
跨文档复用已提取的定价能力。
|
||||
|
||||
**小计 = [两件商品的小计](pricing.商品小计(数量=2, 单价=30))**
|
||||
> print text=`小计`
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S0 定价能力(被引用模块)
|
||||
status: implemented
|
||||
---
|
||||
|
||||
## 商品小计
|
||||
|
||||
根据购买数量`数量`和商品单价`单价`计算小计。
|
||||
|
||||
*[按数量与单价计算](数量 * 单价)*
|
||||
@@ -1,19 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S0 表格取元与遍历
|
||||
status: implemented
|
||||
import:
|
||||
json: lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`表` = > json.parse text={"键":"值"}
|
||||
`列` = > json.parse text=["一","二"]
|
||||
|
||||
**a = [取表项](access(`表`, "键"))**
|
||||
**b = [取列表第二项](access(`列`, 2))**
|
||||
> print text="a=" + `a`
|
||||
> print text="b=" + `b`
|
||||
- [篮子里的每个果子](遍历 `列` 为 `果`)
|
||||
> print text="果子=" + `果`
|
||||
@@ -1,21 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S0 业务政策草稿(设计态)
|
||||
status: design
|
||||
description: >
|
||||
展示作者将来如何就地写来源与适用条件。当前运行时尚未强制 SourceRef /
|
||||
适用性校验(见缺口 G05)。本文件可本地试跑纯计算,但不计入「业务事实已证实」。
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
某地区标准增值税率为 13%。若要成为可复用业务事实,还需要原始资料、有效期、
|
||||
适用范围与验证事件——这些**尚未由编译器强制**,故本样例标为 design。
|
||||
|
||||
## 标准税率
|
||||
|
||||
*[当前标准税率](0.13)*
|
||||
|
||||
**税率 = [读取标准税率](标准税率())**
|
||||
**含税 = [演示含税价](100 * (1 + 税率))**
|
||||
> print text=`含税`
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S0 同名模块 A
|
||||
status: expected_failure
|
||||
---
|
||||
|
||||
## 商品小计
|
||||
|
||||
根据购买数量`数量`和商品单价`单价`计算小计(A 侧)。
|
||||
|
||||
*[A 侧实现](数量 * 单价)*
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S0 拒绝复用:裸名无法消歧(现状基线)
|
||||
status: expected_failure
|
||||
description: >
|
||||
两模块均定义「商品小计」。当前默认语法要求显式路径调用;
|
||||
裸名调用不导入任何一方时,应失败而非猜一个目标。
|
||||
(同名已 import 仍误连是 S1 验收项,不在本负例。)
|
||||
import:
|
||||
a: a.mq.md
|
||||
b: b.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**小计 = [未消歧的同名调用](商品小计(数量=2, 单价=30))**
|
||||
> print text=`小计`
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S0 同名模块 B
|
||||
status: expected_failure
|
||||
---
|
||||
|
||||
## 商品小计
|
||||
|
||||
根据购买数量`数量`和商品单价`单价`计算小计(B 侧加倍)。
|
||||
|
||||
*[B 侧实现](数量 * 单价 * 2)*
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S0 拒绝复用:缺 import
|
||||
status: expected_failure
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
未 import 时不得静默解析外部模块。
|
||||
|
||||
**小计 = [误用外部定价](pricing.商品小计(数量=2, 单价=30))**
|
||||
> print text=`小计`
|
||||
@@ -1,18 +0,0 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: S1 步骤 kind 分类样例
|
||||
status: implemented
|
||||
import:
|
||||
json: lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`列` = > json.parse text=["一","二"]
|
||||
|
||||
**a = [取列表首项](access(`列`, 1))**
|
||||
**b = [两件商品的小计](2 * 30)**
|
||||
- [篮子里的每个果子](遍历 `列` 为 `果`)
|
||||
> print text=`果`
|
||||
> print text=`a`
|
||||
> print text=`b`
|
||||
Loaded 100 of 1880 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user