From 5f66f04d90f06b77fe22bf153791b7945e21bb3f Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 00:06:14 +0800 Subject: [PATCH] test: gate Tool v1 dispatch on frozen RC.1 and RC.2 releases Refs #1 --- README.md | 8 +- docs/ARCHITECTURE.md | 2 +- docs/PROTOCOL_BASELINE.md | 20 +- docs/VALIDATION.md | 21 ++ docs/validation/rc2-control-flow.json | 132 +++++++++++++ scripts/validate-control-flow.py | 219 +++++++++++++++++++++ src/alignment/semantic.rs | 8 + src/rules/supplemental.rs | 8 +- tests/rc2_pipeline.rs | 267 ++++++++++++++++++++++++++ tool.json | 2 +- 10 files changed, 670 insertions(+), 17 deletions(-) create mode 100644 docs/validation/rc2-control-flow.json create mode 100755 scripts/validate-control-flow.py create mode 100644 tests/rc2_pipeline.rs diff --git a/README.md b/README.md index 4d8a9d7..d50c767 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # marqdo-lint -`marqdo-lint` 是面向 Marqdo `.mq.md` 可执行文档的独立可读性检查工具。它把真实 Markdown AST 与公开 Analysis v2 对齐,检查分支、循环、叙述和说明的阅读质量,而不重新解释语言语义。 +`marqdo-lint` 是面向 Marqdo `.mq.md` 可执行文档的独立可读性检查工具。它把真实 Markdown AST 与公开 Analysis v2/v3 对齐,检查分支、循环、叙述和说明的阅读质量,而不重新解释语言语义。 ## 当前基线 -- Marqdo 3.0.0-rc.1,核心审阅提交 `f7a5a7b0163bf5229ed09adfffd892f9899e6667` +- 冻结 Marqdo `3.0.0-rc.1` 和 `3.0.0-rc.2`,对应发布提交见 [协议基线](docs/PROTOCOL_BASELINE.md) - Markdown Profile `marqdo.md.v1` -- Analysis v2 与 CLI Tool v1 +- Analysis v2/v3 与 CLI Tool v1 - Rust 1.89 或更新版本 ## 构建 @@ -15,7 +15,7 @@ cargo build --locked ``` -运行测试时需要兼容的冻结核心,并通过 `MARQDO_BIN` 指定其绝对路径。工具只调用公开的 `inspect --ast --json` 和 `check --emit`,不链接核心私有 crate。 +运行测试时需要兼容的冻结核心,并通过 `MARQDO_BIN` 指定其绝对路径。工具通过 `--version`、`inspect --ast --json` 和 `check --json --emit` 读取公开信息。双核心发布门禁见 [验收记录](docs/VALIDATION.md)。 ## 使用 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 839429f..e053c25 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -13,7 +13,7 @@ SourceSnapshot ── MarkdownTree ──┐ - `input`:调用公开 CLI、校验协议、读取真实 AST/Analysis,并在 AST 不可用时提供严格同配置的文档级 comrak 降级。 - `model`:保存精确字节、半开 byte span、标题段、列表项、执行载体和静态语义节点。 -- `alignment`:通过 span、文档顺序和语义嵌套对齐执行与阅读结构;关联不唯一时停止相关判断。 +- `alignment` 为每个函数按源码 span 索引执行载体,按语句体路径匹配有序分支臂、嵌套控制以及最近循环目标。关联不唯一时,函数保留可独立确认的文档诊断。 - `engine`:为每个函数复用同一份结构对齐和度量,并组装诊断。 - `rules`:稳定 ID、元数据与纯检测逻辑。规则不各自调用 CLI,也不分别实现输出。 - `metrics`:函数级叙述比例和解释覆盖,不把文字长度当成正确性证明。 diff --git a/docs/PROTOCOL_BASELINE.md b/docs/PROTOCOL_BASELINE.md index b67a289..880f761 100644 --- a/docs/PROTOCOL_BASELINE.md +++ b/docs/PROTOCOL_BASELINE.md @@ -1,22 +1,24 @@ # 协议基线 -本仓库是独立的 `marqdo-lint` 实现,不是 Marqdo 核心的一部分。 +`marqdo-lint` 通过独立发布的 Marqdo 可执行文件取得公开协议数据。 | 项目 | 固定值 | |---|---| -| 核心审阅提交 | `f7a5a7b0163bf5229ed09adfffd892f9899e6667` | -| 核心产品版本 | `3.0.0-rc.1` | +| Marqdo `3.0.0-rc.1` | `f7a5a7b0163bf5229ed09adfffd892f9899e6667` | +| Marqdo `3.0.0-rc.2` | `9149ee40a48fcda692c5c112f66c465487d13dfb` | | Markdown Profile | `marqdo.md.v1`,comrak `=1.0.0` | -| Analysis | `marqdo.analysis`,schema version 2 | +| Analysis | `marqdo.analysis`,schema version 2 或 3 | | 外部工具 | `marqdo.cli-tool`,schema version 1 | | Lint 输出 | `marqdo.lint`,schema version 1 | -实现只读取源码并调用 `marqdo inspect --ast --json`、`marqdo check --json --emit`。不得链接核心私有 crate,不得使用 `inspect --ir` 代替公开 Analysis,也不得根据旧版列表规则推断控制流。 +`MarqdoRunner` 调用 `--version`、`inspect FILE --ast --json` 和 `check FILE --json --emit PATH`。Canonical AST 提供 Markdown 容器,公开 Analysis 提供执行结构。读端保留原始 JSON 用于安全修复校验,在语句边界沿 `body` 和 `arms[].body` 遍历。模块使用包实例与相对路径标识,工作区文档按源码摘要校验,span 使用所属模块的原始 UTF-8 字节。 -验收使用从上述提交构建并冻结的核心二进制。PATH 中较早的核心不能代替该二进制。核心二进制、源码提交和所有验证输入的摘要记录在验证报告中。 +Tool v1 manifest 声明 `analysis: [2, 3]`。`MARQDO_PROTOCOL_ANALYSIS` 表示最高共同版本,读端根据每个工件的 `schema_version` 解码。RC.1 输出 v2。RC.2 的多臂分支仍可用 v2,只要任一投影模块含有 `break` 或 `continue`,核心便输出 v3。[Analysis v3 合同](https://git.cflmy.cn/cflmy/marqdo-cli/src/tag/v3.0.0-rc.2/spec/analysis-v3.md) · [Tool v1 协商](https://git.cflmy.cn/cflmy/marqdo-cli/src/tag/v3.0.0-rc.2/spec/tool-v1.md) + +[双核心验收记录](VALIDATION.md) 保存两个冻结发布工件的摘要、测试用例和独立 Tool 安装结果。 ## 失败状态 -- `complete`:公开 Analysis 可用,语义关联规则可以运行。 -- `analysis_incomplete`:语言检查失败或语义关联不唯一。工具保留核心诊断,只运行有充分依据的文档级规则,不把该状态当成没有违规。 -- 协议不兼容、配置错误和工具 I/O 错误属于工具失败,不伪装成风格诊断。 +- `complete` 表示公开 Analysis 与源码已可靠对齐,可以运行语义规则和完整度量。 +- `analysis_incomplete` 表示语言检查失败或关联不唯一。报告保留核心诊断或对齐原因,相关函数继续运行有充分依据的文档规则。 +- 不兼容版本、无效的必要协议结构、错误源码摘要、非法字节范围或 UTF-8 边界会作为工具错误返回退出码 `2`。 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 837caf7..0a5dcfc 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,5 +1,26 @@ # RFC-LINT-0001 验收记录 +## 工单 #1 的双核心验收 + +使用正式发布的 Linux x86_64 归档,先核验归档 SHA-256,再分别解包。RC.1 和 RC.2 各运行一次 `cargo test --locked`,每次报告 64 项通过。各版本专属的场景在对应版本上执行。[机器可读记录](validation/rc2-control-flow.json) 保存源码提交、归档摘要、二进制前后摘要、输入摘要和实测退出码。 + +| 核心 | 发布归档 SHA-256 | 工具协商 | 实测 Analysis 工件 | +|---|---|---|---| +| RC.1 | `9f49036ada141871492ef721f08569c74fd2854b5e5d1bfc065ba4d812dcabc7` | 2 | v2 旧分支 | +| RC.2 | `e32e6426caf023fc813ebdbf5a171ec164ee2ffb843ae5594b8e7b9780f496ea` | 3 | v2 旧分支、`hello` 和四臂分支。v3 嵌套跳转、发行示例及作者示例 | + +两个核心都从临时工作目录安装同一个 `scripts/package-tool.sh` 生成的包,各自使用隔离注册目录。核心分发正确传递退出码 `0`、`1`、`2`,卸载后分发失败。`strace` 记录协商环境和子进程,Lint 实际调用 `--version`、`inspect FILE --ast --json`、`check FILE --json --emit PATH`。`marqdo.lint` v1 JSON 的状态和源码摘要通过校验。终端报告保留规则 ID,未完成的检查在 `--fail-on never` 下仍返回 `2`。 + +两版协议的安全修复均通过真实核心复检、dry run 与空白写回。改变分支臂归属或最近循环目标的候选得到 `MQD-SAFETY-001`,原始字节保持不变。回归测试还覆盖 RC.1 的旧默认臂 span 和同名变量,RC.2 显式空 `else`、跨 heading 诊断、导入模块提升工件版本,以及 BOM、CRLF、emoji 和错误 UTF-8 边界。 + +在仓库根目录运行发布门禁,传入两个已解包的核心绝对路径。门禁需要 Python 3.11+ 和 `strace`,并校验冻结二进制的 SHA-256。缺少任一核心会直接失败。 + +```sh +python3 scripts/validate-control-flow.py /absolute/rc1/marqdo /absolute/rc2/marqdo +``` + +## RC.1 初始验收 + 验收使用 Marqdo `3.0.0-rc.1`,从提交 `f7a5a7b0163bf5229ed09adfffd892f9899e6667` 的 Git 归档构建。工具调用、规则测试和应用试跑使用同一个核心二进制。[机器可读记录](validation/rfc-0001.json) 保存二进制、发布包、输入摘要、实际退出码和诊断 ID。 ## 本仓库验收 diff --git a/docs/validation/rc2-control-flow.json b/docs/validation/rc2-control-flow.json new file mode 100644 index 0000000..8fa7160 --- /dev/null +++ b/docs/validation/rc2-control-flow.json @@ -0,0 +1,132 @@ +{ + "lint_binary_sha256": "92ca782924c777c291a191c46c9f3a8129084b98b826c0d885a474dd0b180a87", + "tool_analysis_compatibility": [ + 2, + 3 + ], + "cores": { + "3.0.0-rc.1": { + "source_commit": "f7a5a7b0163bf5229ed09adfffd892f9899e6667", + "archive_sha256": "9f49036ada141871492ef721f08569c74fd2854b5e5d1bfc065ba4d812dcabc7", + "binary_sha256": "2fc5f74d8dd64a4a1b4617e630cb2af9fae5ba0ab769467c32ecb5a988894b6d", + "negotiated_analysis": 2, + "tests_passed": 64, + "binary_sha256_before": "2fc5f74d8dd64a4a1b4617e630cb2af9fae5ba0ab769467c32ecb5a988894b6d", + "tool": { + "install_exit": 0, + "remove_exit": 0, + "dispatch_after_remove_exit": 2, + "static_child_commands": [ + "--version", + "check FILE --json --emit PATH", + "inspect FILE --ast --json" + ], + "cases": { + "legacy-branches": { + "input_sha256": "dcc2c9869c5f2a53cff5a2c479e67143b9b0617ffe0b605bf920a7322d85aa3f", + "analysis_major": 2, + "analysis_status": "complete", + "exit": 0, + "format": "json" + }, + "style-warning": { + "input_sha256": "db86228a987c15eeadef1543c9780c717593aafce0ff0db9892524bd2eb5ef67", + "analysis_major": 2, + "analysis_status": "complete", + "exit": 1, + "format": "human", + "diagnostic": "MQD-BRANCH-001" + }, + "incomplete": { + "input_sha256": "eca6e049188fdd5dbc9519cb99f70bcd03fda66e1394b57c931f8e3029f18bc7", + "analysis_major": null, + "analysis_status": "analysis_incomplete", + "exit": 2, + "format": "json", + "diagnostic": "sem.unclosed_control" + } + } + }, + "binary_sha256_after": "2fc5f74d8dd64a4a1b4617e630cb2af9fae5ba0ab769467c32ecb5a988894b6d" + }, + "3.0.0-rc.2": { + "source_commit": "9149ee40a48fcda692c5c112f66c465487d13dfb", + "archive_sha256": "e32e6426caf023fc813ebdbf5a171ec164ee2ffb843ae5594b8e7b9780f496ea", + "binary_sha256": "5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b", + "negotiated_analysis": 3, + "tests_passed": 64, + "binary_sha256_before": "5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b", + "tool": { + "install_exit": 0, + "remove_exit": 0, + "dispatch_after_remove_exit": 2, + "static_child_commands": [ + "--version", + "check FILE --json --emit PATH", + "inspect FILE --ast --json" + ], + "cases": { + "legacy-branches": { + "input_sha256": "dcc2c9869c5f2a53cff5a2c479e67143b9b0617ffe0b605bf920a7322d85aa3f", + "analysis_major": 2, + "analysis_status": "complete", + "exit": 0, + "format": "json" + }, + "style-warning": { + "input_sha256": "db86228a987c15eeadef1543c9780c717593aafce0ff0db9892524bd2eb5ef67", + "analysis_major": 2, + "analysis_status": "complete", + "exit": 1, + "format": "human", + "diagnostic": "MQD-BRANCH-001" + }, + "incomplete": { + "input_sha256": "eca6e049188fdd5dbc9519cb99f70bcd03fda66e1394b57c931f8e3029f18bc7", + "analysis_major": null, + "analysis_status": "analysis_incomplete", + "exit": 2, + "format": "json", + "diagnostic": "sem.unclosed_control" + }, + "release-hello": { + "input_sha256": "b5e715f5e11f3cc15fab550e93fb957b52a5fada382afbe89142ac543f896164", + "analysis_major": 2, + "analysis_status": "complete", + "exit": 0, + "format": "json" + }, + "multi-arm": { + "input_sha256": "92485c1da250e6658de4908bf4b49156b2094188d0aa02cb133c8388a116f3e0", + "analysis_major": 2, + "analysis_status": "complete", + "exit": 0, + "format": "json" + }, + "loop-jumps": { + "input_sha256": "d80d0b20f64e49679204c4adff7829e14199645e0a4ea14fb72289aa30b4aa4e", + "analysis_major": 3, + "analysis_status": "complete", + "exit": 0, + "format": "json" + }, + "release-control-flow": { + "input_sha256": "f9cf24e290551a20e8eb817170e3871c11cbb70a3d7ab6dfdc7205b4eadfcb31", + "analysis_major": 3, + "analysis_status": "complete", + "exit": 0, + "format": "json" + }, + "author-example": { + "input_sha256": "3f91893c57ce366443ac9f5a8372e12cc2bc85f5297f632c033b76138d433f86", + "analysis_major": 3, + "analysis_status": "complete", + "exit": 0, + "format": "json" + } + } + }, + "binary_sha256_after": "5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b" + } + } +} diff --git a/scripts/validate-control-flow.py b/scripts/validate-control-flow.py new file mode 100755 index 0000000..051a442 --- /dev/null +++ b/scripts/validate-control-flow.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Run the RC.1/RC.2 release gate using unpacked Linux release bundles.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + + +ROOT = Path(__file__).resolve().parents[1] +RELEASES = { + "3.0.0-rc.1": { + "source_commit": "f7a5a7b0163bf5229ed09adfffd892f9899e6667", + "archive_sha256": "9f49036ada141871492ef721f08569c74fd2854b5e5d1bfc065ba4d812dcabc7", + "binary_sha256": "2fc5f74d8dd64a4a1b4617e630cb2af9fae5ba0ab769467c32ecb5a988894b6d", + "negotiated_analysis": 2, + }, + "3.0.0-rc.2": { + "source_commit": "9149ee40a48fcda692c5c112f66c465487d13dfb", + "archive_sha256": "e32e6426caf023fc813ebdbf5a171ec164ee2ffb843ae5594b8e7b9780f496ea", + "binary_sha256": "5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b", + "negotiated_analysis": 3, + }, +} + + +class ValidationError(Exception): + pass + + +def require(condition, message): + if not condition: + raise ValidationError(message) + + +def sha256(path): + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def run(args, *, cwd=ROOT, env=None, expected=0): + result = subprocess.run(list(map(str, args)), cwd=cwd, env=env, capture_output=True, text=True) + if expected is not None and result.returncode != expected: + raise ValidationError( + f"{args}: expected exit {expected}, got {result.returncode}\n" + f"{result.stdout}{result.stderr}" + ) + return result + + +def validate_core(binary, version): + require(binary.is_file() and os.access(binary, os.X_OK), f"missing frozen core: {binary}") + digest = sha256(binary) + require(digest == RELEASES[version]["binary_sha256"], f"unexpected {version} binary SHA-256: {digest}") + require(run([binary, "--version"]).stdout.strip() == f"marqdo {version}", f"wrong version: {binary}") + return digest + + +def test_suite(binary): + env = dict(os.environ, MARQDO_BIN=str(binary)) + cached_cargo = ROOT / ".cache/cargo-home" + if cached_cargo.is_dir(): + env.setdefault("CARGO_HOME", str(cached_cargo)) + output = run(["cargo", "test", "--locked"], env=env).stdout + counts = re.findall(r"test result: ok\. (\d+) passed; 0 failed", output) + require(counts and sum(map(int, counts)) > 0, "cargo test reported no passing tests") + return sum(map(int, counts)) + + +def trace_dispatch(strace, binary, work, env, name, args, major, expected): + trace = work / f"{name}.trace" + result = run( + [strace, "-f", "-qq", "-v", "-s", "4096", "-e", "trace=execve", "-o", trace, binary, "lint", *args], + cwd=work, env=env, expected=expected, + ) + core_calls = [] + tool_calls = [] + for line in trace.read_text().splitlines(): + match = re.search(r'execve\(("(?:[^"\\]|\\.)*"), (\[(?:"(?:[^"\\]|\\.)*"(?:, )?)*\]),', line) + if not match: + continue + program = Path(json.loads(match[1])) + argv = json.loads(match[2])[1:] + if program == binary: + core_calls.append(argv) + elif program.name == "marqdo-lint": + tool_calls.append(line) + else: + raise ValidationError(f"{name}: unexpected executed program {program}") + require(len(tool_calls) == 1, f"{name}: expected one packaged lint process") + require(f'"MARQDO_PROTOCOL_ANALYSIS={major}"' in tool_calls[0], f"{name}: incorrect negotiated Analysis major") + require(core_calls and core_calls[0][0] == "lint", f"{name}: missing core dispatch process") + child_commands = set() + for argv in core_calls[1:]: + if argv == ["--version"]: + child_commands.add("--version") + elif len(argv) == 4 and argv[0] == "inspect" and argv[2:] == ["--ast", "--json"]: + child_commands.add("inspect FILE --ast --json") + elif len(argv) == 5 and argv[0] == "check" and argv[2:4] == ["--json", "--emit"]: + child_commands.add("check FILE --json --emit PATH") + else: + raise ValidationError(f"{name}: unexpected core child command {argv}") + require(len(child_commands) == 3, f"{name}: missing static child command: {child_commands}") + return result.stdout, sorted(child_commands) + + +def validate_bundle(strace, binary, version, bundle, directory): + work = directory / "independent-cwd" + work.mkdir(parents=True) + home = directory / "home" + home.mkdir() + env = { + "PATH": "/usr/bin:/bin", + "LANG": "C.UTF-8", + "HOME": str(home), + "MARQDO_TOOL_HOME": str(directory / "registry"), + } + manifest = bundle / "tool.json" + run([binary, "tool", "install", manifest], cwd=work, env=env) + tools = run([binary, "tool", "list", "--json"], cwd=work, env=env).stdout + require('"lint"' in tools, f"{version}: lint missing after tool install") + major = RELEASES[version]["negotiated_analysis"] + cases = [ + ("legacy-branches", ROOT / "tests/fixtures/golden/branches.mq.md", 2, 0, "json", "never", None), + ("style-warning", ROOT / "examples/bad/branch-single-item.mq.md", 2, 1, "human", "warning", "MQD-BRANCH-001"), + ("incomplete", ROOT / "tests/fixtures/golden/invalid-control.mq.md", None, 2, "json", "never", "sem.unclosed_control"), + ] + if major == 3: + cases.extend([ + ("release-hello", binary.parent / "examples/hello.mq.md", 2, 0, "json", "never", None), + ("multi-arm", ROOT / "tests/fixtures/rc2/multi-arm.mq.md", 2, 0, "json", "never", None), + ("loop-jumps", ROOT / "tests/fixtures/rc2/loop-jumps.mq.md", 3, 0, "json", "never", None), + ("release-control-flow", binary.parent / "examples/control-flow.mq.md", 3, 0, "json", "never", None), + ("author-example", ROOT / "examples/good/control-flow-rc2.mq.md", 3, 0, "json", "warning", None), + ]) + evidence = {} + for name, original, expected_major, status, output_format, fail_on, diagnostic in cases: + source = work / f"{name}.mq.md" + shutil.copyfile(original, source) + if expected_major is not None: + artifact = work / f"{name}.analysis.json" + run([binary, "check", source.name, "--json", "--emit", artifact], cwd=work, env=env) + actual = json.loads(artifact.read_text())["schema_version"] + require(actual == expected_major, f"{name}: incorrect artifact major {actual}") + text, commands = trace_dispatch( + strace, binary, work, env, name, + [source.name, "--format", output_format, "--fail-on", fail_on], major, status, + ) + digest = sha256(source) + analysis_status = "analysis_incomplete" if status == 2 else "complete" + if output_format == "json": + report = json.loads(text) + require(report["schema"] == "marqdo.lint" and report["schema_version"] == 1, f"{name}: unexpected report protocol") + require(report["analysis_status"] == analysis_status, f"{name}: unexpected report state") + require(report["source"]["digest"] == f"sha256:{digest}", f"{name}: source digest mismatch") + if diagnostic: + require(diagnostic in text, f"{name}: missing diagnostic {diagnostic}") + evidence[name] = { + "input_sha256": digest, + "analysis_major": expected_major, + "analysis_status": analysis_status, + "exit": status, + "format": output_format, + **({"diagnostic": diagnostic} if diagnostic else {}), + } + run([binary, "tool", "remove", "lint"], cwd=work, env=env) + tools = run([binary, "tool", "list", "--json"], cwd=work, env=env).stdout + require('"lint"' not in tools, f"{version}: lint remains after uninstall") + removed = run([binary, "lint", "legacy-branches.mq.md"], cwd=work, env=env, expected=None) + require(removed.returncode != 0, f"{version}: removed lint still dispatches") + return {"install_exit": 0, "remove_exit": 0, "dispatch_after_remove_exit": removed.returncode, + "static_child_commands": commands, "cases": evidence} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("rc1", type=Path, help="frozen marqdo 3.0.0-rc.1 executable") + parser.add_argument("rc2", type=Path, help="frozen marqdo 3.0.0-rc.2 executable") + parser.add_argument("--report", type=Path, help="write JSON evidence to this path") + args = parser.parse_args() + try: + binaries = dict(zip(RELEASES, (args.rc1.resolve(), args.rc2.resolve()))) + before = {version: validate_core(binary, version) for version, binary in binaries.items()} + strace = shutil.which("strace") + require(strace, "strace is required to verify the Tool v1 subprocess contract") + results = {} + for version, binary in binaries.items(): + passed = test_suite(binary) + print(f"{version}: cargo test --locked, {passed} tests passed", flush=True) + results[version] = {**RELEASES[version], "tests_passed": passed, "binary_sha256_before": before[version]} + with tempfile.TemporaryDirectory(prefix="marqdo-lint-release-") as scratch: + bundle = Path(scratch) / "bundle" + run([ROOT / "scripts/package-tool.sh", bundle]) + manifest = json.loads((bundle / "tool.json").read_text()) + require(manifest["compatibility"]["analysis"] == [2, 3], "unexpected bundle compatibility") + evidence = { + "lint_binary_sha256": sha256(bundle / "bin/marqdo-lint"), + "tool_analysis_compatibility": manifest["compatibility"]["analysis"], + "cores": results, + } + for version, binary in binaries.items(): + results[version]["tool"] = validate_bundle(strace, binary, version, bundle, Path(scratch) / version) + after = sha256(binary) + require(after == before[version], f"{version}: core binary changed during gate") + results[version]["binary_sha256_after"] = after + print(f"{version}: packaged Tool v1 install, dispatch, exit codes and removal passed", flush=True) + if args.report: + args.report.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n") + except (OSError, ValidationError, ValueError, KeyError) as error: + parser.exit(1, f"release gate failed: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/src/alignment/semantic.rs b/src/alignment/semantic.rs index 43e1586..b725a20 100644 --- a/src/alignment/semantic.rs +++ b/src/alignment/semantic.rs @@ -136,6 +136,14 @@ impl<'a, 'source> Matcher<'a, 'source> { .is_some_and(|control| self.tree.controls[control].kind == ControlKind::Loop), StatementKind::Break => located.jump == Some(JumpKind::Break), StatementKind::Continue => located.jump == Some(JumpKind::Continue), + StatementKind::Expression => { + let value = &statement.value["value"]; + // RC.1 could emit these bare identifiers as variable expressions. + located.ordinary + || (located.jump.is_some() + && value["kind"] == "variable" + && value["name"].as_str() == Some(located.carrier.payload.trim())) + } _ => located.ordinary, }; let primary = index.at(statement.span).filter(eligible); diff --git a/src/rules/supplemental.rs b/src/rules/supplemental.rs index 4cfbd63..f2d385f 100644 --- a/src/rules/supplemental.rs +++ b/src/rules/supplemental.rs @@ -97,7 +97,11 @@ pub fn check_heading_boundary( .filter(|diagnostic| { matches!( diagnostic.code.as_str(), - "sem.unmatched_else" | "sem.unmatched_end" + "sem.unmatched_else" + | "sem.unmatched_else_if" + | "sem.unmatched_end" + | "sem.break_outside_loop" + | "sem.continue_outside_loop" ) }) .find_map(|diagnostic| { @@ -117,7 +121,7 @@ pub fn check_heading_boundary( .name; diagnostics.push( Diagnostic::new("MQD-KNOW-001", markdown.nodes[heading.node].span) - .with_message("核心报告控制块未闭合,后续标题段的 else/end 无法关闭它") + .with_message("核心报告控制块未闭合,后续标题段的控制载体无法关联到该控制块") .with_related(opener.span) .with_related(related.span) .with_function(name), diff --git a/tests/rc2_pipeline.rs b/tests/rc2_pipeline.rs new file mode 100644 index 0000000..10e5c43 --- /dev/null +++ b/tests/rc2_pipeline.rs @@ -0,0 +1,267 @@ +use std::{ + fs, + path::{Path, PathBuf}, + process::Command, +}; + +use marqdo_lint::{ + alignment::{align_function, JumpKind}, + input::{AnalysisStatus, MarqdoRunner, ProjectInput}, + model::SourceSnapshot, +}; +use serde_json::Value; + +fn core(required: &str) -> Option { + let path = std::env::var_os("MARQDO_BIN").map(PathBuf::from)?; + let output = Command::new(&path).arg("--version").output().unwrap(); + (String::from_utf8(output.stdout).unwrap().trim() == required).then_some(path) +} + +fn lint(core: &Path, source: &Path) -> (i32, Vec, String) { + let output = Command::new(env!("CARGO_BIN_EXE_marqdo-lint")) + .env("MARQDO_BIN", core) + .arg(source) + .args(["--format", "json", "--fail-on", "never"]) + .output() + .unwrap(); + ( + output.status.code().unwrap(), + output.stdout, + String::from_utf8(output.stderr).unwrap(), + ) +} + +#[test] +fn rc1_bare_identifiers_remain_ordinary_expressions() { + let Some(core) = core("marqdo 3.0.0-rc.1") else { + return; + }; + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("legacy.mq.md"); + fs::write( + &path, + "## @exec main\n\n**break = 1**\n\n`break`\n\n*return break*\n", + ) + .unwrap(); + let (status, output, stderr) = lint(&core, &path); + assert_eq!(status, 0, "{stderr}"); + let report: Value = serde_json::from_slice(&output).unwrap(); + assert_eq!(report["analysis_status"], "complete"); + assert_eq!(report["metrics"]["functions"][0]["statement_count"], 3); +} + +#[test] +fn rc2_offsets_use_utf8_bytes_and_only_standalone_jumps_are_control() { + let Some(core) = core("marqdo 3.0.0-rc.2") else { + return; + }; + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("unicode.mq.md"); + let source = "\u{feff}## @exec main\n\n正文讨论跳转与读数 😀。\n\n**continue = 1**\n\n**call_result = break(1)**\n\n> **while false**:引用中的循环。\n>\n> *continue*\n>\n> `end`\n\n*return continue + continue_work(call_result)*\n\n[惰性链接 `break`](https://example.invalid)\n\n```text\n`break`\n```\n\n### @knowledge 惰性说明\n\n`continue` 与 **break**\n\n## @exec break\n\n`params(x: Int)`\n\n*return x*\n\n## @exec continue_work\n\n`params(x: Int)`\n\n*return x*\n".replace('\n', "\r\n"); + fs::write(&path, &source).unwrap(); + let runner = MarqdoRunner::discover(Some(&core)).unwrap(); + let project = ProjectInput::load(&path, &runner).unwrap(); + assert_eq!( + project.analysis_status, + AnalysisStatus::Complete, + "{}", + project.core_output + ); + assert_eq!(project.analysis.as_ref().unwrap().schema_version, 3); + let document = &project.documents[0]; + let module = document.module.as_ref().unwrap(); + let function = module + .functions + .iter() + .find(|f| f.local_name == "main") + .unwrap(); + let tree = align_function(&document.markdown, function); + assert!(tree.complete, "{:?}", tree.issues); + let [jump] = tree.jumps.as_slice() else { + panic!("expected one jump") + }; + assert_eq!(jump.kind, JumpKind::Continue); + assert_eq!(jump.carrier.span.start, source.find("*continue*").unwrap()); + assert_eq!( + document.source.slice(jump.carrier.span).unwrap(), + "*continue*" + ); + assert!(module.calls.iter().any(|call| call["target"] + .as_str() + .is_some_and(|id| id.ends_with("::break")))); + assert!(module.calls.iter().any(|call| call["target"] + .as_str() + .is_some_and(|id| id.ends_with("::continue_work")))); +} + +#[test] +fn rc2_imported_jump_promotes_the_project_and_offsets_remain_module_local() { + let Some(core) = core("marqdo 3.0.0-rc.2") else { + return; + }; + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("index.mq.md"); + let left = directory.path().join("left.mq.md"); + let right = directory.path().join("right.mq.md"); + fs::write(&path, "---\nimport:\n left: './left.mq.md'\n right: './right.mq.md'\n---\n\n## @exec main\n\n计算两个模块的返回值。\n\n*return left.helper() + right.helper()*\n").unwrap(); + fs::write( + &left, + "## @exec helper\n\n`while false`\n\n*break*\n\n`end`\n\n*return 1*\n", + ) + .unwrap(); + fs::write(&right, "## @exec helper\n\n*return 2*\n").unwrap(); + let runner = MarqdoRunner::discover(Some(&core)).unwrap(); + let project = ProjectInput::load(&path, &runner).unwrap(); + assert_eq!( + project.analysis_status, + AnalysisStatus::Complete, + "{}", + project.core_output + ); + assert_eq!(project.analysis.as_ref().unwrap().schema_version, 3); + assert_eq!(project.documents.len(), 3); + let report_for = |path: &Path| { + project + .documents + .iter() + .find(|document| document.source.path == path) + .unwrap() + }; + let left_id = &report_for(&left).module.as_ref().unwrap().functions[0]; + let right_id = &report_for(&right).module.as_ref().unwrap().functions[0]; + assert_ne!(left_id.id, right_id.id); + assert_eq!(left_id.heading_span, right_id.heading_span); + assert_eq!( + left_id.body[0]["span"]["start"], + right_id.body[0]["span"]["start"] + ); + let (status, output, stderr) = lint(&core, &path); + assert_eq!(status, 0, "{stderr}"); + let report: Value = serde_json::from_slice(&output).unwrap(); + let documents = report["reports"].as_array().unwrap(); + for source in [&path, &left, &right] { + let snapshot = SourceSnapshot::load(source).unwrap(); + let document = documents + .iter() + .find(|doc| doc["source"]["digest"] == snapshot.digest) + .unwrap(); + assert_eq!(document["analysis_status"], "complete"); + let jump = document["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|d| d["id"] == "MQD-STYLE-001"); + assert_eq!(jump, source == &left); + } +} + +#[test] +fn rc2_core_errors_keep_locations_and_exit_two_even_at_never_threshold() { + let Some(core) = core("marqdo 3.0.0-rc.2") else { + return; + }; + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("invalid.mq.md"); + for (source, code, point) in [ + ("`else if true`\n", "sem.unmatched_else_if", ":3:1:"), + ("`break`\n", "sem.break_outside_loop", ":3:1:"), + ( + "`while true`\n\n### 下一段\n\n`continue`\n\n`end`\n", + "sem.continue_outside_loop", + ":7:1:", + ), + ] { + fs::write(&path, format!("## @exec main\n\n{source}")).unwrap(); + let (status, output, stderr) = lint(&core, &path); + assert_eq!(status, 2, "{stderr}"); + let report: Value = serde_json::from_slice(&output).unwrap(); + assert_eq!(report["analysis_status"], "analysis_incomplete"); + let core_output = report["core_output"].as_str().unwrap(); + assert!( + core_output + .lines() + .any(|line| line.contains(code) && line.contains(point)), + "{core_output}" + ); + assert!(report["metrics"]["functions"] + .as_array() + .unwrap() + .is_empty()); + assert!(report["diagnostics"] + .as_array() + .unwrap() + .iter() + .all(|d| !d["id"].as_str().unwrap().starts_with("MQD-BRANCH") + && !d["id"].as_str().unwrap().starts_with("MQD-LOOP"))); + } +} + +#[cfg(unix)] +#[test] +fn public_protocol_failures_cannot_be_hidden_by_never_threshold() { + use std::os::unix::fs::PermissionsExt; + + let Some(core) = std::env::var_os("MARQDO_BIN") else { + return; + }; + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("multi-arm.mq.md"); + let proxy = directory.path().join("core-proxy"); + let source = include_str!("fixtures/rc2/multi-arm.mq.md"); + fs::write(&path, source).unwrap(); + fs::write( + directory.path().join("core-path"), + PathBuf::from(core) + .canonicalize() + .unwrap() + .as_os_str() + .as_encoded_bytes(), + ) + .unwrap(); + fs::write(&proxy, "#!/bin/sh\nset -eu\nbase=$(dirname \"$0\")\ncase \"$1\" in\n check) cp \"$base/projection.json\" \"$5\" ;;\n *) exec \"$(cat \"$base/core-path\")\" \"$@\" ;;\nesac\n").unwrap(); + fs::set_permissions(&proxy, fs::Permissions::from_mode(0o755)).unwrap(); + let raw: Value = + serde_json::from_str(include_str!("fixtures/rc2/multi-arm.analysis.json")).unwrap(); + let mut major = raw.clone(); + major["schema_version"] = 999.into(); + let mut digest = raw.clone(); + digest["modules"][0]["source_digest"] = "0".repeat(64).into(); + let mut utf8 = raw.clone(); + utf8["modules"][0]["functions"][0]["body"][0]["arms"][1]["span"]["start"] = + (source.find('首').unwrap() + 1).into(); + let mut v2_jump = raw.clone(); + v2_jump["modules"][0]["functions"][0]["body"][0]["arms"][1]["body"][0]["kind"] = "break".into(); + for (artifact, error) in [ + (major, "999"), + (digest, "源码摘要"), + (utf8, "UTF-8"), + (v2_jump, "Analysis v2"), + ] { + fs::write( + directory.path().join("projection.json"), + serde_json::to_vec(&artifact).unwrap(), + ) + .unwrap(); + let (status, output, stderr) = lint(&proxy, &path); + assert_eq!(status, 2, "{stderr}"); + assert!(output.is_empty()); + assert!(stderr.contains(error), "{stderr}"); + } + let mut duplicate = raw; + duplicate["modules"][0]["functions"][0]["body"][0]["arms"][2]["condition_span"] = + duplicate["modules"][0]["functions"][0]["body"][0]["arms"][1]["condition_span"].clone(); + fs::write( + directory.path().join("projection.json"), + serde_json::to_vec(&duplicate).unwrap(), + ) + .unwrap(); + let (status, output, _) = lint(&proxy, &path); + assert_eq!(status, 2); + let report: Value = serde_json::from_slice(&output).unwrap(); + assert_eq!(report["analysis_status"], "analysis_incomplete"); + assert!(report["notices"][0].as_str().unwrap().contains("span 重复")); + assert!(report["metrics"]["functions"] + .as_array() + .unwrap() + .is_empty()); +} diff --git a/tool.json b/tool.json index 23cb920..dd08d28 100644 --- a/tool.json +++ b/tool.json @@ -7,6 +7,6 @@ "entrypoint": "bin/marqdo-lint", "compatibility": { "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2] + "analysis": [2, 3] } }