diff --git "a/evals/run_evals.py" "b/evals/run_evals.py" new file mode 100644--- /dev/null +++ "b/evals/run_evals.py" @@ -0,0 +1,2856 @@ +#!/usr/bin/env python3 +"""Deterministic positive and controlled-failure evaluations for v1.3.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import re +import shutil +import sys +import tempfile +import threading +from datetime import datetime, timezone +from pathlib import Path +from typing import Callable + +try: + from jsonschema import Draft202012Validator, FormatChecker + from referencing import Registry, Resource +except ImportError as exc: # Fail visibly; schema validation is not optional. + print( + json.dumps( + { + "ok": False, + "error": "missing_dependency", + "message": f"jsonschema and referencing are required: {exc}", + }, + sort_keys=True, + ), + file=sys.stderr, + ) + raise SystemExit(2) from exc + + +ROOT = Path(__file__).resolve().parents[1] +RUNNER_PATH = ROOT / "evals" / "run_evals.py" +VERSION = "1.3.0" +NOW = "2026-07-30T00:00:00Z" +TARGETS = ( + "employee_memory", + "employee_worklog", + "team_journal", + "central_board", +) +SCHEMA_NAMES = ( + "handoff-packet.schema.json", + "persistence-contract.schema.json", + "dispatch-receipt.schema.json", + "log-append-receipt.schema.json", + "closure-receipt.schema.json", + "return-packet.schema.json", + "parent-verification.schema.json", +) + + +def load_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def observed_at() -> str: + return ( + datetime.now(timezone.utc) + .replace(microsecond=0) + .isoformat() + .replace("+00:00", "Z") + ) + + +def schema_registry() -> tuple[dict[str, dict], Registry]: + schemas: dict[str, dict] = {} + registry = Registry() + for name in SCHEMA_NAMES: + schema = load_json(ROOT / "contracts" / name) + Draft202012Validator.check_schema(schema) + schemas[name] = schema + registry = registry.with_resource( + schema["$id"], Resource.from_contents(schema) + ) + return schemas, registry + + +SCHEMAS, REGISTRY = schema_registry() + + +def validate(instance: dict, schema_name: str) -> None: + Draft202012Validator( + SCHEMAS[schema_name], + registry=REGISTRY, + format_checker=FormatChecker(), + ).validate(instance) + + +def expect_rejection(label: str, call: Callable[[], object]) -> str: + try: + call() + except Exception as exc: + message = f"{type(exc).__name__}: {exc}" + if not str(exc): + raise AssertionError(f"{label} rejected without a locatable message") + return message + raise AssertionError(f"{label} was accepted; expected rejection") + + +def assert_under(path: Path, root: Path) -> None: + try: + path.resolve().relative_to(root.resolve()) + except ValueError as exc: + raise AssertionError( + f"wrong authoritative root: {path.resolve()} is outside {root.resolve()}" + ) from exc + + +def iter_json_refs(value: object) -> list[str]: + refs: list[str] = [] + if isinstance(value, dict): + for key, child in value.items(): + if key == "$ref" and isinstance(child, str): + refs.append(child) + else: + refs.extend(iter_json_refs(child)) + elif isinstance(value, list): + for child in value: + refs.extend(iter_json_refs(child)) + return refs + + +def validate_package(base: Path = ROOT) -> list[str]: + required = [ + ".claude-plugin/plugin.json", + "README.md", + "README.zh-CN.md", + "SKILL.md", + "SKILL.zh-CN.md", + "SOP.md", + "SOP.zh-CN.md", + "中文用户看这里.md", + "references/rule-pack.md", + "references/rule-pack.zh-CN.md", + "references/adapter-contracts.md", + "references/adapter-contracts.zh-CN.md", + *[f"contracts/{name}" for name in SCHEMA_NAMES], + "evals/run_evals.py", + "evals/fixtures.json", + "evals/result.schema.json", + "evals/case-bundles/real-harness.json", + "evals/results/2026-07-30.json", + "manifests/handoff-protocol.json", + "manifests/handoff-rule-pack.json", + ] + missing = [relative for relative in required if not (base / relative).exists()] + if missing: + raise AssertionError( + "invalid_install: missing required package files: " + ", ".join(missing) + ) + + for name in SCHEMA_NAMES: + try: + candidate = load_json(base / "contracts" / name) + Draft202012Validator.check_schema(candidate) + except Exception as exc: + raise AssertionError( + f"invalid_install: malformed Schema contracts/{name}: " + f"{type(exc).__name__}: {exc}" + ) from exc + for ref in iter_json_refs(candidate): + if ref.startswith("#") or "://" in ref: + continue + ref_path = ( + base / "contracts" / ref.split("#", 1)[0] + ).resolve() + if not ref_path.is_file(): + raise AssertionError( + "invalid_install: unresolved local Schema reference " + f"contracts/{name} -> {ref}" + ) + try: + result_schema = load_json(base / "evals" / "result.schema.json") + Draft202012Validator.check_schema(result_schema) + except Exception as exc: + raise AssertionError( + "invalid_install: malformed Schema evals/result.schema.json: " + f"{type(exc).__name__}: {exc}" + ) from exc + saved_result = load_json(base / "evals" / "results" / "2026-07-30.json") + Draft202012Validator( + result_schema, format_checker=FormatChecker() + ).validate(saved_result) + copied_runner_hash = sha256(base / "evals" / "run_evals.py") + if saved_result["runner"]["sha256"] != copied_runner_hash: + raise AssertionError( + "invalid_install: saved result does not pin the packaged runner" + ) + plugin = load_json(base / ".claude-plugin" / "plugin.json") + if plugin["version"] != VERSION: + raise AssertionError( + f"invalid_install: plugin version is {plugin['version']}, " + f"expected {VERSION}" + ) + for relative in ( + "manifests/handoff-protocol.json", + "manifests/handoff-rule-pack.json", + ): + manifest = load_json(base / relative) + entrypoint = manifest["authority"]["entrypoint"].removeprefix("doc:") + entrypoint_hash = sha256(base / entrypoint) + source = manifest["source"] + if source["integrity"]["value"] != entrypoint_hash: + raise AssertionError( + f"invalid_install: manifest integrity drift in {relative}" + ) + expected_revision = f"sha256:{entrypoint_hash}" + if ( + source["type"] != "filesystem" + or source["location"] != "." + or source["revision"] != expected_revision + ): + raise AssertionError( + f"invalid_install: manifest source identity drift in {relative}" + ) + for evidence_group in ("implementation", "tests"): + for evidence in manifest["evidence"].get(evidence_group, []): + if not evidence.get("integrity"): + continue + evidence_path = ( + base / evidence["uri"].split(":", 1)[1].split("#", 1)[0] + ) + if evidence["integrity"]["value"] != sha256(evidence_path): + raise AssertionError( + f"invalid_install: {evidence_group} evidence drift " + f"in {relative}" + ) + for evidence in manifest["evidence"].get("tests", []): + evidence_path = ( + base / evidence["uri"].split(":", 1)[1].split("#", 1)[0] + ) + if evidence.get("observedAt") != saved_result["observed_at"]: + raise AssertionError( + f"invalid_install: test-evidence timestamp drift in {relative}" + ) + tests = manifest["verification"]["tests"] + if any( + test.get("lastRunAt") != saved_result["observed_at"] + for test in tests + ): + raise AssertionError( + f"invalid_install: verification timestamp drift in {relative}" + ) + + markdown_files = [ + relative for relative in required if relative.lower().endswith(".md") + ] + for relative in markdown_files: + text = (base / relative).read_text(encoding="utf-8") + for raw_link in re.findall(r"\]\(([^)]+)\)", text): + local = raw_link.split("#", 1)[0] + if not local or "://" in local: + continue + target = (base / Path(relative).parent / local).resolve() + try: + target.relative_to(base.resolve()) + except ValueError as exc: + raise AssertionError( + f"invalid_install: {relative} link escapes package: {local}" + ) from exc + if not target.exists(): + raise AssertionError( + f"invalid_install: {relative} link target is missing: {local}" + ) + return [ + f"{len(required)} required package files present", + f"{len(markdown_files)} package Markdown files have complete local links", + f"{len(SCHEMA_NAMES) + 1} JSON Schemas are Draft 2020-12 valid", + "all local JSON Schema references resolve inside the package", + ] + + +def validate_bilingual_parity() -> tuple[list[str], list[str]]: + pairs = ( + ("SKILL.md", "SKILL.zh-CN.md"), + ("README.md", "README.zh-CN.md"), + ("SOP.md", "SOP.zh-CN.md"), + ("references/rule-pack.md", "references/rule-pack.zh-CN.md"), + ( + "references/adapter-contracts.md", + "references/adapter-contracts.zh-CN.md", + ), + ) + texts: dict[str, str] = {} + for left, right in pairs: + left_text = (ROOT / left).read_text(encoding="utf-8") + right_text = (ROOT / right).read_text(encoding="utf-8") + texts[left] = left_text + texts[right] = right_text + left_headings = re.findall(r"^#{1,6} ", left_text, flags=re.MULTILINE) + right_headings = re.findall(r"^#{1,6} ", right_text, flags=re.MULTILINE) + if len(left_headings) != len(right_headings): + raise AssertionError( + f"bilingual heading drift: {left}={len(left_headings)} " + f"{right}={len(right_headings)}" + ) + + critical_tokens = { + "SKILL.md": ( + "bounded_subagent", + "independent_task", + "persistence", + "closure receipt", + "authoritative root", + "central-board", + "handoff_id", + "contract_id", + "dispatch_id", + "evidence_nonce", + "evidence_anchor", + "separate choices", + ), + "SKILL.zh-CN.md": ( + "bounded_subagent", + "independent_task", + "持久化", + "收口回执", + "权威根", + "中央看板", + "handoff_id", + "contract_id", + "dispatch_id", + "evidence_nonce", + "evidence_anchor", + "分开判断", + ), + "references/rule-pack.md": ( + "agent.task.create", + "authoritative_root", + "employee_memory", + "employee_worklog", + "team_journal", + "central_board", + "handoff_id", + "contract_id", + "dispatch_id", + "evidence_nonce", + "evidence_anchor", + "separate axes", + ), + "references/rule-pack.zh-CN.md": ( + "agent.task.create", + "authoritative_root", + "employee_memory", + "employee_worklog", + "team_journal", + "central_board", + "handoff_id", + "contract_id", + "dispatch_id", + "evidence_nonce", + "evidence_anchor", + "两条独立轴", + ), + "references/adapter-contracts.md": ( + "agent.task.create", + "workspace.authoritative.resolve", + "exit code zero", + "handoff_id", + "contract_id", + "dispatch_id", + "evidence_nonce", + "evidence_anchor", + "Persistence does not choose", + ), + "references/adapter-contracts.zh-CN.md": ( + "agent.task.create", + "workspace.authoritative.resolve", + "退出码 0", + "handoff_id", + "contract_id", + "dispatch_id", + "evidence_nonce", + "evidence_anchor", + "持久化要求不决定", + ), + } + for relative, tokens in critical_tokens.items(): + missing = [token for token in tokens if token not in texts[relative]] + if missing: + raise AssertionError( + f"bilingual critical-contract drift in {relative}: {missing}" + ) + authority_pairs = ( + ("README.md", "README.zh-CN.md"), + ("SKILL.md", "SKILL.zh-CN.md"), + ("references/rule-pack.md", "references/rule-pack.zh-CN.md"), + ( + "references/adapter-contracts.md", + "references/adapter-contracts.zh-CN.md", + ), + ) + for english, chinese in authority_pairs: + if "English edition" not in texts[english]: + raise AssertionError(f"language authority drift in {english}") + if "英文版" not in texts[chinese]: + raise AssertionError(f"language authority drift in {chinese}") + return ( + [ + "five English/Chinese document pairs have matching heading counts", + "execution-mode, persistence, four-target, root, and adapter terms exist in both languages", + "all bilingual authority footers name English as authoritative", + ], + [ + "SKILL.md + SKILL.zh-CN.md", + "references/rule-pack.md + references/rule-pack.zh-CN.md", + "references/adapter-contracts.md + references/adapter-contracts.zh-CN.md", + ], + ) + + +def assert_version_values( + plugin_version: str, manifest_versions: list[str], document_texts: list[str] +) -> None: + versions = [plugin_version, *manifest_versions] + if any(value != VERSION for value in versions): + raise AssertionError( + f"version drift: expected {VERSION}, observed {versions}" + ) + marker = f"**{VERSION}**" + if any(marker not in text for text in document_texts): + raise AssertionError(f"version drift: document missing marker {marker}") + + +def validate_versions_and_manifests( + component_schema_path: str | None, +) -> tuple[list[str], list[str]]: + plugin = load_json(ROOT / ".claude-plugin" / "plugin.json") + manifest_paths = sorted((ROOT / "manifests").glob("*.json")) + expected_names = {"handoff-protocol.json", "handoff-rule-pack.json"} + if {path.name for path in manifest_paths} != expected_names: + raise AssertionError("component manifest set is incomplete") + manifests = [load_json(path) for path in manifest_paths] + assert_version_values( + plugin["version"], + [manifest["release"]["version"] for manifest in manifests], + [ + (ROOT / "SKILL.md").read_text(encoding="utf-8"), + (ROOT / "SKILL.zh-CN.md").read_text(encoding="utf-8"), + (ROOT / "README.md").read_text(encoding="utf-8"), + (ROOT / "README.zh-CN.md").read_text(encoding="utf-8"), + ], + ) + for manifest in manifests: + if manifest["schemaVersion"] != "agent-modpack.component/v0.2-draft": + raise AssertionError("unexpected component schema version") + if manifest["executionModel"] != "discipline-document": + raise AssertionError("runtime capability was falsely claimed") + entry = manifest["authority"]["entrypoint"].removeprefix("doc:") + actual = sha256(ROOT / entry) + declared = manifest["source"]["integrity"]["value"] + if declared != actual: + raise AssertionError( + f"manifest integrity drift for {manifest['id']}: " + f"declared={declared} actual={actual}" + ) + expected_revision = f"sha256:{actual}" + if ( + manifest["source"]["type"] != "filesystem" + or manifest["source"]["location"] != "." + or manifest["source"]["revision"] != expected_revision + ): + raise AssertionError( + f"manifest source identity drift for {manifest['id']}: " + f"expected filesystem . {expected_revision}" + ) + capability_versions = [ + item["version"] for item in manifest["capabilities"]["provides"] + ] + if any(value != VERSION for value in capability_versions): + raise AssertionError( + f"capability version drift in {manifest['id']}: " + f"{capability_versions}" + ) + for evidence_group in ("implementation", "tests"): + for evidence in manifest["evidence"].get(evidence_group, []): + uri = evidence["uri"].split("#", 1)[0] + if ":" not in uri or not evidence.get("integrity"): + continue + relative = uri.split(":", 1)[1] + evidence_path = ROOT / relative + if not evidence_path.is_file(): + raise AssertionError( + f"manifest evidence missing for {manifest['id']}: {relative}" + ) + declared_evidence_hash = evidence["integrity"]["value"] + actual_evidence_hash = sha256(evidence_path) + if declared_evidence_hash != actual_evidence_hash: + raise AssertionError( + f"manifest evidence drift for {manifest['id']} " + f"{relative}: declared={declared_evidence_hash} " + f"actual={actual_evidence_hash}" + ) + + saved_result = load_json(ROOT / "evals" / "results" / "2026-07-30.json") + result_schema = load_json(ROOT / "evals" / "result.schema.json") + Draft202012Validator( + result_schema, format_checker=FormatChecker() + ).validate(saved_result) + if saved_result["version"] != VERSION or saved_result["ok"] is not True: + raise AssertionError("saved v1.3 evidence is not a successful v1.3 result") + current_runner_hash = sha256(RUNNER_PATH) + if saved_result["runner"]["sha256"] != current_runner_hash: + raise AssertionError( + "saved evidence runner hash drift: " + f"declared={saved_result['runner']['sha256']} " + f"actual={current_runner_hash}" + ) + if any(item["status"] != "pass" for item in saved_result["results"]): + raise AssertionError("saved result has ok=true but contains a failed case") + if saved_result["component_schema"] is None: + raise AssertionError( + "saved result does not identify the frozen external component Schema" + ) + fixture_ids = { + item["id"] for item in load_json(ROOT / "evals" / "fixtures.json")["fixtures"] + } + saved_ids = {item["id"] for item in saved_result["results"]} + if fixture_ids != saved_ids: + raise AssertionError( + f"saved evidence does not cover fixture set: " + f"fixtures={sorted(fixture_ids)} saved={sorted(saved_ids)}" + ) + + checks = [ + "plugin, Skills, READMEs, manifests, and capabilities agree on v1.3.0", + "manifest entrypoint SHA-256 values match real files", + "manifest test-evidence SHA-256 values match the saved result", + "saved v1.3 result validates, pins this runner, and covers every fixture", + "two component manifests retain discipline-document execution", + ] + evidence = [ + ".claude-plugin/plugin.json", + "manifests/handoff-protocol.json", + "manifests/handoff-rule-pack.json", + ] + if component_schema_path: + schema = load_json(Path(component_schema_path)) + Draft202012Validator.check_schema(schema) + validator = Draft202012Validator(schema, format_checker=FormatChecker()) + for manifest in manifests: + validator.validate(manifest) + checks.append("external component schema validation passed") + evidence.append( + "component-schema:" + f"{schema.get('$id', '')}#sha256={sha256(Path(component_schema_path))}" + ) + else: + checks.append("external component schema was not requested") + return checks, evidence + + +def create_authoritative_root(base: Path, root_id: str = "fictional-team") -> dict: + root = base / "authoritative" + root.mkdir(parents=True) + sentinel = root / ".handoff-authority.json" + sentinel.write_text( + json.dumps({"root_id": root_id}, sort_keys=True) + "\n", + encoding="utf-8", + ) + return { + "root_id": root_id, + "resolved_path": str(root.resolve()), + "resolution_evidence": "sentinel:.handoff-authority.json#root_id", + } + + +def verify_authoritative_root(root_info: dict) -> Path: + root = Path(root_info["resolved_path"]).resolve() + sentinel = root / ".handoff-authority.json" + if not sentinel.is_file(): + raise AssertionError(f"authoritative-root sentinel missing: {sentinel}") + observed = load_json(sentinel) + if observed.get("root_id") != root_info["root_id"]: + raise AssertionError( + f"authoritative-root ID mismatch: expected={root_info['root_id']} " + f"observed={observed.get('root_id')}" + ) + return root + + +def make_persistence_contract( + root_info: dict, + *, + required: bool, + handoff_id: str = "handoff-fictional-001", + contract_id: str = "contract-fictional-001", +) -> dict: + root = Path(root_info["resolved_path"]) + paths = { + "employee_memory": root / "employee" / "memory.md", + "employee_worklog": root / "employee" / "worklog.md", + "team_journal": root / "shared" / "team-journal.jsonl", + "central_board": root / "shared" / "central-board.jsonl", + } + targets = [] + for target in TARGETS: + if not required: + targets.append( + { + "target": target, + "requirement": "not_applicable", + "writer": "none", + "verification": "not_applicable", + "reason": "Bounded fictional subtask produced no durable fact.", + } + ) + continue + if target == "team_journal": + writer = "recipient" + verification = "provider_receipt" + elif target == "central_board": + writer = "parent" + verification = "parent_readback" + else: + writer = "recipient" + verification = "parent_readback" + targets.append( + { + "target": target, + "requirement": "required", + "writer": writer, + "path": str(paths[target].resolve()), + "evidence_nonce": ( + f"FIXTURE-NONCE::{handoff_id}::{contract_id}::{target}" + ), + "verification": verification, + } + ) + contract = { + "handoff_id": handoff_id, + "contract_id": contract_id, + "authoritative_root": root_info, + "targets": targets, + } + validate_persistence_contract(contract) + return contract + + +def validate_persistence_contract(contract: dict) -> None: + validate(contract, "persistence-contract.schema.json") + observed = [item["target"] for item in contract["targets"]] + if len(observed) != len(set(observed)): + raise AssertionError(f"duplicate persistence targets: {observed}") + if set(observed) != set(TARGETS): + raise AssertionError( + f"persistence targets must be exactly {list(TARGETS)}; observed={observed}" + ) + required_nonces = [ + item["evidence_nonce"] + for item in contract["targets"] + if item["requirement"] == "required" + ] + if len(required_nonces) != len(set(required_nonces)): + raise AssertionError( + "required persistence targets must use distinct evidence nonces" + ) + root = verify_authoritative_root(contract["authoritative_root"]) + for item in contract["targets"]: + if item["requirement"] == "required": + assert_under(Path(item["path"]), root) + + +class AdapterFailure(RuntimeError): + def __init__(self, capability: str, exit_code: int, detail: str) -> None: + self.capability = capability + self.exit_code = exit_code + super().__init__( + f"{capability} failed with exit_code={exit_code}: {detail}" + ) + + +class FakeHarness: + def __init__( + self, + *, + can_spawn: bool, + can_create_task: bool, + can_message: bool = False, + log_exit_code: int = 0, + ) -> None: + self.can_spawn = can_spawn + self.can_create_task = can_create_task + self.can_message = can_message + self.log_exit_code = log_exit_code + self.calls: list[dict] = [] + self._journal_lock = threading.Lock() + self._event_counter = 0 + + def spawn( + self, + recipient: str, + requested_mode: str, + *, + handoff_id: str, + contract_id: str | None = None, + degradation_reason: str | None = None, + ) -> dict: + if not self.can_spawn: + raise AdapterFailure("agent.spawn", 69, "capability unavailable") + receipt = { + "handoff_id": handoff_id, + "dispatch_id": f"spawn-{len(self.calls) + 1:03d}", + "recipient_id": recipient, + "timestamp": NOW, + "status": "accepted", + "requested_mode": requested_mode, + "effective_mode": "bounded_subagent", + "provider": {"fake_harness": True}, + } + if contract_id: + receipt["contract_id"] = contract_id + if requested_mode == "independent_task": + receipt["degraded_from"] = "independent_task" + receipt["degradation_reason"] = degradation_reason or ( + "agent.task.create unavailable" + ) + validate(receipt, "dispatch-receipt.schema.json") + self.calls.append({"method": "agent.spawn", "receipt": receipt}) + return receipt + + def create_task(self, recipient: str, packet: dict) -> dict: + if not self.can_create_task: + raise AdapterFailure( + "agent.task.create", 69, "capability unavailable" + ) + receipt = { + "handoff_id": packet["handoff_id"], + "contract_id": packet["persistence_contract"]["contract_id"], + "dispatch_id": f"task-dispatch-{len(self.calls) + 1:03d}", + "recipient_id": recipient, + "timestamp": NOW, + "status": "accepted", + "requested_mode": "independent_task", + "effective_mode": "independent_task", + "task_id": ( + f"fictional-task-{len(self.calls) + 1:03d}-" + f"{packet['handoff_id']}" + ), + "workspace_receipt": packet["persistence_contract"][ + "authoritative_root" + ], + "provider": {"fake_harness": True}, + } + validate(receipt, "dispatch-receipt.schema.json") + self.calls.append({"method": "agent.task.create", "receipt": receipt}) + return receipt + + def append_journal(self, path: Path, event: dict) -> dict: + if self.log_exit_code != 0: + self.calls.append( + { + "method": "collaboration.log.append", + "status": "failed", + "exit_code": self.log_exit_code, + } + ) + raise AdapterFailure( + "collaboration.log.append", + self.log_exit_code, + "controlled fake-provider failure", + ) + with self._journal_lock: + path.parent.mkdir(parents=True, exist_ok=True) + position = ( + len(path.read_text(encoding="utf-8").splitlines()) + if path.exists() + else 0 + ) + with path.open("a", encoding="utf-8", newline="\n") as handle: + handle.write(json.dumps(event, sort_keys=True) + "\n") + self._event_counter += 1 + receipt = { + "exit_code": 0, + "event_id": f"event-{self._event_counter:03d}", + "timestamp": NOW, + "append_position": position, + "provider": {"fake_atomic_lock": True}, + } + validate(receipt, "log-append-receipt.schema.json") + self.calls.append( + { + "method": "collaboration.log.append", + "path": str(path.resolve()), + "event": copy.deepcopy(event), + "receipt": receipt, + } + ) + return receipt + + +def make_handoff_packet( + contract: dict, + *, + mode: str, + allow_degradation: bool = False, + continuity_required: bool = False, +) -> dict: + packet = { + "goal": "Complete one fictional delegated task and close it durably.", + "context_constraints": [ + "Use the temporary authoritative root only.", + "Use fictional data and no network.", + ], + "acceptance_criteria": [ + "Return valid evidence and parent-verifiable closure receipts." + ], + "known_pitfalls": [ + "Do not treat a child claim, worktree, or overlay write as proof." + ], + "handoff_id": contract["handoff_id"], + "execution_mode": mode, + "continuity_required": continuity_required, + "allow_mode_degradation": allow_degradation, + "persistence_contract": contract, + } + validate(packet, "handoff-packet.schema.json") + if packet.get("persistence_contract") and ( + packet.get("handoff_id") + != packet["persistence_contract"].get("handoff_id") + ): + raise AssertionError("handoff packet and persistence contract IDs differ") + validate_persistence_contract(contract) + if packet["handoff_id"] != contract["handoff_id"]: + raise AssertionError("handoff packet and persistence contract IDs differ") + return packet + + +def route_dispatch( + harness: FakeHarness, recipient: str, packet: dict +) -> dict: + validate(packet, "handoff-packet.schema.json") + if packet.get("persistence_contract") and ( + packet.get("handoff_id") + != packet["persistence_contract"].get("handoff_id") + ): + raise AssertionError("handoff packet and persistence contract IDs differ") + mode = packet.get("execution_mode", "bounded_subagent") + handoff_id = packet.get("handoff_id") or "handoff-legacy-v1.2" + contract_id = packet.get("persistence_contract", {}).get("contract_id") + if mode == "independent_task": + if harness.can_create_task: + return harness.create_task(recipient, packet) + if ( + packet.get("allow_mode_degradation") is True + and packet.get("continuity_required") is not True + and harness.can_spawn + ): + return harness.spawn( + recipient, + mode, + handoff_id=handoff_id, + contract_id=contract_id, + degradation_reason=( + "agent.task.create unavailable; packet explicitly permits " + "bounded_subagent degradation" + ), + ) + receipt = { + "handoff_id": handoff_id, + "contract_id": contract_id, + "recipient_id": recipient, + "timestamp": NOW, + "status": "undelivered", + "requested_mode": "independent_task", + "reason": ( + "agent.task.create unavailable; no permitted bounded_subagent " + "degradation" + ), + } + if contract_id is None: + receipt.pop("contract_id") + validate(receipt, "dispatch-receipt.schema.json") + return receipt + if not harness.can_spawn: + receipt = { + "handoff_id": handoff_id, + "recipient_id": recipient, + "timestamp": NOW, + "status": "undelivered", + "requested_mode": "bounded_subagent", + "reason": "agent.spawn unavailable", + } + validate(receipt, "dispatch-receipt.schema.json") + return receipt + return harness.spawn( + recipient, + "bounded_subagent", + handoff_id=handoff_id, + contract_id=contract_id, + ) + + +def make_fictional_dispatch_receipt( + contract: dict, dispatch_id: str +) -> dict: + receipt = { + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_id, + "recipient_id": "fictional-employee", + "timestamp": NOW, + "status": "accepted", + "requested_mode": "bounded_subagent", + "effective_mode": "bounded_subagent", + "provider": {"fictional_test_fixture": True}, + } + validate(receipt, "dispatch-receipt.schema.json") + return receipt + + +def expected_evidence_anchor( + contract: dict, target: str, dispatch_id: str +) -> str: + target_contract = next( + item for item in contract["targets"] if item["target"] == target + ) + return ( + f"HANDOFF-EVIDENCE::{contract['handoff_id']}::" + f"{contract['contract_id']}::{dispatch_id}::{target}::" + f"{target_contract['evidence_nonce']}" + ) + + +class CentralBoardWriter: + def __init__(self, writer_id: str) -> None: + self.writer_id = writer_id + self._lock = threading.Lock() + + def apply( + self, + path: Path, + marker: str, + *, + actor: str, + evidence_anchor: str | None = None, + ) -> None: + if actor != self.writer_id: + raise PermissionError( + f"central_board single-writer violation: actor={actor} " + f"expected={self.writer_id}" + ) + with self._lock: + path.parent.mkdir(parents=True, exist_ok=True) + record = {"marker": marker} + if evidence_anchor is not None: + record["evidence_anchor"] = evidence_anchor + with path.open("a", encoding="utf-8", newline="\n") as handle: + handle.write(json.dumps(record, sort_keys=True) + "\n") + + +def produce_required_receipts( + contract: dict, harness: FakeHarness, *, dispatch_id: str +) -> tuple[list[dict], dict[str, str]]: + target_map = {item["target"]: item for item in contract["targets"]} + markers = { + "employee_memory": "MEMORY-CANARY-001", + "employee_worklog": "WORKLOG-CANARY-001", + "team_journal": "JOURNAL-CANARY-001", + "central_board": "BOARD-PROPOSAL-001", + } + receipts: list[dict] = [] + for target in ("employee_memory", "employee_worklog"): + path = Path(target_map[target]["path"]) + evidence_anchor = expected_evidence_anchor( + contract, target, dispatch_id + ) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + evidence_anchor + "\n" + markers[target] + "\n", + encoding="utf-8", + ) + receipts.append( + { + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_id, + "target": target, + "status": "updated", + "writer": "recipient", + "path": str(path), + "evidence": { + "kind": "content_anchor", + "value": markers[target], + "evidence_anchor": evidence_anchor, + }, + } + ) + + journal_path = Path(target_map["team_journal"]["path"]) + journal_anchor = expected_evidence_anchor( + contract, "team_journal", dispatch_id + ) + log_receipt = harness.append_journal( + journal_path, + { + "marker": markers["team_journal"], + "evidence_anchor": journal_anchor, + }, + ) + receipts.append( + { + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_id, + "target": "team_journal", + "status": "updated", + "writer": "recipient", + "path": str(journal_path), + "evidence": { + "kind": "provider_receipt", + "value": markers["team_journal"], + "evidence_anchor": journal_anchor, + "exit_code": log_receipt["exit_code"], + "event_id": log_receipt["event_id"], + "append_position": log_receipt["append_position"], + "timestamp": log_receipt["timestamp"], + "provider": log_receipt["provider"], + }, + } + ) + + board_path = Path(target_map["central_board"]["path"]) + board_anchor = expected_evidence_anchor( + contract, "central_board", dispatch_id + ) + receipts.append( + { + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_id, + "target": "central_board", + "status": "proposed_for_parent", + "writer": "recipient", + "path": str(board_path), + "evidence": { + "kind": "proposal", + "value": markers["central_board"], + "evidence_anchor": board_anchor, + }, + } + ) + for receipt in receipts: + validate(receipt, "closure-receipt.schema.json") + return receipts, markers + + +def produce_na_receipts(contract: dict, *, dispatch_id: str) -> list[dict]: + receipts = [] + for item in contract["targets"]: + receipt = { + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_id, + "target": item["target"], + "status": "not_applicable", + "writer": "none", + "reason": item["reason"], + } + validate(receipt, "closure-receipt.schema.json") + receipts.append(receipt) + return receipts + + +def validate_dispatch_linkage( + contract: dict, dispatch_receipt: dict +) -> None: + validate(dispatch_receipt, "dispatch-receipt.schema.json") + if dispatch_receipt["status"] != "accepted": + raise AssertionError( + "persistence chain cannot link to an undelivered dispatch" + ) + expected_ids = { + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + } + for field, expected in expected_ids.items(): + if dispatch_receipt.get(field) != expected: + raise AssertionError( + f"cross-task dispatch receipt: {field} expected={expected} " + f"observed={dispatch_receipt.get(field)}" + ) + if dispatch_receipt["effective_mode"] == "independent_task": + expected_root = contract["authoritative_root"] + observed_root = dispatch_receipt["workspace_receipt"] + for field in ("root_id", "resolution_evidence"): + if observed_root[field] != expected_root[field]: + raise AssertionError( + "dispatch workspace receipt mismatch: " + f"{field} expected={expected_root[field]} " + f"observed={observed_root[field]}" + ) + expected_path = Path(expected_root["resolved_path"]).resolve() + observed_path = Path(observed_root["resolved_path"]).resolve() + if observed_path != expected_path: + raise AssertionError( + "dispatch workspace receipt mismatch: resolved_path " + f"expected={expected_path} observed={observed_path}" + ) + + +def validate_return_linkage( + return_packet: dict, contract: dict, dispatch_receipt: dict +) -> None: + validate(return_packet, "return-packet.schema.json") + if len(return_packet.get("closure_receipts", [])) != len(TARGETS): + raise AssertionError( + "persistence contract return requires exactly four closure receipts" + ) + validate_dispatch_linkage(contract, dispatch_receipt) + if ( + "execution_mode" in return_packet + and return_packet["execution_mode"] + != dispatch_receipt["effective_mode"] + ): + raise AssertionError( + "return execution-mode mismatch: " + f"expected={dispatch_receipt['effective_mode']} " + f"observed={return_packet['execution_mode']}" + ) + expected_ids = { + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_receipt["dispatch_id"], + } + for field, expected in expected_ids.items(): + if return_packet.get(field) != expected: + raise AssertionError( + f"cross-task return mix: {field} expected={expected} " + f"observed={return_packet.get(field)}" + ) + for receipt in return_packet.get("closure_receipts", []): + for field, expected in expected_ids.items(): + if receipt[field] != expected: + raise AssertionError( + f"cross-task closure mix in return: {field} " + f"expected={expected} observed={receipt[field]}" + ) + + +def verify_closure( + contract: dict, + closure_receipts: list[dict], + *, + dispatch_receipt: dict, + board_writer: CentralBoardWriter | None, + log_calls: list[dict] | None = None, +) -> dict: + validate_persistence_contract(contract) + validate_dispatch_linkage(contract, dispatch_receipt) + dispatch_id = dispatch_receipt["dispatch_id"] + for receipt in closure_receipts: + validate(receipt, "closure-receipt.schema.json") + expected_ids = { + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_id, + } + for field, expected_id in expected_ids.items(): + if receipt[field] != expected_id: + raise AssertionError( + f"cross-task closure mix: {field} expected={expected_id} " + f"observed={receipt[field]}" + ) + + contract_map = {item["target"]: item for item in contract["targets"]} + receipt_targets = [item["target"] for item in closure_receipts] + if len(receipt_targets) != len(set(receipt_targets)): + raise AssertionError(f"duplicate closure receipts: {receipt_targets}") + if set(receipt_targets) != set(contract_map): + raise AssertionError( + f"partial closure: expected={sorted(contract_map)} " + f"observed={sorted(receipt_targets)}" + ) + receipt_map = {item["target"]: item for item in closure_receipts} + root = verify_authoritative_root(contract["authoritative_root"]) + checks = [] + + for target in TARGETS: + expected = contract_map[target] + observed = receipt_map[target] + if expected["requirement"] == "not_applicable": + if observed["status"] != "not_applicable" or not observed.get( + "reason" + ): + raise AssertionError(f"{target} lacks a reasoned N/A receipt") + checks.append( + { + "target": target, + "status": "not_applicable", + "evidence": observed["reason"], + } + ) + continue + + if target != "central_board" and observed["writer"] != expected["writer"]: + raise AssertionError( + f"{target} writer mismatch: expected={expected['writer']} " + f"observed={observed['writer']}" + ) + observed_path = Path(observed["path"]).resolve() + expected_path = Path(expected["path"]).resolve() + assert_under(observed_path, root) + if observed_path != expected_path: + raise AssertionError( + f"{target} path mismatch: expected={expected_path} " + f"observed={observed_path}" + ) + evidence_kind = observed["evidence"]["kind"] + marker = observed["evidence"]["value"] + evidence_anchor = observed["evidence"]["evidence_anchor"] + expected_anchor = expected_evidence_anchor( + contract, target, dispatch_id + ) + if evidence_anchor != expected_anchor: + raise AssertionError( + f"{target} evidence anchor mismatch: " + f"expected={expected_anchor} observed={evidence_anchor}" + ) + if expected["verification"] == "provider_receipt": + if evidence_kind != "provider_receipt": + raise AssertionError( + f"{target} verification mismatch: contract requires " + "provider_receipt" + ) + elif expected["verification"] == "parent_readback": + allowed = ( + {"proposal"} + if target == "central_board" + else {"content_anchor", "sha256"} + ) + if evidence_kind not in allowed: + raise AssertionError( + f"{target} verification mismatch: " + f"expected one of {sorted(allowed)} observed={evidence_kind}" + ) + + if target == "central_board": + if observed["status"] != "proposed_for_parent": + raise AssertionError("child must propose, not claim board update") + if board_writer is None: + raise AssertionError("central_board proposal has no single writer") + expected_board_writer = ( + "parent" + if expected["writer"] == "parent" + else expected.get("writer_id") + ) + if board_writer.writer_id != expected_board_writer: + raise AssertionError( + "central_board writer mismatch: " + f"expected={expected_board_writer} " + f"observed={board_writer.writer_id}" + ) + board_writer.apply( + observed_path, + marker, + actor=board_writer.writer_id, + evidence_anchor=evidence_anchor, + ) + else: + if observed["status"] != "updated": + raise AssertionError(f"{target} was not reported updated") + + if target == "team_journal": + evidence = observed["evidence"] + if ( + evidence["kind"] != "provider_receipt" + or evidence.get("exit_code") != 0 + or not evidence.get("event_id") + or "append_position" not in evidence + or not evidence.get("timestamp") + or not evidence.get("provider") + ): + raise AssertionError("team_journal lacks an exit-zero append receipt") + matches = [ + call + for call in (log_calls or []) + if call.get("method") == "collaboration.log.append" + and call.get("receipt", {}).get("event_id") + == evidence["event_id"] + ] + if len(matches) != 1: + raise AssertionError( + "team_journal provider receipt is not backed by exactly " + "one adapter call" + ) + provider_call = matches[0] + provider_receipt = provider_call["receipt"] + for field in ( + "exit_code", + "event_id", + "append_position", + "timestamp", + "provider", + ): + if evidence[field] != provider_receipt[field]: + raise AssertionError( + f"team_journal provider receipt mismatch: {field}" + ) + if Path(provider_call["path"]).resolve() != observed_path: + raise AssertionError("team_journal provider wrote a different path") + if provider_call["event"].get("marker") != marker: + raise AssertionError("team_journal provider appended a different event") + if ( + provider_call["event"].get("evidence_anchor") + != evidence_anchor + ): + raise AssertionError( + "team_journal provider appended a different evidence anchor" + ) + + if not observed_path.is_file(): + raise AssertionError(f"partial landing: {target} file missing") + content = observed_path.read_text(encoding="utf-8") + if target == "team_journal": + lines = content.splitlines() + position = observed["evidence"]["append_position"] + if position >= len(lines): + raise AssertionError( + "team_journal append position is outside the real file" + ) + event = json.loads(lines[position]) + if event.get("marker") != marker: + raise AssertionError( + "team_journal append position does not contain the marker" + ) + if event.get("evidence_anchor") != evidence_anchor: + raise AssertionError( + "team_journal append position does not contain " + "the contract evidence anchor" + ) + else: + if evidence_anchor not in content: + raise AssertionError( + f"parent readback evidence anchor missing for {target}: " + f"{evidence_anchor}" + ) + if evidence_kind == "sha256": + actual_digest = sha256(observed_path) + if actual_digest != marker: + raise AssertionError( + f"parent readback SHA-256 mismatch for {target}: " + f"declared={marker} actual={actual_digest}" + ) + elif marker not in content: + raise AssertionError( + f"parent readback content marker missing for {target}: {marker}" + ) + checks.append( + { + "target": target, + "status": "verified", + "path": str(observed_path), + "evidence": f"parent readback found {marker}", + } + ) + + trace = { + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_id, + "status": "pass", + "authoritative_root": contract["authoritative_root"], + "checks": checks, + } + validate(trace, "parent-verification.schema.json") + return trace + + +def eval_four_target_closeout( + component_schema_path: str | None, +) -> tuple[list[str], list[str]]: + package_checks = validate_package() + bilingual_checks, bilingual_evidence = validate_bilingual_parity() + manifest_checks, manifest_evidence = validate_versions_and_manifests( + component_schema_path + ) + with tempfile.TemporaryDirectory(prefix="handoff-v13-four-target-") as tmp: + root_info = create_authoritative_root(Path(tmp)) + contract = make_persistence_contract(root_info, required=True) + packet = make_handoff_packet( + contract, + mode="independent_task", + continuity_required=True, + ) + harness = FakeHarness(can_spawn=True, can_create_task=True) + dispatch_receipt = route_dispatch(harness, "fictional-employee", packet) + closure_receipts, _ = produce_required_receipts( + contract, + harness, + dispatch_id=dispatch_receipt["dispatch_id"], + ) + return_packet = { + "conclusion": "The fictional independent task closed all four targets.", + "evidence": [ + dispatch_receipt["dispatch_id"], + "four closure receipts", + ], + "gaps": [], + "artifact_paths": [ + item["path"] + for item in closure_receipts + if item["status"] != "not_applicable" + ], + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_receipt["dispatch_id"], + "execution_mode": "independent_task", + "closure_receipts": closure_receipts, + } + validate_return_linkage(return_packet, contract, dispatch_receipt) + trace = verify_closure( + contract, + closure_receipts, + dispatch_receipt=dispatch_receipt, + board_writer=CentralBoardWriter("parent"), + log_calls=harness.calls, + ) + if len(trace["checks"]) != 4: + raise AssertionError("parent verification did not check all four targets") + if any(item["status"] != "verified" for item in trace["checks"]): + raise AssertionError("a required target was not verified") + + return ( + package_checks + + bilingual_checks + + manifest_checks + + [ + "independent-task dispatch receipt is schema-valid", + "return packet contains four schema-valid closure receipts", + "parent read four of four targets from the authoritative root", + ], + bilingual_evidence + + manifest_evidence + + [ + "contracts/handoff-packet.schema.json", + "contracts/return-packet.schema.json", + "contracts/parent-verification.schema.json", + ], + ) + + +def eval_atomic_log() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-log-") as tmp: + journal = Path(tmp) / "journal.jsonl" + harness = FakeHarness(can_spawn=False, can_create_task=False) + receipts: list[dict] = [] + errors: list[Exception] = [] + + def append(index: int) -> None: + try: + receipts.append( + harness.append_journal(journal, {"event": f"E-{index:02d}"}) + ) + except Exception as exc: # surfaced below + errors.append(exc) + + threads = [threading.Thread(target=append, args=(index,)) for index in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + if errors: + raise AssertionError(f"concurrent append errors: {errors}") + lines = journal.read_text(encoding="utf-8").splitlines() + observed_events = { + json.loads(line).get("event") for line in lines + } + expected_events = {f"E-{index:02d}" for index in range(8)} + ids = [receipt["event_id"] for receipt in receipts] + positions = [receipt["append_position"] for receipt in receipts] + if ( + len(lines) != 8 + or observed_events != expected_events + or len(set(ids)) != 8 + or set(positions) != set(range(8)) + ): + raise AssertionError( + f"atomic append loss/corruption: lines={len(lines)} " + f"events={sorted(str(item) for item in observed_events)} " + f"ids={ids} positions={positions}" + ) + return ( + [ + "eight concurrent appends produced eight exit-zero receipts", + "event IDs and append positions are unique", + "journal contains the exact eight distinct fictional events", + ], + ["contracts/log-append-receipt.schema.json"], + ) + + +def eval_independent_routing() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-route-") as tmp: + contract = make_persistence_contract( + create_authoritative_root(Path(tmp)), required=True + ) + packet = make_handoff_packet(contract, mode="independent_task") + harness = FakeHarness(can_spawn=True, can_create_task=True) + receipt = route_dispatch(harness, "fictional-employee", packet) + methods = [call["method"] for call in harness.calls] + if methods != ["agent.task.create"]: + raise AssertionError(f"wrong adapter routing: {methods}") + if receipt["effective_mode"] != "independent_task" or not receipt.get( + "task_id" + ): + raise AssertionError( + "independent task lacks a separately resumable task receipt" + ) + return ( + [ + "independent_task selected agent.task.create", + "nested agent.spawn was not called", + "separately resumable task and workspace receipts are present", + ], + ["contracts/dispatch-receipt.schema.json"], + ) + + +def eval_explicit_degradation() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-degrade-") as tmp: + contract = make_persistence_contract( + create_authoritative_root(Path(tmp)), required=True + ) + packet = make_handoff_packet( + contract, + mode="independent_task", + allow_degradation=True, + continuity_required=False, + ) + harness = FakeHarness(can_spawn=True, can_create_task=False) + receipt = route_dispatch(harness, "fictional-employee", packet) + if receipt["effective_mode"] != "bounded_subagent": + raise AssertionError("degradation did not select bounded_subagent") + if receipt.get("degraded_from") != "independent_task" or not receipt.get( + "degradation_reason" + ): + raise AssertionError("degradation was not explicit") + return ( + [ + "bounded fallback ran only after explicit packet permission", + "receipt records requested and effective modes", + "receipt contains a concrete degradation reason", + ], + ["contracts/dispatch-receipt.schema.json"], + ) + + +def eval_bounded_na() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-na-") as tmp: + contract = make_persistence_contract( + create_authoritative_root(Path(tmp)), required=False + ) + packet = make_handoff_packet(contract, mode="bounded_subagent") + harness = FakeHarness(can_spawn=True, can_create_task=False) + dispatch_receipt = route_dispatch( + harness, "fictional-specialist", packet + ) + receipts = produce_na_receipts( + contract, dispatch_id=dispatch_receipt["dispatch_id"] + ) + return_packet = { + "conclusion": "The bounded fictional subtask produced no durable fact.", + "evidence": ["bounded result returned to parent"], + "gaps": [], + "artifact_paths": [contract["authoritative_root"]["resolved_path"]], + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_receipt["dispatch_id"], + "execution_mode": "bounded_subagent", + "closure_receipts": receipts, + } + validate_return_linkage(return_packet, contract, dispatch_receipt) + trace = verify_closure( + contract, + receipts, + dispatch_receipt=dispatch_receipt, + board_writer=None, + ) + if [item["status"] for item in trace["checks"]] != [ + "not_applicable" + ] * 4: + raise AssertionError("bounded N/A trace is incomplete") + return ( + [ + "bounded task returned four reasoned N/A receipts", + "parent trace contains four N/A checks", + "no durable write was falsely claimed", + ], + ["contracts/persistence-contract.schema.json"], + ) + + +def eval_v12_compatibility() -> tuple[list[str], list[str]]: + legacy_handoff = { + "goal": "Inspect one fictional artifact.", + "context_constraints": ["Temporary workspace only."], + "acceptance_criteria": ["Return one checkable conclusion."], + "known_pitfalls": ["Do not invent evidence."], + } + validate(legacy_handoff, "handoff-packet.schema.json") + harness = FakeHarness(can_spawn=True, can_create_task=True) + receipt = route_dispatch(harness, "fictional-specialist", legacy_handoff) + if receipt["effective_mode"] != "bounded_subagent": + raise AssertionError("v1.2 packet did not default to bounded_subagent") + legacy_return = { + "conclusion": "The fictional artifact was inspected.", + "evidence": ["fictional digest verified"], + "gaps": [], + "artifact_paths": ["fictional/artifact.txt"], + } + validate(legacy_return, "return-packet.schema.json") + return ( + [ + "original v1.2 four-field handoff remains schema-valid", + "omitted execution_mode routes as bounded_subagent", + "original v1.2 four-field return remains schema-valid", + ], + [ + "contracts/handoff-packet.schema.json", + "contracts/return-packet.schema.json", + ], + ) + + +def eval_undelivered_outcome() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-undelivered-") as tmp: + contract = make_persistence_contract( + create_authoritative_root(Path(tmp)), required=True + ) + packet = make_handoff_packet( + contract, + mode="independent_task", + allow_degradation=False, + continuity_required=True, + ) + harness = FakeHarness(can_spawn=False, can_create_task=False) + outcome = route_dispatch(harness, "fictional-employee", packet) + validate(outcome, "dispatch-receipt.schema.json") + if outcome["status"] != "undelivered" or not outcome.get("reason"): + raise AssertionError("missing capability did not yield undelivered") + forbidden = {"dispatch_id", "task_id", "provider"} & set(outcome) + if forbidden: + raise AssertionError( + f"undelivered outcome invented provider evidence: {forbidden}" + ) + if harness.calls: + raise AssertionError("undelivered outcome fabricated an adapter call") + return ( + [ + "missing task capability produced a schema-valid undelivered outcome", + "no dispatch/task ID, provider receipt, or adapter call was invented", + ], + ["contracts/dispatch-receipt.schema.json"], + ) + + +def eval_bounded_durable_closeout() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-bounded-durable-") as tmp: + contract = make_persistence_contract( + create_authoritative_root(Path(tmp)), + required=True, + handoff_id="handoff-bounded-durable-001", + contract_id="contract-bounded-durable-001", + ) + packet = make_handoff_packet(contract, mode="bounded_subagent") + harness = FakeHarness(can_spawn=True, can_create_task=True) + dispatch_receipt = route_dispatch( + harness, "fictional-specialist", packet + ) + if [call["method"] for call in harness.calls] != ["agent.spawn"]: + raise AssertionError( + "bounded durable handoff did not stay on agent.spawn" + ) + if ( + dispatch_receipt["effective_mode"] != "bounded_subagent" + or "task_id" in dispatch_receipt + or "workspace_receipt" in dispatch_receipt + ): + raise AssertionError( + "durable writes falsely promoted bounded handoff " + "to independent_task" + ) + + receipts, _ = produce_required_receipts( + contract, + harness, + dispatch_id=dispatch_receipt["dispatch_id"], + ) + return_packet = { + "conclusion": ( + "The bounded fictional subtask completed durable closeout " + "without becoming independently resumable." + ), + "evidence": [ + dispatch_receipt["dispatch_id"], + "four bounded closure receipts", + ], + "gaps": ["No independently resumable task/thread exists."], + "artifact_paths": [ + item["path"] for item in receipts + ], + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_receipt["dispatch_id"], + "execution_mode": "bounded_subagent", + "closure_receipts": receipts, + } + validate_return_linkage( + return_packet, contract, dispatch_receipt + ) + trace = verify_closure( + contract, + receipts, + dispatch_receipt=dispatch_receipt, + board_writer=CentralBoardWriter("parent"), + log_calls=harness.calls, + ) + if any(item["status"] != "verified" for item in trace["checks"]): + raise AssertionError( + "bounded durable closeout did not verify all four targets" + ) + if any( + call["method"] == "agent.task.create" + for call in harness.calls + ): + raise AssertionError( + "bounded durable closeout fabricated an independent task" + ) + return ( + [ + "bounded_subagent used agent.spawn even with four required durable targets", + "memory, worklog, journal, and board proposal completed full parent readback", + "no task ID, workspace receipt, or independently resumable thread was claimed", + ], + [ + "references/rule-pack.md#choose-the-execution-mode-first", + "contracts/handoff-packet.schema.json", + "contracts/dispatch-receipt.schema.json", + "contracts/parent-verification.schema.json", + ], + ) + + +def eval_no_followup() -> tuple[list[str], list[str]]: + harness = FakeHarness( + can_spawn=False, can_create_task=False, can_message=False + ) + suspicious_return = {"conclusion": "done"} + required = {"conclusion", "evidence", "gaps", "artifact_paths"} + missing = sorted(required - set(suspicious_return)) + report = { + "status": "pending", + "missing_fields": missing, + "followup": "unavailable", + "claim": "No follow-up mechanism was available; PASS is not claimed.", + } + if harness.calls: + raise AssertionError("a follow-up call was fabricated") + if missing != ["artifact_paths", "evidence", "gaps"]: + raise AssertionError(f"wrong missing fields: {missing}") + if "PASS is not claimed" not in report["claim"]: + raise AssertionError("report falsely claims success") + return ( + [ + "missing return fields remain pending", + "zero follow-up calls were recorded", + "no child wording or PASS was fabricated", + ], + ["references/rule-pack.md#missing-or-suspicious-return-data"], + ) + + +def eval_empty_targets_rejected() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-empty-") as tmp: + contract = { + "handoff_id": "handoff-empty-targets-001", + "contract_id": "contract-empty-targets-001", + "authoritative_root": create_authoritative_root(Path(tmp)), + "targets": [], + } + message = expect_rejection( + "empty persistence target set", + lambda: validate_persistence_contract(contract), + ) + if "non-empty" not in message and "too short" not in message: + raise AssertionError(f"empty-set error is not locatable: {message}") + return ( + ["empty persistence target set was rejected with a locatable error"], + ["contracts/persistence-contract.schema.json#properties/targets"], + ) + + +def eval_wrong_root_rejected() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-wrong-root-") as tmp: + base = Path(tmp) + contract = make_persistence_contract( + create_authoritative_root(base), required=True + ) + harness = FakeHarness(can_spawn=False, can_create_task=True) + dispatch_receipt = route_dispatch( + harness, + "fictional-employee", + make_handoff_packet(contract, mode="independent_task"), + ) + receipts, _ = produce_required_receipts( + contract, harness, dispatch_id=dispatch_receipt["dispatch_id"] + ) + wrong_workspace = copy.deepcopy(dispatch_receipt) + wrong_workspace["workspace_receipt"] = create_authoritative_root( + base / "workspace-decoy", "decoy-workspace" + ) + workspace_message = expect_rejection( + "wrong dispatch workspace", + lambda: verify_closure( + contract, + receipts, + dispatch_receipt=wrong_workspace, + board_writer=CentralBoardWriter("parent"), + log_calls=harness.calls, + ), + ) + if "workspace receipt mismatch" not in workspace_message: + raise AssertionError( + f"workspace error is not locatable: {workspace_message}" + ) + decoy = base / "decoy" / "memory.md" + decoy.parent.mkdir(parents=True) + memory_anchor = expected_evidence_anchor( + contract, "employee_memory", dispatch_receipt["dispatch_id"] + ) + decoy.write_text( + memory_anchor + "\nMEMORY-CANARY-001\n", + encoding="utf-8", + ) + memory = next( + item for item in receipts if item["target"] == "employee_memory" + ) + memory["path"] = str(decoy.resolve()) + message = expect_rejection( + "wrong-root closure", + lambda: verify_closure( + contract, + receipts, + dispatch_receipt=dispatch_receipt, + board_writer=CentralBoardWriter("parent"), + log_calls=harness.calls, + ), + ) + if "authoritative root" not in message: + raise AssertionError(f"wrong-root error is not locatable: {message}") + return ( + [ + "dispatch workspace receipt was bound to the contract root", + "decoy-root closure path was rejected before completion", + ], + ["contracts/parent-verification.schema.json"], + ) + + +def eval_partial_landing_rejected() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-partial-") as tmp: + contract = make_persistence_contract( + create_authoritative_root(Path(tmp)), required=True + ) + harness = FakeHarness(can_spawn=False, can_create_task=False) + dispatch_receipt = make_fictional_dispatch_receipt( + contract, "dispatch-partial-001" + ) + receipts, _ = produce_required_receipts( + contract, harness, dispatch_id="dispatch-partial-001" + ) + worklog = Path( + next( + item["path"] + for item in contract["targets"] + if item["target"] == "employee_worklog" + ) + ) + worklog.unlink() + message = expect_rejection( + "partial landing", + lambda: verify_closure( + contract, + receipts, + dispatch_receipt=dispatch_receipt, + board_writer=CentralBoardWriter("parent"), + log_calls=harness.calls, + ), + ) + if "partial landing" not in message: + raise AssertionError(f"partial-landing error is not locatable: {message}") + return ( + ["three-of-four landing was rejected by parent readback"], + ["references/rule-pack.md#parent-verification-gate"], + ) + + +def eval_log_nonzero_rejected() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-log-fail-") as tmp: + journal = Path(tmp) / "journal.jsonl" + harness = FakeHarness( + can_spawn=False, + can_create_task=False, + log_exit_code=23, + ) + message = expect_rejection( + "nonzero journal append", + lambda: harness.append_journal(journal, {"marker": "FAIL"}), + ) + if "exit_code=23" not in message: + raise AssertionError(f"nonzero error is not locatable: {message}") + success_receipts = [ + call.get("receipt") + for call in harness.calls + if call.get("receipt") is not None + ] + if success_receipts or journal.exists(): + raise AssertionError("nonzero append produced success evidence") + return ( + [ + "exit code 23 surfaced in the adapter error", + "no event ID, success receipt, or journal write was produced", + ], + ["contracts/log-append-receipt.schema.json"], + ) + + +def eval_board_single_writer() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-board-") as tmp: + board = Path(tmp) / "board.jsonl" + writer = CentralBoardWriter("coordinator") + message = expect_rejection( + "child board write", + lambda: writer.apply(board, "CHILD-WRITE", actor="child-a"), + ) + if "single-writer violation" not in message: + raise AssertionError(f"board error is not locatable: {message}") + + threads = [ + threading.Thread( + target=writer.apply, + args=(board, marker), + kwargs={"actor": "coordinator"}, + ) + for marker in ("PROPOSAL-A", "PROPOSAL-B") + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + lines = [json.loads(line) for line in board.read_text(encoding="utf-8").splitlines()] + markers = {item["marker"] for item in lines} + if markers != {"PROPOSAL-A", "PROPOSAL-B"} or len(lines) != 2: + raise AssertionError(f"serialized board lost an update: {lines}") + return ( + [ + "direct child board write was rejected", + "the named coordinator serialized two concurrent proposals", + "both proposals survived without overwrite", + ], + ["references/rule-pack.md#persistence-contract-four-targets-no-empty-set-green"], + ) + + +def eval_incomplete_install_rejected() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-install-") as tmp: + base = Path(tmp) + shutil.copy2(ROOT / "SKILL.md", base / "SKILL.md") + message = expect_rejection( + "single-file installation", lambda: validate_package(base) + ) + if "invalid_install" not in message or "references/" not in message: + raise AssertionError(f"install error is not locatable: {message}") + with tempfile.TemporaryDirectory(prefix="handoff-v13-schema-copy-") as tmp: + copied = Path(tmp) / "handoff-protocol" + shutil.copytree( + ROOT, + copied, + ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"), + ) + copied_handoff_schema = ( + copied / "contracts" / "handoff-packet.schema.json" + ) + original_handoff_schema = load_json(copied_handoff_schema) + missing_ref_schema = copy.deepcopy(original_handoff_schema) + missing_ref_schema["properties"]["persistence_contract"][ + "$ref" + ] = "missing-persistence-contract.schema.json" + copied_handoff_schema.write_text( + json.dumps(missing_ref_schema, indent=2) + "\n", + encoding="utf-8", + ) + ref_message = expect_rejection( + "unresolved copied Schema reference", + lambda: validate_package(copied), + ) + if "unresolved local Schema reference" not in ref_message: + raise AssertionError( + f"copied-ref error is not locatable: {ref_message}" + ) + + copied_handoff_schema.write_text( + '{"$schema":"https://json-schema.org/draft/2020-12/schema",' + '"type":123}\n', + encoding="utf-8", + ) + schema_message = expect_rejection( + "malformed copied Schema", lambda: validate_package(copied) + ) + if "invalid_install" not in schema_message or "malformed Schema" not in schema_message: + raise AssertionError( + f"copied-schema error is not locatable: {schema_message}" + ) + return ( + [ + "a lone SKILL.md was rejected as invalid_install", + "an unresolved local Schema reference in a copied package was rejected", + "a malformed Schema inside a copied package was rejected", + ], + ["README.md#install", "SKILL.md#contracts-and-evidence"], + ) + + +def eval_version_drift_rejected() -> tuple[list[str], list[str]]: + plugin = load_json(ROOT / ".claude-plugin" / "plugin.json") + manifests = [ + load_json(ROOT / "manifests" / "handoff-protocol.json"), + load_json(ROOT / "manifests" / "handoff-rule-pack.json"), + ] + drifted = copy.deepcopy(manifests) + drifted[0]["release"]["version"] = "1.2.0" + texts = [ + (ROOT / "SKILL.md").read_text(encoding="utf-8"), + (ROOT / "SKILL.zh-CN.md").read_text(encoding="utf-8"), + ] + message = expect_rejection( + "manifest version drift", + lambda: assert_version_values( + plugin["version"], + [item["release"]["version"] for item in drifted], + texts, + ), + ) + if "version drift" not in message: + raise AssertionError(f"version error is not locatable: {message}") + return ( + ["a simulated v1.2 manifest was rejected against v1.3"], + [".claude-plugin/plugin.json", "manifests/handoff-protocol.json"], + ) + + +def eval_duplicate_targets_rejected() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-duplicates-") as tmp: + contract = make_persistence_contract( + create_authoritative_root(Path(tmp)), required=False + ) + duplicate_contract = copy.deepcopy(contract) + duplicate_contract["targets"] = [ + copy.deepcopy(contract["targets"][0]) for _ in range(4) + ] + expect_rejection( + "duplicate persistence targets", + lambda: validate(duplicate_contract, "persistence-contract.schema.json"), + ) + required_contract = make_persistence_contract( + contract["authoritative_root"], required=True + ) + duplicate_nonce_contract = copy.deepcopy(required_contract) + for item in duplicate_nonce_contract["targets"]: + item["evidence_nonce"] = "REUSED-NONCE" + nonce_message = expect_rejection( + "duplicate persistence evidence nonces", + lambda: validate_persistence_contract( + duplicate_nonce_contract + ), + ) + if "distinct evidence nonces" not in nonce_message: + raise AssertionError( + f"duplicate-nonce error is not locatable: {nonce_message}" + ) + + receipts = produce_na_receipts( + contract, dispatch_id="dispatch-duplicates-001" + ) + duplicate_return = { + "conclusion": "fictional", + "evidence": ["fictional"], + "gaps": [], + "artifact_paths": [contract["authoritative_root"]["resolved_path"]], + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": "dispatch-duplicates-001", + "execution_mode": "bounded_subagent", + "closure_receipts": [copy.deepcopy(receipts[0]) for _ in range(4)], + } + expect_rejection( + "duplicate closure targets", + lambda: validate(duplicate_return, "return-packet.schema.json"), + ) + + duplicate_trace = { + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": "dispatch-duplicates-001", + "status": "pass", + "authoritative_root": contract["authoritative_root"], + "checks": [ + { + "target": "employee_memory", + "status": "not_applicable", + "evidence": "fictional N/A", + } + for _ in range(4) + ], + } + expect_rejection( + "duplicate parent checks", + lambda: validate( + duplicate_trace, "parent-verification.schema.json" + ), + ) + return ( + [ + "duplicate persistence targets were rejected", + "duplicate evidence nonces were rejected", + "duplicate closure receipts were rejected", + "duplicate parent checks were rejected", + ], + [ + "contracts/persistence-contract.schema.json", + "contracts/return-packet.schema.json", + "contracts/parent-verification.schema.json", + ], + ) + + +def eval_inconsistent_parent_pass_rejected() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-pass-fail-") as tmp: + root_info = create_authoritative_root(Path(tmp)) + checks = [ + { + "target": target, + "status": "verified", + "evidence": "fictional readback", + } + for target in TARGETS + ] + checks[1]["status"] = "failed" + trace = { + "handoff_id": "handoff-pass-fail-001", + "contract_id": "contract-pass-fail-001", + "dispatch_id": "dispatch-pass-fail-001", + "status": "pass", + "authoritative_root": root_info, + "checks": checks, + } + message = expect_rejection( + "pass trace with failed check", + lambda: validate(trace, "parent-verification.schema.json"), + ) + if "verified" not in message and "not_applicable" not in message: + raise AssertionError( + f"inconsistent-pass error is not locatable: {message}" + ) + return ( + ["status=pass with a failed target check was rejected"], + ["contracts/parent-verification.schema.json"], + ) + + +def eval_accepted_without_provider_rejected() -> tuple[list[str], list[str]]: + fake_acceptance = { + "handoff_id": "handoff-fake-acceptance-001", + "dispatch_id": "invented-001", + "recipient_id": "fictional-employee", + "timestamp": NOW, + "status": "accepted", + "requested_mode": "bounded_subagent", + "effective_mode": "bounded_subagent", + } + expect_rejection( + "accepted dispatch without provider", + lambda: validate(fake_acceptance, "dispatch-receipt.schema.json"), + ) + fake_acceptance["provider"] = {} + expect_rejection( + "accepted dispatch with empty provider", + lambda: validate(fake_acceptance, "dispatch-receipt.schema.json"), + ) + return ( + ["accepted dispatch without nonempty provider evidence was rejected"], + ["contracts/dispatch-receipt.schema.json"], + ) + + +def eval_child_board_update_rejected() -> tuple[list[str], list[str]]: + forged = { + "handoff_id": "handoff-forged-board-001", + "contract_id": "contract-forged-board-001", + "dispatch_id": "dispatch-forged-board-001", + "target": "central_board", + "status": "updated", + "writer": "recipient", + "path": "fictional/central-board.md", + "evidence": { + "kind": "content_anchor", + "value": "FORGED", + "evidence_anchor": "FORGED-ANCHOR", + }, + } + expect_rejection( + "child direct board update", + lambda: validate(forged, "closure-receipt.schema.json"), + ) + fake_memory_proposal = { + "handoff_id": "handoff-forged-memory-001", + "contract_id": "contract-forged-memory-001", + "dispatch_id": "dispatch-forged-memory-001", + "target": "employee_memory", + "status": "proposed_for_parent", + "writer": "recipient", + "path": "fictional/memory.md", + "evidence": { + "kind": "proposal", + "value": "FORGED-MEMORY-PROPOSAL", + "evidence_anchor": "FORGED-MEMORY-ANCHOR", + }, + } + proposal_message = expect_rejection( + "employee memory proposal", + lambda: validate( + fake_memory_proposal, "closure-receipt.schema.json" + ), + ) + if "central_board" not in proposal_message: + raise AssertionError( + f"non-board proposal error is not locatable: {proposal_message}" + ) + return ( + [ + "child direct central-board update was rejected at Schema level", + "employee-owned targets could not masquerade as parent proposals", + ], + ["contracts/closure-receipt.schema.json"], + ) + + +def eval_counterfeit_closure_rejected() -> tuple[list[str], list[str]]: + empty_provider_receipt = { + "exit_code": 0, + "event_id": "event-empty-provider", + "timestamp": NOW, + "append_position": 0, + "provider": {}, + } + expect_rejection( + "empty log provider receipt", + lambda: validate( + empty_provider_receipt, "log-append-receipt.schema.json" + ), + ) + with tempfile.TemporaryDirectory(prefix="handoff-v13-forgery-") as tmp: + contract = make_persistence_contract( + create_authoritative_root(Path(tmp)), required=True + ) + harness = FakeHarness(can_spawn=False, can_create_task=False) + dispatch_receipt = make_fictional_dispatch_receipt( + contract, "dispatch-forgery-001" + ) + receipts, _ = produce_required_receipts( + contract, harness, dispatch_id="dispatch-forgery-001" + ) + + wrong_writer = copy.deepcopy(receipts) + next( + item + for item in wrong_writer + if item["target"] == "employee_memory" + )["writer"] = "parent" + writer_message = expect_rejection( + "wrong closure writer", + lambda: verify_closure( + contract, + wrong_writer, + dispatch_receipt=dispatch_receipt, + board_writer=CentralBoardWriter("parent"), + log_calls=harness.calls, + ), + ) + if "writer" not in writer_message: + raise AssertionError( + f"writer error is not locatable: {writer_message}" + ) + + counterfeit = copy.deepcopy(receipts) + journal = next( + item for item in counterfeit if item["target"] == "team_journal" + ) + journal["evidence"]["event_id"] = "forged-event-999" + validate(journal, "closure-receipt.schema.json") + provider_message = expect_rejection( + "counterfeit journal provider receipt", + lambda: verify_closure( + contract, + counterfeit, + dispatch_receipt=dispatch_receipt, + board_writer=CentralBoardWriter("parent"), + log_calls=harness.calls, + ), + ) + if "provider receipt" not in provider_message: + raise AssertionError( + f"provider error is not locatable: {provider_message}" + ) + + fake_hash = copy.deepcopy(receipts) + memory = next( + item for item in fake_hash if item["target"] == "employee_memory" + ) + memory["evidence"] = { + "kind": "sha256", + "value": "0" * 64, + "evidence_anchor": memory["evidence"]["evidence_anchor"], + } + validate(memory, "closure-receipt.schema.json") + hash_message = expect_rejection( + "counterfeit SHA-256 evidence", + lambda: verify_closure( + contract, + fake_hash, + dispatch_receipt=dispatch_receipt, + board_writer=CentralBoardWriter("parent"), + log_calls=harness.calls, + ), + ) + if "SHA-256 mismatch" not in hash_message: + raise AssertionError( + f"SHA-256 error is not locatable: {hash_message}" + ) + + wrong_method = copy.deepcopy(contract) + next( + item + for item in wrong_method["targets"] + if item["target"] == "employee_memory" + )["verification"] = "provider_receipt" + method_message = expect_rejection( + "contract verification-method mismatch", + lambda: validate_persistence_contract(wrong_method), + ) + if "parent_readback" not in method_message: + raise AssertionError( + f"verification-method error is not locatable: {method_message}" + ) + return ( + [ + "empty log-provider evidence was rejected", + "wrong employee-owned writer was rejected", + "counterfeit journal event receipt was rejected against adapter calls", + "counterfeit SHA-256 evidence was rejected against the real file digest", + "target verification-method mismatch was rejected", + ], + [ + "contracts/closure-receipt.schema.json", + "contracts/log-append-receipt.schema.json", + ], + ) + + +def eval_cross_task_mix_rejected() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-cross-task-") as tmp: + base = Path(tmp) + shared_root = create_authoritative_root(base, "root-shared") + contract_a = make_persistence_contract( + shared_root, + required=True, + handoff_id="handoff-task-a", + contract_id="contract-task-a", + ) + contract_b = make_persistence_contract( + shared_root, + required=True, + handoff_id="handoff-task-b", + contract_id="contract-task-b", + ) + packet_a = make_handoff_packet(contract_a, mode="independent_task") + packet_b = make_handoff_packet(contract_b, mode="independent_task") + harness = FakeHarness(can_spawn=True, can_create_task=True) + dispatch_a = route_dispatch(harness, "fictional-a", packet_a) + dispatch_b = route_dispatch(harness, "fictional-b", packet_b) + if dispatch_a["task_id"] == dispatch_b["task_id"]: + raise AssertionError("independent task IDs are not unique") + receipts_a, _ = produce_required_receipts( + contract_a, harness, dispatch_id=dispatch_a["dispatch_id"] + ) + mixed_return = { + "conclusion": "forged cross-task return", + "evidence": ["forged"], + "gaps": [], + "artifact_paths": [ + item["path"] + for item in receipts_a + if item["status"] != "not_applicable" + ], + "handoff_id": contract_b["handoff_id"], + "contract_id": contract_b["contract_id"], + "dispatch_id": dispatch_b["dispatch_id"], + "execution_mode": "independent_task", + "closure_receipts": receipts_a, + } + validate(mixed_return, "return-packet.schema.json") + return_message = expect_rejection( + "cross-task return mix", + lambda: validate_return_linkage( + mixed_return, contract_b, dispatch_b + ), + ) + if "cross-task" not in return_message: + raise AssertionError( + f"cross-task return error is not locatable: {return_message}" + ) + + relabelled_receipts = copy.deepcopy(receipts_a) + for receipt in relabelled_receipts: + receipt["handoff_id"] = contract_b["handoff_id"] + receipt["contract_id"] = contract_b["contract_id"] + receipt["dispatch_id"] = dispatch_b["dispatch_id"] + receipt["evidence"][ + "evidence_anchor" + ] = expected_evidence_anchor( + contract_b, + receipt["target"], + dispatch_b["dispatch_id"], + ) + relabelled_return = copy.deepcopy(mixed_return) + relabelled_return["closure_receipts"] = relabelled_receipts + validate_return_linkage(relabelled_return, contract_b, dispatch_b) + + wrong_mode_return = copy.deepcopy(relabelled_return) + wrong_mode_return["execution_mode"] = "bounded_subagent" + mode_message = expect_rejection( + "return execution-mode mismatch", + lambda: validate_return_linkage( + wrong_mode_return, contract_b, dispatch_b + ), + ) + if "execution-mode mismatch" not in mode_message: + raise AssertionError( + f"return-mode error is not locatable: {mode_message}" + ) + + tampered_dispatch = copy.deepcopy(dispatch_b) + tampered_dispatch["handoff_id"] = contract_a["handoff_id"] + dispatch_message = expect_rejection( + "cross-task dispatch receipt", + lambda: validate_return_linkage( + relabelled_return, contract_b, tampered_dispatch + ), + ) + if "dispatch receipt" not in dispatch_message: + raise AssertionError( + f"dispatch linkage error is not locatable: {dispatch_message}" + ) + + closure_message = expect_rejection( + "relabelled stale closure evidence", + lambda: verify_closure( + contract_b, + relabelled_receipts, + dispatch_receipt=dispatch_b, + board_writer=CentralBoardWriter("parent"), + log_calls=harness.calls, + ), + ) + if "evidence anchor" not in closure_message: + raise AssertionError( + f"stale-evidence error is not locatable: {closure_message}" + ) + + contract_c = make_persistence_contract( + shared_root, + required=True, + handoff_id="handoff-task-c", + contract_id="contract-task-c", + ) + packet_c = make_handoff_packet(contract_c, mode="independent_task") + dispatch_c1 = route_dispatch(harness, "fictional-c", packet_c) + receipts_c1, _ = produce_required_receipts( + contract_c, harness, dispatch_id=dispatch_c1["dispatch_id"] + ) + dispatch_c2 = route_dispatch(harness, "fictional-c", packet_c) + replayed_receipts = copy.deepcopy(receipts_c1) + for receipt in replayed_receipts: + receipt["dispatch_id"] = dispatch_c2["dispatch_id"] + receipt["evidence"][ + "evidence_anchor" + ] = expected_evidence_anchor( + contract_c, + receipt["target"], + dispatch_c2["dispatch_id"], + ) + replay_message = expect_rejection( + "same-contract prior-dispatch replay", + lambda: verify_closure( + contract_c, + replayed_receipts, + dispatch_receipt=dispatch_c2, + board_writer=CentralBoardWriter("parent"), + log_calls=harness.calls, + ), + ) + if "evidence anchor" not in replay_message: + raise AssertionError( + f"same-contract replay error is not locatable: {replay_message}" + ) + return ( + [ + "two independent dispatches received unique task IDs", + "task A receipts were rejected inside task B return", + "return execution mode was bound to the dispatch effective mode", + "the parent rejected a dispatch receipt whose own IDs were relabelled", + "same-root stale artifacts still failed task B's fresh evidence anchors", + "a prior dispatch under the same contract failed the new dispatch-bound anchors", + ], + [ + "contracts/handoff-packet.schema.json", + "contracts/persistence-contract.schema.json", + "contracts/dispatch-receipt.schema.json", + "contracts/return-packet.schema.json", + "contracts/closure-receipt.schema.json", + "contracts/parent-verification.schema.json", + ], + ) + + +def eval_dispatch_state_contradictions_rejected() -> tuple[list[str], list[str]]: + root = { + "root_id": "fictional-root", + "resolved_path": "fictional/root", + "resolution_evidence": "fictional receipt", + } + unauthorized_upgrade = { + "handoff_id": "handoff-upgrade-001", + "contract_id": "contract-upgrade-001", + "dispatch_id": "dispatch-upgrade-001", + "recipient_id": "fictional-employee", + "timestamp": NOW, + "status": "accepted", + "requested_mode": "bounded_subagent", + "effective_mode": "independent_task", + "task_id": "fictional-task", + "workspace_receipt": root, + "provider": {"fictional": True}, + } + upgrade_message = expect_rejection( + "unauthorized bounded-to-independent upgrade", + lambda: validate( + unauthorized_upgrade, "dispatch-receipt.schema.json" + ), + ) + if "oneOf" not in upgrade_message: + raise AssertionError( + f"mode-upgrade error is not locatable: {upgrade_message}" + ) + + contradictory_undelivered = { + "handoff_id": "handoff-undelivered-001", + "contract_id": "contract-undelivered-001", + "recipient_id": "fictional-employee", + "timestamp": NOW, + "status": "undelivered", + "requested_mode": "independent_task", + "effective_mode": "bounded_subagent", + "workspace_receipt": root, + "degraded_from": "independent_task", + "degradation_reason": "fictional contradiction", + "reason": "nothing was delivered", + } + undelivered_message = expect_rejection( + "undelivered receipt with execution evidence", + lambda: validate( + contradictory_undelivered, "dispatch-receipt.schema.json" + ), + ) + if "should not be valid" not in undelivered_message: + raise AssertionError( + f"undelivered-state error is not locatable: {undelivered_message}" + ) + return ( + [ + "bounded_subagent could not be silently upgraded to independent_task", + "undelivered could not carry effective-mode, workspace, or degradation evidence", + ], + ["contracts/dispatch-receipt.schema.json"], + ) + + +def eval_bounded_contract_requires_closure() -> tuple[list[str], list[str]]: + with tempfile.TemporaryDirectory(prefix="handoff-v13-bounded-close-") as tmp: + contract = make_persistence_contract( + create_authoritative_root(Path(tmp)), required=True + ) + harness = FakeHarness(can_spawn=True, can_create_task=False) + dispatch_receipt = route_dispatch( + harness, + "fictional-employee", + make_handoff_packet(contract, mode="bounded_subagent"), + ) + missing_closure = { + "conclusion": "fictional bounded result", + "evidence": ["fictional"], + "gaps": [], + "artifact_paths": [ + contract["authoritative_root"]["resolved_path"] + ], + "handoff_id": contract["handoff_id"], + "contract_id": contract["contract_id"], + "dispatch_id": dispatch_receipt["dispatch_id"], + "execution_mode": "bounded_subagent", + } + schema_message = expect_rejection( + "bounded contract return without closure receipts", + lambda: validate( + missing_closure, "return-packet.schema.json" + ), + ) + if "closure_receipts" not in schema_message: + raise AssertionError( + f"bounded-closeout Schema error is not locatable: " + f"{schema_message}" + ) + + legacy_shaped = { + key: value + for key, value in missing_closure.items() + if key + not in { + "handoff_id", + "contract_id", + "dispatch_id", + "execution_mode", + } + } + validate(legacy_shaped, "return-packet.schema.json") + linkage_message = expect_rejection( + "cross-object bounded contract without closure receipts", + lambda: validate_return_linkage( + legacy_shaped, contract, dispatch_receipt + ), + ) + if "exactly four closure receipts" not in linkage_message: + raise AssertionError( + f"bounded-closeout linkage error is not locatable: " + f"{linkage_message}" + ) + return ( + [ + "a bounded return carrying contract_id required four closure receipts at Schema level", + "cross-object linkage also rejected a legacy-shaped return when a contract existed", + ], + [ + "contracts/return-packet.schema.json", + "references/rule-pack.md#return-packet-four-required-fields", + ], + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument( + "--component-schema", + help="Optional path to a frozen agent-modpack component.schema.json", + ) + parser.add_argument( + "--inject-failure", + help="Diagnostic: force one named fixture to fail and prove exit code 1", + ) + args = parser.parse_args() + + component_schema_metadata = None + if args.component_schema: + try: + component_path = Path(args.component_schema) + component_schema = load_json(component_path) + Draft202012Validator.check_schema(component_schema) + component_schema_metadata = { + "schema_id": component_schema.get("$id", ""), + "sha256": sha256(component_path), + } + except Exception as exc: + print( + json.dumps( + { + "ok": False, + "error": "component_schema_input_error", + "message": f"{type(exc).__name__}: {exc}", + }, + sort_keys=True, + ), + file=sys.stderr, + ) + return 2 + + cases: dict[str, Callable[[], tuple[list[str], list[str]]]] = { + "SK-HP-P-001": lambda: eval_four_target_closeout( + args.component_schema + ), + "SK-HP-P-002": eval_atomic_log, + "SK-HP-P-003": eval_independent_routing, + "SK-HP-P-004": eval_explicit_degradation, + "SK-HP-P-005": eval_bounded_na, + "SK-HP-P-006": eval_v12_compatibility, + "SK-HP-P-007": eval_undelivered_outcome, + "SK-HP-P-008": eval_bounded_durable_closeout, + "SK-HP-N-001": eval_no_followup, + "SK-HP-N-002": eval_empty_targets_rejected, + "SK-HP-N-003": eval_wrong_root_rejected, + "SK-HP-N-004": eval_partial_landing_rejected, + "SK-HP-N-005": eval_log_nonzero_rejected, + "SK-HP-N-006": eval_board_single_writer, + "SK-HP-N-007": eval_incomplete_install_rejected, + "SK-HP-N-008": eval_version_drift_rejected, + "SK-HP-N-009": eval_duplicate_targets_rejected, + "SK-HP-N-010": eval_inconsistent_parent_pass_rejected, + "SK-HP-N-011": eval_accepted_without_provider_rejected, + "SK-HP-N-012": eval_child_board_update_rejected, + "SK-HP-N-013": eval_counterfeit_closure_rejected, + "SK-HP-N-014": eval_cross_task_mix_rejected, + "SK-HP-N-015": eval_dispatch_state_contradictions_rejected, + "SK-HP-N-016": eval_bounded_contract_requires_closure, + } + fixtures = load_json(ROOT / "evals" / "fixtures.json") + fixture_ids = [item["id"] for item in fixtures["fixtures"]] + if fixture_ids != list(cases): + print( + json.dumps( + { + "ok": False, + "error": "fixture_runner_drift", + "fixture_ids": fixture_ids, + "runner_ids": list(cases), + }, + sort_keys=True, + ), + file=sys.stderr, + ) + return 2 + if args.inject_failure and args.inject_failure not in cases: + print( + json.dumps( + { + "ok": False, + "error": "unknown_injected_failure_case", + "case_id": args.inject_failure, + }, + sort_keys=True, + ), + file=sys.stderr, + ) + return 2 + + results = [] + for case_id, call in cases.items(): + try: + checks, evidence = call() + if args.inject_failure == case_id: + raise AssertionError( + f"diagnostic failure injected for {case_id}" + ) + results.append( + { + "id": case_id, + "status": "pass", + "checks": checks, + "evidence": evidence, + } + ) + except Exception as exc: + results.append( + { + "id": case_id, + "status": "fail", + "checks": [f"{type(exc).__name__}: {exc}"], + "evidence": [f"fixture:{case_id}"], + } + ) + + output = { + "ok": all(item["status"] == "pass" for item in results), + "version": VERSION, + "observed_at": observed_at(), + "command": "python evals/run_evals.py" + + ( + " --component-schema " + if args.component_schema + else "" + ) + + ( + f" --inject-failure {args.inject_failure}" + if args.inject_failure + else "" + ), + "component_schema": component_schema_metadata, + "runner": { + "path": "evals/run_evals.py", + "sha256": sha256(RUNNER_PATH), + }, + "results": results, + } + result_schema = load_json(ROOT / "evals" / "result.schema.json") + try: + Draft202012Validator.check_schema(result_schema) + Draft202012Validator( + result_schema, format_checker=FormatChecker() + ).validate(output) + except Exception as exc: + print( + json.dumps( + { + "ok": False, + "error": "result_schema_failure", + "message": f"{type(exc).__name__}: {exc}", + }, + sort_keys=True, + ), + file=sys.stderr, + ) + return 2 + + print(json.dumps(output, ensure_ascii=False, sort_keys=True)) + if not output["ok"]: + failed = [item["id"] for item in results if item["status"] == "fail"] + print( + "handoff-protocol eval failure: " + ", ".join(failed), + file=sys.stderr, + ) + return 0 if output["ok"] else 1 + + +if __name__ == "__main__": + sys.exit(main())