426 lines
16 KiB
Python
Executable File
426 lines
16 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Single-core rc.4 acceptance gate for marqdo-lint.
|
|
|
|
The script verifies the pinned marqdo-cli v3.0.0-rc.4 archive/binary, exercises
|
|
one `check --emit` entry path, the packaged Tool revision 1 lifecycle, positive
|
|
rule/fix behavior, JSON report schema, negative fail-closed cases and emits a
|
|
machine-readable acceptance manifest.
|
|
"""
|
|
|
|
import argparse
|
|
import datetime
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
CLI_SOURCE_SHA = "452e9a32bd9e40dba427d4180691c58bab74449e"
|
|
CLI_ARCHIVE_SHA = "9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8"
|
|
CLI_BINARY_SHA = "a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e"
|
|
ANALYSIS_SCHEMA_SHA = "03929300cec53bb29309a933f74c1aa807943bfd7dbecc80cf4f7f54d037eb30"
|
|
PLATFORM = "linux-x86_64-glibc2.39"
|
|
MANIFEST_SCHEMA = "marqdo.lint.acceptance"
|
|
MANIFEST_VERSION = 1
|
|
|
|
|
|
class GateError(Exception):
|
|
pass
|
|
|
|
|
|
def sha256_file(path):
|
|
with Path(path).open("rb") as stream:
|
|
return hashlib.file_digest(stream, "sha256").hexdigest()
|
|
|
|
|
|
def sha256_bytes(data):
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def run(command, *, cwd=ROOT, env=None, expected=0, timeout=900):
|
|
result = subprocess.run(
|
|
[str(item) for item in command],
|
|
cwd=cwd,
|
|
env=env,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=timeout,
|
|
)
|
|
if expected is not None and result.returncode != expected:
|
|
raise GateError(
|
|
f"command failed ({result.returncode}): {' '.join(map(str, command))}\n"
|
|
f"{result.stdout}\n{result.stderr}"
|
|
)
|
|
return result
|
|
|
|
|
|
def cargo_command():
|
|
return os.environ.get("CARGO", "cargo")
|
|
|
|
|
|
def test_count(stdout):
|
|
counts = re.findall(r"test result: ok\. (\d+) passed; 0 failed", stdout)
|
|
return sum(int(value) for value in counts)
|
|
|
|
|
|
def lint_binary():
|
|
candidate = os.environ.get("MARQDO_LINT_BIN")
|
|
if candidate:
|
|
return Path(candidate).resolve()
|
|
for profile in ("debug", "release"):
|
|
path = ROOT / "target" / profile / "marqdo-lint"
|
|
if path.is_file():
|
|
return path
|
|
raise GateError("marqdo-lint binary is missing; build it before running the gate")
|
|
|
|
|
|
def validate_core(binary):
|
|
if not binary.is_file() or not os.access(binary, os.X_OK):
|
|
raise GateError(f"missing executable core: {binary}")
|
|
digest = sha256_file(binary)
|
|
if digest != CLI_BINARY_SHA:
|
|
raise GateError(f"unexpected rc.4 binary SHA-256: {digest}")
|
|
output = run([binary, "--version"]).stdout.strip()
|
|
if output != "marqdo 3.0.0-rc.4":
|
|
raise GateError(f"wrong core version: {output!r}")
|
|
return digest
|
|
|
|
|
|
def gate(manifest, gate_id, command, function):
|
|
try:
|
|
detail = function()
|
|
manifest["gates"][gate_id] = {
|
|
"state": "PASS",
|
|
"command": command,
|
|
"exit_code": 0,
|
|
}
|
|
print(f"{gate_id}: PASS", flush=True)
|
|
return detail
|
|
except (GateError, OSError, ValueError, KeyError, subprocess.TimeoutExpired) as error:
|
|
manifest["gates"][gate_id] = {
|
|
"state": "FAIL",
|
|
"command": command,
|
|
"exit_code": 1,
|
|
"detail": str(error)[:4000],
|
|
}
|
|
print(f"{gate_id}: FAIL - {error}", flush=True)
|
|
return None
|
|
|
|
|
|
def g01(manifest):
|
|
run([ROOT / "scripts/check-no-legacy.sh"])
|
|
|
|
|
|
def g02(manifest):
|
|
run([cargo_command(), "fmt", "--all", "--", "--check"])
|
|
run([cargo_command(), "clippy", "--all-targets", "--", "-D", "warnings"])
|
|
result = run([cargo_command(), "test", "--locked"], timeout=1800)
|
|
count = test_count(result.stdout)
|
|
if count == 0:
|
|
raise GateError("cargo test reported no passing tests")
|
|
manifest["tests_passed"] = count
|
|
|
|
|
|
def g03(manifest):
|
|
binary = manifest["_core"]
|
|
work = Path(tempfile.mkdtemp(prefix="marqdo-lint-install-"))
|
|
try:
|
|
bundle = work / "bundle"
|
|
run([ROOT / "scripts/package-tool.sh", bundle], timeout=1800)
|
|
env = dict(os.environ)
|
|
env.update(
|
|
{
|
|
"MARQDO_TOOL_HOME": str(work / "registry"),
|
|
"PATH": "/usr/bin:/bin",
|
|
"LANG": "C.UTF-8",
|
|
"HOME": str(work / "home"),
|
|
}
|
|
)
|
|
(work / "home").mkdir()
|
|
env.pop("MARQDO_BIN", None)
|
|
dispatch = work / "project"
|
|
dispatch.mkdir()
|
|
shutil.copyfile(
|
|
ROOT / "examples/nested/inventory.mq.md", dispatch / "inventory.mq.md"
|
|
)
|
|
shutil.copyfile(
|
|
ROOT / "examples/bad/branch-single-item.mq.md", dispatch / "bad.mq.md"
|
|
)
|
|
shutil.copyfile(
|
|
ROOT / "tests/fixtures/golden/invalid-control.mq.md", dispatch / "invalid.mq.md"
|
|
)
|
|
run([binary, "tool", "install", bundle / "tool.json"], env=env)
|
|
listed = run([binary, "tool", "list", "--json"], env=env).stdout
|
|
if '"lint"' not in listed:
|
|
raise GateError("lint is not listed after tool install")
|
|
run([binary, "lint", "inventory.mq.md", "--format", "json"], cwd=dispatch, env=env)
|
|
run(
|
|
[binary, "lint", "bad.mq.md", "--format", "human"],
|
|
cwd=dispatch,
|
|
env=env,
|
|
expected=1,
|
|
)
|
|
run(
|
|
[binary, "lint", "invalid.mq.md", "--format", "json", "--fail-on", "never"],
|
|
cwd=dispatch,
|
|
env=env,
|
|
expected=2,
|
|
)
|
|
run([binary, "tool", "remove", "lint"], env=env)
|
|
after = run(
|
|
[binary, "lint", "inventory.mq.md", "--format", "json"],
|
|
cwd=dispatch,
|
|
env=env,
|
|
expected=None,
|
|
)
|
|
if after.returncode == 0:
|
|
raise GateError("removed lint still dispatches")
|
|
manifest["lint_binary_sha256"] = f"sha256:{sha256_file(bundle / 'bin/marqdo-lint')}"
|
|
manifest["tool_bundle_digest"] = f"sha256:{sha256_file(bundle / 'tool.json')}"
|
|
finally:
|
|
shutil.rmtree(work, ignore_errors=True)
|
|
|
|
|
|
def g04(manifest):
|
|
binary = manifest["_core"]
|
|
lint = lint_binary()
|
|
env = dict(os.environ, MARQDO_BIN=str(binary))
|
|
positive = [
|
|
("inventory", ROOT / "examples/nested/inventory.mq.md"),
|
|
("multi-arm", ROOT / "tests/fixtures/control/multi-arm.mq.md"),
|
|
("loop-jumps", ROOT / "tests/fixtures/control/loop-jumps.mq.md"),
|
|
("knowledge", ROOT / "examples/knowledge/discount.mq.md"),
|
|
]
|
|
for name, path in positive:
|
|
result = run(
|
|
[lint, path, "--format", "json", "--fail-on", "never"],
|
|
env=env,
|
|
)
|
|
report = json.loads(result.stdout)
|
|
if report["analysis_status"] != "complete":
|
|
raise GateError(f"{name}: analysis is not complete")
|
|
work = Path(tempfile.mkdtemp(prefix="marqdo-lint-fix-"))
|
|
try:
|
|
for name in ("marqdo.yaml", "geometry.mq.md"):
|
|
shutil.copyfile(ROOT / "tests/fixtures/multi" / name, work / name)
|
|
source = (ROOT / "tests/fixtures/multi/index.mq.md").read_text()
|
|
dirty = source.replace("## @exec main\n\n", "## @exec main\n \t\n")
|
|
(work / "index.mq.md").write_text(dirty)
|
|
run(
|
|
[lint, "index.mq.md", "--fix", "safe", "--dry-run", "--format", "json", "--fail-on", "never"],
|
|
cwd=work,
|
|
env=env,
|
|
)
|
|
if (work / "index.mq.md").read_text() != dirty:
|
|
raise GateError("dry-run wrote the source")
|
|
run(
|
|
[lint, "index.mq.md", "--fix", "safe", "--format", "json", "--fail-on", "never"],
|
|
cwd=work,
|
|
env=env,
|
|
)
|
|
if (work / "index.mq.md").read_text() != source:
|
|
raise GateError("safe fix did not produce the expected idempotent result")
|
|
run(
|
|
[lint, "index.mq.md", "--format", "json", "--fail-on", "never"],
|
|
cwd=work,
|
|
env=env,
|
|
)
|
|
finally:
|
|
shutil.rmtree(work, ignore_errors=True)
|
|
|
|
|
|
def g05(manifest):
|
|
import jsonschema
|
|
|
|
binary = manifest["_core"]
|
|
lint = lint_binary()
|
|
env = dict(os.environ, MARQDO_BIN=str(binary))
|
|
schema = json.loads((ROOT / "schemas/marqdo-lint-v1.schema.json").read_text())
|
|
result = run(
|
|
[lint, ROOT / "examples/nested/inventory.mq.md", "--format", "json", "--fail-on", "never"],
|
|
env=env,
|
|
)
|
|
report = json.loads(result.stdout)
|
|
jsonschema.validate(report, schema)
|
|
if report["schema"] != "marqdo.lint" or report["schema_version"] != 1:
|
|
raise GateError("unexpected lint report protocol")
|
|
|
|
|
|
def g06(manifest):
|
|
binary = manifest["_core"]
|
|
lint = lint_binary()
|
|
artifact = json.loads(
|
|
(ROOT / "tests/fixtures/rc4/branches.analysis.json").read_text()
|
|
)
|
|
retired = json.loads(json.dumps(artifact))
|
|
for field in ("source", "document", "anchors"):
|
|
retired["modules"][0].pop(field, None)
|
|
bad_digest = json.loads(json.dumps(artifact))
|
|
bad_digest["modules"][0]["source_digest"] = "0" * 64
|
|
bad_revision = json.loads(json.dumps(artifact))
|
|
bad_revision["schema_version"] = 2
|
|
work = Path(tempfile.mkdtemp(prefix="marqdo-lint-negative-"))
|
|
try:
|
|
source = work / "branches.mq.md"
|
|
shutil.copyfile(ROOT / "tests/fixtures/golden/branches.mq.md", source)
|
|
proxy = work / "core-proxy"
|
|
proxy.write_text(
|
|
"#!/bin/sh\n"
|
|
"set -eu\n"
|
|
"case \"$1\" in\n"
|
|
" --version) echo 'marqdo 3.0.0-rc.4' ;;\n"
|
|
" check) case \"$4\" in --emit) cp \"$0.artifact\" \"$5\" ;; esac ;;\n"
|
|
" *) echo 'unsupported proxy command' >&2; exit 2 ;;\n"
|
|
"esac\n"
|
|
)
|
|
proxy.chmod(0o755)
|
|
for name, payload, needle in [
|
|
("retired", retired, "旧 revision 3"),
|
|
("digest", bad_digest, "source_digest"),
|
|
("revision", bad_revision, "revision 3"),
|
|
]:
|
|
(work / "core-proxy.artifact").write_text(
|
|
json.dumps(payload, ensure_ascii=False)
|
|
)
|
|
result = run(
|
|
[lint, source, "--format", "json", "--fail-on", "never"],
|
|
env=dict(os.environ, MARQDO_BIN=str(proxy)),
|
|
expected=None,
|
|
)
|
|
if result.returncode != 2:
|
|
raise GateError(f"{name}: expected exit 2, got {result.returncode}")
|
|
if needle not in result.stderr:
|
|
raise GateError(f"{name}: missing diagnostic {needle!r}: {result.stderr}")
|
|
tool = json.loads((ROOT / "tool.json").read_text())
|
|
old_tool = dict(tool)
|
|
old_tool["compatibility"] = {"marqdo": ">=3.0.0-rc.4,<4.0.0", "analysis": [3]}
|
|
old_manifest = work / "old-tool.json"
|
|
old_manifest.write_text(json.dumps(old_tool, ensure_ascii=False))
|
|
registry = work / "registry"
|
|
install = run(
|
|
[binary, "tool", "install", old_manifest],
|
|
env=dict(os.environ, MARQDO_TOOL_HOME=str(registry)),
|
|
expected=None,
|
|
)
|
|
if install.returncode == 0:
|
|
raise GateError("old tool manifest installed successfully")
|
|
if "compatibility" not in install.stderr:
|
|
raise GateError("old tool manifest error does not name compatibility")
|
|
finally:
|
|
shutil.rmtree(work, ignore_errors=True)
|
|
|
|
|
|
def g08(manifest):
|
|
banned = [
|
|
"双核心",
|
|
"Analysis v2/v3",
|
|
"compatibility 协商",
|
|
"RC" + "." + "1",
|
|
"RC" + "." + "2",
|
|
]
|
|
for name in [
|
|
"README.md",
|
|
"docs/PROTOCOL_BASELINE.md",
|
|
"docs/VALIDATION.md",
|
|
"docs/ARCHITECTURE.md",
|
|
"docs/CLI.md",
|
|
]:
|
|
text = (ROOT / name).read_text()
|
|
for phrase in banned:
|
|
if phrase in text:
|
|
raise GateError(f"{name}: contains retired phrase {phrase!r}")
|
|
|
|
|
|
def g09(manifest):
|
|
pipeline = ROOT / ".woodpecker/main.yml"
|
|
if not pipeline.is_file():
|
|
raise GateError("missing .woodpecker/main.yml")
|
|
text = pipeline.read_text()
|
|
for needle in ["check-no-legacy", "validate-control-flow", "cargo test --locked"]:
|
|
if needle not in text:
|
|
raise GateError(f"CI pipeline is missing {needle!r}")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("core", type=Path, help="unpacked marqdo 3.0.0-rc.4 executable")
|
|
parser.add_argument("--report", type=Path, help="acceptance manifest path")
|
|
args = parser.parse_args()
|
|
manifest = {
|
|
"schema": MANIFEST_SCHEMA,
|
|
"schema_version": MANIFEST_VERSION,
|
|
"lint_commit": run(["git", "rev-parse", "HEAD"]).stdout.strip(),
|
|
"lint_version": run([cargo_command(), "metadata", "--no-deps", "--format-version", "1"]).stdout
|
|
and json.loads(
|
|
run([cargo_command(), "metadata", "--no-deps", "--format-version", "1"]).stdout
|
|
)["packages"][0]["version"],
|
|
"lint_binary_sha256": None,
|
|
"tool_bundle_digest": None,
|
|
"cli_source_sha": CLI_SOURCE_SHA,
|
|
"cli_archive_sha256": f"sha256:{CLI_ARCHIVE_SHA}",
|
|
"cli_binary_sha256": f"sha256:{CLI_BINARY_SHA}",
|
|
"cli_binary_sha256_before": None,
|
|
"cli_binary_sha256_after": None,
|
|
"analysis_schema_sha256": f"sha256:{ANALYSIS_SCHEMA_SHA}",
|
|
"platform": PLATFORM,
|
|
"generated_utc": datetime.datetime.now(datetime.timezone.utc)
|
|
.replace(microsecond=0)
|
|
.isoformat()
|
|
.replace("+00:00", "Z"),
|
|
"gates": {},
|
|
"unverified": [
|
|
"G10 independent application trial: qdagent/qdqc pinned commits are not available in this workspace; result is analysis_incomplete semantics only, no false-positive rate claim."
|
|
],
|
|
}
|
|
try:
|
|
before = validate_core(args.core.resolve())
|
|
manifest["cli_binary_sha256_before"] = f"sha256:{before}"
|
|
manifest["_core"] = args.core.resolve()
|
|
os.environ["MARQDO_BIN"] = str(args.core.resolve())
|
|
gate(manifest, "G01", "scripts/check-no-legacy.sh", lambda: g01(manifest))
|
|
gate(manifest, "G02", "cargo fmt --check; cargo clippy -D warnings; cargo test --locked", lambda: g02(manifest))
|
|
gate(manifest, "G03", "scripts/package-tool.sh + tool install/list/dispatch/remove", lambda: g03(manifest))
|
|
gate(manifest, "G04", "lint positive rules and safe fix", lambda: g04(manifest))
|
|
gate(manifest, "G05", "lint JSON report vs schemas/marqdo-lint-v1.schema.json", lambda: g05(manifest))
|
|
gate(manifest, "G06", "negative protocol/artifact/tool cases fail closed", lambda: g06(manifest))
|
|
gate(manifest, "G07", "single-core rc.4 evidence manifest", lambda: None)
|
|
gate(manifest, "G08", "docs facts are rc.4-only", lambda: g08(manifest))
|
|
gate(manifest, "G09", "Woodpecker CI covers G01-G07", lambda: g09(manifest))
|
|
after = sha256_file(args.core.resolve())
|
|
manifest["cli_binary_sha256_after"] = f"sha256:{after}"
|
|
if after != before:
|
|
raise GateError("core binary changed during acceptance")
|
|
manifest["gates"]["G10"] = {
|
|
"state": "UNVERIFIED",
|
|
"command": "independent qdagent/qdqc trial",
|
|
"exit_code": None,
|
|
}
|
|
manifest.pop("_core", None)
|
|
report = args.report or (
|
|
ROOT / "docs/validation" / f"{CLI_SOURCE_SHA}.json"
|
|
)
|
|
report.parent.mkdir(parents=True, exist_ok=True)
|
|
report.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
|
|
failed = [
|
|
gate_id
|
|
for gate_id, value in manifest["gates"].items()
|
|
if value["state"] == "FAIL"
|
|
]
|
|
print("\n".join(f"{key}: {value['state']}" for key, value in manifest["gates"].items()))
|
|
print(f"manifest: {report}")
|
|
if failed:
|
|
print(f"FAILED gates: {', '.join(failed)}")
|
|
return 1
|
|
return 0
|
|
except (GateError, OSError, ValueError, KeyError, subprocess.TimeoutExpired) as error:
|
|
print(f"acceptance failed: {error}")
|
|
return 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|