Datasets:
File size: 111,193 Bytes
f24bcdf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 | #!/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', '<no-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", "<no-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 <provided>"
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())
|