test(web): probe the real Analysis contract for WEB-00

Add scripts/risk-probe.py and scripts/ci.sh: consume only the verified CLI's
public Analysis 3 for the research-workspace entry, its two component targets
and two negative fixtures. Verify the exact Knowledge H2 anchor/spans, the GFM
component table AST/header/cell links, references with candidate_path/fragment,
target anchor resolution with source digests, and that ordinary links and
missing anchors stay distinguishable facts.

The local candidate passes with no gaps, so WEB-DESIGN's Analysis dependency
needs no correction; no new CLI syntax/private field is requested. Record the
CLI/root identities, commands and unverified scope in the evidence document.

Refs cflmy/marqdo#6, cflmy/marqdo-ext-web#1
This commit was merged in pull request #3.
This commit is contained in:
cflmy committed 2026-11-27 02:27:42 +08:00
1 parent f70095d60a
commit df4324f3e3
4 files changed
+457 -1

No files matched your search

+388
View File
@@ -0,0 +1,388 @@
#!/usr/bin/env python3
"""WEB-00 W-M0: prove the public Analysis contract can bind the Web design model.
This probe consumes only the real CLI's public Analysis 3 (`check --emit`) and
never parses Markdown itself. It checks the facts `docs/WEB-DESIGN.md` depends
on:
* a design component is an exact Knowledge H2 with an anchor and spans;
* the `组件` retention table is a real GFM table in the AST, with the exact
header and one link per component cell;
* design links appear as Analysis references with `candidate_path` and
`fragment`, so Design never has to guess by label or filename;
* each candidate target resolves to a Knowledge H2 anchor in its own module
Analysis, with a source digest for identity;
* ordinary paragraph links and missing anchors stay distinguishable facts
(negative fixtures), so the contract's rejections are implementable.
Inputs are explicit: `--cli` names the verified CLI binary. The CLI digest and
platform are recorded in the evidence. The probe fails when a required fact is
missing; it does not claim a PASS from a substring or a mock.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
DEFAULT_ROOT = REPO / "examples" / "research-workspace"
ENTRY = "index.mq.md"
DESIGN_H2_ANCHOR = "工作台"
COMPONENTS_SECTION = "组件"
COMPONENTS_HEADER = ["行", "槽", "组件", "宽度"]
class ProbeError(Exception):
pass
class Probe:
def __init__(self, cli: Path, root: Path, work: Path):
self.cli = cli
self.root = root
self.work = work
self.checks: list[dict] = []
self.facts: dict = {}
self.inputs: dict[str, dict] = {}
# -- helpers -----------------------------------------------------------
def record(self, check_id: str, ok: bool, detail: str) -> bool:
self.checks.append({"id": check_id, "status": "PASS" if ok else "FAIL", "detail": detail})
return ok
def require(self, check_id: str, ok: bool, detail: str) -> None:
if not self.record(check_id, ok, detail):
raise ProbeError(f"{check_id}: {detail}")
def analyze(self, document: Path) -> dict:
out = self.work / (hashlib.sha256(str(document).encode()).hexdigest()[:16] + ".analysis.json")
result = subprocess.run(
[str(self.cli), "check", str(document), "--emit", str(out)],
cwd=str(REPO),
capture_output=True,
)
if result.returncode != 0:
raise ProbeError(
f"CLI check failed for {document} ({result.returncode}): "
f"{result.stderr.decode(errors='replace')}"
)
analysis = json.loads(out.read_text())
if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") != 3:
raise ProbeError(f"{document}: not public Analysis 3")
if len(analysis.get("modules", [])) != 1:
raise ProbeError(f"{document}: expected one analyzed module")
module = analysis["modules"][0]
try:
label = document.relative_to(self.root).as_posix()
except ValueError:
label = "fixture/" + document.name
self.inputs[label] = {
"source_digest": module["source_digest"],
"module_id": module["id"],
}
return module
@staticmethod
def text(module: dict, span: dict) -> str:
raw = module["source"].encode()
return raw[span["start"] : span["end"]].decode(errors="replace")
@staticmethod
def children(node: dict, kind: str):
for child in node.get("children") or []:
if child.get("kind") == kind:
yield child
yield from Probe.children(child, kind)
@staticmethod
def unit_by_anchor(module: dict, anchor: str) -> dict | None:
for entry in module.get("anchors", []):
if entry.get("anchor") == anchor:
return next(
(unit for unit in module["units"] if unit["id"] == entry["unit_id"]),
None,
)
return None
@staticmethod
def reference_for(module: dict, url: str, span: dict) -> dict | None:
for reference in module.get("references", []):
if reference.get("url") == url and reference.get("span") == span:
return reference
return None
# -- checks ------------------------------------------------------------
def check_cli_identity(self, expected_sha256: str | None) -> None:
version = subprocess.run([str(self.cli), "--version"], capture_output=True, text=True)
self.require("cli-version", version.returncode == 0 and bool(version.stdout.strip()), version.stdout.strip())
digest = "sha256:" + hashlib.sha256(self.cli.read_bytes()).hexdigest()
self.facts["cli"] = {
"path": str(self.cli),
"version": version.stdout.strip(),
"sha256": digest,
"platform": {"system": platform.system(), "machine": platform.machine()},
}
if expected_sha256:
self.require(
"cli-pinned-digest",
digest == expected_sha256,
f"CLI digest {digest} vs expected {expected_sha256}",
)
def check_entry(self) -> dict:
module = self.analyze(self.root / ENTRY)
self.require(
"entry-source-identity",
len(module.get("source_digest", "")) == 64,
f"source_digest={module.get('source_digest')}",
)
unit = self.unit_by_anchor(module, DESIGN_H2_ANCHOR)
self.require("design-unit-anchor", unit is not None, f"anchor {DESIGN_H2_ANCHOR!r}")
assert unit is not None
self.require(
"design-unit-shape",
unit.get("kind") == "knowledge"
and unit.get("level") == 2
and unit.get("heading_span")
and unit.get("span"),
f"unit kind/level/spans: {unit.get('kind')}/{unit.get('level')}/{bool(unit.get('heading_span'))}",
)
return module
def check_components_table(self, module: dict) -> tuple[dict, dict]:
section = next(
(
unit
for unit in module["units"]
if unit.get("name") == COMPONENTS_SECTION and unit.get("level") == 3
),
None,
)
self.require("components-section", section is not None, f"H3 {COMPONENTS_SECTION!r}")
assert section is not None
tables = [
node
for node in self.children(module["document"], "table")
if node["span"]["start"] >= section["span"]["start"]
and node["span"]["end"] <= section["span"]["end"]
]
self.require("components-table-is-ast", len(tables) == 1, f"{len(tables)} GFM table(s) in section")
table = tables[0]
rows = list(self.children(table, "table_row"))
self.require("components-table-rows", len(rows) >= 2, f"{len(rows)} rows")
header = rows[0]
self.require("components-table-header-row", header.get("header") is True, "first row is header")
header_cells = list(self.children(header, "table_cell"))
texts = [self.text(module, cell["span"]).strip() for cell in header_cells]
self.require(
"components-table-header",
texts == COMPONENTS_HEADER,
f"header cells {texts!r}",
)
self.facts["components_table"] = {
"span": table["span"],
"rows": len(rows),
"header": texts,
"alignments": table.get("alignments"),
}
return table, section
def check_component_links(self, module: dict, table: dict, section: dict) -> list[dict]:
rows = list(self.children(table, "table_row"))[1:]
self.require("component-rows-present", bool(rows), "no component rows")
links = []
for index, row in enumerate(rows, start=1):
cells = list(self.children(row, "table_cell"))
self.require("component-row-cells", len(cells) == 4, f"row {index}: {len(cells)} cells")
component_cell = cells[2]
cell_links = list(self.children(component_cell, "link"))
self.require("component-cell-one-link", len(cell_links) == 1, f"row {index}: {len(cell_links)} links")
link = cell_links[0]
cell_text = self.text(module, component_cell["span"])
link_text = self.text(module, link["span"])
self.require(
"component-cell-link-only",
cell_text.strip() == link_text.strip(),
f"row {index} cell content {cell_text!r}",
)
reference = self.reference_for(module, link["url"], link["span"])
self.require(
"component-link-has-reference",
reference is not None,
f"row {index}: reference for {link['url']}: {reference is not None}",
)
assert reference is not None
candidate = reference.get("candidate_path")
fragment = reference.get("fragment")
self.require(
"component-link-candidate",
bool(candidate) and bool(fragment) and not Path(candidate).is_absolute()
and ".." not in Path(candidate).parts,
f"row {index}: candidate_path={candidate!r} fragment={fragment!r}",
)
self.require(
"component-link-state",
reference.get("state") in ("not_loaded", "resolved"),
f"row {index}: state={reference.get('state')!r}",
)
links.append(
{
"row": index,
"url": link["url"],
"span": link["span"],
"cell_span": component_cell["span"],
"reference_state": reference.get("state"),
"candidate_path": candidate,
"fragment": fragment,
}
)
self.facts["design_links"] = links
return links
def check_target_anchors(self, links: list[dict]) -> None:
resolved = []
for link in links:
target = (self.root / link["candidate_path"]).resolve()
self.require(
"target-inside-root",
target.is_file() and str(target).startswith(str(self.root.resolve())),
f"{link['candidate_path']} exists inside --root: "
f"{target.is_file() and str(target).startswith(str(self.root.resolve()))}",
)
module = self.analyze(target)
unit = self.unit_by_anchor(module, link["fragment"])
self.require(
"target-anchor-resolves",
unit is not None and unit.get("kind") == "knowledge",
f"{link['candidate_path']}#{link['fragment']} did not resolve to a Knowledge H2",
)
resolved.append(
{
"candidate_path": link["candidate_path"],
"fragment": link["fragment"],
"target_module_id": module["id"],
"target_source_digest": module["source_digest"],
"target_unit_id": unit["id"],
}
)
self.facts["resolved_targets"] = resolved
def check_negative_fixtures(self) -> None:
fixtures = self.work / "negative"
fixtures.mkdir(parents=True, exist_ok=True)
(fixtures / "target.mq.md").write_text("# 目标页\n\n## @knowledge 目标组件\n\n正文。\n")
(fixtures / "plain-link.mq.md").write_text(
"# 普通文档\n\n## 正文\n\n见 [目标](target.mq.md#目标组件)。\n"
)
(fixtures / "missing-anchor.mq.md").write_text(
"## @knowledge 页面\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n"
"| 1 | a | [缺失](target.mq.md#不存在) | 1fr |\n"
)
plain = self.analyze(fixtures / "plain-link.mq.md")
plain_tables = list(self.children(plain["document"], "table"))
plain_refs = plain.get("references", [])
self.require(
"negative-plain-link-not-a-table",
not plain_tables and any(r.get("candidate_path") == "target.mq.md" for r in plain_refs),
"ordinary paragraph link must stay a normal reference, not a component table row",
)
missing = self.analyze(fixtures / "missing-anchor.mq.md")
missing_ref = next(
(r for r in missing.get("references", []) if r.get("fragment") == "不存在"), None
)
self.require(
"negative-missing-anchor-has-candidate",
missing_ref is not None and missing_ref.get("state") == "not_loaded",
"missing anchor must still expose candidate_path/fragment for a deterministic rejection",
)
self.facts["negative_fixtures"] = {
"plain_link": {"tables": len(plain_tables), "references": len(plain_refs)},
"missing_anchor": {
"state": missing_ref.get("state") if missing_ref else None,
"candidate_path": missing_ref.get("candidate_path") if missing_ref else None,
"fragment": missing_ref.get("fragment") if missing_ref else None,
},
}
def run(self, expected_sha256: str | None) -> dict:
self.check_cli_identity(expected_sha256)
module = self.check_entry()
table, section = self.check_components_table(module)
links = self.check_component_links(module, table, section)
self.check_target_anchors(links)
self.check_negative_fixtures()
gaps = []
facts = self.facts
if "components_table" not in facts:
gaps.append("Analysis does not expose the GFM table AST needed by the contract")
if "design_links" not in facts:
gaps.append("Analysis does not expose design link references with candidate_path/fragment")
if "resolved_targets" not in facts:
gaps.append("Analysis cannot resolve target Knowledge H2 anchors")
failures = [check for check in self.checks if check["status"] == "FAIL"]
repo_sha = None
if (REPO / ".git").exists():
repo_sha = subprocess.run(
["git", "-C", str(REPO), "rev-parse", "HEAD"], capture_output=True, text=True
).stdout.strip()
return {
"schema": "marqdo.web-analysis-probe",
"schema_version": 1,
"status": "PASS" if not failures and not gaps else "FAIL",
"repository": {"sha": repo_sha},
"inputs": self.inputs,
"facts": facts,
"checks": self.checks,
"gaps": gaps,
}
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cli", required=True)
parser.add_argument("--root", default=str(DEFAULT_ROOT))
parser.add_argument("--out", default=None)
parser.add_argument("--expected-cli-sha256", default=None)
parser.add_argument("--json", action="store_true")
args = parser.parse_args(argv)
cli = Path(args.cli).resolve()
if not cli.is_file():
print(f"risk-probe: error: no CLI executable at {cli}", file=sys.stderr)
return 2
work = Path(tempfile.mkdtemp(prefix="marqdo-web00-"))
try:
report = Probe(cli, Path(args.root).resolve(), work).run(
args.expected_cli_sha256
)
except ProbeError as error:
print(f"risk-probe: FAIL: {error}", file=sys.stderr)
return 1
finally:
shutil.rmtree(work, ignore_errors=True)
text = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
if args.out:
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(text)
if args.json:
print(text, end="")
else:
print(f"WEB-00 Analysis probe: {report['status']}")
for check in report["checks"]:
print(f" {check['status']} {check['id']}: {check['detail']}")
for gap in report["gaps"]:
print(f" GAP {gap}")
return 0 if report["status"] == "PASS" else 1
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))