Datasets:
File size: 116,260 Bytes
b8ea052 | 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 | """Compile atomic PVR checks into typed, cacheable tool calls.
The evidence planner emits rich human-readable plans. Those plans are useful
for auditing, but their free-form ``tool_sequence`` entries are not an
executable API. This module is the strict bridge between a resolved contract
and runtime tools:
* every call is owned by one or more atomic ``check_id`` values;
* detector prompts are scoped to one check, never unioned across a case;
* identical physical calls may be cached without losing check provenance;
* unsupported checker/tool requirements are explicit and route to fallback.
"""
from __future__ import annotations
import hashlib
import json
import re
from dataclasses import dataclass, field, replace
from typing import Any, Iterable, Mapping
from pvr_eval.core.schema import AtomicCheckSpec, EvalContract
from pvr_eval.agent.contract_metric_binding import (
PRESERVATION_RULE_TYPES,
REGISTERED_RULE_TYPES,
canonical_rule_type,
metric_capability,
)
from pvr_eval.agent.detector_fusion import semantic_class
from pvr_eval.agent.evidence_program import DEFAULT_AVAILABLE_OPERATIONS, EvidenceProgram, compile_evidence_program
from pvr_eval.agent.executable_predicate import validate_executable_predicate
from pvr_eval.contracts.metric_profiles import (
human_pose_profile_parameters,
local_correspondence_profile_parameters,
)
from pvr_eval.contracts.region_materializer_registry import executable_region_materializer
TOOL_PLAN_SCHEMA_VERSION = "pvr.agent_tool_plan.v2"
MAX_DETECTOR_QUERIES_PER_CALL = 8
# Operations with a real executor or a fixed checker implementation in this
# runtime. Text alignment/quality remain excluded: current OCR checkers do not
# actually compare input/output strings or emit calibrated legibility metrics.
RUNTIME_AVAILABLE_OPERATIONS = frozenset(DEFAULT_AVAILABLE_OPERATIONS - {"text_alignment", "text_quality"})
_SUPPORTED_EXPLICIT_COLORS = frozenset(
{"red", "orange", "yellow", "green", "cyan", "blue", "purple", "pink", "black", "white", "gray", "grey", "brown"}
)
@dataclass(frozen=True)
class ToolCallSpec:
"""One physical tool invocation that may serve several atomic checks."""
call_id: str
cache_key: str
tool: str
case_key: str
image_role: str
image_identity: str
check_ids: tuple[str, ...]
queries: tuple[str, ...] = ()
region_ids: tuple[str, ...] = ()
depends_on: tuple[str, ...] = ()
params: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return {
"call_id": self.call_id,
"cache_key": self.cache_key,
"tool": self.tool,
"case_key": self.case_key,
"image_role": self.image_role,
"image_identity": self.image_identity,
"check_ids": list(self.check_ids),
"queries": list(self.queries),
"region_ids": list(self.region_ids),
"depends_on": list(self.depends_on),
"params": self.params,
}
@dataclass(frozen=True)
class CheckToolPlan:
check_id: str
checker: str
tool_call_ids: tuple[str, ...]
fallback: str
status: str
reasons: tuple[str, ...] = ()
declared_tool_families: tuple[str, ...] = ()
unrecognized_declared_tools: tuple[str, ...] = ()
evidence_program: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return {
"check_id": self.check_id,
"checker": self.checker,
"tool_call_ids": list(self.tool_call_ids),
"fallback": self.fallback,
"status": self.status,
"reasons": list(self.reasons),
"declared_tool_families": list(self.declared_tool_families),
"unrecognized_declared_tools": list(self.unrecognized_declared_tools),
"evidence_program": self.evidence_program,
}
_STATE_PREFIXES = {
"moved", "move", "relocated", "relocate", "original", "output", "input",
"remaining", "required", "matching", "distinct", "visible", "detected",
}
def _clean_query(value: Any) -> str:
text = re.sub(r"[_/]+", " ", str(value or "").strip().lower())
text = re.sub(r"\s+", " ", text).strip(" ,.;:-")
words = text.split()
while words and words[0] in _STATE_PREFIXES:
words.pop(0)
return " ".join(words)
def _query_tokens(value: str) -> set[str]:
stop = {"a", "an", "the", "of", "or", "and", "from", "on", "in", "at", "to", "with", "belonging"}
return {word for word in re.findall(r"[a-z0-9]+", value.lower()) if word not in stop}
def _same_concept(left: str, right: str) -> bool:
a, b = _query_tokens(left), _query_tokens(right)
if not a or not b:
return False
# A shared source anchor can dominate token overlap. Explicitly different
# colours still denote different inventory members and must never be
# collapsed into one detector query.
left_colours = a & _SUPPORTED_EXPLICIT_COLORS
right_colours = b & _SUPPORTED_EXPLICIT_COLORS
if left_colours and right_colours and left_colours != right_colours:
return False
# A target and its support/location often share several words (for
# example, "bird on robot left shoulder" and "robot left shoulder").
# They are not aliases: collapsing them removes the target noun and makes
# an absence search incapable of looking for the object that may have
# moved. Known coarse entity classes are therefore a hard merge gate.
known_classes = {
"appliance", "backpack", "bird", "bottle", "cat", "chair", "computer", "container",
"document", "dog", "furniture", "person", "phone", "printer", "snack", "table", "television",
}
left_class = semantic_class({"query_text": left})
right_class = semantic_class({"query_text": right})
if left_class != right_class and (left_class in known_classes or right_class in known_classes):
return False
overlap = len(a & b)
if overlap >= 2 and (a <= b or b <= a):
return True
return overlap >= 2 and overlap / len(a | b) >= 0.5
def canonical_detector_queries(values: Iterable[Any]) -> tuple[str, ...]:
"""Collapse obvious per-check aliases without merging distinct entities."""
clusters: list[list[str]] = []
for raw in values:
query = _clean_query(raw)
if not query:
continue
target = next((cluster for cluster in clusters if any(_same_concept(query, item) for item in cluster)), None)
if target is None:
clusters.append([query])
elif query not in target:
target.append(query)
representatives = []
for cluster in clusters:
# Short noun phrases are generally more stable for DINO/YOLO-World.
representatives.append(min(cluster, key=lambda item: (len(_query_tokens(item)), len(item), item)))
return tuple(dict.fromkeys(representatives))
def _registered_subject_detector_aliases(
predicate: Mapping[str, Any], values: Sequence[str],
) -> tuple[str, ...]:
"""Add narrow visual aliases for registered repeated-object profiles.
These aliases improve proposal recall only. They do not change the
physical subject cardinality, and downstream repeated-component geometry
must still certify a unique group before any fact can be emitted.
"""
rule_type = str(predicate.get("source_rule_type") or "")
semantic = " ".join(values).casefold()
if rule_type == "supported_nonintersecting_placement" and "binder" in semantic:
return ("file folders matching the input shelf binders",)
return ()
_REGION_ACTION_WORDS = frozenset(
{
"align", "apply", "classify", "compare", "compute", "construct", "define", "detect", "divide",
"estimate", "evaluate", "exclude", "expand", "fit", "form", "identify", "include", "infer",
"inspect", "mark", "match", "measure", "perform", "position", "preserve", "preserving", "refine",
"register", "retain", "reuse", "segment", "select", "subtract", "transfer", "use",
}
)
_HARD_DERIVED_REGION_TOKENS = frozenset(
{
"all", "allowed", "audit", "band", "boundary", "compare", "comparison", "corridor", "edge",
"footprint", "inventory", "union",
}
)
_REGION_PROCEDURAL_TOKENS = frozenset(
{"downstream", "extrapolation", "geometry", "legal", "movement", "orientation", "upstream"}
)
_DERIVED_REGION_TOKENS = frozenset(
{
"all", "allowed", "audit", "band", "boundary", "components", "context", "correspondence", "corridor", "crop",
"crops", "edge", "footprint", "invariant", "locations", "margin", "scene", "search", "union",
}
)
_REGION_ID_GENERIC_TOKENS = frozenset(
{
"after", "anchor", "area", "areas", "as", "before", "both", "by", "component", "components",
"context", "correspondence", "crop", "crops", "entities", "entity", "evidence", "exact", "for", "from",
"id", "identity", "input", "instance", "instances", "interior", "invariant", "item", "items", "landing",
"mask", "masks", "match",
"neatness", "object", "objects", "of", "output", "reference", "references", "region", "regions", "roi", "set", "source",
"structure", "target", "template", "templates", "to", "using", "vacancy", "writing", "zone", "zones",
}
)
_REGION_DESCRIPTOR_ONLY_TOKENS = frozenset(
{
"all", "background", "bottom", "center", "color", "delicate", "duplicate", "estimated", "exact",
"five", "forbidden", "four", "global", "grounded", "irrelevant", "left", "lower", "middle", "morphed",
"original", "relocated", "right", "solid", "specific", "suspected", "three", "top", "upper",
}
| _SUPPORTED_EXPLICIT_COLORS
)
def _sanitize_region_entity_phrase(value: str) -> str:
"""Keep an object noun phrase and discard tool/procedure language."""
phrase = re.sub(r"[_/]+", " ", str(value or "").lower())
phrase = re.sub(r"\bsam[- ]?(?:segment(?:ation)?|refine)\b", "sam", phrase)
phrase = re.sub(
r"^(?:followed by|aided by|edge-guided|after|before|repeat(?: the)? same|obtain|add)\s+",
"",
phrase,
)
phrase = re.sub(r"^(?:seed\s+)?sam\s+(?:from|for|to separate|as)?\s*", "", phrase)
phrase = re.sub(r"^re-segment\s+", "", phrase)
phrase = re.sub(r"^(?:separate boxes for|search for)\s+", "", phrase)
phrase = re.split(
r"\b(?:using|after registration|before registration|followed by sam|aided by|"
r"as identity|for identity|matching source identity|identity cues?|identity descriptors?|"
r"identity reference|identity template|identity set|registration|segmentation|sam prompts?|sam evidence)\b",
phrase,
maxsplit=1,
)[0]
phrase = re.sub(r"\b(?:identity|registration|segmentation|detection|sam)\b", " ", phrase)
phrase = re.sub(r"\bdetector boxes?\b", " ", phrase)
phrase = re.sub(r"\s+", " ", phrase).strip(" .:-")
words = phrase.split()
if not words or len(words) > 6:
return ""
if any(word in _REGION_ACTION_WORDS or word in _REGION_PROCEDURAL_TOKENS for word in words):
return ""
if any(
word in {
"are", "consolidate", "derive", "descriptor", "descriptors", "dilated", "exclusion", "geometric",
"matches", "multi-scale", "outside", "polygon", "prompts", "reject", "whose",
}
for word in words
):
return ""
if set(words) <= _REGION_DESCRIPTOR_ONLY_TOKENS:
return ""
if phrase in {"image", "item", "items", "object", "objects", "scene", "scenes", "them"}:
return ""
return phrase
def _split_region_id_entities(region_id: str) -> tuple[str, ...]:
text = re.sub(r"[_/]+", " ", region_id.lower()).strip()
# Preserve useful compound color descriptions such as ``black_and_white_cat``.
if re.search(
rf"\b(?:{'|'.join(sorted(_SUPPORTED_EXPLICIT_COLORS))})\s+and\s+"
rf"(?:{'|'.join(sorted(_SUPPORTED_EXPLICIT_COLORS))})\b",
text,
):
return (text,)
return tuple(item.strip() for item in re.split(r"\b(?:and|or)\b", text) if item.strip())
def _region_id_fallback(region_id: str) -> tuple[str, ...]:
"""Return a conservative object phrase encoded by a region id.
Derived geometry such as an edit corridor or a boundary is not an object
detector target. Returning no query forces an explicit parser/VLM
fallback instead of manufacturing a plausible-looking but meaningless
DINO box.
"""
tokens = [item for item in re.findall(r"[a-z0-9]+", region_id.lower()) if item]
normalized_tokens = {item[:-1] if item.endswith("s") and len(item) > 3 else item for item in tokens}
if normalized_tokens & _DERIVED_REGION_TOKENS:
return ()
phrases: list[str] = []
for entity in _split_region_id_entities(region_id):
words = [
item for item in re.findall(r"[a-z0-9]+", entity.lower())
if item not in _REGION_ID_GENERIC_TOKENS
]
phrase = _sanitize_region_entity_phrase(" ".join(words))
if phrase:
phrases.append(phrase)
return canonical_detector_queries(phrases)
def region_detector_queries(value: str, region_id: str, limit: int = 8) -> tuple[str, ...]:
"""Compile resolver prose into short, entity-only DINO/YOLO prompts.
This is intentionally conservative. Detector prompts are object or
container noun phrases; instructions about unions, matching, topology,
boundaries, or image comparison remain typed downstream operations.
"""
text = re.sub(r"[_/]+", " ", str(value or "").lower())
# Resolver prose often names the proposal tool inline. Normalize compound
# verbs before clause splitting so ``SAM-segment X`` and
# ``identity-match X`` yield the entity X, never a detector prompt that
# still contains the tool instruction.
text = re.sub(
r"\b(?:sam(?:[- ]?(?:segment(?:ation)?|refine))?|identity[- ]?match(?:ing)?|input[- ]?output[- ]?match(?:ing)?)\b",
"detect",
text,
)
raw_region_tokens = set(re.findall(r"[a-z0-9]+", region_id.lower()))
region_tokens = {item[:-1] if item.endswith("s") and len(item) > 3 else item for item in raw_region_tokens}
if region_tokens & _HARD_DERIVED_REGION_TOKENS:
return ()
if re.search(r"\bmatch\b.*\b(?:paired )?(?:input output )?crops?\b", text) or re.search(
r"\bfor (?:each|every) matched\b.*\bgenerate (?:a )?crop\b", text
):
return ()
text = re.split(r"\b(?:exclude|excluding|do not count|never count)\b", text, maxsplit=1)[0]
procedural = bool(re.search(r"\b(?:union|subtract|difference|boundary|corridor|footprint|exact mapped slots)\b", text))
fragments = re.split(r"[,;]|\band\b|\bor\b|\bthen\b", text)
cleaned: list[str] = []
for fragment in fragments:
fragment = re.sub(
r"^(?:in|from|on) the (?:input|output),?\s*|^(?:for every|for each)\s+|"
r"^after\s+(?:selecting|detecting|locating)\s+|^(?:including|retaining|especially|for)\s+",
"",
fragment.strip(),
)
# Strip detector/segmenter imperatives independently for every clause.
fragment = re.sub(
r"^(?:(?:individually\s+)?(?:locate|detect|ground|segment|propose|find|enumerate|generate|"
r"include|extract|fit|apply|estimate|align|register|preserve|reuse)\s+)+",
"",
fragment,
)
fragment = re.sub(r"^(?:for|from|as|using)\s+", "", fragment)
fragment = re.sub(
r"\b(?:in|into|from|on)\s+(?:the\s+)?(?:input|output)(?:\s+image)?\b",
" ",
fragment,
)
fragment = re.split(
r"\b(?:where|whose|that|which|as one|intended to|associated with|resting on|to identify|to compute|to find)\b",
fragment,
maxsplit=1,
)[0]
fragment = re.sub(
r"\b(?:the|a|an|its|their|this|those|any other|visible|full|complete|relevant|nearby|original|"
r"output|input|each|every|distinct|estimated|matched|relocated|pre existing|already orderly)\b",
" ",
fragment,
)
fragment = re.sub(r"\b(?:with|around|within|across|between|through|while|except|against|under|beneath|behind|beside|near)\b.*$", "", fragment)
fragment = re.sub(r"\b(?:instance|instances|area|region|roi|masks?|crop|context|margin|locations?)\b", " ", fragment)
fragment = re.sub(r"\b(?:immediately|portion|but)\b", " ", fragment)
fragment = re.sub(r"\bwhite paper writing\b", "white paper", fragment)
fragment = re.sub(
r"\b(?:horizontal )?top surface of (?:large )?(?:foreground )?(?:wooden )?desk\b",
"desk surface",
fragment,
)
fragment = re.sub(
r"\b(?:small )?(?:dark )?(?:standing )?(?:rectangular )?frame slate\b",
"standing frame slate",
fragment,
)
fragment = re.sub(r"\b(?:wall )?window perspective lines?\b", "", fragment)
fragment = _sanitize_region_entity_phrase(fragment)
fragment = re.sub(r"\b(?:in|into|from|on|to)$", "", fragment).strip()
words = fragment.split()
if (
not words
or len(words) > 6
or any(word in _REGION_ACTION_WORDS for word in words)
or any(word in _REGION_PROCEDURAL_TOKENS for word in words)
):
continue
if fragment in {"image", "item", "items", "objects", "scenes", "them"}:
continue
cleaned.append(fragment)
queries = canonical_detector_queries(cleaned)
core_tokens = {
token for token in re.findall(r"[a-z0-9]+", region_id.lower())
if token not in {
"all", "area", "exact", "id", "instance", "mask", "output", "input", "region", "roi",
"source", "target", "zone",
}
}
semantic_core_tokens = core_tokens - {"left", "right", "top", "bottom", "front", "back", "middle", "center"}
matching = tuple(query for query in queries if semantic_core_tokens & _query_tokens(query))
fallback = _region_id_fallback(region_id)
if matching:
queries = matching
elif fallback:
# Region ids are contract-owned and usually name the intended object
# more reliably than a procedural resolver sentence. Prefer that
# entity-only phrase when no extracted phrase agrees with the id.
queries = fallback
if len(queries) == 1 and len(queries[0].split()) == 1:
queries = fallback or queries
if not queries and "entry" in region_tokens and re.search(r"\b(?:lane|lanes|crosswalk|road|arrow)\b", text):
return ()
if not queries or procedural:
# Procedural derived regions must not be reduced to a single detector
# box merely because their id happens to contain an object word.
if procedural and not fallback:
return ()
queries = fallback
normalized_region_id = region_id.lower()
if any(token in normalized_region_id for token in ("inventory", "original_clutter_instances")):
generic_inventory = {
"loose inanimate item", "loose inanimate items", "coherent stack", "coherent stacks",
"assign stable ids", "stable ids",
}
if queries and all(query in generic_inventory for query in queries):
return ()
if "decor" in normalized_region_id:
queries = tuple(query for query in queries if query not in {"wall", "walls", "shelf", "shelves"})
return queries
def _singular_head(value: str) -> str:
words = [word for word in re.findall(r"[a-z0-9-]+", value.lower()) if word]
words = [word for word in words if word not in {"all", "each", "every", "four", "five", "six", "distinct"}]
if not words:
return "object"
head = " ".join(words[-2:])
if head.endswith("ies"):
return head[:-3] + "y"
if head.endswith("s") and not head.endswith("ss"):
return head[:-1]
return head
def expand_detector_query(value: Any) -> tuple[str, ...]:
"""Split explicit entity lists while retaining single-object descriptions.
DINO should receive one semantic entity per query. Detailed attributes of
one object stay together, while comma-separated inventories and colon
lists become separate queries. The caller batches every emitted query, so
expansion never causes silent truncation.
"""
text = _clean_query(value)
if not text:
return ()
if ":" in text:
prefix, raw_items = text.split(":", 1)
parts = [re.sub(r"^(?:and|or)\s+", "", item.strip(" ,")) for item in raw_items.split(",")]
parts = [item for item in parts if item]
if len(parts) >= 2:
head = _singular_head(prefix)
return tuple(f"{item} {head}" for item in parts)
if "," not in text:
return (text,)
first_comma = text.index(",")
descriptor = re.search(r"\b(?:with|including|containing|depicting|bearing)\b", text)
if descriptor and descriptor.start() < first_comma:
return (text,)
parts = [re.sub(r"^(?:and|or)\s+", "", item.strip(" ,")) for item in text.split(",")]
parts = [item for item in parts if item]
if len(parts) < 2:
return (text,)
location = ""
match = re.search(
r"\b(?:on|in|at|near|beside|inside|within|under|above|behind|across|from)\b.+$",
parts[-1],
)
if match:
location = match.group(0)
parts[-1] = parts[-1][: match.start()].strip()
expanded = []
for part in parts:
part = re.sub(r"^(?:all|each|every|new)\s+", "", part).strip()
if not part:
continue
if location and not re.search(r"\b(?:on|in|at|near|beside|inside|within|under|above|behind|across|from)\b", part):
part = f"{part} {location}"
expanded.append(part)
return tuple(expanded) or (text,)
def _values(params: dict[str, Any], key: str) -> list[Any]:
value = params.get(key)
if value is None or value == "":
return []
if isinstance(value, (list, tuple, set)):
return list(value)
return [value]
def _explicit_colors(params: dict[str, Any]) -> tuple[str, ...]:
values: list[Any] = []
for key in ("line_color", "wire_color", "route_color", "expected_color", "target_color", "color", "colors"):
values.extend(_values(params, key))
return tuple(
dict.fromkeys(
str(value).lower().strip() for value in values
if str(value).lower().strip() in _SUPPORTED_EXPLICIT_COLORS
)
)
def _has_structured_cells(params: dict[str, Any]) -> bool:
return any(
isinstance(params.get(key), list)
and bool(params[key])
and all(isinstance(item, dict) for item in params[key])
for key in ("expected_cells", "cells", "slots", "expected_slots", "cell_states")
)
def detector_queries_for_check(spec: AtomicCheckSpec) -> tuple[str, ...]:
params = dict(spec.params or {})
# Reviewed object_queries are the detector interface. Legacy ``object``
# prose often repeats the whole question and must not broaden it with
# region nouns or parenthetical examples.
raw = _values(params, "object_queries")
if not raw:
raw = []
for key in ("labels", "objects", "object"):
raw.extend(_values(params, key))
expanded = [query for value in raw for query in expand_detector_query(value)]
return canonical_detector_queries(expanded)
def _checker_base(checker: str) -> str:
return str(checker).split("|", 1)[0].split(":", 1)[0].strip()
def _region_ids(spec: AtomicCheckSpec) -> tuple[str, ...]:
params = dict(spec.params or {})
regions = params.get("planned_regions", [])
out = []
if isinstance(regions, list):
for item in regions:
if isinstance(item, dict):
value = item.get("region_id") or item.get("id")
if value:
out.append(str(value))
for key in ("zone", "zone_id", "target_zone", "source_zone", "forbidden_zone"):
value = params.get(key)
if isinstance(value, str) and value:
out.append(value)
return tuple(dict.fromkeys(out))
def normalize_declared_tool(value: Any) -> str | None:
text = re.sub(r"[^a-z0-9]+", "_", str(value or "").lower()).strip("_")
if not text:
return None
if "vlm" in text:
return "vlm_fallback"
if any(token in text for token in ("grounding", "dino", "yolo", "open_vocabulary", "object_detection", "person_detection")):
return "open_vocabulary_detector"
if "sam" in text or "segmentation" in text:
return "mask_refiner"
if "ocr" in text or "text_recognition" in text or "text_detection" in text:
return "ocr"
if any(token in text for token in ("registration", "homography", "alignment", "feature_matching")):
return "image_registration"
if any(token in text for token in ("change_mask", "difference", "similarity", "perceptual", "edge_comparison")):
return "change_analysis"
if any(token in text for token in ("route", "path", "skeleton", "centerline", "connectivity")):
return "route_parser"
if any(token in text for token in ("grid", "slot", "board", "rack", "shelf", "cell_parser")):
return "state_parser"
if any(token in text for token in ("color", "symbol", "checkbox", "glyph")):
return "visual_attribute_parser"
if any(token in text for token in ("pose", "keypoint", "skeleton")):
return "human_pose_parser"
if any(token in text for token in ("geometry", "containment", "overlap", "distance", "counting", "matching", "comparison")):
return "checker_internal"
return None
def _declared_tool_audit(spec: AtomicCheckSpec) -> tuple[tuple[str, ...], tuple[str, ...]]:
raw = spec.params.get("tool_sequence", []) if isinstance(spec.params, dict) else []
raw = raw if isinstance(raw, list) else [raw]
families, unknown = [], []
for item in raw:
family = normalize_declared_tool(item)
if family:
families.append(family)
elif str(item).strip():
unknown.append(str(item).strip())
return tuple(dict.fromkeys(families)), tuple(dict.fromkeys(unknown))
def _cache_key(
*, case_key: str, tool: str, image_role: str, image_identity: str, queries: tuple[str, ...],
region_ids: tuple[str, ...], depends_on: tuple[str, ...], params: dict[str, Any],
) -> str:
payload = {
"case_key": case_key,
"tool": tool,
"image_role": image_role,
"image_identity": image_identity,
"queries": list(queries),
"region_ids": list(region_ids),
"depends_on": list(depends_on),
"params": params,
}
return hashlib.sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
def _call(*, case_key: str, check_id: str, tool: str, image_role: str, image_identity: str, queries: tuple[str, ...] = (), region_ids: tuple[str, ...] = (), depends_on: tuple[str, ...] = (), params: dict[str, Any] | None = None) -> ToolCallSpec:
call_params = dict(params or {})
cache_key = _cache_key(
case_key=case_key, tool=tool, image_role=image_role, image_identity=image_identity,
queries=queries, region_ids=region_ids, depends_on=depends_on, params=call_params,
)
return ToolCallSpec(
call_id=f"call_{cache_key[:20]}",
cache_key=cache_key,
tool=tool,
case_key=case_key,
image_role=image_role,
image_identity=image_identity,
check_ids=(check_id,),
queries=queries,
region_ids=region_ids,
depends_on=depends_on,
params=call_params,
)
def _chunks(values: tuple[str, ...], size: int) -> list[tuple[str, ...]]:
return [values[index : index + size] for index in range(0, len(values), size)]
def _region_zone_kind(
region_id: str, region_queries: tuple[str, ...], target_queries: tuple[str, ...], rule_type: str
) -> str:
"""Separate spatial support surfaces from regions that are object instances.
Both kinds are region-resolver inputs, but only an independent spatial
region may arbitrate a target detector conflict. Treating a second box
for the target object as a destination zone makes every false positive
self-validating, which is exactly the role leakage this typed plan is
intended to prevent.
"""
tokens = set(re.findall(r"[a-z0-9]+", region_id.lower()))
instance_tokens = {
"instance", "instances", "item", "items", "object", "objects", "inventory",
"mask", "masks", "entity", "entities", "relocated", "moved", "binder", "binders",
}
same_as_target = any(
_same_concept(region_query, target_query)
for region_query in region_queries
for target_query in target_queries
)
if tokens & instance_tokens or same_as_target:
return "instance_reference"
positive_zone_rules = {"destination_zone_containment", "source_zone_vacancy", "desk_clutter_residual_count"}
negative_tokens = {"forbidden", "protected", "exclusion", "exclude", "tray", "invariant"}
if rule_type in positive_zone_rules and not tokens & negative_tokens:
return "spatial_constraint"
return "context_region"
def _calls_for_executable_predicate(
case_key: str,
spec: AtomicCheckSpec,
predicate: Mapping[str, Any],
image_identities: dict[str, str],
program: EvidenceProgram | None = None,
) -> tuple[list[ToolCallSpec], list[str]]:
"""Lower one authoritative predicate without consulting legacy prose."""
validation = validate_executable_predicate(predicate)
if not validation.valid or predicate.get("status") != "executable":
return [], list(dict.fromkeys(("executable_predicate_not_executable", *validation.reasons)))
family = str(predicate.get("family") or "")
if family == "registered_metric_bridge":
if program is None:
return [], ["registered_metric_bridge_missing_evidence_program"]
return _calls_for_program(
case_key,
spec,
program,
image_identities,
authoritative_lowering=False,
)
if family == "structured_case_parser":
if program is None:
return [], ["structured_case_parser_missing_evidence_program"]
return _calls_for_program(
case_key,
spec,
program,
image_identities,
authoritative_lowering=False,
)
supported_families = {
"source_region_clearance",
"surface_residual_inventory",
"destination_membership",
"relocation_transition",
"cross_image_inventory_integrity",
"source_region_restoration",
"source_instance_displacement",
"fixed_location_instance_preservation",
"fixed_location_entity_preservation",
"registered_invariant_region_preservation",
"relocated_entity_integrity",
"registered_structural_state",
"group_pose_arrangement",
"contract_family_all_of",
}
if family not in supported_families:
return [], [f"predicate_family_has_no_lowerer:{predicate.get('family') or 'missing'}"]
operations = [item for item in predicate.get("operations", []) if isinstance(item, Mapping)]
operation_kinds = {str(item.get("kind") or "") for item in operations}
runtime_unavailable_regions = [
str(region.get("region_id") or region.get("id") or "missing")
for region in predicate.get("regions", [])
if isinstance(region, Mapping)
and not executable_region_materializer(
str(
(region.get("materializer") or {}).get("kind")
if isinstance(region.get("materializer"), Mapping)
else ""
)
)
]
if predicate.get("capability_versions") and runtime_unavailable_regions:
return [], [
"predicate_region_materializer_runtime_unavailable:"
+ ",".join(runtime_unavailable_regions)
]
semantic_families = {
str(item) for item in predicate.get("target_families", []) if str(item)
} or {family}
required = {"object_detection", "mask_refinement", "predicate_decision"}
if family in {"source_region_clearance", "source_region_restoration", "relocation_transition", "source_instance_displacement"}:
required.add("source_state_classification")
if family == "fixed_location_instance_preservation" or "fixed_location_entity_preservation" in semantic_families:
required.update({"instance_matching", "image_registration"})
if predicate.get("parameters", {}).get("source_instance_annotations"):
required.add("instance_matching")
if predicate.get("parameters", {}).get("source_selector_profile"):
required.add("source_instance_selection")
if family in {"surface_residual_inventory", "destination_membership", "relocation_transition"}:
required.update({"region_resolution", "spatial_geometry", "counting"})
if family == "relocation_transition":
required.discard("counting")
missing = sorted(required - operation_kinds)
if missing:
return [], ["predicate_missing_required_operations:" + ",".join(missing)]
def subject_queries(role: str) -> tuple[str, ...]:
roster_queries = tuple(dict.fromkeys(
str(item.get("query_text") or "").strip()
for item in predicate.get("parameters", {}).get("source_instance_annotations", [])
if isinstance(item, Mapping) and str(item.get("query_text") or "").strip()
))
if roster_queries:
# Human-verified annotations define distinct source instances.
# Do not semantic-dedupe location-qualified queries here: two
# raccoons on different trunks or two yellow birds on different
# branches are separate roster members, not detector aliases.
return roster_queries
values: list[str] = []
for item in predicate.get("subjects", []):
if isinstance(item, Mapping):
plural_key = "input_queries" if role == "input" else "output_queries"
plural_values = item.get(plural_key)
if isinstance(plural_values, (list, tuple)):
values.extend(str(value) for value in plural_values if str(value or "").strip())
continue
key = "input_query" if role == "input" else "output_query"
value = item.get(key) or item.get("identity_query")
else:
value = item
if str(value or "").strip():
values.append(str(value))
if predicate.get("parameters", {}).get("articulated_entity_preservation_profile"):
values.extend(
str(value)
for value in predicate.get("component_queries", [])
if str(value or "").strip()
)
if role == "pred" and family == "group_pose_arrangement":
# Group-pose predicates deliberately separate the aggregate
# subject (for example, a relocated binder row) from its physical
# components (individual binder spines). The terminal adapter
# measures PCA and spacing on the components, so omitting these
# queries makes an otherwise executable predicate impossible to
# satisfy at runtime.
values.extend(
str(value)
for value in predicate.get("component_queries", [])
if str(value or "").strip()
)
if role == "pred" and "crop_classification" in operation_kinds:
values.extend(
str(value)
for value in predicate.get("parameters", {}).get(
"classification_proposal_queries", []
)
if str(value or "").strip()
)
values.extend(_registered_subject_detector_aliases(predicate, values))
return canonical_detector_queries(values)
identity_queries = subject_queries("pred")
if not identity_queries:
return [], ["executable_predicate_has_no_detector_queries"]
calls: list[ToolCallSpec] = []
detectors_by_role: dict[str, list[ToolCallSpec]] = {}
for role in ("input", "pred"):
role_declared = any(
item.get("kind") == "object_detection" and role in item.get("image_roles", [])
for item in operations
)
if not role_declared:
continue
role_queries = subject_queries(role)
role_calls = [
_call(
case_key=case_key,
check_id=spec.check_id,
tool="open_vocabulary_detector",
image_role=role,
image_identity=image_identities[role],
queries=batch,
params={
"evidence_role": "target_instance",
"purpose": "target_detection",
"predicate_family": family,
"predicate_schema_version": predicate["schema_version"],
},
)
for batch in _chunks(role_queries, MAX_DETECTOR_QUERIES_PER_CALL)
]
detectors_by_role[role] = role_calls
calls.extend(role_calls)
masks_by_role: dict[str, ToolCallSpec] = {}
for role in ("input", "pred"):
role_declared = any(
item.get("kind") == "mask_refinement" and role in item.get("image_roles", [])
for item in operations
)
dependencies = detectors_by_role.get(role, [])
if role_declared and not dependencies:
return [], [f"predicate_mask_refinement_has_no_detector_dependency:{role}"]
if not role_declared:
continue
mask = _call(
case_key=case_key,
check_id=spec.check_id,
tool="mask_refiner",
image_role=role,
image_identity=image_identities[role],
queries=subject_queries(role),
depends_on=tuple(item.call_id for item in dependencies),
params={
"detection_scope": "dependency_call_ids_v1",
"source_zone_policy": "per_instance_input_mask_or_bbox",
"predicate_family": family,
},
)
masks_by_role[role] = mask
calls.append(mask)
source_selector_call: ToolCallSpec | None = None
source_selector_parameters = predicate.get("parameters", {}).get("source_selector")
if "source_instance_selection" in operation_kinds:
if not isinstance(source_selector_parameters, Mapping):
return [], ["source_instance_selector_parameters_missing"]
input_target_mask = masks_by_role.get("input")
selector_identity_queries = canonical_detector_queries(
source_selector_parameters.get("identity_queries", [])
)
anchor_queries = canonical_detector_queries(
source_selector_parameters.get("anchor_queries", [])
)
if input_target_mask is None or not selector_identity_queries or not anchor_queries:
return [], ["source_instance_selector_dependencies_incomplete"]
# A selector may identify an allowed-edit support object (for example
# a shoulder bird) while the predicate roster is a different entity
# (the robot). In that case it receives its own question-scoped
# detector/mask lineage instead of reusing the roster mask.
if tuple(selector_identity_queries) != tuple(subject_queries("input")):
identity_detectors = [
_call(
case_key=case_key,
check_id=spec.check_id,
tool="open_vocabulary_detector",
image_role="input",
image_identity=image_identities["input"],
queries=batch,
params={
"evidence_role": "source_selector_identity",
"purpose": "source_selector_identity_detection",
"predicate_family": family,
"predicate_schema_version": predicate["schema_version"],
},
)
for batch in _chunks(selector_identity_queries, MAX_DETECTOR_QUERIES_PER_CALL)
]
calls.extend(identity_detectors)
input_target_mask = _call(
case_key=case_key,
check_id=spec.check_id,
tool="mask_refiner",
image_role="input",
image_identity=image_identities["input"],
queries=selector_identity_queries,
depends_on=tuple(item.call_id for item in identity_detectors),
params={
"detection_scope": "dependency_call_ids_v1",
"evidence_role": "source_selector_identity",
"predicate_family": family,
},
)
calls.append(input_target_mask)
anchor_detectors = [
_call(
case_key=case_key,
check_id=spec.check_id,
tool="open_vocabulary_detector",
image_role="input",
image_identity=image_identities["input"],
queries=batch,
params={
"evidence_role": "source_selector_anchor",
"purpose": "source_selector_anchor_detection",
"predicate_family": family,
"predicate_schema_version": predicate["schema_version"],
},
)
for batch in _chunks(anchor_queries, MAX_DETECTOR_QUERIES_PER_CALL)
]
calls.extend(anchor_detectors)
anchor_mask = _call(
case_key=case_key,
check_id=spec.check_id,
tool="mask_refiner",
image_role="input",
image_identity=image_identities["input"],
queries=anchor_queries,
depends_on=tuple(item.call_id for item in anchor_detectors),
params={
"detection_scope": "dependency_call_ids_v1",
"evidence_role": "source_selector_anchor",
"predicate_family": family,
},
)
calls.append(anchor_mask)
source_selector_call = _call(
case_key=case_key,
check_id=spec.check_id,
tool="source_instance_selector",
image_role="input",
image_identity=image_identities["input"],
queries=selector_identity_queries,
depends_on=(input_target_mask.call_id, anchor_mask.call_id),
params={
**dict(source_selector_parameters),
"identity_mask_call_id": input_target_mask.call_id,
"anchor_mask_call_id": anchor_mask.call_id,
"lineage_policy": "raw_fused_mask_content_sha256_v1",
},
)
calls.append(source_selector_call)
region_resolvers_by_role: dict[str, ToolCallSpec] = {}
zone_masks_by_role: dict[str, ToolCallSpec] = {}
labeled_zone_ids: list[str] = []
labeled_zone_ocr: ToolCallSpec | None = None
special_region_specs: list[dict[str, Any]] = []
if "region_resolution" in operation_kinds:
region_calls_by_role: dict[str, list[ToolCallSpec]] = {}
region_specs_by_role: dict[str, list[dict[str, Any]]] = {}
regions_to_propose: list[dict[str, Any]] = []
for raw_region in predicate.get("regions", []):
if not isinstance(raw_region, Mapping):
continue
region = dict(raw_region)
region_id = str(region.get("region_id") or region.get("id") or "").strip()
materializer = region.get("materializer") if isinstance(region.get("materializer"), Mapping) else {}
if materializer.get("kind") == "input_target_mask_transfer":
continue
materializer_kind = str(materializer.get("kind") or "")
if materializer_kind in {"input_ocr_color_zone", "ocr_container_layout"}:
labeled_zone_ids.append(region_id)
continue
if materializer_kind == "registered_change_derivation":
special_region_specs.append(region)
continue
if materializer_kind in {
"anchor_relative_zone", "shelf_grid_parser", "planar_free_space_parser",
"derived_free_space_zone", "architecture_region_parser",
}:
special_region_specs.append(region)
# Special regions are derived from independently detected
# support geometry. Give every support query its own region
# ID so a union cannot silently confuse a shelf with a tray,
# a robot with the ground, or an anchor with the moved item.
roles = [str(item) for item in region.get("image_roles", []) if str(item) in {"input", "pred"}]
roles = roles or ["pred"]
for support_index, query in enumerate(
canonical_detector_queries(materializer.get("queries", [])), 1
):
support_id = f"{region_id}__support_{support_index:02d}"
regions_to_propose.append(
{
"region_id": support_id,
"parent_materialized_region_id": region_id,
"semantic_role": "materializer_support",
"image_roles": roles,
"source_image": "both" if set(roles) == {"input", "pred"} else roles[0],
"proposal_method": "grounding_dino_box",
"query_or_rule": query,
"materializer": {
"kind": "detector_segmenter",
"queries": [query],
"selection_policy": "top1_then_segment",
},
"geometry_policy": "support_mask_required",
}
)
continue
regions_to_propose.append(region)
for region in regions_to_propose:
region_id = str(region.get("region_id") or region.get("id") or "").strip()
materializer = region.get("materializer") if isinstance(region.get("materializer"), Mapping) else {}
materializer_kind = str(materializer.get("kind") or "")
region_queries = canonical_detector_queries(materializer.get("queries", []))
roles = [str(item) for item in region.get("image_roles", []) if str(item)]
if materializer_kind not in {"open_vocabulary_detector", "detector_segmenter"}:
return [], [f"predicate_region_materializer_not_registered:{region_id or 'missing'}:{materializer_kind or 'missing'}"]
if not region_id or not region_queries or not roles:
return [], [f"predicate_region_not_materializable:{region_id or 'missing'}"]
for role in roles:
role_calls = [
_call(
case_key=case_key,
check_id=spec.check_id,
tool="open_vocabulary_detector",
image_role=role,
image_identity=image_identities[role],
queries=batch,
region_ids=(region_id,),
params={
"purpose": "region_proposal",
"evidence_role": "zone_support_instance",
"zone_kind": "spatial_constraint",
"region_id": region_id,
"proposal_method": region.get("proposal_method", "grounding_dino_box"),
"selection_policy": materializer.get("selection_policy", "dino_first_top1_per_query"),
"predicate_family": family,
"semantic_role": region.get("semantic_role", ""),
},
)
for batch in _chunks(region_queries, MAX_DETECTOR_QUERIES_PER_CALL)
]
region_calls_by_role.setdefault(role, []).extend(role_calls)
region_specs_by_role.setdefault(role, []).append(region)
calls.extend(role_calls)
for role, proposal_calls in sorted(region_calls_by_role.items()):
specs = region_specs_by_role[role]
# Both resolvers must advertise the same cross-role policy. The
# region materializer first records the input reference and then
# transfers it to ``pred`` only when both rows are marked stable.
# Marking only the pred row silently prevented the reference from
# ever being recorded.
stable_cross_role = any(
{"input", "pred"}.issubset(set(item.get("image_roles", []))) for item in specs
)
resolver = _call(
case_key=case_key,
check_id=spec.check_id,
tool="region_resolver",
image_role=role,
image_identity=image_identities[role],
region_ids=tuple(dict.fromkeys(str(item["region_id"]) for item in specs)),
depends_on=tuple(item.call_id for item in proposal_calls),
params={
"regions": specs,
"min_score": 0.15,
"selection_policy": "dino_first_top1_per_query",
"cross_role_policy": "stable_input_reference" if stable_cross_role else "independent",
"max_candidates": 8,
"nms_iou": 0.70,
"min_area_fraction": 0.0005,
"max_area_fraction": 0.90,
"predicate_family": family,
},
)
region_resolvers_by_role[role] = resolver
calls.append(resolver)
zone_mask = _call(
case_key=case_key,
check_id=spec.check_id,
tool="zone_mask_refiner",
image_role=role,
image_identity=image_identities[role],
region_ids=resolver.region_ids,
depends_on=(resolver.call_id,),
params={
"geometry_policy": "strict_sam_or_fastsam_mask_v1",
"predicate_family": family,
},
)
zone_masks_by_role[role] = zone_mask
calls.append(zone_mask)
if labeled_zone_ids:
labeled_zone_ocr = _call(
case_key=case_key,
check_id=spec.check_id,
tool="ocr",
image_role="pred",
image_identity=image_identities["pred"],
region_ids=tuple(dict.fromkeys(labeled_zone_ids)),
params={
"purpose": "ocr_container_layout_materialization",
"ocr_scope": "full_frame",
"materializer_backend": "ocr_container_layout_v1",
"predicate_family": family,
},
)
calls.append(labeled_zone_ocr)
matcher = None
if "instance_matching" in operation_kinds:
input_mask = masks_by_role.get("input")
pred_mask = masks_by_role.get("pred")
if input_mask is None or pred_mask is None:
return [], ["predicate_instance_matching_requires_input_and_pred_masks"]
protected_subject_queries = [
str(value)
for value in predicate.get("parameters", {}).get("protected_subject_queries", [])
if str(value or "").strip()
]
source_instance_annotations = list(
predicate.get("parameters", {}).get("source_instance_annotations", [])
)
roster_queries = [
str(item.get("query_text") or "")
for item in source_instance_annotations
if isinstance(item, Mapping) and str(item.get("query_text") or "").strip()
]
target_subject_queries = list(dict.fromkeys(roster_queries or (
str(value)
for subject in predicate.get("subjects", [])
if isinstance(subject, Mapping)
and str(subject.get("id") or "") != "protected_subjects"
for value in (
subject.get("output_queries")
or subject.get("aliases")
or [subject.get("identity_query")]
)
if str(value or "").strip()
)))
matcher = _call(
case_key=case_key,
check_id=spec.check_id,
tool="instance_matcher",
image_role="input_pred",
image_identity=image_identities["input_pred"],
queries=identity_queries,
depends_on=(input_mask.call_id, pred_mask.call_id),
params={
"minimum_confidence": float(
predicate.get("parameters", {}).get("minimum_match_confidence", 0.55)
),
"ambiguity_margin": 0.04,
"minimum_detector_score": float(
predicate.get("parameters", {}).get("minimum_detection_confidence", 0.15)
),
"spatial_consistency": family == "fixed_location_instance_preservation" or "fixed_location_entity_preservation" in semantic_families,
"spatial_weight": 0.30 if family == "fixed_location_instance_preservation" or "fixed_location_entity_preservation" in semantic_families else 0.0,
"required_matching_features": list(
predicate.get("parameters", {}).get("required_matching_features", [])
),
"mask_shape_weight": (
0.10
if "mask shape" in {
str(value).strip().lower()
for value in predicate.get("parameters", {}).get("required_matching_features", [])
}
else 0.0
),
"source_instance_annotations": source_instance_annotations,
**(
{
"source_annotation_mask_profile": str(
predicate.get("parameters", {}).get("source_annotation_mask_profile")
or "fastsam_bbox_prompt_or_color_component_v2"
)
}
if source_instance_annotations
else {}
),
"classification_labels": list(
predicate.get("parameters", {}).get("matching_classification_labels", [])
),
# A matcher may depend on masks for both the target inventory
# and protected context subjects. Keep those semantic roles
# explicit so the executor never forces a bear/robot/moose
# crop into the target closed set.
"target_subject_queries": target_subject_queries,
"protected_subject_queries": protected_subject_queries,
**(
{
"protected_subject_source_annotations": list(
predicate.get("parameters", {}).get(
"protected_subject_source_annotations", []
)
),
"protected_subject_source_mask_profile": str(
predicate.get("parameters", {}).get(
"protected_subject_source_mask_profile"
) or ""
),
"protected_subject_minimum_identity_confidence": float(
predicate.get("parameters", {}).get(
"protected_subject_minimum_identity_confidence", 0.45
)
),
"protected_classification_minimum_margin": float(
predicate.get("parameters", {}).get(
"protected_classification_minimum_margin", 0.0
)
),
"protected_classification_minimum_probability": float(
predicate.get("parameters", {}).get(
"protected_classification_minimum_probability", 0.25
)
),
}
if protected_subject_queries
else {}
),
"use_segmenter_proposals": bool(
predicate.get("parameters", {}).get("matching_use_segmenter_proposals", False)
),
"segmenter_min_area_fraction": float(
predicate.get("parameters", {}).get("matching_segmenter_min_area_fraction", 0.00003)
),
"segmenter_max_area_fraction": float(
predicate.get("parameters", {}).get("matching_segmenter_max_area_fraction", 0.08)
),
"segmenter_max_proposals": int(
predicate.get("parameters", {}).get("matching_segmenter_max_proposals", 128)
),
"classification_minimum_margin": float(
predicate.get("parameters", {}).get("matching_classification_minimum_margin", 0.06)
),
"classification_minimum_probability": float(
predicate.get("parameters", {}).get("matching_classification_minimum_probability", 0.25)
),
"localized_source_residual_enabled": bool(
predicate.get("parameters", {}).get("localized_source_residual_enabled", False)
),
"localized_source_residual_minimum_correlation": float(
predicate.get("parameters", {}).get("localized_source_residual_minimum_correlation", 0.85)
),
"localized_source_residual_maximum_mean_absolute_error": float(
predicate.get("parameters", {}).get("localized_source_residual_maximum_mean_absolute_error", 0.10)
),
"verified_roster_profile": str(
predicate.get("parameters", {}).get("verified_roster_profile") or ""
),
"verified_roster_assignment_mode": str(
predicate.get("parameters", {}).get("verified_roster_assignment_mode")
or "identity_exact"
),
"verified_roster_expected_counts": dict(
predicate.get("parameters", {}).get("verified_roster_expected_counts", {})
),
"verified_roster_minimum_area_ratio": float(
predicate.get("parameters", {}).get("verified_roster_minimum_area_ratio", 0.10)
),
"verified_roster_maximum_area_ratio": float(
predicate.get("parameters", {}).get("verified_roster_maximum_area_ratio", 6.0)
),
**(
{
"identity_agnostic_target_coverage_profile": str(
predicate.get("parameters", {}).get(
"identity_agnostic_target_coverage_profile"
)
),
"target_coverage_minimum_probability": float(
predicate.get("parameters", {}).get(
"target_coverage_minimum_probability", 0.50
)
),
"target_coverage_minimum_margin": float(
predicate.get("parameters", {}).get(
"target_coverage_minimum_margin", 0.15
)
),
"target_coverage_minimum_animal_probability": float(
predicate.get("parameters", {}).get(
"target_coverage_minimum_animal_probability", 0.75
)
),
"target_coverage_minimum_animal_margin": float(
predicate.get("parameters", {}).get(
"target_coverage_minimum_animal_margin", 0.50
)
),
"target_coverage_maximum_protected_overlap": float(
predicate.get("parameters", {}).get(
"target_coverage_maximum_protected_overlap", 0.10
)
),
"target_coverage_neighborhood_fraction_of_diagonal": float(
predicate.get("parameters", {}).get(
"target_coverage_neighborhood_fraction_of_diagonal", 0.08
)
),
}
if predicate.get("parameters", {}).get(
"identity_agnostic_target_coverage_profile"
)
else {}
),
"algorithm": "hungarian_clip_colour_shape_maskshape_semantic_spatial_group_roster_v5",
"predicate_family": family,
},
)
calls.append(matcher)
classifier = None
if "crop_classification" in operation_kinds:
pred_mask = masks_by_role.get("pred")
if pred_mask is None:
return [], ["predicate_crop_classification_requires_pred_masks"]
classifier = _call(
case_key=case_key,
check_id=spec.check_id,
tool="instance_classifier",
image_role="pred",
image_identity=image_identities["pred"],
queries=identity_queries,
depends_on=(pred_mask.call_id,),
params={
"labels": list(predicate.get("parameters", {}).get("classification_labels", [])),
"minimum_margin": float(
predicate.get("parameters", {}).get("classification_minimum_margin", 0.02)
),
"minimum_probability": float(
predicate.get("parameters", {}).get("classification_minimum_probability", 0.25)
),
"minimum_detector_score": float(
predicate.get("parameters", {}).get(
"classification_proposal_minimum_score",
predicate.get("parameters", {}).get("minimum_detection_confidence", 0.15),
)
),
"use_segmenter_proposals": bool(
predicate.get("parameters", {}).get("classification_use_segmenter_proposals", False)
),
"proposal_zone_ids": list(
predicate.get("parameters", {}).get("classification_proposal_zone_ids", [])
),
"segmenter_min_area_fraction": float(
predicate.get("parameters", {}).get("classification_segmenter_min_area_fraction", 0.00005)
),
"segmenter_max_area_fraction": float(
predicate.get("parameters", {}).get("classification_segmenter_max_area_fraction", 0.08)
),
"segmenter_max_proposals": int(
predicate.get("parameters", {}).get("classification_segmenter_max_proposals", 128)
),
"algorithm": "clip_closed_set_crop_classifier_v1",
"predicate_family": family,
},
)
calls.append(classifier)
registration = None
if "image_registration" in operation_kinds:
registration = _call(
case_key=case_key,
check_id=spec.check_id,
tool="image_registration",
image_role="input_pred",
image_identity=image_identities["input_pred"],
params={
"registration_method": predicate.get("parameters", {}).get(
"registration_method", "robust_static_background_alignment"
),
"registration_tolerance_pixels": int(
predicate.get("parameters", {}).get("registration_tolerance_pixels", 0)
),
"predicate_family": family,
},
)
calls.append(registration)
parser_calls: list[ToolCallSpec] = []
if "change_analysis" in operation_kinds:
change = _call(
case_key=case_key,
check_id=spec.check_id,
tool="change_analysis",
image_role="input_pred",
image_identity=image_identities["input_pred"],
region_ids=tuple(
str(item.get("region_id") or "") for item in predicate.get("regions", [])
if isinstance(item, Mapping) and str(item.get("region_id") or "")
),
depends_on=tuple(dict.fromkeys(
([registration.call_id] if registration is not None else [])
+ [item.call_id for item in region_resolvers_by_role.values()]
+ [item.call_id for item in zone_masks_by_role.values()]
)),
params={
"predicate_family": family,
"target_families": sorted(semantic_families),
"region_specs": list(predicate.get("regions", [])),
"rule_parameters": dict(predicate.get("parameters", {})),
},
)
calls.append(change)
parser_calls.append(change)
def single_image_roles(operation_kind: str) -> set[str]:
"""Return only roles accepted by the single-image CV executors."""
return {
str(role)
for operation in operations
if str(operation.get("kind") or "") == operation_kind
for role in operation.get("image_roles", [])
if str(role) in {"input", "pred"}
}
if "state_parsing" in operation_kinds or special_region_specs:
state_roles = single_image_roles("state_parsing")
state_roles.update(
str(role)
for region in special_region_specs
for role in region.get("image_roles", [])
if str(role) in {"input", "pred"}
)
# A special output materializer from an older typed predicate may not
# carry image_roles. Preserve the historical output-first default,
# but never send a paired role to a single-image parser.
if not state_roles:
state_roles.add("pred")
for role in sorted(state_roles):
role_regions = [
item
for item in predicate.get("regions", [])
if isinstance(item, Mapping)
and (
not item.get("image_roles")
or role in {str(value) for value in item.get("image_roles", [])}
)
]
role_special_regions = [
item
for item in special_region_specs
if not item.get("image_roles")
or role in {str(value) for value in item.get("image_roles", [])}
]
state_dependencies = []
if role in region_resolvers_by_role:
state_dependencies.append(region_resolvers_by_role[role].call_id)
if registration is not None:
state_dependencies.append(registration.call_id)
state = _call(
case_key=case_key,
check_id=spec.check_id,
tool="state_parser",
image_role=role,
image_identity=image_identities[role],
region_ids=tuple(
str(item.get("region_id") or "")
for item in role_regions
if str(item.get("region_id") or "")
),
depends_on=tuple(dict.fromkeys(state_dependencies)),
params={
"parser_mode": "typed_contract_materializers_v1",
"predicate_family": family,
"target_families": sorted(semantic_families),
"region_specs": role_special_regions,
"rule_parameters": dict(predicate.get("parameters", {})),
"obligation_bindings": list(predicate.get("parameter_bindings", [])),
},
)
calls.append(state)
parser_calls.append(state)
if "visual_attribute" in operation_kinds:
attribute_roles = single_image_roles("visual_attribute") or {"pred"}
for role in sorted(attribute_roles):
mask = masks_by_role.get(role)
attribute = _call(
case_key=case_key,
check_id=spec.check_id,
tool="visual_attribute_parser",
image_role=role,
image_identity=image_identities[role],
queries=subject_queries(role),
depends_on=(mask.call_id,) if mask is not None else (),
params={
"parser_mode": "typed_contract_attributes_v1",
"predicate_family": family,
"target_families": sorted(semantic_families),
"rule_parameters": dict(predicate.get("parameters", {})),
"obligation_bindings": list(predicate.get("parameter_bindings", [])),
},
)
calls.append(attribute)
parser_calls.append(attribute)
if "pose_estimation" in operation_kinds:
pose_roles = single_image_roles("pose_estimation") or {"input", "pred"}
pose_profile = str(predicate.get("parameters", {}).get("pose_profile") or "")
try:
pose_parameters = human_pose_profile_parameters(pose_profile)
except ValueError:
return [], ["pose_estimation_requires_registered_pose_profile"]
for role in sorted(pose_roles):
detector_dependencies = tuple(
item.call_id for item in detectors_by_role.get(role, [])
)
pose = _call(
case_key=case_key,
check_id=spec.check_id,
tool="human_pose_parser",
image_role=role,
image_identity=image_identities[role],
queries=subject_queries(role),
depends_on=detector_dependencies,
params={
"parser_mode": "coco17_human_pose_v1",
"predicate_family": family,
"rule_parameters": dict(predicate.get("parameters", {})),
**pose_parameters,
},
)
calls.append(pose)
parser_calls.append(pose)
if "local_correspondence" in operation_kinds:
if matcher is None or registration is None:
return [], ["local_correspondence_requires_matcher_and_registration"]
local_profile = str(
predicate.get("parameters", {}).get("local_correspondence_profile") or ""
)
try:
local_parameters = local_correspondence_profile_parameters(local_profile)
except ValueError:
return [], ["local_correspondence_requires_registered_profile"]
local = _call(
case_key=case_key,
check_id=spec.check_id,
tool="local_correspondence",
image_role="input_pred",
image_identity=image_identities["input_pred"],
queries=identity_queries,
depends_on=(matcher.call_id, registration.call_id),
params={
"parser_mode": "sift_mutual_ransac_affine_v1",
"predicate_family": family,
"rule_parameters": dict(predicate.get("parameters", {})),
**local_parameters,
},
)
calls.append(local)
parser_calls.append(local)
dependencies = [*masks_by_role.values()]
if source_selector_call is not None:
dependencies.append(source_selector_call)
if matcher is not None:
dependencies.append(matcher)
if classifier is not None:
dependencies.append(classifier)
if registration is not None:
dependencies.append(registration)
dependencies.extend(detectors_by_role.get("pred", []))
dependencies.extend(region_resolvers_by_role.values())
dependencies.extend(zone_masks_by_role.values())
if labeled_zone_ocr is not None:
dependencies.append(labeled_zone_ocr)
dependencies.extend(parser_calls)
source_rule_type = str(predicate.get("source_rule_type") or "")
reviewed_predicate = bool(
family in {
"fixed_location_entity_preservation",
"registered_invariant_region_preservation",
"relocated_entity_integrity",
"destination_membership",
"registered_structural_state",
"group_pose_arrangement",
"contract_family_all_of",
}
and predicate.get("capability_versions")
)
metric = _call(
case_key=case_key,
check_id=spec.check_id,
tool="contract_metric_binding",
image_role="input_pred",
image_identity=image_identities["input_pred"],
queries=identity_queries,
depends_on=tuple(dict.fromkeys(item.call_id for item in dependencies)),
params={
# Reviewed contracts retain their exact source rule because their
# typed clauses, rather than a legacy canonical alias, define the
# executable semantics. Legacy bridges continue to use the
# canonical registry key.
"metric_binding": (
source_rule_type if reviewed_predicate else canonical_rule_type(source_rule_type)
),
"source_rule_type": source_rule_type,
"executable_predicate": dict(predicate),
"negative_evidence_policy": "fail_closed_unknown",
"rule_parameters": dict(predicate.get("parameters", {})),
},
)
calls.append(metric)
return calls, []
def _calls_for_program(
case_key: str,
spec: AtomicCheckSpec,
program: EvidenceProgram,
image_identities: dict[str, str],
*,
authoritative_lowering: bool = True,
) -> tuple[list[ToolCallSpec], list[str]]:
"""Lower one semantic evidence program into physical tool calls."""
predicate = (
program.checker_params.get("executable_predicate")
if isinstance(program.checker_params.get("executable_predicate"), Mapping)
else None
)
if program.checker_params.get("require_executable_predicate") and authoritative_lowering:
if predicate is None:
return [], ["missing_executable_predicate"]
return _calls_for_executable_predicate(case_key, spec, predicate, image_identities, program)
compiled_spec = replace(spec, params=program.checker_params)
queries = list(detector_queries_for_check(compiled_spec))
regions = tuple(item.region_id for item in program.regions)
requirements = [item for item in program.requirements if not item.optional and item.status == "supported"]
operations = {item.operation for item in requirements}
roles_by_operation: dict[str, set[str]] = {}
for requirement in requirements:
roles_by_operation.setdefault(requirement.operation, set()).update(requirement.image_roles)
calls: list[ToolCallSpec] = []
reasons: list[str] = []
call_params = dict(program.checker_params)
detector_by_role: dict[str, list[ToolCallSpec]] = {}
target_detector_by_role: dict[str, list[ToolCallSpec]] = {}
masks_by_role: dict[str, ToolCallSpec] = {}
parser_calls_by_operation: dict[str, list[ToolCallSpec]] = {}
checker_semantics = " ".join(
[
str(spec.checker),
str(program.checker_params.get("evidence_type", "")),
str((program.checker_params.get("decision_rule") or {}).get("type", ""))
if isinstance(program.checker_params.get("decision_rule"), dict)
else "",
]
).lower()
decision_rule = call_params.get("decision_rule") if isinstance(call_params.get("decision_rule"), dict) else {}
source_rule_type = str(decision_rule.get("type") or "")
rule_type = canonical_rule_type(source_rule_type)
# A reviewed referring expression can be valuable for localization but
# too brittle for exhaustive absence search (for example, "small bird
# perched on the robot's left shoulder"). When a source-vacancy contract
# also supplies one short object identity, keep that identity as an
# additional detector query. The support/location expression remains in
# the named-region stream and must not be the only way to find the target.
if rule_type == "source_zone_vacancy":
short_object_queries = canonical_detector_queries(
query
for value in _values(call_params, "object")
for query in expand_detector_query(value)
if 0 < len(re.findall(r"[a-z0-9]+", query.lower())) <= 3
)
queries = list(dict.fromkeys((*short_object_queries, *queries)))
stable_cross_role_regions = any(
token in checker_semantics for token in ("preservation", "integrity", "invariant")
) or rule_type in {"desk_clutter_residual_count"}
stable_instance_locations = any(
token in checker_semantics for token in ("preservation", "integrity", "invariant")
)
target_evidence_role = "invariant_instance" if stable_instance_locations else "target_instance"
# Runtime availability is parameter-sensitive. A generic parser binary
# existing on disk is not enough to call a check executable when the
# contract omits the schema that parser actually consumes.
unmaterialized_regions = [
item.region_id for item in program.regions
if item.status == "auto_resolvable" and item.resolver_operation != "object_detection"
]
if unmaterialized_regions:
reasons.append("region_backend_has_no_named_zone_materializer:" + ",".join(unmaterialized_regions))
if "visual_attribute" in operations and not _explicit_colors(call_params):
reasons.append("visual_attribute_parser_requires_explicit_supported_color")
if "route_extraction" in operations and not _explicit_colors(call_params):
reasons.append("route_parser_requires_explicit_route_color_or_typed_model")
if "state_parsing" in operations and not _has_structured_cells(call_params):
reasons.append("state_parser_requires_explicit_cells_with_geometry_and_color")
detector_requirements = [
item for item in requirements
if item.operation == "object_detection" and item.source != "planned_regions"
]
detector_queries = canonical_detector_queries(queries)
detector_roles = {role for item in detector_requirements for role in item.image_roles}
if detector_roles and not detector_queries:
reasons.append("detector_checker_has_no_check_scoped_queries")
for role in sorted(detector_roles):
detector_calls = [
_call(
case_key=case_key,
check_id=spec.check_id,
tool="open_vocabulary_detector",
image_role=role,
image_identity=image_identities[role],
queries=query_batch,
params={"evidence_role": target_evidence_role, "purpose": "target_detection"},
)
for query_batch in _chunks(detector_queries, MAX_DETECTOR_QUERIES_PER_CALL)
]
detector_by_role[role] = detector_calls
target_detector_by_role[role] = list(detector_calls)
calls.extend(detector_calls)
# Region proposals are separate typed calls so their detections can be
# materialized back into named checker zones instead of being confused
# with the target-object detections for the same question.
region_proposals_by_role: dict[str, list[ToolCallSpec]] = {}
region_specs_by_role: dict[str, list[Any]] = {}
region_resolvers_by_role: dict[str, ToolCallSpec] = {}
spatial_region_ids_by_role: dict[str, list[str]] = {}
for region in program.regions:
if region.status != "auto_resolvable" or region.resolver_operation != "object_detection":
continue
for role in region.image_roles:
region_query = region_detector_queries(region.query_or_rule, region.region_id)
if not region_query:
# Inventory/source regions name a set of target instances, not
# a new scene surface. Reuse the check-scoped object queries
# and materialize their union instead of inventing a generic
# detector prompt such as "inventory".
if any(token in region.region_id.lower() for token in ("inventory", "sources", "instances")):
region_query = detector_queries
if not region_query:
reasons.append(f"region_proposal_has_no_detector_query:{region.region_id}")
continue
if role == "pred" and any(_same_concept(region_query[0], query) for query in detector_queries):
reasons.append(f"region_query_not_independent_of_target_object:{region.region_id}")
zone_kind = _region_zone_kind(region.region_id, region_query, detector_queries, rule_type)
if zone_kind == "spatial_constraint":
spatial_region_ids_by_role.setdefault(role, []).append(region.region_id)
region_calls = [
_call(
case_key=case_key,
check_id=spec.check_id,
tool="open_vocabulary_detector",
image_role=role,
image_identity=image_identities[role],
queries=query_batch,
region_ids=(region.region_id,),
params={
"purpose": "region_proposal",
"evidence_role": "zone_support_instance",
"zone_kind": zone_kind,
"region_id": region.region_id,
"proposal_method": region.proposal_method,
"selection_policy": "dino_first_top1_per_query",
},
)
for query_batch in _chunks(region_query, MAX_DETECTOR_QUERIES_PER_CALL)
]
detector_by_role.setdefault(role, []).extend(region_calls)
region_proposals_by_role.setdefault(role, []).extend(region_calls)
region_specs_by_role.setdefault(role, []).append(region)
calls.extend(region_calls)
# Materialization has its own terminal status. A successful detector call
# with zero boxes is valid negative detector evidence, but not a usable
# checker zone.
for role, proposal_calls in sorted(region_proposals_by_role.items()):
resolver_call = _call(
case_key=case_key,
check_id=spec.check_id,
tool="region_resolver",
image_role=role,
image_identity=image_identities[role],
region_ids=tuple(item.region_id for item in region_specs_by_role[role]),
depends_on=tuple(item.call_id for item in proposal_calls),
params={
"regions": [item.to_dict() for item in region_specs_by_role[role]],
"min_score": float(program.checker_params.get("region_min_score", 0.15)),
"selection_policy": "dino_first_top1_per_query",
"cross_role_policy": "stable_input_reference" if stable_cross_role_regions else "independent",
"max_candidates": int(program.checker_params.get("region_max_candidates", 6)),
"nms_iou": float(program.checker_params.get("region_nms_iou", 0.70)),
"min_area_fraction": float(program.checker_params.get("region_min_area_fraction", 0.0005)),
"max_area_fraction": float(program.checker_params.get("region_max_area_fraction", 0.90)),
},
)
region_resolvers_by_role[role] = resolver_call
calls.append(resolver_call)
# A detector box only prompts the zone segmenter; it is not itself valid
# containment geometry. Make this refinement an explicit physical call
# so its success/failure and provenance are represented in the execution
# ledger rather than appearing as anonymous derived evidence.
zone_masks_by_role: dict[str, ToolCallSpec] = {}
for role, region_ids_for_role in sorted(spatial_region_ids_by_role.items()):
resolver = region_resolvers_by_role.get(role)
if resolver is None:
reasons.append(f"zone_mask_refinement_has_no_region_dependency:{role}")
continue
zone_mask_call = _call(
case_key=case_key,
check_id=spec.check_id,
tool="zone_mask_refiner",
image_role=role,
image_identity=image_identities[role],
region_ids=tuple(dict.fromkeys(region_ids_for_role)),
depends_on=(resolver.call_id,),
params={"geometry_policy": "strict_sam_or_fastsam_mask_v1"},
)
zone_masks_by_role[role] = zone_mask_call
calls.append(zone_mask_call)
for role in sorted(roles_by_operation.get("mask_refinement", set())):
# Region-proposal detections must never become target instances. The
# region resolver consumes those calls separately; mask refinement is
# seeded only by the check's target-object detector calls.
dependencies = target_detector_by_role.get(role, [])
if not dependencies:
reasons.append(f"mask_refinement_has_no_detector_dependency:{role}")
continue
mask_call = _call(
case_key=case_key,
check_id=spec.check_id,
tool="mask_refiner",
image_role=role,
image_identity=image_identities[role],
queries=detector_queries,
region_ids=regions,
depends_on=tuple(item.call_id for item in dependencies),
params={"detection_scope": "dependency_call_ids_v1"},
)
masks_by_role[role] = mask_call
calls.append(mask_call)
matcher_call = None
if "instance_matching" in operations:
input_mask = masks_by_role.get("input")
pred_mask = masks_by_role.get("pred")
if input_mask is None or pred_mask is None:
reasons.append("instance_matching_requires_input_and_pred_masks")
else:
predicate_parameters = (
predicate.get("parameters", {})
if isinstance(predicate, Mapping)
and isinstance(predicate.get("parameters"), Mapping)
else {}
)
protected_subject_queries = [
str(value)
for value in predicate_parameters.get("protected_subject_queries", [])
if str(value or "").strip()
]
source_instance_annotations = list(
predicate_parameters.get("source_instance_annotations", [])
)
roster_queries = [
str(item.get("query_text") or "")
for item in source_instance_annotations
if isinstance(item, Mapping) and str(item.get("query_text") or "").strip()
]
target_subject_queries = list(dict.fromkeys(roster_queries or (
str(value)
for subject in (predicate.get("subjects", []) if isinstance(predicate, Mapping) else [])
if isinstance(subject, Mapping)
and str(subject.get("id") or "") != "protected_subjects"
for value in (
subject.get("output_queries")
or subject.get("aliases")
or [subject.get("identity_query")]
)
if str(value or "").strip()
)))
matcher_call = _call(
case_key=case_key,
check_id=spec.check_id,
tool="instance_matcher",
image_role="input_pred",
image_identity=image_identities["input_pred"],
queries=detector_queries,
depends_on=(input_mask.call_id, pred_mask.call_id),
params={
"minimum_confidence": float(
predicate_parameters.get(
"minimum_match_confidence",
call_params.get("min_match_confidence", call_params.get("minimum_match_confidence", 0.55)),
)
),
"ambiguity_margin": float(call_params.get("match_ambiguity_margin", 0.04)),
"minimum_detector_score": float(
predicate_parameters.get(
"minimum_detector_confidence",
predicate_parameters.get(
"minimum_detection_confidence",
call_params.get("minimum_detector_score", 0.15),
),
)
),
"spatial_consistency": stable_instance_locations,
"spatial_weight": float(call_params.get("match_spatial_weight", 0.30 if stable_instance_locations else 0.0)),
"required_matching_features": list(
predicate_parameters.get("required_matching_features", [])
),
"mask_shape_weight": (
0.10
if "mask shape" in {
str(value).strip().lower()
for value in predicate_parameters.get("required_matching_features", [])
}
else 0.0
),
"source_instance_annotations": source_instance_annotations,
**(
{
"source_annotation_mask_profile": str(
predicate_parameters.get("source_annotation_mask_profile")
or "fastsam_bbox_prompt_or_color_component_v2"
)
}
if source_instance_annotations
else {}
),
"classification_labels": list(
predicate_parameters.get("matching_classification_labels", [])
),
"target_subject_queries": target_subject_queries,
"protected_subject_queries": protected_subject_queries,
**(
{
"protected_subject_source_annotations": list(
predicate_parameters.get(
"protected_subject_source_annotations", []
)
),
"protected_subject_source_mask_profile": str(
predicate_parameters.get(
"protected_subject_source_mask_profile"
) or ""
),
"protected_subject_minimum_identity_confidence": float(
predicate_parameters.get(
"protected_subject_minimum_identity_confidence", 0.45
)
),
"protected_classification_minimum_margin": float(
predicate_parameters.get(
"protected_classification_minimum_margin", 0.0
)
),
"protected_classification_minimum_probability": float(
predicate_parameters.get(
"protected_classification_minimum_probability", 0.25
)
),
}
if protected_subject_queries
else {}
),
"use_segmenter_proposals": bool(
predicate_parameters.get("matching_use_segmenter_proposals", False)
),
"segmenter_min_area_fraction": float(
predicate_parameters.get("matching_segmenter_min_area_fraction", 0.00003)
),
"segmenter_max_area_fraction": float(
predicate_parameters.get("matching_segmenter_max_area_fraction", 0.08)
),
"segmenter_max_proposals": int(
predicate_parameters.get("matching_segmenter_max_proposals", 128)
),
"classification_minimum_margin": float(
predicate_parameters.get("matching_classification_minimum_margin", 0.06)
),
"classification_minimum_probability": float(
predicate_parameters.get("matching_classification_minimum_probability", 0.25)
),
"localized_source_residual_enabled": bool(
predicate_parameters.get("localized_source_residual_enabled", False)
),
"localized_source_residual_minimum_correlation": float(
predicate_parameters.get("localized_source_residual_minimum_correlation", 0.85)
),
"localized_source_residual_maximum_mean_absolute_error": float(
predicate_parameters.get("localized_source_residual_maximum_mean_absolute_error", 0.10)
),
"verified_roster_profile": str(
predicate_parameters.get("verified_roster_profile") or ""
),
"verified_roster_assignment_mode": str(
predicate_parameters.get("verified_roster_assignment_mode")
or "identity_exact"
),
"verified_roster_expected_counts": dict(
predicate_parameters.get("verified_roster_expected_counts", {})
),
"verified_roster_minimum_area_ratio": float(
predicate_parameters.get("verified_roster_minimum_area_ratio", 0.10)
),
"verified_roster_maximum_area_ratio": float(
predicate_parameters.get("verified_roster_maximum_area_ratio", 6.0)
),
**(
{
"identity_agnostic_target_coverage_profile": str(
predicate_parameters.get(
"identity_agnostic_target_coverage_profile"
)
),
"target_coverage_minimum_probability": float(
predicate_parameters.get(
"target_coverage_minimum_probability", 0.50
)
),
"target_coverage_minimum_margin": float(
predicate_parameters.get(
"target_coverage_minimum_margin", 0.15
)
),
"target_coverage_minimum_animal_probability": float(
predicate_parameters.get(
"target_coverage_minimum_animal_probability", 0.75
)
),
"target_coverage_minimum_animal_margin": float(
predicate_parameters.get(
"target_coverage_minimum_animal_margin", 0.50
)
),
"target_coverage_maximum_protected_overlap": float(
predicate_parameters.get(
"target_coverage_maximum_protected_overlap", 0.10
)
),
"target_coverage_neighborhood_fraction_of_diagonal": float(
predicate_parameters.get(
"target_coverage_neighborhood_fraction_of_diagonal", 0.08
)
),
}
if predicate_parameters.get(
"identity_agnostic_target_coverage_profile"
)
else {}
),
"algorithm": "hungarian_clip_colour_shape_maskshape_semantic_spatial_group_roster_v5",
},
)
calls.append(matcher_call)
registration = None
if "image_registration" in operations:
registration = _call(
case_key=case_key,
check_id=spec.check_id,
tool="image_registration",
image_role="input_pred",
image_identity=image_identities["input_pred"],
region_ids=regions,
params=call_params,
)
calls.append(registration)
if "change_analysis" in operations:
if registration is None:
reasons.append("change_analysis_has_no_registration_dependency")
calls.append(
_call(
case_key=case_key,
check_id=spec.check_id,
tool="change_analysis",
image_role="input_pred",
image_identity=image_identities["input_pred"],
region_ids=regions,
depends_on=tuple(
dict.fromkeys(
[
*([registration.call_id] if registration else []),
*(item.call_id for _, item in sorted(region_resolvers_by_role.items())),
]
)
),
params=call_params,
)
)
tool_by_operation = {
"ocr": "ocr",
"route_extraction": "route_parser",
"state_parsing": "state_parser",
"visual_attribute": "visual_attribute_parser",
"pose_estimation": "human_pose_parser",
"local_correspondence": "local_correspondence",
}
for operation, tool in tool_by_operation.items():
for role in sorted(roles_by_operation.get(operation, set())):
resolver = region_resolvers_by_role.get(role)
parser_params = dict(call_params)
if operation == "pose_estimation":
rule_parameters = decision_rule.get("parameters") if isinstance(decision_rule.get("parameters"), Mapping) else {}
try:
parser_params.update(human_pose_profile_parameters(str(rule_parameters.get("pose_profile") or "")))
except ValueError:
reasons.append("pose_estimation_requires_registered_pose_profile")
continue
if operation == "local_correspondence":
rule_parameters = decision_rule.get("parameters") if isinstance(decision_rule.get("parameters"), Mapping) else {}
try:
parser_params.update(
local_correspondence_profile_parameters(
str(rule_parameters.get("local_correspondence_profile") or "")
)
)
except ValueError:
reasons.append("local_correspondence_requires_registered_profile")
continue
parser_dependencies = (resolver.call_id,) if resolver else ()
if operation == "local_correspondence":
if matcher_call is None or registration is None:
reasons.append("local_correspondence_requires_matcher_and_registration")
continue
parser_dependencies = (matcher_call.call_id, registration.call_id)
parser_call = _call(
case_key=case_key,
check_id=spec.check_id,
tool=tool,
image_role=role,
image_identity=image_identities[role],
region_ids=regions,
depends_on=parser_dependencies,
params=parser_params,
)
calls.append(parser_call)
parser_calls_by_operation.setdefault(operation, []).append(parser_call)
if "structured_check" in operations:
# The structured checker is the terminal parser for one reviewed
# atomic rule. It runs after every upstream evidence producer owned
# by the check and consumes the merged observations plus raw images.
# Keeping it as an explicit physical call makes parser failures and
# insufficient evidence visible in the execution ledger.
# The versioned adapter receives raw input/output images and the
# already-merged observation document. It reports ``insufficient``
# itself when evidence it actually consumes is missing. Making every
# exploratory OCR/detector call a hard dependency would incorrectly
# suppress conclusive image-parser results.
structured_dependencies: tuple[str, ...] = ()
calls.append(
_call(
case_key=case_key,
check_id=spec.check_id,
tool="structured_checker",
image_role="input_pred",
image_identity=image_identities["input_pred"],
queries=detector_queries,
region_ids=regions,
depends_on=structured_dependencies,
params={
**call_params,
"structured_adapter": "pvr_structured_contract_v1",
"source_rule_type": source_rule_type,
},
)
)
if rule_type in REGISTERED_RULE_TYPES:
# This is a terminal decision call, so it depends only on evidence the
# registered metric handler actually reads. Unrelated parser calls
# remain auditable but cannot invalidate a conclusive metric.
capability = metric_capability(rule_type)
metric_dependencies: list[ToolCallSpec] = []
operation_calls = {
"instance_matching": [matcher_call] if matcher_call is not None else [],
"mask_refinement": [item for _, item in sorted(masks_by_role.items())],
"ocr": list(parser_calls_by_operation.get("ocr", [])),
"image_registration": [registration] if registration is not None else [],
}
if capability is not None:
for requirement in capability.evidence:
if requirement.terminal_dependency:
metric_dependencies.extend(operation_calls.get(requirement.operation, []))
for region_requirement in capability.regions:
matching_regions = [
region
for region in program.regions
if (not region_requirement.image_role or region_requirement.image_role in region.image_roles)
and any(token in region.region_id.lower() for token in region_requirement.tokens)
]
if not matching_regions:
static_zone_ids = (
tuple(str(zone_id) for zone_id in call_params.get("zones", {}))
if isinstance(call_params.get("zones"), dict)
else ()
)
if not any(
token in zone_id.lower()
for zone_id in static_zone_ids
for token in region_requirement.tokens
):
reasons.append(
"metric_required_region_not_declared:"
+ "|".join(region_requirement.tokens)
)
continue
if any(region.status == "auto_resolvable" for region in matching_regions):
resolver = region_resolvers_by_role.get(region_requirement.image_role)
if resolver is not None:
metric_dependencies.append(resolver)
required_ids = {region.region_id for region in matching_regions}
if required_ids & set(spatial_region_ids_by_role.get(region_requirement.image_role, [])):
zone_mask = zone_masks_by_role.get(region_requirement.image_role)
if zone_mask is not None:
metric_dependencies.append(zone_mask)
metric_dependency_ids = tuple(dict.fromkeys(item.call_id for item in metric_dependencies))
calls.append(
_call(
case_key=case_key,
check_id=spec.check_id,
tool="contract_metric_binding",
image_role="input_pred",
image_identity=image_identities["input_pred"],
queries=detector_queries,
region_ids=regions,
depends_on=metric_dependency_ids,
params={
"metric_binding": rule_type,
"source_rule_type": source_rule_type,
"rule_parameters": dict(decision_rule.get("parameters") or {}),
"decision_conditions": {
key: str(decision_rule.get(key) or "")
for key in ("pass_condition", "partial_condition", "fail_condition")
},
"enforce_contract_compliance": True,
"zones": dict(call_params.get("zones") or {}) if isinstance(call_params.get("zones"), dict) else {},
"negative_evidence_policy": "fail_closed_unknown",
"executable_predicate": dict(predicate) if predicate is not None else None,
},
)
)
if not calls and program.executable:
reasons.append("executable_program_has_no_external_tool_calls")
return calls, reasons
def build_case_tool_plan(
contract: EvalContract,
*,
case_key: str,
input_image_id: str | None = None,
pred_image_id: str | None = None,
) -> dict[str, Any]:
"""Return one executable, cache-aware plan for a case."""
image_identities = {
"input": input_image_id or f"{case_key}:input",
"pred": pred_image_id or f"{case_key}:pred",
}
image_identities["input_pred"] = f"{image_identities['input']}|{image_identities['pred']}"
physical: dict[str, ToolCallSpec] = {}
check_plans: list[CheckToolPlan] = []
compiled_checks: dict[str, dict[str, Any]] = {}
for spec in contract.atomic_checks:
program = compile_evidence_program(
spec,
contract_zones=contract.zones,
available_operations=RUNTIME_AVAILABLE_OPERATIONS,
)
compiled_checks[spec.check_id] = {
"params": program.checker_params,
"evidence_program": program.to_dict(),
}
calls, reasons = _calls_for_program(case_key, spec, program, image_identities)
call_ids = []
for call in calls:
existing = physical.get(call.cache_key)
if existing is None:
physical[call.cache_key] = call
existing = call
elif spec.check_id not in existing.check_ids:
physical[call.cache_key] = ToolCallSpec(
**{**existing.__dict__, "check_ids": tuple((*existing.check_ids, spec.check_id))}
)
existing = physical[call.cache_key]
call_ids.append(existing.call_id)
authoritative_predicate = (
program.checker_params.get("executable_predicate")
if program.checker_params.get("require_executable_predicate")
and isinstance(program.checker_params.get("executable_predicate"), Mapping)
else None
)
if authoritative_predicate is not None:
families = tuple(
dict.fromkeys(
str(item.get("tool_family") or item.get("kind") or "")
for item in authoritative_predicate.get("operations", [])
if isinstance(item, Mapping) and (item.get("tool_family") or item.get("kind"))
)
)
unknown = ()
else:
families, unknown = _declared_tool_audit(spec)
reasons.extend(program.reasons)
if "resolved_plan_has_unresolved_facts" in reasons:
reasons.append("resolved_plan_has_unresolved_fact")
semantic_fact_requirements = (
list(authoritative_predicate.get("semantic_fact_requirements", []) or [])
if authoritative_predicate is not None
else []
)
requires_predicate = bool(program.checker_params.get("require_executable_predicate"))
predicate_status = str((authoritative_predicate or {}).get("status") or "blocked_uncompiled")
# An uncompiled predicate has no executable evidence path to hand to a
# fallback model. Advertising ``vlm_audit`` here made strict-zero-VLM
# plans look as if a blocked rule had a legitimate physical route.
# Keep it blocked and empty; only an executable predicate with an
# explicit semantic obligation may request the separately gated audit.
if requires_predicate and predicate_status != "executable":
fallback = ""
elif semantic_fact_requirements:
fallback = "vlm_audit"
elif requires_predicate:
fallback = ""
else:
fallback = str(program.checker_params.get("fallback_checker") or "")
if semantic_fact_requirements:
reasons.extend(
"semantic_fact_requires_vlm:" + str(item.get("fact") or "missing")
for item in semantic_fact_requirements
if isinstance(item, Mapping)
)
# A terminal metric may make a non-preservation check executable when
# its own typed dependency contract is complete. Preservation rules
# cannot discard unsupported appearance/integrity evidence merely
# because a matcher-only terminal node exists.
terminal_calls = [call for call in calls if call.tool == "contract_metric_binding"]
terminal_rule = str(terminal_calls[0].params.get("metric_binding") or "") if terminal_calls else ""
terminal_blockers = (
"metric_required_region_not_declared:",
"mask_refinement_has_no_detector_dependency:",
"instance_matching_requires_input_and_pred_masks",
"resolved_plan_has_unresolved_fact",
)
terminal_complete = bool(
terminal_calls
and terminal_rule not in PRESERVATION_RULE_TYPES
and not any(str(reason).startswith(terminal_blockers) for reason in reasons)
)
if semantic_fact_requirements and calls:
# Objective producers still run first and their evidence is passed
# into the semantic verifier. The check is deliberately not
# advertised as fully objective while a reviewed prose obligation
# lacks a deterministic fact producer.
status = "fallback_required"
elif terminal_complete or (program.executable and not reasons and calls):
status = "executable"
elif program.checker_params.get("require_executable_predicate"):
predicate_status = str((authoritative_predicate or {}).get("status") or "blocked_uncompiled")
status = (
predicate_status
if predicate_status.startswith("blocked_") or predicate_status == "manual_review_required"
else "blocked_uncompiled"
)
else:
status = "fallback_required"
check_plans.append(
CheckToolPlan(
check_id=spec.check_id,
checker=spec.checker,
tool_call_ids=tuple(dict.fromkeys(call_ids)),
fallback=fallback,
status=status,
reasons=tuple(dict.fromkeys(reasons)),
declared_tool_families=families,
unrecognized_declared_tools=unknown,
evidence_program=program.to_dict(),
)
)
calls = sorted(physical.values(), key=lambda item: (item.tool, item.image_role, item.call_id))
return {
"schema_version": TOOL_PLAN_SCHEMA_VERSION,
"case_key": case_key,
"case_id": contract.case_id,
"check_plans": [item.to_dict() for item in check_plans],
"compiled_checks": compiled_checks,
"tool_calls": [item.to_dict() for item in calls],
"summary": {
"atomic_checks": len(check_plans),
"executable_checks": sum(item.status == "executable" for item in check_plans),
"fallback_required_checks": sum(item.status != "executable" for item in check_plans),
"manual_review_required_checks": sum(item.status == "manual_review_required" for item in check_plans),
"blocked_uncompiled_checks": sum(item.status.startswith("blocked_") for item in check_plans),
"physical_tool_calls": len(calls),
"detector_calls": sum(item.tool == "open_vocabulary_detector" for item in calls),
"max_detector_queries_per_call": max((len(item.queries) for item in calls if item.tool == "open_vocabulary_detector"), default=0),
},
}
|