Files
relayview-skills/tests/test_role_steps.py
T

291 lines
15 KiB
Python
Raw Normal View History

"""Validation of every supported role/step pair, including Tester and Coordinator.
The fixtures under tests/fixtures/packages are valid packages for the newer
role/step pairs; invalid cases are derived from them by one mutation each.
"""
import hashlib
import json
import os
import shutil
import struct
import tempfile
import unittest
import zipfile
from pathlib import Path
from tools.packages import PackageError, check_package, package_archive
ROOT = Path(__file__).resolve().parents[1]
FIXTURES = ROOT / "tests/fixtures/packages"
NEW_PAIR_FIXTURES = {
"tester-fixture": (1, "tester", "testing"),
"tester-communication-fixture": (3, "tester", "testing"),
"coordinator-fixture": (1, "coordinator", "coordination"),
"coordinator-communication-fixture": (3, "coordinator", "coordination"),
"coordinator-manual-fixture": (1, "coordinator", "coordination"),
}
def reference_identity(package):
"""Mirror RelayView's scripts/verify-first-party-skills-source.py identity."""
manifest_bytes = (package / "relayview-skill.json").read_bytes()
identity = hashlib.sha256(b"relayview-instruction-package-v1\0")
def frame(data):
identity.update(struct.pack(">I", len(data)))
identity.update(data)
frame(manifest_bytes)
for item in sorted(json.loads(manifest_bytes)["files"], key=lambda item: item["path"]):
frame(item["path"].encode("utf-8"))
frame((package / item["path"]).read_bytes())
return identity.hexdigest()
def reference_archive_sha256(package, destination):
"""Mirror RelayView's scripts/verify-first-party-skills-source.py archive."""
with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_STORED) as archive:
files = [(file.name, file) for file in (ROOT / "LICENSE", ROOT / "NOTICE.md")]
files += [(f"{package.name}/{file.relative_to(package).as_posix()}", file)
for file in sorted(package.rglob("*")) if file.is_file()]
for name, file in files:
info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
info.external_attr = 0o100644 << 16
archive.writestr(info, file.read_bytes())
return hashlib.sha256(Path(destination).read_bytes()).hexdigest()
class FixtureCopy:
"""A temporary copy of one fixture that a test mutates once."""
def __init__(self, name):
self.name = name
def __enter__(self):
self._directory = tempfile.TemporaryDirectory()
self.path = Path(self._directory.name) / self.name
shutil.copytree(FIXTURES / self.name, self.path)
return self
def __exit__(self, *exc):
self._directory.cleanup()
@property
def manifest(self):
return json.loads((self.path / "relayview-skill.json").read_text())
def write_manifest(self, manifest):
(self.path / "relayview-skill.json").write_text(json.dumps(manifest, indent=2) + "\n")
def write_file(self, relative, data, declare=True):
"""Write package content; when declared, refresh its digest so only the content is under test."""
file = self.path / relative
file.write_bytes(data if isinstance(data, bytes) else data.encode("utf-8"))
if declare:
manifest = self.manifest
digest = hashlib.sha256(file.read_bytes()).hexdigest()
entry = next((item for item in manifest["files"] if item["path"] == relative), None)
if entry is None:
manifest["files"].append({"path": relative, "sha256": digest})
else:
entry["sha256"] = digest
self.write_manifest(manifest)
def replace_in_skill(self, old, new):
text = (self.path / "SKILL.md").read_text()
assert old in text, old
self.write_file("SKILL.md", text.replace(old, new, 1))
class NewRoleStepPairTests(unittest.TestCase):
def test_fixtures_declare_the_new_pairs_under_schema_one_and_three(self):
self.assertEqual(sorted(path.name for path in FIXTURES.iterdir()), sorted(NEW_PAIR_FIXTURES))
for name, (schema, role, step) in NEW_PAIR_FIXTURES.items():
with self.subTest(name=name):
manifest = json.loads((FIXTURES / name / "relayview-skill.json").read_text())
self.assertEqual((manifest["schemaVersion"], manifest["role"], manifest["step"]), (schema, role, step))
self.assertEqual(manifest.get("treatment"), "communication_context" if schema == 3 else None)
def test_valid_fixtures_pass_with_relayview_identity_and_archive(self):
for name in NEW_PAIR_FIXTURES:
with self.subTest(name=name), tempfile.TemporaryDirectory() as directory:
package = FIXTURES / name
self.assertEqual(check_package(package), reference_identity(package))
first = package_archive(package, Path(directory) / "one.zip")
second = package_archive(package, Path(directory) / "two.zip")
self.assertEqual(first, second)
self.assertEqual(first, reference_archive_sha256(package, Path(directory) / "reference.zip"))
with zipfile.ZipFile(Path(directory) / "one.zip") as archive:
for info in archive.infolist():
self.assertEqual(info.date_time, (1980, 1, 1, 0, 0, 0))
self.assertEqual(info.external_attr >> 16, 0o100644)
self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
def test_identity_algorithm_is_pinned(self):
# Regression pin: changing this value means the relayview-instruction-package-v1
# framing changed, which would break every RelayView bundle lock.
self.assertEqual(check_package(FIXTURES / "tester-fixture"),
"31a04937d9572067f0c3327fbaba97e11f6962fd7f68fefdb2c70ef8f5aad394")
def test_manual_fixture_disables_model_invocation(self):
self.assertIn("disable-model-invocation: true\n", (FIXTURES / "coordinator-manual-fixture/SKILL.md").read_text())
class RoleStepRejectionTests(unittest.TestCase):
def assertRejected(self, copy, message):
with self.assertRaisesRegex(PackageError, message):
check_package(copy.path)
def test_rejects_wrong_role_step_combinations(self):
combinations = (
("tester", "coordination"), ("coordinator", "testing"),
("tester", "review"), ("tester", "implementation"),
("coordinator", "planning"), ("coordinator", "design"),
("planner", "testing"), ("reviewer", "coordination"), ("designer", "testing"),
("Tester", "testing"), ("coordinator", "Coordination"),
("tester", None), (["tester"], "testing"), ("operator", "coordination"),
)
for name in NEW_PAIR_FIXTURES:
for role, step in combinations:
with self.subTest(name=name, role=role, step=step), FixtureCopy(name) as copy:
copy.write_manifest(dict(copy.manifest, role=role, step=step))
self.assertRejected(copy, "incompatible role or step")
def test_rejects_issue_claim_outside_the_planner(self):
for name in ("tester-fixture", "coordinator-fixture"):
with self.subTest(name=name), FixtureCopy(name) as copy:
copy.write_manifest(dict(copy.manifest, schemaVersion=2, issueClaim={"statusLabel": None}))
self.assertRejected(copy, "invalid issue claim policy")
def test_rejects_schema_and_treatment_mismatches(self):
fields, treatment = "unsupported manifest fields", "invalid communication treatment"
cases = {
"tester-fixture": [
({"treatment": "communication_context"}, fields),
({"schemaVersion": 3}, fields),
({"schemaVersion": True}, fields),
({"schemaVersion": "1"}, fields),
({"schemaVersion": 1.5}, fields),
({"schemaVersion": 4}, fields),
],
"coordinator-communication-fixture": [
({"treatment": "context"}, treatment),
({"treatment": None}, treatment),
({"schemaVersion": 1}, fields),
({"schemaVersion": True}, fields),
],
}
for name, changes in cases.items():
for change, message in changes:
with self.subTest(name=name, change=change), FixtureCopy(name) as copy:
copy.write_manifest(dict(copy.manifest, **change))
self.assertRejected(copy, message)
with FixtureCopy("tester-communication-fixture") as copy:
manifest = copy.manifest
del manifest["treatment"]
copy.write_manifest(manifest)
self.assertRejected(copy, "unsupported manifest fields")
def test_rejects_sidecar_capability_fields(self):
for name in NEW_PAIR_FIXTURES:
for field, value in (("tools", ["shell"]), ("permissions", {"network": True}), ("network", True),
("credentials", ["gitea"]), ("dispatch", True), ("resources", ["gpu-worker"])):
with self.subTest(name=name, field=field), FixtureCopy(name) as copy:
copy.write_manifest(dict(copy.manifest, **{field: value}))
self.assertRejected(copy, "unsupported manifest fields")
with self.subTest(name=name, field="source.scope"), FixtureCopy(name) as copy:
copy.write_manifest(dict(copy.manifest, source={"kind": "user", "reference": "fixture-1", "scope": "all"}))
self.assertRejected(copy, "invalid source")
def test_rejects_bad_digests(self):
for name in ("tester-fixture", "coordinator-fixture"):
resource = next(item["path"] for item in json.loads((FIXTURES / name / "relayview-skill.json").read_text())["files"] if item["path"] != "SKILL.md")
for path in ("SKILL.md", resource):
for digest, message in (("0" * 64, "changed file"), ("A" * 64, "invalid digest"),
("0" * 63, "invalid digest"), (None, "invalid digest")):
with self.subTest(name=name, path=path, digest=digest), FixtureCopy(name) as copy:
manifest = copy.manifest
next(item for item in manifest["files"] if item["path"] == path)["sha256"] = digest
copy.write_manifest(manifest)
self.assertRejected(copy, message)
with self.subTest(name=name, change="content after digest"), FixtureCopy(name) as copy:
(copy.path / resource).write_text("changed\n")
self.assertRejected(copy, "changed file")
def test_rejects_forbidden_frontmatter(self):
metadata, boolean = "unsupported skill metadata", "must be a boolean"
cases = (
("metadata:\n", "tools: [shell]\nmetadata:\n", metadata),
("metadata:\n", "allowed-tools: Bash\nmetadata:\n", metadata),
("metadata:\n", "model: any\nmetadata:\n", metadata),
("metadata:\n", "role: coordinator\nmetadata:\n", metadata),
("metadata:\n", "metadata: {}\n", metadata),
("metadata:\n", "metadata:\n relayview-tools: shell\n", metadata),
("metadata:\n", "metadata:\n relayview-role: tester\n", metadata),
("metadata:\n", "name: other-name\nmetadata:\n", metadata),
("metadata:\n", "disable-model-invocation: yes\nmetadata:\n", boolean),
("metadata:\n", "disable-model-invocation:yes\nmetadata:\n", metadata),
("metadata:\n", "disable-model-invocation:\nmetadata:\n", metadata),
)
for name in NEW_PAIR_FIXTURES:
for old, new, message in cases:
with self.subTest(name=name, new=new), FixtureCopy(name) as copy:
if name == "coordinator-manual-fixture":
# Drop the fixture's own key so an inserted one is not merely a duplicate.
copy.replace_in_skill("disable-model-invocation: true\n", "")
copy.replace_in_skill(old, new)
self.assertRejected(copy, message)
2026-11-25 19:01:50 -05:00
def test_frontmatter_lines_end_in_lf_only(self):
def replace_bytes(old, new, count=1):
return lambda copy: copy.write_file("SKILL.md", (copy.path / "SKILL.md").read_bytes().replace(old, new, count))
cases = (
("CRLF throughout", replace_bytes(b"\n", b"\r\n", -1)),
("CRLF after description", replace_bytes(b"\nmetadata:", b"\r\nmetadata:")),
("lone CR after description", replace_bytes(b"\nmetadata:", b"\rmetadata:")),
("U+2028 after description", replace_bytes(b"\nmetadata:", "\u2028metadata:".encode())),
("CRLF on opening delimiter", replace_bytes(b"---\n", b"---\r\n")),
("CRLF on closing delimiter", replace_bytes(b"\n---\n", b"\n---\r\n")),
)
for name in NEW_PAIR_FIXTURES:
for label, mutate in cases:
with self.subTest(name=name, case=label), FixtureCopy(name) as copy:
mutate(copy)
self.assertRejected(copy, "invalid SKILL.md frontmatter")
def test_line_break_rule_stops_at_the_frontmatter(self):
for name in NEW_PAIR_FIXTURES:
with self.subTest(name=name, case="CRLF body"), FixtureCopy(name) as copy:
text = (copy.path / "SKILL.md").read_text()
head, body = text.split("\n---\n", 1)
copy.write_file("SKILL.md", head + "\n---\n" + body.replace("\n", "\r\n") + "\u2028\n")
check_package(copy.path)
with self.subTest(name=name, case="frontmatter only, no final newline"), FixtureCopy(name) as copy:
text = (copy.path / "SKILL.md").read_text()
copy.write_file("SKILL.md", text.split("\n---\n", 1)[0] + "\n---")
check_package(copy.path)
2026-11-25 19:01:50 -05:00
def test_rejects_unsafe_or_undeclared_content(self):
cases = (
("BOM", lambda copy: copy.write_file("SKILL.md", b"\xef\xbb\xbf" + (copy.path / "SKILL.md").read_bytes()), "invalid text"),
("NUL", lambda copy: copy.write_file("notes.md", "a\x00b\n"), "invalid text"),
("invalid UTF-8", lambda copy: copy.write_file("notes.md", b"\xff\xfe\n"), "invalid UTF-8"),
("empty resource", lambda copy: copy.write_file("notes.md", b""), "text bounds"),
("undeclared", lambda copy: copy.write_file("notes.md", "extra\n", declare=False), "undeclared file"),
("script", lambda copy: copy.write_file("helper.py", "print('unsafe')\n"), "unsupported package content"),
("JSON resource", lambda copy: copy.write_file("data.json", "{}\n"), "unsupported package content"),
("missing declared", lambda copy: copy.write_manifest(dict(copy.manifest, files=copy.manifest["files"] + [{"path": "absent.md", "sha256": "0" * 64}])), "missing declared file"),
("escape", lambda copy: copy.write_manifest(dict(copy.manifest, files=copy.manifest["files"] + [{"path": "../outside.md", "sha256": "0" * 64}])), "invalid file path"),
("executable", lambda copy: os.chmod(copy.path / "SKILL.md", 0o755), "executable"),
("symlink", lambda copy: os.symlink(copy.path / "SKILL.md", copy.path / "link.md"), "is a link"),
)
for name in NEW_PAIR_FIXTURES:
for label, mutate, message in cases:
with self.subTest(name=name, case=label), FixtureCopy(name) as copy:
mutate(copy)
self.assertRejected(copy, message)
if __name__ == "__main__":
unittest.main()