This commit is contained in:
commit
f8b82d4143
94 files changed
+3905
-546
No files matched your search
@@ -0,0 +1,356 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Dependency-direction gate for the Engine / Host Contract / Native Host split.
|
||||
|
||||
Issue #13 / ADR-0071 replace the old "fixed crate count and fixed paths" check
|
||||
with a reviewed responsibility graph. This script reads Cargo's actual resolved
|
||||
metadata (not a grep over manifests) and enforces:
|
||||
|
||||
* the Engine crates reach no native host, sandbox, foreign, plugin-loader,
|
||||
worker, package or CLI dependency over normal/build edges;
|
||||
* ``marqdo-host-contract`` depends only on the neutral value/span types;
|
||||
* the native host never compiles against runtime/frontend/IR;
|
||||
* the plugin ABI crate carries no native loading (``libloading``) and the SDK
|
||||
carries no loader/worker/host edge;
|
||||
* the independent embedding consumer resolves the same neutral graph;
|
||||
* every workspace crate is in the reviewed allowlist below, with a stated
|
||||
responsibility. Adding a crate requires editing that list in the same change.
|
||||
|
||||
Dev-dependencies are reported and checked separately; they are never allowed to
|
||||
stand in for the real Engine build. The companion
|
||||
``check_engine_boundary.py`` builds and runs the real consumer and CLI.
|
||||
|
||||
Usage:
|
||||
python3 tools/ci/check_dependency_boundaries.py [--offline]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
CONSUMER_MANIFEST = REPO_ROOT / "tests" / "embedding" / "Cargo.toml"
|
||||
|
||||
# Reviewed responsibility allowlist. A new workspace crate must be added here
|
||||
# (with its responsibility and owner layer) in the same change that adds it.
|
||||
WORKSPACE_CRATES = {
|
||||
"marqdo-span": "engine: UTF-8 position and diagnostic base types",
|
||||
"marqdo-value": "engine: Value, RuntimeError and the one Value Wire encoding",
|
||||
"marqdo-expression": "engine: expression grammar",
|
||||
"marqdo-markdown": "engine: the only Markdown profile and AST",
|
||||
"marqdo-ir": "engine: IR, function identity and builtin inventory",
|
||||
"marqdo-frontend": "engine: document mapping, signatures and static binding",
|
||||
"marqdo-runtime": "engine: evaluator, control flow and Memory",
|
||||
"marqdo-host-contract": "engine: platform-neutral Host trait and runtime observation facts",
|
||||
"marqdo-host": "native host: capabilities, resources, OS adapters and trusted extension execution",
|
||||
"marqdo-sandbox": "native host support: OS isolation probe and strict launch",
|
||||
"marqdo-foreign": "native host support: controlled one-shot foreign kernels (F-A)",
|
||||
"marqdo-plugin-abi": "public contract: C ABI types, wire envelope and protocol errors",
|
||||
"marqdo-plugin-sdk": "public contract consumer: third-party plugin development helpers",
|
||||
"marqdo-worker-ipc": "shared plumbing: one bounded worker frame transport",
|
||||
"marqdo-provider-worker": "shipped worker: provider helper process",
|
||||
"marqdo-package": "product support: project manifest, lock and dependency resolution",
|
||||
"marqdo-cli": "composition root: arguments, prepare, commands, product projection",
|
||||
}
|
||||
|
||||
ENGINE_CRATES = [
|
||||
"marqdo-span",
|
||||
"marqdo-value",
|
||||
"marqdo-expression",
|
||||
"marqdo-markdown",
|
||||
"marqdo-ir",
|
||||
"marqdo-frontend",
|
||||
"marqdo-runtime",
|
||||
"marqdo-host-contract",
|
||||
]
|
||||
|
||||
FORBIDDEN_FOR_ENGINE = {
|
||||
"marqdo-host",
|
||||
"marqdo-sandbox",
|
||||
"marqdo-foreign",
|
||||
"marqdo-plugin-abi",
|
||||
"marqdo-plugin-sdk",
|
||||
"marqdo-provider-worker",
|
||||
"marqdo-worker-ipc",
|
||||
"marqdo-package",
|
||||
"marqdo-cli",
|
||||
"libloading",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"flate2",
|
||||
"regex",
|
||||
"glob",
|
||||
"getrandom",
|
||||
}
|
||||
|
||||
# Normal/build edges only; "dev" is reported but never used to justify a build.
|
||||
BUILD_KINDS = {None, "build"}
|
||||
|
||||
|
||||
class GateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def run_metadata(manifest: Path | None, offline: bool) -> dict:
|
||||
command = [cargo(), "metadata", "--format-version", "1", "--locked"]
|
||||
if manifest is not None:
|
||||
command += ["--manifest-path", str(manifest)]
|
||||
if offline:
|
||||
command += ["--offline"]
|
||||
result = subprocess.run(
|
||||
command, cwd=REPO_ROOT, capture_output=True, text=True, check=False
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise GateError(f"`{' '.join(command)}` failed:\n{result.stderr}")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def cargo() -> str:
|
||||
path = shutil.which("cargo")
|
||||
if path is None:
|
||||
raise GateError("cargo is not on PATH")
|
||||
return path
|
||||
|
||||
|
||||
def package_names(metadata: dict) -> dict[str, dict]:
|
||||
return {package["name"]: package for package in metadata["packages"]}
|
||||
|
||||
|
||||
def workspace_package_names(metadata: dict) -> set[str]:
|
||||
members = set(metadata.get("workspace_members", []))
|
||||
return {
|
||||
package["name"]
|
||||
for package in metadata["packages"]
|
||||
if package["id"] in members
|
||||
}
|
||||
|
||||
|
||||
def dependency_graph(metadata: dict) -> dict[str, dict[str, set[str]]]:
|
||||
"""Map package name -> {dependency name: {normal, build, dev}}."""
|
||||
names_by_id = {package["id"]: package["name"] for package in metadata["packages"]}
|
||||
graph: dict[str, dict[str, set[str]]] = {name: {} for name in names_by_id.values()}
|
||||
for node in metadata.get("resolve", {}).get("nodes", []):
|
||||
source = names_by_id.get(node["id"])
|
||||
if source is None:
|
||||
continue
|
||||
for dependency in node.get("deps", []):
|
||||
target = names_by_id.get(dependency.get("pkg"))
|
||||
if target is None:
|
||||
continue
|
||||
kinds = {
|
||||
kind.get("kind")
|
||||
for kind in dependency.get("dep_kinds", [{"kind": None}])
|
||||
}
|
||||
graph[source].setdefault(target, set()).update(kinds)
|
||||
return graph
|
||||
|
||||
|
||||
def reachable(graph: dict[str, dict[str, set[str]]], root: str, kinds: set) -> dict[str, str]:
|
||||
"""Return reachable package -> first path from root over selected edge kinds."""
|
||||
seen: dict[str, str] = {root: root}
|
||||
queue = [root]
|
||||
while queue:
|
||||
current = queue.pop()
|
||||
for target, edge_kinds in graph.get(current, {}).items():
|
||||
if not (edge_kinds & kinds):
|
||||
continue
|
||||
if target in seen:
|
||||
continue
|
||||
seen[target] = f"{seen[current]} -> {target}"
|
||||
queue.append(target)
|
||||
return seen
|
||||
|
||||
|
||||
def direct_build_dependencies(graph: dict[str, dict[str, set[str]]], root: str) -> set[str]:
|
||||
return {
|
||||
target
|
||||
for target, edge_kinds in graph.get(root, {}).items()
|
||||
if edge_kinds & BUILD_KINDS
|
||||
}
|
||||
|
||||
|
||||
def check_workspace(metadata: dict) -> list[str]:
|
||||
problems: list[str] = []
|
||||
names = package_names(metadata)
|
||||
members = workspace_package_names(metadata)
|
||||
|
||||
stale = sorted(set(WORKSPACE_CRATES) - members)
|
||||
if stale:
|
||||
problems.append(
|
||||
"reviewed crate allowlist names crates that are not workspace members: "
|
||||
+ ", ".join(stale)
|
||||
)
|
||||
undocumented = sorted(members - set(WORKSPACE_CRATES))
|
||||
if undocumented:
|
||||
problems.append(
|
||||
"workspace members missing a reviewed responsibility in "
|
||||
"tools/ci/check_dependency_boundaries.py: " + ", ".join(undocumented)
|
||||
)
|
||||
|
||||
graph = dependency_graph(metadata)
|
||||
for crate in ENGINE_CRATES:
|
||||
if crate not in graph:
|
||||
continue
|
||||
closure = reachable(graph, crate, BUILD_KINDS)
|
||||
for forbidden in sorted(FORBIDDEN_FOR_ENGINE & set(closure)):
|
||||
problems.append(
|
||||
f"engine crate `{crate}` reaches forbidden dependency `{forbidden}`: "
|
||||
f"{closure[forbidden]}"
|
||||
)
|
||||
|
||||
contract = "marqdo-host-contract"
|
||||
if contract in graph:
|
||||
allowed = {"marqdo-span", "marqdo-value"}
|
||||
direct = direct_build_dependencies(graph, contract)
|
||||
unexpected = sorted(direct - allowed)
|
||||
if unexpected:
|
||||
problems.append(
|
||||
"marqdo-host-contract must depend only on neutral span/value types; got: "
|
||||
+ ", ".join(unexpected)
|
||||
)
|
||||
|
||||
host = "marqdo-host"
|
||||
if host in graph:
|
||||
closure = reachable(graph, host, BUILD_KINDS)
|
||||
for forbidden in (
|
||||
"marqdo-runtime",
|
||||
"marqdo-frontend",
|
||||
"marqdo-ir",
|
||||
"marqdo-expression",
|
||||
"marqdo-markdown",
|
||||
"marqdo-cli",
|
||||
):
|
||||
if forbidden in closure:
|
||||
problems.append(
|
||||
f"native host `marqdo-host` must not depend back on `{forbidden}`: "
|
||||
f"{closure[forbidden]}"
|
||||
)
|
||||
|
||||
abi = "marqdo-plugin-abi"
|
||||
if abi in graph:
|
||||
direct = direct_build_dependencies(graph, abi)
|
||||
for forbidden in ("libloading", "marqdo-worker-ipc", "marqdo-host", "marqdo-sandbox"):
|
||||
if forbidden in direct:
|
||||
problems.append(
|
||||
f"public contract `marqdo-plugin-abi` must not carry execution-side "
|
||||
f"dependency `{forbidden}`"
|
||||
)
|
||||
|
||||
sdk = "marqdo-plugin-sdk"
|
||||
if sdk in graph:
|
||||
closure = reachable(graph, sdk, BUILD_KINDS)
|
||||
for forbidden in (
|
||||
"libloading",
|
||||
"marqdo-worker-ipc",
|
||||
"marqdo-host",
|
||||
"marqdo-sandbox",
|
||||
"marqdo-cli",
|
||||
"marqdo-provider-worker",
|
||||
):
|
||||
if forbidden in closure:
|
||||
problems.append(
|
||||
f"plugin SDK reaches execution-side dependency `{forbidden}`: "
|
||||
f"{closure[forbidden]}"
|
||||
)
|
||||
|
||||
# CLT Tool / package identity is a product concern; the CLI is the only
|
||||
# crate allowed to combine engine + native host + package.
|
||||
cli = "marqdo-cli"
|
||||
if cli in graph:
|
||||
direct = direct_build_dependencies(graph, cli)
|
||||
for required in ("marqdo-runtime", "marqdo-host", "marqdo-host-contract"):
|
||||
if required not in direct:
|
||||
problems.append(
|
||||
f"CLI composition root must depend on `{required}` directly"
|
||||
)
|
||||
|
||||
return problems
|
||||
|
||||
|
||||
def check_consumer(metadata: dict) -> list[str]:
|
||||
problems: list[str] = []
|
||||
graph = dependency_graph(metadata)
|
||||
package = next(
|
||||
(
|
||||
item
|
||||
for item in metadata["packages"]
|
||||
if item["name"] == "marqdo-embedding-consumer"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if package is None:
|
||||
return ["embedding consumer package was not resolved"]
|
||||
|
||||
names = package_names(metadata)
|
||||
if "marqdo-host" in names or "marqdo-cli" in names or "marqdo-sandbox" in names:
|
||||
problems.append(
|
||||
"independent embedding consumer resolved a native host, sandbox or CLI package"
|
||||
)
|
||||
|
||||
closure = reachable(graph, "marqdo-runtime", BUILD_KINDS)
|
||||
for forbidden in sorted(FORBIDDEN_FOR_ENGINE & set(closure)):
|
||||
problems.append(
|
||||
f"runtime in the independent consumer reaches forbidden dependency "
|
||||
f"`{forbidden}`: {closure[forbidden]}"
|
||||
)
|
||||
|
||||
direct = direct_build_dependencies(graph, "marqdo-embedding-consumer")
|
||||
allowed_direct = {
|
||||
"marqdo-frontend",
|
||||
"marqdo-host-contract",
|
||||
"marqdo-ir",
|
||||
"marqdo-runtime",
|
||||
"marqdo-span",
|
||||
"marqdo-value",
|
||||
"serde_json",
|
||||
"serde",
|
||||
}
|
||||
unexpected = sorted(direct - allowed_direct)
|
||||
if unexpected:
|
||||
problems.append(
|
||||
"embedding consumer has unexpected direct dependencies: "
|
||||
+ ", ".join(unexpected)
|
||||
)
|
||||
for required in ("marqdo-runtime", "marqdo-host-contract", "marqdo-frontend"):
|
||||
if required not in direct:
|
||||
problems.append(
|
||||
f"embedding consumer must depend directly on `{required}`"
|
||||
)
|
||||
return problems
|
||||
|
||||
|
||||
def evaluate(workspace_metadata: dict, consumer_metadata: dict) -> list[str]:
|
||||
problems = check_workspace(workspace_metadata)
|
||||
problems += check_consumer(consumer_metadata)
|
||||
return problems
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--offline",
|
||||
action="store_true",
|
||||
help="pass --offline to cargo metadata (used on hosts with a warm cache)",
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
try:
|
||||
workspace = run_metadata(None, arguments.offline)
|
||||
consumer = run_metadata(CONSUMER_MANIFEST, arguments.offline)
|
||||
except GateError as error:
|
||||
print(f"FAIL dependency-boundaries: {error}", file=sys.stderr)
|
||||
return 1
|
||||
problems = evaluate(workspace, consumer)
|
||||
if problems:
|
||||
for problem in problems:
|
||||
print(f"FAIL dependency-boundaries: {problem}", file=sys.stderr)
|
||||
return 1
|
||||
print("PASS dependency-boundaries")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Engine independence + differential execution gate (issue #13 §4.3-4.4).
|
||||
|
||||
1. Builds the real independent consumer in ``tests/embedding`` with its own
|
||||
lock file and workspace.
|
||||
2. Runs it: the same Markdown program goes through the real Frontend, static
|
||||
call binding and Runtime, with real fuel/stack/deadline/memory limits and
|
||||
explicit resource refusal.
|
||||
3. Builds the real CLI and executes the same program, then compares the
|
||||
terminal Value Wire encoding with the consumer result.
|
||||
4. Delegates the Cargo-metadata dependency-direction checks to
|
||||
``check_dependency_boundaries.py``.
|
||||
|
||||
This is a build-and-run gate, not a source grep. It never mocks the interpreter
|
||||
and never constructs an expected value in place of execution.
|
||||
|
||||
Usage:
|
||||
python3 tools/ci/check_engine_boundary.py [--offline]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
CONSUMER = REPO_ROOT / "tests" / "embedding"
|
||||
PROGRAM = CONSUMER / "program.mq.md"
|
||||
FORBIDDEN_RUNTIME_EDGES = {
|
||||
"marqdo-host",
|
||||
"marqdo-sandbox",
|
||||
"marqdo-foreign",
|
||||
"libloading",
|
||||
"rustls",
|
||||
}
|
||||
|
||||
|
||||
class GateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def tool(name: str) -> str:
|
||||
path = shutil.which(name)
|
||||
if path is None:
|
||||
raise GateError(f"`{name}` is not on PATH")
|
||||
return path
|
||||
|
||||
|
||||
def run(
|
||||
command: list[str],
|
||||
*,
|
||||
check: bool = True,
|
||||
cwd: Path = REPO_ROOT,
|
||||
) -> subprocess.CompletedProcess:
|
||||
result = subprocess.run(
|
||||
command, cwd=cwd, capture_output=True, text=True, check=False
|
||||
)
|
||||
if check and result.returncode != 0:
|
||||
raise GateError(
|
||||
f"`{' '.join(command)}` failed with {result.returncode}:\n"
|
||||
f"{result.stdout}\n{result.stderr}"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def build_dependencies(package: str, offline: bool) -> set[str]:
|
||||
"""Parse `cargo tree -e normal,build` package names for one package."""
|
||||
command = [tool("cargo"), "tree", "-p", package, "-e", "normal,build", "--prefix", "none"]
|
||||
if offline:
|
||||
command.append("--offline")
|
||||
result = run(command)
|
||||
names: set[str] = set()
|
||||
for line in result.stdout.splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped:
|
||||
continue
|
||||
# Lines look like `marqdo-value v3.0.0-rc.4 (/path)` or `serde v1.0.1`.
|
||||
name = stripped.split(" v", 1)[0].strip()
|
||||
if name:
|
||||
names.add(name)
|
||||
return names
|
||||
|
||||
|
||||
def parse_consumer(stdout: str) -> tuple[dict[str, str], dict[str, str]]:
|
||||
results: dict[str, str] = {}
|
||||
errors: dict[str, str] = {}
|
||||
for line in stdout.splitlines():
|
||||
if line.startswith("result "):
|
||||
_, name, encoded = line.split(" ", 2)
|
||||
results[name] = encoded
|
||||
elif line.startswith("error "):
|
||||
_, name, code = line.split(" ", 2)
|
||||
errors[name] = code
|
||||
return results, errors
|
||||
|
||||
|
||||
def terminal_value(snapshot: dict) -> object:
|
||||
event = snapshot["events"][-1]
|
||||
if event["kind"] != "run.completed":
|
||||
raise GateError(f"CLI did not complete: {event}")
|
||||
return event["payload"]["value"]
|
||||
|
||||
|
||||
def cli_value(binary: Path, function: str, args: list[str]) -> object:
|
||||
command = [
|
||||
str(binary),
|
||||
"call",
|
||||
str(PROGRAM),
|
||||
function,
|
||||
*args,
|
||||
"--output",
|
||||
"json",
|
||||
]
|
||||
result = run(command)
|
||||
return terminal_value(json.loads(result.stdout))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--offline", action="store_true")
|
||||
arguments = parser.parse_args()
|
||||
offline_flag = ["--offline"] if arguments.offline else []
|
||||
try:
|
||||
# Dependency direction is a separate, fast check.
|
||||
dependency_command = [sys.executable, str(REPO_ROOT / "tools/ci/check_dependency_boundaries.py")]
|
||||
dependency_command += offline_flag
|
||||
run(dependency_command)
|
||||
|
||||
cargo = tool("cargo")
|
||||
run([cargo, "build", "--locked", *offline_flag, "--manifest-path", str(CONSUMER / "Cargo.toml")])
|
||||
consumer = CONSUMER / "target" / "debug" / "embedding-consumer"
|
||||
if not consumer.is_file():
|
||||
raise GateError(f"embedding consumer binary not found: {consumer}")
|
||||
consumer_run = run([str(consumer)])
|
||||
results, errors = parse_consumer(consumer_run.stdout)
|
||||
|
||||
expected_errors = {
|
||||
"fuel": "resource.exhausted",
|
||||
"stack": "resource.exhausted",
|
||||
"deadline": "resource.exhausted",
|
||||
"oob": "runtime.index",
|
||||
"file_denied": "permission.denied",
|
||||
"file_unsupported": "resource.unsupported",
|
||||
}
|
||||
for name, code in expected_errors.items():
|
||||
if errors.get(name) != code:
|
||||
raise GateError(
|
||||
f"consumer negative case `{name}` expected `{code}`, got "
|
||||
f"`{errors.get(name)}` (stderr: {consumer_run.stderr})"
|
||||
)
|
||||
|
||||
# A real CLI invocation on the same file and arguments must produce the
|
||||
# identical terminal Value Wire encoding.
|
||||
run([cargo, "build", "--locked", *offline_flag, "-p", "marqdo-cli"])
|
||||
cli = REPO_ROOT / "target" / "debug" / "marqdo"
|
||||
if not cli.is_file():
|
||||
raise GateError(f"CLI binary not found: {cli}")
|
||||
comparisons = [
|
||||
("sum_to", ["--arg", "n=10"]),
|
||||
("types", ["--arg", "seed=7"]),
|
||||
]
|
||||
for function, args in comparisons:
|
||||
if function not in results:
|
||||
raise GateError(f"consumer did not report a `{function}` result")
|
||||
from_cli = cli_value(cli, function, args)
|
||||
from_consumer = json.loads(results[function])
|
||||
if from_cli != from_consumer:
|
||||
raise GateError(
|
||||
f"differential mismatch for `{function}`: CLI={from_cli!r} "
|
||||
f"consumer={from_consumer!r}"
|
||||
)
|
||||
print(f"PASS differential value `{function}` {json.dumps(from_cli, ensure_ascii=False)}")
|
||||
|
||||
runtime_dependencies = build_dependencies("marqdo-runtime", arguments.offline)
|
||||
leaked = sorted(FORBIDDEN_RUNTIME_EDGES & runtime_dependencies)
|
||||
if leaked:
|
||||
raise GateError(
|
||||
"marqdo-runtime normal/build tree contains forbidden dependencies: "
|
||||
+ ", ".join(leaked)
|
||||
)
|
||||
print(
|
||||
"PASS runtime build tree has no native host/loader dependency "
|
||||
f"({len(runtime_dependencies)} packages)"
|
||||
)
|
||||
print("PASS embedding-consumer " + consumer_run.stdout.strip().splitlines()[-1])
|
||||
except GateError as error:
|
||||
print(f"FAIL engine-boundary: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print("PASS engine-boundary")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real third-party plugin SDK consumption gate (issue #13 §6.3, S04-S05).
|
||||
|
||||
Builds the fixture in ``tests/sdk-plugin`` with only the public Rust SDK, creates
|
||||
the host-specific ``plugin.yaml``, then lets a real built CLI load and invoke it
|
||||
with explicit trust and an explicit plugin grant. A tampered digest must fail
|
||||
closed. No mock host, no direct Rust call into plugin internals.
|
||||
|
||||
Usage:
|
||||
python3 tools/ci/check_plugin_sdk.py [--offline]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
FIXTURE = REPO_ROOT / "tests" / "sdk-plugin"
|
||||
CALL_DOC = FIXTURE / "call.mq.md"
|
||||
|
||||
|
||||
class GateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def cargo() -> str:
|
||||
path = shutil.which("cargo")
|
||||
if path is None:
|
||||
raise GateError("cargo is not on PATH")
|
||||
return path
|
||||
|
||||
|
||||
def run(command: list[str], *, check: bool = True) -> subprocess.CompletedProcess:
|
||||
result = subprocess.run(
|
||||
command, cwd=REPO_ROOT, capture_output=True, text=True, check=False
|
||||
)
|
||||
if check and result.returncode != 0:
|
||||
raise GateError(
|
||||
f"`{' '.join(command)}` failed with {result.returncode}:\n"
|
||||
f"{result.stdout}\n{result.stderr}"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def host_triple() -> str:
|
||||
result = run(["rustc", "-vV"])
|
||||
for line in result.stdout.splitlines():
|
||||
if line.startswith("host: "):
|
||||
return line[len("host: ") :].strip()
|
||||
raise GateError("rustc -vV did not report a host triple")
|
||||
|
||||
|
||||
def artifact_name() -> str:
|
||||
system = platform.system()
|
||||
if system == "Darwin":
|
||||
return "libmarqdo_sdk_plugin_fixture.dylib"
|
||||
if system == "Windows":
|
||||
return "marqdo_sdk_plugin_fixture.dll"
|
||||
return "libmarqdo_sdk_plugin_fixture.so"
|
||||
|
||||
|
||||
def write_manifest(
|
||||
directory: Path,
|
||||
digest: str,
|
||||
triple: str,
|
||||
artifact: str,
|
||||
*,
|
||||
tamper: bool = False,
|
||||
) -> None:
|
||||
effective = "0" * 64 if tamper else digest
|
||||
manifest = f"""plugin:
|
||||
name: sdk.demo
|
||||
version: 0.1.0
|
||||
abi: "^1.0"
|
||||
kind: native
|
||||
exports:
|
||||
- name: sdk.add
|
||||
signature: "($a: Int, $b: Int) -> Int"
|
||||
- name: sdk.echo
|
||||
signature: "($text: Text) -> Text"
|
||||
artifacts:
|
||||
- target: {triple}
|
||||
file: {artifact}
|
||||
sha256: "{effective}"
|
||||
"""
|
||||
(directory / "plugin.yaml").write_text(manifest, encoding="utf-8")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--offline", action="store_true")
|
||||
parser.add_argument(
|
||||
"--sdk-revision",
|
||||
default=None,
|
||||
help="informational: exact CLI/SDK source revision under test",
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
offline = ["--offline"] if arguments.offline else []
|
||||
try:
|
||||
run([cargo(), "build", "--locked", "-p", "marqdo-cli", *offline])
|
||||
run([cargo(), "build", "--locked", "--manifest-path", str(FIXTURE / "Cargo.toml"), *offline])
|
||||
name = artifact_name()
|
||||
built = FIXTURE / "target" / "debug" / name
|
||||
if not built.is_file():
|
||||
raise GateError(f"SDK fixture artifact not found: {built}")
|
||||
triple = host_triple()
|
||||
binary = REPO_ROOT / "target" / "debug" / "marqdo"
|
||||
if not binary.is_file():
|
||||
raise GateError(f"CLI binary not found: {binary}")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="marqdo-sdk-plugin-") as raw:
|
||||
directory = Path(raw)
|
||||
artifact = "plugin" + Path(name).suffix
|
||||
shutil.copyfile(built, directory / artifact)
|
||||
digest = hashlib.sha256((directory / artifact).read_bytes()).hexdigest()
|
||||
command = [
|
||||
str(binary),
|
||||
"call",
|
||||
str(CALL_DOC),
|
||||
"main",
|
||||
"--plugin",
|
||||
str(directory),
|
||||
"--trust-native-plugin",
|
||||
"--allow-plugin",
|
||||
"sdk.demo",
|
||||
]
|
||||
|
||||
write_manifest(directory, digest, triple, artifact)
|
||||
positive = run(command, check=False)
|
||||
if positive.returncode != 0 or positive.stdout.strip() != "42":
|
||||
raise GateError(
|
||||
"real CLI could not invoke the SDK plugin: "
|
||||
f"exit={positive.returncode} stdout={positive.stdout!r} "
|
||||
f"stderr={positive.stderr!r}"
|
||||
)
|
||||
print("PASS sdk-plugin-real-invocation (Int 42)")
|
||||
|
||||
write_manifest(directory, digest, triple, artifact, tamper=True)
|
||||
negative = run(command, check=False)
|
||||
if negative.returncode == 0:
|
||||
raise GateError("tampered plugin artifact digest was accepted")
|
||||
combined = negative.stdout + negative.stderr
|
||||
if "sha256" not in combined.lower() and "artifact" not in combined.lower():
|
||||
raise GateError(
|
||||
"tampered artifact failed without an artifact/sha256 diagnostic: "
|
||||
+ combined
|
||||
)
|
||||
print("PASS sdk-plugin-tampered-digest-rejected")
|
||||
except GateError as error:
|
||||
print(f"FAIL plugin-sdk: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print("PASS plugin-sdk")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,223 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative-case tests for the dependency-direction gate (issue #13 G03).
|
||||
|
||||
The architecture gate must actually reject violations, not just accept the
|
||||
current tree. These synthetic Cargo-metadata graphs exercise each forbidden edge
|
||||
and the reviewed-allowlist rule.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import check_dependency_boundaries as gate # noqa: E402
|
||||
|
||||
|
||||
def package_id(name: str) -> str:
|
||||
return f"path+file:///repo#{name}@0.0.0"
|
||||
|
||||
|
||||
def metadata(
|
||||
edges: dict[str, list[str]],
|
||||
*,
|
||||
members: set[str] | None = None,
|
||||
extra_packages: set[str] | None = None,
|
||||
) -> dict:
|
||||
names = set(edges)
|
||||
for targets in edges.values():
|
||||
names.update(targets)
|
||||
names.update(extra_packages or set())
|
||||
packages = [
|
||||
{"id": package_id(name), "name": name, "version": "0.0.0"}
|
||||
for name in sorted(names)
|
||||
]
|
||||
nodes = []
|
||||
for source, targets in edges.items():
|
||||
nodes.append(
|
||||
{
|
||||
"id": package_id(source),
|
||||
"deps": [
|
||||
{
|
||||
"name": target,
|
||||
"pkg": package_id(target),
|
||||
"dep_kinds": [{"kind": None, "target": None}],
|
||||
}
|
||||
for target in targets
|
||||
],
|
||||
}
|
||||
)
|
||||
if members is None:
|
||||
members = set(gate.WORKSPACE_CRATES)
|
||||
return {
|
||||
"packages": packages,
|
||||
"workspace_members": [package_id(name) for name in members],
|
||||
"resolve": {"nodes": nodes},
|
||||
}
|
||||
|
||||
|
||||
def valid_workspace_edges() -> dict[str, list[str]]:
|
||||
edges = {name: [] for name in gate.WORKSPACE_CRATES}
|
||||
edges["marqdo-value"] = ["marqdo-span"]
|
||||
edges["marqdo-span"] = []
|
||||
edges["marqdo-expression"] = ["marqdo-span", "marqdo-value"]
|
||||
edges["marqdo-markdown"] = ["marqdo-span"]
|
||||
edges["marqdo-ir"] = ["marqdo-span", "marqdo-value"]
|
||||
edges["marqdo-frontend"] = [
|
||||
"marqdo-markdown",
|
||||
"marqdo-expression",
|
||||
"marqdo-ir",
|
||||
"marqdo-value",
|
||||
"marqdo-span",
|
||||
]
|
||||
edges["marqdo-host-contract"] = ["marqdo-value", "marqdo-span"]
|
||||
edges["marqdo-runtime"] = [
|
||||
"marqdo-host-contract",
|
||||
"marqdo-ir",
|
||||
"marqdo-expression",
|
||||
"marqdo-value",
|
||||
"marqdo-span",
|
||||
]
|
||||
edges["marqdo-plugin-abi"] = ["marqdo-value"]
|
||||
edges["marqdo-plugin-sdk"] = ["marqdo-plugin-abi"]
|
||||
edges["marqdo-worker-ipc"] = []
|
||||
edges["marqdo-sandbox"] = []
|
||||
edges["marqdo-foreign"] = ["marqdo-worker-ipc"]
|
||||
edges["marqdo-provider-worker"] = ["marqdo-worker-ipc"]
|
||||
edges["marqdo-package"] = ["marqdo-value"]
|
||||
edges["marqdo-host"] = [
|
||||
"marqdo-host-contract",
|
||||
"marqdo-plugin-abi",
|
||||
"marqdo-foreign",
|
||||
"marqdo-sandbox",
|
||||
"marqdo-worker-ipc",
|
||||
]
|
||||
edges["marqdo-cli"] = [
|
||||
"marqdo-runtime",
|
||||
"marqdo-host-contract",
|
||||
"marqdo-host",
|
||||
"marqdo-frontend",
|
||||
"marqdo-package",
|
||||
]
|
||||
return edges
|
||||
|
||||
|
||||
def valid_consumer_edges() -> dict[str, list[str]]:
|
||||
return {
|
||||
"marqdo-embedding-consumer": [
|
||||
"marqdo-runtime",
|
||||
"marqdo-host-contract",
|
||||
"marqdo-frontend",
|
||||
"marqdo-ir",
|
||||
"marqdo-span",
|
||||
"marqdo-value",
|
||||
"serde_json",
|
||||
],
|
||||
"marqdo-runtime": [
|
||||
"marqdo-host-contract",
|
||||
"marqdo-ir",
|
||||
"marqdo-expression",
|
||||
"marqdo-value",
|
||||
"marqdo-span",
|
||||
],
|
||||
"marqdo-host-contract": ["marqdo-value", "marqdo-span"],
|
||||
"marqdo-frontend": ["marqdo-ir", "marqdo-value"],
|
||||
"marqdo-ir": ["marqdo-value"],
|
||||
"marqdo-value": ["marqdo-span"],
|
||||
"marqdo-span": [],
|
||||
"serde_json": [],
|
||||
}
|
||||
|
||||
|
||||
class DependencyBoundaryTests(unittest.TestCase):
|
||||
def assert_rejected(self, workspace_edges_edit, needle: str) -> None:
|
||||
edges = valid_workspace_edges()
|
||||
workspace_edges_edit(edges)
|
||||
workspace = metadata(edges)
|
||||
consumer = metadata(valid_consumer_edges(), members={"marqdo-embedding-consumer"})
|
||||
problems = gate.evaluate(workspace, consumer)
|
||||
self.assertTrue(
|
||||
any(needle in problem for problem in problems),
|
||||
f"expected a problem containing {needle!r}, got {problems}",
|
||||
)
|
||||
|
||||
def test_current_shape_is_accepted(self) -> None:
|
||||
workspace = metadata(valid_workspace_edges())
|
||||
consumer = metadata(valid_consumer_edges(), members={"marqdo-embedding-consumer"})
|
||||
self.assertEqual(gate.evaluate(workspace, consumer), [])
|
||||
|
||||
def test_runtime_to_native_host_is_rejected(self) -> None:
|
||||
self.assert_rejected(
|
||||
lambda edges: edges["marqdo-runtime"].append("marqdo-host"),
|
||||
"forbidden dependency `marqdo-host`",
|
||||
)
|
||||
|
||||
def test_engine_to_sandbox_is_rejected(self) -> None:
|
||||
self.assert_rejected(
|
||||
lambda edges: edges["marqdo-runtime"].append("marqdo-sandbox"),
|
||||
"forbidden dependency `marqdo-sandbox`",
|
||||
)
|
||||
|
||||
def test_engine_to_libloading_is_rejected(self) -> None:
|
||||
self.assert_rejected(
|
||||
lambda edges: edges["marqdo-runtime"].append("libloading"),
|
||||
"forbidden dependency `libloading`",
|
||||
)
|
||||
|
||||
def test_native_host_back_edge_is_rejected(self) -> None:
|
||||
self.assert_rejected(
|
||||
lambda edges: edges["marqdo-host"].append("marqdo-runtime"),
|
||||
"must not depend back on `marqdo-runtime`",
|
||||
)
|
||||
|
||||
def test_contract_extra_dependency_is_rejected(self) -> None:
|
||||
self.assert_rejected(
|
||||
lambda edges: edges["marqdo-host-contract"].append("serde_json"),
|
||||
"must depend only on neutral span/value types",
|
||||
)
|
||||
|
||||
def test_abi_native_loader_is_rejected(self) -> None:
|
||||
self.assert_rejected(
|
||||
lambda edges: edges["marqdo-plugin-abi"].append("libloading"),
|
||||
"must not carry execution-side dependency `libloading`",
|
||||
)
|
||||
|
||||
def test_sdk_host_edge_is_rejected(self) -> None:
|
||||
self.assert_rejected(
|
||||
lambda edges: edges["marqdo-plugin-sdk"].append("marqdo-host"),
|
||||
"plugin SDK reaches execution-side dependency `marqdo-host`",
|
||||
)
|
||||
|
||||
def test_undocumented_workspace_crate_is_rejected(self) -> None:
|
||||
edges = valid_workspace_edges()
|
||||
edges["marqdo-unreviewed"] = []
|
||||
workspace = metadata(edges, members=set(gate.WORKSPACE_CRATES) | {"marqdo-unreviewed"})
|
||||
consumer = metadata(valid_consumer_edges(), members={"marqdo-embedding-consumer"})
|
||||
problems = gate.evaluate(workspace, consumer)
|
||||
self.assertTrue(
|
||||
any("missing a reviewed responsibility" in problem for problem in problems),
|
||||
problems,
|
||||
)
|
||||
|
||||
def test_cli_without_contract_is_rejected(self) -> None:
|
||||
self.assert_rejected(
|
||||
lambda edges: edges["marqdo-cli"].remove("marqdo-host-contract"),
|
||||
"CLI composition root must depend on `marqdo-host-contract`",
|
||||
)
|
||||
|
||||
def test_consumer_native_host_is_rejected(self) -> None:
|
||||
edges = valid_consumer_edges()
|
||||
edges["marqdo-embedding-consumer"].append("marqdo-host")
|
||||
consumer = metadata(edges, members={"marqdo-embedding-consumer"})
|
||||
workspace = metadata(valid_workspace_edges())
|
||||
problems = gate.evaluate(workspace, consumer)
|
||||
self.assertTrue(
|
||||
any("resolved a native host" in problem for problem in problems), problems
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user