File size: 44,357 Bytes
5e5d6c5 | 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 | from __future__ import annotations
import hashlib
import json
from collections.abc import Iterator, Mapping, Sequence
from copy import deepcopy
from dataclasses import dataclass, replace
from typing import overload
import pytest
from ctx.engine.benefit import BenefitSelectionResult, NetBenefitPolicy
from ctx.engine.content import MaterialDescriptor, MaterialIdentity
from ctx.engine.installation import InstallPlanDescriptor, InstallPlanningBundle
from ctx.engine.planner import CapabilityCandidate, WorkObservation
from ctx.engine.planning_v3 import AuthenticatedNetBenefitPlanner
from ctx.engine.replay import PlanningContext, StructuredSurrogate
from ctx.runtime.authenticated_benefit import capability_presentation_digest
from ctx.runtime.benefit_closure import (
EligibleCatalogClaim,
QueryCapabilityEligibility,
ReviewedBenefitAuthorities,
eligible_catalog_claim_digest,
load_reviewed_benefit_profiles_bytes,
)
from ctx.runtime.eligible_catalog import (
EligibleCatalogLayer,
EligibleCatalogError,
PreparedEligibleCatalogQuery,
load_eligible_catalog_layer_bytes,
open_reviewed_query_catalog,
)
from ctx.runtime.planning_v3 import (
AuthenticatedReplayDecisionPlannerV3,
AuthorityBoundInstallPlanningBundle,
)
def _digest(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def _canonical_bytes(value: object) -> bytes:
return json.dumps(
value,
ensure_ascii=True,
allow_nan=False,
separators=(",", ":"),
sort_keys=True,
).encode("utf-8")
CALIBRATION_DIGEST = _digest("eligible-catalog-calibration")
POLICY = NetBenefitPolicy(
calibration_digest=CALIBRATION_DIGEST,
minimum_relevance_ppm=1,
context_token_cost_u=1,
)
def _aggregate_binding(field_name: str, value: str) -> str:
return hashlib.sha256(
_canonical_bytes(
{
"field": field_name,
"schema": "ctx.reviewed-authority-bindings-v1",
"values": [value],
}
)
).hexdigest()
def _catalog_manifest(
*,
actionability: str = "manual",
material_snapshot_digest: str | None = None,
installation_snapshot_digest: str | None = None,
material_descriptor: MaterialDescriptor | None = None,
install_bundle: InstallPlanningBundle | None = None,
) -> dict[str, object]:
return {
"authority": {
"authority_digest": _digest("ctx-release-authority"),
"authority_id": "ctx-release",
"authority_kind": "ctx-release",
"catalog_layer_kind": "ctx",
"sequence": 1,
},
"bindings": {
"candidate_projection_version": "ctx.benefit-eligible-entry-v1",
"catalog_namespace_digest": _digest("ctx-catalog-namespace"),
"catalog_provenance_digest": _digest("ctx-catalog-provenance"),
"installation_snapshot_digest": installation_snapshot_digest,
"material_snapshot_digest": material_snapshot_digest,
},
"entries": [
{
"actionability": actionability,
"capability_id": "skill:ctx-python-testing",
"equivalence_key": None,
"install_bundle": (
None
if install_bundle is None
else {
"descriptor": install_bundle.descriptor.to_dict(),
"result_material": install_bundle.result_material.to_dict(),
}
),
"kind": "skill",
"material_descriptor": (
None if material_descriptor is None else material_descriptor.to_dict()
),
"name": "ctx-python-testing",
}
],
"schema": "ctx.benefit-eligible-catalog-v1",
}
def _reviewed_profiles_body(layer) -> bytes: # type: ignore[no-untyped-def]
entry = layer.entries[0]
manifest = {
"authority": {
"authority_digest": layer.authority_digest,
"authority_id": layer.authority_id,
"authority_kind": layer.authority_kind,
"catalog_layer_kind": layer.catalog_layer_kind,
"sequence": layer.sequence,
},
"bindings": {
"calibration_digest": CALIBRATION_DIGEST,
"candidate_projection_version": layer.candidate_projection_version,
"catalog_artifact_sha256": layer.catalog_artifact_sha256,
"catalog_namespace_digest": layer.catalog_namespace_digest,
"catalog_provenance_digest": layer.catalog_provenance_digest,
"catalog_retrieval_snapshot_digest": layer.catalog_retrieval_snapshot_digest,
"installation_snapshot_digest": layer.installation_snapshot_digest,
"material_snapshot_digest": layer.material_snapshot_digest,
"policy_digest": POLICY.policy_digest,
},
"profiles": [
{
"actionability": entry.actionability,
"capability_id": entry.capability_id,
"catalog_entry_claim_digest": entry.catalog_entry_claim_digest,
"complements": [],
"conflicts": [],
"costs": {
"approval_prompts": 0,
"child_agent_units": 0,
"context_tokens": 120,
"credential_burden_units": 0,
"permission_burden_units": 0,
"process_units": 0,
"runtime_millis": 0,
"tool_schema_tokens": 0,
},
"coverage_keys": ["python-testing"],
"expected_task_benefit_ppm": 500_000,
"kind": entry.kind,
"match_policy": {
"allowed_equivalence_keys": [],
"allowed_reason_codes": ["reviewed-match"],
"allowed_signals": ["python", "testing"],
"minimum_matching_signals": 2,
"minimum_non_language_matching_signals": 1,
"required_any_signals": ["testing"],
},
"maximum_relevance_ppm": 700_000,
"name": entry.name,
"profile_id": "profile-ctx-python-testing",
"review_basis_digest": _digest("review-basis:ctx-python-testing"),
"security_approved": True,
"source_trusted": True,
"trust_ppm": 900_000,
}
],
"schema": "ctx.reviewed-benefit-profiles-v2",
}
return _canonical_bytes(manifest)
@dataclass
class _HostPolicy:
host_policy_snapshot_digest: str = _digest("eligible-catalog-host-policy")
def eligibility_for(
self,
presentation: CapabilityCandidate,
claim: EligibleCatalogClaim,
) -> QueryCapabilityEligibility:
return QueryCapabilityEligibility(
presentation_digest=capability_presentation_digest(presentation),
catalog_entry_claim_digest=claim.catalog_entry_claim_digest,
catalog_claim_digest=eligible_catalog_claim_digest(claim),
available=True,
permissions_allowed=True,
credentials_available=True,
)
@dataclass
class _AuditStore:
results: dict[str, BenefitSelectionResult]
def store(self, result: BenefitSelectionResult) -> str:
self.results[result.result_digest] = result
return result.result_digest
def _open_catalog(): # type: ignore[no-untyped-def]
catalog_body = _canonical_bytes(_catalog_manifest())
layer = load_eligible_catalog_layer_bytes(
catalog_body,
hashlib.sha256(catalog_body).hexdigest(),
)
profiles_body = _reviewed_profiles_body(layer)
profiles = ReviewedBenefitAuthorities.create(
(
load_reviewed_benefit_profiles_bytes(
profiles_body,
hashlib.sha256(profiles_body).hexdigest(),
),
)
)
return layer, open_reviewed_query_catalog(
layers=(layer,),
profiles=profiles,
policy=POLICY,
)
def test_exact_catalog_profile_join_prepares_one_sealed_query() -> None:
layer, catalog = _open_catalog()
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
candidates = prepared.closure.source.retrieve(observation)
assert tuple(candidate.capability_id for candidate in candidates) == (
"skill:ctx-python-testing",
)
assert candidates[0].matching_signals == ("python", "testing")
assert candidates[0].reason_codes == ("reviewed-match",)
assert candidates[0].source_digest == layer.entries[0].source_digest
assert prepared.material_authority is None
assert prepared.install_authority is None
assert catalog.vocabulary.signals == ("testing",)
prepared.close()
catalog.close()
with pytest.raises(EligibleCatalogError, match="closed"):
catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
def test_catalog_bytes_are_closed_canonical_and_exact_hash_bound() -> None:
body = _canonical_bytes(_catalog_manifest())
with pytest.raises(EligibleCatalogError, match="SHA-256"):
load_eligible_catalog_layer_bytes(body, _digest("wrong"))
manifest = _catalog_manifest()
manifest["description"] = "graph prose is not catalog authority"
mutated = _canonical_bytes(manifest)
with pytest.raises(EligibleCatalogError, match="declared fields"):
load_eligible_catalog_layer_bytes(mutated, hashlib.sha256(mutated).hexdigest())
noncanonical = json.dumps(_catalog_manifest()).encode("utf-8")
with pytest.raises(EligibleCatalogError, match="canonical"):
load_eligible_catalog_layer_bytes(
noncanonical,
hashlib.sha256(noncanonical).hexdigest(),
)
def _open_actionable_catalog(actionability: str): # type: ignore[no-untyped-def]
capability_id = "skill:ctx-python-testing"
kind = "skill"
material_identity = MaterialIdentity.create(
capability_id=capability_id,
kind=kind,
content_sha256=_digest(f"{actionability}-content"),
content_bytes=240,
)
raw_material_snapshot = _digest("raw-material-snapshot")
raw_installation_snapshot = _digest("raw-installation-snapshot")
material_descriptor = None
install_bundle = None
if actionability == "load":
material_descriptor = MaterialDescriptor.create(
capability_id=capability_id,
kind=kind,
actionability="load",
content_sha256=material_identity.content_sha256,
content_bytes=material_identity.content_bytes,
estimated_tokens=60,
provenance_digest=raw_material_snapshot,
material_identity_digest=material_identity.identity_digest,
)
else:
descriptor = InstallPlanDescriptor.create(
capability_id=capability_id,
kind=kind,
installer_id="ctx-skill-cas",
plan_digest=_digest("install-plan"),
provenance_digest=raw_installation_snapshot,
result_material_identity_digest=material_identity.identity_digest,
)
install_bundle = InstallPlanningBundle(
descriptor=descriptor,
result_material=material_identity,
)
body = _canonical_bytes(
_catalog_manifest(
actionability=actionability,
material_snapshot_digest=(raw_material_snapshot if actionability == "load" else None),
installation_snapshot_digest=(
raw_installation_snapshot if actionability == "install" else None
),
material_descriptor=material_descriptor,
install_bundle=install_bundle,
)
)
layer = load_eligible_catalog_layer_bytes(body, hashlib.sha256(body).hexdigest())
profiles_body = _reviewed_profiles_body(layer)
profile_manifest = json.loads(profiles_body)
profile_manifest["profiles"][0]["actionability"] = actionability
profile_manifest["profiles"][0]["catalog_entry_claim_digest"] = layer.entries[
0
].catalog_entry_claim_digest
profiles_body = _canonical_bytes(profile_manifest)
profiles = ReviewedBenefitAuthorities.create(
(
load_reviewed_benefit_profiles_bytes(
profiles_body,
hashlib.sha256(profiles_body).hexdigest(),
),
)
)
return layer, open_reviewed_query_catalog(
layers=(layer,),
profiles=profiles,
policy=POLICY,
)
def _actionability_variant_manifest() -> dict[str, object]:
capability_id = "skill:ctx-python-testing"
kind = "skill"
raw_material_snapshot = _digest("variant-material-snapshot")
raw_installation_snapshot = _digest("variant-installation-snapshot")
material_identity = MaterialIdentity.create(
capability_id=capability_id,
kind=kind,
content_sha256=_digest("variant-content"),
content_bytes=240,
)
material_descriptor = MaterialDescriptor.create(
capability_id=capability_id,
kind=kind,
actionability="load",
content_sha256=material_identity.content_sha256,
content_bytes=material_identity.content_bytes,
estimated_tokens=60,
provenance_digest=raw_material_snapshot,
material_identity_digest=material_identity.identity_digest,
)
install_bundle = InstallPlanningBundle(
descriptor=InstallPlanDescriptor.create(
capability_id=capability_id,
kind=kind,
installer_id="ctx-skill-cas",
plan_digest=_digest("variant-install-plan"),
provenance_digest=raw_installation_snapshot,
result_material_identity_digest=material_identity.identity_digest,
),
result_material=material_identity,
)
manifest = _catalog_manifest()
manifest["bindings"] = {
"candidate_projection_version": "ctx.benefit-eligible-entry-v1",
"catalog_namespace_digest": _digest("ctx-catalog-namespace"),
"catalog_provenance_digest": _digest("ctx-catalog-provenance"),
"installation_snapshot_digest": raw_installation_snapshot,
"material_snapshot_digest": raw_material_snapshot,
}
manifest["entries"] = [
{
"actionability": "install",
"capability_id": capability_id,
"equivalence_key": None,
"install_bundle": {
"descriptor": install_bundle.descriptor.to_dict(),
"result_material": install_bundle.result_material.to_dict(),
},
"kind": kind,
"material_descriptor": None,
"name": "ctx-python-testing",
},
{
"actionability": "load",
"capability_id": capability_id,
"equivalence_key": None,
"install_bundle": None,
"kind": kind,
"material_descriptor": material_descriptor.to_dict(),
"name": "ctx-python-testing",
},
]
return manifest
def _open_actionability_variant_catalog(): # type: ignore[no-untyped-def]
body = _canonical_bytes(_actionability_variant_manifest())
layer = load_eligible_catalog_layer_bytes(body, hashlib.sha256(body).hexdigest())
profile_manifest = json.loads(_reviewed_profiles_body(layer))
prototype = profile_manifest["profiles"][0]
profile_manifest["profiles"] = []
for entry in layer.entries:
profile = deepcopy(prototype)
profile["actionability"] = entry.actionability
profile["catalog_entry_claim_digest"] = entry.catalog_entry_claim_digest
profile["profile_id"] = f"profile-{entry.name}-{entry.actionability}"
profile["review_basis_digest"] = _digest(
f"review:{entry.capability_id}:{entry.actionability}"
)
profile_manifest["profiles"].append(profile)
profiles_body = _canonical_bytes(profile_manifest)
profiles = ReviewedBenefitAuthorities.create(
(
load_reviewed_benefit_profiles_bytes(
profiles_body,
hashlib.sha256(profiles_body).hexdigest(),
),
)
)
return layer, open_reviewed_query_catalog(
layers=(layer,),
profiles=profiles,
policy=POLICY,
)
@dataclass
class _ActionabilityHostPolicy:
selected_actionability: str
host_policy_snapshot_digest: str = _digest("variant-host-policy")
def eligibility_for(
self,
presentation: CapabilityCandidate,
claim: EligibleCatalogClaim,
) -> QueryCapabilityEligibility:
return QueryCapabilityEligibility(
presentation_digest=capability_presentation_digest(presentation),
catalog_entry_claim_digest=claim.catalog_entry_claim_digest,
catalog_claim_digest=eligible_catalog_claim_digest(claim),
available=presentation.actionability == self.selected_actionability,
permissions_allowed=True,
credentials_available=True,
)
def test_catalog_accepts_distinct_install_and_load_variants_for_one_capability() -> None:
layer, catalog = _open_actionability_variant_catalog()
assert tuple((entry.capability_id, entry.actionability) for entry in layer.entries) == (
("skill:ctx-python-testing", "install"),
("skill:ctx-python-testing", "load"),
)
catalog.close()
def test_catalog_layer_rejects_duplicate_capability_actionability_pair() -> None:
manifest = _actionability_variant_manifest()
entries = manifest["entries"]
assert isinstance(entries, list)
entries.insert(1, deepcopy(entries[0]))
body = _canonical_bytes(manifest)
with pytest.raises(EligibleCatalogError, match="capability actionability"):
load_eligible_catalog_layer_bytes(body, hashlib.sha256(body).hexdigest())
def test_catalog_layers_reject_duplicate_capability_actionability_pair() -> None:
ctx_body = _canonical_bytes(_catalog_manifest())
ctx_layer = load_eligible_catalog_layer_bytes(
ctx_body,
hashlib.sha256(ctx_body).hexdigest(),
)
user_manifest = _catalog_manifest()
user_manifest["authority"] = {
"authority_digest": _digest("user-authority"),
"authority_id": "user-local",
"authority_kind": "user",
"catalog_layer_kind": "user",
"sequence": 1,
}
user_manifest["bindings"] = {
"candidate_projection_version": "ctx.benefit-eligible-entry-v1",
"catalog_namespace_digest": _digest("user-catalog-namespace"),
"catalog_provenance_digest": _digest("user-catalog-provenance"),
"installation_snapshot_digest": None,
"material_snapshot_digest": None,
}
user_body = _canonical_bytes(user_manifest)
user_layer = load_eligible_catalog_layer_bytes(
user_body,
hashlib.sha256(user_body).hexdigest(),
)
profiles = ReviewedBenefitAuthorities.create(
(
load_reviewed_benefit_profiles_bytes(
_reviewed_profiles_body(ctx_layer),
hashlib.sha256(_reviewed_profiles_body(ctx_layer)).hexdigest(),
),
load_reviewed_benefit_profiles_bytes(
_reviewed_profiles_body(user_layer),
hashlib.sha256(_reviewed_profiles_body(user_layer)).hexdigest(),
),
)
)
with pytest.raises(EligibleCatalogError, match="capability actionability collision"):
open_reviewed_query_catalog(
layers=(ctx_layer, user_layer),
profiles=profiles,
policy=POLICY,
)
@pytest.mark.parametrize("selected_actionability", ["install", "load"])
def test_host_policy_selects_one_variant_for_the_single_global_planner(
selected_actionability: str,
) -> None:
_layer, catalog = _open_actionability_variant_catalog()
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(
observation=observation,
host_policy=_ActionabilityHostPolicy(selected_actionability),
)
candidates = prepared.closure.source.retrieve(observation)
assert tuple(
(candidate.capability_id, candidate.actionability) for candidate in candidates
) == (("skill:ctx-python-testing", selected_actionability),)
adapter = AuthenticatedReplayDecisionPlannerV3(
planner=AuthenticatedNetBenefitPlanner(
policy=POLICY,
audit_store=_AuditStore(results={}),
),
source=prepared.closure.source,
benefit_facts_port=prepared.closure.benefit_facts,
material_port=prepared.material_authority,
install_bundle_port=prepared.install_authority,
planner_version="eligible-catalog-v1",
catalog_namespace_digest=prepared.closure.catalog_namespace_digest,
)
decision = adapter(
StructuredSurrogate.create(
schema_id="ctx.observation.current-work",
schema_version=1,
value={
"active_capability_ids": [],
"baseline_capability_ids": [],
"languages": ["python"],
"rejected_capability_ids": [],
"requested_limit": 5,
"signals": ["testing"],
},
),
None,
PlanningContext(
planner_version="eligible-catalog-v1",
catalog_snapshot_digest=adapter.catalog_snapshot_digest,
),
)
selections = decision.value["capabilities"]
assert isinstance(selections, tuple)
assert len(selections) == 1
selection = selections[0]
assert isinstance(selection, Mapping)
assert selection["actionability"] == selected_actionability
def test_host_policy_exposing_both_variants_fails_before_planning() -> None:
_layer, catalog = _open_actionability_variant_catalog()
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
with pytest.raises(EligibleCatalogError, match="multiple actionability variants"):
catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
def test_load_authority_is_frozen_from_the_same_catalog_bytes() -> None:
_layer, catalog = _open_actionable_catalog("load")
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
candidate = prepared.closure.source.retrieve(observation)[0]
assert prepared.material_authority is not None
bundle = prepared.material_authority.load_bundle(candidate)
assert bundle is not None
assert bundle.presentation == candidate
assert bundle.catalog_snapshot_digest == prepared.closure.closure_snapshot_digest
assert bundle.material_snapshot_digest == prepared.closure.material_snapshot_digest
assert bundle.descriptor.material_identity_digest is not None
assert prepared.install_authority is None
substituted = replace(candidate, normalized_score_ppm=candidate.normalized_score_ppm - 1)
assert prepared.material_authority.load_bundle(substituted) is None
def test_install_authority_is_frozen_from_the_same_catalog_bytes() -> None:
_layer, catalog = _open_actionable_catalog("install")
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
candidate = prepared.closure.source.retrieve(observation)[0]
assert prepared.install_authority is not None
bundle = prepared.install_authority.describe_bundle(candidate.capability_id, candidate.kind)
assert bundle is not None
assert bundle.descriptor.descriptor_digest == candidate.install_descriptor_digest
assert bundle.descriptor.plan_digest == candidate.install_plan_digest
assert bundle.descriptor.provenance_digest == _digest("raw-installation-snapshot")
assert bundle.installation_snapshot_digest == prepared.closure.installation_snapshot_digest
assert prepared.material_authority is None
@pytest.mark.parametrize("actionability", ["load", "install"])
def test_actionable_catalog_composes_into_schema_v3_without_silent_drop(
actionability: str,
) -> None:
_layer, catalog = _open_actionable_catalog(actionability)
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
adapter = AuthenticatedReplayDecisionPlannerV3(
planner=AuthenticatedNetBenefitPlanner(
policy=POLICY,
audit_store=_AuditStore(results={}),
),
source=prepared.closure.source,
benefit_facts_port=prepared.closure.benefit_facts,
material_port=prepared.material_authority,
install_bundle_port=prepared.install_authority,
planner_version="eligible-catalog-v1",
catalog_namespace_digest=prepared.closure.catalog_namespace_digest,
)
surrogate = StructuredSurrogate.create(
schema_id="ctx.observation.current-work",
schema_version=1,
value={
"active_capability_ids": [],
"baseline_capability_ids": [],
"languages": ["python"],
"rejected_capability_ids": [],
"requested_limit": 5,
"signals": ["testing"],
},
)
decision = adapter(
surrogate,
None,
PlanningContext(
planner_version="eligible-catalog-v1",
catalog_snapshot_digest=adapter.catalog_snapshot_digest,
),
)
selections = decision.value["capabilities"]
assert isinstance(selections, tuple)
assert len(selections) == 1
selection = selections[0]
assert isinstance(selection, Mapping)
assert selection["actionability"] == actionability
def _manual_entry(name: str) -> dict[str, object]:
return {
"actionability": "manual",
"capability_id": f"skill:{name}",
"equivalence_key": None,
"install_bundle": None,
"kind": "skill",
"material_descriptor": None,
"name": name,
}
def test_catalog_rejects_noncanonical_entry_order_instead_of_reordering_it() -> None:
manifest = _catalog_manifest()
manifest["entries"] = [_manual_entry("z-last"), _manual_entry("a-first")]
body = _canonical_bytes(manifest)
with pytest.raises(EligibleCatalogError, match="canonical capability order"):
load_eligible_catalog_layer_bytes(body, hashlib.sha256(body).hexdigest())
def test_catalog_and_reviewed_profiles_must_be_bijective() -> None:
body = _canonical_bytes(_catalog_manifest())
layer = load_eligible_catalog_layer_bytes(body, hashlib.sha256(body).hexdigest())
profile_manifest = json.loads(_reviewed_profiles_body(layer))
orphan = deepcopy(profile_manifest["profiles"][0])
orphan["capability_id"] = "skill:orphan"
orphan["name"] = "orphan"
orphan["profile_id"] = "profile-orphan"
orphan["catalog_entry_claim_digest"] = _digest("orphan-entry-claim")
orphan["review_basis_digest"] = _digest("orphan-review")
orphan["coverage_keys"] = ["orphan"]
profile_manifest["profiles"].append(orphan)
profiles_body = _canonical_bytes(profile_manifest)
profiles = ReviewedBenefitAuthorities.create(
(
load_reviewed_benefit_profiles_bytes(
profiles_body,
hashlib.sha256(profiles_body).hexdigest(),
),
)
)
with pytest.raises(EligibleCatalogError, match="one-to-one"):
open_reviewed_query_catalog(layers=(layer,), profiles=profiles, policy=POLICY)
def _open_large_catalog_with_target(
*,
noise_context_tokens: int,
noise_equivalence_key: str | None = None,
):
manifest = _catalog_manifest()
names = [f"noise-{index:03d}" for index in range(513)] + ["target"]
manifest["entries"] = [_manual_entry(name) for name in names]
if noise_equivalence_key is not None:
raw_entries = manifest["entries"]
assert isinstance(raw_entries, list)
for entry in raw_entries:
assert isinstance(entry, dict)
if entry["name"] != "target":
entry["equivalence_key"] = noise_equivalence_key
body = _canonical_bytes(manifest)
layer = load_eligible_catalog_layer_bytes(body, hashlib.sha256(body).hexdigest())
profile_manifest = json.loads(_reviewed_profiles_body(layer))
prototype = profile_manifest["profiles"][0]
records = []
for entry in layer.entries:
record = deepcopy(prototype)
record["capability_id"] = entry.capability_id
record["name"] = entry.name
record["profile_id"] = f"profile-{entry.name}"
record["catalog_entry_claim_digest"] = entry.catalog_entry_claim_digest
record["review_basis_digest"] = _digest(f"review:{entry.capability_id}")
record["coverage_keys"] = [entry.name]
record["costs"]["context_tokens"] = 120 if entry.name == "target" else noise_context_tokens
record["maximum_relevance_ppm"] = 500_000 if entry.name == "target" else 1_000_000
record["match_policy"]["allowed_equivalence_keys"] = (
[] if noise_equivalence_key is None else [noise_equivalence_key]
)
records.append(record)
profile_manifest["profiles"] = records
profiles_body = _canonical_bytes(profile_manifest)
profiles = ReviewedBenefitAuthorities.create(
(
load_reviewed_benefit_profiles_bytes(
profiles_body,
hashlib.sha256(profiles_body).hexdigest(),
),
)
)
return open_reviewed_query_catalog(
layers=(layer,),
profiles=profiles,
policy=POLICY,
)
def test_net_benefit_filter_runs_before_the_512_candidate_bound() -> None:
catalog = _open_large_catalog_with_target(noise_context_tokens=1_000_000)
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
assert tuple(
candidate.capability_id for candidate in prepared.closure.source.retrieve(observation)
) == ("skill:target",)
@dataclass
class _TargetOnlyHostPolicy(_HostPolicy):
def eligibility_for(
self,
presentation: CapabilityCandidate,
claim: EligibleCatalogClaim,
) -> QueryCapabilityEligibility:
return QueryCapabilityEligibility(
presentation_digest=capability_presentation_digest(presentation),
catalog_entry_claim_digest=claim.catalog_entry_claim_digest,
catalog_claim_digest=eligible_catalog_claim_digest(claim),
available=presentation.capability_id == "skill:target",
permissions_allowed=True,
credentials_available=True,
)
def test_host_feasibility_filter_runs_before_the_512_candidate_bound() -> None:
catalog = _open_large_catalog_with_target(noise_context_tokens=120)
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(
observation=observation,
host_policy=_TargetOnlyHostPolicy(),
)
assert tuple(
candidate.capability_id for candidate in prepared.closure.source.retrieve(observation)
) == ("skill:target",)
def test_equivalent_high_score_rows_cannot_poison_the_512_candidate_bound() -> None:
catalog = _open_large_catalog_with_target(
noise_context_tokens=120,
noise_equivalence_key="noise-equivalent",
)
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
candidates = prepared.closure.source.retrieve(observation)
assert "skill:target" in {candidate.capability_id for candidate in candidates}
assert len(candidates) <= 512
def test_distinct_feasible_frontier_over_512_fails_closed() -> None:
catalog = _open_large_catalog_with_target(noise_context_tokens=120)
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
with pytest.raises(EligibleCatalogError, match="exact bounded policy frontier"):
catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
def test_equivalence_dominance_preserves_inbound_conflict_alternatives() -> None:
manifest = _catalog_manifest()
names = ["a", "b", *(f"noise-{index:03d}" for index in range(511)), "peer"]
entries = [_manual_entry(name) for name in names]
for raw_entry in entries:
if raw_entry["name"] in {"a", "b"}:
raw_entry["equivalence_key"] = "tool-equivalent"
elif str(raw_entry["name"]).startswith("noise-"):
raw_entry["equivalence_key"] = "noise-equivalent"
manifest["entries"] = entries
body = _canonical_bytes(manifest)
layer = load_eligible_catalog_layer_bytes(body, hashlib.sha256(body).hexdigest())
profile_manifest = json.loads(_reviewed_profiles_body(layer))
prototype = profile_manifest["profiles"][0]
records = []
for catalog_entry in layer.entries:
record = deepcopy(prototype)
record["capability_id"] = catalog_entry.capability_id
record["name"] = catalog_entry.name
record["profile_id"] = f"profile-{catalog_entry.name}"
record["catalog_entry_claim_digest"] = catalog_entry.catalog_entry_claim_digest
record["review_basis_digest"] = _digest(f"review:{catalog_entry.capability_id}")
record["coverage_keys"] = [catalog_entry.name]
record["conflicts"] = ["skill:a"] if catalog_entry.name == "peer" else []
record["maximum_relevance_ppm"] = {
"a": 1_000_000,
"b": 900_000,
"peer": 950_000,
}.get(catalog_entry.name, 800_000)
record["match_policy"]["allowed_equivalence_keys"] = [
"noise-equivalent",
"tool-equivalent",
]
records.append(record)
profile_manifest["profiles"] = records
profiles_body = _canonical_bytes(profile_manifest)
profiles = ReviewedBenefitAuthorities.create(
(
load_reviewed_benefit_profiles_bytes(
profiles_body,
hashlib.sha256(profiles_body).hexdigest(),
),
)
)
catalog = open_reviewed_query_catalog(
layers=(layer,),
profiles=profiles,
policy=POLICY,
)
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
retained = {value.capability_id for value in prepared.closure.source.retrieve(observation)}
assert {"skill:a", "skill:b", "skill:peer"}.issubset(retained)
def test_prepared_query_cannot_be_constructed_by_callers() -> None:
_layer, catalog = _open_catalog()
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
with pytest.raises(TypeError, match="catalog factory"):
PreparedEligibleCatalogQuery(
closure=prepared.closure,
material_authority=None,
install_authority=None,
)
class _OverlongLayerSequence(Sequence[EligibleCatalogLayer]):
def __len__(self) -> int:
return 65
def __iter__(self) -> Iterator[EligibleCatalogLayer]:
raise AssertionError("layer input was read beyond its declared bound")
@overload
def __getitem__(self, index: int) -> EligibleCatalogLayer: ...
@overload
def __getitem__(self, index: slice) -> Sequence[EligibleCatalogLayer]: ...
def __getitem__(
self,
index: int | slice,
) -> EligibleCatalogLayer | Sequence[EligibleCatalogLayer]:
raise AssertionError(f"layer input index {index!r} was read before the length bound")
def test_catalog_layer_input_is_bounded_before_materialization() -> None:
_layer, catalog = _open_catalog()
with pytest.raises(EligibleCatalogError, match="bounded"):
open_reviewed_query_catalog(
layers=_OverlongLayerSequence(),
profiles=catalog._profiles,
policy=POLICY,
)
@pytest.mark.parametrize("actionability", ["load", "install"])
def test_actionable_authority_survives_multi_layer_aggregation(
actionability: str,
) -> None:
ctx_layer, single_catalog = _open_actionable_catalog(actionability)
ctx_profile = single_catalog._profiles.authorities[0]
user_manifest = _catalog_manifest()
user_manifest["authority"] = {
"authority_digest": _digest("user-authority"),
"authority_id": "user-local",
"authority_kind": "user",
"catalog_layer_kind": "user",
"sequence": 1,
}
user_manifest["bindings"] = {
"candidate_projection_version": "ctx.benefit-eligible-entry-v1",
"catalog_namespace_digest": _digest("user-catalog-namespace"),
"catalog_provenance_digest": _digest("user-catalog-provenance"),
"installation_snapshot_digest": None,
"material_snapshot_digest": None,
}
user_manifest["entries"] = [_manual_entry("user-helper")]
user_body = _canonical_bytes(user_manifest)
user_layer = load_eligible_catalog_layer_bytes(
user_body,
hashlib.sha256(user_body).hexdigest(),
)
user_profiles_body = _reviewed_profiles_body(user_layer)
user_profile = load_reviewed_benefit_profiles_bytes(
user_profiles_body,
hashlib.sha256(user_profiles_body).hexdigest(),
)
profiles = ReviewedBenefitAuthorities.create((ctx_profile, user_profile))
catalog = open_reviewed_query_catalog(
layers=(ctx_layer, user_layer),
profiles=profiles,
policy=POLICY,
)
observation = WorkObservation(
signals=("testing",),
languages=("python",),
requested_limit=5,
)
prepared = catalog.prepare_query(observation=observation, host_policy=_HostPolicy())
candidate = next(
value
for value in prepared.closure.source.retrieve(observation)
if value.capability_id == "skill:ctx-python-testing"
)
if actionability == "load":
assert prepared.material_authority is not None
load_bundle = prepared.material_authority.load_bundle(candidate)
assert load_bundle is not None
assert load_bundle.descriptor.provenance_digest == ctx_layer.material_snapshot_digest
assert load_bundle.authority_material_snapshot_digest == ctx_layer.material_snapshot_digest
assert load_bundle.material_snapshot_digest == profiles.material_snapshot_digest
assert (
load_bundle.material_snapshot_digest != load_bundle.authority_material_snapshot_digest
)
else:
assert prepared.install_authority is not None
install_bundle = prepared.install_authority.describe_bundle(
candidate.capability_id,
candidate.kind,
)
assert isinstance(install_bundle, AuthorityBoundInstallPlanningBundle)
assert install_bundle.descriptor.provenance_digest == ctx_layer.installation_snapshot_digest
assert install_bundle.authority_installation_snapshot_digest == (
ctx_layer.installation_snapshot_digest
)
assert install_bundle.installation_snapshot_digest == profiles.installation_snapshot_digest
assert install_bundle.installation_snapshot_digest != (
install_bundle.authority_installation_snapshot_digest
)
adapter = AuthenticatedReplayDecisionPlannerV3(
planner=AuthenticatedNetBenefitPlanner(
policy=POLICY,
audit_store=_AuditStore(results={}),
),
source=prepared.closure.source,
benefit_facts_port=prepared.closure.benefit_facts,
material_port=prepared.material_authority,
install_bundle_port=prepared.install_authority,
planner_version="eligible-catalog-v1",
catalog_namespace_digest=prepared.closure.catalog_namespace_digest,
)
decision = adapter(
StructuredSurrogate.create(
schema_id="ctx.observation.current-work",
schema_version=1,
value={
"active_capability_ids": [],
"baseline_capability_ids": [],
"languages": ["python"],
"rejected_capability_ids": [],
"requested_limit": 5,
"signals": ["testing"],
},
),
None,
PlanningContext(
planner_version="eligible-catalog-v1",
catalog_snapshot_digest=adapter.catalog_snapshot_digest,
),
)
raw_selections = decision.value["capabilities"]
assert isinstance(raw_selections, tuple)
selected: dict[str, str] = {}
for raw_selection in raw_selections:
assert isinstance(raw_selection, Mapping)
capability_id = raw_selection["capability_id"]
selected_actionability = raw_selection["actionability"]
assert isinstance(capability_id, str)
assert isinstance(selected_actionability, str)
selected[capability_id] = selected_actionability
assert selected["skill:ctx-python-testing"] == actionability
@pytest.mark.parametrize("actionability", ["load", "install"])
def test_actionable_entry_rejects_cross_capability_planning_authority(
actionability: str,
) -> None:
raw_snapshot = _digest(f"raw-{actionability}-snapshot")
aggregate = _aggregate_binding(f"{actionability}ation_snapshot_digest", raw_snapshot)
if actionability == "load":
aggregate = _aggregate_binding("material_snapshot_digest", raw_snapshot)
other_material = MaterialIdentity.create(
capability_id="skill:other",
kind="skill",
content_sha256=_digest("other-content"),
content_bytes=100,
)
material_descriptor = None
install_bundle = None
if actionability == "load":
material_descriptor = MaterialDescriptor.create(
capability_id="skill:other",
kind="skill",
actionability="load",
content_sha256=other_material.content_sha256,
content_bytes=other_material.content_bytes,
estimated_tokens=25,
provenance_digest=aggregate,
material_identity_digest=other_material.identity_digest,
)
else:
install_bundle = InstallPlanningBundle(
descriptor=InstallPlanDescriptor.create(
capability_id="skill:other",
kind="skill",
installer_id="ctx-skill-cas",
plan_digest=_digest("other-plan"),
provenance_digest=aggregate,
result_material_identity_digest=other_material.identity_digest,
),
result_material=other_material,
)
body = _canonical_bytes(
_catalog_manifest(
actionability=actionability,
material_snapshot_digest=raw_snapshot if actionability == "load" else None,
installation_snapshot_digest=(raw_snapshot if actionability == "install" else None),
material_descriptor=material_descriptor,
install_bundle=install_bundle,
)
)
with pytest.raises(EligibleCatalogError, match="planning authority"):
load_eligible_catalog_layer_bytes(body, hashlib.sha256(body).hexdigest())
|