contract.rs (526400B)
1 #![forbid(unsafe_code)] 2 3 mod admission_authority; 4 pub(crate) mod artifact_bundle; 5 mod comment_authority; 6 #[cfg(test)] 7 mod conformance_inventory_tests; 8 mod deletion_authority; 9 mod registry_v7; 10 pub(crate) use registry_v7::{ 11 validate_event_contract_registry_v7_inventory, write_event_contract_registry_v7_inventory, 12 }; 13 14 use crate::coverage::{CoveragePolicyFile, CoverageThresholds, read_coverage_policy}; 15 use admission_authority::validate_admission_operation_authority; 16 use artifact_bundle::{ 17 GeneratedArtifact, read_regular_file, validate_canonical_json_artifact, 18 validate_sha256_artifact, with_artifact_bundle_transaction, 19 }; 20 use comment_authority::{ 21 COMMENT_CASE_KINDS, COMMENT_CONFORMANCE_VECTOR_RELATIVE, COMMENT_OPERATION_EXPECTATIONS, 22 COMMENT_VECTOR_EXPECTATIONS, REQUIRED_COMMENT_PUBLIC_TYPES, 23 }; 24 use deletion_authority::{ 25 DELETION_ADMIT_INVALID_IDS, DELETION_ADMIT_VALID_IDS, DELETION_AUTHORED_INVALID_IDS, 26 DELETION_AUTHORED_VALID_IDS, DELETION_CASE_KINDS, DELETION_CONFORMANCE_VECTOR_RELATIVE, 27 DELETION_OPERATION_EXPECTATIONS, DELETION_PROJECT_INVALID_IDS, DELETION_PROJECT_VALID_IDS, 28 DELETION_SUPPRESSION_CONFORMANCE_VECTOR_RELATIVE, DELETION_SUPPRESSION_VALID_IDS, 29 REQUIRED_DELETION_PUBLIC_TYPES, 30 }; 31 use semver::Version; 32 use serde::{Deserialize, Serialize}; 33 use serde_json::Value; 34 use sha2::{Digest, Sha256}; 35 use std::collections::{BTreeMap, BTreeSet}; 36 use std::fs; 37 use std::path::{Path, PathBuf}; 38 use walkdir::WalkDir; 39 40 pub(crate) fn validate_artifact_contracts(workspace_root: &Path) -> Result<(), String> { 41 validate_event_contract_registry_v7_inventory(workspace_root)?; 42 validate_knowledge_contract_manifest(workspace_root) 43 } 44 45 const CONFORMANCE_ROOT_RELATIVE: &str = "contracts/conformance"; 46 const CONFORMANCE_SCHEMA_RELATIVE: &str = "contracts/conformance/schema/vector.schema.json"; 47 const KNOWLEDGE_MANIFEST_RELATIVE: &str = 48 "contracts/knowledge/knowledge_event_contract_manifest.v2.json"; 49 const KNOWLEDGE_MANIFEST_SHA256_RELATIVE: &str = 50 "contracts/knowledge/knowledge_event_contract_manifest.v2.sha256"; 51 const KNOWLEDGE_MANIFEST_WRITE_COMMAND: &str = "cargo xtask contract knowledge-manifest --write"; 52 const KNOWLEDGE_MANIFEST_AND_DECODE_RELATIVE: &str = 53 "contracts/conformance/vectors/knowledge/manifest_and_decode.v1.json"; 54 const KNOWLEDGE_PUBLIC_SURFACE_RELATIVE: &str = 55 "contracts/conformance/vectors/knowledge/public_surface.v1.json"; 56 const POST_CONFORMANCE_VECTOR_RELATIVE: &str = 57 "contracts/conformance/vectors/post/verified_profiles.v1.json"; 58 const FOOD_AVAILABILITY_CONFORMANCE_VECTOR_RELATIVE: &str = 59 "contracts/conformance/vectors/food_availability/profile.v1.json"; 60 const RELEASES_ROOT_RELATIVE: &str = "contracts/releases"; 61 const RELEASE_POLICY_RELATIVE: &str = "contracts/releases/publish_policy.toml"; 62 const SQLITE_RUNTIME_CONTRACT_RELATIVE: &str = "contracts/releases/sqlite_runtime.toml"; 63 const CHANGELOG_RELATIVE: &str = "CHANGELOG.md"; 64 const REPLICA_CONTRACT_RELATIVE: &str = "contracts/replica.toml"; 65 const REPLICA_CONTRACT_NAME: &str = "radroots_replica_contract"; 66 const REPLICA_TRANSFER_CONSTANT: &str = "RADROOTS_REPLICA_TRANSFER_VERSION"; 67 const REPLICA_TRANSFER_VERSION: u32 = 2; 68 const CONFORMANCE_VECTOR_MIRRORS: [(&str, &str); 19] = [ 69 ( 70 "contracts/conformance/vectors/blossom/bud11_claims.v1.json", 71 "crates/blossom/tests/fixtures/bud11_claims.v1.json", 72 ), 73 ( 74 "contracts/conformance/vectors/blossom/hash_path_and_descriptor.v1.json", 75 "crates/blossom/tests/fixtures/hash_path_and_descriptor.v1.json", 76 ), 77 ( 78 "contracts/conformance/vectors/blossom/bud11_nostr_adapter.v1.json", 79 "crates/nostr/tests/fixtures/bud11_nostr_adapter.v1.json", 80 ), 81 ( 82 "contracts/conformance/vectors/nip17/adapter.v1.json", 83 "crates/nostr/tests/fixtures/nip17_adapter.v1.json", 84 ), 85 ( 86 "contracts/conformance/vectors/calendar/nip52_baseline.v1.json", 87 "crates/event_codec/tests/fixtures/calendar_nip52_baseline.v1.json", 88 ), 89 ( 90 "contracts/conformance/vectors/calendar/radroots_profile.v1.json", 91 "crates/event_codec/tests/fixtures/calendar_radroots_profile.v1.json", 92 ), 93 ( 94 "contracts/conformance/vectors/comment/verified_profile.v1.json", 95 "crates/event_codec/tests/fixtures/comment_verified_profile.v1.json", 96 ), 97 ( 98 "contracts/conformance/vectors/deletion/verified_profile.v1.json", 99 "crates/event_codec/tests/fixtures/deletion_verified_profile.v1.json", 100 ), 101 ( 102 "contracts/conformance/vectors/deletion/suppression.v1.json", 103 "crates/event_codec/tests/fixtures/deletion_suppression.v1.json", 104 ), 105 ( 106 "contracts/conformance/vectors/event/verified_admission.v1.json", 107 "crates/event_codec/tests/fixtures/verified_admission.v1.json", 108 ), 109 ( 110 "contracts/conformance/vectors/event/authored_plan_wire.v1.json", 111 "crates/event_codec/tests/fixtures/authored_plan_wire.v1.json", 112 ), 113 ( 114 "contracts/conformance/vectors/events/operational_listing_tags_full.v1.json", 115 "crates/event_codec/tests/fixtures/operational_listing_tags_full.v1.json", 116 ), 117 ( 118 "contracts/conformance/vectors/food_availability/profile.v1.json", 119 "crates/event_codec/tests/fixtures/food_availability_profile.v1.json", 120 ), 121 ( 122 "contracts/conformance/vectors/operational_listing/build_draft.v1.json", 123 "crates/event_codec/tests/fixtures/operational_listing_build_draft.v1.json", 124 ), 125 ( 126 "contracts/conformance/vectors/operational_listing/build_tags.v1.json", 127 "crates/event_codec/tests/fixtures/operational_listing_build_tags.v1.json", 128 ), 129 ( 130 "contracts/conformance/vectors/operational_listing/parse_event.v1.json", 131 "crates/event_codec/tests/fixtures/operational_listing_parse_event.v1.json", 132 ), 133 ( 134 "contracts/conformance/vectors/profile/metadata.v1.json", 135 "crates/event_codec/tests/fixtures/profile_metadata.v1.json", 136 ), 137 ( 138 "contracts/conformance/vectors/profile/verified_event.v1.json", 139 "crates/event_codec/tests/fixtures/profile_verified_event.v1.json", 140 ), 141 ( 142 "contracts/conformance/vectors/post/verified_profiles.v1.json", 143 "crates/event_codec/tests/fixtures/post_verified_profiles.v1.json", 144 ), 145 ]; 146 const KNOWLEDGE_MVP_SUPPORT_CONTRACT_IDS: [&str; 8] = [ 147 "radroots.wiki.article.v1", 148 "radroots.wiki.redirect.v1", 149 "radroots.wiki.merge_request.v1", 150 "radroots.knowledge.source.v1", 151 "radroots.knowledge.claim.v1", 152 "radroots.knowledge.relation.v1", 153 "radroots.knowledge.review.v1", 154 "radroots.knowledge.field_report.v1", 155 ]; 156 const KNOWLEDGE_BETA_CONTRACT_IDS: [&str; 3] = [ 157 "radroots.knowledge.evidence_bounty.v1", 158 "radroots.knowledge.change_proposal.v1", 159 "radroots.knowledge.contribution_attestation.v1", 160 ]; 161 const EVENT_BOUNDARY_MATRIX_RELATIVE: &str = "contracts/event_boundary_matrix.md"; 162 const COVERAGE_REQUIRED_THRESHOLD: f64 = 90.0; 163 const COVERAGE_REQUIRED_THRESHOLD_LABEL: &str = "90/90/90/90"; 164 const COVERAGE_REPORT_EPSILON: f64 = 0.000_001; 165 const DTO_TOOLING_DEPENDENCIES: [&str; 4] = [ 166 "dto_bindgen", 167 "dto_bindgen_backend_ts", 168 "dto_bindgen_core", 169 "dto_bindgen_macros", 170 ]; 171 const RETIRED_OPERATION_EVENT_NAMES: [&str; 15] = [ 172 "WireEventParts", 173 "RadrootsFrozenEventDraft", 174 "RadrootsNostrEvent", 175 "RadrootsNostrEventRef", 176 "RadrootsNostrEventPtr", 177 "RadrootsCalendarDateEvent", 178 "RadrootsCalendarTimeEvent", 179 "RadrootsCalendarDateValue", 180 "RadrootsInboundCalendarDateEvent", 181 "RadrootsInboundCalendarTimeEvent", 182 "RadrootsCalendar", 183 "RadrootsCalendarEventRsvp", 184 "RadrootsCalendarRsvp", 185 "RadrootsComment", 186 "RadrootsNip10RelayHint", 187 ]; 188 const REQUIRED_CALENDAR_PUBLIC_TYPES: [&str; 34] = [ 189 "Nip01EventWireParts", 190 "BlobUrl", 191 "AuthoredImage", 192 "AuthoredImageError", 193 "IanaTimeZoneId", 194 "CalendarUri", 195 "CalendarRequest", 196 "CalendarParticipant", 197 "CalendarEventError", 198 "CalendarDate", 199 "AuthoredCalendarDateEvent", 200 "AuthoredCalendarTimeEvent", 201 "ParsedNip52CalendarCommon", 202 "ParsedNip52CalendarCommonParts", 203 "ParsedNip52CalendarDateEvent", 204 "ObservedUtcDay", 205 "ParsedNip52CalendarTimeEvent", 206 "CalendarAdmissionError", 207 "AdmittedCalendarDateEvent", 208 "AdmittedCalendarTimeEvent", 209 "CalendarUid", 210 "CalendarEventReference", 211 "CalendarEventRevisionReference", 212 "CalendarEventAuthorReference", 213 "AuthoredCalendar", 214 "ParsedNip52CalendarParts", 215 "ParsedNip52Calendar", 216 "AdmittedCalendar", 217 "CalendarEventRsvpStatus", 218 "CalendarEventFreeBusy", 219 "AuthoredCalendarEventRsvp", 220 "ParsedNip52CalendarEventRsvpParts", 221 "ParsedNip52CalendarEventRsvp", 222 "AdmittedCalendarEventRsvp", 223 ]; 224 const REQUIRED_POST_PUBLIC_TYPES: [&str; 34] = [ 225 "ApprovedBlobUrl", 226 "ByteVerifiedDescriptor", 227 "Nip01EventWireParts", 228 "EventEnvelope", 229 "RadrootsSignatureVerifiedEvent", 230 "AuthoredImage", 231 "Post", 232 "AuthoredPostError", 233 "PostImageDimensions", 234 "AuthoredPostImage", 235 "AuthoredUpdate", 236 "AuthoredPhotoUpdate", 237 "AuthoredAsk", 238 "Nip10ReplyError", 239 "NostrRelayHint", 240 "Nip10ReplyReference", 241 "AuthoredNip10Reply", 242 "RadrootsPostDiagnostic", 243 "RadrootsPostClassification", 244 "RadrootsInboundPostImeta", 245 "RadrootsInboundPostProjection", 246 "RadrootsPostProjectionError", 247 "RadrootsAdmittedRootPostEvent", 248 "RadrootsThreadExcludedPostCandidate", 249 "RadrootsPostAdmissionOutcome", 250 "RadrootsPostAdmissionError", 251 "RadrootsNip10ReplyStyle", 252 "RadrootsNip10ReplyDiagnostic", 253 "RadrootsInboundNip10EventReference", 254 "RadrootsInboundNip10Participant", 255 "RadrootsInboundNip10ReplyProjection", 256 "RadrootsNip10ReplyProjectionError", 257 "RadrootsAdmittedNip10ReplyEvent", 258 "RadrootsNip10ReplyAdmissionError", 259 ]; 260 const REQUIRED_FOOD_AVAILABILITY_PUBLIC_TYPES: [&str; 31] = [ 261 "ByteVerifiedDescriptor", 262 "Nip01EventWireParts", 263 "EventEnvelope", 264 "RadrootsSignatureVerifiedEvent", 265 "ClassifiedListingPartition", 266 "AuthoredImage", 267 "FoodAvailabilityError", 268 "FoodContent", 269 "FoodIdentifier", 270 "FoodText", 271 "FoodPublishedAt", 272 "FoodCurrency", 273 "FoodUnit", 274 "FoodPrice", 275 "FoodQuantity", 276 "FoodAvailabilityStatus", 277 "FoodImageDimensions", 278 "FoodAvailabilityImage", 279 "FoodAvailabilityDetailsParts", 280 "FoodAvailabilityDetails", 281 "RadrootsFoodAvailabilityEncodeError", 282 "RadrootsFoodAvailabilityImageDiagnostic", 283 "RadrootsInboundFoodAvailabilityImage", 284 "RadrootsInboundFoodAvailabilityProjection", 285 "RadrootsFoodAvailabilityProjectionOutcome", 286 "RadrootsFoodAvailabilityProjectionError", 287 "RadrootsAdmittedFoodAvailabilityEvent", 288 "RadrootsExcludedClassifiedListingCandidate", 289 "RadrootsFoodAvailabilityAdmissionOutcome", 290 "RadrootsFoodAvailabilityAdmissionError", 291 "RadrootsFoodAvailabilityRevisionError", 292 ]; 293 const CALENDAR_OPERATION_EXPECTATIONS: [CalendarOperationExpectation; 12] = [ 294 CalendarOperationExpectation { 295 key: "social_calendar_date_event_build_authored_draft", 296 id: "social.calendar_date_event.build_authored_draft", 297 inputs: &["AuthoredCalendarDateEvent"], 298 outputs: &["Nip01EventWireParts"], 299 error_class: "encode_error", 300 rust_modules: &[ 301 "crates/event/src/calendar.rs", 302 "crates/event/src/media.rs", 303 "crates/event_codec/src/calendar/encode.rs", 304 ], 305 rust_types: &[ 306 "radroots_event::calendar::AuthoredCalendarDateEvent", 307 "radroots_event::calendar::CalendarDate", 308 "radroots_event::calendar::CalendarEventError", 309 "radroots_event::media::AuthoredImage", 310 "radroots_event::wire::Nip01EventWireParts", 311 "radroots_event_codec::error::EventEncodeError", 312 ], 313 vector: "contracts/conformance/vectors/calendar/radroots_profile.v1.json", 314 }, 315 CalendarOperationExpectation { 316 key: "social_calendar_date_event_parse_nip52", 317 id: "social.calendar_date_event.parse_nip52", 318 inputs: &["u32", "NostrTags", "String"], 319 outputs: &["ParsedNip52CalendarDateEvent"], 320 error_class: "parse_error", 321 rust_modules: &[ 322 "crates/event/src/calendar.rs", 323 "crates/event_codec/src/calendar/decode.rs", 324 ], 325 rust_types: &[ 326 "radroots_event::calendar::CalendarDate", 327 "radroots_event::calendar::CalendarRequest", 328 "radroots_event::calendar::CalendarUri", 329 "radroots_event::calendar::ParsedNip52CalendarCommon", 330 "radroots_event::calendar::ParsedNip52CalendarCommonParts", 331 "radroots_event::calendar::ParsedNip52CalendarDateEvent", 332 "radroots_event_codec::error::EventParseError", 333 ], 334 vector: "contracts/conformance/vectors/calendar/nip52_baseline.v1.json", 335 }, 336 CalendarOperationExpectation { 337 key: "social_calendar_date_event_admit_radroots_profile", 338 id: "social.calendar_date_event.admit_radroots_profile", 339 inputs: &["ParsedNip52CalendarDateEvent"], 340 outputs: &["AdmittedCalendarDateEvent"], 341 error_class: "admission_error", 342 rust_modules: &[ 343 "crates/event/src/calendar.rs", 344 "crates/event_codec/src/calendar/decode.rs", 345 ], 346 rust_types: &[ 347 "radroots_event::calendar::AdmittedCalendarDateEvent", 348 "radroots_event::calendar::CalendarAdmissionError", 349 "radroots_event::calendar::ParsedNip52CalendarDateEvent", 350 ], 351 vector: "contracts/conformance/vectors/calendar/radroots_profile.v1.json", 352 }, 353 CalendarOperationExpectation { 354 key: "social_calendar_time_event_build_authored_draft", 355 id: "social.calendar_time_event.build_authored_draft", 356 inputs: &["AuthoredCalendarTimeEvent"], 357 outputs: &["Nip01EventWireParts"], 358 error_class: "encode_error", 359 rust_modules: &[ 360 "crates/event/src/calendar.rs", 361 "crates/event/src/media.rs", 362 "crates/event_codec/src/calendar/encode.rs", 363 ], 364 rust_types: &[ 365 "radroots_event::calendar::AuthoredCalendarTimeEvent", 366 "radroots_event::calendar::CalendarEventError", 367 "radroots_event::calendar::IanaTimeZoneId", 368 "radroots_event::media::AuthoredImage", 369 "radroots_event::wire::Nip01EventWireParts", 370 "radroots_event_codec::error::EventEncodeError", 371 ], 372 vector: "contracts/conformance/vectors/calendar/radroots_profile.v1.json", 373 }, 374 CalendarOperationExpectation { 375 key: "social_calendar_time_event_parse_nip52", 376 id: "social.calendar_time_event.parse_nip52", 377 inputs: &["u32", "NostrTags", "String"], 378 outputs: &["ParsedNip52CalendarTimeEvent"], 379 error_class: "parse_error", 380 rust_modules: &[ 381 "crates/event/src/calendar.rs", 382 "crates/event_codec/src/calendar/decode.rs", 383 ], 384 rust_types: &[ 385 "radroots_event::calendar::CalendarRequest", 386 "radroots_event::calendar::CalendarUri", 387 "radroots_event::calendar::IanaTimeZoneId", 388 "radroots_event::calendar::ObservedUtcDay", 389 "radroots_event::calendar::ParsedNip52CalendarCommon", 390 "radroots_event::calendar::ParsedNip52CalendarCommonParts", 391 "radroots_event::calendar::ParsedNip52CalendarTimeEvent", 392 "radroots_event_codec::error::EventParseError", 393 ], 394 vector: "contracts/conformance/vectors/calendar/nip52_baseline.v1.json", 395 }, 396 CalendarOperationExpectation { 397 key: "social_calendar_time_event_admit_radroots_profile", 398 id: "social.calendar_time_event.admit_radroots_profile", 399 inputs: &["ParsedNip52CalendarTimeEvent"], 400 outputs: &["AdmittedCalendarTimeEvent"], 401 error_class: "admission_error", 402 rust_modules: &[ 403 "crates/event/src/calendar.rs", 404 "crates/event_codec/src/calendar/decode.rs", 405 ], 406 rust_types: &[ 407 "radroots_event::calendar::AdmittedCalendarTimeEvent", 408 "radroots_event::calendar::CalendarAdmissionError", 409 "radroots_event::calendar::ParsedNip52CalendarTimeEvent", 410 ], 411 vector: "contracts/conformance/vectors/calendar/radroots_profile.v1.json", 412 }, 413 CalendarOperationExpectation { 414 key: "social_calendar_build_authored_draft", 415 id: "social.calendar.build_authored_draft", 416 inputs: &["AuthoredCalendar"], 417 outputs: &["Nip01EventWireParts"], 418 error_class: "encode_error", 419 rust_modules: &[ 420 "crates/event/src/calendar.rs", 421 "crates/event/src/media.rs", 422 "crates/event_codec/src/calendar/encode.rs", 423 ], 424 rust_types: &[ 425 "radroots_event::calendar::AuthoredCalendar", 426 "radroots_event::calendar::CalendarEventError", 427 "radroots_event::calendar::CalendarEventReference", 428 "radroots_event::calendar::CalendarUid", 429 "radroots_event::media::AuthoredImage", 430 "radroots_event::wire::Nip01EventWireParts", 431 "radroots_event_codec::error::EventEncodeError", 432 ], 433 vector: "contracts/conformance/vectors/calendar/radroots_profile.v1.json", 434 }, 435 CalendarOperationExpectation { 436 key: "social_calendar_parse_nip52", 437 id: "social.calendar.parse_nip52", 438 inputs: &["u32", "NostrTags", "String"], 439 outputs: &["ParsedNip52Calendar"], 440 error_class: "parse_error", 441 rust_modules: &[ 442 "crates/event/src/calendar.rs", 443 "crates/event_codec/src/calendar/decode.rs", 444 ], 445 rust_types: &[ 446 "radroots_event::calendar::CalendarEventError", 447 "radroots_event::calendar::CalendarEventReference", 448 "radroots_event::calendar::CalendarUri", 449 "radroots_event::calendar::ParsedNip52Calendar", 450 "radroots_event::calendar::ParsedNip52CalendarParts", 451 "radroots_event_codec::error::EventParseError", 452 ], 453 vector: "contracts/conformance/vectors/calendar/nip52_baseline.v1.json", 454 }, 455 CalendarOperationExpectation { 456 key: "social_calendar_admit_radroots_profile", 457 id: "social.calendar.admit_radroots_profile", 458 inputs: &["ParsedNip52Calendar"], 459 outputs: &["AdmittedCalendar"], 460 error_class: "admission_error", 461 rust_modules: &[ 462 "crates/event/src/calendar.rs", 463 "crates/event_codec/src/calendar/decode.rs", 464 ], 465 rust_types: &[ 466 "radroots_blossom::BlobUrl", 467 "radroots_event::calendar::AdmittedCalendar", 468 "radroots_event::calendar::CalendarAdmissionError", 469 "radroots_event::calendar::CalendarEventReference", 470 "radroots_event::calendar::CalendarUid", 471 "radroots_event::calendar::ParsedNip52Calendar", 472 ], 473 vector: "contracts/conformance/vectors/calendar/radroots_profile.v1.json", 474 }, 475 CalendarOperationExpectation { 476 key: "social_calendar_rsvp_build_authored_draft", 477 id: "social.calendar_rsvp.build_authored_draft", 478 inputs: &["AuthoredCalendarEventRsvp"], 479 outputs: &["Nip01EventWireParts"], 480 error_class: "encode_error", 481 rust_modules: &[ 482 "crates/event/src/calendar.rs", 483 "crates/event_codec/src/calendar/encode.rs", 484 ], 485 rust_types: &[ 486 "radroots_event::calendar::AuthoredCalendarEventRsvp", 487 "radroots_event::calendar::CalendarEventAuthorReference", 488 "radroots_event::calendar::CalendarEventError", 489 "radroots_event::calendar::CalendarEventReference", 490 "radroots_event::calendar::CalendarEventRevisionReference", 491 "radroots_event::calendar::CalendarUid", 492 "radroots_event::calendar::CalendarEventFreeBusy", 493 "radroots_event::calendar::CalendarEventRsvpStatus", 494 "radroots_event::wire::Nip01EventWireParts", 495 "radroots_event_codec::error::EventEncodeError", 496 ], 497 vector: "contracts/conformance/vectors/calendar/radroots_profile.v1.json", 498 }, 499 CalendarOperationExpectation { 500 key: "social_calendar_rsvp_parse_nip52", 501 id: "social.calendar_rsvp.parse_nip52", 502 inputs: &["u32", "NostrTags", "String"], 503 outputs: &["ParsedNip52CalendarEventRsvp"], 504 error_class: "parse_error", 505 rust_modules: &[ 506 "crates/event/src/calendar.rs", 507 "crates/event_codec/src/calendar/decode.rs", 508 ], 509 rust_types: &[ 510 "radroots_event::calendar::CalendarEventAuthorReference", 511 "radroots_event::calendar::CalendarEventError", 512 "radroots_event::calendar::CalendarEventReference", 513 "radroots_event::calendar::CalendarEventRevisionReference", 514 "radroots_event::calendar::ParsedNip52CalendarEventRsvp", 515 "radroots_event::calendar::ParsedNip52CalendarEventRsvpParts", 516 "radroots_event::calendar::CalendarEventFreeBusy", 517 "radroots_event::calendar::CalendarEventRsvpStatus", 518 "radroots_event_codec::error::EventParseError", 519 ], 520 vector: "contracts/conformance/vectors/calendar/nip52_baseline.v1.json", 521 }, 522 CalendarOperationExpectation { 523 key: "social_calendar_rsvp_admit_radroots_profile", 524 id: "social.calendar_rsvp.admit_radroots_profile", 525 inputs: &["ParsedNip52CalendarEventRsvp"], 526 outputs: &["AdmittedCalendarEventRsvp"], 527 error_class: "admission_error", 528 rust_modules: &[ 529 "crates/event/src/calendar.rs", 530 "crates/event_codec/src/calendar/decode.rs", 531 ], 532 rust_types: &[ 533 "radroots_event::calendar::AdmittedCalendarEventRsvp", 534 "radroots_event::calendar::CalendarAdmissionError", 535 "radroots_event::calendar::CalendarEventAuthorReference", 536 "radroots_event::calendar::CalendarEventReference", 537 "radroots_event::calendar::CalendarEventRevisionReference", 538 "radroots_event::calendar::CalendarUid", 539 "radroots_event::calendar::ParsedNip52CalendarEventRsvp", 540 "radroots_event::calendar::CalendarEventFreeBusy", 541 "radroots_event::calendar::CalendarEventRsvpStatus", 542 ], 543 vector: "contracts/conformance/vectors/calendar/radroots_profile.v1.json", 544 }, 545 ]; 546 const POST_OPERATION_EXPECTATIONS: [PostOperationExpectation; 8] = [ 547 PostOperationExpectation { 548 key: "social_update_build_authored_draft", 549 id: "social.update.build_authored_draft", 550 inputs: &["AuthoredUpdate"], 551 outputs: &["Nip01EventWireParts"], 552 error_class: "encode_error", 553 signing: "none", 554 rust_modules: &[ 555 "crates/event/src/post.rs", 556 "crates/event_codec/src/post/authored.rs", 557 ], 558 rust_types: &[ 559 "radroots_event::post::AuthoredPostError", 560 "radroots_event::post::AuthoredUpdate", 561 ], 562 case_kinds: &[ 563 "social.update.build_authored_draft.valid", 564 "social.update.build_authored_draft.invalid", 565 ], 566 }, 567 PostOperationExpectation { 568 key: "social_photo_update_build_authored_draft", 569 id: "social.photo_update.build_authored_draft", 570 inputs: &["AuthoredPhotoUpdate"], 571 outputs: &["Nip01EventWireParts"], 572 error_class: "encode_error", 573 signing: "none", 574 rust_modules: &[ 575 "crates/event/src/post.rs", 576 "crates/event_codec/src/post/authored.rs", 577 ], 578 rust_types: &[ 579 "radroots_blossom::ApprovedBlobUrl", 580 "radroots_blossom::ByteVerifiedDescriptor", 581 "radroots_event::media::AuthoredImage", 582 "radroots_event::post::AuthoredPhotoUpdate", 583 "radroots_event::post::AuthoredPostError", 584 "radroots_event::post::AuthoredPostImage", 585 "radroots_event::post::PostImageDimensions", 586 ], 587 case_kinds: &[ 588 "social.photo_update.build_authored_draft.valid", 589 "social.photo_update.build_authored_draft.invalid", 590 ], 591 }, 592 PostOperationExpectation { 593 key: "social_ask_build_authored_draft", 594 id: "social.ask.build_authored_draft", 595 inputs: &["AuthoredAsk"], 596 outputs: &["Nip01EventWireParts"], 597 error_class: "encode_error", 598 signing: "none", 599 rust_modules: &[ 600 "crates/event/src/post.rs", 601 "crates/event_codec/src/post/authored.rs", 602 ], 603 rust_types: &[ 604 "radroots_event::post::AuthoredAsk", 605 "radroots_event::post::AuthoredPostError", 606 "radroots_event::post::AuthoredPostImage", 607 ], 608 case_kinds: &[ 609 "social.ask.build_authored_draft.valid", 610 "social.ask.build_authored_draft.invalid", 611 ], 612 }, 613 PostOperationExpectation { 614 key: "social_reply_build_authored_draft", 615 id: "social.reply.build_authored_draft", 616 inputs: &["AuthoredNip10Reply"], 617 outputs: &["Nip01EventWireParts"], 618 error_class: "encode_error", 619 signing: "none", 620 rust_modules: &[ 621 "crates/event/src/relay_hint.rs", 622 "crates/event/src/reply.rs", 623 "crates/event_codec/src/reply/authored.rs", 624 ], 625 rust_types: &[ 626 "radroots_event::post::reply::AuthoredNip10Reply", 627 "radroots_event::post::reply::Nip10ReplyError", 628 "radroots_event::tag::relay_hint::NostrRelayHint", 629 "radroots_event::post::reply::Nip10ReplyReference", 630 ], 631 case_kinds: &[ 632 "social.reply.build_authored_draft.valid", 633 "social.reply.build_authored_draft.invalid", 634 ], 635 }, 636 PostOperationExpectation { 637 key: "social_reply_project_verified_event", 638 id: "social.reply.project_verified_event", 639 inputs: &["RadrootsSignatureVerifiedEvent"], 640 outputs: &["RadrootsInboundNip10ReplyProjection"], 641 error_class: "parse_error", 642 signing: "none", 643 rust_modules: &[ 644 "crates/event/src/relay_hint.rs", 645 "crates/event_codec/src/reply/inbound.rs", 646 ], 647 rust_types: &[ 648 "radroots_event::tag::relay_hint::NostrRelayHint", 649 "radroots_event_codec::decode::reply::RadrootsInboundNip10EventReference", 650 "radroots_event_codec::decode::reply::RadrootsInboundNip10Participant", 651 "radroots_event_codec::decode::reply::RadrootsInboundNip10ReplyProjection", 652 "radroots_event_codec::decode::reply::RadrootsNip10ReplyDiagnostic", 653 "radroots_event_codec::decode::reply::RadrootsNip10ReplyProjectionError", 654 "radroots_event_codec::decode::reply::RadrootsNip10ReplyStyle", 655 "radroots_event_codec::verify::RadrootsSignatureVerifiedEvent", 656 ], 657 case_kinds: &[ 658 "social.reply.project_verified_event.valid", 659 "social.reply.project_verified_event.invalid", 660 ], 661 }, 662 PostOperationExpectation { 663 key: "social_reply_verify_and_admit_event", 664 id: "social.reply.verify_and_admit_event", 665 inputs: &["EventEnvelope"], 666 outputs: &["RadrootsAdmittedNip10ReplyEvent"], 667 error_class: "admission_error", 668 signing: "nip01", 669 rust_modules: &[ 670 "crates/event_codec/src/reply/admission.rs", 671 "crates/event_codec/src/reply/inbound.rs", 672 "crates/event_codec/src/verification.rs", 673 ], 674 rust_types: &[ 675 "radroots_event::envelope::EventEnvelope", 676 "radroots_event_codec::admission::reply::RadrootsAdmittedNip10ReplyEvent", 677 "radroots_event_codec::admission::reply::RadrootsNip10ReplyAdmissionError", 678 "radroots_event_codec::decode::reply::RadrootsInboundNip10ReplyProjection", 679 "radroots_event_codec::verify::RadrootsSignatureVerifiedEvent", 680 ], 681 case_kinds: &[ 682 "social.reply.verify_and_admit_event.valid", 683 "social.reply.verify_and_admit_event.invalid", 684 ], 685 }, 686 PostOperationExpectation { 687 key: "social_post_project_verified_event", 688 id: "social.post.project_verified_event", 689 inputs: &["RadrootsSignatureVerifiedEvent"], 690 outputs: &["RadrootsInboundPostProjection"], 691 error_class: "parse_error", 692 signing: "none", 693 rust_modules: &["crates/event_codec/src/post/inbound.rs"], 694 rust_types: &[ 695 "radroots_event_codec::decode::post::RadrootsInboundPostImeta", 696 "radroots_event_codec::decode::post::RadrootsInboundPostProjection", 697 "radroots_event_codec::decode::post::RadrootsPostClassification", 698 "radroots_event_codec::decode::post::RadrootsPostDiagnostic", 699 "radroots_event_codec::decode::post::RadrootsPostProjectionError", 700 "radroots_event_codec::verify::RadrootsSignatureVerifiedEvent", 701 ], 702 case_kinds: &[ 703 "social.post.project_verified_event.valid", 704 "social.post.project_verified_event.invalid", 705 ], 706 }, 707 PostOperationExpectation { 708 key: "social_post_verify_and_admit_event", 709 id: "social.post.verify_and_admit_event", 710 inputs: &["EventEnvelope"], 711 outputs: &["RadrootsPostAdmissionOutcome"], 712 error_class: "admission_error", 713 signing: "nip01", 714 rust_modules: &[ 715 "crates/event_codec/src/post/admission.rs", 716 "crates/event_codec/src/post/inbound.rs", 717 "crates/event_codec/src/verification.rs", 718 ], 719 rust_types: &[ 720 "radroots_event::envelope::EventEnvelope", 721 "radroots_event_codec::admission::post::RadrootsAdmittedRootPostEvent", 722 "radroots_event_codec::admission::post::RadrootsPostAdmissionError", 723 "radroots_event_codec::admission::post::RadrootsPostAdmissionOutcome", 724 "radroots_event_codec::admission::post::RadrootsThreadExcludedPostCandidate", 725 "radroots_event_codec::decode::post::RadrootsInboundPostProjection", 726 "radroots_event_codec::verify::RadrootsSignatureVerifiedEvent", 727 ], 728 case_kinds: &[ 729 "social.post.verify_and_admit_event.valid", 730 "social.post.verify_and_admit_event.invalid", 731 ], 732 }, 733 ]; 734 const POST_OPERATION_KEY_PREFIXES: [&str; 5] = [ 735 "social_update_", 736 "social_photo_update_", 737 "social_ask_", 738 "social_reply_", 739 "social_post_", 740 ]; 741 const POST_OPERATION_ID_PREFIXES: [&str; 5] = [ 742 "social.update.", 743 "social.photo_update.", 744 "social.ask.", 745 "social.reply.", 746 "social.post.", 747 ]; 748 const POST_VECTOR_EXPECTATIONS: [(&str, &str); 64] = [ 749 ( 750 "authored_update_wire", 751 "social.update.build_authored_draft.valid", 752 ), 753 ( 754 "authored_update_blank", 755 "social.update.build_authored_draft.invalid", 756 ), 757 ( 758 "authored_photo_update_wire", 759 "social.photo_update.build_authored_draft.valid", 760 ), 761 ( 762 "authored_photo_update_mime_underscore", 763 "social.photo_update.build_authored_draft.invalid", 764 ), 765 ("authored_ask_wire", "social.ask.build_authored_draft.valid"), 766 ( 767 "authored_ask_blank", 768 "social.ask.build_authored_draft.invalid", 769 ), 770 ( 771 "authored_nip10_direct_wire", 772 "social.reply.build_authored_draft.valid", 773 ), 774 ( 775 "authored_nip10_nested_wire", 776 "social.reply.build_authored_draft.valid", 777 ), 778 ( 779 "authored_nip10_canonical_ipv6_relay", 780 "social.reply.build_authored_draft.valid", 781 ), 782 ( 783 "authored_nip10_ambiguous_parent", 784 "social.reply.build_authored_draft.invalid", 785 ), 786 ( 787 "authored_nip10_invalid_event_id", 788 "social.reply.build_authored_draft.invalid", 789 ), 790 ( 791 "authored_nip10_invalid_relay_percent_host", 792 "social.reply.build_authored_draft.invalid", 793 ), 794 ( 795 "authored_nip10_invalid_relay_bad_percent_host", 796 "social.reply.build_authored_draft.invalid", 797 ), 798 ( 799 "authored_nip10_invalid_relay_ipv4_overflow", 800 "social.reply.build_authored_draft.invalid", 801 ), 802 ( 803 "authored_nip10_invalid_relay_ipvfuture", 804 "social.reply.build_authored_draft.invalid", 805 ), 806 ( 807 "authored_nip10_invalid_relay_empty_port", 808 "social.reply.build_authored_draft.invalid", 809 ), 810 ( 811 "authored_nip10_invalid_relay_zero_port", 812 "social.reply.build_authored_draft.invalid", 813 ), 814 ( 815 "authored_nip10_invalid_relay_port_overflow", 816 "social.reply.build_authored_draft.invalid", 817 ), 818 ( 819 "project_signed_nip10_marked_direct", 820 "social.reply.project_verified_event.valid", 821 ), 822 ( 823 "project_signed_nip10_marked_with_citation", 824 "social.reply.project_verified_event.valid", 825 ), 826 ( 827 "project_signed_nip10_marked_with_malformed_citation", 828 "social.reply.project_verified_event.valid", 829 ), 830 ( 831 "project_signed_nip10_marked_nested_reordered", 832 "social.reply.project_verified_event.valid", 833 ), 834 ( 835 "project_signed_nip10_positional_direct", 836 "social.reply.project_verified_event.valid", 837 ), 838 ( 839 "project_signed_nip10_positional_direct_with_author_hint", 840 "social.reply.project_verified_event.valid", 841 ), 842 ( 843 "project_signed_nip10_positional_many", 844 "social.reply.project_verified_event.valid", 845 ), 846 ( 847 "project_signed_nip10_positional_many_with_author_hints", 848 "social.reply.project_verified_event.valid", 849 ), 850 ( 851 "project_signed_nip10_positional_malformed_middle_citation", 852 "social.reply.project_verified_event.valid", 853 ), 854 ( 855 "project_signed_nip10_precedes_ask_and_media", 856 "social.reply.project_verified_event.valid", 857 ), 858 ( 859 "project_signed_nip10_invalid_relay", 860 "social.reply.project_verified_event.valid", 861 ), 862 ( 863 "project_signed_nip10_canonical_relay_authorities", 864 "social.reply.project_verified_event.valid", 865 ), 866 ( 867 "project_signed_nip10_malformed_relay_authorities", 868 "social.reply.project_verified_event.valid", 869 ), 870 ( 871 "project_signed_nip10_ambiguous_same_reference", 872 "social.reply.project_verified_event.invalid", 873 ), 874 ( 875 "project_signed_nip10_missing_author", 876 "social.reply.project_verified_event.valid", 877 ), 878 ( 879 "project_signed_nip10_invalid_event_id", 880 "social.reply.project_verified_event.invalid", 881 ), 882 ( 883 "project_signed_nip10_author_hint_mismatch", 884 "social.reply.project_verified_event.valid", 885 ), 886 ( 887 "project_signed_nip10_blank_content", 888 "social.reply.project_verified_event.valid", 889 ), 890 ( 891 "project_signed_nip10_invalid_author_hint_tolerated", 892 "social.reply.project_verified_event.valid", 893 ), 894 ( 895 "project_signed_nip10_invalid_participant_tolerated", 896 "social.reply.project_verified_event.valid", 897 ), 898 ( 899 "project_signed_nip10_lone_reply_marker", 900 "social.reply.project_verified_event.invalid", 901 ), 902 ( 903 "project_signed_nip10_unknown_marker", 904 "social.reply.project_verified_event.invalid", 905 ), 906 ( 907 "admit_signed_nip10_marked_direct", 908 "social.reply.verify_and_admit_event.valid", 909 ), 910 ( 911 "admit_signed_nip10_positional_direct", 912 "social.reply.verify_and_admit_event.valid", 913 ), 914 ( 915 "admit_signed_nip10_invalid_signature", 916 "social.reply.verify_and_admit_event.invalid", 917 ), 918 ( 919 "project_signed_update", 920 "social.post.project_verified_event.valid", 921 ), 922 ( 923 "project_signed_empty_inbound_update", 924 "social.post.project_verified_event.valid", 925 ), 926 ( 927 "project_signed_structural_photo", 928 "social.post.project_verified_event.valid", 929 ), 930 ( 931 "project_signed_photo_preserves_fallbacks_and_unknown_fields", 932 "social.post.project_verified_event.valid", 933 ), 934 ( 935 "project_signed_normalized_ask_precedes_malformed_media", 936 "social.post.project_verified_event.valid", 937 ), 938 ( 939 "project_signed_malformed_imeta_is_update", 940 "social.post.project_verified_event.valid", 941 ), 942 ( 943 "project_signed_duplicate_singleton_is_update", 944 "social.post.project_verified_event.valid", 945 ), 946 ( 947 "project_signed_mixed_imeta_is_update", 948 "social.post.project_verified_event.valid", 949 ), 950 ( 951 "project_signed_thread_candidate_precedes_ask_and_media", 952 "social.post.project_verified_event.valid", 953 ), 954 ( 955 "project_signed_malformed_ask_marker_is_update", 956 "social.post.project_verified_event.valid", 957 ), 958 ( 959 "project_signed_duplicate_normalized_ask_marker", 960 "social.post.project_verified_event.invalid", 961 ), 962 ( 963 "project_signed_kind_20_is_not_photo_update", 964 "social.post.project_verified_event.invalid", 965 ), 966 ( 967 "admit_signed_update", 968 "social.post.verify_and_admit_event.valid", 969 ), 970 ( 971 "admit_signed_structural_photo", 972 "social.post.verify_and_admit_event.valid", 973 ), 974 ( 975 "admit_signed_normalized_ask_precedes_malformed_media", 976 "social.post.verify_and_admit_event.valid", 977 ), 978 ( 979 "admit_signed_thread_candidate_precedes_ask_and_media", 980 "social.post.verify_and_admit_event.valid", 981 ), 982 ( 983 "admit_signed_empty_e_thread_candidate", 984 "social.post.verify_and_admit_event.valid", 985 ), 986 ( 987 "admit_signed_empty_e_value_thread_candidate", 988 "social.post.verify_and_admit_event.valid", 989 ), 990 ( 991 "admit_signed_duplicate_normalized_ask_marker", 992 "social.post.verify_and_admit_event.invalid", 993 ), 994 ( 995 "admit_signed_kind_20_is_not_photo_update", 996 "social.post.verify_and_admit_event.invalid", 997 ), 998 ( 999 "admit_signed_invalid_signature", 1000 "social.post.verify_and_admit_event.invalid", 1001 ), 1002 ]; 1003 const FOOD_AVAILABILITY_OPERATION_EXPECTATIONS: [FoodAvailabilityOperationExpectation; 4] = [ 1004 FoodAvailabilityOperationExpectation { 1005 key: "food_availability_build_authored_draft", 1006 id: "food_availability.build_authored_draft", 1007 inputs: &["FoodAvailabilityDetails", "u64"], 1008 outputs: &["Nip01EventWireParts"], 1009 error_class: "encode_error", 1010 signing: "none", 1011 rust_modules: &[ 1012 "crates/event/src/food_availability.rs", 1013 "crates/event_codec/src/food_availability/authored.rs", 1014 ], 1015 rust_types: &[ 1016 "radroots_blossom::ByteVerifiedDescriptor", 1017 "radroots_event::food::availability::FoodAvailabilityDetails", 1018 "radroots_event::food::availability::FoodAvailabilityDetailsParts", 1019 "radroots_event::food::availability::FoodAvailabilityError", 1020 "radroots_event::food::availability::FoodAvailabilityImage", 1021 "radroots_event::media::AuthoredImage", 1022 "radroots_event::wire::Nip01EventWireParts", 1023 "radroots_event_codec::food_availability::authored::RadrootsFoodAvailabilityEncodeError", 1024 ], 1025 case_kinds: &[ 1026 "food_availability.build_authored_draft.valid", 1027 "food_availability.build_authored_draft.invalid", 1028 ], 1029 }, 1030 FoodAvailabilityOperationExpectation { 1031 key: "food_availability_project_verified_event", 1032 id: "food_availability.project_verified_event", 1033 inputs: &["RadrootsSignatureVerifiedEvent"], 1034 outputs: &["RadrootsFoodAvailabilityProjectionOutcome"], 1035 error_class: "parse_error", 1036 signing: "none", 1037 rust_modules: &[ 1038 "crates/event/src/classified_listing.rs", 1039 "crates/event/src/food_availability.rs", 1040 "crates/event_codec/src/food_availability/inbound.rs", 1041 ], 1042 rust_types: &[ 1043 "radroots_event::listing::classified::ClassifiedListingPartition", 1044 "radroots_event::food::availability::FoodAvailabilityError", 1045 "radroots_event_codec::food_availability::inbound::RadrootsFoodAvailabilityImageDiagnostic", 1046 "radroots_event_codec::food_availability::inbound::RadrootsFoodAvailabilityProjectionError", 1047 "radroots_event_codec::food_availability::inbound::RadrootsFoodAvailabilityProjectionOutcome", 1048 "radroots_event_codec::food_availability::inbound::RadrootsInboundFoodAvailabilityImage", 1049 "radroots_event_codec::food_availability::inbound::RadrootsInboundFoodAvailabilityProjection", 1050 "radroots_event_codec::verify::RadrootsSignatureVerifiedEvent", 1051 ], 1052 case_kinds: &[ 1053 "food_availability.project_verified_event.valid", 1054 "food_availability.project_verified_event.invalid", 1055 ], 1056 }, 1057 FoodAvailabilityOperationExpectation { 1058 key: "food_availability_verify_and_admit_event", 1059 id: "food_availability.verify_and_admit_event", 1060 inputs: &["EventEnvelope"], 1061 outputs: &["RadrootsFoodAvailabilityAdmissionOutcome"], 1062 error_class: "admission_error", 1063 signing: "nip01", 1064 rust_modules: &[ 1065 "crates/event_codec/src/food_availability/admission.rs", 1066 "crates/event_codec/src/food_availability/inbound.rs", 1067 "crates/event_codec/src/verification.rs", 1068 ], 1069 rust_types: &[ 1070 "radroots_event::envelope::EventEnvelope", 1071 "radroots_event_codec::food_availability::admission::RadrootsAdmittedFoodAvailabilityEvent", 1072 "radroots_event_codec::food_availability::admission::RadrootsExcludedClassifiedListingCandidate", 1073 "radroots_event_codec::food_availability::admission::RadrootsFoodAvailabilityAdmissionError", 1074 "radroots_event_codec::food_availability::admission::RadrootsFoodAvailabilityAdmissionOutcome", 1075 "radroots_event_codec::food_availability::inbound::RadrootsInboundFoodAvailabilityProjection", 1076 "radroots_event_codec::verify::RadrootsSignatureVerifiedEvent", 1077 ], 1078 case_kinds: &[ 1079 "food_availability.verify_and_admit_event.valid", 1080 "food_availability.verify_and_admit_event.invalid", 1081 ], 1082 }, 1083 FoodAvailabilityOperationExpectation { 1084 key: "food_availability_validate_revision", 1085 id: "food_availability.validate_revision", 1086 inputs: &["RadrootsSignatureVerifiedEvent"], 1087 outputs: &["Unit"], 1088 error_class: "validation_error", 1089 signing: "none", 1090 rust_modules: &[ 1091 "crates/event_codec/src/food_availability/inbound.rs", 1092 "crates/event_codec/src/food_availability/revision.rs", 1093 ], 1094 rust_types: &[ 1095 "radroots_event_codec::food_availability::inbound::RadrootsFoodAvailabilityProjectionError", 1096 "radroots_event_codec::food_availability::revision::RadrootsFoodAvailabilityRevisionError", 1097 "radroots_event_codec::verify::RadrootsSignatureVerifiedEvent", 1098 ], 1099 case_kinds: &[ 1100 "food_availability.validate_revision.valid", 1101 "food_availability.validate_revision.invalid", 1102 ], 1103 }, 1104 ]; 1105 const FOOD_AVAILABILITY_CASE_KINDS: [&str; 8] = [ 1106 "food_availability.build_authored_draft.valid", 1107 "food_availability.build_authored_draft.invalid", 1108 "food_availability.project_verified_event.valid", 1109 "food_availability.project_verified_event.invalid", 1110 "food_availability.verify_and_admit_event.valid", 1111 "food_availability.verify_and_admit_event.invalid", 1112 "food_availability.validate_revision.valid", 1113 "food_availability.validate_revision.invalid", 1114 ]; 1115 const FOOD_AVAILABILITY_VECTOR_EXPECTATIONS: [(&str, &str); 40] = [ 1116 ( 1117 "food_authored_unit_g_001", 1118 "food_availability.build_authored_draft.valid", 1119 ), 1120 ( 1121 "food_authored_unit_kg_002", 1122 "food_availability.build_authored_draft.valid", 1123 ), 1124 ( 1125 "food_authored_unit_lb_003", 1126 "food_availability.build_authored_draft.valid", 1127 ), 1128 ( 1129 "food_authored_unit_oz_004", 1130 "food_availability.build_authored_draft.valid", 1131 ), 1132 ( 1133 "food_authored_unit_each_005", 1134 "food_availability.build_authored_draft.valid", 1135 ), 1136 ( 1137 "food_authored_unit_dozen_006", 1138 "food_availability.build_authored_draft.valid", 1139 ), 1140 ( 1141 "food_authored_unit_bunch_007", 1142 "food_availability.build_authored_draft.valid", 1143 ), 1144 ( 1145 "food_authored_unit_punnet_008", 1146 "food_availability.build_authored_draft.valid", 1147 ), 1148 ( 1149 "food_authored_unit_bag_009", 1150 "food_availability.build_authored_draft.valid", 1151 ), 1152 ( 1153 "food_authored_unit_basket_010", 1154 "food_availability.build_authored_draft.valid", 1155 ), 1156 ( 1157 "food_authored_wire_budget_ascii_max_011", 1158 "food_availability.build_authored_draft.valid", 1159 ), 1160 ( 1161 "food_authored_wire_budget_escaped_overflow_012", 1162 "food_availability.build_authored_draft.invalid", 1163 ), 1164 ( 1165 "food_authored_future_published_at_013", 1166 "food_availability.build_authored_draft.invalid", 1167 ), 1168 ( 1169 "food_admission_normalizes_decimal_currency_014", 1170 "food_availability.project_verified_event.valid", 1171 ), 1172 ( 1173 "food_admission_optional_standard_tags_015", 1174 "food_availability.verify_and_admit_event.valid", 1175 ), 1176 ( 1177 "food_admission_excludes_operational_before_validation_016", 1178 "food_availability.project_verified_event.valid", 1179 ), 1180 ( 1181 "food_admission_excludes_generic_nip99_017", 1182 "food_availability.project_verified_event.valid", 1183 ), 1184 ( 1185 "food_admission_rejects_ambiguous_markers_018", 1186 "food_availability.project_verified_event.invalid", 1187 ), 1188 ( 1189 "food_admission_rejects_wrong_kind_019", 1190 "food_availability.project_verified_event.invalid", 1191 ), 1192 ( 1193 "food_admission_rejects_core_tag_shape_020", 1194 "food_availability.project_verified_event.invalid", 1195 ), 1196 ( 1197 "food_admission_rejects_prohibited_delivery_021", 1198 "food_availability.project_verified_event.invalid", 1199 ), 1200 ( 1201 "food_admission_rejects_price_frequency_022", 1202 "food_availability.project_verified_event.invalid", 1203 ), 1204 ( 1205 "food_admission_requires_price_unit_023", 1206 "food_availability.project_verified_event.invalid", 1207 ), 1208 ( 1209 "food_admission_bounds_raw_decimal_digits_024", 1210 "food_availability.project_verified_event.invalid", 1211 ), 1212 ( 1213 "food_admission_rejects_malformed_price_unit_025", 1214 "food_availability.project_verified_event.invalid", 1215 ), 1216 ( 1217 "food_admission_rejects_quantity_unit_mismatch_026", 1218 "food_availability.project_verified_event.invalid", 1219 ), 1220 ( 1221 "food_admission_rejects_status_027", 1222 "food_availability.project_verified_event.invalid", 1223 ), 1224 ( 1225 "food_admission_rejects_future_published_at_028", 1226 "food_availability.project_verified_event.invalid", 1227 ), 1228 ( 1229 "food_admission_preserves_ordered_image_diagnostics_029", 1230 "food_availability.project_verified_event.valid", 1231 ), 1232 ( 1233 "food_admission_bounds_image_projection_030", 1234 "food_availability.project_verified_event.valid", 1235 ), 1236 ( 1237 "food_admission_rejects_invalid_signature_031", 1238 "food_availability.verify_and_admit_event.invalid", 1239 ), 1240 ( 1241 "food_revision_accepts_later_created_at_032", 1242 "food_availability.validate_revision.valid", 1243 ), 1244 ( 1245 "food_revision_rejects_invalid_previous_033", 1246 "food_availability.validate_revision.invalid", 1247 ), 1248 ( 1249 "food_revision_rejects_invalid_current_034", 1250 "food_availability.validate_revision.invalid", 1251 ), 1252 ( 1253 "food_revision_rejects_identifier_coordinate_change_035", 1254 "food_availability.validate_revision.invalid", 1255 ), 1256 ( 1257 "food_revision_rejects_author_coordinate_change_036", 1258 "food_availability.validate_revision.invalid", 1259 ), 1260 ( 1261 "food_revision_rejects_published_at_change_037", 1262 "food_availability.validate_revision.invalid", 1263 ), 1264 ( 1265 "food_revision_rejects_older_created_at_038", 1266 "food_availability.validate_revision.invalid", 1267 ), 1268 ( 1269 "food_revision_equal_time_a_current_039", 1270 "food_availability.validate_revision.invalid", 1271 ), 1272 ( 1273 "food_revision_equal_time_b_current_040", 1274 "food_availability.validate_revision.valid", 1275 ), 1276 ]; 1277 #[derive(Debug, Deserialize)] 1278 #[serde(deny_unknown_fields)] 1279 pub struct ContractManifest { 1280 pub contract: ManifestContract, 1281 pub surface: Surface, 1282 pub policy: Policy, 1283 } 1284 1285 #[derive(Debug, Deserialize)] 1286 #[serde(deny_unknown_fields)] 1287 pub struct ManifestContract { 1288 pub name: String, 1289 pub version: String, 1290 pub source: String, 1291 } 1292 1293 #[derive(Debug, Deserialize)] 1294 #[serde(deny_unknown_fields)] 1295 pub struct Surface { 1296 pub model_crates: Vec<String>, 1297 pub algorithm_crates: Vec<String>, 1298 pub rust_crate_tiers: Option<RustCrateTiers>, 1299 pub internal_replica_crates: Option<InternalReplicaCrates>, 1300 } 1301 1302 #[derive(Debug, Deserialize)] 1303 #[serde(deny_unknown_fields)] 1304 pub struct RustCrateTiers { 1305 pub advanced_substrate: Vec<String>, 1306 pub published_support: Vec<String>, 1307 pub deferred_publication: Vec<String>, 1308 } 1309 1310 #[derive(Debug, Deserialize)] 1311 #[serde(deny_unknown_fields)] 1312 pub struct InternalReplicaCrates { 1313 pub schema: String, 1314 pub storage: String, 1315 pub sync: String, 1316 } 1317 1318 #[derive(Debug, Deserialize)] 1319 #[serde(deny_unknown_fields)] 1320 pub struct Policy { 1321 pub exclude_internal_workspace_crates: bool, 1322 pub require_reproducible_exports: bool, 1323 pub require_conformance_vectors: bool, 1324 pub replica: Option<ReplicaPolicy>, 1325 } 1326 1327 #[derive(Debug, Deserialize)] 1328 #[serde(deny_unknown_fields)] 1329 pub struct ReplicaPolicy { 1330 pub forbid_legacy_alias_identifiers: bool, 1331 pub require_transport_agnostic_sync_contract: bool, 1332 pub require_deterministic_emit_ingest: bool, 1333 } 1334 1335 #[derive(Debug, Deserialize)] 1336 #[serde(deny_unknown_fields)] 1337 pub struct ReplicaContractManifest { 1338 pub schema_version: u32, 1339 pub contract: ReplicaContractMetadata, 1340 pub crate_family: ReplicaContractCrateFamily, 1341 pub policy: ReplicaContractPolicy, 1342 pub transfer: ReplicaTransferContract, 1343 } 1344 1345 #[derive(Debug, Deserialize)] 1346 #[serde(deny_unknown_fields)] 1347 pub struct ReplicaContractMetadata { 1348 pub name: String, 1349 pub version: String, 1350 pub purpose: String, 1351 } 1352 1353 #[derive(Debug, Deserialize)] 1354 #[serde(deny_unknown_fields)] 1355 pub struct ReplicaContractCrateFamily { 1356 pub schema: String, 1357 pub storage: String, 1358 pub sync: String, 1359 } 1360 1361 #[derive(Debug, Deserialize)] 1362 #[serde(deny_unknown_fields)] 1363 pub struct ReplicaContractPolicy { 1364 pub transport_agnostic_sync_core: bool, 1365 pub deterministic_emit_and_ingest: bool, 1366 pub forbid_legacy_alias_identifiers: bool, 1367 pub profile_event_emission: String, 1368 pub unknown_sync_request_fields: String, 1369 pub classified_listing_signature_verification: String, 1370 pub classified_listing_head_selection: String, 1371 pub classified_listing_operational_projection: String, 1372 pub classified_listing_excluded_or_rejected_head: String, 1373 pub classified_listing_head_only_ingest: String, 1374 pub legacy_bare_envelope_ingest: String, 1375 pub legacy_ingest_feature: String, 1376 pub phase_1_ingest_replacement: String, 1377 pub future_product_ingest_input: String, 1378 } 1379 1380 #[derive(Debug, Deserialize)] 1381 #[serde(deny_unknown_fields)] 1382 pub struct ReplicaTransferContract { 1383 pub version: u32, 1384 pub source: String, 1385 pub constant: String, 1386 } 1387 1388 #[derive(Debug, Deserialize)] 1389 #[serde(deny_unknown_fields)] 1390 pub struct OperationsContractManifest { 1391 pub contract: ManifestContract, 1392 pub public: PublicContract, 1393 pub shared_types: SharedTypesContract, 1394 pub errors: ErrorClassesContract, 1395 pub operations: BTreeMap<String, PublicOperationContract>, 1396 pub implementation_provenance: Option<ImplementationProvenance>, 1397 } 1398 1399 #[derive(Debug, Deserialize)] 1400 #[serde(deny_unknown_fields)] 1401 pub struct PublicContract { 1402 pub domains: Vec<String>, 1403 } 1404 1405 #[derive(Debug, Deserialize)] 1406 #[serde(deny_unknown_fields)] 1407 pub struct SharedTypesContract { 1408 pub public: Vec<String>, 1409 } 1410 1411 #[derive(Debug, Deserialize)] 1412 #[serde(deny_unknown_fields)] 1413 pub struct ErrorClassesContract { 1414 pub classes: Vec<String>, 1415 } 1416 1417 #[derive(Debug, Deserialize)] 1418 #[serde(deny_unknown_fields)] 1419 pub struct ImplementationProvenance { 1420 pub model_crates: Vec<String>, 1421 pub algorithm_crates: Vec<String>, 1422 } 1423 1424 #[derive(Debug, Deserialize)] 1425 #[serde(deny_unknown_fields)] 1426 pub struct PublicOperationContract { 1427 pub domain: String, 1428 pub id: String, 1429 pub stability: String, 1430 pub inputs: Vec<String>, 1431 pub outputs: Vec<String>, 1432 pub error_class: String, 1433 #[allow(dead_code)] 1434 pub deterministic: bool, 1435 pub signing: String, 1436 pub transport: String, 1437 pub implementation: PublicOperationImplementation, 1438 pub conformance: PublicOperationConformance, 1439 } 1440 1441 #[derive(Debug, Deserialize)] 1442 #[serde(deny_unknown_fields)] 1443 pub struct PublicOperationImplementation { 1444 pub rust_modules: Vec<String>, 1445 pub rust_types: Vec<String>, 1446 } 1447 1448 #[derive(Debug, Deserialize)] 1449 #[serde(deny_unknown_fields)] 1450 pub struct PublicOperationConformance { 1451 pub vector: String, 1452 #[serde(default)] 1453 pub case_kinds: Vec<String>, 1454 } 1455 1456 #[derive(Debug, Deserialize, Serialize)] 1457 #[serde(deny_unknown_fields)] 1458 struct DeletionConformanceRawEvent { 1459 id: String, 1460 pubkey: String, 1461 created_at: u64, 1462 kind: u32, 1463 tags: Vec<Vec<String>>, 1464 content: String, 1465 sig: String, 1466 } 1467 1468 #[derive(Clone, Copy)] 1469 struct CalendarOperationExpectation { 1470 key: &'static str, 1471 id: &'static str, 1472 inputs: &'static [&'static str], 1473 outputs: &'static [&'static str], 1474 error_class: &'static str, 1475 rust_modules: &'static [&'static str], 1476 rust_types: &'static [&'static str], 1477 vector: &'static str, 1478 } 1479 1480 #[derive(Clone, Copy)] 1481 struct PostOperationExpectation { 1482 key: &'static str, 1483 id: &'static str, 1484 inputs: &'static [&'static str], 1485 outputs: &'static [&'static str], 1486 error_class: &'static str, 1487 signing: &'static str, 1488 rust_modules: &'static [&'static str], 1489 rust_types: &'static [&'static str], 1490 case_kinds: &'static [&'static str], 1491 } 1492 1493 #[derive(Clone, Copy)] 1494 struct CommentOperationExpectation { 1495 key: &'static str, 1496 id: &'static str, 1497 inputs: &'static [&'static str], 1498 outputs: &'static [&'static str], 1499 error_class: &'static str, 1500 signing: &'static str, 1501 rust_modules: &'static [&'static str], 1502 rust_types: &'static [&'static str], 1503 case_kinds: &'static [&'static str], 1504 } 1505 1506 #[derive(Clone, Copy)] 1507 struct DeletionOperationExpectation { 1508 key: &'static str, 1509 id: &'static str, 1510 vector: &'static str, 1511 inputs: &'static [&'static str], 1512 outputs: &'static [&'static str], 1513 error_class: &'static str, 1514 signing: &'static str, 1515 rust_modules: &'static [&'static str], 1516 rust_types: &'static [&'static str], 1517 case_kinds: &'static [&'static str], 1518 } 1519 1520 #[derive(Clone, Copy)] 1521 struct FoodAvailabilityOperationExpectation { 1522 key: &'static str, 1523 id: &'static str, 1524 inputs: &'static [&'static str], 1525 outputs: &'static [&'static str], 1526 error_class: &'static str, 1527 signing: &'static str, 1528 rust_modules: &'static [&'static str], 1529 rust_types: &'static [&'static str], 1530 case_kinds: &'static [&'static str], 1531 } 1532 1533 #[derive(Debug, Deserialize)] 1534 #[serde(deny_unknown_fields)] 1535 pub struct VersionPolicy { 1536 pub contract: VersionContract, 1537 pub semver: SemverRules, 1538 pub release_integrity: ReleaseIntegrityRules, 1539 } 1540 1541 #[derive(Debug, Deserialize)] 1542 #[serde(deny_unknown_fields)] 1543 pub struct VersionContract { 1544 pub version: String, 1545 pub stability: String, 1546 } 1547 1548 #[derive(Debug, Deserialize)] 1549 #[serde(deny_unknown_fields)] 1550 pub struct SemverRules { 1551 pub major_on: Vec<String>, 1552 pub minor_on: Vec<String>, 1553 pub patch_on: Vec<String>, 1554 } 1555 1556 #[derive(Debug, Deserialize)] 1557 #[serde(deny_unknown_fields)] 1558 pub struct ReleaseIntegrityRules { 1559 pub requires_conformance_pass: bool, 1560 pub requires_contract_manifest_diff: bool, 1561 pub requires_release_notes: bool, 1562 } 1563 1564 #[derive(Debug, Deserialize)] 1565 #[serde(deny_unknown_fields)] 1566 struct ReleaseRecord { 1567 schema_version: u32, 1568 release: ReleaseRecordMetadata, 1569 artifacts: ReleaseRecordArtifacts, 1570 changes: Vec<ReleaseRecordChange>, 1571 } 1572 1573 #[derive(Debug, Deserialize)] 1574 #[serde(deny_unknown_fields)] 1575 struct ReleaseRecordMetadata { 1576 version: String, 1577 previous_version: String, 1578 contract_base_version: String, 1579 status: String, 1580 } 1581 1582 #[derive(Debug, Deserialize)] 1583 #[serde(deny_unknown_fields)] 1584 struct ReleaseRecordArtifacts { 1585 changelog: String, 1586 manifest: String, 1587 operations: String, 1588 replica: String, 1589 conformance: String, 1590 publish_policy: String, 1591 #[serde(default)] 1592 sqlite_runtime: Option<String>, 1593 } 1594 1595 #[derive(Debug, Deserialize)] 1596 #[serde(deny_unknown_fields)] 1597 struct SqliteRuntimeContract { 1598 schema_version: u32, 1599 package: SqliteRuntimePackage, 1600 activation: SqliteRuntimeActivation, 1601 access: SqliteRuntimeAccess, 1602 sealed_native_adapter: SqliteRuntimeSealedNativeAdapter, 1603 migration: SqliteRuntimeMigration, 1604 } 1605 1606 #[derive(Debug, Deserialize)] 1607 #[serde(deny_unknown_fields)] 1608 struct SqliteRuntimePackage { 1609 name: String, 1610 version: String, 1611 source: String, 1612 checksum: String, 1613 } 1614 1615 #[derive(Debug, Deserialize)] 1616 #[serde(deny_unknown_fields)] 1617 struct SqliteRuntimeActivation { 1618 route: Vec<String>, 1619 } 1620 1621 #[derive(Debug, Deserialize)] 1622 #[serde(deny_unknown_fields)] 1623 struct SqliteRuntimeAccess { 1624 high_level_library: String, 1625 native_linkage_owner: String, 1626 native_linkage_package: String, 1627 maximum_native_linkages: u32, 1628 forbidden_high_level_dependencies: Vec<String>, 1629 } 1630 1631 #[derive(Debug, Deserialize)] 1632 #[serde(deny_unknown_fields)] 1633 struct SqliteRuntimeSealedNativeAdapter { 1634 owner_package: String, 1635 relative_module: String, 1636 capability: String, 1637 status: String, 1638 } 1639 1640 #[derive(Debug, Deserialize)] 1641 #[serde(deny_unknown_fields)] 1642 struct SqliteRuntimeMigration { 1643 owner: String, 1644 status: String, 1645 temporary_direct_dependencies: Vec<String>, 1646 } 1647 1648 #[derive(Debug, Deserialize)] 1649 #[serde(deny_unknown_fields)] 1650 struct ReleaseRecordChange { 1651 id: String, 1652 classification: String, 1653 semver_impacts: Vec<String>, 1654 summary: String, 1655 } 1656 1657 #[derive(Debug)] 1658 pub struct ContractBundle { 1659 pub root: PathBuf, 1660 pub manifest: ContractManifest, 1661 pub version: VersionPolicy, 1662 pub replica: ReplicaContractManifest, 1663 pub operations_manifest: OperationsContractManifest, 1664 } 1665 1666 #[derive(Debug, Deserialize)] 1667 struct WorkspaceCargoManifest { 1668 workspace: WorkspaceSection, 1669 } 1670 1671 #[derive(Debug, Deserialize)] 1672 struct WorkspaceSection { 1673 members: Vec<String>, 1674 } 1675 1676 #[derive(Debug, Deserialize)] 1677 struct WorkspaceVersionCargoManifest { 1678 workspace: WorkspaceVersionSection, 1679 } 1680 1681 #[derive(Debug, Deserialize)] 1682 struct WorkspaceVersionSection { 1683 members: Vec<String>, 1684 package: WorkspacePackageVersion, 1685 dependencies: BTreeMap<String, WorkspaceDependencyVersion>, 1686 } 1687 1688 #[derive(Debug, Deserialize)] 1689 struct WorkspacePackageVersion { 1690 version: String, 1691 #[serde(default)] 1692 repository: String, 1693 } 1694 1695 #[derive(Debug, Deserialize)] 1696 struct WorkspaceDependencyVersion { 1697 path: Option<String>, 1698 version: Option<String>, 1699 } 1700 1701 #[derive(Debug, Deserialize)] 1702 struct VersionedPackageCargoManifest { 1703 package: VersionedPackageSection, 1704 } 1705 1706 #[derive(Debug, Deserialize)] 1707 struct VersionedPackageSection { 1708 name: String, 1709 version: PackageVersionSource, 1710 } 1711 1712 #[derive(Debug, Deserialize)] 1713 #[serde(untagged)] 1714 enum PackageVersionSource { 1715 Literal(String), 1716 Workspace { workspace: bool }, 1717 } 1718 1719 #[derive(Debug, Deserialize)] 1720 struct CargoLockManifest { 1721 package: Vec<CargoLockPackage>, 1722 } 1723 1724 #[derive(Debug, Deserialize)] 1725 struct CargoLockPackage { 1726 name: String, 1727 version: String, 1728 source: Option<String>, 1729 checksum: Option<String>, 1730 } 1731 1732 #[derive(Debug, Deserialize)] 1733 struct PackageCargoManifest { 1734 package: PackageSection, 1735 } 1736 1737 #[derive(Debug, Deserialize)] 1738 struct PackageSection { 1739 name: String, 1740 publish: Option<PackagePublish>, 1741 } 1742 1743 #[derive(Clone, Debug, Deserialize, PartialEq, Eq)] 1744 #[serde(untagged)] 1745 enum PackagePublish { 1746 Bool(bool), 1747 Registries(Vec<String>), 1748 } 1749 1750 #[cfg_attr(not(test), allow(dead_code))] 1751 #[derive(Debug, Deserialize)] 1752 struct CoverageRequiredFile { 1753 required: CoverageRequiredSection, 1754 } 1755 1756 #[cfg_attr(not(test), allow(dead_code))] 1757 #[derive(Debug, Deserialize)] 1758 struct CoverageRequiredSection { 1759 crates: Vec<String>, 1760 } 1761 1762 #[derive(Debug, Clone, PartialEq, Eq)] 1763 struct EventBoundaryRow { 1764 domain: String, 1765 kind: String, 1766 radroots_type: String, 1767 rpc_methods: BTreeSet<String>, 1768 } 1769 1770 #[derive(Clone, Copy)] 1771 struct EventBoundarySourceWitness { 1772 relative_path: &'static str, 1773 required_fragments: &'static [&'static str], 1774 } 1775 1776 #[derive(Clone, Copy)] 1777 struct EventBoundaryExpectation { 1778 domain: &'static str, 1779 kind: &'static str, 1780 radroots_type: &'static str, 1781 rpc_methods: &'static [&'static str], 1782 witnesses: &'static [EventBoundarySourceWitness], 1783 } 1784 1785 const PROFILE_WITNESSES: [EventBoundarySourceWitness; 5] = [ 1786 EventBoundarySourceWitness { 1787 relative_path: "crates/event/src/profile.rs", 1788 required_fragments: &["pub struct AuthoredProfile"], 1789 }, 1790 EventBoundarySourceWitness { 1791 relative_path: "crates/event_codec/src/profile/inbound/registry_v7.rs", 1792 required_fragments: &["pub struct RadrootsInboundProfileMetadata"], 1793 }, 1794 EventBoundarySourceWitness { 1795 relative_path: "crates/event_codec/src/profile/admission.rs", 1796 required_fragments: &[ 1797 "pub struct RadrootsAdmittedProfileEvent", 1798 "pub fn verify_and_admit_profile_event", 1799 ], 1800 }, 1801 EventBoundarySourceWitness { 1802 relative_path: "crates/event_codec/src/verification/v1.rs", 1803 required_fragments: &[ 1804 "pub struct RadrootsSignatureVerifiedEvent", 1805 "pub fn verify_nip01_event", 1806 ], 1807 }, 1808 EventBoundarySourceWitness { 1809 relative_path: "crates/event/src/kinds.rs", 1810 required_fragments: &["pub const KIND_PROFILE: u32 = 0;"], 1811 }, 1812 ]; 1813 1814 const FOLLOW_WITNESSES: [EventBoundarySourceWitness; 2] = [ 1815 EventBoundarySourceWitness { 1816 relative_path: "crates/event/src/follow.rs", 1817 required_fragments: &["pub struct Follow"], 1818 }, 1819 EventBoundarySourceWitness { 1820 relative_path: "crates/event/src/kinds.rs", 1821 required_fragments: &["pub const KIND_FOLLOW: u32 = 3;"], 1822 }, 1823 ]; 1824 1825 const POST_WITNESSES: [EventBoundarySourceWitness; 5] = [ 1826 EventBoundarySourceWitness { 1827 relative_path: "crates/event/src/post.rs", 1828 required_fragments: &[ 1829 "pub struct Post", 1830 "pub struct AuthoredUpdate", 1831 "pub struct AuthoredPhotoUpdate", 1832 "pub struct AuthoredAsk", 1833 ], 1834 }, 1835 EventBoundarySourceWitness { 1836 relative_path: "crates/event_codec/src/post/authored.rs", 1837 required_fragments: &[ 1838 "pub fn authored_update_to_wire_parts", 1839 "pub fn authored_photo_update_to_wire_parts", 1840 "pub fn authored_ask_to_wire_parts", 1841 ], 1842 }, 1843 EventBoundarySourceWitness { 1844 relative_path: "crates/event_codec/src/post/inbound/registry_v7.rs", 1845 required_fragments: &[ 1846 "pub struct RadrootsInboundPostProjection", 1847 "pub fn project_verified_post_event", 1848 ], 1849 }, 1850 EventBoundarySourceWitness { 1851 relative_path: "crates/event_codec/src/post/admission.rs", 1852 required_fragments: &[ 1853 "pub struct RadrootsAdmittedRootPostEvent", 1854 "pub struct RadrootsThreadExcludedPostCandidate", 1855 "pub enum RadrootsPostAdmissionOutcome", 1856 "pub fn verify_and_admit_post_event", 1857 ], 1858 }, 1859 EventBoundarySourceWitness { 1860 relative_path: "crates/event/src/kinds.rs", 1861 required_fragments: &["pub const KIND_POST: u32 = 1;"], 1862 }, 1863 ]; 1864 1865 const REPLY_WITNESSES: [EventBoundarySourceWitness; 5] = [ 1866 EventBoundarySourceWitness { 1867 relative_path: "crates/event/src/relay_hint.rs", 1868 required_fragments: &["pub struct NostrRelayHint"], 1869 }, 1870 EventBoundarySourceWitness { 1871 relative_path: "crates/event/src/reply.rs", 1872 required_fragments: &[ 1873 "pub struct Nip10ReplyReference", 1874 "pub struct AuthoredNip10Reply", 1875 ], 1876 }, 1877 EventBoundarySourceWitness { 1878 relative_path: "crates/event_codec/src/reply/inbound/registry_v7.rs", 1879 required_fragments: &[ 1880 "pub struct RadrootsInboundNip10ReplyProjection", 1881 "pub fn project_verified_nip10_reply_event", 1882 ], 1883 }, 1884 EventBoundarySourceWitness { 1885 relative_path: "crates/event_codec/src/reply/admission.rs", 1886 required_fragments: &[ 1887 "pub struct RadrootsAdmittedNip10ReplyEvent", 1888 "pub fn verify_and_admit_nip10_reply_event", 1889 ], 1890 }, 1891 EventBoundarySourceWitness { 1892 relative_path: "crates/nostr/src/events/reply.rs", 1893 required_fragments: &[ 1894 "pub struct Nip10ReplyBuilder", 1895 "pub fn build_nip10_reply_event", 1896 ], 1897 }, 1898 ]; 1899 1900 const COMMENT_WITNESSES: [EventBoundarySourceWitness; 7] = [ 1901 EventBoundarySourceWitness { 1902 relative_path: "crates/event/src/relay_hint.rs", 1903 required_fragments: &["pub struct NostrRelayHint"], 1904 }, 1905 EventBoundarySourceWitness { 1906 relative_path: "crates/event/src/comment.rs", 1907 required_fragments: &[ 1908 "pub enum Nip22CommentRoot", 1909 "pub enum Nip22CommentPosition", 1910 "pub struct AuthoredNip22Comment", 1911 ], 1912 }, 1913 EventBoundarySourceWitness { 1914 relative_path: "crates/event_codec/src/comment/authored.rs", 1915 required_fragments: &["pub fn authored_nip22_comment_to_wire_parts"], 1916 }, 1917 EventBoundarySourceWitness { 1918 relative_path: "crates/event_codec/src/comment/inbound/registry_v7.rs", 1919 required_fragments: &[ 1920 "pub struct RadrootsInboundNip22CommentProjection", 1921 "pub fn project_verified_nip22_comment_event", 1922 ], 1923 }, 1924 EventBoundarySourceWitness { 1925 relative_path: "crates/event_codec/src/comment/admission.rs", 1926 required_fragments: &[ 1927 "pub struct RadrootsAdmittedNip22CommentEvent", 1928 "pub fn verify_and_admit_nip22_comment_event", 1929 ], 1930 }, 1931 EventBoundarySourceWitness { 1932 relative_path: "crates/nostr/src/events/comment.rs", 1933 required_fragments: &[ 1934 "pub struct Nip22CommentBuilder", 1935 "pub fn build_nip22_comment_event", 1936 ], 1937 }, 1938 EventBoundarySourceWitness { 1939 relative_path: "crates/event/src/kinds.rs", 1940 required_fragments: &["pub const KIND_COMMENT: u32 = 1111;"], 1941 }, 1942 ]; 1943 1944 const DELETION_WITNESSES: [EventBoundarySourceWitness; 7] = [ 1945 EventBoundarySourceWitness { 1946 relative_path: "crates/event/src/deletion.rs", 1947 required_fragments: &["pub struct AuthoredNip09DeletionRequest"], 1948 }, 1949 EventBoundarySourceWitness { 1950 relative_path: "crates/event_codec/src/deletion/authored.rs", 1951 required_fragments: &["pub fn authored_nip09_deletion_request_to_wire_parts"], 1952 }, 1953 EventBoundarySourceWitness { 1954 relative_path: "crates/event_codec/src/deletion/reconciliation_v1.rs", 1955 required_fragments: &[ 1956 "pub struct RadrootsInboundNip09DeletionProjection", 1957 "pub fn project_verified_nip09_deletion_request_event", 1958 ], 1959 }, 1960 EventBoundarySourceWitness { 1961 relative_path: "crates/event_codec/src/deletion/reconciliation_v1.rs", 1962 required_fragments: &[ 1963 "pub struct RadrootsAdmittedNip09DeletionRequestEvent", 1964 "pub fn verify_and_admit_nip09_deletion_request_event", 1965 ], 1966 }, 1967 EventBoundarySourceWitness { 1968 relative_path: "crates/event_codec/src/deletion/reconciliation_v1.rs", 1969 required_fragments: &[ 1970 "pub enum RadrootsNip09SuppressionOutcome", 1971 "pub enum RadrootsNip09SuppressionReason", 1972 "pub struct RadrootsNip09EventReferenceEvidence", 1973 "pub struct RadrootsNip09AddressReferenceEvidence", 1974 "pub struct RadrootsNip09SuppressionDecision", 1975 "pub fn evaluate_nip09_suppression", 1976 ], 1977 }, 1978 EventBoundarySourceWitness { 1979 relative_path: "crates/nostr/src/events/deletion.rs", 1980 required_fragments: &[ 1981 "pub struct Nip09DeletionRequestBuilder", 1982 "pub fn build_nip09_deletion_request_event", 1983 ], 1984 }, 1985 EventBoundarySourceWitness { 1986 relative_path: "crates/event/src/kinds.rs", 1987 required_fragments: &["pub const KIND_DELETION_REQUEST: u32 = 5;"], 1988 }, 1989 ]; 1990 1991 const REACTION_WITNESSES: [EventBoundarySourceWitness; 2] = [ 1992 EventBoundarySourceWitness { 1993 relative_path: "crates/event/src/reaction.rs", 1994 required_fragments: &["pub struct Reaction"], 1995 }, 1996 EventBoundarySourceWitness { 1997 relative_path: "crates/event/src/kinds.rs", 1998 required_fragments: &["pub const KIND_REACTION: u32 = 7;"], 1999 }, 2000 ]; 2001 2002 const REPOST_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2003 EventBoundarySourceWitness { 2004 relative_path: "crates/event/src/repost.rs", 2005 required_fragments: &["pub struct Repost"], 2006 }, 2007 EventBoundarySourceWitness { 2008 relative_path: "crates/event/src/kinds.rs", 2009 required_fragments: &["pub const KIND_REPOST: u32 = 6;"], 2010 }, 2011 ]; 2012 2013 const GENERIC_REPOST_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2014 EventBoundarySourceWitness { 2015 relative_path: "crates/event/src/repost.rs", 2016 required_fragments: &["pub struct GenericRepost"], 2017 }, 2018 EventBoundarySourceWitness { 2019 relative_path: "crates/event/src/kinds.rs", 2020 required_fragments: &["pub const KIND_GENERIC_REPOST: u32 = 16;"], 2021 }, 2022 ]; 2023 2024 const SEAL_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2025 EventBoundarySourceWitness { 2026 relative_path: "crates/event/src/seal.rs", 2027 required_fragments: &["pub struct Seal"], 2028 }, 2029 EventBoundarySourceWitness { 2030 relative_path: "crates/event/src/kinds.rs", 2031 required_fragments: &["pub const KIND_SEAL: u32 = 13;"], 2032 }, 2033 ]; 2034 2035 const MESSAGE_WITNESSES: [EventBoundarySourceWitness; 4] = [ 2036 EventBoundarySourceWitness { 2037 relative_path: "crates/event/src/message.rs", 2038 required_fragments: &["pub struct Message"], 2039 }, 2040 EventBoundarySourceWitness { 2041 relative_path: "crates/event/src/kinds.rs", 2042 required_fragments: &["pub const KIND_MESSAGE: u32 = 14;"], 2043 }, 2044 EventBoundarySourceWitness { 2045 relative_path: "crates/nostr/src/nip17.rs", 2046 required_fragments: &["pub async fn wrap_message<T>(", "KIND_MESSAGE =>"], 2047 }, 2048 EventBoundarySourceWitness { 2049 relative_path: "crates/nostr/src/lib.rs", 2050 required_fragments: &["pub mod nip17;"], 2051 }, 2052 ]; 2053 2054 const MESSAGE_FILE_WITNESSES: [EventBoundarySourceWitness; 4] = [ 2055 EventBoundarySourceWitness { 2056 relative_path: "crates/event/src/message_file.rs", 2057 required_fragments: &["pub struct MessageFile"], 2058 }, 2059 EventBoundarySourceWitness { 2060 relative_path: "crates/event/src/kinds.rs", 2061 required_fragments: &["pub const KIND_MESSAGE_FILE: u32 = 15;"], 2062 }, 2063 EventBoundarySourceWitness { 2064 relative_path: "crates/nostr/src/nip17.rs", 2065 required_fragments: &["pub async fn wrap_message_file<T>(", "KIND_MESSAGE_FILE =>"], 2066 }, 2067 EventBoundarySourceWitness { 2068 relative_path: "crates/nostr/src/lib.rs", 2069 required_fragments: &["pub mod nip17;"], 2070 }, 2071 ]; 2072 2073 const GIFT_WRAP_WITNESSES: [EventBoundarySourceWitness; 4] = [ 2074 EventBoundarySourceWitness { 2075 relative_path: "crates/event/src/gift_wrap.rs", 2076 required_fragments: &["pub struct GiftWrap"], 2077 }, 2078 EventBoundarySourceWitness { 2079 relative_path: "crates/event/src/kinds.rs", 2080 required_fragments: &["pub const KIND_GIFT_WRAP: u32 = 1059;"], 2081 }, 2082 EventBoundarySourceWitness { 2083 relative_path: "crates/nostr/src/nip17.rs", 2084 required_fragments: &["pub async fn unwrap_gift_wrap<T>("], 2085 }, 2086 EventBoundarySourceWitness { 2087 relative_path: "crates/nostr/src/lib.rs", 2088 required_fragments: &["pub mod nip17;"], 2089 }, 2090 ]; 2091 2092 const PUBLIC_FILE_METADATA_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2093 EventBoundarySourceWitness { 2094 relative_path: "crates/event/src/file_metadata.rs", 2095 required_fragments: &["pub struct FileMetadata"], 2096 }, 2097 EventBoundarySourceWitness { 2098 relative_path: "crates/event/src/kinds.rs", 2099 required_fragments: &["pub const KIND_PUBLIC_FILE_METADATA: u32 = KIND_FILE_METADATA;"], 2100 }, 2101 ]; 2102 2103 const REPORT_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2104 EventBoundarySourceWitness { 2105 relative_path: "crates/event/src/report.rs", 2106 required_fragments: &["pub struct Report"], 2107 }, 2108 EventBoundarySourceWitness { 2109 relative_path: "crates/event/src/kinds.rs", 2110 required_fragments: &["pub const KIND_REPORT: u32 = 1984;"], 2111 }, 2112 ]; 2113 2114 const LIST_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2115 EventBoundarySourceWitness { 2116 relative_path: "crates/event/src/list.rs", 2117 required_fragments: &["pub struct List"], 2118 }, 2119 EventBoundarySourceWitness { 2120 relative_path: "crates/event/src/kinds.rs", 2121 required_fragments: &[ 2122 "pub const KIND_LIST_MUTE: u32 = 10000;", 2123 "pub const KIND_LIST_GOOD_WIKI_RELAYS: u32 = 10102;", 2124 ], 2125 }, 2126 ]; 2127 2128 const RELAY_LIST_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2129 EventBoundarySourceWitness { 2130 relative_path: "crates/event/src/list.rs", 2131 required_fragments: &["pub struct List"], 2132 }, 2133 EventBoundarySourceWitness { 2134 relative_path: "crates/event/src/kinds.rs", 2135 required_fragments: &["pub const KIND_LIST_READ_WRITE_RELAYS: u32 = 10002;"], 2136 }, 2137 ]; 2138 2139 const LIST_SET_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2140 EventBoundarySourceWitness { 2141 relative_path: "crates/event/src/list_set.rs", 2142 required_fragments: &["pub struct ListSet"], 2143 }, 2144 EventBoundarySourceWitness { 2145 relative_path: "crates/event/src/kinds.rs", 2146 required_fragments: &[ 2147 "pub const KIND_LIST_SET_FOLLOW: u32 = 30000;", 2148 "pub const KIND_LIST_SET_MEDIA_STARTER_PACK: u32 = 39092;", 2149 ], 2150 }, 2151 ]; 2152 2153 const ARTICLE_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2154 EventBoundarySourceWitness { 2155 relative_path: "crates/event/src/article.rs", 2156 required_fragments: &["pub struct Article"], 2157 }, 2158 EventBoundarySourceWitness { 2159 relative_path: "crates/event/src/kinds.rs", 2160 required_fragments: &["pub const KIND_ARTICLE: u32 = 30023;"], 2161 }, 2162 ]; 2163 2164 const KNOWLEDGE_WITNESSES: [EventBoundarySourceWitness; 3] = [ 2165 EventBoundarySourceWitness { 2166 relative_path: "crates/event/src/knowledge.rs", 2167 required_fragments: &[ 2168 "pub struct WikiArticle", 2169 "pub struct KnowledgeClaim", 2170 "pub struct KnowledgeFieldReport", 2171 "pub struct EvidenceBounty", 2172 ], 2173 }, 2174 EventBoundarySourceWitness { 2175 relative_path: "crates/event/src/kinds.rs", 2176 required_fragments: &[ 2177 "pub const KIND_WIKI_MERGE_REQUEST: u32 = 818;", 2178 "pub const KIND_KNOWLEDGE_CLAIM: u32 = 3460;", 2179 "pub const KIND_KNOWLEDGE_SOURCE: u32 = 30450;", 2180 "pub const KIND_WIKI_ARTICLE: u32 = 30818;", 2181 ], 2182 }, 2183 EventBoundarySourceWitness { 2184 relative_path: "crates/event/src/contract/registry_v7.rs", 2185 required_fragments: &[ 2186 "Reducer::KnowledgeProjection", 2187 "\"radroots.wiki.article.v1\"", 2188 "\"radroots.knowledge.claim.v1\"", 2189 "pub fn validate_event_contract_shape", 2190 ], 2191 }, 2192 ]; 2193 2194 const APP_DATA_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2195 EventBoundarySourceWitness { 2196 relative_path: "crates/event/src/app_data.rs", 2197 required_fragments: &["pub struct AppData"], 2198 }, 2199 EventBoundarySourceWitness { 2200 relative_path: "crates/event/src/kinds.rs", 2201 required_fragments: &["pub const KIND_APP_DATA: u32 = 30078;"], 2202 }, 2203 ]; 2204 2205 const APP_HANDLER_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2206 EventBoundarySourceWitness { 2207 relative_path: "crates/event/src/kinds.rs", 2208 required_fragments: &["pub const KIND_APPLICATION_HANDLER: u32 = 31990;"], 2209 }, 2210 EventBoundarySourceWitness { 2211 relative_path: "crates/nostr/src/events/application_handler.rs", 2212 required_fragments: &["pub fn build_application_handler_event("], 2213 }, 2214 ]; 2215 2216 const CALENDAR_DATE_WITNESSES: [EventBoundarySourceWitness; 4] = [ 2217 EventBoundarySourceWitness { 2218 relative_path: "crates/event/src/calendar.rs", 2219 required_fragments: &[ 2220 "pub struct AuthoredCalendarDateEvent", 2221 "pub struct ParsedNip52CalendarDateEvent", 2222 "pub struct AdmittedCalendarDateEvent", 2223 ], 2224 }, 2225 EventBoundarySourceWitness { 2226 relative_path: "crates/event_codec/src/calendar/encode.rs", 2227 required_fragments: &["pub fn date_to_wire_parts("], 2228 }, 2229 EventBoundarySourceWitness { 2230 relative_path: "crates/event_codec/src/calendar/decode.rs", 2231 required_fragments: &[ 2232 "pub fn parse_nip52_calendar_date_event(", 2233 "pub fn admit_radroots_calendar_date_event(", 2234 ], 2235 }, 2236 EventBoundarySourceWitness { 2237 relative_path: "crates/event/src/kinds.rs", 2238 required_fragments: &["pub const KIND_CALENDAR_DATE_EVENT: u32 = 31922;"], 2239 }, 2240 ]; 2241 2242 const CALENDAR_TIME_WITNESSES: [EventBoundarySourceWitness; 4] = [ 2243 EventBoundarySourceWitness { 2244 relative_path: "crates/event/src/calendar.rs", 2245 required_fragments: &[ 2246 "pub struct AuthoredCalendarTimeEvent", 2247 "pub struct ParsedNip52CalendarTimeEvent", 2248 "pub struct AdmittedCalendarTimeEvent", 2249 ], 2250 }, 2251 EventBoundarySourceWitness { 2252 relative_path: "crates/event_codec/src/calendar/encode.rs", 2253 required_fragments: &["pub fn time_to_wire_parts("], 2254 }, 2255 EventBoundarySourceWitness { 2256 relative_path: "crates/event_codec/src/calendar/decode.rs", 2257 required_fragments: &[ 2258 "pub fn parse_nip52_calendar_time_event(", 2259 "pub fn admit_radroots_calendar_time_event(", 2260 ], 2261 }, 2262 EventBoundarySourceWitness { 2263 relative_path: "crates/event/src/kinds.rs", 2264 required_fragments: &["pub const KIND_CALENDAR_TIME_EVENT: u32 = 31923;"], 2265 }, 2266 ]; 2267 2268 const CALENDAR_WITNESSES: [EventBoundarySourceWitness; 4] = [ 2269 EventBoundarySourceWitness { 2270 relative_path: "crates/event/src/calendar.rs", 2271 required_fragments: &[ 2272 "pub struct AuthoredCalendar {", 2273 "pub struct ParsedNip52Calendar {", 2274 "pub struct AdmittedCalendar {", 2275 ], 2276 }, 2277 EventBoundarySourceWitness { 2278 relative_path: "crates/event_codec/src/calendar/encode.rs", 2279 required_fragments: &["pub fn calendar_to_wire_parts("], 2280 }, 2281 EventBoundarySourceWitness { 2282 relative_path: "crates/event_codec/src/calendar/decode.rs", 2283 required_fragments: &[ 2284 "pub fn parse_nip52_calendar(", 2285 "pub fn admit_radroots_calendar(", 2286 ], 2287 }, 2288 EventBoundarySourceWitness { 2289 relative_path: "crates/event/src/kinds.rs", 2290 required_fragments: &["pub const KIND_CALENDAR: u32 = KIND_LIST_SET_CALENDAR;"], 2291 }, 2292 ]; 2293 2294 const CALENDAR_RSVP_WITNESSES: [EventBoundarySourceWitness; 4] = [ 2295 EventBoundarySourceWitness { 2296 relative_path: "crates/event/src/calendar.rs", 2297 required_fragments: &[ 2298 "pub struct AuthoredCalendarEventRsvp {", 2299 "pub struct ParsedNip52CalendarEventRsvp {", 2300 "pub struct AdmittedCalendarEventRsvp {", 2301 ], 2302 }, 2303 EventBoundarySourceWitness { 2304 relative_path: "crates/event_codec/src/calendar/encode.rs", 2305 required_fragments: &["pub fn rsvp_to_wire_parts("], 2306 }, 2307 EventBoundarySourceWitness { 2308 relative_path: "crates/event_codec/src/calendar/decode.rs", 2309 required_fragments: &[ 2310 "pub fn parse_nip52_calendar_event_rsvp(", 2311 "pub fn admit_radroots_calendar_event_rsvp(", 2312 ], 2313 }, 2314 EventBoundarySourceWitness { 2315 relative_path: "crates/event/src/kinds.rs", 2316 required_fragments: &["pub const KIND_CALENDAR_EVENT_RSVP: u32 = 31925;"], 2317 }, 2318 ]; 2319 2320 const FARM_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2321 EventBoundarySourceWitness { 2322 relative_path: "crates/event/src/farm.rs", 2323 required_fragments: &["pub struct Farm"], 2324 }, 2325 EventBoundarySourceWitness { 2326 relative_path: "crates/event/src/kinds.rs", 2327 required_fragments: &["pub const KIND_FARM: u32 = 30340;"], 2328 }, 2329 ]; 2330 2331 const PLOT_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2332 EventBoundarySourceWitness { 2333 relative_path: "crates/event/src/plot.rs", 2334 required_fragments: &["pub struct Plot"], 2335 }, 2336 EventBoundarySourceWitness { 2337 relative_path: "crates/event/src/kinds.rs", 2338 required_fragments: &["pub const KIND_PLOT: u32 = 30350;"], 2339 }, 2340 ]; 2341 2342 const COOP_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2343 EventBoundarySourceWitness { 2344 relative_path: "crates/event/src/coop.rs", 2345 required_fragments: &["pub struct Coop"], 2346 }, 2347 EventBoundarySourceWitness { 2348 relative_path: "crates/event/src/kinds.rs", 2349 required_fragments: &["pub const KIND_COOP: u32 = 30360;"], 2350 }, 2351 ]; 2352 2353 const DOCUMENT_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2354 EventBoundarySourceWitness { 2355 relative_path: "crates/event/src/document.rs", 2356 required_fragments: &["pub struct Document"], 2357 }, 2358 EventBoundarySourceWitness { 2359 relative_path: "crates/event/src/kinds.rs", 2360 required_fragments: &["pub const KIND_DOCUMENT: u32 = 30361;"], 2361 }, 2362 ]; 2363 2364 const RESOURCE_AREA_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2365 EventBoundarySourceWitness { 2366 relative_path: "crates/event/src/resource_area.rs", 2367 required_fragments: &["pub struct ResourceArea"], 2368 }, 2369 EventBoundarySourceWitness { 2370 relative_path: "crates/event/src/kinds.rs", 2371 required_fragments: &["pub const KIND_RESOURCE_AREA: u32 = 30370;"], 2372 }, 2373 ]; 2374 2375 const RESOURCE_CAP_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2376 EventBoundarySourceWitness { 2377 relative_path: "crates/event/src/resource_cap.rs", 2378 required_fragments: &["pub struct ResourceHarvestCap"], 2379 }, 2380 EventBoundarySourceWitness { 2381 relative_path: "crates/event/src/kinds.rs", 2382 required_fragments: &["pub const KIND_RESOURCE_HARVEST_CAP: u32 = 30371;"], 2383 }, 2384 ]; 2385 2386 const OPERATIONAL_LISTING_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2387 EventBoundarySourceWitness { 2388 relative_path: "crates/event/src/operational_listing.rs", 2389 required_fragments: &["pub struct OperationalListing"], 2390 }, 2391 EventBoundarySourceWitness { 2392 relative_path: "crates/event/src/kinds.rs", 2393 required_fragments: &["pub const KIND_CLASSIFIED_LISTING: u32 = 30402;"], 2394 }, 2395 ]; 2396 2397 const FOOD_AVAILABILITY_WITNESSES: [EventBoundarySourceWitness; 6] = [ 2398 EventBoundarySourceWitness { 2399 relative_path: "crates/event/src/food_availability.rs", 2400 required_fragments: &[ 2401 "pub const RADROOTS_FOOD_AVAILABILITY_CONTRACT_ID: &str", 2402 "pub struct FoodAvailabilityDetails", 2403 ], 2404 }, 2405 EventBoundarySourceWitness { 2406 relative_path: "crates/event/src/kinds.rs", 2407 required_fragments: &["pub const KIND_CLASSIFIED_LISTING: u32 = 30402;"], 2408 }, 2409 EventBoundarySourceWitness { 2410 relative_path: "crates/event_codec/src/food_availability/authored.rs", 2411 required_fragments: &["pub fn authored_food_availability_to_wire_parts("], 2412 }, 2413 EventBoundarySourceWitness { 2414 relative_path: "crates/event_codec/src/food_availability/inbound/registry_v7.rs", 2415 required_fragments: &[ 2416 "pub struct RadrootsInboundFoodAvailabilityProjection", 2417 "pub fn project_verified_food_availability_event(", 2418 ], 2419 }, 2420 EventBoundarySourceWitness { 2421 relative_path: "crates/event_codec/src/food_availability/admission.rs", 2422 required_fragments: &[ 2423 "pub struct RadrootsAdmittedFoodAvailabilityEvent", 2424 "pub fn verify_and_admit_food_availability_event(", 2425 ], 2426 }, 2427 EventBoundarySourceWitness { 2428 relative_path: "crates/event_codec/src/food_availability/revision.rs", 2429 required_fragments: &["pub fn validate_food_availability_revision("], 2430 }, 2431 ]; 2432 2433 const DVM_REQUEST_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2434 EventBoundarySourceWitness { 2435 relative_path: "crates/event/src/job_request.rs", 2436 required_fragments: &["pub struct JobRequest"], 2437 }, 2438 EventBoundarySourceWitness { 2439 relative_path: "crates/event/src/kinds.rs", 2440 required_fragments: &[ 2441 "pub const KIND_JOB_REQUEST_MIN: u32 = 5000;", 2442 "pub const KIND_JOB_REQUEST_MAX: u32 = 5999;", 2443 ], 2444 }, 2445 ]; 2446 2447 const DVM_RESULT_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2448 EventBoundarySourceWitness { 2449 relative_path: "crates/event/src/job_result.rs", 2450 required_fragments: &["pub struct JobResult"], 2451 }, 2452 EventBoundarySourceWitness { 2453 relative_path: "crates/event/src/kinds.rs", 2454 required_fragments: &[ 2455 "pub const KIND_JOB_RESULT_MIN: u32 = 6000;", 2456 "pub const KIND_JOB_RESULT_MAX: u32 = 6999;", 2457 ], 2458 }, 2459 ]; 2460 2461 const DVM_FEEDBACK_WITNESSES: [EventBoundarySourceWitness; 2] = [ 2462 EventBoundarySourceWitness { 2463 relative_path: "crates/event/src/job_feedback.rs", 2464 required_fragments: &["pub struct JobFeedback"], 2465 }, 2466 EventBoundarySourceWitness { 2467 relative_path: "crates/event/src/kinds.rs", 2468 required_fragments: &["pub const KIND_JOB_FEEDBACK: u32 = 7000;"], 2469 }, 2470 ]; 2471 2472 const TRADE_PROPOSAL_WITNESSES: [EventBoundarySourceWitness; 3] = [ 2473 EventBoundarySourceWitness { 2474 relative_path: "crates/event/src/kinds.rs", 2475 required_fragments: &["pub const KIND_TRADE_PROPOSAL: u32 = 3470;"], 2476 }, 2477 EventBoundarySourceWitness { 2478 relative_path: "crates/event/src/trade.rs", 2479 required_fragments: &[ 2480 "pub const RADROOTS_TRADE_PROPOSAL_CONTRACT_ID: &str", 2481 "Self::Proposal => KIND_TRADE_PROPOSAL", 2482 ], 2483 }, 2484 EventBoundarySourceWitness { 2485 relative_path: "crates/event_codec/src/trade/mod.rs", 2486 required_fragments: &[ 2487 "pub fn trade_mutation_event_build", 2488 "pub fn trade_mutation_from_event", 2489 "pub fn trade_mutation_from_verified_event", 2490 "pub fn validate_trade_mutation_tags", 2491 ], 2492 }, 2493 ]; 2494 2495 const TRADE_DECISION_WITNESSES: [EventBoundarySourceWitness; 3] = [ 2496 EventBoundarySourceWitness { 2497 relative_path: "crates/event/src/kinds.rs", 2498 required_fragments: &["pub const KIND_TRADE_DECISION: u32 = 3471;"], 2499 }, 2500 EventBoundarySourceWitness { 2501 relative_path: "crates/event/src/trade.rs", 2502 required_fragments: &[ 2503 "pub const RADROOTS_TRADE_DECISION_CONTRACT_ID: &str", 2504 "Self::Decision => KIND_TRADE_DECISION", 2505 ], 2506 }, 2507 EventBoundarySourceWitness { 2508 relative_path: "crates/event_codec/src/trade/mod.rs", 2509 required_fragments: &[ 2510 "pub fn trade_mutation_event_build", 2511 "pub fn trade_mutation_from_event", 2512 "pub fn trade_mutation_from_verified_event", 2513 "pub fn validate_trade_mutation_tags", 2514 ], 2515 }, 2516 ]; 2517 2518 const TRADE_REVISION_PROPOSAL_WITNESSES: [EventBoundarySourceWitness; 3] = [ 2519 EventBoundarySourceWitness { 2520 relative_path: "crates/event/src/kinds.rs", 2521 required_fragments: &["pub const KIND_TRADE_REVISION_PROPOSAL: u32 = 3472;"], 2522 }, 2523 EventBoundarySourceWitness { 2524 relative_path: "crates/event/src/trade.rs", 2525 required_fragments: &[ 2526 "pub const RADROOTS_TRADE_REVISION_PROPOSAL_CONTRACT_ID: &str", 2527 "Self::RevisionProposal => KIND_TRADE_REVISION_PROPOSAL", 2528 ], 2529 }, 2530 EventBoundarySourceWitness { 2531 relative_path: "crates/event_codec/src/trade/mod.rs", 2532 required_fragments: &[ 2533 "pub fn trade_mutation_event_build", 2534 "pub fn trade_mutation_from_event", 2535 "pub fn trade_mutation_from_verified_event", 2536 "pub fn validate_trade_mutation_tags", 2537 ], 2538 }, 2539 ]; 2540 2541 const TRADE_REVISION_DECISION_WITNESSES: [EventBoundarySourceWitness; 3] = [ 2542 EventBoundarySourceWitness { 2543 relative_path: "crates/event/src/kinds.rs", 2544 required_fragments: &["pub const KIND_TRADE_REVISION_DECISION: u32 = 3473;"], 2545 }, 2546 EventBoundarySourceWitness { 2547 relative_path: "crates/event/src/trade.rs", 2548 required_fragments: &[ 2549 "pub const RADROOTS_TRADE_REVISION_DECISION_CONTRACT_ID: &str", 2550 "Self::RevisionDecision => KIND_TRADE_REVISION_DECISION", 2551 ], 2552 }, 2553 EventBoundarySourceWitness { 2554 relative_path: "crates/event_codec/src/trade/mod.rs", 2555 required_fragments: &[ 2556 "pub fn trade_mutation_event_build", 2557 "pub fn trade_mutation_from_event", 2558 "pub fn trade_mutation_from_verified_event", 2559 "pub fn validate_trade_mutation_tags", 2560 ], 2561 }, 2562 ]; 2563 2564 const TRADE_CANCELLATION_WITNESSES: [EventBoundarySourceWitness; 3] = [ 2565 EventBoundarySourceWitness { 2566 relative_path: "crates/event/src/kinds.rs", 2567 required_fragments: &["pub const KIND_TRADE_CANCELLATION: u32 = 3474;"], 2568 }, 2569 EventBoundarySourceWitness { 2570 relative_path: "crates/event/src/trade.rs", 2571 required_fragments: &[ 2572 "pub const RADROOTS_TRADE_CANCELLATION_CONTRACT_ID: &str", 2573 "Self::Cancellation => KIND_TRADE_CANCELLATION", 2574 ], 2575 }, 2576 EventBoundarySourceWitness { 2577 relative_path: "crates/event_codec/src/trade/mod.rs", 2578 required_fragments: &[ 2579 "pub fn trade_mutation_event_build", 2580 "pub fn trade_mutation_from_event", 2581 "pub fn trade_mutation_from_verified_event", 2582 "pub fn validate_trade_mutation_tags", 2583 ], 2584 }, 2585 ]; 2586 2587 const RELAY_DOC_WITNESSES: [EventBoundarySourceWitness; 1] = [EventBoundarySourceWitness { 2588 relative_path: "crates/event/src/relay_document.rs", 2589 required_fragments: &["pub struct RelayDocument"], 2590 }]; 2591 2592 const CANONICAL_EVENT_BOUNDARY_EXPECTATIONS: [EventBoundaryExpectation; 43] = [ 2593 EventBoundaryExpectation { 2594 domain: "profile", 2595 kind: "0", 2596 radroots_type: "AuthoredProfile / RadrootsInboundProfileMetadata", 2597 rpc_methods: &[ 2598 "events.profile.publish", 2599 "events.profile.list", 2600 "events.profile.get", 2601 ], 2602 witnesses: &PROFILE_WITNESSES, 2603 }, 2604 EventBoundaryExpectation { 2605 domain: "follow", 2606 kind: "3", 2607 radroots_type: "Follow", 2608 rpc_methods: &[ 2609 "events.follow.publish", 2610 "events.follow.list", 2611 "events.follow.get", 2612 ], 2613 witnesses: &FOLLOW_WITNESSES, 2614 }, 2615 EventBoundaryExpectation { 2616 domain: "post", 2617 kind: "1", 2618 radroots_type: "AuthoredUpdate / AuthoredPhotoUpdate / AuthoredAsk / RadrootsInboundPostProjection", 2619 rpc_methods: &["events.post.publish", "events.post.list", "events.post.get"], 2620 witnesses: &POST_WITNESSES, 2621 }, 2622 EventBoundaryExpectation { 2623 domain: "reply", 2624 kind: "1", 2625 radroots_type: "AuthoredNip10Reply / RadrootsInboundNip10ReplyProjection / RadrootsAdmittedNip10ReplyEvent / Nip10ReplyBuilder", 2626 rpc_methods: &[ 2627 "social.reply.build_authored_draft", 2628 "social.reply.project_verified_event", 2629 "social.reply.verify_and_admit_event", 2630 ], 2631 witnesses: &REPLY_WITNESSES, 2632 }, 2633 EventBoundaryExpectation { 2634 domain: "comment", 2635 kind: "1111", 2636 radroots_type: "AuthoredNip22Comment / RadrootsInboundNip22CommentProjection / RadrootsAdmittedNip22CommentEvent / Nip22CommentBuilder", 2637 rpc_methods: &[ 2638 "social.comment.build_authored_draft", 2639 "social.comment.project_verified_event", 2640 "social.comment.verify_and_admit_event", 2641 ], 2642 witnesses: &COMMENT_WITNESSES, 2643 }, 2644 EventBoundaryExpectation { 2645 domain: "deletion_request", 2646 kind: "5", 2647 radroots_type: "AuthoredNip09DeletionRequest / RadrootsInboundNip09DeletionProjection / RadrootsAdmittedNip09DeletionRequestEvent / RadrootsNip09SuppressionDecision / Nip09DeletionRequestBuilder", 2648 rpc_methods: &[ 2649 "social.deletion_request.build_authored_draft", 2650 "social.deletion_request.project_verified_event", 2651 "social.deletion_request.verify_and_admit_event", 2652 "social.deletion_request.evaluate_suppression", 2653 ], 2654 witnesses: &DELETION_WITNESSES, 2655 }, 2656 EventBoundaryExpectation { 2657 domain: "reaction", 2658 kind: "7", 2659 radroots_type: "Reaction", 2660 rpc_methods: &[ 2661 "events.reaction.publish", 2662 "events.reaction.list", 2663 "events.reaction.get", 2664 ], 2665 witnesses: &REACTION_WITNESSES, 2666 }, 2667 EventBoundaryExpectation { 2668 domain: "repost", 2669 kind: "6", 2670 radroots_type: "Repost", 2671 rpc_methods: &[ 2672 "events.repost.publish", 2673 "events.repost.list", 2674 "events.repost.get", 2675 ], 2676 witnesses: &REPOST_WITNESSES, 2677 }, 2678 EventBoundaryExpectation { 2679 domain: "generic_repost", 2680 kind: "16", 2681 radroots_type: "GenericRepost", 2682 rpc_methods: &[ 2683 "events.generic_repost.publish", 2684 "events.generic_repost.list", 2685 "events.generic_repost.get", 2686 ], 2687 witnesses: &GENERIC_REPOST_WITNESSES, 2688 }, 2689 EventBoundaryExpectation { 2690 domain: "seal", 2691 kind: "13", 2692 radroots_type: "Seal", 2693 rpc_methods: &["events.seal.encode", "events.seal.decode"], 2694 witnesses: &SEAL_WITNESSES, 2695 }, 2696 EventBoundaryExpectation { 2697 domain: "message", 2698 kind: "14", 2699 radroots_type: "Message", 2700 rpc_methods: &[ 2701 "events.message.publish", 2702 "events.message.list", 2703 "events.message.get", 2704 ], 2705 witnesses: &MESSAGE_WITNESSES, 2706 }, 2707 EventBoundaryExpectation { 2708 domain: "message_file", 2709 kind: "15", 2710 radroots_type: "MessageFile", 2711 rpc_methods: &[ 2712 "events.message_file.publish", 2713 "events.message_file.list", 2714 "events.message_file.get", 2715 ], 2716 witnesses: &MESSAGE_FILE_WITNESSES, 2717 }, 2718 EventBoundaryExpectation { 2719 domain: "gift_wrap", 2720 kind: "1059", 2721 radroots_type: "GiftWrap", 2722 rpc_methods: &[ 2723 "events.gift_wrap.publish", 2724 "events.gift_wrap.list", 2725 "events.gift_wrap.get", 2726 ], 2727 witnesses: &GIFT_WRAP_WITNESSES, 2728 }, 2729 EventBoundaryExpectation { 2730 domain: "public_file_metadata", 2731 kind: "1063", 2732 radroots_type: "FileMetadata", 2733 rpc_methods: &[ 2734 "events.public_file_metadata.publish", 2735 "events.public_file_metadata.list", 2736 "events.public_file_metadata.get", 2737 ], 2738 witnesses: &PUBLIC_FILE_METADATA_WITNESSES, 2739 }, 2740 EventBoundaryExpectation { 2741 domain: "report", 2742 kind: "1984", 2743 radroots_type: "Report", 2744 rpc_methods: &[ 2745 "events.report.publish", 2746 "events.report.list", 2747 "events.report.get", 2748 ], 2749 witnesses: &REPORT_WITNESSES, 2750 }, 2751 EventBoundaryExpectation { 2752 domain: "list", 2753 kind: "10000..10102", 2754 radroots_type: "List", 2755 rpc_methods: &["events.list.publish", "events.list.list", "events.list.get"], 2756 witnesses: &LIST_WITNESSES, 2757 }, 2758 EventBoundaryExpectation { 2759 domain: "relay_list", 2760 kind: "10002", 2761 radroots_type: "List", 2762 rpc_methods: &[ 2763 "events.relay_list.publish", 2764 "events.relay_list.list", 2765 "events.relay_list.get", 2766 ], 2767 witnesses: &RELAY_LIST_WITNESSES, 2768 }, 2769 EventBoundaryExpectation { 2770 domain: "list_set", 2771 kind: "30000..30007, 30015, 30030, 30063, 30267, 39089, 39092", 2772 radroots_type: "ListSet", 2773 rpc_methods: &[ 2774 "events.list_set.publish", 2775 "events.list_set.list", 2776 "events.list_set.get", 2777 ], 2778 witnesses: &LIST_SET_WITNESSES, 2779 }, 2780 EventBoundaryExpectation { 2781 domain: "article", 2782 kind: "30023", 2783 radroots_type: "Article", 2784 rpc_methods: &[ 2785 "events.article.publish", 2786 "events.article.list", 2787 "events.article.get", 2788 ], 2789 witnesses: &ARTICLE_WITNESSES, 2790 }, 2791 EventBoundaryExpectation { 2792 domain: "knowledge", 2793 kind: "818, 3460..3465, 30450..30451, 30818..30819", 2794 radroots_type: "RadrootsKnowledgeEvent", 2795 rpc_methods: &[ 2796 "events.knowledge.publish", 2797 "events.knowledge.list", 2798 "events.knowledge.get", 2799 ], 2800 witnesses: &KNOWLEDGE_WITNESSES, 2801 }, 2802 EventBoundaryExpectation { 2803 domain: "app_data", 2804 kind: "30078", 2805 radroots_type: "AppData", 2806 rpc_methods: &[ 2807 "events.app_data.publish", 2808 "events.app_data.list", 2809 "events.app_data.get", 2810 ], 2811 witnesses: &APP_DATA_WITNESSES, 2812 }, 2813 EventBoundaryExpectation { 2814 domain: "app_handler", 2815 kind: "31990", 2816 radroots_type: "KIND_APPLICATION_HANDLER", 2817 rpc_methods: &[ 2818 "events.app_handler.publish", 2819 "events.app_handler.list", 2820 "events.app_handler.get", 2821 ], 2822 witnesses: &APP_HANDLER_WITNESSES, 2823 }, 2824 EventBoundaryExpectation { 2825 domain: "calendar_date", 2826 kind: "31922", 2827 radroots_type: "AuthoredCalendarDateEvent / ParsedNip52CalendarDateEvent / AdmittedCalendarDateEvent", 2828 rpc_methods: &[ 2829 "events.calendar_date.publish", 2830 "events.calendar_date.list", 2831 "events.calendar_date.get", 2832 ], 2833 witnesses: &CALENDAR_DATE_WITNESSES, 2834 }, 2835 EventBoundaryExpectation { 2836 domain: "calendar_time", 2837 kind: "31923", 2838 radroots_type: "AuthoredCalendarTimeEvent / ParsedNip52CalendarTimeEvent / AdmittedCalendarTimeEvent", 2839 rpc_methods: &[ 2840 "events.calendar_time.publish", 2841 "events.calendar_time.list", 2842 "events.calendar_time.get", 2843 ], 2844 witnesses: &CALENDAR_TIME_WITNESSES, 2845 }, 2846 EventBoundaryExpectation { 2847 domain: "calendar", 2848 kind: "31924", 2849 radroots_type: "AuthoredCalendar / ParsedNip52Calendar / AdmittedCalendar", 2850 rpc_methods: &[ 2851 "events.calendar.publish", 2852 "events.calendar.list", 2853 "events.calendar.get", 2854 ], 2855 witnesses: &CALENDAR_WITNESSES, 2856 }, 2857 EventBoundaryExpectation { 2858 domain: "calendar_rsvp", 2859 kind: "31925", 2860 radroots_type: "AuthoredCalendarEventRsvp / ParsedNip52CalendarEventRsvp / AdmittedCalendarEventRsvp", 2861 rpc_methods: &[ 2862 "events.calendar_rsvp.publish", 2863 "events.calendar_rsvp.list", 2864 "events.calendar_rsvp.get", 2865 ], 2866 witnesses: &CALENDAR_RSVP_WITNESSES, 2867 }, 2868 EventBoundaryExpectation { 2869 domain: "farm", 2870 kind: "30340", 2871 radroots_type: "Farm", 2872 rpc_methods: &["events.farm.publish", "events.farm.list", "events.farm.get"], 2873 witnesses: &FARM_WITNESSES, 2874 }, 2875 EventBoundaryExpectation { 2876 domain: "plot", 2877 kind: "30350", 2878 radroots_type: "Plot", 2879 rpc_methods: &["events.plot.publish", "events.plot.list", "events.plot.get"], 2880 witnesses: &PLOT_WITNESSES, 2881 }, 2882 EventBoundaryExpectation { 2883 domain: "coop", 2884 kind: "30360", 2885 radroots_type: "Coop", 2886 rpc_methods: &["events.coop.publish", "events.coop.list", "events.coop.get"], 2887 witnesses: &COOP_WITNESSES, 2888 }, 2889 EventBoundaryExpectation { 2890 domain: "document", 2891 kind: "30361", 2892 radroots_type: "Document", 2893 rpc_methods: &[ 2894 "events.document.publish", 2895 "events.document.list", 2896 "events.document.get", 2897 ], 2898 witnesses: &DOCUMENT_WITNESSES, 2899 }, 2900 EventBoundaryExpectation { 2901 domain: "resource_area", 2902 kind: "30370", 2903 radroots_type: "ResourceArea", 2904 rpc_methods: &[ 2905 "events.resource_area.publish", 2906 "events.resource_area.list", 2907 "events.resource_area.get", 2908 ], 2909 witnesses: &RESOURCE_AREA_WITNESSES, 2910 }, 2911 EventBoundaryExpectation { 2912 domain: "resource_cap", 2913 kind: "30371", 2914 radroots_type: "ResourceHarvestCap", 2915 rpc_methods: &[ 2916 "events.resource_cap.publish", 2917 "events.resource_cap.list", 2918 "events.resource_cap.get", 2919 ], 2920 witnesses: &RESOURCE_CAP_WITNESSES, 2921 }, 2922 EventBoundaryExpectation { 2923 domain: "food_availability", 2924 kind: "30402", 2925 radroots_type: "FoodAvailabilityDetails / RadrootsInboundFoodAvailabilityProjection / RadrootsAdmittedFoodAvailabilityEvent / FoodAvailabilityBuilder", 2926 rpc_methods: &[ 2927 "food_availability.build_authored_draft", 2928 "food_availability.project_verified_event", 2929 "food_availability.verify_and_admit_event", 2930 "food_availability.validate_revision", 2931 ], 2932 witnesses: &FOOD_AVAILABILITY_WITNESSES, 2933 }, 2934 EventBoundaryExpectation { 2935 domain: "operational_listing", 2936 kind: "30402", 2937 radroots_type: "OperationalListing", 2938 rpc_methods: &[ 2939 "events.operational_listing.publish", 2940 "events.operational_listing.list", 2941 "events.operational_listing.get", 2942 ], 2943 witnesses: &OPERATIONAL_LISTING_WITNESSES, 2944 }, 2945 EventBoundaryExpectation { 2946 domain: "dvm_request", 2947 kind: "5000-5999", 2948 radroots_type: "JobRequest", 2949 rpc_methods: &[ 2950 "events.dvm_request.publish", 2951 "events.dvm_request.list", 2952 "events.dvm_request.get", 2953 ], 2954 witnesses: &DVM_REQUEST_WITNESSES, 2955 }, 2956 EventBoundaryExpectation { 2957 domain: "dvm_result", 2958 kind: "6000-6999", 2959 radroots_type: "JobResult", 2960 rpc_methods: &[ 2961 "events.dvm_result.publish", 2962 "events.dvm_result.list", 2963 "events.dvm_result.get", 2964 ], 2965 witnesses: &DVM_RESULT_WITNESSES, 2966 }, 2967 EventBoundaryExpectation { 2968 domain: "dvm_feedback", 2969 kind: "7000", 2970 radroots_type: "JobFeedback", 2971 rpc_methods: &[ 2972 "events.dvm_feedback.publish", 2973 "events.dvm_feedback.list", 2974 "events.dvm_feedback.get", 2975 ], 2976 witnesses: &DVM_FEEDBACK_WITNESSES, 2977 }, 2978 EventBoundaryExpectation { 2979 domain: "trade:proposal", 2980 kind: "3470", 2981 radroots_type: "TradeMutationEnvelopeV1", 2982 rpc_methods: &[ 2983 "trade.get_trade", 2984 "trade.list_trades", 2985 "trade.submit_proposal", 2986 ], 2987 witnesses: &TRADE_PROPOSAL_WITNESSES, 2988 }, 2989 EventBoundaryExpectation { 2990 domain: "trade:decision", 2991 kind: "3471", 2992 radroots_type: "TradeMutationEnvelopeV1", 2993 rpc_methods: &[ 2994 "trade.decide_candidate", 2995 "trade.get_trade", 2996 "trade.list_trades", 2997 ], 2998 witnesses: &TRADE_DECISION_WITNESSES, 2999 }, 3000 EventBoundaryExpectation { 3001 domain: "trade:revision_proposal", 3002 kind: "3472", 3003 radroots_type: "TradeMutationEnvelopeV1", 3004 rpc_methods: &[ 3005 "trade.get_trade", 3006 "trade.list_trades", 3007 "trade.propose_revision", 3008 ], 3009 witnesses: &TRADE_REVISION_PROPOSAL_WITNESSES, 3010 }, 3011 EventBoundaryExpectation { 3012 domain: "trade:revision_decision", 3013 kind: "3473", 3014 radroots_type: "TradeMutationEnvelopeV1", 3015 rpc_methods: &[ 3016 "trade.decide_candidate", 3017 "trade.get_trade", 3018 "trade.list_trades", 3019 ], 3020 witnesses: &TRADE_REVISION_DECISION_WITNESSES, 3021 }, 3022 EventBoundaryExpectation { 3023 domain: "trade:cancellation", 3024 kind: "3474", 3025 radroots_type: "TradeMutationEnvelopeV1", 3026 rpc_methods: &["trade.cancel_trade", "trade.get_trade", "trade.list_trades"], 3027 witnesses: &TRADE_CANCELLATION_WITNESSES, 3028 }, 3029 EventBoundaryExpectation { 3030 domain: "relay_doc", 3031 kind: "N/A", 3032 radroots_type: "RelayDocument", 3033 rpc_methods: &["system.relay_doc.get"], 3034 witnesses: &RELAY_DOC_WITNESSES, 3035 }, 3036 ]; 3037 3038 #[derive(Debug, Deserialize)] 3039 struct ReleaseContractFile { 3040 release: ReleaseSection, 3041 #[serde(default)] 3042 publication: Option<PublicationControl>, 3043 #[serde(default)] 3044 workspace_classification: Option<WorkspaceReleaseClassification>, 3045 #[serde(default)] 3046 classification: ReleaseClassification, 3047 #[serde(default)] 3048 publish: Option<ReleaseCrateSet>, 3049 #[serde(default)] 3050 internal: Option<ReleaseCrateSet>, 3051 publish_order: ReleaseCrateSet, 3052 } 3053 3054 #[derive(Debug, Default, Deserialize)] 3055 struct ReleaseClassification { 3056 #[serde(default)] 3057 public: Vec<String>, 3058 #[serde(default)] 3059 internal: Vec<String>, 3060 #[serde(default)] 3061 deferred: Vec<String>, 3062 #[serde(default)] 3063 retired: Vec<String>, 3064 #[serde(default)] 3065 yank_only: Vec<String>, 3066 } 3067 3068 #[derive(Debug, Deserialize)] 3069 struct ReleaseSection { 3070 version: String, 3071 } 3072 3073 #[derive(Debug, Deserialize)] 3074 struct PublicationControl { 3075 frozen: bool, 3076 registry: String, 3077 final_enablement_step: u16, 3078 #[serde(default)] 3079 spec_id: String, 3080 #[serde(default)] 3081 approved_packages: Vec<String>, 3082 #[serde(default)] 3083 local_packages: Vec<String>, 3084 #[serde(default)] 3085 external_packages: Vec<String>, 3086 } 3087 3088 #[derive(Debug, Deserialize)] 3089 struct WorkspaceReleaseClassification { 3090 #[serde(default)] 3091 private: Vec<String>, 3092 #[serde(default)] 3093 build_codegen: Vec<String>, 3094 #[serde(default)] 3095 test_support: Vec<String>, 3096 #[serde(default)] 3097 preview: Vec<String>, 3098 #[serde(default)] 3099 retired: Vec<String>, 3100 } 3101 3102 #[derive(Debug, Deserialize)] 3103 struct CratesReleaseArchitecture { 3104 spec_id: String, 3105 package_count: usize, 3106 repositories: CratesReleaseRepositories, 3107 package: Vec<CratesReleasePackage>, 3108 } 3109 3110 #[derive(Debug, Deserialize)] 3111 struct CratesReleaseRepositories { 3112 lib: CratesReleaseRepository, 3113 sdk: CratesReleaseRepository, 3114 } 3115 3116 #[derive(Debug, Deserialize)] 3117 struct CratesReleaseRepository { 3118 version: String, 3119 packages: Vec<String>, 3120 } 3121 3122 #[derive(Debug, Deserialize)] 3123 struct CratesReleasePackage { 3124 name: String, 3125 } 3126 3127 #[derive(Debug, Deserialize)] 3128 struct ConsolidationReleaseOwnership { 3129 canonical_rust_repository: String, 3130 } 3131 3132 #[derive(Debug, Deserialize)] 3133 struct ReleaseCrateSet { 3134 crates: Vec<String>, 3135 } 3136 3137 #[derive(Debug, Deserialize)] 3138 #[serde(deny_unknown_fields)] 3139 struct ConformanceVectorFile { 3140 suite: String, 3141 contract_version: String, 3142 vectors: Vec<ConformanceVectorEntry>, 3143 } 3144 3145 #[allow(dead_code)] 3146 #[derive(Debug, Deserialize)] 3147 #[serde(deny_unknown_fields)] 3148 struct ConformanceVectorEntry { 3149 id: String, 3150 kind: String, 3151 input: Value, 3152 expected: Option<Value>, 3153 expected_error_contains: Option<String>, 3154 } 3155 3156 impl ConformanceVectorEntry { 3157 fn expected_value(&self) -> Result<&Value, String> { 3158 self.expected.as_ref().ok_or_else(|| { 3159 format!( 3160 "conformance vector {} does not define an expected output", 3161 self.id 3162 ) 3163 }) 3164 } 3165 } 3166 3167 impl ReleaseContractFile { 3168 fn uses_classification(&self) -> bool { 3169 !self.classification.public.is_empty() 3170 || !self.classification.internal.is_empty() 3171 || !self.classification.deferred.is_empty() 3172 || !self.classification.retired.is_empty() 3173 || !self.classification.yank_only.is_empty() 3174 } 3175 3176 fn public_crates(&self) -> Vec<String> { 3177 if let Some(publication) = &self.publication 3178 && !publication.local_packages.is_empty() 3179 { 3180 return publication.local_packages.clone(); 3181 } 3182 if self.uses_classification() { 3183 return self.classification.public.clone(); 3184 } 3185 self.publish 3186 .as_ref() 3187 .map(|set| set.crates.clone()) 3188 .unwrap_or_default() 3189 } 3190 3191 fn internal_crates(&self) -> Vec<String> { 3192 if self.uses_classification() { 3193 return self.classification.internal.clone(); 3194 } 3195 self.internal 3196 .as_ref() 3197 .map(|set| set.crates.clone()) 3198 .unwrap_or_default() 3199 } 3200 3201 fn deferred_crates(&self) -> Vec<String> { 3202 self.classification.deferred.clone() 3203 } 3204 3205 fn retired_crates(&self) -> Vec<String> { 3206 self.classification.retired.clone() 3207 } 3208 3209 fn yank_only_crates(&self) -> Vec<String> { 3210 self.classification.yank_only.clone() 3211 } 3212 } 3213 3214 fn parse_toml<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T, String> { 3215 let raw = match fs::read_to_string(path) { 3216 Ok(raw) => raw, 3217 Err(e) => return Err(format!("read {}: {e}", path.display())), 3218 }; 3219 match toml::from_str::<T>(&raw) { 3220 Ok(parsed) => Ok(parsed), 3221 Err(e) => Err(format!("parse {}: {e}", path.display())), 3222 } 3223 } 3224 3225 fn parse_json<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T, String> { 3226 let raw = match fs::read_to_string(path) { 3227 Ok(raw) => raw, 3228 Err(e) => return Err(format!("read {}: {e}", path.display())), 3229 }; 3230 match serde_json::from_str::<T>(&raw) { 3231 Ok(parsed) => Ok(parsed), 3232 Err(e) => Err(format!("parse {}: {e}", path.display())), 3233 } 3234 } 3235 3236 fn resolve_event_boundary_matrix_path(workspace_root: &Path) -> Result<PathBuf, String> { 3237 let candidate = workspace_root.join(EVENT_BOUNDARY_MATRIX_RELATIVE); 3238 if candidate.is_file() { 3239 return Ok(candidate); 3240 } 3241 resolve_missing_event_boundary_matrix_path(workspace_root) 3242 } 3243 3244 fn missing_event_boundary_matrix_error() -> String { 3245 format!("canonical event matrix not found at {EVENT_BOUNDARY_MATRIX_RELATIVE}") 3246 } 3247 3248 #[cfg(not(test))] 3249 fn resolve_missing_event_boundary_matrix_path(_workspace_root: &Path) -> Result<PathBuf, String> { 3250 Err(missing_event_boundary_matrix_error()) 3251 } 3252 3253 #[cfg(test)] 3254 #[cfg_attr(coverage_nightly, coverage(off))] 3255 fn resolve_missing_event_boundary_matrix_path(workspace_root: &Path) -> Result<PathBuf, String> { 3256 if !should_synthesize_owner_contracts_for_tests(workspace_root) { 3257 return Err(missing_event_boundary_matrix_error()); 3258 } 3259 let path = std::env::temp_dir().join(format!( 3260 "radroots_xtask_event_boundary_{}.md", 3261 std::process::id() 3262 )); 3263 fs::write(&path, synthetic_event_boundary_matrix()) 3264 .map_err(|e| format!("write {}: {e}", path.display()))?; 3265 Ok(path) 3266 } 3267 3268 #[cfg(test)] 3269 #[cfg_attr(coverage_nightly, coverage(off))] 3270 fn synthetic_event_boundary_matrix() -> String { 3271 let mut raw = String::from( 3272 "# Event boundary matrix\n\n## Coverage matrix\n\n| Domain | Kind | Radroots Type | RPC Methods | Notes |\n| --- | --- | --- | --- | --- |\n", 3273 ); 3274 for expectation in CANONICAL_EVENT_BOUNDARY_EXPECTATIONS { 3275 raw.push_str(&format!( 3276 "| {} | {} | {} | {} | synthetic test matrix |\n", 3277 expectation.domain, 3278 expectation.kind, 3279 expectation.radroots_type, 3280 expectation.rpc_methods.join(", ") 3281 )); 3282 } 3283 raw.push('\n'); 3284 raw 3285 } 3286 3287 fn parse_event_boundary_matrix(path: &Path) -> Result<BTreeMap<String, EventBoundaryRow>, String> { 3288 let raw = match fs::read_to_string(path) { 3289 Ok(raw) => raw, 3290 Err(e) => return Err(format!("read {}: {e}", path.display())), 3291 }; 3292 let mut rows = BTreeMap::new(); 3293 let mut in_table = false; 3294 for line in raw.lines() { 3295 let trimmed = line.trim(); 3296 if trimmed == "| Domain | Kind | Radroots Type | RPC Methods | Notes |" { 3297 in_table = true; 3298 continue; 3299 } 3300 if !in_table { 3301 continue; 3302 } 3303 if trimmed.is_empty() { 3304 break; 3305 } 3306 if trimmed == "| --- | --- | --- | --- | --- |" { 3307 continue; 3308 } 3309 if !trimmed.starts_with('|') { 3310 break; 3311 } 3312 let columns = trimmed 3313 .trim_matches('|') 3314 .split('|') 3315 .map(|part| part.trim()) 3316 .collect::<Vec<_>>(); 3317 if columns.len() != 5 { 3318 return Err(format!( 3319 "canonical event matrix row in {} must have exactly 5 columns: {}", 3320 path.display(), 3321 trimmed 3322 )); 3323 } 3324 let domain = columns[0].to_string(); 3325 if domain.is_empty() { 3326 return Err(format!( 3327 "canonical event matrix row in {} must define a non-empty domain", 3328 path.display() 3329 )); 3330 } 3331 let rpc_methods = columns[3] 3332 .split(',') 3333 .map(str::trim) 3334 .filter(|item| !item.is_empty()) 3335 .map(|item| item.to_string()) 3336 .collect::<BTreeSet<_>>(); 3337 if rpc_methods.is_empty() { 3338 return Err(format!( 3339 "canonical event matrix row {} in {} must define rpc methods", 3340 domain, 3341 path.display() 3342 )); 3343 } 3344 let row = EventBoundaryRow { 3345 domain: domain.clone(), 3346 kind: columns[1].to_string(), 3347 radroots_type: columns[2].to_string(), 3348 rpc_methods, 3349 }; 3350 if rows.insert(domain.clone(), row).is_some() { 3351 return Err(format!( 3352 "canonical event matrix {} has duplicate domain row {}", 3353 path.display(), 3354 domain 3355 )); 3356 } 3357 } 3358 3359 if rows.is_empty() { 3360 return Err(format!( 3361 "canonical event matrix {} does not contain the coverage table", 3362 path.display() 3363 )); 3364 } 3365 3366 Ok(rows) 3367 } 3368 3369 fn validate_event_boundary_source_witness( 3370 workspace_root: &Path, 3371 domain: &str, 3372 witness: &EventBoundarySourceWitness, 3373 ) -> Result<(), String> { 3374 let path = workspace_root.join(witness.relative_path); 3375 let source = match fs::read_to_string(&path) { 3376 Ok(source) => source, 3377 Err(e) => return Err(format!("read {}: {e}", path.display())), 3378 }; 3379 for fragment in witness.required_fragments { 3380 if !source.contains(fragment) { 3381 return Err(format!( 3382 "canonical event row {} is missing required implementation fragment {} in {}", 3383 domain, 3384 fragment, 3385 path.display() 3386 )); 3387 } 3388 } 3389 Ok(()) 3390 } 3391 3392 fn validate_canonical_event_boundary_at_path( 3393 workspace_root: &Path, 3394 matrix_path: &Path, 3395 ) -> Result<(), String> { 3396 let rows = parse_event_boundary_matrix(matrix_path)?; 3397 let expected_domains = CANONICAL_EVENT_BOUNDARY_EXPECTATIONS 3398 .iter() 3399 .map(|row| row.domain.to_string()) 3400 .collect::<BTreeSet<_>>(); 3401 let actual_domains = rows.keys().cloned().collect::<BTreeSet<_>>(); 3402 if actual_domains != expected_domains { 3403 let missing = expected_domains 3404 .difference(&actual_domains) 3405 .cloned() 3406 .collect::<BTreeSet<_>>(); 3407 let extra = actual_domains 3408 .difference(&expected_domains) 3409 .cloned() 3410 .collect::<BTreeSet<_>>(); 3411 return Err(format!( 3412 "canonical event matrix {} is missing rows: {}; and includes unexpected rows: {}", 3413 matrix_path.display(), 3414 join_set(&missing), 3415 join_set(&extra) 3416 )); 3417 } 3418 3419 for expectation in CANONICAL_EVENT_BOUNDARY_EXPECTATIONS { 3420 let row = rows.get(expectation.domain).ok_or_else(|| { 3421 format!( 3422 "canonical event matrix {} is missing required row {}", 3423 matrix_path.display(), 3424 expectation.domain 3425 ) 3426 })?; 3427 if row.kind != expectation.kind { 3428 return Err(format!( 3429 "canonical event row {} kind drift: expected {}, got {}", 3430 expectation.domain, expectation.kind, row.kind 3431 )); 3432 } 3433 if row.radroots_type != expectation.radroots_type { 3434 return Err(format!( 3435 "canonical event row {} type drift: expected {}, got {}", 3436 expectation.domain, expectation.radroots_type, row.radroots_type 3437 )); 3438 } 3439 let expected_methods = expectation 3440 .rpc_methods 3441 .iter() 3442 .map(|method| (*method).to_string()) 3443 .collect::<BTreeSet<_>>(); 3444 if row.rpc_methods != expected_methods { 3445 return Err(format!( 3446 "canonical event row {} rpc drift: expected {}, got {}", 3447 expectation.domain, 3448 join_set(&expected_methods), 3449 join_set(&row.rpc_methods) 3450 )); 3451 } 3452 for witness in expectation.witnesses { 3453 validate_event_boundary_source_witness(workspace_root, expectation.domain, witness)?; 3454 } 3455 } 3456 3457 Ok(()) 3458 } 3459 3460 pub fn validate_canonical_event_boundary(workspace_root: &Path) -> Result<(), String> { 3461 let matrix_path = resolve_event_boundary_matrix_path(workspace_root)?; 3462 validate_canonical_event_boundary_at_path(workspace_root, &matrix_path) 3463 } 3464 3465 fn contract_root(workspace_root: &Path) -> PathBuf { 3466 workspace_root.join("contracts") 3467 } 3468 3469 fn conformance_root(workspace_root: &Path) -> PathBuf { 3470 workspace_root.join(CONFORMANCE_ROOT_RELATIVE) 3471 } 3472 3473 fn conformance_schema_path(workspace_root: &Path) -> PathBuf { 3474 workspace_root.join(CONFORMANCE_SCHEMA_RELATIVE) 3475 } 3476 3477 fn required_field_set(value: &Value, field: &str, path: &Path) -> Result<BTreeSet<String>, String> { 3478 let required = value 3479 .as_array() 3480 .ok_or_else(|| format!("{field} in {} must be an array", path.display()))?; 3481 let mut names = BTreeSet::new(); 3482 for item in required { 3483 let name = item 3484 .as_str() 3485 .ok_or_else(|| format!("{field} in {} must contain strings", path.display()))?; 3486 if name.trim().is_empty() { 3487 return Err(format!( 3488 "{field} in {} must not contain empty names", 3489 path.display() 3490 )); 3491 } 3492 names.insert(name.to_string()); 3493 } 3494 Ok(names) 3495 } 3496 3497 fn validate_string_schema_property( 3498 property: &Value, 3499 field: &str, 3500 path: &Path, 3501 min_length: Option<u64>, 3502 pattern: Option<&str>, 3503 ) -> Result<(), String> { 3504 let property = property 3505 .as_object() 3506 .ok_or_else(|| format!("{field} schema in {} must be an object", path.display()))?; 3507 let kind = property 3508 .get("type") 3509 .and_then(Value::as_str) 3510 .ok_or_else(|| format!("{field} schema in {} must declare type", path.display()))?; 3511 if kind != "string" { 3512 return Err(format!( 3513 "{field} schema in {} must use type=string", 3514 path.display() 3515 )); 3516 } 3517 if let Some(expected) = min_length { 3518 let actual = property 3519 .get("minLength") 3520 .and_then(Value::as_u64) 3521 .ok_or_else(|| format!("{field} schema in {} must set minLength", path.display()))?; 3522 if actual != expected { 3523 return Err(format!( 3524 "{field} schema in {} must set minLength={expected}", 3525 path.display() 3526 )); 3527 } 3528 } 3529 if let Some(expected) = pattern { 3530 let actual = property 3531 .get("pattern") 3532 .and_then(Value::as_str) 3533 .ok_or_else(|| format!("{field} schema in {} must set pattern", path.display()))?; 3534 if actual != expected { 3535 return Err(format!( 3536 "{field} schema in {} must set pattern {}", 3537 path.display(), 3538 expected 3539 )); 3540 } 3541 } 3542 Ok(()) 3543 } 3544 3545 fn validate_conformance_schema(workspace_root: &Path) -> Result<(), String> { 3546 let path = conformance_schema_path(workspace_root); 3547 let schema = parse_json::<Value>(&path)?; 3548 let schema_obj = schema.as_object().ok_or_else(|| { 3549 format!( 3550 "conformance schema {} must be a JSON object", 3551 path.display() 3552 ) 3553 })?; 3554 let schema_type = schema_obj 3555 .get("type") 3556 .and_then(Value::as_str) 3557 .ok_or_else(|| format!("conformance schema {} must declare type", path.display()))?; 3558 if schema_type != "object" { 3559 return Err(format!( 3560 "conformance schema {} must use type=object", 3561 path.display() 3562 )); 3563 } 3564 let additional = schema_obj 3565 .get("additionalProperties") 3566 .and_then(Value::as_bool) 3567 .ok_or_else(|| { 3568 format!( 3569 "conformance schema {} must declare additionalProperties", 3570 path.display() 3571 ) 3572 })?; 3573 if additional { 3574 return Err(format!( 3575 "conformance schema {} must disallow additionalProperties", 3576 path.display() 3577 )); 3578 } 3579 let root_required = required_field_set( 3580 schema_obj.get("required").ok_or_else(|| { 3581 format!( 3582 "conformance schema {} missing required list", 3583 path.display() 3584 ) 3585 })?, 3586 "required", 3587 &path, 3588 )?; 3589 let expected_root_required = BTreeSet::from([ 3590 "suite".to_string(), 3591 "contract_version".to_string(), 3592 "vectors".to_string(), 3593 ]); 3594 if root_required != expected_root_required { 3595 return Err(format!( 3596 "conformance schema {} must require suite, contract_version, and vectors", 3597 path.display() 3598 )); 3599 } 3600 let properties = schema_obj 3601 .get("properties") 3602 .and_then(Value::as_object) 3603 .ok_or_else(|| { 3604 format!( 3605 "conformance schema {} missing properties map", 3606 path.display() 3607 ) 3608 })?; 3609 validate_string_schema_property( 3610 properties.get("suite").ok_or_else(|| { 3611 format!( 3612 "conformance schema {} missing suite property", 3613 path.display() 3614 ) 3615 })?, 3616 "suite", 3617 &path, 3618 Some(1), 3619 None, 3620 )?; 3621 validate_string_schema_property( 3622 properties.get("contract_version").ok_or_else(|| { 3623 format!( 3624 "conformance schema {} missing contract_version property", 3625 path.display() 3626 ) 3627 })?, 3628 "contract_version", 3629 &path, 3630 None, 3631 Some("^[0-9]+\\.[0-9]+\\.[0-9]+$"), 3632 )?; 3633 let vectors = properties 3634 .get("vectors") 3635 .and_then(Value::as_object) 3636 .ok_or_else(|| { 3637 format!( 3638 "conformance schema {} missing vectors property", 3639 path.display() 3640 ) 3641 })?; 3642 let vectors_type = vectors 3643 .get("type") 3644 .and_then(Value::as_str) 3645 .ok_or_else(|| format!("vectors schema in {} must declare type", path.display()))?; 3646 if vectors_type != "array" { 3647 return Err(format!( 3648 "vectors schema in {} must use type=array", 3649 path.display() 3650 )); 3651 } 3652 let items = vectors 3653 .get("items") 3654 .and_then(Value::as_object) 3655 .ok_or_else(|| format!("vectors schema in {} must define items", path.display()))?; 3656 let items_type = items 3657 .get("type") 3658 .and_then(Value::as_str) 3659 .ok_or_else(|| format!("vector item schema in {} must declare type", path.display()))?; 3660 if items_type != "object" { 3661 return Err(format!( 3662 "vector item schema in {} must use type=object", 3663 path.display() 3664 )); 3665 } 3666 let items_additional = items 3667 .get("additionalProperties") 3668 .and_then(Value::as_bool) 3669 .ok_or_else(|| { 3670 format!( 3671 "vector item schema in {} must declare additionalProperties", 3672 path.display() 3673 ) 3674 })?; 3675 if items_additional { 3676 return Err(format!( 3677 "vector item schema in {} must disallow additionalProperties", 3678 path.display() 3679 )); 3680 } 3681 let item_required = required_field_set( 3682 items.get("required").ok_or_else(|| { 3683 format!( 3684 "vector item schema in {} missing required list", 3685 path.display() 3686 ) 3687 })?, 3688 "required", 3689 &path, 3690 )?; 3691 let expected_item_required = 3692 BTreeSet::from(["id".to_string(), "input".to_string(), "kind".to_string()]); 3693 if item_required != expected_item_required { 3694 return Err(format!( 3695 "vector item schema in {} must require id, kind, and input", 3696 path.display() 3697 )); 3698 } 3699 let expected_one_of = serde_json::json!([ 3700 { 3701 "required": ["expected"], 3702 "not": {"required": ["expected_error_contains"]} 3703 }, 3704 { 3705 "required": ["expected_error_contains"], 3706 "not": {"required": ["expected"]} 3707 } 3708 ]); 3709 if items.get("oneOf") != Some(&expected_one_of) { 3710 return Err(format!( 3711 "vector item schema in {} must require exactly one of expected or expected_error_contains", 3712 path.display() 3713 )); 3714 } 3715 let item_properties = items 3716 .get("properties") 3717 .and_then(Value::as_object) 3718 .ok_or_else(|| { 3719 format!( 3720 "vector item schema in {} missing properties", 3721 path.display() 3722 ) 3723 })?; 3724 validate_string_schema_property( 3725 item_properties.get("id").ok_or_else(|| { 3726 format!( 3727 "vector item schema in {} missing id property", 3728 path.display() 3729 ) 3730 })?, 3731 "id", 3732 &path, 3733 Some(1), 3734 None, 3735 )?; 3736 validate_string_schema_property( 3737 item_properties.get("kind").ok_or_else(|| { 3738 format!( 3739 "vector item schema in {} missing kind property", 3740 path.display() 3741 ) 3742 })?, 3743 "kind", 3744 &path, 3745 Some(1), 3746 None, 3747 )?; 3748 for field in ["input", "expected"] { 3749 let property = item_properties.get(field).ok_or_else(|| { 3750 format!( 3751 "vector item schema in {} missing {} property", 3752 path.display(), 3753 field 3754 ) 3755 })?; 3756 if !property.is_object() { 3757 return Err(format!( 3758 "vector item schema in {} must define {} as an object schema", 3759 path.display(), 3760 field 3761 )); 3762 } 3763 } 3764 validate_string_schema_property( 3765 item_properties 3766 .get("expected_error_contains") 3767 .ok_or_else(|| { 3768 format!( 3769 "vector item schema in {} missing expected_error_contains property", 3770 path.display() 3771 ) 3772 })?, 3773 "expected_error_contains", 3774 &path, 3775 Some(1), 3776 None, 3777 )?; 3778 Ok(()) 3779 } 3780 3781 fn base_contract_version(version: &str) -> &str { 3782 version.split_once('-').map_or(version, |(base, _)| base) 3783 } 3784 3785 fn parse_semver_version(version: &str) -> Result<Version, String> { 3786 Version::parse(version) 3787 .map_err(|error| format!("version {version} is not valid SemVer: {error}")) 3788 } 3789 3790 fn validate_contract_version_lockstep(bundle: &ContractBundle) -> Result<(), String> { 3791 let contract_version = bundle.manifest.contract.version.as_str(); 3792 parse_semver_version(contract_version)?; 3793 if bundle.version.contract.version != contract_version { 3794 return Err(format!( 3795 "version contract {} must match manifest contract version {}", 3796 bundle.version.contract.version, contract_version 3797 )); 3798 } 3799 if bundle.operations_manifest.contract.version != contract_version { 3800 return Err(format!( 3801 "operations contract version {} must match manifest contract version {}", 3802 bundle.operations_manifest.contract.version, contract_version 3803 )); 3804 } 3805 Ok(()) 3806 } 3807 3808 fn validate_workspace_version_lockstep( 3809 workspace_root: &Path, 3810 contract_version: &str, 3811 ) -> Result<(), String> { 3812 let workspace_manifest = 3813 parse_toml::<WorkspaceVersionCargoManifest>(&workspace_root.join("Cargo.toml"))?; 3814 let architecture_path = 3815 workspace_root.join("contracts/crates/release_v1/radroots_crates_release_v1.toml"); 3816 let governed_version = if architecture_path.is_file() { 3817 parse_toml::<CratesReleaseArchitecture>(&architecture_path)? 3818 .repositories 3819 .lib 3820 .version 3821 } else { 3822 contract_version.to_owned() 3823 }; 3824 if workspace_manifest.workspace.package.version != governed_version { 3825 return Err(format!( 3826 "workspace.package.version {} must match library repository version {}", 3827 workspace_manifest.workspace.package.version, governed_version 3828 )); 3829 } 3830 let mut governed_packages = BTreeMap::new(); 3831 for member in &workspace_manifest.workspace.members { 3832 let package_path = workspace_root.join(member).join("Cargo.toml"); 3833 let package = parse_toml::<VersionedPackageCargoManifest>(&package_path)?; 3834 let expected_version = governed_version.as_str(); 3835 match package.package.version { 3836 PackageVersionSource::Literal(ref version) if version == expected_version => {} 3837 PackageVersionSource::Literal(version) => { 3838 return Err(format!( 3839 "workspace member {member} package version {version} must match governed version {expected_version}" 3840 )); 3841 } 3842 PackageVersionSource::Workspace { workspace } => { 3843 return Err(format!( 3844 "workspace member {member} must set an explicit package version {expected_version}, not version.workspace = {workspace}, so mounted path consumers preserve the governed package version" 3845 )); 3846 } 3847 } 3848 governed_packages.insert( 3849 member.clone(), 3850 (package.package.name.clone(), expected_version.to_owned()), 3851 ); 3852 3853 if package.package.name.starts_with("radroots_") { 3854 let exact_requirement = format!("={expected_version}"); 3855 let dependency = workspace_manifest 3856 .workspace 3857 .dependencies 3858 .get(&package.package.name) 3859 .ok_or_else(|| { 3860 format!( 3861 "workspace dependency {} is required for member {member}", 3862 package.package.name 3863 ) 3864 })?; 3865 if dependency.path.as_deref() != Some(member.as_str()) { 3866 return Err(format!( 3867 "workspace dependency {} path must be {member}", 3868 package.package.name 3869 )); 3870 } 3871 if dependency.version.as_deref() != Some(exact_requirement.as_str()) { 3872 return Err(format!( 3873 "workspace dependency {} version must be the exact requirement {}", 3874 package.package.name, exact_requirement 3875 )); 3876 } 3877 } 3878 } 3879 3880 for (dependency_name, dependency) in &workspace_manifest.workspace.dependencies { 3881 let Some(path) = dependency.path.as_deref() else { 3882 continue; 3883 }; 3884 let Some((_, expected_version)) = governed_packages.get(path) else { 3885 continue; 3886 }; 3887 let exact_requirement = format!("={expected_version}"); 3888 if dependency.version.as_deref() != Some(exact_requirement.as_str()) { 3889 return Err(format!( 3890 "workspace path dependency {dependency_name} version must be the exact requirement {exact_requirement}" 3891 )); 3892 } 3893 } 3894 3895 validate_cargo_lock_version_lockstep(workspace_root, &governed_packages) 3896 } 3897 3898 fn validate_cargo_lock_version_lockstep( 3899 workspace_root: &Path, 3900 governed_packages: &BTreeMap<String, (String, String)>, 3901 ) -> Result<(), String> { 3902 let lock = parse_toml::<CargoLockManifest>(&workspace_root.join("Cargo.lock"))?; 3903 for (member, (package_name, expected_version)) in governed_packages { 3904 let workspace_entries = lock 3905 .package 3906 .iter() 3907 .filter(|package| package.name == *package_name && package.source.is_none()) 3908 .collect::<Vec<_>>(); 3909 if workspace_entries.len() != 1 { 3910 return Err(format!( 3911 "Cargo.lock must contain exactly one source-free entry for workspace member {member} ({package_name})" 3912 )); 3913 } 3914 if workspace_entries[0].version != *expected_version { 3915 return Err(format!( 3916 "Cargo.lock package {package_name} version {} must match governed version {expected_version}", 3917 workspace_entries[0].version 3918 )); 3919 } 3920 } 3921 Ok(()) 3922 } 3923 3924 fn valid_release_change_id(value: &str) -> bool { 3925 !value.is_empty() 3926 && !value.starts_with('-') 3927 && !value.ends_with('-') 3928 && !value.contains("--") 3929 && value 3930 .bytes() 3931 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') 3932 } 3933 3934 fn validate_release_record( 3935 workspace_root: &Path, 3936 contract_version: &str, 3937 semver: &SemverRules, 3938 ) -> Result<(), String> { 3939 let current_version = parse_semver_version(contract_version)?; 3940 let releases_root = workspace_root.join(RELEASES_ROOT_RELATIVE); 3941 if !releases_root.is_dir() { 3942 return Err(format!( 3943 "release records directory {RELEASES_ROOT_RELATIVE} is required" 3944 )); 3945 } 3946 let record_relative = format!("{RELEASES_ROOT_RELATIVE}/{contract_version}.toml"); 3947 let record = parse_toml::<ReleaseRecord>(&workspace_root.join(&record_relative))?; 3948 if record.schema_version != 1 { 3949 return Err(format!( 3950 "release record {record_relative} schema_version must be 1" 3951 )); 3952 } 3953 if record.release.version != contract_version { 3954 return Err(format!( 3955 "release record version {} must match contract version {contract_version}", 3956 record.release.version 3957 )); 3958 } 3959 let previous_version = parse_semver_version(&record.release.previous_version)?; 3960 if record.release.previous_version == contract_version { 3961 return Err("release.previous_version must differ from release.version".to_string()); 3962 } 3963 if current_version <= previous_version { 3964 return Err(format!( 3965 "release version {contract_version} must be greater than previous version {}", 3966 record.release.previous_version 3967 )); 3968 } 3969 let contract_base_version = format!( 3970 "{}.{}.{}", 3971 current_version.major, current_version.minor, current_version.patch 3972 ); 3973 if record.release.contract_base_version != contract_base_version { 3974 return Err(format!( 3975 "release.contract_base_version {} must match contract base version {}", 3976 record.release.contract_base_version, contract_base_version 3977 )); 3978 } 3979 if !matches!( 3980 record.release.status.as_str(), 3981 "unreleased" | "released" | "yanked" 3982 ) { 3983 return Err(format!( 3984 "release.status {} must be unreleased, released, or yanked", 3985 record.release.status 3986 )); 3987 } 3988 3989 let mut expected_artifacts = vec![ 3990 ( 3991 record.artifacts.changelog.as_str(), 3992 CHANGELOG_RELATIVE, 3993 false, 3994 ), 3995 ( 3996 record.artifacts.manifest.as_str(), 3997 "contracts/manifest.toml", 3998 false, 3999 ), 4000 ( 4001 record.artifacts.operations.as_str(), 4002 "contracts/operations.toml", 4003 false, 4004 ), 4005 ( 4006 record.artifacts.replica.as_str(), 4007 REPLICA_CONTRACT_RELATIVE, 4008 false, 4009 ), 4010 ( 4011 record.artifacts.conformance.as_str(), 4012 CONFORMANCE_ROOT_RELATIVE, 4013 true, 4014 ), 4015 ( 4016 record.artifacts.publish_policy.as_str(), 4017 RELEASE_POLICY_RELATIVE, 4018 false, 4019 ), 4020 ]; 4021 if let Some(sqlite_runtime) = record.artifacts.sqlite_runtime.as_deref() { 4022 expected_artifacts.push((sqlite_runtime, SQLITE_RUNTIME_CONTRACT_RELATIVE, false)); 4023 } 4024 for (actual, expected, directory) in expected_artifacts { 4025 if actual != expected { 4026 return Err(format!( 4027 "release artifact path {actual} must use canonical path {expected}" 4028 )); 4029 } 4030 let path = workspace_root.join(actual); 4031 if directory && !path.is_dir() || !directory && !path.is_file() { 4032 return Err(format!("release artifact {actual} does not exist")); 4033 } 4034 } 4035 4036 if record.changes.is_empty() { 4037 return Err("release record must contain at least one change".to_string()); 4038 } 4039 let mut change_ids = BTreeSet::new(); 4040 let mut has_breaking_change = false; 4041 let major_impacts = semver 4042 .major_on 4043 .iter() 4044 .map(String::as_str) 4045 .collect::<BTreeSet<_>>(); 4046 let minor_impacts = semver 4047 .minor_on 4048 .iter() 4049 .map(String::as_str) 4050 .collect::<BTreeSet<_>>(); 4051 let patch_impacts = semver 4052 .patch_on 4053 .iter() 4054 .map(String::as_str) 4055 .collect::<BTreeSet<_>>(); 4056 for change in &record.changes { 4057 if !valid_release_change_id(&change.id) { 4058 return Err(format!( 4059 "release change id {} must use lowercase kebab-case", 4060 change.id 4061 )); 4062 } 4063 if !change_ids.insert(change.id.as_str()) { 4064 return Err(format!( 4065 "release record has duplicate change id {}", 4066 change.id 4067 )); 4068 } 4069 if !matches!( 4070 change.classification.as_str(), 4071 "breaking" | "feature" | "fix" | "deprecation" | "security" | "docs" 4072 ) { 4073 return Err(format!( 4074 "release change {} has unsupported classification {}", 4075 change.id, change.classification 4076 )); 4077 } 4078 has_breaking_change |= change.classification == "breaking"; 4079 if change.semver_impacts.is_empty() { 4080 return Err(format!( 4081 "release change {} must declare at least one exact semver impact", 4082 change.id 4083 )); 4084 } 4085 let mut change_impacts = BTreeSet::new(); 4086 let mut has_major_impact = false; 4087 let mut has_minor_impact = false; 4088 let mut has_patch_impact = false; 4089 for impact in &change.semver_impacts { 4090 if !change_impacts.insert(impact.as_str()) { 4091 return Err(format!( 4092 "release change {} has duplicate semver impact {impact}", 4093 change.id 4094 )); 4095 } 4096 if major_impacts.contains(impact.as_str()) { 4097 has_major_impact = true; 4098 } else if minor_impacts.contains(impact.as_str()) { 4099 has_minor_impact = true; 4100 } else if patch_impacts.contains(impact.as_str()) { 4101 has_patch_impact = true; 4102 } else { 4103 return Err(format!( 4104 "release change {} semver impact {impact} is not governed by contracts/version.toml", 4105 change.id 4106 )); 4107 } 4108 } 4109 let classification_matches = if has_major_impact { 4110 change.classification == "breaking" 4111 } else if has_minor_impact { 4112 matches!(change.classification.as_str(), "feature" | "deprecation") 4113 } else if has_patch_impact { 4114 matches!(change.classification.as_str(), "fix" | "security" | "docs") 4115 } else { 4116 false 4117 }; 4118 if !classification_matches { 4119 return Err(format!( 4120 "release change {} classification {} does not match its governed semver impacts", 4121 change.id, change.classification 4122 )); 4123 } 4124 if change.summary.trim().is_empty() { 4125 return Err(format!( 4126 "release change {} summary must not be empty", 4127 change.id 4128 )); 4129 } 4130 } 4131 if current_version.major != previous_version.major && !has_breaking_change { 4132 return Err("a major version transition requires a breaking release change".to_string()); 4133 } 4134 4135 let declares_registry_sqlite = change_ids.contains("registry-sqlite-provenance"); 4136 if declares_registry_sqlite != record.artifacts.sqlite_runtime.is_some() { 4137 return Err(format!( 4138 "release change registry-sqlite-provenance and artifact {SQLITE_RUNTIME_CONTRACT_RELATIVE} must be declared together" 4139 )); 4140 } 4141 if declares_registry_sqlite { 4142 validate_sqlite_runtime_contract(workspace_root)?; 4143 } 4144 4145 validate_changelog_release_notes(workspace_root, contract_version) 4146 } 4147 4148 fn validate_sqlite_runtime_contract(workspace_root: &Path) -> Result<(), String> { 4149 const PACKAGE_NAME: &str = "libsqlite3-sys"; 4150 const PACKAGE_VERSION: &str = "0.37.0"; 4151 const PACKAGE_SOURCE: &str = "registry+https://github.com/rust-lang/crates.io-index"; 4152 const ACTIVATION_ROUTE: [&str; 3] = [ 4153 "radroots_event_store/sqlite", 4154 "sqlx/sqlite-bundled", 4155 "libsqlite3-sys/bundled", 4156 ]; 4157 const FORBIDDEN_HIGH_LEVEL_DEPENDENCIES: [&str; 6] = [ 4158 "diesel", "refinery", "rusqlite", "sea-orm", "sqlite", "sqlite3", 4159 ]; 4160 const TEMPORARY_DIRECT_DEPENDENCIES: [&str; 0] = []; 4161 4162 let contract = parse_toml::<SqliteRuntimeContract>( 4163 &workspace_root.join(SQLITE_RUNTIME_CONTRACT_RELATIVE), 4164 )?; 4165 if contract.schema_version != 2 4166 || contract.package.name != PACKAGE_NAME 4167 || contract.package.version != PACKAGE_VERSION 4168 || contract.package.source != PACKAGE_SOURCE 4169 || contract.activation.route != ACTIVATION_ROUTE 4170 || contract.access.high_level_library != "sqlx" 4171 || contract.access.native_linkage_owner != "sqlx" 4172 || contract.access.native_linkage_package != PACKAGE_NAME 4173 || contract.access.maximum_native_linkages != 1 4174 || contract.access.forbidden_high_level_dependencies != FORBIDDEN_HIGH_LEVEL_DEPENDENCIES 4175 || contract.sealed_native_adapter.owner_package != "radroots_service_sqlite" 4176 || contract.sealed_native_adapter.relative_module 4177 != "crates/service_sqlite/src/sqlite_native_backup.rs" 4178 || contract.sealed_native_adapter.capability != "incremental_online_backup" 4179 || contract.sealed_native_adapter.status != "active" 4180 || contract.migration.owner != "rcld-rshr-045" 4181 || contract.migration.status != "in_progress" 4182 || contract.migration.temporary_direct_dependencies != TEMPORARY_DIRECT_DEPENDENCIES 4183 { 4184 return Err(format!( 4185 "{SQLITE_RUNTIME_CONTRACT_RELATIVE} must govern the exact SQLx access, native SQLite linkage, sealed-adapter, and RCLD-045 migration policy" 4186 )); 4187 } 4188 if contract.package.checksum.len() != 64 4189 || !contract 4190 .package 4191 .checksum 4192 .bytes() 4193 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) 4194 { 4195 return Err(format!( 4196 "{SQLITE_RUNTIME_CONTRACT_RELATIVE} package.checksum must be a lowercase SHA-256 digest" 4197 )); 4198 } 4199 4200 let lock = parse_toml::<CargoLockManifest>(&workspace_root.join("Cargo.lock"))?; 4201 let matches = lock 4202 .package 4203 .iter() 4204 .filter(|package| { 4205 package.name == contract.package.name 4206 && package.version == contract.package.version 4207 && package.source.as_deref() == Some(contract.package.source.as_str()) 4208 && package.checksum.as_deref() == Some(contract.package.checksum.as_str()) 4209 }) 4210 .count(); 4211 if matches != 1 { 4212 return Err(format!( 4213 "Cargo.lock must contain exactly one package matching {SQLITE_RUNTIME_CONTRACT_RELATIVE}" 4214 )); 4215 } 4216 4217 let native_linkages = lock 4218 .package 4219 .iter() 4220 .filter(|package| package.name == contract.access.native_linkage_package) 4221 .count(); 4222 if native_linkages != contract.access.maximum_native_linkages as usize { 4223 return Err(format!( 4224 "Cargo.lock must contain exactly {} {} native linkage", 4225 contract.access.maximum_native_linkages, contract.access.native_linkage_package 4226 )); 4227 } 4228 4229 let workspace = parse_toml::<WorkspaceCargoManifest>(&workspace_root.join("Cargo.toml"))?; 4230 for member in &workspace.workspace.members { 4231 let package = 4232 parse_toml::<PackageCargoManifest>(&workspace_root.join(member).join("Cargo.toml"))?; 4233 if package.package.name == PACKAGE_NAME { 4234 return Err(format!( 4235 "workspace member {member} must not vendor registry package {PACKAGE_NAME}" 4236 )); 4237 } 4238 } 4239 4240 let actual_temporary = sqlite_forbidden_direct_dependencies( 4241 workspace_root, 4242 &workspace.workspace.members, 4243 &contract.access.forbidden_high_level_dependencies, 4244 )?; 4245 let expected_temporary = contract 4246 .migration 4247 .temporary_direct_dependencies 4248 .iter() 4249 .cloned() 4250 .collect::<BTreeSet<_>>(); 4251 if actual_temporary != expected_temporary { 4252 return Err(format!( 4253 "{SQLITE_RUNTIME_CONTRACT_RELATIVE} temporary direct dependency inventory is stale: expected {expected_temporary:?}, found {actual_temporary:?}" 4254 )); 4255 } 4256 4257 let direct_native_dependencies = sqlite_direct_dependency_owners( 4258 workspace_root, 4259 &workspace.workspace.members, 4260 PACKAGE_NAME, 4261 )?; 4262 let expected_direct_native_dependencies = BTreeSet::from([ 4263 "radroots_service_sqlite:libsqlite3-sys".to_owned(), 4264 "workspace:libsqlite3-sys".to_owned(), 4265 ]); 4266 if direct_native_dependencies != expected_direct_native_dependencies { 4267 return Err(format!( 4268 "direct {PACKAGE_NAME} access must be limited to the sealed adapter owner: expected {expected_direct_native_dependencies:?}, found {direct_native_dependencies:?}" 4269 )); 4270 } 4271 validate_sqlite_native_adapter_source(workspace_root, &contract.sealed_native_adapter)?; 4272 4273 let storage_sqlite = 4274 fs::read_to_string(workspace_root.join("crates/storage_sqlite/Cargo.toml")) 4275 .map_err(|error| format!("read crates/storage_sqlite/Cargo.toml: {error}"))?; 4276 let storage_sqlite: toml::Value = toml::from_str(&storage_sqlite) 4277 .map_err(|error| format!("parse crates/storage_sqlite/Cargo.toml: {error}"))?; 4278 let sqlite_features = storage_sqlite 4279 .get("dependencies") 4280 .and_then(|dependencies| dependencies.get("sqlx")) 4281 .and_then(|sqlx| sqlx.get("features")) 4282 .and_then(toml::Value::as_array) 4283 .ok_or_else(|| { 4284 "crates/storage_sqlite/Cargo.toml dependencies.sqlx.features is required".to_string() 4285 })?; 4286 if !sqlite_features 4287 .iter() 4288 .any(|feature| feature.as_str() == Some("sqlite-bundled")) 4289 { 4290 return Err( 4291 "crates/storage_sqlite/Cargo.toml dependencies.sqlx.features must activate sqlite-bundled" 4292 .to_string(), 4293 ); 4294 } 4295 Ok(()) 4296 } 4297 4298 fn validate_sqlite_native_adapter_source( 4299 workspace_root: &Path, 4300 adapter: &SqliteRuntimeSealedNativeAdapter, 4301 ) -> Result<(), String> { 4302 let adapter_path = workspace_root.join(&adapter.relative_module); 4303 let adapter_source = fs::read_to_string(&adapter_path) 4304 .map_err(|error| format!("read {}: {error}", adapter_path.display()))?; 4305 for required in [ 4306 "use libsqlite3_sys as ffi;", 4307 "LockedSqliteHandle", 4308 "ffi::sqlite3_backup_init", 4309 "ffi::sqlite3_backup_step", 4310 "ffi::sqlite3_backup_finish", 4311 ] { 4312 if !adapter_source.contains(required) { 4313 return Err(format!( 4314 "{} must contain the sealed native adapter boundary `{required}`", 4315 adapter_path.display() 4316 )); 4317 } 4318 } 4319 4320 let source_root = workspace_root.join("crates/service_sqlite/src"); 4321 for entry in WalkDir::new(&source_root).follow_links(false) { 4322 let entry = entry.map_err(|error| format!("walk {}: {error}", source_root.display()))?; 4323 if !entry.file_type().is_file() 4324 || entry 4325 .path() 4326 .extension() 4327 .and_then(|extension| extension.to_str()) 4328 != Some("rs") 4329 || entry.path() == adapter_path 4330 { 4331 continue; 4332 } 4333 let source = fs::read_to_string(entry.path()) 4334 .map_err(|error| format!("read {}: {error}", entry.path().display()))?; 4335 for forbidden in [ 4336 "libsqlite3_sys", 4337 "sqlite3_backup_", 4338 "unsafe {", 4339 "unsafe fn ", 4340 "unsafe impl ", 4341 ] { 4342 if source.contains(forbidden) { 4343 return Err(format!( 4344 "{} contains native SQLite or unsafe authority outside the sealed adapter: `{forbidden}`", 4345 entry.path().display() 4346 )); 4347 } 4348 } 4349 } 4350 Ok(()) 4351 } 4352 4353 fn sqlite_forbidden_direct_dependencies( 4354 workspace_root: &Path, 4355 members: &[String], 4356 forbidden: &[String], 4357 ) -> Result<BTreeSet<String>, String> { 4358 let forbidden = forbidden 4359 .iter() 4360 .map(String::as_str) 4361 .collect::<BTreeSet<_>>(); 4362 sqlite_direct_dependencies_matching(workspace_root, members, |dependency| { 4363 forbidden.contains(dependency) 4364 }) 4365 } 4366 4367 fn sqlite_direct_dependency_owners( 4368 workspace_root: &Path, 4369 members: &[String], 4370 dependency: &str, 4371 ) -> Result<BTreeSet<String>, String> { 4372 sqlite_direct_dependencies_matching(workspace_root, members, |candidate| { 4373 candidate == dependency 4374 }) 4375 } 4376 4377 fn sqlite_direct_dependencies_matching( 4378 workspace_root: &Path, 4379 members: &[String], 4380 matches: impl Fn(&str) -> bool, 4381 ) -> Result<BTreeSet<String>, String> { 4382 let mut found = BTreeSet::new(); 4383 let workspace_manifest = parse_toml::<toml::Value>(&workspace_root.join("Cargo.toml"))?; 4384 if let Some(dependencies) = workspace_manifest 4385 .get("workspace") 4386 .and_then(|workspace| workspace.get("dependencies")) 4387 .and_then(toml::Value::as_table) 4388 { 4389 collect_matching_dependencies("workspace", dependencies, &matches, &mut found); 4390 } 4391 4392 for member in members { 4393 let path = workspace_root.join(member).join("Cargo.toml"); 4394 let manifest = parse_toml::<toml::Value>(&path)?; 4395 let owner = manifest 4396 .get("package") 4397 .and_then(|package| package.get("name")) 4398 .and_then(toml::Value::as_str) 4399 .ok_or_else(|| format!("{} package.name is required", path.display()))?; 4400 for section in ["dependencies", "dev-dependencies", "build-dependencies"] { 4401 if let Some(dependencies) = manifest.get(section).and_then(toml::Value::as_table) { 4402 collect_matching_dependencies(owner, dependencies, &matches, &mut found); 4403 } 4404 } 4405 if let Some(targets) = manifest.get("target").and_then(toml::Value::as_table) { 4406 for target in targets.values().filter_map(toml::Value::as_table) { 4407 for section in ["dependencies", "dev-dependencies", "build-dependencies"] { 4408 if let Some(dependencies) = target.get(section).and_then(toml::Value::as_table) 4409 { 4410 collect_matching_dependencies(owner, dependencies, &matches, &mut found); 4411 } 4412 } 4413 } 4414 } 4415 } 4416 Ok(found) 4417 } 4418 4419 fn collect_matching_dependencies( 4420 owner: &str, 4421 dependencies: &toml::map::Map<String, toml::Value>, 4422 matches: &impl Fn(&str) -> bool, 4423 found: &mut BTreeSet<String>, 4424 ) { 4425 for (alias, specification) in dependencies { 4426 let package = specification 4427 .as_table() 4428 .and_then(|table| table.get("package")) 4429 .and_then(toml::Value::as_str) 4430 .unwrap_or(alias); 4431 if matches(package) { 4432 found.insert(format!("{owner}:{package}")); 4433 } 4434 } 4435 } 4436 4437 fn validate_changelog_release_notes( 4438 workspace_root: &Path, 4439 contract_version: &str, 4440 ) -> Result<(), String> { 4441 let path = workspace_root.join(CHANGELOG_RELATIVE); 4442 let raw = 4443 fs::read_to_string(&path).map_err(|error| format!("read {}: {error}", path.display()))?; 4444 let heading = format!("## [{contract_version}]"); 4445 let mut in_release = false; 4446 let mut has_release_note = false; 4447 for line in raw.lines() { 4448 let trimmed = line.trim(); 4449 if trimmed == heading { 4450 if in_release { 4451 return Err(format!( 4452 "{CHANGELOG_RELATIVE} contains duplicate heading {heading}" 4453 )); 4454 } 4455 in_release = true; 4456 continue; 4457 } 4458 if in_release && trimmed.starts_with("## [") { 4459 break; 4460 } 4461 if in_release && trimmed.starts_with("- ") && trimmed.len() > 2 { 4462 has_release_note = true; 4463 } 4464 } 4465 if !in_release { 4466 return Err(format!("{CHANGELOG_RELATIVE} is missing heading {heading}")); 4467 } 4468 if !has_release_note { 4469 return Err(format!( 4470 "{CHANGELOG_RELATIVE} release {contract_version} must contain at least one note" 4471 )); 4472 } 4473 Ok(()) 4474 } 4475 4476 fn validate_conformance_vector_mirrors(workspace_root: &Path) -> Result<(), String> { 4477 for (canonical_relative, mirror_relative) in CONFORMANCE_VECTOR_MIRRORS { 4478 let canonical = fs::read(workspace_root.join(canonical_relative)) 4479 .map_err(|error| format!("read {canonical_relative}: {error}"))?; 4480 let mirror = fs::read(workspace_root.join(mirror_relative)) 4481 .map_err(|error| format!("read {mirror_relative}: {error}"))?; 4482 if canonical != mirror { 4483 return Err(format!( 4484 "packaged conformance mirror {mirror_relative} must exactly match {canonical_relative}" 4485 )); 4486 } 4487 } 4488 Ok(()) 4489 } 4490 4491 fn validate_version_governance( 4492 bundle: &ContractBundle, 4493 workspace_root: &Path, 4494 ) -> Result<(), String> { 4495 validate_contract_version_lockstep(bundle)?; 4496 let version = bundle.manifest.contract.version.as_str(); 4497 validate_workspace_version_lockstep(workspace_root, version)?; 4498 validate_release_record(workspace_root, version, &bundle.version.semver)?; 4499 validate_conformance_vector_mirrors(workspace_root) 4500 } 4501 4502 fn validate_conformance_directory(workspace_root: &Path, dir: &Path) -> Result<(), String> { 4503 let relative = dir.strip_prefix(workspace_root).map_err(|error| { 4504 format!( 4505 "conformance inventory directory {} is outside workspace root {}: {error}", 4506 dir.display(), 4507 workspace_root.display() 4508 ) 4509 })?; 4510 let mut current = workspace_root.to_path_buf(); 4511 validate_real_conformance_directory(¤t)?; 4512 for component in relative.components() { 4513 let std::path::Component::Normal(segment) = component else { 4514 return Err(format!( 4515 "conformance inventory directory must be workspace-relative and normalized: {}", 4516 dir.display() 4517 )); 4518 }; 4519 current.push(segment); 4520 validate_real_conformance_directory(¤t)?; 4521 } 4522 Ok(()) 4523 } 4524 4525 fn validate_real_conformance_directory(path: &Path) -> Result<(), String> { 4526 let metadata = fs::symlink_metadata(path) 4527 .map_err(|error| format!("inspect conformance inventory {}: {error}", path.display()))?; 4528 if metadata.file_type().is_symlink() { 4529 return Err(format!( 4530 "conformance inventory directory contains a symlink: {}", 4531 path.display() 4532 )); 4533 } 4534 if !metadata.is_dir() { 4535 return Err(format!( 4536 "conformance inventory path must be a directory: {}", 4537 path.display() 4538 )); 4539 } 4540 Ok(()) 4541 } 4542 4543 fn collect_conformance_vector_paths( 4544 workspace_root: &Path, 4545 dir: &Path, 4546 paths: &mut Vec<PathBuf>, 4547 ) -> Result<(), String> { 4548 validate_conformance_directory(workspace_root, dir)?; 4549 let read_dir = match fs::read_dir(dir) { 4550 Ok(read_dir) => read_dir, 4551 Err(e) => return Err(format!("read dir {}: {e}", dir.display())), 4552 }; 4553 let mut entries = read_dir 4554 .collect::<Result<Vec<_>, _>>() 4555 .map_err(|error| format!("read dir {}: {error}", dir.display()))?; 4556 entries.sort_by_key(|entry| entry.file_name()); 4557 for entry in entries { 4558 let path = entry.path(); 4559 let file_type = entry 4560 .file_type() 4561 .map_err(|error| format!("inspect conformance entry {}: {error}", path.display()))?; 4562 if file_type.is_symlink() { 4563 return Err(format!( 4564 "conformance inventory entry must not be a symlink: {}", 4565 path.display() 4566 )); 4567 } 4568 if file_type.is_dir() { 4569 collect_conformance_vector_paths(workspace_root, &path, paths)?; 4570 } else if !file_type.is_file() { 4571 return Err(format!( 4572 "conformance inventory entry must be a regular file or a directory: {}", 4573 path.display() 4574 )); 4575 } else if path.extension().and_then(|ext| ext.to_str()) == Some("json") { 4576 paths.push(path); 4577 } 4578 } 4579 Ok(()) 4580 } 4581 4582 fn validate_conformance_vector_file( 4583 path: &Path, 4584 contract_version: &str, 4585 ) -> Result<ConformanceVectorFile, String> { 4586 let vector = parse_json::<ConformanceVectorFile>(path)?; 4587 if vector.suite.trim().is_empty() { 4588 return Err(format!( 4589 "conformance vector {} suite must not be empty", 4590 path.display() 4591 )); 4592 } 4593 if vector.vectors.is_empty() { 4594 return Err(format!( 4595 "conformance vector {} must contain at least one vector", 4596 path.display() 4597 )); 4598 } 4599 if vector.contract_version != base_contract_version(contract_version) { 4600 return Err(format!( 4601 "conformance vector {} version {} must match contract version {}", 4602 path.display(), 4603 vector.contract_version, 4604 base_contract_version(contract_version) 4605 )); 4606 } 4607 let mut ids = BTreeSet::new(); 4608 for entry in &vector.vectors { 4609 if entry.id.trim().is_empty() || entry.kind.trim().is_empty() { 4610 return Err(format!( 4611 "conformance vector {} entries must define non-empty id and kind", 4612 path.display() 4613 )); 4614 } 4615 if !ids.insert(entry.id.clone()) { 4616 return Err(format!( 4617 "conformance vector {} has duplicate vector id {}", 4618 path.display(), 4619 entry.id 4620 )); 4621 } 4622 match (&entry.expected, &entry.expected_error_contains) { 4623 (Some(_), None) => {} 4624 (None, Some(fragment)) if !fragment.trim().is_empty() => {} 4625 (None, Some(_)) => { 4626 return Err(format!( 4627 "conformance vector {} entry {} expected_error_contains must not be blank", 4628 path.display(), 4629 entry.id 4630 )); 4631 } 4632 _ => { 4633 return Err(format!( 4634 "conformance vector {} entry {} must define exactly one of expected or expected_error_contains", 4635 path.display(), 4636 entry.id 4637 )); 4638 } 4639 } 4640 } 4641 Ok(vector) 4642 } 4643 4644 fn validate_all_conformance_vectors( 4645 workspace_root: &Path, 4646 contract_version: &str, 4647 ) -> Result<(), String> { 4648 let vectors_dir = conformance_root(workspace_root).join("vectors"); 4649 if !vectors_dir.is_dir() { 4650 return validate_missing_conformance_vectors(workspace_root, &vectors_dir); 4651 } 4652 let mut paths = Vec::new(); 4653 collect_conformance_vector_paths(workspace_root, &vectors_dir, &mut paths)?; 4654 if paths.is_empty() { 4655 return Err(format!( 4656 "conformance vectors directory {} must contain JSON vectors", 4657 vectors_dir.display() 4658 )); 4659 } 4660 let canonical_comment_path = workspace_root.join(COMMENT_CONFORMANCE_VECTOR_RELATIVE); 4661 let canonical_deletion_path = workspace_root.join(DELETION_CONFORMANCE_VECTOR_RELATIVE); 4662 let canonical_deletion_suppression_path = 4663 workspace_root.join(DELETION_SUPPRESSION_CONFORMANCE_VECTOR_RELATIVE); 4664 for path in paths { 4665 let vector = validate_conformance_vector_file(&path, contract_version)?; 4666 validate_comment_vector_namespace(&path, &canonical_comment_path, &vector)?; 4667 validate_deletion_vector_namespace( 4668 &path, 4669 &canonical_deletion_path, 4670 &canonical_deletion_suppression_path, 4671 &vector, 4672 )?; 4673 } 4674 Ok(()) 4675 } 4676 4677 fn validate_deletion_vector_namespace( 4678 path: &Path, 4679 canonical_request_path: &Path, 4680 canonical_suppression_path: &Path, 4681 vector: &ConformanceVectorFile, 4682 ) -> Result<(), String> { 4683 if path == canonical_request_path || path == canonical_suppression_path { 4684 return Ok(()); 4685 } 4686 if let Some(entry) = vector 4687 .vectors 4688 .iter() 4689 .find(|entry| entry.kind.starts_with("social.deletion_request.")) 4690 { 4691 return Err(format!( 4692 "deletion conformance case kind {} in {} is outside canonical vectors {} and {}", 4693 entry.kind, 4694 path.display(), 4695 canonical_request_path.display(), 4696 canonical_suppression_path.display() 4697 )); 4698 } 4699 Ok(()) 4700 } 4701 4702 fn validate_comment_vector_namespace( 4703 path: &Path, 4704 canonical_path: &Path, 4705 vector: &ConformanceVectorFile, 4706 ) -> Result<(), String> { 4707 if path == canonical_path { 4708 return Ok(()); 4709 } 4710 if let Some(entry) = vector 4711 .vectors 4712 .iter() 4713 .find(|entry| entry.kind.starts_with("social.comment.")) 4714 { 4715 return Err(format!( 4716 "comment conformance case kind {} in {} is outside canonical vector {}", 4717 entry.kind, 4718 path.display(), 4719 canonical_path.display() 4720 )); 4721 } 4722 Ok(()) 4723 } 4724 4725 pub fn write_knowledge_contract_manifest(workspace_root: &Path) -> Result<(), String> { 4726 let manifest_json = write_knowledge_contract_manifest_artifacts(workspace_root)?; 4727 validate_knowledge_contract_manifest_context(workspace_root, &manifest_json) 4728 } 4729 4730 pub fn validate_knowledge_contract_manifest(workspace_root: &Path) -> Result<(), String> { 4731 let manifest_json = validate_knowledge_contract_manifest_artifacts(workspace_root)?; 4732 validate_knowledge_contract_manifest_context(workspace_root, &manifest_json) 4733 } 4734 4735 fn write_knowledge_contract_manifest_artifacts(workspace_root: &Path) -> Result<String, String> { 4736 with_artifact_bundle_transaction(workspace_root, |transaction| { 4737 let manifest_json = expected_knowledge_contract_manifest_json()?; 4738 let manifest_sha256 = expected_knowledge_contract_manifest_sha256()?; 4739 transaction.write(vec![ 4740 GeneratedArtifact { 4741 relative: KNOWLEDGE_MANIFEST_RELATIVE, 4742 contents: manifest_json.into_bytes(), 4743 }, 4744 GeneratedArtifact { 4745 relative: KNOWLEDGE_MANIFEST_SHA256_RELATIVE, 4746 contents: format!("{manifest_sha256}\n").into_bytes(), 4747 }, 4748 ])?; 4749 validate_knowledge_contract_manifest_artifacts_under_lock(workspace_root) 4750 }) 4751 } 4752 4753 fn validate_knowledge_contract_manifest_artifacts(workspace_root: &Path) -> Result<String, String> { 4754 with_artifact_bundle_transaction(workspace_root, |_| { 4755 validate_knowledge_contract_manifest_artifacts_under_lock(workspace_root) 4756 }) 4757 } 4758 4759 fn validate_knowledge_contract_manifest_artifacts_under_lock( 4760 workspace_root: &Path, 4761 ) -> Result<String, String> { 4762 let expected_json = expected_knowledge_contract_manifest_json()?; 4763 let expected_sha256 = expected_knowledge_contract_manifest_sha256()?; 4764 let actual_json = read_regular_file(workspace_root, KNOWLEDGE_MANIFEST_RELATIVE)?; 4765 let actual_sha256 = read_regular_file(workspace_root, KNOWLEDGE_MANIFEST_SHA256_RELATIVE)?; 4766 let actual_json_text = std::str::from_utf8(&actual_json) 4767 .map_err(|error| format!("{KNOWLEDGE_MANIFEST_RELATIVE} must be UTF-8 JSON: {error}"))?; 4768 let parsed = 4769 radroots_event_codec::manifest::parse_knowledge_contract_manifest_json(actual_json_text) 4770 .map_err(|error| format!("parse {KNOWLEDGE_MANIFEST_RELATIVE}: {error}"))?; 4771 4772 validate_knowledge_contract_manifest_shape(&parsed)?; 4773 validate_canonical_json_artifact(KNOWLEDGE_MANIFEST_RELATIVE, &actual_json)?; 4774 validate_sha256_artifact(KNOWLEDGE_MANIFEST_SHA256_RELATIVE, &actual_sha256)?; 4775 4776 if actual_json != expected_json.as_bytes() { 4777 return Err(stale_knowledge_manifest_error(KNOWLEDGE_MANIFEST_RELATIVE)); 4778 } 4779 if actual_sha256 != format!("{expected_sha256}\n").as_bytes() { 4780 return Err(stale_knowledge_manifest_error( 4781 KNOWLEDGE_MANIFEST_SHA256_RELATIVE, 4782 )); 4783 } 4784 if parsed != radroots_event_codec::manifest::knowledge_contract_manifest() { 4785 return Err(stale_knowledge_manifest_error(KNOWLEDGE_MANIFEST_RELATIVE)); 4786 } 4787 4788 Ok(actual_json_text.to_owned()) 4789 } 4790 4791 fn expected_knowledge_contract_manifest_json() -> Result<String, String> { 4792 let expected_json = radroots_event_codec::manifest::contract_manifest_json() 4793 .map_err(|error| format!("serialize knowledge contract manifest: {error}"))?; 4794 Ok(expected_json) 4795 } 4796 4797 fn expected_knowledge_contract_manifest_sha256() -> Result<String, String> { 4798 radroots_event_codec::manifest::contract_manifest_sha256() 4799 .map_err(|error| format!("hash knowledge contract manifest: {error}")) 4800 } 4801 4802 fn validate_knowledge_contract_manifest_shape( 4803 manifest: &radroots_event_codec::manifest::RadrootsKnowledgeContractManifest, 4804 ) -> Result<(), String> { 4805 if manifest.schema_version 4806 != radroots_event_codec::manifest::RADROOTS_KNOWLEDGE_CONTRACT_MANIFEST_SCHEMA_VERSION 4807 { 4808 return Err(format!( 4809 "{KNOWLEDGE_MANIFEST_RELATIVE} schema_version must be {}", 4810 radroots_event_codec::manifest::RADROOTS_KNOWLEDGE_CONTRACT_MANIFEST_SCHEMA_VERSION 4811 )); 4812 } 4813 if manifest.registry_version 4814 != radroots_event_codec::manifest::registry_v7::RADROOTS_EVENT_CONTRACT_REGISTRY_V7_VERSION 4815 { 4816 return Err(format!( 4817 "{KNOWLEDGE_MANIFEST_RELATIVE} registry_version must be {}", 4818 radroots_event_codec::manifest::registry_v7::RADROOTS_EVENT_CONTRACT_REGISTRY_V7_VERSION 4819 )); 4820 } 4821 if manifest.contract_count != manifest.contracts.len() { 4822 return Err(format!( 4823 "{KNOWLEDGE_MANIFEST_RELATIVE} contract_count must match its contract inventory" 4824 )); 4825 } 4826 if manifest 4827 .contracts 4828 .windows(2) 4829 .any(|pair| pair[0].contract_id >= pair[1].contract_id) 4830 { 4831 return Err(format!( 4832 "{KNOWLEDGE_MANIFEST_RELATIVE} contract IDs must be unique and strictly sorted" 4833 )); 4834 } 4835 Ok(()) 4836 } 4837 4838 fn stale_knowledge_manifest_error(relative: &str) -> String { 4839 format!("{relative} is stale; run `{KNOWLEDGE_MANIFEST_WRITE_COMMAND}`") 4840 } 4841 4842 fn validate_knowledge_contract_manifest_context( 4843 workspace_root: &Path, 4844 manifest_json: &str, 4845 ) -> Result<(), String> { 4846 validate_knowledge_manifest_witnesses(workspace_root, manifest_json)?; 4847 validate_knowledge_conformance_vector_inventory(workspace_root)?; 4848 4849 let bundle = load_contract_bundle(workspace_root)?; 4850 let knowledge_manifest_vector = validate_conformance_vector_file( 4851 &workspace_root.join(KNOWLEDGE_MANIFEST_AND_DECODE_RELATIVE), 4852 &bundle.manifest.contract.version, 4853 )?; 4854 validate_knowledge_manifest_vector_semantics(manifest_json, &knowledge_manifest_vector)?; 4855 validate_conformance_vector_file( 4856 &workspace_root.join(KNOWLEDGE_PUBLIC_SURFACE_RELATIVE), 4857 &bundle.manifest.contract.version, 4858 )?; 4859 Ok(()) 4860 } 4861 4862 fn validate_knowledge_manifest_vector_semantics( 4863 manifest_json: &str, 4864 vector: &ConformanceVectorFile, 4865 ) -> Result<(), String> { 4866 let manifest = serde_json::from_str::<Value>(manifest_json) 4867 .map_err(|error| format!("parse knowledge manifest JSON: {error}"))?; 4868 let schema_version = manifest 4869 .get("schema_version") 4870 .and_then(Value::as_u64) 4871 .ok_or_else(|| { 4872 "knowledge manifest schema_version must be an unsigned integer".to_string() 4873 })?; 4874 let registry_version = manifest 4875 .get("registry_version") 4876 .and_then(Value::as_u64) 4877 .ok_or_else(|| { 4878 "knowledge manifest registry_version must be an unsigned integer".to_string() 4879 })?; 4880 let case = vector 4881 .vectors 4882 .iter() 4883 .find(|entry| entry.id == "knowledge_manifest_fields_valid_001") 4884 .ok_or_else(|| { 4885 "knowledge manifest conformance must define knowledge_manifest_fields_valid_001" 4886 .to_string() 4887 })?; 4888 if case.kind != "knowledge.contract_manifest_json.valid" { 4889 return Err(format!( 4890 "knowledge manifest conformance case kind drift: expected knowledge.contract_manifest_json.valid, got {}", 4891 case.kind 4892 )); 4893 } 4894 4895 let expected_registry_marker = format!("radroots_event_contract_registry_v{registry_version}"); 4896 let actual_registry_marker = case.input.get("registry").and_then(Value::as_str); 4897 if actual_registry_marker != Some(expected_registry_marker.as_str()) { 4898 return Err(format!( 4899 "knowledge manifest conformance registry marker drift: expected {expected_registry_marker}, got {}", 4900 actual_registry_marker.unwrap_or("<missing-or-non-string>") 4901 )); 4902 } 4903 4904 for (field, expected) in [ 4905 ("schema_version", schema_version), 4906 ("registry_version", registry_version), 4907 ] { 4908 let actual = case.expected_value()?.get(field).and_then(Value::as_u64); 4909 if actual != Some(expected) { 4910 return Err(format!( 4911 "knowledge manifest conformance expected {field} drift: expected {expected}, got {}", 4912 actual 4913 .map(|value| value.to_string()) 4914 .unwrap_or_else(|| "<missing-or-non-integer>".to_string()) 4915 )); 4916 } 4917 } 4918 Ok(()) 4919 } 4920 4921 fn validate_knowledge_conformance_vector_inventory(workspace_root: &Path) -> Result<(), String> { 4922 let expected = BTreeSet::from([ 4923 KNOWLEDGE_MANIFEST_AND_DECODE_RELATIVE.to_owned(), 4924 KNOWLEDGE_PUBLIC_SURFACE_RELATIVE.to_owned(), 4925 ]); 4926 let mut paths = Vec::new(); 4927 collect_conformance_vector_paths( 4928 workspace_root, 4929 &workspace_root.join("contracts/conformance/vectors/knowledge"), 4930 &mut paths, 4931 )?; 4932 let mut actual = BTreeSet::new(); 4933 for path in paths { 4934 let relative = path.strip_prefix(workspace_root).map_err(|error| { 4935 format!( 4936 "knowledge conformance vector {} is outside workspace root {}: {error}", 4937 path.display(), 4938 workspace_root.display() 4939 ) 4940 })?; 4941 actual.insert(relative.to_string_lossy().replace('\\', "/")); 4942 } 4943 if actual != expected { 4944 return Err(format!( 4945 "knowledge conformance vector inventory mismatch: expected {:?}, found {:?}", 4946 expected, actual 4947 )); 4948 } 4949 Ok(()) 4950 } 4951 4952 fn validate_knowledge_manifest_witnesses( 4953 workspace_root: &Path, 4954 actual_json: &str, 4955 ) -> Result<(), String> { 4956 for relative in legacy_knowledge_manifest_relatives() { 4957 let path = workspace_root.join(&relative); 4958 if path.exists() { 4959 return Err(format!( 4960 "stale knowledge manifest artifact remains at {}", 4961 relative 4962 )); 4963 } 4964 } 4965 4966 let value = serde_json::from_str::<Value>(actual_json) 4967 .map_err(|error| format!("parse knowledge manifest JSON: {error}"))?; 4968 if value.get("schema_version").and_then(Value::as_u64) != Some(2) { 4969 return Err("knowledge manifest schema_version must be 2".to_string()); 4970 } 4971 let contracts = value 4972 .get("contracts") 4973 .and_then(Value::as_array) 4974 .ok_or_else(|| "knowledge manifest contracts must be an array".to_string())?; 4975 let mut previous_id: Option<String> = None; 4976 let mut ids = BTreeSet::new(); 4977 4978 for contract in contracts { 4979 let contract_id = contract 4980 .get("contract_id") 4981 .and_then(Value::as_str) 4982 .ok_or_else(|| "knowledge manifest entry missing contract_id".to_string())?; 4983 if let Some(previous) = previous_id.as_deref() 4984 && previous > contract_id 4985 { 4986 return Err("knowledge manifest contracts must be sorted by contract_id".to_string()); 4987 } 4988 previous_id = Some(contract_id.to_string()); 4989 if !ids.insert(contract_id.to_string()) { 4990 return Err(format!( 4991 "knowledge manifest has duplicate contract id {contract_id}" 4992 )); 4993 } 4994 4995 if contract.get("stability").and_then(Value::as_str) != Some("experimental") { 4996 return Err(format!( 4997 "knowledge manifest contract {contract_id} must be experimental" 4998 )); 4999 } 5000 if contract_id == "radroots.wiki.merge_request.v1" 5001 && contract.get("content_schema").and_then(Value::as_str) != Some("plain_text") 5002 { 5003 return Err( 5004 "wiki merge request manifest content_schema must be plain_text".to_string(), 5005 ); 5006 } 5007 5008 let sdk_builder_support = manifest_bool_field(contract, "sdk_builder_support")?; 5009 let sdk_draft_support = manifest_bool_field(contract, "sdk_draft_support")?; 5010 let wasm_tag_builder_support = manifest_bool_field(contract, "wasm_tag_builder_support")?; 5011 let wasm_verified_decode_support = 5012 manifest_bool_field(contract, "wasm_verified_decode_support")?; 5013 5014 if KNOWLEDGE_MVP_SUPPORT_CONTRACT_IDS.contains(&contract_id) 5015 && (!sdk_builder_support || !sdk_draft_support || !wasm_tag_builder_support) 5016 { 5017 return Err(format!( 5018 "knowledge manifest MVP contract {contract_id} must report SDK and WASM tag support" 5019 )); 5020 } 5021 if KNOWLEDGE_BETA_CONTRACT_IDS.contains(&contract_id) 5022 && (sdk_builder_support || sdk_draft_support || wasm_tag_builder_support) 5023 { 5024 return Err(format!( 5025 "knowledge manifest beta contract {contract_id} must not overclaim builder support" 5026 )); 5027 } 5028 if !wasm_verified_decode_support { 5029 return Err(format!( 5030 "knowledge manifest contract {contract_id} must report WASM verified decode support" 5031 )); 5032 } 5033 } 5034 5035 for contract_id in KNOWLEDGE_MVP_SUPPORT_CONTRACT_IDS 5036 .iter() 5037 .chain(KNOWLEDGE_BETA_CONTRACT_IDS.iter()) 5038 { 5039 if !ids.contains(*contract_id) { 5040 return Err(format!( 5041 "knowledge manifest missing required contract {contract_id}" 5042 )); 5043 } 5044 } 5045 5046 Ok(()) 5047 } 5048 5049 fn legacy_knowledge_manifest_relatives() -> [String; 2] { 5050 [ 5051 KNOWLEDGE_MANIFEST_RELATIVE.replace(".v2.", ".v1."), 5052 KNOWLEDGE_MANIFEST_SHA256_RELATIVE.replace(".v2.", ".v1."), 5053 ] 5054 } 5055 5056 fn manifest_bool_field(contract: &Value, field: &str) -> Result<bool, String> { 5057 contract 5058 .get(field) 5059 .and_then(Value::as_bool) 5060 .ok_or_else(|| format!("knowledge manifest entry missing boolean field {field}")) 5061 } 5062 5063 #[cfg(not(test))] 5064 fn validate_missing_conformance_vectors( 5065 _workspace_root: &Path, 5066 vectors_dir: &Path, 5067 ) -> Result<(), String> { 5068 Err(format!( 5069 "conformance vectors directory {} must exist", 5070 vectors_dir.display() 5071 )) 5072 } 5073 5074 #[cfg(test)] 5075 #[cfg_attr(coverage_nightly, coverage(off))] 5076 fn validate_missing_conformance_vectors( 5077 _workspace_root: &Path, 5078 _vectors_dir: &Path, 5079 ) -> Result<(), String> { 5080 Ok(()) 5081 } 5082 5083 #[derive(Debug)] 5084 struct WorkspacePackageRecord { 5085 name: String, 5086 #[cfg_attr(not(test), allow(dead_code))] 5087 manifest_path: PathBuf, 5088 publish_enabled: bool, 5089 publish: Option<PackagePublish>, 5090 manifest_value: toml::Value, 5091 } 5092 5093 fn workspace_package_records(workspace_root: &Path) -> Result<Vec<WorkspacePackageRecord>, String> { 5094 let workspace_manifest = 5095 parse_toml::<WorkspaceCargoManifest>(&workspace_root.join("Cargo.toml"))?; 5096 let mut records = Vec::with_capacity(workspace_manifest.workspace.members.len()); 5097 for member in workspace_manifest.workspace.members { 5098 let manifest_path = workspace_root.join(&member).join("Cargo.toml"); 5099 let raw = match fs::read_to_string(&manifest_path) { 5100 Ok(raw) => raw, 5101 Err(e) => return Err(format!("read {}: {e}", manifest_path.display())), 5102 }; 5103 let manifest_value = match toml::from_str::<toml::Value>(&raw) { 5104 Ok(value) => value, 5105 Err(e) => return Err(format!("parse {}: {e}", manifest_path.display())), 5106 }; 5107 let package_manifest = match toml::from_str::<PackageCargoManifest>(&raw) { 5108 Ok(manifest) => manifest, 5109 Err(e) => return Err(format!("parse {}: {e}", manifest_path.display())), 5110 }; 5111 let name = package_manifest.package.name; 5112 let publish_enabled = package_publish_enabled(package_manifest.package.publish.as_ref()); 5113 let publish = package_manifest.package.publish.clone(); 5114 records.push(WorkspacePackageRecord { 5115 name, 5116 manifest_path, 5117 publish_enabled, 5118 publish, 5119 manifest_value, 5120 }); 5121 } 5122 Ok(records) 5123 } 5124 5125 fn workspace_package_names(workspace_root: &Path) -> Result<Vec<String>, String> { 5126 Ok(workspace_package_records(workspace_root)? 5127 .into_iter() 5128 .map(|record| record.name) 5129 .collect()) 5130 } 5131 5132 fn coverage_required_workspace_crates(workspace_root: &Path) -> Result<BTreeSet<String>, String> { 5133 let names = workspace_package_names(workspace_root)? 5134 .into_iter() 5135 .filter(|crate_name| !coverage_policy_excludes_workspace_crate(crate_name)) 5136 .collect::<Vec<_>>(); 5137 collect_unique_set(&names, "workspace coverage crates") 5138 } 5139 5140 fn coverage_policy_excludes_workspace_crate(crate_name: &str) -> bool { 5141 crate_name.contains("_simplex_") || crate_name.starts_with("simplex_") 5142 } 5143 5144 #[cfg_attr(not(test), allow(dead_code))] 5145 fn workspace_package_manifests(workspace_root: &Path) -> Result<BTreeMap<String, PathBuf>, String> { 5146 let mut manifests = BTreeMap::new(); 5147 for record in workspace_package_records(workspace_root)? { 5148 if manifests 5149 .insert(record.name, record.manifest_path) 5150 .is_some() 5151 { 5152 return Err("duplicate workspace package name in manifest map".to_string()); 5153 } 5154 } 5155 Ok(manifests) 5156 } 5157 5158 fn load_coverage_policy( 5159 contract_root: &Path, 5160 ) -> Result<crate::coverage::CoveragePolicyFile, String> { 5161 read_coverage_policy(&coverage_root(contract_root).join("coverage.toml")) 5162 } 5163 5164 fn coverage_root(contract_root: &Path) -> PathBuf { 5165 contract_root.to_path_buf() 5166 } 5167 5168 fn release_contract_path(workspace_root: &Path, _contract_version: &str) -> PathBuf { 5169 workspace_root.join(RELEASE_POLICY_RELATIVE) 5170 } 5171 5172 #[cfg(test)] 5173 fn root_release_policy_path(workspace_root: &Path) -> PathBuf { 5174 release_contract_path(workspace_root, "1.0.0") 5175 } 5176 5177 fn resolve_release_contract_path_with_override( 5178 workspace_root: &Path, 5179 contract_version: &str, 5180 release_policy_override: Option<PathBuf>, 5181 ) -> Result<PathBuf, String> { 5182 if let Some(path) = release_policy_override { 5183 if !path.is_file() { 5184 return Err(format!( 5185 "release policy override points to a missing file: {}", 5186 path.display() 5187 )); 5188 } 5189 return Ok(path); 5190 } 5191 5192 let path = release_contract_path(workspace_root, contract_version); 5193 if !path.is_file() { 5194 return Err(format!( 5195 "release publish policy not found; expected {}", 5196 path.display() 5197 )); 5198 } 5199 5200 Ok(path) 5201 } 5202 5203 #[cfg(test)] 5204 fn load_release_contract( 5205 workspace_root: &Path, 5206 contract_version: &str, 5207 ) -> Result<ReleaseContractFile, String> { 5208 load_release_contract_with_override(workspace_root, contract_version, None) 5209 } 5210 5211 fn load_release_contract_with_override( 5212 workspace_root: &Path, 5213 contract_version: &str, 5214 release_policy_override: Option<PathBuf>, 5215 ) -> Result<ReleaseContractFile, String> { 5216 let path = resolve_release_contract_path_with_override( 5217 workspace_root, 5218 contract_version, 5219 release_policy_override, 5220 )?; 5221 parse_toml::<ReleaseContractFile>(&path) 5222 } 5223 5224 #[cfg(test)] 5225 #[cfg_attr(coverage_nightly, coverage(off))] 5226 fn should_synthesize_owner_contracts_for_tests(workspace_root: &Path) -> bool { 5227 workspace_root 5228 .join("crates") 5229 .join("core") 5230 .join("Cargo.toml") 5231 .is_file() 5232 && workspace_root 5233 .join("crates") 5234 .join("event_codec") 5235 .join("Cargo.toml") 5236 .is_file() 5237 && workspace_root 5238 .join("crates") 5239 .join("trade") 5240 .join("Cargo.toml") 5241 .is_file() 5242 && workspace_root 5243 .join("contracts") 5244 .join("manifest.toml") 5245 .is_file() 5246 && workspace_root 5247 .join("contracts") 5248 .join("coverage.toml") 5249 .is_file() 5250 } 5251 5252 fn package_publish_enabled(publish: Option<&PackagePublish>) -> bool { 5253 match publish { 5254 None => true, 5255 Some(PackagePublish::Bool(flag)) => *flag, 5256 Some(PackagePublish::Registries(registries)) => !registries.is_empty(), 5257 } 5258 } 5259 5260 #[cfg_attr(not(test), allow(dead_code))] 5261 fn workspace_package_publish_flags( 5262 workspace_root: &Path, 5263 ) -> Result<BTreeMap<String, bool>, String> { 5264 let mut flags = BTreeMap::new(); 5265 for record in workspace_package_records(workspace_root)? { 5266 if flags 5267 .insert(record.name.clone(), record.publish_enabled) 5268 .is_some() 5269 { 5270 return Err(format!("duplicate workspace package name {}", record.name)); 5271 } 5272 } 5273 Ok(flags) 5274 } 5275 5276 fn workspace_package_publish_configs( 5277 workspace_root: &Path, 5278 ) -> Result<BTreeMap<String, Option<PackagePublish>>, String> { 5279 let mut configs = BTreeMap::new(); 5280 for record in workspace_package_records(workspace_root)? { 5281 if configs 5282 .insert(record.name.clone(), record.publish.clone()) 5283 .is_some() 5284 { 5285 return Err(format!("duplicate workspace package name {}", record.name)); 5286 } 5287 } 5288 Ok(configs) 5289 } 5290 5291 fn read_workspace_package_dependencies( 5292 workspace_root: &Path, 5293 ) -> Result<BTreeMap<String, BTreeSet<String>>, String> { 5294 let package_records = workspace_package_records(workspace_root)?; 5295 let workspace_names = package_records 5296 .iter() 5297 .map(|record| record.name.clone()) 5298 .collect::<BTreeSet<_>>(); 5299 5300 let mut deps = BTreeMap::new(); 5301 for record in package_records { 5302 let mut package_deps = BTreeSet::new(); 5303 for section in ["dependencies", "build-dependencies"] { 5304 let Some(table) = record 5305 .manifest_value 5306 .get(section) 5307 .and_then(toml::Value::as_table) 5308 else { 5309 continue; 5310 }; 5311 for dep_name in table.keys() { 5312 if workspace_names.contains(dep_name) { 5313 package_deps.insert(dep_name.clone()); 5314 } 5315 } 5316 } 5317 deps.insert(record.name, package_deps); 5318 } 5319 5320 Ok(deps) 5321 } 5322 5323 fn validate_publishable_dto_tooling_sources( 5324 workspace_root: &Path, 5325 public_crates: &BTreeSet<String>, 5326 ) -> Result<(), String> { 5327 let workspace_manifest_value = parse_toml::<toml::Value>(&workspace_root.join("Cargo.toml"))?; 5328 let package_records = workspace_package_records(workspace_root)?; 5329 5330 for record in package_records { 5331 if !public_crates.contains(&record.name) { 5332 continue; 5333 } 5334 for section in ["dependencies", "build-dependencies"] { 5335 let Some(dependencies) = record 5336 .manifest_value 5337 .get(section) 5338 .and_then(toml::Value::as_table) 5339 else { 5340 continue; 5341 }; 5342 for dependency_name in DTO_TOOLING_DEPENDENCIES { 5343 let Some(dependency_value) = dependencies.get(dependency_name) else { 5344 continue; 5345 }; 5346 validate_publishable_dto_dependency_source( 5347 workspace_manifest_value.as_table(), 5348 record.name.as_str(), 5349 section, 5350 dependency_name, 5351 dependency_value, 5352 )?; 5353 } 5354 } 5355 } 5356 5357 Ok(()) 5358 } 5359 5360 fn validate_publishable_dto_dependency_source( 5361 workspace_manifest: Option<&toml::value::Table>, 5362 crate_name: &str, 5363 section: &str, 5364 dependency_name: &str, 5365 dependency_value: &toml::Value, 5366 ) -> Result<(), String> { 5367 let resolved = 5368 resolve_workspace_dependency_source(workspace_manifest, dependency_name, dependency_value) 5369 .unwrap_or(dependency_value); 5370 if dependency_has_source_key(resolved, "git") { 5371 return Err(format!( 5372 "public crate {crate_name} {section}.{dependency_name} must use a crates.io DTO tooling dependency, not a git source" 5373 )); 5374 } 5375 if dependency_has_source_key(resolved, "path") { 5376 return Err(format!( 5377 "public crate {crate_name} {section}.{dependency_name} must use a crates.io DTO tooling dependency, not a path source" 5378 )); 5379 } 5380 Ok(()) 5381 } 5382 5383 fn resolve_workspace_dependency_source<'a>( 5384 workspace_manifest: Option<&'a toml::value::Table>, 5385 dependency_name: &str, 5386 dependency_value: &toml::Value, 5387 ) -> Option<&'a toml::Value> { 5388 if !dependency_has_workspace_true(dependency_value) { 5389 return None; 5390 } 5391 workspace_manifest? 5392 .get("workspace")? 5393 .as_table()? 5394 .get("dependencies")? 5395 .as_table()? 5396 .get(dependency_name) 5397 } 5398 5399 fn dependency_has_workspace_true(value: &toml::Value) -> bool { 5400 value 5401 .as_table() 5402 .and_then(|table| table.get("workspace")) 5403 .and_then(toml::Value::as_bool) 5404 .unwrap_or(false) 5405 } 5406 5407 fn dependency_has_source_key(value: &toml::Value, key: &str) -> bool { 5408 value.as_table().and_then(|table| table.get(key)).is_some() 5409 } 5410 5411 fn join_set(items: &BTreeSet<String>) -> String { 5412 items.iter().cloned().collect::<Vec<_>>().join(", ") 5413 } 5414 5415 fn collect_unique_set(items: &[String], field: &str) -> Result<BTreeSet<String>, String> { 5416 let mut set = BTreeSet::new(); 5417 for item in items { 5418 if item.trim().is_empty() { 5419 return Err(format!("{field} contains an empty crate name")); 5420 } 5421 if !set.insert(item.clone()) { 5422 return Err(format!("{field} has duplicate crate {}", item)); 5423 } 5424 } 5425 Ok(set) 5426 } 5427 5428 fn collect_non_empty_set(items: &[String], field: &str) -> Result<BTreeSet<String>, String> { 5429 let mut set = BTreeSet::new(); 5430 for item in items { 5431 if item.trim().is_empty() { 5432 return Err(format!("{field} contains an empty value")); 5433 } 5434 if !set.insert(item.clone()) { 5435 return Err(format!("{field} has duplicate value {}", item)); 5436 } 5437 } 5438 Ok(set) 5439 } 5440 5441 fn validate_crate_identifier(value: &str, field: &str) -> Result<(), String> { 5442 let trimmed = value.trim(); 5443 if trimmed.is_empty() { 5444 return Err(format!("{field} is required")); 5445 } 5446 if trimmed != value 5447 || trimmed.contains('/') 5448 || trimmed.contains('\\') 5449 || trimmed.contains("..") 5450 || trimmed == "radroots_sdk" 5451 { 5452 return Err(format!("{field} must be a crate identifier")); 5453 } 5454 Ok(()) 5455 } 5456 5457 fn validate_surface_metadata(surface: &Surface) -> Result<(), String> { 5458 if let Some(tiers) = &surface.rust_crate_tiers { 5459 let mut tier_crates = BTreeSet::new(); 5460 for (field, crates) in [ 5461 ( 5462 "surface.rust_crate_tiers.advanced_substrate", 5463 &tiers.advanced_substrate, 5464 ), 5465 ( 5466 "surface.rust_crate_tiers.published_support", 5467 &tiers.published_support, 5468 ), 5469 ( 5470 "surface.rust_crate_tiers.deferred_publication", 5471 &tiers.deferred_publication, 5472 ), 5473 ] { 5474 let entries = collect_unique_set(crates, field)?; 5475 if entries.is_empty() { 5476 return Err(format!("{field} must not be empty")); 5477 } 5478 for crate_name in entries { 5479 if !tier_crates.insert(crate_name.clone()) { 5480 return Err(format!( 5481 "surface.rust_crate_tiers has duplicate crate {crate_name}" 5482 )); 5483 } 5484 } 5485 } 5486 } 5487 5488 if let Some(replica) = &surface.internal_replica_crates { 5489 validate_crate_identifier(&replica.schema, "surface.internal_replica_crates.schema")?; 5490 validate_crate_identifier(&replica.storage, "surface.internal_replica_crates.storage")?; 5491 validate_crate_identifier(&replica.sync, "surface.internal_replica_crates.sync")?; 5492 } 5493 5494 Ok(()) 5495 } 5496 5497 fn validate_policy_metadata(policy: &Policy) -> Result<(), String> { 5498 if !policy.exclude_internal_workspace_crates 5499 || !policy.require_reproducible_exports 5500 || !policy.require_conformance_vectors 5501 { 5502 return Err("contract policy flags must all be true".to_string()); 5503 } 5504 if let Some(replica) = &policy.replica 5505 && (!replica.forbid_legacy_alias_identifiers 5506 || !replica.require_transport_agnostic_sync_contract 5507 || !replica.require_deterministic_emit_ingest) 5508 { 5509 return Err("contract replica policy flags must all be true".to_string()); 5510 } 5511 Ok(()) 5512 } 5513 5514 fn parse_replica_transfer_constant(path: &Path, name: &str) -> Result<u32, String> { 5515 let source = 5516 fs::read_to_string(path).map_err(|error| format!("read {}: {error}", path.display()))?; 5517 let declaration_prefix = format!("pub const {name}: u32 ="); 5518 let mut value = None; 5519 for line in source.lines() { 5520 let Some(raw_value) = line.trim().strip_prefix(&declaration_prefix) else { 5521 continue; 5522 }; 5523 let raw_value = raw_value.trim().strip_suffix(';').ok_or_else(|| { 5524 format!( 5525 "replica transfer constant {name} in {} must terminate with a semicolon", 5526 path.display() 5527 ) 5528 })?; 5529 let parsed = raw_value.parse::<u32>().map_err(|error| { 5530 format!( 5531 "replica transfer constant {name} in {} must be a u32 literal: {error}", 5532 path.display() 5533 ) 5534 })?; 5535 if value.replace(parsed).is_some() { 5536 return Err(format!( 5537 "replica transfer constant {name} must be declared exactly once in {}", 5538 path.display() 5539 )); 5540 } 5541 } 5542 value.ok_or_else(|| { 5543 format!( 5544 "replica transfer constant {name} is missing from {}", 5545 path.display() 5546 ) 5547 }) 5548 } 5549 5550 fn has_exact_legacy_ingest_cfg(attributes: &[syn::Attribute]) -> bool { 5551 let mut cfg_attributes = attributes 5552 .iter() 5553 .filter(|attribute| attribute.path().is_ident("cfg")); 5554 let Some(attribute) = cfg_attributes.next() else { 5555 return false; 5556 }; 5557 if cfg_attributes.next().is_some() { 5558 return false; 5559 } 5560 let syn::Meta::List(arguments) = &attribute.meta else { 5561 return false; 5562 }; 5563 let Ok(predicate) = arguments.parse_args::<syn::Meta>() else { 5564 return false; 5565 }; 5566 let syn::Meta::NameValue(feature) = predicate else { 5567 return false; 5568 }; 5569 if !feature.path.is_ident("feature") { 5570 return false; 5571 } 5572 matches!( 5573 feature.value, 5574 syn::Expr::Lit(syn::ExprLit { 5575 lit: syn::Lit::Str(value), 5576 .. 5577 }) if value.value() == "legacy-ingest" 5578 ) 5579 } 5580 5581 fn replica_use_tree_references_ingest(tree: &syn::UseTree) -> bool { 5582 match tree { 5583 syn::UseTree::Path(path) => { 5584 path.ident == "ingest" || replica_use_tree_references_ingest(&path.tree) 5585 } 5586 syn::UseTree::Name(name) => name.ident == "ingest", 5587 syn::UseTree::Rename(rename) => rename.ident == "ingest", 5588 syn::UseTree::Group(group) => group.items.iter().any(replica_use_tree_references_ingest), 5589 syn::UseTree::Glob(_) => false, 5590 } 5591 } 5592 5593 fn collect_public_replica_ingest_exports<'a>( 5594 items: &'a [syn::Item], 5595 exports: &mut Vec<&'a syn::ItemUse>, 5596 ) { 5597 for item in items { 5598 match item { 5599 syn::Item::Use(export) 5600 if matches!(&export.vis, syn::Visibility::Public(_)) 5601 && replica_use_tree_references_ingest(&export.tree) => 5602 { 5603 exports.push(export); 5604 } 5605 syn::Item::Mod(module) if matches!(&module.vis, syn::Visibility::Public(_)) => { 5606 if let Some((_, nested_items)) = &module.content { 5607 collect_public_replica_ingest_exports(nested_items, exports); 5608 } 5609 } 5610 _ => {} 5611 } 5612 } 5613 } 5614 5615 fn validate_replica_legacy_ingest_exports(lib_path: &Path, source: &str) -> Result<(), String> { 5616 let syntax = syn::parse_file(source) 5617 .map_err(|error| format!("parse replica sync source {}: {error}", lib_path.display()))?; 5618 let ingest_modules = syntax 5619 .items 5620 .iter() 5621 .filter_map(|item| match item { 5622 syn::Item::Mod(module) if module.ident == "ingest" => Some(module), 5623 _ => None, 5624 }) 5625 .collect::<Vec<_>>(); 5626 if ingest_modules.len() != 1 { 5627 return Err(format!( 5628 "replica legacy ingest source {} must declare exactly one ingest module", 5629 lib_path.display() 5630 )); 5631 } 5632 let ingest_module = ingest_modules[0]; 5633 if !matches!(&ingest_module.vis, syn::Visibility::Public(_)) { 5634 return Err(format!( 5635 "replica legacy ingest module in {} must remain public", 5636 lib_path.display() 5637 )); 5638 } 5639 if !has_exact_legacy_ingest_cfg(&ingest_module.attrs) { 5640 return Err(format!( 5641 "replica legacy ingest module in {} must be guarded by exact #[cfg(feature = \"legacy-ingest\")]", 5642 lib_path.display() 5643 )); 5644 } 5645 5646 let mut ingest_exports = Vec::new(); 5647 collect_public_replica_ingest_exports(&syntax.items, &mut ingest_exports); 5648 if ingest_exports.is_empty() { 5649 return Err(format!( 5650 "replica legacy ingest source {} must publicly re-export the ingest API", 5651 lib_path.display() 5652 )); 5653 } 5654 if ingest_exports 5655 .iter() 5656 .any(|export| !has_exact_legacy_ingest_cfg(&export.attrs)) 5657 { 5658 return Err(format!( 5659 "every public replica ingest re-export in {} must be guarded by exact #[cfg(feature = \"legacy-ingest\")]", 5660 lib_path.display() 5661 )); 5662 } 5663 Ok(()) 5664 } 5665 5666 fn validate_replica_policy_source_witnesses(sync_root: &Path) -> Result<(), String> { 5667 let cargo_path = sync_root.join("Cargo.toml"); 5668 let cargo_source = fs::read_to_string(&cargo_path) 5669 .map_err(|error| format!("read {}: {error}", cargo_path.display()))?; 5670 let cargo: toml::Value = toml::from_str(&cargo_source) 5671 .map_err(|error| format!("parse {}: {error}", cargo_path.display()))?; 5672 let features = cargo 5673 .get("features") 5674 .and_then(toml::Value::as_table) 5675 .ok_or_else(|| format!("replica sync {} must define features", cargo_path.display()))?; 5676 let default_features = features 5677 .get("default") 5678 .and_then(toml::Value::as_array) 5679 .ok_or_else(|| { 5680 format!( 5681 "replica sync {} must define default features", 5682 cargo_path.display() 5683 ) 5684 })?; 5685 let mut pending_default_features = default_features 5686 .iter() 5687 .filter_map(toml::Value::as_str) 5688 .collect::<Vec<_>>(); 5689 let mut visited_default_features = BTreeSet::new(); 5690 while let Some(feature) = pending_default_features.pop() { 5691 if !visited_default_features.insert(feature) { 5692 continue; 5693 } 5694 if feature == "legacy-ingest" { 5695 return Err(format!( 5696 "replica legacy-ingest must not be enabled by default features in {}", 5697 cargo_path.display() 5698 )); 5699 } 5700 if let Some(members) = features.get(feature).and_then(toml::Value::as_array) { 5701 pending_default_features.extend( 5702 members 5703 .iter() 5704 .filter_map(toml::Value::as_str) 5705 .filter(|member| features.contains_key(*member)), 5706 ); 5707 } 5708 } 5709 let legacy_features = features 5710 .get("legacy-ingest") 5711 .and_then(toml::Value::as_array) 5712 .ok_or_else(|| { 5713 format!( 5714 "replica sync {} must define the explicit legacy-ingest feature", 5715 cargo_path.display() 5716 ) 5717 })?; 5718 if !legacy_features 5719 .iter() 5720 .filter_map(toml::Value::as_str) 5721 .any(|feature| feature == "std") 5722 { 5723 return Err(format!( 5724 "replica legacy-ingest feature in {} must enable std", 5725 cargo_path.display() 5726 )); 5727 } 5728 5729 let lib_path = sync_root.join("src/lib.rs"); 5730 let lib_source = fs::read_to_string(&lib_path) 5731 .map_err(|error| format!("read {}: {error}", lib_path.display()))?; 5732 validate_replica_legacy_ingest_exports(&lib_path, &lib_source)?; 5733 5734 let types_path = sync_root.join("src/types.rs"); 5735 let types_source = fs::read_to_string(&types_path) 5736 .map_err(|error| format!("read {}: {error}", types_path.display()))?; 5737 for type_name in [ 5738 "RadrootsReplicaFarmSelector", 5739 "RadrootsReplicaSyncOptions", 5740 "RadrootsReplicaSyncRequest", 5741 ] { 5742 let witness = format!("#[serde(deny_unknown_fields)]\npub struct {type_name}"); 5743 if !types_source.contains(&witness) { 5744 return Err(format!( 5745 "replica request type {type_name} must place #[serde(deny_unknown_fields)] immediately before its public struct declaration in {}", 5746 types_path.display() 5747 )); 5748 } 5749 } 5750 if types_source.contains("include_profiles") { 5751 return Err(format!( 5752 "retired replica request identifier include_profiles is forbidden in {}", 5753 types_path.display() 5754 )); 5755 } 5756 5757 let emit_path = sync_root.join("src/emit.rs"); 5758 let emit_source = fs::read_to_string(&emit_path) 5759 .map_err(|error| format!("read {}: {error}", emit_path.display()))?; 5760 let test_module_marker = "#[cfg(test)]\nmod tests {"; 5761 let test_module_start = emit_source.rfind(test_module_marker).ok_or_else(|| { 5762 format!( 5763 "replica emit source {} must keep its bottom test module behind #[cfg(test)]", 5764 emit_path.display() 5765 ) 5766 })?; 5767 let production_source = &emit_source[..test_module_start]; 5768 if !production_source.contains("pub fn radroots_replica_sync_all_with_options(") { 5769 return Err(format!( 5770 "replica emit source {} is missing radroots_replica_sync_all_with_options", 5771 emit_path.display() 5772 )); 5773 } 5774 let production_code = production_source 5775 .lines() 5776 .filter(|line| !line.trim_start().starts_with("//")) 5777 .collect::<Vec<_>>() 5778 .join("\n"); 5779 for identifier in production_code 5780 .split(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) 5781 .filter(|identifier| !identifier.is_empty()) 5782 { 5783 if identifier.to_ascii_lowercase().contains("profile") { 5784 return Err(format!( 5785 "replica emit production source {} must not contain Profile-related identifier {identifier}", 5786 emit_path.display() 5787 )); 5788 } 5789 } 5790 let compact_production = production_code 5791 .chars() 5792 .filter(|character| !character.is_ascii_whitespace()) 5793 .collect::<String>(); 5794 if compact_production.contains("kind:0") { 5795 return Err(format!( 5796 "replica emit production source {} must not construct a literal kind-0 event", 5797 emit_path.display() 5798 )); 5799 } 5800 5801 Ok(()) 5802 } 5803 5804 fn validate_replica_contract(bundle: &ContractBundle, workspace_root: &Path) -> Result<(), String> { 5805 let replica = &bundle.replica; 5806 if replica.schema_version != 1 { 5807 return Err("replica contract schema_version must be 1".to_string()); 5808 } 5809 if replica.contract.name != REPLICA_CONTRACT_NAME { 5810 return Err(format!( 5811 "replica contract name must be {REPLICA_CONTRACT_NAME}" 5812 )); 5813 } 5814 if replica.contract.version != bundle.manifest.contract.version { 5815 return Err(format!( 5816 "replica contract version {} must match manifest contract version {}", 5817 replica.contract.version, bundle.manifest.contract.version 5818 )); 5819 } 5820 if replica.contract.purpose.trim().is_empty() { 5821 return Err("replica contract purpose is required".to_string()); 5822 } 5823 5824 let manifest_family = bundle 5825 .manifest 5826 .surface 5827 .internal_replica_crates 5828 .as_ref() 5829 .ok_or_else(|| "surface.internal_replica_crates is required".to_string())?; 5830 for (field, actual, expected) in [ 5831 ( 5832 "schema", 5833 replica.crate_family.schema.as_str(), 5834 manifest_family.schema.as_str(), 5835 ), 5836 ( 5837 "storage", 5838 replica.crate_family.storage.as_str(), 5839 manifest_family.storage.as_str(), 5840 ), 5841 ( 5842 "sync", 5843 replica.crate_family.sync.as_str(), 5844 manifest_family.sync.as_str(), 5845 ), 5846 ] { 5847 validate_crate_identifier(actual, &format!("replica.crate_family.{field}"))?; 5848 if actual != expected { 5849 return Err(format!( 5850 "replica crate_family.{field} {actual} must match surface.internal_replica_crates.{field} {expected}" 5851 )); 5852 } 5853 } 5854 5855 let package_manifests = workspace_package_manifests(workspace_root)?; 5856 for (field, crate_name) in [ 5857 ("schema", replica.crate_family.schema.as_str()), 5858 ("storage", replica.crate_family.storage.as_str()), 5859 ("sync", replica.crate_family.sync.as_str()), 5860 ] { 5861 if !package_manifests.contains_key(crate_name) { 5862 return Err(format!( 5863 "replica crate_family.{field} {crate_name} must name a workspace package" 5864 )); 5865 } 5866 } 5867 5868 let manifest_policy = bundle 5869 .manifest 5870 .policy 5871 .replica 5872 .as_ref() 5873 .ok_or_else(|| "policy.replica is required".to_string())?; 5874 let policy_parity = [ 5875 ( 5876 "transport_agnostic_sync_core", 5877 replica.policy.transport_agnostic_sync_core, 5878 manifest_policy.require_transport_agnostic_sync_contract, 5879 ), 5880 ( 5881 "deterministic_emit_and_ingest", 5882 replica.policy.deterministic_emit_and_ingest, 5883 manifest_policy.require_deterministic_emit_ingest, 5884 ), 5885 ( 5886 "forbid_legacy_alias_identifiers", 5887 replica.policy.forbid_legacy_alias_identifiers, 5888 manifest_policy.forbid_legacy_alias_identifiers, 5889 ), 5890 ]; 5891 for (field, actual, expected) in policy_parity { 5892 if !actual || actual != expected { 5893 return Err(format!( 5894 "replica policy.{field} must be true and match manifest policy.replica" 5895 )); 5896 } 5897 } 5898 if replica.policy.profile_event_emission != "excluded" { 5899 return Err("replica policy.profile_event_emission must be excluded".to_string()); 5900 } 5901 if replica.policy.unknown_sync_request_fields != "reject" { 5902 return Err("replica policy.unknown_sync_request_fields must be reject".to_string()); 5903 } 5904 for (field, actual, expected) in [ 5905 ( 5906 "classified_listing_signature_verification", 5907 replica 5908 .policy 5909 .classified_listing_signature_verification 5910 .as_str(), 5911 "required_before_state", 5912 ), 5913 ( 5914 "classified_listing_head_selection", 5915 replica.policy.classified_listing_head_selection.as_str(), 5916 "raw_before_profile", 5917 ), 5918 ( 5919 "classified_listing_operational_projection", 5920 replica 5921 .policy 5922 .classified_listing_operational_projection 5923 .as_str(), 5924 "operational_partition_only", 5925 ), 5926 ( 5927 "classified_listing_excluded_or_rejected_head", 5928 replica 5929 .policy 5930 .classified_listing_excluded_or_rejected_head 5931 .as_str(), 5932 "remove_projection_and_advance", 5933 ), 5934 ( 5935 "classified_listing_head_only_ingest", 5936 replica.policy.classified_listing_head_only_ingest.as_str(), 5937 "reject_require_profile_aware", 5938 ), 5939 ( 5940 "legacy_bare_envelope_ingest", 5941 replica.policy.legacy_bare_envelope_ingest.as_str(), 5942 "explicit_non_default_feature_only", 5943 ), 5944 ( 5945 "legacy_ingest_feature", 5946 replica.policy.legacy_ingest_feature.as_str(), 5947 "legacy-ingest", 5948 ), 5949 ( 5950 "phase_1_ingest_replacement", 5951 replica.policy.phase_1_ingest_replacement.as_str(), 5952 "none", 5953 ), 5954 ( 5955 "future_product_ingest_input", 5956 replica.policy.future_product_ingest_input.as_str(), 5957 "store_produced_verified_valid_visible_admission", 5958 ), 5959 ] { 5960 if actual != expected { 5961 return Err(format!("replica policy.{field} must be {expected}")); 5962 } 5963 } 5964 5965 if replica.transfer.version != REPLICA_TRANSFER_VERSION { 5966 return Err(format!( 5967 "replica transfer.version must be {REPLICA_TRANSFER_VERSION}" 5968 )); 5969 } 5970 if replica.transfer.constant != REPLICA_TRANSFER_CONSTANT { 5971 return Err(format!( 5972 "replica transfer.constant must be {REPLICA_TRANSFER_CONSTANT}" 5973 )); 5974 } 5975 let sync_manifest = package_manifests 5976 .get(&replica.crate_family.sync) 5977 .expect("replica sync workspace package was validated"); 5978 let sync_root = sync_manifest 5979 .parent() 5980 .expect("workspace package manifest has a parent"); 5981 validate_replica_policy_source_witnesses(sync_root)?; 5982 let expected_source = sync_root 5983 .strip_prefix(workspace_root) 5984 .expect("workspace package lives under the workspace root") 5985 .join("src/types.rs"); 5986 if Path::new(&replica.transfer.source) != expected_source { 5987 return Err(format!( 5988 "replica transfer.source {} must be {}", 5989 replica.transfer.source, 5990 expected_source.display() 5991 )); 5992 } 5993 let source_path = workspace_root.join(&replica.transfer.source); 5994 let source_version = parse_replica_transfer_constant(&source_path, &replica.transfer.constant)?; 5995 if source_version != replica.transfer.version { 5996 return Err(format!( 5997 "replica transfer source constant {} value {} must match contract version {}", 5998 replica.transfer.constant, source_version, replica.transfer.version 5999 )); 6000 } 6001 6002 Ok(()) 6003 } 6004 6005 fn validate_operations_contract( 6006 bundle: &ContractBundle, 6007 operations_manifest: &OperationsContractManifest, 6008 workspace_root: &Path, 6009 ) -> Result<(), String> { 6010 validate_conformance_schema(workspace_root)?; 6011 let conformance_root = conformance_root(workspace_root); 6012 if operations_manifest.contract.name.trim().is_empty() { 6013 return Err("operations contract name is required".to_string()); 6014 } 6015 if operations_manifest.contract.version.trim().is_empty() { 6016 return Err("operations contract version is required".to_string()); 6017 } 6018 if operations_manifest.contract.source.trim().is_empty() { 6019 return Err("operations contract source is required".to_string()); 6020 } 6021 if operations_manifest.contract.name != bundle.manifest.contract.name { 6022 return Err("operations contract name must match manifest contract name".to_string()); 6023 } 6024 if operations_manifest.contract.version != bundle.manifest.contract.version { 6025 return Err("operations contract version must match manifest contract version".to_string()); 6026 } 6027 if operations_manifest.contract.source != bundle.manifest.contract.source { 6028 return Err("operations contract source must match manifest contract source".to_string()); 6029 } 6030 6031 let domains = collect_non_empty_set(&operations_manifest.public.domains, "public.domains")?; 6032 if domains.is_empty() { 6033 return Err("public.domains must not be empty".to_string()); 6034 } 6035 let shared_types = collect_non_empty_set( 6036 &operations_manifest.shared_types.public, 6037 "shared_types.public", 6038 )?; 6039 if shared_types.is_empty() { 6040 return Err("shared_types.public must not be empty".to_string()); 6041 } 6042 validate_no_retired_operation_event_names( 6043 &operations_manifest.shared_types.public, 6044 "shared_types.public", 6045 )?; 6046 let error_classes = 6047 collect_non_empty_set(&operations_manifest.errors.classes, "errors.classes")?; 6048 if error_classes.is_empty() { 6049 return Err("errors.classes must not be empty".to_string()); 6050 } 6051 if operations_manifest.operations.is_empty() { 6052 return Err("operations map must not be empty".to_string()); 6053 } 6054 6055 if let Some(provenance) = &operations_manifest.implementation_provenance { 6056 let manifest_models = collect_unique_set( 6057 &bundle.manifest.surface.model_crates, 6058 "surface.model_crates", 6059 )?; 6060 let manifest_algorithms = collect_unique_set( 6061 &bundle.manifest.surface.algorithm_crates, 6062 "surface.algorithm_crates", 6063 )?; 6064 let provenance_models = collect_unique_set( 6065 &provenance.model_crates, 6066 "implementation_provenance.model_crates", 6067 )?; 6068 let provenance_algorithms = collect_unique_set( 6069 &provenance.algorithm_crates, 6070 "implementation_provenance.algorithm_crates", 6071 )?; 6072 if provenance_models != manifest_models || provenance_algorithms != manifest_algorithms { 6073 return Err( 6074 "operations implementation_provenance must match manifest surface crates" 6075 .to_string(), 6076 ); 6077 } 6078 } 6079 6080 let mut operation_ids = BTreeSet::new(); 6081 for (operation_key, operation) in &operations_manifest.operations { 6082 if operation_key.trim().is_empty() { 6083 return Err("operations map contains an empty key".to_string()); 6084 } 6085 if operation.domain.trim().is_empty() { 6086 return Err(format!("operation {} domain is required", operation_key)); 6087 } 6088 if !domains.contains(&operation.domain) { 6089 return Err(format!( 6090 "operation {} references unknown domain {}", 6091 operation_key, operation.domain 6092 )); 6093 } 6094 if operation.id.trim().is_empty() { 6095 return Err(format!("operation {} id is required", operation_key)); 6096 } 6097 if !operation_ids.insert(operation.id.clone()) { 6098 return Err(format!("operations has duplicate id {}", operation.id)); 6099 } 6100 if operation.stability.trim().is_empty() { 6101 return Err(format!("operation {} stability is required", operation.id)); 6102 } 6103 if !operation.deterministic { 6104 return Err(format!( 6105 "operation {} deterministic must be true for the public contract", 6106 operation.id 6107 )); 6108 } 6109 if operation.inputs.is_empty() { 6110 return Err(format!( 6111 "operation {} inputs must not be empty", 6112 operation.id 6113 )); 6114 } 6115 let _ = collect_non_empty_set( 6116 &operation.inputs, 6117 &format!("operation {} inputs", operation.id), 6118 )?; 6119 validate_no_retired_operation_event_names( 6120 &operation.inputs, 6121 &format!("operation {} inputs", operation.id), 6122 )?; 6123 if operation.outputs.is_empty() { 6124 return Err(format!( 6125 "operation {} outputs must not be empty", 6126 operation.id 6127 )); 6128 } 6129 let _ = collect_non_empty_set( 6130 &operation.outputs, 6131 &format!("operation {} outputs", operation.id), 6132 )?; 6133 validate_no_retired_operation_event_names( 6134 &operation.outputs, 6135 &format!("operation {} outputs", operation.id), 6136 )?; 6137 if !error_classes.contains(&operation.error_class) { 6138 return Err(format!( 6139 "operation {} references unknown error class {}", 6140 operation.id, operation.error_class 6141 )); 6142 } 6143 if operation.signing.trim().is_empty() { 6144 return Err(format!("operation {} signing is required", operation.id)); 6145 } 6146 if operation.transport.trim().is_empty() { 6147 return Err(format!("operation {} transport is required", operation.id)); 6148 } 6149 if operation.implementation.rust_modules.is_empty() { 6150 return Err(format!( 6151 "operation {} implementation.rust_modules must not be empty", 6152 operation.id 6153 )); 6154 } 6155 let _ = collect_non_empty_set( 6156 &operation.implementation.rust_types, 6157 &format!("operation {} implementation.rust_types", operation.id), 6158 )?; 6159 validate_no_retired_operation_event_names( 6160 &operation.implementation.rust_types, 6161 &format!("operation {} implementation.rust_types", operation.id), 6162 )?; 6163 for rust_module in &operation.implementation.rust_modules { 6164 if rust_module.trim().is_empty() { 6165 return Err(format!( 6166 "operation {} implementation.rust_modules contains an empty value", 6167 operation.id 6168 )); 6169 } 6170 let path = workspace_root.join(rust_module); 6171 if !path.is_file() { 6172 return Err(format!( 6173 "operation {} references missing rust module {}", 6174 operation.id, rust_module 6175 )); 6176 } 6177 } 6178 if operation.conformance.vector.trim().is_empty() { 6179 return Err(format!( 6180 "operation {} conformance.vector is required", 6181 operation.id 6182 )); 6183 } 6184 if !operation 6185 .conformance 6186 .vector 6187 .starts_with("contracts/conformance/") 6188 { 6189 return Err(format!( 6190 "operation {} conformance.vector must live under contracts/conformance/", 6191 operation.id 6192 )); 6193 } 6194 let vector_path = workspace_root.join(&operation.conformance.vector); 6195 if !vector_path.starts_with(&conformance_root) { 6196 return Err(format!( 6197 "operation {} conformance.vector must resolve under {}", 6198 operation.id, 6199 conformance_root.display() 6200 )); 6201 } 6202 let vector = 6203 validate_conformance_vector_file(&vector_path, &operations_manifest.contract.version)?; 6204 validate_operation_case_kinds(operation, &vector)?; 6205 } 6206 6207 Ok(()) 6208 } 6209 6210 fn validate_capsule_operation_authority( 6211 operations_manifest: &OperationsContractManifest, 6212 workspace_root: &Path, 6213 ) -> Result<(), String> { 6214 let shared_types = collect_non_empty_set( 6215 &operations_manifest.shared_types.public, 6216 "shared_types.public", 6217 )?; 6218 validate_comment_operation_authority(operations_manifest, workspace_root)?; 6219 validate_deletion_operation_authority(operations_manifest, workspace_root)?; 6220 validate_admission_operation_authority(operations_manifest, workspace_root)?; 6221 validate_post_operation_authority(operations_manifest, workspace_root)?; 6222 validate_calendar_operation_authority(operations_manifest, &shared_types)?; 6223 validate_food_availability_operation_authority(operations_manifest, workspace_root) 6224 } 6225 6226 fn validate_operation_case_kinds( 6227 operation: &PublicOperationContract, 6228 vector: &ConformanceVectorFile, 6229 ) -> Result<(), String> { 6230 if operation.conformance.case_kinds.is_empty() { 6231 return Ok(()); 6232 } 6233 let case_kinds = collect_non_empty_set( 6234 &operation.conformance.case_kinds, 6235 &format!("operation {} conformance.case_kinds", operation.id), 6236 )?; 6237 if case_kinds.len() != operation.conformance.case_kinds.len() { 6238 return Err(format!( 6239 "operation {} conformance.case_kinds must not contain duplicates", 6240 operation.id 6241 )); 6242 } 6243 let prefix = format!("{}.", operation.id); 6244 let vector_kinds = vector 6245 .vectors 6246 .iter() 6247 .map(|entry| entry.kind.as_str()) 6248 .collect::<BTreeSet<_>>(); 6249 for case_kind in case_kinds { 6250 if !case_kind.starts_with(&prefix) { 6251 return Err(format!( 6252 "operation {} conformance case kind {} must start with {}", 6253 operation.id, case_kind, prefix 6254 )); 6255 } 6256 if !vector_kinds.contains(case_kind.as_str()) { 6257 return Err(format!( 6258 "operation {} conformance case kind {} is absent from {}", 6259 operation.id, case_kind, operation.conformance.vector 6260 )); 6261 } 6262 } 6263 Ok(()) 6264 } 6265 6266 fn validate_post_operation_authority( 6267 manifest: &OperationsContractManifest, 6268 workspace_root: &Path, 6269 ) -> Result<(), String> { 6270 let vector = validate_conformance_vector_file( 6271 &workspace_root.join(POST_CONFORMANCE_VECTOR_RELATIVE), 6272 &manifest.contract.version, 6273 )?; 6274 validate_post_operation_inventory(manifest, &vector) 6275 } 6276 6277 fn validate_post_operation_inventory( 6278 manifest: &OperationsContractManifest, 6279 vector: &ConformanceVectorFile, 6280 ) -> Result<(), String> { 6281 let shared_types = collect_non_empty_set( 6282 &manifest.shared_types.public, 6283 "post operation shared_types.public", 6284 )?; 6285 for required in REQUIRED_POST_PUBLIC_TYPES { 6286 if !shared_types.contains(required) { 6287 return Err(format!( 6288 "post operation authority requires shared public type {required}" 6289 )); 6290 } 6291 } 6292 6293 let expected_keys = POST_OPERATION_EXPECTATIONS 6294 .iter() 6295 .map(|expectation| expectation.key.to_string()) 6296 .collect::<BTreeSet<_>>(); 6297 let actual_keys = manifest 6298 .operations 6299 .iter() 6300 .filter(|(key, operation)| { 6301 operation.conformance.vector == POST_CONFORMANCE_VECTOR_RELATIVE 6302 || POST_OPERATION_KEY_PREFIXES 6303 .iter() 6304 .any(|prefix| key.starts_with(prefix)) 6305 || POST_OPERATION_ID_PREFIXES 6306 .iter() 6307 .any(|prefix| operation.id.starts_with(prefix)) 6308 }) 6309 .map(|(key, _)| key.clone()) 6310 .collect::<BTreeSet<_>>(); 6311 if actual_keys != expected_keys { 6312 let missing = expected_keys 6313 .difference(&actual_keys) 6314 .cloned() 6315 .collect::<BTreeSet<_>>(); 6316 let unexpected = actual_keys 6317 .difference(&expected_keys) 6318 .cloned() 6319 .collect::<BTreeSet<_>>(); 6320 return Err(format!( 6321 "post operation authority drift: missing {}; unexpected {}", 6322 join_set(&missing), 6323 join_set(&unexpected) 6324 )); 6325 } 6326 6327 let mut owners = BTreeMap::new(); 6328 for expected in POST_OPERATION_EXPECTATIONS { 6329 let operation = manifest 6330 .operations 6331 .get(expected.key) 6332 .ok_or_else(|| format!("post operation {} is required", expected.key))?; 6333 validate_post_operation_scalar(expected.key, "domain", &operation.domain, "social")?; 6334 validate_post_operation_scalar(expected.key, "id", &operation.id, expected.id)?; 6335 validate_post_operation_scalar(expected.key, "stability", &operation.stability, "beta")?; 6336 validate_post_operation_scalar( 6337 expected.key, 6338 "error_class", 6339 &operation.error_class, 6340 expected.error_class, 6341 )?; 6342 validate_post_operation_scalar( 6343 expected.key, 6344 "signing", 6345 &operation.signing, 6346 expected.signing, 6347 )?; 6348 validate_post_operation_scalar(expected.key, "transport", &operation.transport, "none")?; 6349 if !operation.deterministic { 6350 return Err(format!( 6351 "post operation {} deterministic drift: expected true, got false", 6352 expected.key 6353 )); 6354 } 6355 validate_post_operation_sequence( 6356 expected.key, 6357 "inputs", 6358 &operation.inputs, 6359 expected.inputs, 6360 )?; 6361 validate_post_operation_sequence( 6362 expected.key, 6363 "outputs", 6364 &operation.outputs, 6365 expected.outputs, 6366 )?; 6367 validate_post_operation_sequence( 6368 expected.key, 6369 "implementation.rust_modules", 6370 &operation.implementation.rust_modules, 6371 expected.rust_modules, 6372 )?; 6373 validate_post_operation_sequence( 6374 expected.key, 6375 "implementation.rust_types", 6376 &operation.implementation.rust_types, 6377 expected.rust_types, 6378 )?; 6379 validate_post_operation_scalar( 6380 expected.key, 6381 "conformance.vector", 6382 &operation.conformance.vector, 6383 POST_CONFORMANCE_VECTOR_RELATIVE, 6384 )?; 6385 validate_operation_case_kinds(operation, vector)?; 6386 if !operation 6387 .conformance 6388 .case_kinds 6389 .iter() 6390 .map(String::as_str) 6391 .eq(expected.case_kinds.iter().copied()) 6392 { 6393 return Err(format!( 6394 "post operation {} conformance.case_kinds drift: expected {:?}, got {:?}", 6395 expected.key, expected.case_kinds, operation.conformance.case_kinds 6396 )); 6397 } 6398 for case_kind in &operation.conformance.case_kinds { 6399 if let Some(previous) = owners.insert(case_kind.as_str(), expected.key) { 6400 return Err(format!( 6401 "post conformance case kind {case_kind} is multiply claimed by {previous} and {}", 6402 expected.key 6403 )); 6404 } 6405 } 6406 } 6407 6408 let mut actual_inventory = BTreeMap::new(); 6409 for entry in &vector.vectors { 6410 if actual_inventory 6411 .insert(entry.id.as_str(), entry.kind.as_str()) 6412 .is_some() 6413 { 6414 return Err(format!( 6415 "post conformance vector inventory has duplicate id {}", 6416 entry.id 6417 )); 6418 } 6419 } 6420 for kind in actual_inventory.values() { 6421 if !owners.contains_key(kind) { 6422 return Err(format!( 6423 "post conformance vector kind {kind} is not claimed by exactly one operation" 6424 )); 6425 } 6426 } 6427 let expected_inventory = POST_VECTOR_EXPECTATIONS 6428 .into_iter() 6429 .collect::<BTreeMap<_, _>>(); 6430 if actual_inventory != expected_inventory { 6431 return Err(format!( 6432 "post conformance vector inventory drift: expected {:?}, got {:?}", 6433 expected_inventory, actual_inventory 6434 )); 6435 } 6436 Ok(()) 6437 } 6438 6439 fn validate_post_operation_scalar( 6440 operation_key: &str, 6441 field: &str, 6442 actual: &str, 6443 expected: &str, 6444 ) -> Result<(), String> { 6445 if actual != expected { 6446 return Err(format!( 6447 "post operation {operation_key} {field} drift: expected {expected}, got {actual}" 6448 )); 6449 } 6450 Ok(()) 6451 } 6452 6453 fn validate_post_operation_sequence( 6454 operation_key: &str, 6455 field: &str, 6456 actual: &[String], 6457 expected: &[&str], 6458 ) -> Result<(), String> { 6459 if !actual 6460 .iter() 6461 .map(String::as_str) 6462 .eq(expected.iter().copied()) 6463 { 6464 return Err(format!( 6465 "post operation {operation_key} {field} drift: expected {:?}, got {:?}", 6466 expected, actual 6467 )); 6468 } 6469 Ok(()) 6470 } 6471 6472 fn validate_comment_operation_authority( 6473 manifest: &OperationsContractManifest, 6474 workspace_root: &Path, 6475 ) -> Result<(), String> { 6476 let vector = validate_conformance_vector_file( 6477 &workspace_root.join(COMMENT_CONFORMANCE_VECTOR_RELATIVE), 6478 &manifest.contract.version, 6479 )?; 6480 validate_comment_operation_inventory(manifest, &vector) 6481 } 6482 6483 fn validate_comment_operation_inventory( 6484 manifest: &OperationsContractManifest, 6485 vector: &ConformanceVectorFile, 6486 ) -> Result<(), String> { 6487 let shared_types = collect_non_empty_set( 6488 &manifest.shared_types.public, 6489 "comment operation shared_types.public", 6490 )?; 6491 for required in REQUIRED_COMMENT_PUBLIC_TYPES { 6492 if !shared_types.contains(required) { 6493 return Err(format!( 6494 "comment operation authority requires shared public type {required}" 6495 )); 6496 } 6497 } 6498 6499 let expected_keys = COMMENT_OPERATION_EXPECTATIONS 6500 .iter() 6501 .map(|expectation| expectation.key.to_string()) 6502 .collect::<BTreeSet<_>>(); 6503 let actual_keys = manifest 6504 .operations 6505 .iter() 6506 .filter(|(key, operation)| { 6507 operation.conformance.vector == COMMENT_CONFORMANCE_VECTOR_RELATIVE 6508 || key.starts_with("social_comment_") 6509 || operation.id.starts_with("social.comment.") 6510 }) 6511 .map(|(key, _)| key.clone()) 6512 .collect::<BTreeSet<_>>(); 6513 if actual_keys != expected_keys { 6514 let missing = expected_keys 6515 .difference(&actual_keys) 6516 .cloned() 6517 .collect::<BTreeSet<_>>(); 6518 let unexpected = actual_keys 6519 .difference(&expected_keys) 6520 .cloned() 6521 .collect::<BTreeSet<_>>(); 6522 return Err(format!( 6523 "comment operation authority drift: missing {}; unexpected {}", 6524 join_set(&missing), 6525 join_set(&unexpected) 6526 )); 6527 } 6528 6529 let mut owners = BTreeMap::new(); 6530 for expected in COMMENT_OPERATION_EXPECTATIONS { 6531 let operation = manifest 6532 .operations 6533 .get(expected.key) 6534 .ok_or_else(|| format!("comment operation {} is required", expected.key))?; 6535 validate_comment_operation_scalar(expected.key, "domain", &operation.domain, "social")?; 6536 validate_comment_operation_scalar(expected.key, "id", &operation.id, expected.id)?; 6537 validate_comment_operation_scalar(expected.key, "stability", &operation.stability, "beta")?; 6538 validate_comment_operation_scalar( 6539 expected.key, 6540 "error_class", 6541 &operation.error_class, 6542 expected.error_class, 6543 )?; 6544 validate_comment_operation_scalar( 6545 expected.key, 6546 "signing", 6547 &operation.signing, 6548 expected.signing, 6549 )?; 6550 validate_comment_operation_scalar(expected.key, "transport", &operation.transport, "none")?; 6551 if !operation.deterministic { 6552 return Err(format!( 6553 "comment operation {} deterministic drift: expected true, got false", 6554 expected.key 6555 )); 6556 } 6557 validate_comment_operation_sequence( 6558 expected.key, 6559 "inputs", 6560 &operation.inputs, 6561 expected.inputs, 6562 )?; 6563 validate_comment_operation_sequence( 6564 expected.key, 6565 "outputs", 6566 &operation.outputs, 6567 expected.outputs, 6568 )?; 6569 validate_comment_operation_sequence( 6570 expected.key, 6571 "implementation.rust_modules", 6572 &operation.implementation.rust_modules, 6573 expected.rust_modules, 6574 )?; 6575 validate_comment_operation_sequence( 6576 expected.key, 6577 "implementation.rust_types", 6578 &operation.implementation.rust_types, 6579 expected.rust_types, 6580 )?; 6581 validate_comment_operation_scalar( 6582 expected.key, 6583 "conformance.vector", 6584 &operation.conformance.vector, 6585 COMMENT_CONFORMANCE_VECTOR_RELATIVE, 6586 )?; 6587 validate_operation_case_kinds(operation, vector)?; 6588 if !operation 6589 .conformance 6590 .case_kinds 6591 .iter() 6592 .map(String::as_str) 6593 .eq(expected.case_kinds.iter().copied()) 6594 { 6595 return Err(format!( 6596 "comment operation {} conformance.case_kinds drift: expected {:?}, got {:?}", 6597 expected.key, expected.case_kinds, operation.conformance.case_kinds 6598 )); 6599 } 6600 for case_kind in &operation.conformance.case_kinds { 6601 if let Some(previous) = owners.insert(case_kind.as_str(), expected.key) { 6602 return Err(format!( 6603 "comment conformance case kind {case_kind} is multiply claimed by {previous} and {}", 6604 expected.key 6605 )); 6606 } 6607 } 6608 } 6609 6610 let expected_case_kinds = COMMENT_CASE_KINDS.into_iter().collect::<BTreeSet<_>>(); 6611 let actual_case_kinds = owners.keys().copied().collect::<BTreeSet<_>>(); 6612 if actual_case_kinds != expected_case_kinds { 6613 return Err(format!( 6614 "comment conformance case-kind authority drift: expected {:?}, got {:?}", 6615 expected_case_kinds, actual_case_kinds 6616 )); 6617 } 6618 6619 let mut actual_inventory = BTreeMap::new(); 6620 for entry in &vector.vectors { 6621 if actual_inventory 6622 .insert(entry.id.as_str(), entry.kind.as_str()) 6623 .is_some() 6624 { 6625 return Err(format!( 6626 "comment conformance vector inventory has duplicate id {}", 6627 entry.id 6628 )); 6629 } 6630 if !owners.contains_key(entry.kind.as_str()) { 6631 return Err(format!( 6632 "comment conformance vector kind {} is not claimed by exactly one operation", 6633 entry.kind 6634 )); 6635 } 6636 } 6637 let expected_inventory = COMMENT_VECTOR_EXPECTATIONS 6638 .into_iter() 6639 .collect::<BTreeMap<_, _>>(); 6640 if actual_inventory != expected_inventory { 6641 return Err(format!( 6642 "comment conformance vector inventory drift: expected {:?}, got {:?}", 6643 expected_inventory, actual_inventory 6644 )); 6645 } 6646 6647 Ok(()) 6648 } 6649 6650 fn validate_comment_operation_scalar( 6651 operation_key: &str, 6652 field: &str, 6653 actual: &str, 6654 expected: &str, 6655 ) -> Result<(), String> { 6656 if actual != expected { 6657 return Err(format!( 6658 "comment operation {operation_key} {field} drift: expected {expected}, got {actual}" 6659 )); 6660 } 6661 Ok(()) 6662 } 6663 6664 fn validate_comment_operation_sequence( 6665 operation_key: &str, 6666 field: &str, 6667 actual: &[String], 6668 expected: &[&str], 6669 ) -> Result<(), String> { 6670 if !actual 6671 .iter() 6672 .map(String::as_str) 6673 .eq(expected.iter().copied()) 6674 { 6675 return Err(format!( 6676 "comment operation {operation_key} {field} drift: expected {:?}, got {:?}", 6677 expected, actual 6678 )); 6679 } 6680 Ok(()) 6681 } 6682 6683 fn validate_deletion_operation_authority( 6684 manifest: &OperationsContractManifest, 6685 workspace_root: &Path, 6686 ) -> Result<(), String> { 6687 let request_vector = validate_conformance_vector_file( 6688 &workspace_root.join(DELETION_CONFORMANCE_VECTOR_RELATIVE), 6689 &manifest.contract.version, 6690 )?; 6691 let suppression_vector = validate_conformance_vector_file( 6692 &workspace_root.join(DELETION_SUPPRESSION_CONFORMANCE_VECTOR_RELATIVE), 6693 &manifest.contract.version, 6694 )?; 6695 validate_deletion_operation_inventory(manifest, &request_vector, &suppression_vector) 6696 } 6697 6698 fn validate_deletion_operation_inventory( 6699 manifest: &OperationsContractManifest, 6700 request_vector: &ConformanceVectorFile, 6701 suppression_vector: &ConformanceVectorFile, 6702 ) -> Result<(), String> { 6703 let shared_types = collect_non_empty_set( 6704 &manifest.shared_types.public, 6705 "deletion operation shared_types.public", 6706 )?; 6707 let expected_public_types = REQUIRED_DELETION_PUBLIC_TYPES 6708 .into_iter() 6709 .collect::<BTreeSet<_>>(); 6710 let actual_public_types = shared_types 6711 .iter() 6712 .map(String::as_str) 6713 .filter(|name| { 6714 name.contains("Nip09Deletion") 6715 || name.starts_with("RadrootsNip09") 6716 || name.starts_with("Nip01Coordinate") 6717 || matches!( 6718 *name, 6719 "Nip01EventWireParts" | "EventEnvelope" | "RadrootsSignatureVerifiedEvent" 6720 ) 6721 }) 6722 .collect::<BTreeSet<_>>(); 6723 if actual_public_types != expected_public_types { 6724 return Err(format!( 6725 "deletion operation public-type authority drift: expected {:?}, got {:?}", 6726 expected_public_types, actual_public_types 6727 )); 6728 } 6729 6730 let expected_keys = DELETION_OPERATION_EXPECTATIONS 6731 .iter() 6732 .map(|expectation| expectation.key.to_string()) 6733 .collect::<BTreeSet<_>>(); 6734 let actual_keys = manifest 6735 .operations 6736 .iter() 6737 .filter(|(key, operation)| { 6738 operation.conformance.vector == DELETION_CONFORMANCE_VECTOR_RELATIVE 6739 || operation.conformance.vector == DELETION_SUPPRESSION_CONFORMANCE_VECTOR_RELATIVE 6740 || key.starts_with("social_deletion_request_") 6741 || operation.id.starts_with("social.deletion_request.") 6742 }) 6743 .map(|(key, _)| key.clone()) 6744 .collect::<BTreeSet<_>>(); 6745 if actual_keys != expected_keys { 6746 let missing = expected_keys 6747 .difference(&actual_keys) 6748 .cloned() 6749 .collect::<BTreeSet<_>>(); 6750 let unexpected = actual_keys 6751 .difference(&expected_keys) 6752 .cloned() 6753 .collect::<BTreeSet<_>>(); 6754 return Err(format!( 6755 "deletion operation authority drift: missing {}; unexpected {}", 6756 join_set(&missing), 6757 join_set(&unexpected) 6758 )); 6759 } 6760 6761 let mut owners = BTreeMap::new(); 6762 for expected in DELETION_OPERATION_EXPECTATIONS { 6763 let vector = match expected.vector { 6764 DELETION_CONFORMANCE_VECTOR_RELATIVE => request_vector, 6765 DELETION_SUPPRESSION_CONFORMANCE_VECTOR_RELATIVE => suppression_vector, 6766 unexpected => { 6767 return Err(format!( 6768 "deletion operation authority contains unsupported vector {unexpected}" 6769 )); 6770 } 6771 }; 6772 let operation = manifest 6773 .operations 6774 .get(expected.key) 6775 .ok_or_else(|| format!("deletion operation {} is required", expected.key))?; 6776 validate_deletion_operation_scalar(expected.key, "domain", &operation.domain, "social")?; 6777 validate_deletion_operation_scalar(expected.key, "id", &operation.id, expected.id)?; 6778 validate_deletion_operation_scalar( 6779 expected.key, 6780 "stability", 6781 &operation.stability, 6782 "beta", 6783 )?; 6784 validate_deletion_operation_scalar( 6785 expected.key, 6786 "error_class", 6787 &operation.error_class, 6788 expected.error_class, 6789 )?; 6790 validate_deletion_operation_scalar( 6791 expected.key, 6792 "signing", 6793 &operation.signing, 6794 expected.signing, 6795 )?; 6796 validate_deletion_operation_scalar( 6797 expected.key, 6798 "transport", 6799 &operation.transport, 6800 "none", 6801 )?; 6802 if !operation.deterministic { 6803 return Err(format!( 6804 "deletion operation {} deterministic drift: expected true, got false", 6805 expected.key 6806 )); 6807 } 6808 validate_deletion_operation_sequence( 6809 expected.key, 6810 "inputs", 6811 &operation.inputs, 6812 expected.inputs, 6813 )?; 6814 validate_deletion_operation_sequence( 6815 expected.key, 6816 "outputs", 6817 &operation.outputs, 6818 expected.outputs, 6819 )?; 6820 validate_deletion_operation_sequence( 6821 expected.key, 6822 "implementation.rust_modules", 6823 &operation.implementation.rust_modules, 6824 expected.rust_modules, 6825 )?; 6826 validate_deletion_operation_sequence( 6827 expected.key, 6828 "implementation.rust_types", 6829 &operation.implementation.rust_types, 6830 expected.rust_types, 6831 )?; 6832 validate_deletion_operation_scalar( 6833 expected.key, 6834 "conformance.vector", 6835 &operation.conformance.vector, 6836 expected.vector, 6837 )?; 6838 validate_operation_case_kinds(operation, vector)?; 6839 if !operation 6840 .conformance 6841 .case_kinds 6842 .iter() 6843 .map(String::as_str) 6844 .eq(expected.case_kinds.iter().copied()) 6845 { 6846 return Err(format!( 6847 "deletion operation {} conformance.case_kinds drift: expected {:?}, got {:?}", 6848 expected.key, expected.case_kinds, operation.conformance.case_kinds 6849 )); 6850 } 6851 for case_kind in &operation.conformance.case_kinds { 6852 if let Some(previous) = owners.insert(case_kind.as_str(), expected.key) { 6853 return Err(format!( 6854 "deletion conformance case kind {case_kind} is multiply claimed by {previous} and {}", 6855 expected.key 6856 )); 6857 } 6858 } 6859 } 6860 6861 let expected_case_kinds = DELETION_CASE_KINDS.into_iter().collect::<BTreeSet<_>>(); 6862 let actual_case_kinds = owners.keys().copied().collect::<BTreeSet<_>>(); 6863 if actual_case_kinds != expected_case_kinds { 6864 return Err(format!( 6865 "deletion conformance case-kind authority drift: expected {:?}, got {:?}", 6866 expected_case_kinds, actual_case_kinds 6867 )); 6868 } 6869 6870 let mut actual_inventory = BTreeMap::new(); 6871 for entry in &request_vector.vectors { 6872 validate_deletion_vector_shape(entry)?; 6873 if actual_inventory 6874 .insert(entry.id.as_str(), entry.kind.as_str()) 6875 .is_some() 6876 { 6877 return Err(format!( 6878 "deletion conformance vector inventory has duplicate id {}", 6879 entry.id 6880 )); 6881 } 6882 if !entry.id.starts_with("nip09_") { 6883 return Err(format!( 6884 "deletion conformance vector id {} must use the nip09_ prefix", 6885 entry.id 6886 )); 6887 } 6888 if !owners.contains_key(entry.kind.as_str()) { 6889 return Err(format!( 6890 "deletion conformance vector kind {} is not claimed by exactly one operation", 6891 entry.kind 6892 )); 6893 } 6894 } 6895 let mut expected_inventory = BTreeMap::new(); 6896 for (ids, kind) in [ 6897 ( 6898 DELETION_AUTHORED_VALID_IDS.as_slice(), 6899 "social.deletion_request.build_authored_draft.valid", 6900 ), 6901 ( 6902 DELETION_AUTHORED_INVALID_IDS.as_slice(), 6903 "social.deletion_request.build_authored_draft.invalid", 6904 ), 6905 ( 6906 DELETION_PROJECT_VALID_IDS.as_slice(), 6907 "social.deletion_request.project_verified_event.valid", 6908 ), 6909 ( 6910 DELETION_PROJECT_INVALID_IDS.as_slice(), 6911 "social.deletion_request.project_verified_event.invalid", 6912 ), 6913 ( 6914 DELETION_ADMIT_VALID_IDS.as_slice(), 6915 "social.deletion_request.verify_and_admit_event.valid", 6916 ), 6917 ( 6918 DELETION_ADMIT_INVALID_IDS.as_slice(), 6919 "social.deletion_request.verify_and_admit_event.invalid", 6920 ), 6921 ] { 6922 for id in ids { 6923 if expected_inventory.insert(*id, kind).is_some() { 6924 return Err(format!( 6925 "deletion authority contains duplicate expected vector id {id}" 6926 )); 6927 } 6928 } 6929 } 6930 if actual_inventory != expected_inventory { 6931 return Err(format!( 6932 "deletion conformance vector inventory drift: expected {:?}, got {:?}", 6933 expected_inventory, actual_inventory 6934 )); 6935 } 6936 6937 validate_deletion_suppression_vector_inventory(suppression_vector, &owners) 6938 } 6939 6940 fn validate_deletion_suppression_vector_inventory( 6941 vector: &ConformanceVectorFile, 6942 owners: &BTreeMap<&str, &str>, 6943 ) -> Result<(), String> { 6944 if vector.suite != "nip09_suppression_evaluator" { 6945 return Err(format!( 6946 "deletion suppression conformance suite drift: expected nip09_suppression_evaluator, got {}", 6947 vector.suite 6948 )); 6949 } 6950 6951 let expected_kind = "social.deletion_request.evaluate_suppression.valid"; 6952 if owners.get(expected_kind).copied() != Some("social_deletion_request_evaluate_suppression") { 6953 return Err(format!( 6954 "deletion suppression conformance kind {expected_kind} is not owned by the evaluator operation" 6955 )); 6956 } 6957 6958 let expected_inventory = DELETION_SUPPRESSION_VALID_IDS 6959 .into_iter() 6960 .map(|id| (id, expected_kind)) 6961 .collect::<BTreeMap<_, _>>(); 6962 let mut actual_inventory = BTreeMap::new(); 6963 for entry in &vector.vectors { 6964 validate_deletion_suppression_vector_shape(entry)?; 6965 if actual_inventory 6966 .insert(entry.id.as_str(), entry.kind.as_str()) 6967 .is_some() 6968 { 6969 return Err(format!( 6970 "deletion suppression conformance vector inventory has duplicate id {}", 6971 entry.id 6972 )); 6973 } 6974 if !entry.id.starts_with("nip09_suppress_") { 6975 return Err(format!( 6976 "deletion suppression conformance vector id {} must use the nip09_suppress_ prefix", 6977 entry.id 6978 )); 6979 } 6980 if entry.kind != expected_kind { 6981 return Err(format!( 6982 "deletion suppression conformance vector {} kind drift: expected {expected_kind}, got {}", 6983 entry.id, entry.kind 6984 )); 6985 } 6986 } 6987 if actual_inventory != expected_inventory { 6988 return Err(format!( 6989 "deletion suppression conformance vector inventory drift: expected {:?}, got {:?}", 6990 expected_inventory, actual_inventory 6991 )); 6992 } 6993 6994 Ok(()) 6995 } 6996 6997 fn validate_deletion_suppression_vector_shape( 6998 entry: &ConformanceVectorEntry, 6999 ) -> Result<(), String> { 7000 validate_deletion_suppression_forbidden_material(&entry.input, &format!("{}.input", entry.id))?; 7001 let expected_value = entry.expected_value()?; 7002 validate_deletion_suppression_forbidden_material( 7003 expected_value, 7004 &format!("{}.expected", entry.id), 7005 )?; 7006 7007 let input = deletion_object(&entry.input, &format!("{} input", entry.id))?; 7008 validate_deletion_object_keys( 7009 input, 7010 &format!("{} input", entry.id), 7011 &["request_event_jsons", "target_event_json"], 7012 )?; 7013 let target_event_json = input 7014 .get("target_event_json") 7015 .and_then(Value::as_str) 7016 .ok_or_else(|| { 7017 format!( 7018 "deletion suppression vector {} input.target_event_json must be a string", 7019 entry.id 7020 ) 7021 })?; 7022 validate_deletion_suppression_fixed_event( 7023 target_event_json, 7024 &format!("{} target_event_json", entry.id), 7025 None, 7026 )?; 7027 7028 let request_event_jsons = input 7029 .get("request_event_jsons") 7030 .and_then(Value::as_array) 7031 .ok_or_else(|| { 7032 format!( 7033 "deletion suppression vector {} input.request_event_jsons must be an array", 7034 entry.id 7035 ) 7036 })?; 7037 let mut request_ids = BTreeSet::new(); 7038 for (index, value) in request_event_jsons.iter().enumerate() { 7039 let event_json = value.as_str().ok_or_else(|| { 7040 format!( 7041 "deletion suppression vector {} input.request_event_jsons[{index}] must be a string", 7042 entry.id 7043 ) 7044 })?; 7045 let event = validate_deletion_suppression_fixed_event( 7046 event_json, 7047 &format!("{} request_event_jsons[{index}]", entry.id), 7048 Some(5), 7049 )?; 7050 request_ids.insert(event.id); 7051 } 7052 7053 let expected = deletion_object(expected_value, &format!("{} expected", entry.id))?; 7054 validate_deletion_object_keys( 7055 expected, 7056 &format!("{} expected", entry.id), 7057 &["address_reference", "event_reference", "outcome", "reason"], 7058 )?; 7059 let outcome = expected 7060 .get("outcome") 7061 .and_then(Value::as_str) 7062 .ok_or_else(|| { 7063 format!( 7064 "deletion suppression vector {} expected.outcome must be a string", 7065 entry.id 7066 ) 7067 })?; 7068 if !matches!(outcome, "visible" | "suppressed") { 7069 return Err(format!( 7070 "deletion suppression vector {} expected.outcome is unsupported: {outcome}", 7071 entry.id 7072 )); 7073 } 7074 let reason = expected 7075 .get("reason") 7076 .and_then(Value::as_str) 7077 .ok_or_else(|| { 7078 format!( 7079 "deletion suppression vector {} expected.reason must be a string", 7080 entry.id 7081 ) 7082 })?; 7083 if !matches!( 7084 reason, 7085 "deletion_request_immune" 7086 | "deletion_no_authorized_reference" 7087 | "deletion_request_author_mismatch" 7088 | "deletion_address_cutoff_precedes_target" 7089 | "deletion_event_id_reference" 7090 | "deletion_address_reference" 7091 | "deletion_event_id_and_address_reference" 7092 ) { 7093 return Err(format!( 7094 "deletion suppression vector {} expected.reason is unsupported: {reason}", 7095 entry.id 7096 )); 7097 } 7098 7099 let event_reference = validate_deletion_suppression_event_reference( 7100 expected 7101 .get("event_reference") 7102 .expect("exact expected keys contain event_reference"), 7103 &entry.id, 7104 &request_ids, 7105 )?; 7106 let address_reference = validate_deletion_suppression_address_reference( 7107 expected 7108 .get("address_reference") 7109 .expect("exact expected keys contain address_reference"), 7110 &entry.id, 7111 &request_ids, 7112 )?; 7113 let decision_shape_matches = match reason { 7114 "deletion_request_immune" 7115 | "deletion_no_authorized_reference" 7116 | "deletion_request_author_mismatch" => { 7117 outcome == "visible" && !event_reference && !address_reference 7118 } 7119 "deletion_address_cutoff_precedes_target" => { 7120 outcome == "visible" && !event_reference && address_reference 7121 } 7122 "deletion_address_reference" => { 7123 outcome == "suppressed" && !event_reference && address_reference 7124 } 7125 "deletion_event_id_and_address_reference" => { 7126 outcome == "suppressed" && event_reference && address_reference 7127 } 7128 "deletion_event_id_reference" => outcome == "suppressed" && event_reference, 7129 _ => unreachable!("supported reason matched above"), 7130 }; 7131 if !decision_shape_matches { 7132 return Err(format!( 7133 "deletion suppression vector {} expected decision shape is inconsistent with reason {reason}", 7134 entry.id 7135 )); 7136 } 7137 7138 Ok(()) 7139 } 7140 7141 fn validate_deletion_suppression_fixed_event( 7142 event_json: &str, 7143 label: &str, 7144 expected_kind: Option<u32>, 7145 ) -> Result<DeletionConformanceRawEvent, String> { 7146 if contains_nsec_material(event_json) { 7147 return Err(format!( 7148 "deletion suppression vector {label} contains forbidden nsec material" 7149 )); 7150 } 7151 if contains_approved_fixture_secret(event_json) { 7152 return Err(format!( 7153 "deletion suppression vector {label} contains forbidden approved fixture secret material" 7154 )); 7155 } 7156 let raw = serde_json::from_str::<DeletionConformanceRawEvent>(event_json).map_err(|error| { 7157 format!("deletion suppression vector {label} has invalid fixed event shape: {error}") 7158 })?; 7159 if expected_kind.is_some_and(|kind| raw.kind != kind) { 7160 return Err(format!( 7161 "deletion suppression vector {label} must contain a kind-5 deletion request" 7162 )); 7163 } 7164 let canonical = serde_json::to_string(&raw).map_err(|error| { 7165 format!("deletion suppression vector {label} cannot be reserialized: {error}") 7166 })?; 7167 if canonical != event_json { 7168 return Err(format!( 7169 "deletion suppression vector {label} must be compact canonical JSON" 7170 )); 7171 } 7172 Ok(raw) 7173 } 7174 7175 fn validate_deletion_suppression_event_reference( 7176 value: &Value, 7177 id: &str, 7178 request_ids: &BTreeSet<String>, 7179 ) -> Result<bool, String> { 7180 if value.is_null() { 7181 return Ok(false); 7182 } 7183 let reference = deletion_object(value, &format!("{id} expected.event_reference"))?; 7184 validate_deletion_object_keys( 7185 reference, 7186 &format!("{id} expected.event_reference"), 7187 &["request_id"], 7188 )?; 7189 validate_deletion_suppression_request_id( 7190 reference.get("request_id"), 7191 id, 7192 "event_reference.request_id", 7193 request_ids, 7194 )?; 7195 Ok(true) 7196 } 7197 7198 fn validate_deletion_suppression_address_reference( 7199 value: &Value, 7200 id: &str, 7201 request_ids: &BTreeSet<String>, 7202 ) -> Result<bool, String> { 7203 if value.is_null() { 7204 return Ok(false); 7205 } 7206 let reference = deletion_object(value, &format!("{id} expected.address_reference"))?; 7207 validate_deletion_object_keys( 7208 reference, 7209 &format!("{id} expected.address_reference"), 7210 &["coordinate", "inclusive_cutoff", "request_id"], 7211 )?; 7212 let coordinate = reference 7213 .get("coordinate") 7214 .and_then(Value::as_str) 7215 .ok_or_else(|| { 7216 format!( 7217 "deletion suppression vector {id} expected.address_reference.coordinate must be a string" 7218 ) 7219 })?; 7220 validate_deletion_suppression_coordinate(coordinate, id)?; 7221 if !reference 7222 .get("inclusive_cutoff") 7223 .is_some_and(|value| value.as_u64().is_some()) 7224 { 7225 return Err(format!( 7226 "deletion suppression vector {id} expected.address_reference.inclusive_cutoff must be an unsigned integer" 7227 )); 7228 } 7229 validate_deletion_suppression_request_id( 7230 reference.get("request_id"), 7231 id, 7232 "address_reference.request_id", 7233 request_ids, 7234 )?; 7235 Ok(true) 7236 } 7237 7238 fn validate_deletion_suppression_request_id( 7239 value: Option<&Value>, 7240 id: &str, 7241 field: &str, 7242 request_ids: &BTreeSet<String>, 7243 ) -> Result<(), String> { 7244 let request_id = value.and_then(Value::as_str).ok_or_else(|| { 7245 format!("deletion suppression vector {id} expected.{field} must be a string") 7246 })?; 7247 if request_id.len() != 64 7248 || !request_id 7249 .bytes() 7250 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) 7251 { 7252 return Err(format!( 7253 "deletion suppression vector {id} expected.{field} must be lowercase 64-character hex" 7254 )); 7255 } 7256 if !request_ids.contains(request_id) { 7257 return Err(format!( 7258 "deletion suppression vector {id} expected.{field} must identify an input request" 7259 )); 7260 } 7261 Ok(()) 7262 } 7263 7264 fn validate_deletion_suppression_coordinate(coordinate: &str, id: &str) -> Result<(), String> { 7265 let mut parts = coordinate.splitn(3, ':'); 7266 let kind_text = parts.next().unwrap_or_default(); 7267 let pubkey = parts.next().unwrap_or_default(); 7268 let identifier = parts.next().ok_or_else(|| { 7269 format!( 7270 "deletion suppression vector {id} expected.address_reference.coordinate has invalid format" 7271 ) 7272 })?; 7273 let kind = kind_text.parse::<u32>().map_err(|_| { 7274 format!( 7275 "deletion suppression vector {id} expected.address_reference.coordinate kind is invalid" 7276 ) 7277 })?; 7278 if kind.to_string() != kind_text 7279 || pubkey.len() != 64 7280 || !pubkey 7281 .bytes() 7282 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) 7283 || (!matches!(kind, 0 | 3) 7284 && !(10_000..=19_999).contains(&kind) 7285 && !(30_000..=39_999).contains(&kind)) 7286 || ((matches!(kind, 0 | 3) || (10_000..=19_999).contains(&kind)) && !identifier.is_empty()) 7287 { 7288 return Err(format!( 7289 "deletion suppression vector {id} expected.address_reference.coordinate is not canonical" 7290 )); 7291 } 7292 Ok(()) 7293 } 7294 7295 fn validate_deletion_suppression_forbidden_material( 7296 value: &Value, 7297 path: &str, 7298 ) -> Result<(), String> { 7299 match value { 7300 Value::Object(object) => { 7301 for (key, child) in object { 7302 let normalized = key.to_ascii_lowercase(); 7303 if matches!(normalized.as_str(), "base" | "mutation") 7304 || normalized.contains("seed") 7305 || normalized.contains("generator") 7306 || normalized.contains("recipe") 7307 || normalized.contains("secret_key") 7308 || normalized.contains("private_key") 7309 || normalized.contains("signing_key") 7310 || normalized.contains("boundary") 7311 { 7312 return Err(format!( 7313 "deletion suppression vector contains forbidden metadata key {path}.{key}" 7314 )); 7315 } 7316 validate_deletion_suppression_forbidden_material(child, &format!("{path}.{key}"))?; 7317 } 7318 } 7319 Value::Array(values) => { 7320 for (index, child) in values.iter().enumerate() { 7321 validate_deletion_suppression_forbidden_material( 7322 child, 7323 &format!("{path}[{index}]"), 7324 )?; 7325 } 7326 } 7327 Value::String(string) => { 7328 if contains_nsec_material(string) { 7329 return Err(format!( 7330 "deletion suppression vector contains forbidden nsec material at {path}" 7331 )); 7332 } 7333 if contains_approved_fixture_secret(string) { 7334 return Err(format!( 7335 "deletion suppression vector contains forbidden approved fixture secret material at {path}" 7336 )); 7337 } 7338 } 7339 _ => {} 7340 } 7341 Ok(()) 7342 } 7343 7344 fn validate_deletion_vector_shape(entry: &ConformanceVectorEntry) -> Result<(), String> { 7345 validate_deletion_forbidden_metadata(&entry.input, &format!("{}.input", entry.id))?; 7346 let expected_value = entry.expected_value()?; 7347 validate_deletion_forbidden_metadata(expected_value, &format!("{}.expected", entry.id))?; 7348 7349 let input = deletion_object(&entry.input, &format!("{} input", entry.id))?; 7350 let is_authored = entry 7351 .kind 7352 .starts_with("social.deletion_request.build_authored_draft."); 7353 let is_valid = entry.kind.ends_with(".valid"); 7354 if is_authored { 7355 validate_deletion_object_keys( 7356 input, 7357 &format!("{} input", entry.id), 7358 &["address_targets", "content", "event_targets"], 7359 )?; 7360 if !input.get("content").is_some_and(Value::is_string) { 7361 return Err(format!( 7362 "deletion vector {} input.content must be a string", 7363 entry.id 7364 )); 7365 } 7366 let event_targets = input 7367 .get("event_targets") 7368 .and_then(Value::as_array) 7369 .ok_or_else(|| { 7370 format!( 7371 "deletion vector {} input.event_targets must be an array", 7372 entry.id 7373 ) 7374 })?; 7375 for (index, target) in event_targets.iter().enumerate() { 7376 let target = deletion_object( 7377 target, 7378 &format!("{} input.event_targets[{index}]", entry.id), 7379 )?; 7380 validate_deletion_object_keys( 7381 target, 7382 &format!("{} input.event_targets[{index}]", entry.id), 7383 &["event_id", "kind"], 7384 )?; 7385 if !target.get("event_id").is_some_and(Value::is_string) 7386 || !target.get("kind").is_some_and(Value::is_u64) 7387 { 7388 return Err(format!( 7389 "deletion vector {} input.event_targets[{index}] must contain string event_id and unsigned kind", 7390 entry.id 7391 )); 7392 } 7393 } 7394 let address_targets = input 7395 .get("address_targets") 7396 .and_then(Value::as_array) 7397 .ok_or_else(|| { 7398 format!( 7399 "deletion vector {} input.address_targets must be an array", 7400 entry.id 7401 ) 7402 })?; 7403 if !address_targets.iter().all(Value::is_string) { 7404 return Err(format!( 7405 "deletion vector {} input.address_targets must contain only strings", 7406 entry.id 7407 )); 7408 } 7409 } else { 7410 validate_deletion_object_keys(input, &format!("{} input", entry.id), &["event_json"])?; 7411 let event_json = input 7412 .get("event_json") 7413 .and_then(Value::as_str) 7414 .ok_or_else(|| { 7415 format!( 7416 "deletion vector {} input.event_json must be a string", 7417 entry.id 7418 ) 7419 })?; 7420 if contains_nsec_material(event_json) { 7421 return Err(format!( 7422 "deletion vector {} input.event_json contains forbidden nsec material", 7423 entry.id 7424 )); 7425 } 7426 let raw = 7427 serde_json::from_str::<DeletionConformanceRawEvent>(event_json).map_err(|error| { 7428 format!( 7429 "deletion vector {} input.event_json has invalid fixed event shape: {error}", 7430 entry.id 7431 ) 7432 })?; 7433 let canonical = serde_json::to_string(&raw).map_err(|error| { 7434 format!( 7435 "deletion vector {} input.event_json cannot be reserialized: {error}", 7436 entry.id 7437 ) 7438 })?; 7439 if canonical != event_json { 7440 return Err(format!( 7441 "deletion vector {} input.event_json must be compact canonical JSON", 7442 entry.id 7443 )); 7444 } 7445 } 7446 7447 let expected = deletion_object(expected_value, &format!("{} expected", entry.id))?; 7448 if !is_valid { 7449 validate_deletion_object_keys(expected, &format!("{} expected", entry.id), &["error"])?; 7450 if !expected 7451 .get("error") 7452 .and_then(Value::as_str) 7453 .is_some_and(|error| !error.is_empty()) 7454 { 7455 return Err(format!( 7456 "deletion vector {} expected.error must be a non-empty string", 7457 entry.id 7458 )); 7459 } 7460 } else if is_authored { 7461 validate_deletion_object_keys( 7462 expected, 7463 &format!("{} expected", entry.id), 7464 &["content", "kind", "tags"], 7465 )?; 7466 if expected.get("kind").and_then(Value::as_u64) != Some(5) 7467 || !expected.get("content").is_some_and(Value::is_string) 7468 || !expected.get("tags").is_some_and(Value::is_array) 7469 { 7470 return Err(format!( 7471 "deletion vector {} authored expected output must contain kind 5, string content, and tags", 7472 entry.id 7473 )); 7474 } 7475 } else { 7476 validate_deletion_object_keys( 7477 expected, 7478 &format!("{} expected", entry.id), 7479 &[ 7480 "address_targets", 7481 "contract_id", 7482 "diagnostics", 7483 "event_targets", 7484 "kind_advisories", 7485 "raw_tags", 7486 ], 7487 )?; 7488 if expected.get("contract_id").and_then(Value::as_str) 7489 != Some("radroots.social.deletion_request.v1") 7490 { 7491 return Err(format!( 7492 "deletion vector {} expected.contract_id drifted", 7493 entry.id 7494 )); 7495 } 7496 for field in [ 7497 "address_targets", 7498 "diagnostics", 7499 "event_targets", 7500 "kind_advisories", 7501 "raw_tags", 7502 ] { 7503 if !expected.get(field).is_some_and(Value::is_array) { 7504 return Err(format!( 7505 "deletion vector {} expected.{field} must be an array", 7506 entry.id 7507 )); 7508 } 7509 } 7510 } 7511 7512 Ok(()) 7513 } 7514 7515 const APPROVED_FIXTURE_SECRET_TEXT_SHA256: [&str; 4] = [ 7516 "abd5b64bb0a9a0b9b2e928edb278d0f4d442d16e620ac56570c354a040f4e01a", 7517 "619b2fc89e98c17205800071802b3f06e12b05b79401da800b8b13aa8597d240", 7518 "82e759d54455fbfa5b9c58367b37f1fbc3d54becc097dcdf71fa48ee0af6b2a6", 7519 "510b06b0d391a517860b8e406cdc827b0481f2e449c9817b73adad07f4ff02a7", 7520 ]; 7521 7522 fn validate_deletion_forbidden_metadata(value: &Value, path: &str) -> Result<(), String> { 7523 match value { 7524 Value::Object(object) => { 7525 for (key, child) in object { 7526 if is_deletion_forbidden_metadata_key(key) { 7527 return Err(format!( 7528 "deletion vector contains forbidden metadata key {path}.{key}" 7529 )); 7530 } 7531 validate_deletion_forbidden_metadata(child, &format!("{path}.{key}"))?; 7532 } 7533 } 7534 Value::Array(values) => { 7535 for (index, child) in values.iter().enumerate() { 7536 validate_deletion_forbidden_metadata(child, &format!("{path}[{index}]"))?; 7537 } 7538 } 7539 Value::String(string) => { 7540 if contains_nsec_material(string) { 7541 return Err(format!( 7542 "deletion vector contains forbidden nsec material at {path}" 7543 )); 7544 } 7545 if contains_approved_fixture_secret(string) { 7546 return Err(format!( 7547 "deletion vector contains forbidden approved fixture secret material at {path}" 7548 )); 7549 } 7550 } 7551 _ => {} 7552 } 7553 Ok(()) 7554 } 7555 7556 fn is_deletion_forbidden_metadata_key(key: &str) -> bool { 7557 let normalized = key.to_ascii_lowercase(); 7558 matches!(normalized.as_str(), "base" | "mutation") 7559 || normalized.contains("seed") 7560 || normalized.contains("generator") 7561 || normalized.contains("recipe") 7562 || normalized.contains("secret_key") 7563 || normalized.contains("private_key") 7564 || normalized.contains("signing_key") 7565 || normalized.contains("boundary") 7566 || normalized.contains("authorization") 7567 || normalized.contains("authorized") 7568 || normalized.contains("cutoff") 7569 || normalized.contains("evaluator") 7570 || normalized.contains("store_mutation") 7571 || normalized.contains("suppression") 7572 || normalized.contains("suppressed") 7573 || normalized == "effect" 7574 || normalized.ends_with("_effect") 7575 || normalized == "effects" 7576 } 7577 7578 fn contains_nsec_material(value: &str) -> bool { 7579 value.to_ascii_lowercase().contains("nsec1") 7580 } 7581 7582 fn contains_approved_fixture_secret(value: &str) -> bool { 7583 value 7584 .to_ascii_lowercase() 7585 .as_bytes() 7586 .windows(64) 7587 .filter(|window| window.iter().all(u8::is_ascii_hexdigit)) 7588 .any(|window| { 7589 let digest = hex::encode(Sha256::digest(window)); 7590 APPROVED_FIXTURE_SECRET_TEXT_SHA256.contains(&digest.as_str()) 7591 }) 7592 } 7593 7594 fn deletion_object<'a>( 7595 value: &'a Value, 7596 label: &str, 7597 ) -> Result<&'a serde_json::Map<String, Value>, String> { 7598 value 7599 .as_object() 7600 .ok_or_else(|| format!("deletion vector {label} must be an object")) 7601 } 7602 7603 fn validate_deletion_object_keys( 7604 object: &serde_json::Map<String, Value>, 7605 label: &str, 7606 expected: &[&str], 7607 ) -> Result<(), String> { 7608 let actual = object.keys().map(String::as_str).collect::<BTreeSet<_>>(); 7609 let expected = expected.iter().copied().collect::<BTreeSet<_>>(); 7610 if actual != expected { 7611 return Err(format!( 7612 "deletion vector {label} keys drift: expected {:?}, got {:?}", 7613 expected, actual 7614 )); 7615 } 7616 Ok(()) 7617 } 7618 7619 fn validate_deletion_operation_scalar( 7620 operation_key: &str, 7621 field: &str, 7622 actual: &str, 7623 expected: &str, 7624 ) -> Result<(), String> { 7625 if actual != expected { 7626 return Err(format!( 7627 "deletion operation {operation_key} {field} drift: expected {expected}, got {actual}" 7628 )); 7629 } 7630 Ok(()) 7631 } 7632 7633 fn validate_deletion_operation_sequence( 7634 operation_key: &str, 7635 field: &str, 7636 actual: &[String], 7637 expected: &[&str], 7638 ) -> Result<(), String> { 7639 if !actual 7640 .iter() 7641 .map(String::as_str) 7642 .eq(expected.iter().copied()) 7643 { 7644 return Err(format!( 7645 "deletion operation {operation_key} {field} drift: expected {:?}, got {:?}", 7646 expected, actual 7647 )); 7648 } 7649 Ok(()) 7650 } 7651 7652 fn validate_food_availability_operation_authority( 7653 manifest: &OperationsContractManifest, 7654 workspace_root: &Path, 7655 ) -> Result<(), String> { 7656 let vector = validate_conformance_vector_file( 7657 &workspace_root.join(FOOD_AVAILABILITY_CONFORMANCE_VECTOR_RELATIVE), 7658 &manifest.contract.version, 7659 )?; 7660 validate_food_availability_operation_inventory(manifest, &vector) 7661 } 7662 7663 fn validate_food_availability_operation_inventory( 7664 manifest: &OperationsContractManifest, 7665 vector: &ConformanceVectorFile, 7666 ) -> Result<(), String> { 7667 let shared_types = collect_non_empty_set( 7668 &manifest.shared_types.public, 7669 "food availability operation shared_types.public", 7670 )?; 7671 for required in REQUIRED_FOOD_AVAILABILITY_PUBLIC_TYPES { 7672 if !shared_types.contains(required) { 7673 return Err(format!( 7674 "food availability operation authority requires shared public type {required}" 7675 )); 7676 } 7677 } 7678 7679 let expected_keys = FOOD_AVAILABILITY_OPERATION_EXPECTATIONS 7680 .iter() 7681 .map(|expectation| expectation.key.to_string()) 7682 .collect::<BTreeSet<_>>(); 7683 let actual_keys = manifest 7684 .operations 7685 .iter() 7686 .filter(|(key, operation)| { 7687 operation.domain == "food_availability" 7688 || operation.conformance.vector == FOOD_AVAILABILITY_CONFORMANCE_VECTOR_RELATIVE 7689 || key.starts_with("food_availability_") 7690 || operation.id.starts_with("food_availability.") 7691 }) 7692 .map(|(key, _)| key.clone()) 7693 .collect::<BTreeSet<_>>(); 7694 if actual_keys != expected_keys { 7695 let missing = expected_keys 7696 .difference(&actual_keys) 7697 .cloned() 7698 .collect::<BTreeSet<_>>(); 7699 let unexpected = actual_keys 7700 .difference(&expected_keys) 7701 .cloned() 7702 .collect::<BTreeSet<_>>(); 7703 return Err(format!( 7704 "food availability operation authority drift: missing {}; unexpected {}", 7705 join_set(&missing), 7706 join_set(&unexpected) 7707 )); 7708 } 7709 7710 let mut owners = BTreeMap::new(); 7711 for expected in FOOD_AVAILABILITY_OPERATION_EXPECTATIONS { 7712 let operation = manifest 7713 .operations 7714 .get(expected.key) 7715 .ok_or_else(|| format!("food availability operation {} is required", expected.key))?; 7716 validate_food_availability_operation_scalar( 7717 expected.key, 7718 "domain", 7719 &operation.domain, 7720 "food_availability", 7721 )?; 7722 validate_food_availability_operation_scalar( 7723 expected.key, 7724 "id", 7725 &operation.id, 7726 expected.id, 7727 )?; 7728 validate_food_availability_operation_scalar( 7729 expected.key, 7730 "stability", 7731 &operation.stability, 7732 "beta", 7733 )?; 7734 validate_food_availability_operation_scalar( 7735 expected.key, 7736 "error_class", 7737 &operation.error_class, 7738 expected.error_class, 7739 )?; 7740 validate_food_availability_operation_scalar( 7741 expected.key, 7742 "signing", 7743 &operation.signing, 7744 expected.signing, 7745 )?; 7746 validate_food_availability_operation_scalar( 7747 expected.key, 7748 "transport", 7749 &operation.transport, 7750 "none", 7751 )?; 7752 if !operation.deterministic { 7753 return Err(format!( 7754 "food availability operation {} deterministic drift: expected true, got false", 7755 expected.key 7756 )); 7757 } 7758 validate_food_availability_operation_sequence( 7759 expected.key, 7760 "inputs", 7761 &operation.inputs, 7762 expected.inputs, 7763 )?; 7764 validate_food_availability_operation_sequence( 7765 expected.key, 7766 "outputs", 7767 &operation.outputs, 7768 expected.outputs, 7769 )?; 7770 validate_food_availability_operation_sequence( 7771 expected.key, 7772 "implementation.rust_modules", 7773 &operation.implementation.rust_modules, 7774 expected.rust_modules, 7775 )?; 7776 validate_food_availability_operation_sequence( 7777 expected.key, 7778 "implementation.rust_types", 7779 &operation.implementation.rust_types, 7780 expected.rust_types, 7781 )?; 7782 validate_food_availability_operation_scalar( 7783 expected.key, 7784 "conformance.vector", 7785 &operation.conformance.vector, 7786 FOOD_AVAILABILITY_CONFORMANCE_VECTOR_RELATIVE, 7787 )?; 7788 validate_operation_case_kinds(operation, vector)?; 7789 if !operation 7790 .conformance 7791 .case_kinds 7792 .iter() 7793 .map(String::as_str) 7794 .eq(expected.case_kinds.iter().copied()) 7795 { 7796 return Err(format!( 7797 "food availability operation {} conformance.case_kinds drift: expected {:?}, got {:?}", 7798 expected.key, expected.case_kinds, operation.conformance.case_kinds 7799 )); 7800 } 7801 for case_kind in &operation.conformance.case_kinds { 7802 if let Some(previous) = owners.insert(case_kind.as_str(), expected.key) { 7803 return Err(format!( 7804 "food availability conformance case kind {case_kind} is multiply claimed by {previous} and {}", 7805 expected.key 7806 )); 7807 } 7808 } 7809 } 7810 7811 let expected_case_kinds = FOOD_AVAILABILITY_CASE_KINDS 7812 .into_iter() 7813 .collect::<BTreeSet<_>>(); 7814 let actual_case_kinds = owners.keys().copied().collect::<BTreeSet<_>>(); 7815 if actual_case_kinds != expected_case_kinds { 7816 return Err(format!( 7817 "food availability conformance case-kind authority drift: expected {:?}, got {:?}", 7818 expected_case_kinds, actual_case_kinds 7819 )); 7820 } 7821 7822 let mut actual_inventory = BTreeMap::new(); 7823 for entry in &vector.vectors { 7824 if actual_inventory 7825 .insert(entry.id.as_str(), entry.kind.as_str()) 7826 .is_some() 7827 { 7828 return Err(format!( 7829 "food availability conformance vector inventory has duplicate id {}", 7830 entry.id 7831 )); 7832 } 7833 } 7834 for kind in actual_inventory.values() { 7835 if !owners.contains_key(kind) { 7836 return Err(format!( 7837 "food availability conformance vector kind {kind} is not claimed by exactly one operation" 7838 )); 7839 } 7840 } 7841 let expected_inventory = FOOD_AVAILABILITY_VECTOR_EXPECTATIONS 7842 .into_iter() 7843 .collect::<BTreeMap<_, _>>(); 7844 if actual_inventory != expected_inventory { 7845 return Err(format!( 7846 "food availability conformance vector inventory drift: expected {:?}, got {:?}", 7847 expected_inventory, actual_inventory 7848 )); 7849 } 7850 Ok(()) 7851 } 7852 7853 fn validate_food_availability_operation_scalar( 7854 operation_key: &str, 7855 field: &str, 7856 actual: &str, 7857 expected: &str, 7858 ) -> Result<(), String> { 7859 if actual != expected { 7860 return Err(format!( 7861 "food availability operation {operation_key} {field} drift: expected {expected}, got {actual}" 7862 )); 7863 } 7864 Ok(()) 7865 } 7866 7867 fn validate_food_availability_operation_sequence( 7868 operation_key: &str, 7869 field: &str, 7870 actual: &[String], 7871 expected: &[&str], 7872 ) -> Result<(), String> { 7873 if !actual 7874 .iter() 7875 .map(String::as_str) 7876 .eq(expected.iter().copied()) 7877 { 7878 return Err(format!( 7879 "food availability operation {operation_key} {field} drift: expected {:?}, got {:?}", 7880 expected, actual 7881 )); 7882 } 7883 Ok(()) 7884 } 7885 7886 fn validate_calendar_operation_authority( 7887 manifest: &OperationsContractManifest, 7888 shared_types: &BTreeSet<String>, 7889 ) -> Result<(), String> { 7890 for required in REQUIRED_CALENDAR_PUBLIC_TYPES { 7891 if !shared_types.contains(required) { 7892 return Err(format!( 7893 "calendar operation authority requires shared public type {required}" 7894 )); 7895 } 7896 } 7897 7898 let expected_keys = CALENDAR_OPERATION_EXPECTATIONS 7899 .iter() 7900 .map(|expectation| expectation.key.to_string()) 7901 .collect::<BTreeSet<_>>(); 7902 let actual_keys = manifest 7903 .operations 7904 .iter() 7905 .filter(|(key, operation)| { 7906 key.starts_with("social_calendar_") || operation.id.starts_with("social.calendar") 7907 }) 7908 .map(|(key, _)| key.clone()) 7909 .collect::<BTreeSet<_>>(); 7910 if actual_keys != expected_keys { 7911 let missing = expected_keys 7912 .difference(&actual_keys) 7913 .cloned() 7914 .collect::<BTreeSet<_>>(); 7915 let unexpected = actual_keys 7916 .difference(&expected_keys) 7917 .cloned() 7918 .collect::<BTreeSet<_>>(); 7919 return Err(format!( 7920 "calendar operation authority drift: missing {}; unexpected {}", 7921 join_set(&missing), 7922 join_set(&unexpected) 7923 )); 7924 } 7925 7926 for expected in CALENDAR_OPERATION_EXPECTATIONS { 7927 let operation = manifest 7928 .operations 7929 .get(expected.key) 7930 .ok_or_else(|| format!("calendar operation {} is required", expected.key))?; 7931 validate_calendar_operation_scalar(expected.key, "domain", &operation.domain, "social")?; 7932 validate_calendar_operation_scalar(expected.key, "id", &operation.id, expected.id)?; 7933 validate_calendar_operation_scalar( 7934 expected.key, 7935 "stability", 7936 &operation.stability, 7937 "beta", 7938 )?; 7939 validate_calendar_operation_scalar( 7940 expected.key, 7941 "error_class", 7942 &operation.error_class, 7943 expected.error_class, 7944 )?; 7945 validate_calendar_operation_scalar(expected.key, "signing", &operation.signing, "none")?; 7946 validate_calendar_operation_scalar( 7947 expected.key, 7948 "transport", 7949 &operation.transport, 7950 "none", 7951 )?; 7952 if !operation.deterministic { 7953 return Err(format!( 7954 "calendar operation {} deterministic drift: expected true, got false", 7955 expected.key 7956 )); 7957 } 7958 validate_calendar_operation_sequence( 7959 expected.key, 7960 "inputs", 7961 &operation.inputs, 7962 expected.inputs, 7963 )?; 7964 validate_calendar_operation_sequence( 7965 expected.key, 7966 "outputs", 7967 &operation.outputs, 7968 expected.outputs, 7969 )?; 7970 validate_calendar_operation_sequence( 7971 expected.key, 7972 "implementation.rust_modules", 7973 &operation.implementation.rust_modules, 7974 expected.rust_modules, 7975 )?; 7976 validate_calendar_operation_sequence( 7977 expected.key, 7978 "implementation.rust_types", 7979 &operation.implementation.rust_types, 7980 expected.rust_types, 7981 )?; 7982 validate_calendar_operation_scalar( 7983 expected.key, 7984 "conformance.vector", 7985 &operation.conformance.vector, 7986 expected.vector, 7987 )?; 7988 } 7989 7990 Ok(()) 7991 } 7992 7993 fn validate_calendar_operation_scalar( 7994 operation_key: &str, 7995 field: &str, 7996 actual: &str, 7997 expected: &str, 7998 ) -> Result<(), String> { 7999 if actual != expected { 8000 return Err(format!( 8001 "calendar operation {operation_key} {field} drift: expected {expected}, got {actual}" 8002 )); 8003 } 8004 Ok(()) 8005 } 8006 8007 fn validate_calendar_operation_sequence( 8008 operation_key: &str, 8009 field: &str, 8010 actual: &[String], 8011 expected: &[&str], 8012 ) -> Result<(), String> { 8013 if !actual 8014 .iter() 8015 .map(String::as_str) 8016 .eq(expected.iter().copied()) 8017 { 8018 return Err(format!( 8019 "calendar operation {operation_key} {field} drift: expected {:?}, got {:?}", 8020 expected, actual 8021 )); 8022 } 8023 Ok(()) 8024 } 8025 8026 fn validate_no_retired_operation_event_names( 8027 values: &[String], 8028 context: &str, 8029 ) -> Result<(), String> { 8030 for value in values { 8031 for retired in RETIRED_OPERATION_EVENT_NAMES { 8032 if value == retired || value.ends_with(&format!("::{retired}")) { 8033 return Err(format!( 8034 "{context} uses retired event type {retired}; use target-state event and wire names" 8035 )); 8036 } 8037 } 8038 } 8039 Ok(()) 8040 } 8041 8042 fn package_field_configured(table: &toml::value::Table, field: &str) -> bool { 8043 let Some(value) = table.get(field) else { 8044 return false; 8045 }; 8046 match value { 8047 toml::Value::String(raw) => !raw.trim().is_empty(), 8048 toml::Value::Array(values) => !values.is_empty(), 8049 toml::Value::Table(inner) => inner 8050 .get("workspace") 8051 .and_then(toml::Value::as_bool) 8052 .is_some_and(|configured| configured), 8053 _ => false, 8054 } 8055 } 8056 8057 fn package_string_array<'a>( 8058 package: &'a toml::value::Table, 8059 crate_name: &str, 8060 field: &str, 8061 ) -> Result<Vec<&'a str>, String> { 8062 let values = package 8063 .get(field) 8064 .and_then(toml::Value::as_array) 8065 .ok_or_else(|| format!("publish crate {crate_name} must define package.{field}"))?; 8066 if values.is_empty() { 8067 return Err(format!( 8068 "publish crate {crate_name} package.{field} must not be empty" 8069 )); 8070 } 8071 let mut resolved = Vec::with_capacity(values.len()); 8072 let mut unique = BTreeSet::new(); 8073 for value in values { 8074 let value = value.as_str().ok_or_else(|| { 8075 format!("publish crate {crate_name} package.{field} entries must be strings") 8076 })?; 8077 if value.trim().is_empty() { 8078 return Err(format!( 8079 "publish crate {crate_name} package.{field} entries must not be empty" 8080 )); 8081 } 8082 if !unique.insert(value) { 8083 return Err(format!( 8084 "publish crate {crate_name} package.{field} contains duplicate {value}" 8085 )); 8086 } 8087 resolved.push(value); 8088 } 8089 Ok(resolved) 8090 } 8091 8092 fn validate_package_file_matches( 8093 workspace_root: &Path, 8094 package_root: &Path, 8095 crate_name: &str, 8096 relative: &str, 8097 ) -> Result<(), String> { 8098 let package_path = package_root.join(relative); 8099 let root_path = workspace_root.join(relative); 8100 let package_bytes = fs::read(&package_path) 8101 .map_err(|error| format!("publish crate {crate_name} must include {relative}: {error}"))?; 8102 let root_bytes = 8103 fs::read(&root_path).map_err(|error| format!("read {}: {error}", root_path.display()))?; 8104 if package_bytes != root_bytes { 8105 return Err(format!( 8106 "publish crate {crate_name} {relative} must match the workspace license" 8107 )); 8108 } 8109 Ok(()) 8110 } 8111 8112 fn validate_publish_package_metadata( 8113 workspace_root: &Path, 8114 publish_crates: &BTreeSet<String>, 8115 ) -> Result<(), String> { 8116 let mut package_records = BTreeMap::new(); 8117 for record in workspace_package_records(workspace_root)? { 8118 if package_records 8119 .insert(record.name.clone(), record) 8120 .is_some() 8121 { 8122 return Err("duplicate workspace package name in package metadata map".to_string()); 8123 } 8124 } 8125 for crate_name in publish_crates { 8126 let record = match package_records.get(crate_name) { 8127 Some(record) => record, 8128 None => { 8129 return Err(format!( 8130 "publish crate {} has no workspace manifest", 8131 crate_name 8132 )); 8133 } 8134 }; 8135 let package = record 8136 .manifest_value 8137 .get("package") 8138 .and_then(toml::Value::as_table) 8139 .expect("workspace package records include [package] table"); 8140 8141 if !package_field_configured(package, "description") { 8142 return Err(format!( 8143 "publish crate {} must define a non-empty package.description", 8144 crate_name 8145 )); 8146 } 8147 for field in [ 8148 "authors", 8149 "version", 8150 "edition", 8151 "rust-version", 8152 "license", 8153 "repository", 8154 "homepage", 8155 "documentation", 8156 "readme", 8157 ] { 8158 if !package_field_configured(package, field) { 8159 return Err(format!( 8160 "publish crate {} must configure package.{}", 8161 crate_name, field 8162 )); 8163 } 8164 } 8165 8166 let expected_documentation = format!("https://docs.rs/{crate_name}"); 8167 if package.get("documentation").and_then(toml::Value::as_str) 8168 != Some(expected_documentation.as_str()) 8169 { 8170 return Err(format!( 8171 "publish crate {crate_name} package.documentation must be {expected_documentation}" 8172 )); 8173 } 8174 if package.get("license-file").is_some() { 8175 return Err(format!( 8176 "publish crate {crate_name} must use the workspace SPDX license expression" 8177 )); 8178 } 8179 8180 let keywords = package_string_array(package, crate_name, "keywords")?; 8181 if keywords.len() > 5 { 8182 return Err(format!( 8183 "publish crate {crate_name} package.keywords exceeds the crates.io limit of 5" 8184 )); 8185 } 8186 let categories = package_string_array(package, crate_name, "categories")?; 8187 if categories.len() > 5 { 8188 return Err(format!( 8189 "publish crate {crate_name} package.categories exceeds the crates.io limit of 5" 8190 )); 8191 } 8192 8193 let include = package_string_array(package, crate_name, "include")?; 8194 for required in [ 8195 "src/**", 8196 "tests/**", 8197 "README.md", 8198 "LICENSE-APACHE", 8199 "LICENSE-MIT", 8200 ] { 8201 if !include.contains(&required) { 8202 return Err(format!( 8203 "publish crate {crate_name} package.include must contain {required}" 8204 )); 8205 } 8206 } 8207 8208 let package_root = record 8209 .manifest_path 8210 .parent() 8211 .expect("workspace member manifest has a parent"); 8212 if !package_root.join("README.md").is_file() { 8213 return Err(format!( 8214 "publish crate {crate_name} must include a package-local README.md" 8215 )); 8216 } 8217 validate_package_file_matches(workspace_root, package_root, crate_name, "LICENSE-APACHE")?; 8218 validate_package_file_matches(workspace_root, package_root, crate_name, "LICENSE-MIT")?; 8219 8220 let docs_rs = package 8221 .get("metadata") 8222 .and_then(toml::Value::as_table) 8223 .and_then(|metadata| metadata.get("docs")) 8224 .and_then(toml::Value::as_table) 8225 .and_then(|docs| docs.get("rs")) 8226 .and_then(toml::Value::as_table) 8227 .ok_or_else(|| { 8228 format!("publish crate {crate_name} must define [package.metadata.docs.rs]") 8229 })?; 8230 if docs_rs 8231 .get("all-features") 8232 .and_then(toml::Value::as_bool) 8233 .unwrap_or(false) 8234 { 8235 return Err(format!( 8236 "publish crate {crate_name} docs.rs must use an intentional feature set" 8237 )); 8238 } 8239 let docs_features = docs_rs 8240 .get("features") 8241 .and_then(toml::Value::as_array) 8242 .ok_or_else(|| format!("publish crate {crate_name} docs.rs must define features"))?; 8243 let declared_features = record 8244 .manifest_value 8245 .get("features") 8246 .and_then(toml::Value::as_table); 8247 for feature in docs_features { 8248 let feature = feature.as_str().ok_or_else(|| { 8249 format!("publish crate {crate_name} docs.rs features must be strings") 8250 })?; 8251 if !declared_features.is_some_and(|features| features.contains_key(feature)) { 8252 return Err(format!( 8253 "publish crate {crate_name} docs.rs selects unknown feature {feature}" 8254 )); 8255 } 8256 } 8257 } 8258 Ok(()) 8259 } 8260 8261 fn parse_coverage_percent(raw: &str, field: &str, crate_name: &str) -> Result<f64, String> { 8262 match raw.parse::<f64>() { 8263 Ok(value) => Ok(value), 8264 Err(e) => Err(format!("parse {} for {}: {e}", field, crate_name)), 8265 } 8266 } 8267 8268 fn parse_branch_coverage_percent(raw: &str, crate_name: &str) -> Result<Option<f64>, String> { 8269 if raw == "unavailable" { 8270 return Ok(None); 8271 } 8272 parse_coverage_percent(raw, "branch", crate_name).map(Some) 8273 } 8274 8275 fn branch_coverage_fails(branch: Option<f64>, thresholds: CoverageThresholds) -> bool { 8276 match branch { 8277 Some(value) => value < thresholds.fail_under_branches, 8278 None => thresholds.require_branches, 8279 } 8280 } 8281 8282 fn branch_coverage_display(branch: Option<f64>) -> String { 8283 branch 8284 .map(|value| value.to_string()) 8285 .unwrap_or_else(|| "unavailable".to_string()) 8286 } 8287 8288 #[derive(Debug)] 8289 struct CoverageRefreshRow { 8290 status: String, 8291 exec: f64, 8292 func: f64, 8293 branch: Option<f64>, 8294 region: f64, 8295 report_path: PathBuf, 8296 } 8297 8298 #[derive(Debug, Deserialize)] 8299 struct CoverageGateReportForValidation { 8300 scope: String, 8301 thresholds: CoverageGateReportThresholdsForValidation, 8302 measured: CoverageGateReportMeasuredForValidation, 8303 result: CoverageGateReportResultForValidation, 8304 } 8305 8306 #[derive(Debug, Deserialize)] 8307 struct CoverageGateReportThresholdsForValidation { 8308 executable_lines: f64, 8309 functions: f64, 8310 regions: f64, 8311 branches: f64, 8312 branches_required: bool, 8313 } 8314 8315 #[derive(Debug, Deserialize)] 8316 struct CoverageGateReportMeasuredForValidation { 8317 executable_lines_percent: f64, 8318 functions_percent: f64, 8319 branches_percent: Option<f64>, 8320 branches_available: bool, 8321 summary_regions_percent: f64, 8322 } 8323 8324 #[derive(Debug, Deserialize)] 8325 struct CoverageGateReportResultForValidation { 8326 pass: bool, 8327 } 8328 8329 type CoverageRefreshRows = BTreeMap<String, CoverageRefreshRow>; 8330 8331 fn coverage_refresh_report_path( 8332 workspace_root: &Path, 8333 report_path: &Path, 8334 raw_report_path: &str, 8335 crate_name: &str, 8336 ) -> Result<PathBuf, String> { 8337 let trimmed = raw_report_path.trim(); 8338 if trimmed.is_empty() { 8339 return Err(format!( 8340 "coverage row for crate {} in {} must include a report path", 8341 crate_name, 8342 report_path.display() 8343 )); 8344 } 8345 let path = Path::new(trimmed); 8346 if path.is_absolute() { 8347 Ok(path.to_path_buf()) 8348 } else { 8349 Ok(workspace_root.join(path)) 8350 } 8351 } 8352 8353 fn load_coverage_refresh_rows(workspace_root: &Path) -> Result<CoverageRefreshRows, String> { 8354 let report_path = workspace_root 8355 .join("target") 8356 .join("coverage") 8357 .join("coverage-refresh.tsv"); 8358 let raw = match fs::read_to_string(&report_path) { 8359 Ok(raw) => raw, 8360 Err(e) => return Err(format!("read {}: {e}", report_path.display())), 8361 }; 8362 let mut rows = BTreeMap::new(); 8363 for line in raw.lines().skip(1) { 8364 let trimmed = line.trim(); 8365 if trimmed.is_empty() { 8366 continue; 8367 } 8368 let parts = trimmed.split('\t').collect::<Vec<_>>(); 8369 if parts.len() < 7 { 8370 return Err(format!( 8371 "coverage row must have at least 7 columns in {}: {}", 8372 report_path.display(), 8373 trimmed 8374 )); 8375 } 8376 let crate_name = parts[0].to_string(); 8377 let status = parts[1].to_string(); 8378 let exec = parse_coverage_percent(parts[2], "exec", &crate_name)?; 8379 let func = parse_coverage_percent(parts[3], "func", &crate_name)?; 8380 let branch = parse_branch_coverage_percent(parts[4], &crate_name)?; 8381 let region = parse_coverage_percent(parts[5], "region", &crate_name)?; 8382 let row_report_path = 8383 coverage_refresh_report_path(workspace_root, &report_path, parts[6], &crate_name)?; 8384 if rows 8385 .insert( 8386 crate_name.clone(), 8387 CoverageRefreshRow { 8388 status, 8389 exec, 8390 func, 8391 branch, 8392 region, 8393 report_path: row_report_path, 8394 }, 8395 ) 8396 .is_some() 8397 { 8398 return Err(format!( 8399 "duplicate coverage row for crate {} in {}", 8400 crate_name, 8401 report_path.display() 8402 )); 8403 } 8404 } 8405 Ok(rows) 8406 } 8407 8408 #[cfg_attr(not(test), allow(dead_code))] 8409 fn validate_required_coverage_summary( 8410 workspace_root: &Path, 8411 required_crates: &BTreeSet<String>, 8412 thresholds: CoverageThresholds, 8413 ) -> Result<(), String> { 8414 let rows = load_coverage_refresh_rows(workspace_root)?; 8415 for crate_name in required_crates { 8416 let row = rows.get(crate_name).ok_or_else(|| { 8417 format!( 8418 "required coverage crate {} missing from coverage-refresh.tsv", 8419 crate_name 8420 ) 8421 })?; 8422 if row.status != "pass" { 8423 return Err(format!( 8424 "required coverage crate {} has non-pass status {}", 8425 crate_name, row.status 8426 )); 8427 } 8428 if row.exec < thresholds.fail_under_exec_lines 8429 || row.func < thresholds.fail_under_functions 8430 || branch_coverage_fails(row.branch, thresholds) 8431 || row.region < thresholds.fail_under_regions 8432 { 8433 return Err(format!( 8434 "required coverage crate {} must satisfy coverage policy {},{},{},{}, found {}/{}/{}/{}", 8435 crate_name, 8436 thresholds.fail_under_exec_lines, 8437 thresholds.fail_under_functions, 8438 thresholds.fail_under_branches, 8439 thresholds.fail_under_regions, 8440 row.exec, 8441 row.func, 8442 branch_coverage_display(row.branch), 8443 row.region 8444 )); 8445 } 8446 } 8447 Ok(()) 8448 } 8449 8450 fn read_coverage_gate_report( 8451 path: &Path, 8452 crate_name: &str, 8453 ) -> Result<CoverageGateReportForValidation, String> { 8454 let raw = match fs::read_to_string(path) { 8455 Ok(raw) => raw, 8456 Err(e) => { 8457 return Err(format!( 8458 "read coverage gate report for {} at {}: {e}", 8459 crate_name, 8460 path.display() 8461 )); 8462 } 8463 }; 8464 serde_json::from_str::<CoverageGateReportForValidation>(&raw).map_err(|e| { 8465 format!( 8466 "parse coverage gate report for {} at {}: {e}", 8467 crate_name, 8468 path.display() 8469 ) 8470 }) 8471 } 8472 8473 fn coverage_percent_matches(left: f64, right: f64) -> bool { 8474 (left - right).abs() <= COVERAGE_REPORT_EPSILON 8475 } 8476 8477 fn coverage_branch_percent_matches(left: Option<f64>, right: Option<f64>) -> bool { 8478 match (left, right) { 8479 (Some(left), Some(right)) => coverage_percent_matches(left, right), 8480 (None, None) => true, 8481 _ => false, 8482 } 8483 } 8484 8485 fn coverage_gate_report_thresholds_match( 8486 report: &CoverageGateReportThresholdsForValidation, 8487 thresholds: CoverageThresholds, 8488 ) -> bool { 8489 coverage_percent_matches(report.executable_lines, thresholds.fail_under_exec_lines) 8490 && coverage_percent_matches(report.functions, thresholds.fail_under_functions) 8491 && coverage_percent_matches(report.regions, thresholds.fail_under_regions) 8492 && coverage_percent_matches(report.branches, thresholds.fail_under_branches) 8493 && report.branches_required == thresholds.require_branches 8494 } 8495 8496 fn validate_coverage_gate_report_for_row( 8497 crate_name: &str, 8498 row: &CoverageRefreshRow, 8499 thresholds: CoverageThresholds, 8500 ) -> Result<(), String> { 8501 let report = read_coverage_gate_report(&row.report_path, crate_name)?; 8502 if report.scope != crate_name { 8503 return Err(format!( 8504 "coverage gate report {} has scope {}, expected {}", 8505 row.report_path.display(), 8506 report.scope, 8507 crate_name 8508 )); 8509 } 8510 if !coverage_gate_report_thresholds_match(&report.thresholds, thresholds) { 8511 return Err(format!( 8512 "coverage gate report {} for {} thresholds do not match policy", 8513 row.report_path.display(), 8514 crate_name 8515 )); 8516 } 8517 if !report.result.pass { 8518 return Err(format!( 8519 "coverage gate report {} for {} has non-pass result", 8520 row.report_path.display(), 8521 crate_name 8522 )); 8523 } 8524 if report.measured.branches_available != report.measured.branches_percent.is_some() { 8525 return Err(format!( 8526 "coverage gate report {} for {} has inconsistent branch measurement", 8527 row.report_path.display(), 8528 crate_name 8529 )); 8530 } 8531 if !coverage_percent_matches(row.exec, report.measured.executable_lines_percent) 8532 || !coverage_percent_matches(row.func, report.measured.functions_percent) 8533 || !coverage_branch_percent_matches(row.branch, report.measured.branches_percent) 8534 || !coverage_percent_matches(row.region, report.measured.summary_regions_percent) 8535 { 8536 return Err(format!( 8537 "coverage row for {} does not match coverage gate report {}", 8538 crate_name, 8539 row.report_path.display() 8540 )); 8541 } 8542 Ok(()) 8543 } 8544 8545 fn validate_required_coverage_summary_with_policy( 8546 workspace_root: &Path, 8547 required_crates: &BTreeSet<String>, 8548 policy: &CoveragePolicyFile, 8549 ) -> Result<(), String> { 8550 let rows = load_coverage_refresh_rows(workspace_root)?; 8551 for crate_name in required_crates { 8552 let row = rows.get(crate_name).ok_or_else(|| { 8553 format!( 8554 "required coverage crate {} missing from coverage-refresh.tsv", 8555 crate_name 8556 ) 8557 })?; 8558 if row.status != "pass" { 8559 return Err(format!( 8560 "required coverage crate {} has non-pass status {}", 8561 crate_name, row.status 8562 )); 8563 } 8564 let thresholds = policy.thresholds_for_scope(crate_name); 8565 validate_coverage_gate_report_for_row(crate_name, row, thresholds)?; 8566 if row.exec < thresholds.fail_under_exec_lines 8567 || row.func < thresholds.fail_under_functions 8568 || branch_coverage_fails(row.branch, thresholds) 8569 || row.region < thresholds.fail_under_regions 8570 { 8571 return Err(format!( 8572 "required coverage crate {} must satisfy coverage policy {},{},{},{}, found {}/{}/{}/{}", 8573 crate_name, 8574 thresholds.fail_under_exec_lines, 8575 thresholds.fail_under_functions, 8576 thresholds.fail_under_branches, 8577 thresholds.fail_under_regions, 8578 row.exec, 8579 row.func, 8580 branch_coverage_display(row.branch), 8581 row.region 8582 )); 8583 } 8584 } 8585 Ok(()) 8586 } 8587 8588 const CORE_UNIT_DIMENSION_ENUM: &str = "UnitDimension"; 8589 const CORE_UNIT_DIMENSION_ORDER: [&str; 3] = ["Count", "Mass", "Volume"]; 8590 8591 fn extract_enum_body<'a>(source: &'a str, enum_name: &str) -> Result<&'a str, String> { 8592 let marker = format!("pub enum {enum_name}"); 8593 let enum_start = match source.find(&marker) { 8594 Some(index) => index, 8595 None => return Err(format!("missing enum {enum_name}")), 8596 }; 8597 let after_start = &source[enum_start..]; 8598 let open_rel = match after_start.find('{') { 8599 Some(index) => index, 8600 None => return Err(format!("missing opening brace for enum {enum_name}")), 8601 }; 8602 let open_idx = enum_start + open_rel; 8603 let mut depth = 0usize; 8604 for (offset, ch) in source[open_idx..].char_indices() { 8605 if ch == '{' { 8606 depth += 1; 8607 continue; 8608 } 8609 if ch != '}' { 8610 continue; 8611 } 8612 depth = depth.saturating_sub(1); 8613 if depth == 0 { 8614 let close_idx = open_idx + offset; 8615 return Ok(&source[(open_idx + 1)..close_idx]); 8616 } 8617 } 8618 Err(format!("missing closing brace for enum {enum_name}")) 8619 } 8620 8621 fn parse_enum_variants(enum_body: &str) -> Vec<String> { 8622 enum_body 8623 .lines() 8624 .filter_map(|line| { 8625 let trimmed = line.trim(); 8626 if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { 8627 return None; 8628 } 8629 let before_comma = trimmed 8630 .split_once(',') 8631 .map_or(trimmed, |(head, _)| head) 8632 .trim(); 8633 if before_comma.is_empty() { 8634 return None; 8635 } 8636 let before_discriminant = before_comma 8637 .split_once('=') 8638 .map_or(before_comma, |(head, _)| head) 8639 .trim(); 8640 if before_discriminant.is_empty() { 8641 return None; 8642 } 8643 let ident = before_discriminant 8644 .split_whitespace() 8645 .next() 8646 .unwrap_or_default(); 8647 Some(ident.to_string()) 8648 }) 8649 .collect() 8650 } 8651 8652 fn validate_core_unit_dimension_variant_order(workspace_root: &Path) -> Result<(), String> { 8653 let source_path = workspace_root 8654 .join("crates") 8655 .join("core") 8656 .join("src") 8657 .join("unit.rs"); 8658 let source = match fs::read_to_string(&source_path) { 8659 Ok(source) => source, 8660 Err(e) => return Err(format!("read {}: {e}", source_path.display())), 8661 }; 8662 let enum_body = extract_enum_body(&source, CORE_UNIT_DIMENSION_ENUM)?; 8663 let variants = parse_enum_variants(enum_body); 8664 let expected = CORE_UNIT_DIMENSION_ORDER 8665 .iter() 8666 .map(|item| (*item).to_string()) 8667 .collect::<Vec<_>>(); 8668 if variants != expected { 8669 return Err(format!( 8670 "core unit dimension variant order must be {} but was {}", 8671 CORE_UNIT_DIMENSION_ORDER.join(", "), 8672 variants.join(", ") 8673 )); 8674 } 8675 Ok(()) 8676 } 8677 8678 fn validate_coverage_policy_parity( 8679 workspace_root: &Path, 8680 contract_root: &Path, 8681 ) -> Result<(), String> { 8682 let policy = load_coverage_policy(contract_root)?; 8683 let thresholds = policy.thresholds(); 8684 if thresholds.fail_under_exec_lines != COVERAGE_REQUIRED_THRESHOLD 8685 || thresholds.fail_under_functions != COVERAGE_REQUIRED_THRESHOLD 8686 || thresholds.fail_under_regions != COVERAGE_REQUIRED_THRESHOLD 8687 || thresholds.fail_under_branches != COVERAGE_REQUIRED_THRESHOLD 8688 || !thresholds.require_branches 8689 { 8690 return Err(format!( 8691 "coverage policy must enforce {COVERAGE_REQUIRED_THRESHOLD_LABEL} with required branches" 8692 )); 8693 } 8694 8695 let required_packages = policy 8696 .required_crate_entries() 8697 .iter() 8698 .cloned() 8699 .collect::<BTreeSet<_>>(); 8700 for package in &required_packages { 8701 let scoped = policy.thresholds_for_scope(package); 8702 if scoped.fail_under_exec_lines < COVERAGE_REQUIRED_THRESHOLD 8703 || scoped.fail_under_functions < COVERAGE_REQUIRED_THRESHOLD 8704 || scoped.fail_under_regions < COVERAGE_REQUIRED_THRESHOLD 8705 || scoped.fail_under_branches < COVERAGE_REQUIRED_THRESHOLD 8706 { 8707 return Err(format!( 8708 "coverage policy scope {package} must enforce at least {COVERAGE_REQUIRED_THRESHOLD_LABEL}" 8709 )); 8710 } 8711 } 8712 let expected_packages = coverage_required_workspace_crates(workspace_root)?; 8713 if expected_packages != required_packages { 8714 let missing = expected_packages 8715 .difference(&required_packages) 8716 .cloned() 8717 .collect::<BTreeSet<_>>(); 8718 let extra = required_packages 8719 .difference(&expected_packages) 8720 .cloned() 8721 .collect::<BTreeSet<_>>(); 8722 return Err(format!( 8723 "coverage policy missing workspace crates: {}; coverage policy includes excluded or unknown crates: {}", 8724 join_set(&missing), 8725 join_set(&extra) 8726 )); 8727 } 8728 8729 Ok(()) 8730 } 8731 8732 fn publish_config_is_public(publish: Option<&PackagePublish>) -> bool { 8733 matches!( 8734 publish, 8735 Some(PackagePublish::Registries(registries)) 8736 if registries.len() == 1 && registries[0] == "crates-io" 8737 ) 8738 } 8739 8740 fn publish_config_is_non_public(publish: Option<&PackagePublish>) -> bool { 8741 matches!(publish, Some(PackagePublish::Bool(false))) 8742 } 8743 8744 fn validate_publication_control( 8745 release: &ReleaseContractFile, 8746 publish_configs: &BTreeMap<String, Option<PackagePublish>>, 8747 require_control: bool, 8748 ) -> Result<bool, String> { 8749 let Some(control) = release.publication.as_ref() else { 8750 if require_control { 8751 return Err("publication control is required".to_string()); 8752 } 8753 return Ok(false); 8754 }; 8755 if control.registry != "crates-io" { 8756 return Err("publication.registry must be crates-io".to_string()); 8757 } 8758 if control.final_enablement_step != 305 { 8759 return Err("publication.final_enablement_step must be 305".to_string()); 8760 } 8761 if !control.frozen { 8762 return Ok(false); 8763 } 8764 for (crate_name, publish) in publish_configs { 8765 if !publish_config_is_non_public(publish.as_ref()) { 8766 return Err(format!( 8767 "publication freeze requires workspace crate {} to set publish = false", 8768 crate_name 8769 )); 8770 } 8771 } 8772 Ok(true) 8773 } 8774 8775 fn validate_v1_release_policy( 8776 workspace_root: &Path, 8777 release: &ReleaseContractFile, 8778 workspace_packages: &BTreeSet<String>, 8779 publish_configs: &BTreeMap<String, Option<PackagePublish>>, 8780 require_v1: bool, 8781 ) -> Result<Option<BTreeSet<String>>, String> { 8782 let Some(control) = release.publication.as_ref() else { 8783 if require_v1 { 8784 return Err("publication control is required".to_string()); 8785 } 8786 return Ok(None); 8787 }; 8788 let declares_v1 = !control.spec_id.is_empty() 8789 || !control.approved_packages.is_empty() 8790 || !control.local_packages.is_empty() 8791 || !control.external_packages.is_empty() 8792 || release.workspace_classification.is_some(); 8793 if !declares_v1 { 8794 if require_v1 { 8795 return Err("publication must define the v1 approved package authority".to_string()); 8796 } 8797 return Ok(None); 8798 } 8799 8800 let architecture_path = 8801 workspace_root.join("contracts/crates/release_v1/radroots_crates_release_v1.toml"); 8802 let architecture = parse_toml::<CratesReleaseArchitecture>(&architecture_path)?; 8803 let expected_approved = collect_unique_set( 8804 &architecture 8805 .package 8806 .iter() 8807 .map(|package| package.name.clone()) 8808 .collect::<Vec<_>>(), 8809 "architecture.package.name", 8810 )?; 8811 if architecture.package_count != expected_approved.len() || architecture.package_count != 19 { 8812 return Err(format!( 8813 "release architecture must define exactly 19 unique packages, found package_count {} and {} unique package records", 8814 architecture.package_count, 8815 expected_approved.len() 8816 )); 8817 } 8818 if architecture.spec_id != "radroots.crates.release.v1" { 8819 return Err("frozen release architecture must retain its V1 identity".to_owned()); 8820 } 8821 let approved = collect_unique_set(&control.approved_packages, "publication.approved_packages")?; 8822 let local = collect_unique_set(&control.local_packages, "publication.local_packages")?; 8823 let external = collect_unique_set(&control.external_packages, "publication.external_packages")?; 8824 let legacy_local = collect_unique_set( 8825 &architecture.repositories.lib.packages, 8826 "architecture.repositories.lib.packages", 8827 )?; 8828 let legacy_external = collect_unique_set( 8829 &architecture.repositories.sdk.packages, 8830 "architecture.repositories.sdk.packages", 8831 )?; 8832 let consolidation_path = workspace_root.join("contracts/consolidation/architecture.v1.toml"); 8833 let workspace = 8834 parse_toml::<WorkspaceVersionCargoManifest>(&workspace_root.join("Cargo.toml"))?; 8835 let consolidated_here = if consolidation_path.is_file() { 8836 let consolidation = parse_toml::<ConsolidationReleaseOwnership>(&consolidation_path)?; 8837 workspace.workspace.package.repository == consolidation.canonical_rust_repository 8838 } else { 8839 false 8840 }; 8841 let current_allocation = consolidated_here 8842 && workspace_root 8843 .join("contracts/crates/catalog.v2.toml") 8844 .is_file(); 8845 let expected_approved = if current_allocation { 8846 crate::catalog::public_packages(workspace_root)? 8847 .into_iter() 8848 .collect() 8849 } else { 8850 expected_approved 8851 }; 8852 let expected_spec = if current_allocation { 8853 "radroots.crates.release.v2" 8854 } else { 8855 architecture.spec_id.as_str() 8856 }; 8857 if control.spec_id != expected_spec { 8858 return Err(format!( 8859 "publication.spec_id {} must match architecture id {expected_spec}", 8860 control.spec_id 8861 )); 8862 } 8863 let (expected_local, expected_external) = if consolidated_here { 8864 (expected_approved.clone(), BTreeSet::new()) 8865 } else { 8866 (legacy_local, legacy_external) 8867 }; 8868 for (field, actual, expected) in [ 8869 ( 8870 "publication.approved_packages", 8871 &approved, 8872 &expected_approved, 8873 ), 8874 ("publication.local_packages", &local, &expected_local), 8875 ( 8876 "publication.external_packages", 8877 &external, 8878 &expected_external, 8879 ), 8880 ] { 8881 if actual != expected { 8882 let missing = expected 8883 .difference(actual) 8884 .cloned() 8885 .collect::<BTreeSet<_>>(); 8886 let extra = actual 8887 .difference(expected) 8888 .cloned() 8889 .collect::<BTreeSet<_>>(); 8890 return Err(format!( 8891 "{field} is missing approved packages: {}; {field} has unapproved packages: {}", 8892 join_set(&missing), 8893 join_set(&extra) 8894 )); 8895 } 8896 } 8897 let ownership_overlap = local 8898 .intersection(&external) 8899 .cloned() 8900 .collect::<BTreeSet<_>>(); 8901 if !ownership_overlap.is_empty() { 8902 return Err(format!( 8903 "local and external approved package ownership overlaps: {}", 8904 join_set(&ownership_overlap) 8905 )); 8906 } 8907 let mut owned = local.clone(); 8908 owned.extend(external.iter().cloned()); 8909 if owned != approved { 8910 return Err( 8911 "local and external package ownership must partition approved packages".to_string(), 8912 ); 8913 } 8914 let external_in_workspace = external 8915 .intersection(workspace_packages) 8916 .cloned() 8917 .collect::<BTreeSet<_>>(); 8918 if !external_in_workspace.is_empty() { 8919 return Err(format!( 8920 "externally owned approved packages must not be workspace members: {}", 8921 join_set(&external_in_workspace) 8922 )); 8923 } 8924 8925 let classification = release.workspace_classification.as_ref().ok_or_else(|| { 8926 "workspace_classification is required for the v1 release policy".to_string() 8927 })?; 8928 let private = collect_unique_set(&classification.private, "workspace_classification.private")?; 8929 let build_codegen = collect_unique_set( 8930 &classification.build_codegen, 8931 "workspace_classification.build_codegen", 8932 )?; 8933 let test_support = collect_unique_set( 8934 &classification.test_support, 8935 "workspace_classification.test_support", 8936 )?; 8937 let preview = collect_unique_set(&classification.preview, "workspace_classification.preview")?; 8938 let retired = collect_unique_set(&classification.retired, "workspace_classification.retired")?; 8939 let classes = [ 8940 ("private", &private), 8941 ("build-codegen", &build_codegen), 8942 ("test-support", &test_support), 8943 ("preview", &preview), 8944 ("retired", &retired), 8945 ]; 8946 for index in 0..classes.len() { 8947 for other_index in (index + 1)..classes.len() { 8948 let overlap = classes[index] 8949 .1 8950 .intersection(classes[other_index].1) 8951 .cloned() 8952 .collect::<BTreeSet<_>>(); 8953 if !overlap.is_empty() { 8954 return Err(format!( 8955 "workspace classification overlap is not allowed between {} and {}: {}", 8956 classes[index].0, 8957 classes[other_index].0, 8958 join_set(&overlap) 8959 )); 8960 } 8961 } 8962 } 8963 let mut classified = BTreeSet::new(); 8964 for (_, entries) in classes { 8965 classified.extend(entries.iter().cloned()); 8966 } 8967 let local_workspace_packages = local 8968 .intersection(workspace_packages) 8969 .cloned() 8970 .collect::<BTreeSet<_>>(); 8971 let public_classification_overlap = classified 8972 .intersection(&local_workspace_packages) 8973 .cloned() 8974 .collect::<BTreeSet<_>>(); 8975 if !public_classification_overlap.is_empty() { 8976 return Err(format!( 8977 "approved local packages must not be classified as private workspace packages: {}", 8978 join_set(&public_classification_overlap) 8979 )); 8980 } 8981 let mut accounted = classified.clone(); 8982 accounted.extend(local_workspace_packages.iter().cloned()); 8983 if accounted != *workspace_packages { 8984 let missing = workspace_packages 8985 .difference(&accounted) 8986 .cloned() 8987 .collect::<BTreeSet<_>>(); 8988 let extra = accounted 8989 .difference(workspace_packages) 8990 .cloned() 8991 .collect::<BTreeSet<_>>(); 8992 return Err(format!( 8993 "workspace classification is missing packages: {}; workspace classification has unknown packages: {}", 8994 join_set(&missing), 8995 join_set(&extra) 8996 )); 8997 } 8998 8999 if control.registry != "crates-io" { 9000 return Err("publication.registry must be crates-io".to_string()); 9001 } 9002 if control.final_enablement_step != 305 { 9003 return Err("publication.final_enablement_step must be 305".to_string()); 9004 } 9005 let publish_order = collect_unique_set(&release.publish_order.crates, "publish_order.crates")?; 9006 if control.frozen { 9007 if !publish_order.is_empty() { 9008 return Err( 9009 "publish_order.crates must remain empty while publication is frozen".to_string(), 9010 ); 9011 } 9012 for (crate_name, publish) in publish_configs { 9013 if !publish_config_is_non_public(publish.as_ref()) { 9014 return Err(format!( 9015 "publication freeze requires workspace crate {} to set publish = false", 9016 crate_name 9017 )); 9018 } 9019 } 9020 return Ok(Some(BTreeSet::new())); 9021 } 9022 9023 if local_workspace_packages != local { 9024 let missing = local 9025 .difference(&local_workspace_packages) 9026 .cloned() 9027 .collect::<BTreeSet<_>>(); 9028 return Err(format!( 9029 "publication enablement is missing approved local workspace packages: {}", 9030 join_set(&missing) 9031 )); 9032 } 9033 if publish_order != local { 9034 return Err("publish_order.crates must contain exactly the approved local packages when publication is enabled".to_string()); 9035 } 9036 for (crate_name, publish) in publish_configs { 9037 if local.contains(crate_name) { 9038 if !publish_config_is_public(publish.as_ref()) { 9039 return Err(format!( 9040 "approved local crate {} must set publish = [\"crates-io\"]", 9041 crate_name 9042 )); 9043 } 9044 } else if !publish_config_is_non_public(publish.as_ref()) { 9045 return Err(format!( 9046 "private workspace crate {} must set publish = false", 9047 crate_name 9048 )); 9049 } 9050 } 9051 Ok(Some(local)) 9052 } 9053 9054 #[cfg(test)] 9055 fn validate_release_publish_policy( 9056 workspace_root: &Path, 9057 _contract_root: &Path, 9058 contract_version: &str, 9059 ) -> Result<(), String> { 9060 let release = load_release_contract(workspace_root, contract_version)?; 9061 if release.release.version.trim().is_empty() { 9062 return Err("release.version must not be empty".to_string()); 9063 } 9064 if release.release.version != contract_version { 9065 return Err(format!( 9066 "release.version {} must match contract version {}", 9067 release.release.version, contract_version 9068 )); 9069 } 9070 9071 let workspace_packages = workspace_package_names(workspace_root)? 9072 .into_iter() 9073 .collect::<BTreeSet<_>>(); 9074 let publish_configs = workspace_package_publish_configs(workspace_root) 9075 .expect("workspace publish configs are stable"); 9076 if validate_v1_release_policy( 9077 workspace_root, 9078 &release, 9079 &workspace_packages, 9080 &publish_configs, 9081 false, 9082 )? 9083 .is_some() 9084 { 9085 return Ok(()); 9086 } 9087 let uses_classification = release.uses_classification(); 9088 let public_field = if uses_classification { 9089 "classification.public" 9090 } else { 9091 "publish.crates" 9092 }; 9093 let internal_field = if uses_classification { 9094 "classification.internal" 9095 } else { 9096 "internal.crates" 9097 }; 9098 9099 let public_set = collect_unique_set(&release.public_crates(), public_field)?; 9100 let internal_set = collect_unique_set(&release.internal_crates(), internal_field)?; 9101 let deferred_set = collect_unique_set(&release.deferred_crates(), "classification.deferred")?; 9102 let retired_set = collect_unique_set(&release.retired_crates(), "classification.retired")?; 9103 let yank_only_set = 9104 collect_unique_set(&release.yank_only_crates(), "classification.yank_only")?; 9105 let publish_order = &release.publish_order.crates; 9106 let publish_order_set = collect_unique_set(publish_order, "publish_order.crates")?; 9107 9108 let class_sets = [ 9109 ("public", &public_set), 9110 ("internal", &internal_set), 9111 ("deferred", &deferred_set), 9112 ("retired", &retired_set), 9113 ("yank-only", &yank_only_set), 9114 ]; 9115 for idx in 0..class_sets.len() { 9116 for other_idx in (idx + 1)..class_sets.len() { 9117 let overlap = class_sets[idx] 9118 .1 9119 .intersection(class_sets[other_idx].1) 9120 .cloned() 9121 .collect::<BTreeSet<_>>(); 9122 if !overlap.is_empty() { 9123 return Err(format!( 9124 "release classification overlap is not allowed between {} and {}: {}", 9125 class_sets[idx].0, 9126 class_sets[other_idx].0, 9127 join_set(&overlap) 9128 )); 9129 } 9130 } 9131 } 9132 9133 let mut combined = public_set.clone(); 9134 combined.extend(internal_set.iter().cloned()); 9135 combined.extend(deferred_set.iter().cloned()); 9136 combined.extend(retired_set.iter().cloned()); 9137 combined.extend(yank_only_set.iter().cloned()); 9138 if combined != workspace_packages { 9139 let missing = workspace_packages 9140 .difference(&combined) 9141 .cloned() 9142 .collect::<BTreeSet<_>>(); 9143 let extra = combined 9144 .difference(&workspace_packages) 9145 .cloned() 9146 .collect::<BTreeSet<_>>(); 9147 return Err(format!( 9148 "release classification sets are missing workspace crates: {}; release classification sets include unknown crates: {}", 9149 join_set(&missing), 9150 join_set(&extra) 9151 )); 9152 } 9153 9154 if publish_order_set != public_set { 9155 let missing = public_set 9156 .difference(&publish_order_set) 9157 .cloned() 9158 .collect::<BTreeSet<_>>(); 9159 let extra = publish_order_set 9160 .difference(&public_set) 9161 .cloned() 9162 .collect::<BTreeSet<_>>(); 9163 return Err(format!( 9164 "publish_order.crates is missing publish crates: {}; publish_order.crates has non-publish crates: {}", 9165 join_set(&missing), 9166 join_set(&extra) 9167 )); 9168 } 9169 9170 let order_index = publish_order 9171 .iter() 9172 .enumerate() 9173 .map(|(idx, name)| (name.clone(), idx)) 9174 .collect::<BTreeMap<_, _>>(); 9175 let dependencies = read_workspace_package_dependencies(workspace_root) 9176 .expect("workspace package manifests were already parsed"); 9177 for crate_name in &public_set { 9178 let crate_deps = &dependencies[crate_name]; 9179 let crate_order = order_index[crate_name]; 9180 for dep in crate_deps { 9181 if !public_set.contains(dep) { 9182 continue; 9183 } 9184 let dep_order = order_index[dep]; 9185 if dep_order >= crate_order { 9186 return Err(format!( 9187 "publish order must place dependency {} before {}", 9188 dep, crate_name 9189 )); 9190 } 9191 } 9192 } 9193 9194 if validate_publication_control(&release, &publish_configs, false)? { 9195 return Ok(()); 9196 } 9197 for crate_name in &public_set { 9198 let publish = publish_configs[crate_name].as_ref(); 9199 if !publish_config_is_public(publish) { 9200 return Err(format!( 9201 "public crate {} must set publish = [\"crates-io\"]", 9202 crate_name 9203 )); 9204 } 9205 } 9206 for crate_name in internal_set 9207 .iter() 9208 .chain(deferred_set.iter()) 9209 .chain(retired_set.iter()) 9210 .chain(yank_only_set.iter()) 9211 { 9212 let publish = publish_configs[crate_name].as_ref(); 9213 if !publish_config_is_non_public(publish) { 9214 return Err(format!( 9215 "non-public crate {} must set publish = false", 9216 crate_name 9217 )); 9218 } 9219 } 9220 Ok(()) 9221 } 9222 9223 #[derive(Clone, Copy)] 9224 enum OperationAuthorityProfile { 9225 CapsuleCanonical, 9226 #[cfg(test)] 9227 Generic, 9228 } 9229 9230 pub fn validate_release_preflight(workspace_root: &Path) -> Result<(), String> { 9231 validate_release_preflight_with_override(workspace_root, None) 9232 } 9233 9234 pub fn validate_release_preflight_with_override( 9235 workspace_root: &Path, 9236 release_policy_override: Option<PathBuf>, 9237 ) -> Result<(), String> { 9238 validate_release_preflight_with_override_and_profile( 9239 workspace_root, 9240 release_policy_override, 9241 OperationAuthorityProfile::CapsuleCanonical, 9242 ) 9243 } 9244 9245 fn validate_release_preflight_with_override_and_profile( 9246 workspace_root: &Path, 9247 release_policy_override: Option<PathBuf>, 9248 authority_profile: OperationAuthorityProfile, 9249 ) -> Result<(), String> { 9250 let bundle = load_contract_bundle(workspace_root)?; 9251 validate_contract_bundle_with_release_policy_override_and_profile( 9252 &bundle, 9253 release_policy_override.clone(), 9254 authority_profile, 9255 )?; 9256 let release = load_release_contract_with_override( 9257 workspace_root, 9258 bundle.version.contract.version.as_str(), 9259 release_policy_override, 9260 )?; 9261 let policy = 9262 load_coverage_policy(&bundle.root).expect("validated contract includes coverage policy"); 9263 let publish_crates = collect_unique_set( 9264 &release.public_crates(), 9265 if release.uses_classification() { 9266 "classification.public" 9267 } else { 9268 "publish.crates" 9269 }, 9270 ) 9271 .expect("validated contract enforces unique public crates"); 9272 let required_crate_list = policy 9273 .required_crates() 9274 .expect("validated contract includes required crates"); 9275 let required_crates = collect_unique_set(&required_crate_list, "required.crates") 9276 .expect("validated contract enforces unique required.crates"); 9277 validate_publishable_dto_tooling_sources(workspace_root, &publish_crates)?; 9278 validate_publish_package_metadata(workspace_root, &publish_crates)?; 9279 validate_required_coverage_summary_with_policy(workspace_root, &required_crates, &policy)?; 9280 Ok(()) 9281 } 9282 9283 fn validate_contract_bundle_with_release_policy_override( 9284 bundle: &ContractBundle, 9285 release_policy_override: Option<PathBuf>, 9286 ) -> Result<(), String> { 9287 validate_contract_bundle_with_release_policy_override_and_profile( 9288 bundle, 9289 release_policy_override, 9290 OperationAuthorityProfile::CapsuleCanonical, 9291 ) 9292 } 9293 9294 fn validate_contract_bundle_with_release_policy_override_and_profile( 9295 bundle: &ContractBundle, 9296 release_policy_override: Option<PathBuf>, 9297 authority_profile: OperationAuthorityProfile, 9298 ) -> Result<(), String> { 9299 if bundle.manifest.contract.name.trim().is_empty() { 9300 return Err("contract name is required".to_string()); 9301 } 9302 if bundle.manifest.contract.version.trim().is_empty() { 9303 return Err("contract version is required".to_string()); 9304 } 9305 if bundle.manifest.contract.source.trim().is_empty() { 9306 return Err("contract source is required".to_string()); 9307 } 9308 if bundle.manifest.surface.model_crates.is_empty() { 9309 return Err("contract surface.model_crates must not be empty".to_string()); 9310 } 9311 if bundle.manifest.surface.algorithm_crates.is_empty() { 9312 return Err("contract surface.algorithm_crates must not be empty".to_string()); 9313 } 9314 validate_surface_metadata(&bundle.manifest.surface)?; 9315 if bundle.version.contract.version.trim().is_empty() { 9316 return Err("version.contract.version is required".to_string()); 9317 } 9318 if bundle.version.contract.stability.trim().is_empty() { 9319 return Err("version.contract.stability is required".to_string()); 9320 } 9321 if bundle.version.semver.major_on.is_empty() 9322 || bundle.version.semver.minor_on.is_empty() 9323 || bundle.version.semver.patch_on.is_empty() 9324 { 9325 return Err("version.semver rules must all be non-empty".to_string()); 9326 } 9327 if !bundle.version.release_integrity.requires_conformance_pass { 9328 return Err("release_integrity.requires_conformance_pass must be true".to_string()); 9329 } 9330 if !bundle 9331 .version 9332 .release_integrity 9333 .requires_contract_manifest_diff 9334 { 9335 return Err("release_integrity.requires_contract_manifest_diff must be true".to_string()); 9336 } 9337 if !bundle.version.release_integrity.requires_release_notes { 9338 return Err("release_integrity.requires_release_notes must be true".to_string()); 9339 } 9340 validate_policy_metadata(&bundle.manifest.policy)?; 9341 let workspace_root = bundle 9342 .root 9343 .parent() 9344 .expect("contract root must have a workspace parent"); 9345 validate_replica_contract(bundle, workspace_root)?; 9346 validate_operations_contract(bundle, &bundle.operations_manifest, workspace_root)?; 9347 if matches!( 9348 authority_profile, 9349 OperationAuthorityProfile::CapsuleCanonical 9350 ) { 9351 validate_capsule_operation_authority(&bundle.operations_manifest, workspace_root)?; 9352 } 9353 validate_all_conformance_vectors(workspace_root, &bundle.manifest.contract.version)?; 9354 validate_core_unit_dimension_variant_order(workspace_root)?; 9355 validate_coverage_policy_parity(workspace_root, &bundle.root)?; 9356 validate_version_governance(bundle, workspace_root)?; 9357 if matches!( 9358 authority_profile, 9359 OperationAuthorityProfile::CapsuleCanonical 9360 ) { 9361 crate::architecture::validate(workspace_root)?; 9362 } 9363 validate_release_publish_policy_with_override_and_control( 9364 workspace_root, 9365 &bundle.root, 9366 bundle.version.contract.version.as_str(), 9367 release_policy_override, 9368 matches!( 9369 authority_profile, 9370 OperationAuthorityProfile::CapsuleCanonical 9371 ), 9372 matches!( 9373 authority_profile, 9374 OperationAuthorityProfile::CapsuleCanonical 9375 ), 9376 )?; 9377 Ok(()) 9378 } 9379 9380 #[cfg(test)] 9381 fn validate_release_publish_policy_with_override( 9382 workspace_root: &Path, 9383 contract_root: &Path, 9384 contract_version: &str, 9385 release_policy_override: Option<PathBuf>, 9386 ) -> Result<(), String> { 9387 validate_release_publish_policy_with_override_and_control( 9388 workspace_root, 9389 contract_root, 9390 contract_version, 9391 release_policy_override, 9392 true, 9393 false, 9394 ) 9395 } 9396 9397 fn validate_release_publish_policy_with_override_and_control( 9398 workspace_root: &Path, 9399 _contract_root: &Path, 9400 contract_version: &str, 9401 release_policy_override: Option<PathBuf>, 9402 require_publication_control: bool, 9403 require_v1_policy: bool, 9404 ) -> Result<(), String> { 9405 let release = load_release_contract_with_override( 9406 workspace_root, 9407 contract_version, 9408 release_policy_override, 9409 )?; 9410 if release.release.version.trim().is_empty() { 9411 return Err("release.version must not be empty".to_string()); 9412 } 9413 if release.release.version != contract_version { 9414 return Err(format!( 9415 "release.version {} must match contract version {}", 9416 release.release.version, contract_version 9417 )); 9418 } 9419 9420 let workspace_packages = workspace_package_names(workspace_root)? 9421 .into_iter() 9422 .collect::<BTreeSet<_>>(); 9423 let publish_configs = workspace_package_publish_configs(workspace_root) 9424 .expect("workspace publish configs are stable"); 9425 if validate_v1_release_policy( 9426 workspace_root, 9427 &release, 9428 &workspace_packages, 9429 &publish_configs, 9430 require_v1_policy, 9431 )? 9432 .is_some() 9433 { 9434 return Ok(()); 9435 } 9436 let uses_classification = release.uses_classification(); 9437 let public_field = if uses_classification { 9438 "classification.public" 9439 } else { 9440 "publish.crates" 9441 }; 9442 let internal_field = if uses_classification { 9443 "classification.internal" 9444 } else { 9445 "internal.crates" 9446 }; 9447 9448 let public_set = collect_unique_set(&release.public_crates(), public_field)?; 9449 let internal_set = collect_unique_set(&release.internal_crates(), internal_field)?; 9450 let deferred_set = collect_unique_set(&release.deferred_crates(), "classification.deferred")?; 9451 let retired_set = collect_unique_set(&release.retired_crates(), "classification.retired")?; 9452 let yank_only_set = 9453 collect_unique_set(&release.yank_only_crates(), "classification.yank_only")?; 9454 let publish_order = &release.publish_order.crates; 9455 let publish_order_set = collect_unique_set(publish_order, "publish_order.crates")?; 9456 9457 let class_sets = [ 9458 ("public", &public_set), 9459 ("internal", &internal_set), 9460 ("deferred", &deferred_set), 9461 ("retired", &retired_set), 9462 ("yank-only", &yank_only_set), 9463 ]; 9464 for idx in 0..class_sets.len() { 9465 for other_idx in (idx + 1)..class_sets.len() { 9466 let overlap = class_sets[idx] 9467 .1 9468 .intersection(class_sets[other_idx].1) 9469 .cloned() 9470 .collect::<BTreeSet<_>>(); 9471 if !overlap.is_empty() { 9472 return Err(format!( 9473 "release classification overlap is not allowed between {} and {}: {}", 9474 class_sets[idx].0, 9475 class_sets[other_idx].0, 9476 join_set(&overlap) 9477 )); 9478 } 9479 } 9480 } 9481 9482 let mut combined = public_set.clone(); 9483 combined.extend(internal_set.iter().cloned()); 9484 combined.extend(deferred_set.iter().cloned()); 9485 combined.extend(retired_set.iter().cloned()); 9486 combined.extend(yank_only_set.iter().cloned()); 9487 if combined != workspace_packages { 9488 let missing = workspace_packages 9489 .difference(&combined) 9490 .cloned() 9491 .collect::<BTreeSet<_>>(); 9492 let extra = combined 9493 .difference(&workspace_packages) 9494 .cloned() 9495 .collect::<BTreeSet<_>>(); 9496 return Err(format!( 9497 "release classification sets are missing workspace crates: {}; release classification sets include unknown crates: {}", 9498 join_set(&missing), 9499 join_set(&extra) 9500 )); 9501 } 9502 9503 if publish_order_set != public_set { 9504 let missing = public_set 9505 .difference(&publish_order_set) 9506 .cloned() 9507 .collect::<BTreeSet<_>>(); 9508 let extra = publish_order_set 9509 .difference(&public_set) 9510 .cloned() 9511 .collect::<BTreeSet<_>>(); 9512 return Err(format!( 9513 "publish_order.crates is missing publish crates: {}; publish_order.crates has non-publish crates: {}", 9514 join_set(&missing), 9515 join_set(&extra) 9516 )); 9517 } 9518 9519 let order_index = publish_order 9520 .iter() 9521 .enumerate() 9522 .map(|(idx, name)| (name.clone(), idx)) 9523 .collect::<BTreeMap<_, _>>(); 9524 let dependencies = read_workspace_package_dependencies(workspace_root) 9525 .expect("workspace package manifests were already parsed"); 9526 for crate_name in &public_set { 9527 let crate_deps = &dependencies[crate_name]; 9528 let crate_order = order_index[crate_name]; 9529 for dep in crate_deps { 9530 if !public_set.contains(dep) { 9531 continue; 9532 } 9533 let dep_order = order_index[dep]; 9534 if dep_order >= crate_order { 9535 return Err(format!( 9536 "publish order must place dependency {} before {}", 9537 dep, crate_name 9538 )); 9539 } 9540 } 9541 } 9542 9543 if validate_publication_control(&release, &publish_configs, require_publication_control)? { 9544 return Ok(()); 9545 } 9546 for crate_name in &public_set { 9547 let publish = publish_configs[crate_name].as_ref(); 9548 if !publish_config_is_public(publish) { 9549 return Err(format!( 9550 "public crate {} must set publish = [\"crates-io\"]", 9551 crate_name 9552 )); 9553 } 9554 } 9555 for crate_name in internal_set 9556 .iter() 9557 .chain(deferred_set.iter()) 9558 .chain(retired_set.iter()) 9559 .chain(yank_only_set.iter()) 9560 { 9561 let publish = publish_configs[crate_name].as_ref(); 9562 if !publish_config_is_non_public(publish) { 9563 return Err(format!( 9564 "non-public crate {} must set publish = false", 9565 crate_name 9566 )); 9567 } 9568 } 9569 9570 Ok(()) 9571 } 9572 9573 pub fn load_contract_bundle(workspace_root: &Path) -> Result<ContractBundle, String> { 9574 reject_legacy_contract_roots(workspace_root)?; 9575 let root = contract_root(workspace_root); 9576 let manifest = parse_toml::<ContractManifest>(&root.join("manifest.toml"))?; 9577 let version = parse_toml::<VersionPolicy>(&root.join("version.toml"))?; 9578 let replica = 9579 parse_toml::<ReplicaContractManifest>(&workspace_root.join(REPLICA_CONTRACT_RELATIVE))?; 9580 let operations_manifest = 9581 parse_toml::<OperationsContractManifest>(&root.join("operations.toml"))?; 9582 Ok(ContractBundle { 9583 root, 9584 manifest, 9585 version, 9586 replica, 9587 operations_manifest, 9588 }) 9589 } 9590 9591 fn reject_legacy_contract_roots(workspace_root: &Path) -> Result<(), String> { 9592 for relative in ["spec", "policy"] { 9593 let legacy_root = workspace_root.join(relative); 9594 if legacy_root.exists() { 9595 return Err(format!( 9596 "legacy contract root {} is forbidden; use contracts/", 9597 legacy_root.display() 9598 )); 9599 } 9600 } 9601 Ok(()) 9602 } 9603 9604 pub fn validate_contract_bundle(bundle: &ContractBundle) -> Result<(), String> { 9605 validate_contract_bundle_with_release_policy_override(bundle, None) 9606 } 9607 9608 #[cfg(test)] 9609 mod tests { 9610 use super::*; 9611 use std::collections::BTreeSet; 9612 use std::fs; 9613 use std::path::{Path, PathBuf}; 9614 use std::time::{SystemTime, UNIX_EPOCH}; 9615 9616 const SYNTHETIC_CONFORMANCE_VECTOR: &str = r#"{ 9617 "suite": "synthetic", 9618 "contract_version": "1.0.0", 9619 "vectors": [ 9620 { 9621 "id": "synthetic_vector_001", 9622 "kind": "synthetic.operation", 9623 "input": {}, 9624 "expected": {} 9625 } 9626 ] 9627 } 9628 "#; 9629 9630 fn workspace_root() -> PathBuf { 9631 let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); 9632 manifest_dir 9633 .join("../..") 9634 .canonicalize() 9635 .expect("canonical workspace root") 9636 } 9637 9638 #[test] 9639 fn sqlite_runtime_policy_matches_the_exact_migration_inventory() { 9640 validate_sqlite_runtime_contract(&workspace_root()) 9641 .expect("current SQLx and SQLite migration policy must validate"); 9642 } 9643 9644 #[test] 9645 fn sqlite_dependency_inventory_uses_the_selected_package_not_its_alias() { 9646 let manifest = toml::from_str::<toml::Value>( 9647 r#"[dependencies] 9648 database = { package = "rusqlite", version = "1" } 9649 sqlx = { version = "1" } 9650 "#, 9651 ) 9652 .expect("dependency fixture"); 9653 let dependencies = manifest 9654 .get("dependencies") 9655 .and_then(toml::Value::as_table) 9656 .expect("dependency table"); 9657 let mut found = BTreeSet::new(); 9658 collect_matching_dependencies( 9659 "fixture", 9660 dependencies, 9661 &|dependency| dependency == "rusqlite", 9662 &mut found, 9663 ); 9664 assert_eq!(found, BTreeSet::from(["fixture:rusqlite".to_string()])); 9665 } 9666 9667 fn validate_generic_contract_bundle(bundle: &ContractBundle) -> Result<(), String> { 9668 validate_contract_bundle_with_release_policy_override_and_profile( 9669 bundle, 9670 None, 9671 OperationAuthorityProfile::Generic, 9672 ) 9673 } 9674 9675 fn validate_generic_release_preflight(workspace_root: &Path) -> Result<(), String> { 9676 validate_release_preflight_with_override_and_profile( 9677 workspace_root, 9678 None, 9679 OperationAuthorityProfile::Generic, 9680 ) 9681 } 9682 9683 fn current_post_authority() -> (OperationsContractManifest, ConformanceVectorFile) { 9684 let root = workspace_root(); 9685 let manifest = 9686 parse_toml::<OperationsContractManifest>(&root.join("contracts/operations.toml")) 9687 .expect("current operations manifest"); 9688 let vector = 9689 parse_json::<ConformanceVectorFile>(&root.join(POST_CONFORMANCE_VECTOR_RELATIVE)) 9690 .expect("current post conformance vector"); 9691 (manifest, vector) 9692 } 9693 9694 fn current_admission_authority() -> (OperationsContractManifest, ConformanceVectorFile) { 9695 let root = workspace_root(); 9696 let manifest = 9697 parse_toml::<OperationsContractManifest>(&root.join("contracts/operations.toml")) 9698 .expect("current operations manifest"); 9699 let vector = parse_json::<ConformanceVectorFile>( 9700 &root.join(admission_authority::ADMISSION_CONFORMANCE_VECTOR_RELATIVE), 9701 ) 9702 .expect("current verified admission conformance vector"); 9703 (manifest, vector) 9704 } 9705 9706 fn current_comment_authority() -> (OperationsContractManifest, ConformanceVectorFile) { 9707 let root = workspace_root(); 9708 let manifest = 9709 parse_toml::<OperationsContractManifest>(&root.join("contracts/operations.toml")) 9710 .expect("current operations manifest"); 9711 let vector = 9712 parse_json::<ConformanceVectorFile>(&root.join(COMMENT_CONFORMANCE_VECTOR_RELATIVE)) 9713 .expect("current Comment conformance vector"); 9714 (manifest, vector) 9715 } 9716 9717 fn current_deletion_authority() -> ( 9718 OperationsContractManifest, 9719 ConformanceVectorFile, 9720 ConformanceVectorFile, 9721 ) { 9722 let root = workspace_root(); 9723 let manifest = 9724 parse_toml::<OperationsContractManifest>(&root.join("contracts/operations.toml")) 9725 .expect("current operations manifest"); 9726 let request_vector = 9727 parse_json::<ConformanceVectorFile>(&root.join(DELETION_CONFORMANCE_VECTOR_RELATIVE)) 9728 .expect("current deletion conformance vector"); 9729 let suppression_vector = parse_json::<ConformanceVectorFile>( 9730 &root.join(DELETION_SUPPRESSION_CONFORMANCE_VECTOR_RELATIVE), 9731 ) 9732 .expect("current deletion suppression conformance vector"); 9733 (manifest, request_vector, suppression_vector) 9734 } 9735 9736 fn current_food_availability_authority() -> (OperationsContractManifest, ConformanceVectorFile) 9737 { 9738 let root = workspace_root(); 9739 let manifest = 9740 parse_toml::<OperationsContractManifest>(&root.join("contracts/operations.toml")) 9741 .expect("current operations manifest"); 9742 let vector = parse_json::<ConformanceVectorFile>( 9743 &root.join(FOOD_AVAILABILITY_CONFORMANCE_VECTOR_RELATIVE), 9744 ) 9745 .expect("current FoodAvailability conformance vector"); 9746 (manifest, vector) 9747 } 9748 9749 fn current_knowledge_manifest_authority() -> (String, ConformanceVectorFile) { 9750 let root = workspace_root(); 9751 let manifest = fs::read_to_string(root.join(KNOWLEDGE_MANIFEST_RELATIVE)) 9752 .expect("current knowledge manifest"); 9753 let vector = 9754 parse_json::<ConformanceVectorFile>(&root.join(KNOWLEDGE_MANIFEST_AND_DECODE_RELATIVE)) 9755 .expect("current knowledge manifest conformance vector"); 9756 (manifest, vector) 9757 } 9758 9759 fn temp_root(prefix: &str) -> PathBuf { 9760 let nanos = SystemTime::now() 9761 .duration_since(UNIX_EPOCH) 9762 .expect("clock") 9763 .as_nanos(); 9764 let root = std::env::temp_dir().join(format!("radroots_xtask_{prefix}_{nanos}")); 9765 fs::create_dir_all(&root).expect("create temp root"); 9766 root 9767 } 9768 9769 fn write_file(path: &Path, content: &str) { 9770 let _ = fs::create_dir_all(path.parent().unwrap_or(Path::new(""))); 9771 fs::write(path, content).expect("write file"); 9772 } 9773 9774 fn required_thresholds() -> CoverageThresholds { 9775 CoverageThresholds { 9776 fail_under_exec_lines: COVERAGE_REQUIRED_THRESHOLD, 9777 fail_under_functions: COVERAGE_REQUIRED_THRESHOLD, 9778 fail_under_regions: COVERAGE_REQUIRED_THRESHOLD, 9779 fail_under_branches: COVERAGE_REQUIRED_THRESHOLD, 9780 require_branches: true, 9781 } 9782 } 9783 9784 fn coverage_thresholds(value: f64, require_branches: bool) -> CoverageThresholds { 9785 CoverageThresholds { 9786 fail_under_exec_lines: value, 9787 fail_under_functions: value, 9788 fail_under_regions: value, 9789 fail_under_branches: value, 9790 require_branches, 9791 } 9792 } 9793 9794 struct TestCoverageRefreshRow<'a> { 9795 crate_name: &'a str, 9796 status: &'a str, 9797 thresholds: CoverageThresholds, 9798 exec: f64, 9799 func: f64, 9800 branch: Option<f64>, 9801 region: f64, 9802 report_pass: bool, 9803 } 9804 9805 fn passing_coverage_row(crate_name: &str) -> TestCoverageRefreshRow<'_> { 9806 TestCoverageRefreshRow { 9807 crate_name, 9808 status: "pass", 9809 thresholds: coverage_thresholds(COVERAGE_REQUIRED_THRESHOLD, true), 9810 exec: 100.0, 9811 func: 100.0, 9812 branch: Some(100.0), 9813 region: 100.0, 9814 report_pass: true, 9815 } 9816 } 9817 9818 fn coverage_refresh_branch_value(branch: Option<f64>) -> String { 9819 branch 9820 .map(|value| value.to_string()) 9821 .unwrap_or_else(|| "unavailable".to_string()) 9822 } 9823 9824 fn write_test_coverage_gate_report(root: &Path, row: &TestCoverageRefreshRow<'_>) -> String { 9825 let report_relative = format!("target/coverage/{}/gate-report.json", row.crate_name); 9826 let report_path = root.join(&report_relative); 9827 let fail_reasons = if row.report_pass { 9828 Vec::<&str>::new() 9829 } else { 9830 vec!["policy gate failed"] 9831 }; 9832 let report = serde_json::json!({ 9833 "scope": row.crate_name, 9834 "thresholds": { 9835 "executable_lines": row.thresholds.fail_under_exec_lines, 9836 "functions": row.thresholds.fail_under_functions, 9837 "regions": row.thresholds.fail_under_regions, 9838 "branches": row.thresholds.fail_under_branches, 9839 "branches_required": row.thresholds.require_branches 9840 }, 9841 "measured": { 9842 "executable_lines_percent": row.exec, 9843 "executable_lines_source": "da", 9844 "functions_percent": row.func, 9845 "branches_percent": row.branch, 9846 "branches_available": row.branch.is_some(), 9847 "summary_lines_percent": row.exec, 9848 "summary_regions_percent": row.region 9849 }, 9850 "counts": { 9851 "executable_lines": { 9852 "covered": 1, 9853 "total": 1 9854 }, 9855 "branches": { 9856 "covered": if row.branch.is_some() { 1 } else { 0 }, 9857 "total": if row.branch.is_some() { 1 } else { 0 } 9858 } 9859 }, 9860 "result": { 9861 "pass": row.report_pass, 9862 "fail_reasons": fail_reasons 9863 } 9864 }); 9865 let json = 9866 serde_json::to_string_pretty(&report).expect("serialize test coverage gate report"); 9867 write_file(&report_path, &format!("{json}\n")); 9868 report_relative 9869 } 9870 9871 fn write_test_coverage_refresh(root: &Path, rows: &[TestCoverageRefreshRow<'_>]) { 9872 let mut refresh_rows = String::from("crate\tstatus\texec\tfunc\tbranch\tregion\treport\n"); 9873 for row in rows { 9874 let report_relative = write_test_coverage_gate_report(root, row); 9875 refresh_rows.push_str(&format!( 9876 "{}\t{}\t{}\t{}\t{}\t{}\t{}\n", 9877 row.crate_name, 9878 row.status, 9879 row.exec, 9880 row.func, 9881 coverage_refresh_branch_value(row.branch), 9882 row.region, 9883 report_relative 9884 )); 9885 } 9886 write_file( 9887 &root 9888 .join("target") 9889 .join("coverage") 9890 .join("coverage-refresh.tsv"), 9891 &refresh_rows, 9892 ); 9893 } 9894 9895 fn create_synthetic_workspace(prefix: &str) -> PathBuf { 9896 let root = temp_root(prefix); 9897 write_file( 9898 &root.join("contracts/crates/release_v1/radroots_crates_release_v1.toml"), 9899 r#"spec_id = "radroots.crates.release.v1" 9900 package_count = 2 9901 9902 [repositories.lib] 9903 version = "1.0.0" 9904 packages = ["radroots_a", "radroots_b"] 9905 9906 [repositories.sdk] 9907 version = "0.1.0" 9908 packages = [] 9909 9910 [[package]] 9911 name = "radroots_a" 9912 9913 [[package]] 9914 name = "radroots_b" 9915 "#, 9916 ); 9917 write_file( 9918 &root.join("Cargo.toml"), 9919 r#"[workspace] 9920 members = ["crates/a", "crates/b"] 9921 resolver = "2" 9922 9923 [workspace.package] 9924 version = "1.0.0" 9925 9926 [workspace.dependencies] 9927 radroots_a = { path = "crates/a", version = "=1.0.0" } 9928 radroots_b = { path = "crates/b", version = "=1.0.0" } 9929 "#, 9930 ); 9931 write_file( 9932 &root.join("crates").join("a").join("Cargo.toml"), 9933 r#"[package] 9934 name = "radroots_a" 9935 publish = ["crates-io"] 9936 version = "1.0.0" 9937 edition = "2024" 9938 authors = ["Radroots Test"] 9939 rust-version = "1.97" 9940 license = "MIT OR Apache-2.0" 9941 description = "crate a" 9942 repository = "https://example.com/a" 9943 homepage = "https://example.com/a" 9944 documentation = "https://docs.rs/radroots_a" 9945 readme = "README.md" 9946 keywords = ["radroots"] 9947 categories = ["data-structures"] 9948 include = ["src/**", "tests/**", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 9949 9950 [package.metadata.docs.rs] 9951 features = [] 9952 "#, 9953 ); 9954 write_file(&root.join("LICENSE-APACHE"), "Apache license\n"); 9955 write_file(&root.join("LICENSE-MIT"), "MIT license\n"); 9956 for relative in ["README.md", "LICENSE-APACHE", "LICENSE-MIT"] { 9957 let contents = if relative == "README.md" { 9958 "# radroots_a\n".to_owned() 9959 } else { 9960 fs::read_to_string(root.join(relative)).expect("read synthetic package metadata") 9961 }; 9962 write_file(&root.join("crates").join("a").join(relative), &contents); 9963 } 9964 write_file( 9965 &root.join("crates").join("b").join("Cargo.toml"), 9966 r#"[package] 9967 name = "radroots_b" 9968 version = "1.0.0" 9969 edition = "2024" 9970 publish = false 9971 9972 [features] 9973 default = ["std"] 9974 std = [] 9975 legacy-ingest = ["std"] 9976 "#, 9977 ); 9978 write_file( 9979 &root.join("crates").join("b").join("src").join("lib.rs"), 9980 r#"#[cfg(feature = "legacy-ingest")] 9981 pub mod ingest; 9982 9983 #[cfg(feature = "legacy-ingest")] 9984 pub use ingest::{radroots_replica_ingest_event, RadrootsReplicaIngestOutcome}; 9985 "#, 9986 ); 9987 write_file( 9988 &root.join("crates").join("b").join("src").join("types.rs"), 9989 r#"use serde::{Deserialize, Serialize}; 9990 9991 pub const RADROOTS_REPLICA_TRANSFER_VERSION: u32 = 2; 9992 9993 #[derive(Clone, Debug, Serialize, Deserialize)] 9994 #[serde(deny_unknown_fields)] 9995 pub struct RadrootsReplicaFarmSelector; 9996 9997 #[derive(Clone, Debug, Serialize, Deserialize)] 9998 #[serde(deny_unknown_fields)] 9999 pub struct RadrootsReplicaSyncOptions; 10000 10001 #[derive(Clone, Debug, Serialize, Deserialize)] 10002 #[serde(deny_unknown_fields)] 10003 pub struct RadrootsReplicaSyncRequest; 10004 "#, 10005 ); 10006 write_file( 10007 &root.join("crates").join("b").join("src").join("emit.rs"), 10008 r#"pub fn radroots_replica_sync_all_with_options() {} 10009 10010 #[cfg(test)] 10011 mod tests {} 10012 "#, 10013 ); 10014 write_file( 10015 &root.join("Cargo.lock"), 10016 r#"version = 4 10017 10018 [[package]] 10019 name = "radroots_a" 10020 version = "1.0.0" 10021 10022 [[package]] 10023 name = "radroots_b" 10024 version = "1.0.0" 10025 "#, 10026 ); 10027 write_file( 10028 &root.join("crates").join("core").join("src").join("unit.rs"), 10029 r#"pub enum UnitDimension { 10030 Count, 10031 Mass, 10032 Volume, 10033 } 10034 "#, 10035 ); 10036 10037 write_file( 10038 &root.join("contracts").join("manifest.toml"), 10039 r#"[contract] 10040 name = "radroots_contract" 10041 version = "1.0.0" 10042 source = "synthetic" 10043 10044 [surface] 10045 model_crates = ["radroots_a"] 10046 algorithm_crates = ["radroots_b"] 10047 10048 [surface.internal_replica_crates] 10049 schema = "radroots_a" 10050 storage = "radroots_b" 10051 sync = "radroots_b" 10052 10053 [policy] 10054 exclude_internal_workspace_crates = true 10055 require_reproducible_exports = true 10056 require_conformance_vectors = true 10057 10058 [policy.replica] 10059 forbid_legacy_alias_identifiers = true 10060 require_transport_agnostic_sync_contract = true 10061 require_deterministic_emit_ingest = true 10062 "#, 10063 ); 10064 write_file( 10065 &root.join("contracts").join("version.toml"), 10066 r#"[contract] 10067 version = "1.0.0" 10068 stability = "alpha" 10069 10070 [semver] 10071 major_on = ["breaking"] 10072 minor_on = ["feature"] 10073 patch_on = ["fix"] 10074 10075 [release_integrity] 10076 requires_conformance_pass = true 10077 requires_contract_manifest_diff = true 10078 requires_release_notes = true 10079 "#, 10080 ); 10081 write_file( 10082 &root.join("contracts").join("replica.toml"), 10083 r#"schema_version = 1 10084 10085 [contract] 10086 name = "radroots_replica_contract" 10087 version = "1.0.0" 10088 purpose = "synthetic deterministic replica sync" 10089 10090 [crate_family] 10091 schema = "radroots_a" 10092 storage = "radroots_b" 10093 sync = "radroots_b" 10094 10095 [policy] 10096 transport_agnostic_sync_core = true 10097 deterministic_emit_and_ingest = true 10098 forbid_legacy_alias_identifiers = true 10099 profile_event_emission = "excluded" 10100 unknown_sync_request_fields = "reject" 10101 classified_listing_signature_verification = "required_before_state" 10102 classified_listing_head_selection = "raw_before_profile" 10103 classified_listing_operational_projection = "operational_partition_only" 10104 classified_listing_excluded_or_rejected_head = "remove_projection_and_advance" 10105 classified_listing_head_only_ingest = "reject_require_profile_aware" 10106 legacy_bare_envelope_ingest = "explicit_non_default_feature_only" 10107 legacy_ingest_feature = "legacy-ingest" 10108 phase_1_ingest_replacement = "none" 10109 future_product_ingest_input = "store_produced_verified_valid_visible_admission" 10110 10111 [transfer] 10112 version = 2 10113 source = "crates/b/src/types.rs" 10114 constant = "RADROOTS_REPLICA_TRANSFER_VERSION" 10115 "#, 10116 ); 10117 write_file( 10118 &root.join("contracts").join("coverage.toml"), 10119 r#"[gate] 10120 fail_under_exec_lines = 90.0 10121 fail_under_functions = 90.0 10122 fail_under_regions = 90.0 10123 fail_under_branches = 90.0 10124 require_branches = true 10125 10126 [required] 10127 crates = ["radroots_a", "radroots_b"] 10128 "#, 10129 ); 10130 write_file( 10131 &root.join(CHANGELOG_RELATIVE), 10132 "# Changelog\n\n## [1.0.0]\n\n- Synthetic breaking release.\n", 10133 ); 10134 for (canonical_relative, mirror_relative) in CONFORMANCE_VECTOR_MIRRORS { 10135 write_file(&root.join(canonical_relative), SYNTHETIC_CONFORMANCE_VECTOR); 10136 write_file(&root.join(mirror_relative), SYNTHETIC_CONFORMANCE_VECTOR); 10137 } 10138 write_file( 10139 &root.join(RELEASES_ROOT_RELATIVE).join("1.0.0.toml"), 10140 r#"schema_version = 1 10141 10142 [release] 10143 version = "1.0.0" 10144 previous_version = "0.1.0-alpha.2" 10145 contract_base_version = "1.0.0" 10146 status = "unreleased" 10147 10148 [artifacts] 10149 changelog = "CHANGELOG.md" 10150 manifest = "contracts/manifest.toml" 10151 operations = "contracts/operations.toml" 10152 replica = "contracts/replica.toml" 10153 conformance = "contracts/conformance" 10154 publish_policy = "contracts/releases/publish_policy.toml" 10155 10156 [[changes]] 10157 id = "synthetic-major-release" 10158 classification = "breaking" 10159 semver_impacts = ["breaking"] 10160 summary = "Exercise synthetic major release governance." 10161 "#, 10162 ); 10163 write_file( 10164 &root_release_policy_path(&root), 10165 r#"[release] 10166 version = "1.0.0" 10167 10168 [publish] 10169 crates = ["radroots_a"] 10170 10171 [internal] 10172 crates = ["radroots_b"] 10173 10174 [publish_order] 10175 crates = ["radroots_a"] 10176 "#, 10177 ); 10178 write_test_coverage_refresh( 10179 &root, 10180 &[ 10181 passing_coverage_row("radroots_a"), 10182 passing_coverage_row("radroots_b"), 10183 ], 10184 ); 10185 add_operation_contract_files(&root); 10186 root 10187 } 10188 10189 fn add_operation_contract_files(root: &Path) { 10190 write_file( 10191 &root.join("contracts").join("operations.toml"), 10192 r#"[contract] 10193 name = "radroots_contract" 10194 version = "1.0.0" 10195 source = "synthetic" 10196 10197 [public] 10198 domains = ["profile", "farm", "operational_listing", "trade"] 10199 10200 [shared_types] 10201 public = [ 10202 "Nip01EventWireParts", 10203 "GenericEventDraft", 10204 "SignedEvent", 10205 "EventEnvelope", 10206 "EventRef", 10207 "EventPtr", 10208 "ClassifiedListingAddress", 10209 "AuthoredProfile", 10210 "RadrootsInboundProfileMetadata", 10211 "Farm", 10212 "OperationalListing", 10213 ] 10214 10215 [errors] 10216 classes = ["encode_error", "parse_error", "validation_error", "address_error"] 10217 10218 [implementation_provenance] 10219 model_crates = ["radroots_a"] 10220 algorithm_crates = ["radroots_b"] 10221 10222 [operations.profile_build_authored_draft] 10223 domain = "profile" 10224 id = "profile.build_authored_draft" 10225 stability = "beta" 10226 inputs = ["AuthoredProfile"] 10227 outputs = ["Nip01EventWireParts"] 10228 error_class = "encode_error" 10229 deterministic = true 10230 signing = "native" 10231 transport = "native" 10232 10233 [operations.profile_build_authored_draft.implementation] 10234 rust_modules = ["crates/core/src/unit.rs"] 10235 rust_types = ["radroots_event::profile::AuthoredProfile"] 10236 10237 [operations.profile_build_authored_draft.conformance] 10238 vector = "contracts/conformance/vectors/profile/metadata.v1.json" 10239 10240 [operations.operational_listing_build_draft] 10241 domain = "operational_listing" 10242 id = "operational_listing.build_draft" 10243 stability = "beta" 10244 inputs = ["OperationalListing"] 10245 outputs = ["Nip01EventWireParts"] 10246 error_class = "encode_error" 10247 deterministic = true 10248 signing = "native" 10249 transport = "native" 10250 10251 [operations.operational_listing_build_draft.implementation] 10252 rust_modules = ["crates/core/src/unit.rs"] 10253 rust_types = ["radroots_event::listing::operational::OperationalListing"] 10254 10255 [operations.operational_listing_build_draft.conformance] 10256 vector = "contracts/conformance/vectors/operational_listing/build_draft.v1.json" 10257 "#, 10258 ); 10259 write_file( 10260 &root 10261 .join("contracts") 10262 .join("conformance") 10263 .join("schema") 10264 .join("vector.schema.json"), 10265 r#"{ 10266 "$schema": "http://json-schema.org/draft-07/schema#", 10267 "$id": "https://radroots.org/core/conformance/vector.schema.json", 10268 "title": "radroots core conformance vector", 10269 "type": "object", 10270 "required": ["suite", "contract_version", "vectors"], 10271 "properties": { 10272 "suite": { 10273 "type": "string", 10274 "minLength": 1 10275 }, 10276 "contract_version": { 10277 "type": "string", 10278 "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" 10279 }, 10280 "vectors": { 10281 "type": "array", 10282 "items": { 10283 "type": "object", 10284 "required": ["id", "kind", "input"], 10285 "properties": { 10286 "id": { 10287 "type": "string", 10288 "minLength": 1 10289 }, 10290 "kind": { 10291 "type": "string", 10292 "minLength": 1 10293 }, 10294 "input": {}, 10295 "expected": {}, 10296 "expected_error_contains": { 10297 "type": "string", 10298 "minLength": 1 10299 } 10300 }, 10301 "oneOf": [ 10302 { 10303 "required": ["expected"], 10304 "not": {"required": ["expected_error_contains"]} 10305 }, 10306 { 10307 "required": ["expected_error_contains"], 10308 "not": {"required": ["expected"]} 10309 } 10310 ], 10311 "additionalProperties": false 10312 } 10313 } 10314 }, 10315 "additionalProperties": false 10316 } 10317 "#, 10318 ); 10319 write_file( 10320 &root 10321 .join("contracts") 10322 .join("conformance") 10323 .join("vectors") 10324 .join("profile") 10325 .join("metadata.v1.json"), 10326 SYNTHETIC_CONFORMANCE_VECTOR, 10327 ); 10328 let operational_listing_vector = r#"{ 10329 "suite": "operational_listing", 10330 "contract_version": "1.0.0", 10331 "vectors": [ 10332 { 10333 "id": "operational_listing_build_draft_minimal_001", 10334 "kind": "operational_listing.build_draft", 10335 "input": {}, 10336 "expected": {} 10337 } 10338 ] 10339 } 10340 "#; 10341 write_file( 10342 &root 10343 .join("contracts") 10344 .join("conformance") 10345 .join("vectors") 10346 .join("operational_listing") 10347 .join("build_draft.v1.json"), 10348 operational_listing_vector, 10349 ); 10350 write_file( 10351 &root 10352 .join("crates") 10353 .join("event_codec") 10354 .join("tests") 10355 .join("fixtures") 10356 .join("operational_listing_build_draft.v1.json"), 10357 operational_listing_vector, 10358 ); 10359 } 10360 10361 fn write_root_release_policy(root: &Path, raw: &str) { 10362 write_file(&root_release_policy_path(root), raw); 10363 } 10364 10365 fn configure_root_release_policy_workspace(root: &Path) { 10366 write_file( 10367 &root.join("Cargo.toml"), 10368 r#"[workspace] 10369 members = ["crates/a", "crates/b", "crates/c", "crates/d", "crates/e"] 10370 resolver = "2" 10371 10372 [workspace.package] 10373 version = "1.0.0" 10374 10375 [workspace.dependencies] 10376 radroots_a = { path = "crates/a", version = "=1.0.0" } 10377 radroots_b = { path = "crates/b", version = "=1.0.0" } 10378 radroots_c = { path = "crates/c", version = "=1.0.0" } 10379 radroots_d = { path = "crates/d", version = "=1.0.0" } 10380 radroots_e = { path = "crates/e", version = "=1.0.0" } 10381 "#, 10382 ); 10383 for crate_name in ["c", "d", "e"] { 10384 write_file( 10385 &root.join("crates").join(crate_name).join("Cargo.toml"), 10386 &format!( 10387 r#"[package] 10388 name = "radroots_{crate_name}" 10389 version = "1.0.0" 10390 edition = "2024" 10391 publish = false 10392 "# 10393 ), 10394 ); 10395 } 10396 write_file( 10397 &root.join("Cargo.lock"), 10398 r#"version = 4 10399 10400 [[package]] 10401 name = "radroots_a" 10402 version = "1.0.0" 10403 10404 [[package]] 10405 name = "radroots_b" 10406 version = "1.0.0" 10407 10408 [[package]] 10409 name = "radroots_c" 10410 version = "1.0.0" 10411 10412 [[package]] 10413 name = "radroots_d" 10414 version = "1.0.0" 10415 10416 [[package]] 10417 name = "radroots_e" 10418 version = "1.0.0" 10419 "#, 10420 ); 10421 write_file( 10422 &root.join("contracts").join("coverage.toml"), 10423 r#"[gate] 10424 fail_under_exec_lines = 90.0 10425 fail_under_functions = 90.0 10426 fail_under_regions = 90.0 10427 fail_under_branches = 90.0 10428 require_branches = true 10429 10430 [required] 10431 crates = ["radroots_a", "radroots_b", "radroots_c", "radroots_d", "radroots_e"] 10432 "#, 10433 ); 10434 write_test_coverage_refresh( 10435 root, 10436 &[ 10437 passing_coverage_row("radroots_a"), 10438 passing_coverage_row("radroots_b"), 10439 passing_coverage_row("radroots_c"), 10440 passing_coverage_row("radroots_d"), 10441 passing_coverage_row("radroots_e"), 10442 ], 10443 ); 10444 let _ = fs::remove_file(root_release_policy_path(root)); 10445 } 10446 10447 #[test] 10448 fn validate_current_contract_bundle() { 10449 let root = workspace_root(); 10450 let bundle = load_contract_bundle(&root).expect("load contract"); 10451 validate_contract_bundle(&bundle).expect("validate contract"); 10452 } 10453 10454 #[test] 10455 fn knowledge_manifest_vector_authority_rejects_registry_drift() { 10456 let (manifest, vector) = current_knowledge_manifest_authority(); 10457 validate_knowledge_manifest_vector_semantics(&manifest, &vector) 10458 .expect("current knowledge manifest vector authority"); 10459 10460 let (manifest, mut vector) = current_knowledge_manifest_authority(); 10461 let case = vector 10462 .vectors 10463 .iter_mut() 10464 .find(|entry| entry.id == "knowledge_manifest_fields_valid_001") 10465 .expect("knowledge manifest case"); 10466 case.input 10467 .as_object_mut() 10468 .expect("knowledge manifest input") 10469 .insert( 10470 "registry".to_string(), 10471 Value::String("radroots_event_contract_registry_v1".to_string()), 10472 ); 10473 let error = validate_knowledge_manifest_vector_semantics(&manifest, &vector) 10474 .expect_err("stale registry marker must fail"); 10475 assert!(error.contains("registry marker drift"), "{error}"); 10476 10477 let (manifest, mut vector) = current_knowledge_manifest_authority(); 10478 let case = vector 10479 .vectors 10480 .iter_mut() 10481 .find(|entry| entry.id == "knowledge_manifest_fields_valid_001") 10482 .expect("knowledge manifest case"); 10483 case.expected 10484 .as_mut() 10485 .expect("knowledge manifest expected output") 10486 .as_object_mut() 10487 .expect("knowledge manifest expected output object") 10488 .insert("registry_version".to_string(), Value::from(1_u64)); 10489 let error = validate_knowledge_manifest_vector_semantics(&manifest, &vector) 10490 .expect_err("stale expected registry version must fail"); 10491 assert!(error.contains("expected registry_version drift"), "{error}"); 10492 } 10493 10494 #[test] 10495 fn knowledge_manifest_artifacts_are_atomic_fresh_and_shape_checked() { 10496 let root = temp_root("knowledge_manifest_artifacts"); 10497 let generated = 10498 write_knowledge_contract_manifest_artifacts(&root).expect("write manifest artifacts"); 10499 assert_eq!( 10500 generated, 10501 expected_knowledge_contract_manifest_json().expect("expected manifest") 10502 ); 10503 assert_eq!( 10504 validate_knowledge_contract_manifest_artifacts(&root) 10505 .expect("fresh manifest artifacts"), 10506 generated 10507 ); 10508 10509 let manifest_path = root.join(KNOWLEDGE_MANIFEST_RELATIVE); 10510 let mut extra_lf = fs::read_to_string(&manifest_path).expect("read manifest"); 10511 extra_lf.push('\n'); 10512 fs::write(&manifest_path, extra_lf).expect("write noncanonical manifest"); 10513 let error = validate_knowledge_contract_manifest_artifacts(&root) 10514 .expect_err("noncanonical manifest must fail"); 10515 assert!(error.contains("exactly one LF"), "{error}"); 10516 10517 write_knowledge_contract_manifest_artifacts(&root).expect("restore manifest artifacts"); 10518 let mut value: Value = 10519 serde_json::from_slice(&fs::read(&manifest_path).expect("read restored manifest")) 10520 .expect("parse restored manifest"); 10521 value["contract_count"] = Value::from(0_u64); 10522 let mut mismatched = serde_json::to_string_pretty(&value).expect("serialize mismatch"); 10523 mismatched.push('\n'); 10524 fs::write(&manifest_path, mismatched).expect("write count mismatch"); 10525 let error = validate_knowledge_contract_manifest_artifacts(&root) 10526 .expect_err("count mismatch must fail"); 10527 assert!(error.contains("contract_count"), "{error}"); 10528 10529 let _ = fs::remove_dir_all(root); 10530 } 10531 10532 #[test] 10533 fn strict_post_release_record_governs_public_boundary_breaks() { 10534 let root = workspace_root(); 10535 let bundle = load_contract_bundle(&root).expect("load current contract bundle"); 10536 let major_impacts = bundle 10537 .version 10538 .semver 10539 .major_on 10540 .iter() 10541 .map(String::as_str) 10542 .collect::<BTreeSet<_>>(); 10543 for impact in [ 10544 "add_exported_field", 10545 "change_exported_function_signature", 10546 "change_exported_constant_value", 10547 ] { 10548 assert!( 10549 major_impacts.contains(impact), 10550 "version policy must govern {impact} as a major impact" 10551 ); 10552 } 10553 assert!( 10554 bundle 10555 .version 10556 .semver 10557 .minor_on 10558 .iter() 10559 .any(|impact| impact == "add_exported_constant"), 10560 "version policy must govern add_exported_constant as a minor impact" 10561 ); 10562 10563 let release = 10564 parse_toml::<ReleaseRecord>(&root.join("contracts/releases/1.0.0-alpha.1.toml")) 10565 .expect("current release record"); 10566 let change = release 10567 .changes 10568 .iter() 10569 .find(|change| change.id == "strict-kind-one-product-profiles") 10570 .expect("strict kind-one release change"); 10571 let impacts = change 10572 .semver_impacts 10573 .iter() 10574 .map(String::as_str) 10575 .collect::<BTreeSet<_>>(); 10576 for impact in [ 10577 "remove_exported_type", 10578 "add_exported_constant", 10579 "add_exported_field", 10580 "change_exported_function_signature", 10581 "change_exported_enum_variant", 10582 "change_exported_constant_value", 10583 ] { 10584 assert!( 10585 impacts.contains(impact), 10586 "strict kind-one release change must declare {impact}" 10587 ); 10588 } 10589 } 10590 10591 #[test] 10592 fn post_operation_authority_rejects_manifest_and_inventory_drift() { 10593 let (manifest, vector) = current_post_authority(); 10594 validate_post_operation_inventory(&manifest, &vector).expect("current post authority"); 10595 10596 let (mut manifest, vector) = current_post_authority(); 10597 manifest 10598 .operations 10599 .remove("social_update_build_authored_draft"); 10600 let error = validate_post_operation_inventory(&manifest, &vector) 10601 .expect_err("missing post operation must fail"); 10602 assert!(error.contains("post operation authority drift")); 10603 10604 let (mut manifest, vector) = current_post_authority(); 10605 manifest 10606 .operations 10607 .get_mut("social_update_build_authored_draft") 10608 .expect("Update operation") 10609 .id = "social.update.wrong".to_string(); 10610 let error = validate_post_operation_inventory(&manifest, &vector) 10611 .expect_err("wrong post operation ID must fail"); 10612 assert!(error.contains("id drift")); 10613 10614 let (mut manifest, vector) = current_post_authority(); 10615 manifest 10616 .operations 10617 .get_mut("social_update_build_authored_draft") 10618 .expect("Update operation") 10619 .conformance 10620 .vector = "contracts/conformance/vectors/profile/metadata.v1.json".to_string(); 10621 let error = validate_post_operation_inventory(&manifest, &vector) 10622 .expect_err("wrong post vector path must fail"); 10623 assert!(error.contains("conformance.vector drift")); 10624 10625 let (mut manifest, vector) = current_post_authority(); 10626 manifest 10627 .operations 10628 .get_mut("social_update_build_authored_draft") 10629 .expect("Update operation") 10630 .conformance 10631 .case_kinds[0] = "social.ask.build_authored_draft.valid".to_string(); 10632 let error = validate_post_operation_inventory(&manifest, &vector) 10633 .expect_err("wrong post case prefix must fail"); 10634 assert!(error.contains("must start with social.update.build_authored_draft.")); 10635 10636 let (mut manifest, vector) = current_post_authority(); 10637 manifest 10638 .operations 10639 .get_mut("social_update_build_authored_draft") 10640 .expect("Update operation") 10641 .conformance 10642 .case_kinds 10643 .pop(); 10644 let error = validate_post_operation_inventory(&manifest, &vector) 10645 .expect_err("missing post case kind must fail"); 10646 assert!(error.contains("conformance.case_kinds drift")); 10647 10648 let (mut manifest, vector) = current_post_authority(); 10649 let operation = manifest 10650 .operations 10651 .get_mut("social_update_build_authored_draft") 10652 .expect("Update operation"); 10653 operation.conformance.case_kinds[1] = operation.conformance.case_kinds[0].clone(); 10654 let error = validate_post_operation_inventory(&manifest, &vector) 10655 .expect_err("duplicate post case kind must fail"); 10656 assert!(error.contains("duplicate value"), "{error}"); 10657 10658 let (manifest, mut vector) = current_post_authority(); 10659 vector.vectors.push(ConformanceVectorEntry { 10660 id: "unclaimed_post_case".to_string(), 10661 kind: "social.post.unclaimed.valid".to_string(), 10662 input: Value::Object(Default::default()), 10663 expected: Some(Value::Object(Default::default())), 10664 expected_error_contains: None, 10665 }); 10666 let error = validate_post_operation_inventory(&manifest, &vector) 10667 .expect_err("unclaimed post vector kind must fail"); 10668 assert!(error.contains("is not claimed by exactly one operation")); 10669 10670 let (manifest, mut vector) = current_post_authority(); 10671 vector.vectors.remove( 10672 vector 10673 .vectors 10674 .iter() 10675 .position(|entry| entry.kind == "social.post.project_verified_event.valid") 10676 .expect("project valid case"), 10677 ); 10678 let error = validate_post_operation_inventory(&manifest, &vector) 10679 .expect_err("post vector count drift must fail"); 10680 assert!(error.contains("post conformance vector inventory drift")); 10681 } 10682 10683 #[test] 10684 fn verified_admission_authority_rejects_manifest_fixture_and_secret_drift() { 10685 let (manifest, vector) = current_admission_authority(); 10686 admission_authority::validate_admission_operation_inventory(&manifest, &vector) 10687 .expect("current verified admission authority"); 10688 10689 let (mut manifest, vector) = current_admission_authority(); 10690 manifest.operations.remove("event_admit_verified"); 10691 let error = admission_authority::validate_admission_operation_inventory(&manifest, &vector) 10692 .expect_err("missing central admission operation must fail"); 10693 assert!(error.contains("operation authority drift"), "{error}"); 10694 10695 let (mut manifest, vector) = current_admission_authority(); 10696 manifest 10697 .shared_types 10698 .public 10699 .retain(|value| value != "RadrootsEventAdmissionError"); 10700 let error = admission_authority::validate_admission_operation_inventory(&manifest, &vector) 10701 .expect_err("missing central admission public type must fail"); 10702 assert!(error.contains("requires shared public type"), "{error}"); 10703 10704 let (manifest, mut vector) = current_admission_authority(); 10705 vector.vectors[0] 10706 .input 10707 .as_object_mut() 10708 .expect("admission input") 10709 .insert( 10710 "secret_key".to_string(), 10711 Value::String("forbidden".to_string()), 10712 ); 10713 let error = admission_authority::validate_admission_operation_inventory(&manifest, &vector) 10714 .expect_err("fixture secret material must fail exact input inventory"); 10715 assert!(error.contains("field inventory drift"), "{error}"); 10716 10717 let (manifest, mut vector) = current_admission_authority(); 10718 vector.vectors[0].id = "renamed_admission_case".to_string(); 10719 let error = admission_authority::validate_admission_operation_inventory(&manifest, &vector) 10720 .expect_err("renamed admission vector must fail exact inventory"); 10721 assert!(error.contains("unexpected id"), "{error}"); 10722 } 10723 10724 #[test] 10725 fn post_operation_authority_rejects_another_vector_namespace_operation() { 10726 let (mut manifest, vector) = current_post_authority(); 10727 let mut unexpected = manifest 10728 .operations 10729 .remove("social_reaction_build_tags") 10730 .expect("unrelated social operation"); 10731 unexpected.id = "social.update.shadow".to_string(); 10732 manifest 10733 .operations 10734 .insert("social_update_shadow".to_string(), unexpected); 10735 10736 let error = validate_post_operation_inventory(&manifest, &vector) 10737 .expect_err("another-vector post namespace operation must fail"); 10738 assert!(error.contains("post operation authority drift"), "{error}"); 10739 assert!(error.contains("social_update_shadow"), "{error}"); 10740 } 10741 10742 #[test] 10743 fn post_operation_authority_rejects_metadata_drift() { 10744 let (mut manifest, vector) = current_post_authority(); 10745 manifest 10746 .operations 10747 .get_mut("social_update_build_authored_draft") 10748 .expect("Update operation") 10749 .stability = "stable".to_string(); 10750 10751 let error = validate_post_operation_inventory(&manifest, &vector) 10752 .expect_err("post operation metadata drift must fail"); 10753 assert!(error.contains("stability drift"), "{error}"); 10754 } 10755 10756 #[test] 10757 fn post_operation_authority_rejects_required_public_type_removal() { 10758 let (mut manifest, vector) = current_post_authority(); 10759 manifest 10760 .shared_types 10761 .public 10762 .retain(|value| value != "RadrootsPostAdmissionOutcome"); 10763 10764 let error = validate_post_operation_inventory(&manifest, &vector) 10765 .expect_err("required post public type removal must fail"); 10766 assert!( 10767 error.contains( 10768 "post operation authority requires shared public type RadrootsPostAdmissionOutcome" 10769 ), 10770 "{error}" 10771 ); 10772 } 10773 10774 #[test] 10775 fn post_operation_authority_rejects_same_count_vector_id_replacement() { 10776 let (manifest, mut vector) = current_post_authority(); 10777 vector 10778 .vectors 10779 .iter_mut() 10780 .find(|entry| entry.id == "authored_update_wire") 10781 .expect("authored Update case") 10782 .id = "authored_update_wire_replacement".to_string(); 10783 10784 let error = validate_post_operation_inventory(&manifest, &vector) 10785 .expect_err("same-count post vector ID replacement must fail"); 10786 assert!(error.contains("post conformance vector inventory drift")); 10787 } 10788 10789 #[test] 10790 fn post_operation_authority_rejects_vector_id_kind_drift() { 10791 let (manifest, mut vector) = current_post_authority(); 10792 let update_position = vector 10793 .vectors 10794 .iter() 10795 .position(|entry| entry.id == "authored_update_wire") 10796 .expect("authored Update case"); 10797 let ask_position = vector 10798 .vectors 10799 .iter() 10800 .position(|entry| entry.id == "authored_ask_wire") 10801 .expect("authored Ask case"); 10802 let update_kind = vector.vectors[update_position].kind.clone(); 10803 vector.vectors[update_position].kind = vector.vectors[ask_position].kind.clone(); 10804 vector.vectors[ask_position].kind = update_kind; 10805 10806 let error = validate_post_operation_inventory(&manifest, &vector) 10807 .expect_err("post vector ID-to-kind drift must fail"); 10808 assert!(error.contains("post conformance vector inventory drift")); 10809 } 10810 10811 #[test] 10812 fn comment_operation_authority_rejects_contract_drift() { 10813 let (manifest, vector) = current_comment_authority(); 10814 validate_comment_operation_inventory(&manifest, &vector) 10815 .expect("current Comment operation authority"); 10816 10817 let (mut manifest, vector) = current_comment_authority(); 10818 manifest 10819 .operations 10820 .remove("social_comment_build_authored_draft"); 10821 let error = validate_comment_operation_inventory(&manifest, &vector) 10822 .expect_err("missing Comment operation must fail"); 10823 assert!( 10824 error.contains("comment operation authority drift"), 10825 "{error}" 10826 ); 10827 10828 let (mut manifest, vector) = current_comment_authority(); 10829 let renamed = manifest 10830 .operations 10831 .remove("social_comment_project_verified_event") 10832 .expect("Comment projection operation"); 10833 manifest 10834 .operations 10835 .insert("social_comment_project_event".to_string(), renamed); 10836 let error = validate_comment_operation_inventory(&manifest, &vector) 10837 .expect_err("renamed Comment operation must fail"); 10838 assert!( 10839 error.contains("comment operation authority drift"), 10840 "{error}" 10841 ); 10842 assert!(error.contains("social_comment_project_event"), "{error}"); 10843 10844 let (mut manifest, vector) = current_comment_authority(); 10845 manifest 10846 .operations 10847 .get_mut("social_comment_verify_and_admit_event") 10848 .expect("Comment admission operation") 10849 .signing = "none".to_string(); 10850 let error = validate_comment_operation_inventory(&manifest, &vector) 10851 .expect_err("Comment operation metadata drift must fail"); 10852 assert!(error.contains("signing drift"), "{error}"); 10853 10854 let (mut manifest, vector) = current_comment_authority(); 10855 manifest 10856 .shared_types 10857 .public 10858 .retain(|value| value != "RadrootsInboundNip22TopLevelEventReference"); 10859 let error = validate_comment_operation_inventory(&manifest, &vector) 10860 .expect_err("required Comment public type removal must fail"); 10861 assert!( 10862 error.contains( 10863 "comment operation authority requires shared public type RadrootsInboundNip22TopLevelEventReference" 10864 ), 10865 "{error}" 10866 ); 10867 } 10868 10869 #[test] 10870 fn comment_operation_authority_rejects_vector_inventory_drift() { 10871 let (manifest, mut vector) = current_comment_authority(); 10872 vector 10873 .vectors 10874 .iter_mut() 10875 .find(|entry| entry.id == "authored_top_event_listing") 10876 .expect("authored top-level event case") 10877 .id = "authored_top_event_listing_replacement".to_string(); 10878 let error = validate_comment_operation_inventory(&manifest, &vector) 10879 .expect_err("same-count Comment vector ID replacement must fail"); 10880 assert!( 10881 error.contains("comment conformance vector inventory drift"), 10882 "{error}" 10883 ); 10884 10885 let (manifest, mut vector) = current_comment_authority(); 10886 vector.vectors.push(ConformanceVectorEntry { 10887 id: "unclaimed_comment_case".to_string(), 10888 kind: "social.comment.project_verified_event.shadow".to_string(), 10889 input: Value::Object(Default::default()), 10890 expected: Some(Value::Object(Default::default())), 10891 expected_error_contains: None, 10892 }); 10893 let error = validate_comment_operation_inventory(&manifest, &vector) 10894 .expect_err("unclaimed Comment vector kind must fail"); 10895 assert!( 10896 error.contains("is not claimed by exactly one operation"), 10897 "{error}" 10898 ); 10899 } 10900 10901 #[test] 10902 fn comment_vector_namespace_rejects_legacy_owners() { 10903 let canonical = PathBuf::from(COMMENT_CONFORMANCE_VECTOR_RELATIVE); 10904 let legacy = PathBuf::from("contracts/conformance/vectors/social/mvp.v1.json"); 10905 let vector = ConformanceVectorFile { 10906 suite: "legacy".to_string(), 10907 contract_version: "1.0.0".to_string(), 10908 vectors: vec![ConformanceVectorEntry { 10909 id: "legacy_comment".to_string(), 10910 kind: "social.comment.build_tags".to_string(), 10911 input: Value::Object(Default::default()), 10912 expected: Some(Value::Object(Default::default())), 10913 expected_error_contains: None, 10914 }], 10915 }; 10916 10917 let error = validate_comment_vector_namespace(&legacy, &canonical, &vector) 10918 .expect_err("legacy Comment vector namespace must fail"); 10919 assert!(error.contains("outside canonical vector"), "{error}"); 10920 validate_comment_vector_namespace(&canonical, &canonical, &vector) 10921 .expect("canonical Comment vector owns the namespace"); 10922 } 10923 10924 #[test] 10925 fn deletion_operation_authority_rejects_contract_drift() { 10926 let (manifest, request_vector, suppression_vector) = current_deletion_authority(); 10927 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 10928 .expect("current deletion operation authority"); 10929 10930 let (mut manifest, request_vector, suppression_vector) = current_deletion_authority(); 10931 manifest 10932 .operations 10933 .remove("social_deletion_request_project_verified_event"); 10934 let error = 10935 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 10936 .expect_err("missing deletion operation must fail"); 10937 assert!( 10938 error.contains("deletion operation authority drift"), 10939 "{error}" 10940 ); 10941 10942 let (mut manifest, request_vector, suppression_vector) = current_deletion_authority(); 10943 manifest 10944 .shared_types 10945 .public 10946 .push("RadrootsNip09DeletionUnauthorizedEffect".to_string()); 10947 let error = 10948 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 10949 .expect_err("unexpected deletion public type must fail"); 10950 assert!( 10951 error.contains("deletion operation public-type authority drift"), 10952 "{error}" 10953 ); 10954 10955 let (mut manifest, request_vector, suppression_vector) = current_deletion_authority(); 10956 manifest 10957 .operations 10958 .get_mut("social_deletion_request_verify_and_admit_event") 10959 .expect("admission operation") 10960 .conformance 10961 .case_kinds 10962 .pop(); 10963 let error = 10964 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 10965 .expect_err("missing deletion case kind must fail"); 10966 assert!(error.contains("conformance.case_kinds drift"), "{error}"); 10967 10968 let (mut manifest, request_vector, suppression_vector) = current_deletion_authority(); 10969 manifest 10970 .operations 10971 .get_mut("social_deletion_request_evaluate_suppression") 10972 .expect("suppression operation") 10973 .conformance 10974 .vector = DELETION_CONFORMANCE_VECTOR_RELATIVE.to_string(); 10975 let error = 10976 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 10977 .expect_err("suppression vector ownership drift must fail"); 10978 assert!(error.contains("conformance.vector drift"), "{error}"); 10979 } 10980 10981 #[test] 10982 fn deletion_operation_authority_rejects_vector_inventory_drift() { 10983 let (manifest, mut request_vector, suppression_vector) = current_deletion_authority(); 10984 request_vector 10985 .vectors 10986 .iter_mut() 10987 .find(|entry| entry.id == "nip09_authored_event_target_min_kind_empty_content") 10988 .expect("authored deletion vector") 10989 .id = "nip09_authored_event_target_min_kind_replacement".to_string(); 10990 let error = 10991 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 10992 .expect_err("same-count deletion vector ID replacement must fail"); 10993 assert!( 10994 error.contains("deletion conformance vector inventory drift"), 10995 "{error}" 10996 ); 10997 10998 let (manifest, mut request_vector, suppression_vector) = current_deletion_authority(); 10999 let source = request_vector 11000 .vectors 11001 .iter() 11002 .find(|entry| entry.id == "nip09_project_signed_event_target_without_k") 11003 .expect("valid signed deletion vector"); 11004 let input = source.input.clone(); 11005 let expected = source.expected.clone(); 11006 request_vector.vectors.push(ConformanceVectorEntry { 11007 id: "nip09_unclaimed_case".to_string(), 11008 kind: "social.deletion_request.unclaimed.valid".to_string(), 11009 input, 11010 expected, 11011 expected_error_contains: None, 11012 }); 11013 let error = 11014 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 11015 .expect_err("unclaimed deletion vector kind must fail"); 11016 assert!( 11017 error.contains("is not claimed by exactly one operation"), 11018 "{error}" 11019 ); 11020 11021 let (manifest, request_vector, mut suppression_vector) = current_deletion_authority(); 11022 suppression_vector 11023 .vectors 11024 .iter_mut() 11025 .find(|entry| entry.id == "nip09_suppress_no_requests_visible") 11026 .expect("visible suppression vector") 11027 .id = "nip09_suppress_replacement_visible".to_string(); 11028 let error = 11029 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 11030 .expect_err("same-count suppression vector ID replacement must fail"); 11031 assert!( 11032 error.contains("deletion suppression conformance vector inventory drift"), 11033 "{error}" 11034 ); 11035 } 11036 11037 #[test] 11038 fn deletion_operation_authority_rejects_generation_and_effect_metadata() { 11039 let (manifest, mut request_vector, suppression_vector) = current_deletion_authority(); 11040 request_vector 11041 .vectors 11042 .iter_mut() 11043 .find(|entry| entry.id == "nip09_authored_event_target_min_kind_empty_content") 11044 .expect("authored deletion vector") 11045 .input 11046 .as_object_mut() 11047 .expect("authored input") 11048 .insert("SeEd".to_string(), Value::from(7_u64)); 11049 let error = 11050 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 11051 .expect_err("generation seed metadata must fail"); 11052 assert!(error.contains("forbidden metadata key"), "{error}"); 11053 11054 let (manifest, mut request_vector, suppression_vector) = current_deletion_authority(); 11055 request_vector 11056 .vectors 11057 .iter_mut() 11058 .find(|entry| entry.id == "nip09_project_signed_event_target_without_k") 11059 .expect("signed deletion vector") 11060 .input 11061 .as_object_mut() 11062 .expect("signed input") 11063 .insert("trace".to_string(), Value::Bool(true)); 11064 let error = 11065 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 11066 .expect_err("extra signed input key must fail"); 11067 assert!(error.contains("input keys drift"), "{error}"); 11068 11069 let (manifest, mut request_vector, suppression_vector) = current_deletion_authority(); 11070 request_vector 11071 .vectors 11072 .iter_mut() 11073 .find(|entry| entry.id == "nip09_project_signed_event_target_without_k") 11074 .expect("signed deletion vector") 11075 .expected 11076 .as_mut() 11077 .expect("projection expected") 11078 .as_object_mut() 11079 .expect("projection expected object") 11080 .insert("AuThOrIzAtIoN".to_string(), Value::Bool(true)); 11081 let error = 11082 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 11083 .expect_err("effect-authority output must fail"); 11084 assert!(error.contains("forbidden metadata key"), "{error}"); 11085 11086 let (manifest, mut request_vector, suppression_vector) = current_deletion_authority(); 11087 request_vector 11088 .vectors 11089 .iter_mut() 11090 .find(|entry| entry.id == "nip09_admit_signed_event_target") 11091 .expect("admission deletion vector") 11092 .input 11093 .as_object_mut() 11094 .expect("signed input") 11095 .insert( 11096 "event_json".to_string(), 11097 Value::String(r#"{"content":"NSEC1FORBIDDEN"}"#.to_string()), 11098 ); 11099 let error = 11100 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 11101 .expect_err("nsec material must fail"); 11102 assert!(error.contains("forbidden nsec material"), "{error}"); 11103 11104 let (manifest, mut request_vector, suppression_vector) = current_deletion_authority(); 11105 request_vector 11106 .vectors 11107 .iter_mut() 11108 .find(|entry| entry.id == "nip09_admit_signed_event_target") 11109 .expect("admission deletion vector") 11110 .input 11111 .as_object_mut() 11112 .expect("signed input") 11113 .insert( 11114 "event_json".to_string(), 11115 Value::String( 11116 r#"{"content":"prefix10C5304D6C9AE3A1A16F7860F1CC8F5E3A76225A2663B3A989A0D775919B7DF5suffix"}"# 11117 .to_string(), 11118 ), 11119 ); 11120 let error = 11121 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 11122 .expect_err("approved fixture secret material must fail"); 11123 assert!( 11124 error.contains("forbidden approved fixture secret material"), 11125 "{error}" 11126 ); 11127 } 11128 11129 #[test] 11130 fn deletion_suppression_authority_rejects_shape_and_material_drift() { 11131 let (manifest, request_vector, mut suppression_vector) = current_deletion_authority(); 11132 suppression_vector.suite = "nip09_suppression_shadow".to_string(); 11133 let error = 11134 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 11135 .expect_err("suppression suite drift must fail"); 11136 assert!( 11137 error.contains("deletion suppression conformance suite drift"), 11138 "{error}" 11139 ); 11140 11141 let (manifest, request_vector, mut suppression_vector) = current_deletion_authority(); 11142 suppression_vector 11143 .vectors 11144 .iter_mut() 11145 .find(|entry| entry.id == "nip09_suppress_no_requests_visible") 11146 .expect("visible suppression vector") 11147 .input 11148 .as_object_mut() 11149 .expect("suppression input") 11150 .insert("seed".to_string(), Value::from(7_u64)); 11151 let error = 11152 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 11153 .expect_err("suppression generation metadata must fail"); 11154 assert!(error.contains("forbidden metadata key"), "{error}"); 11155 11156 let (manifest, request_vector, mut suppression_vector) = current_deletion_authority(); 11157 suppression_vector 11158 .vectors 11159 .iter_mut() 11160 .find(|entry| entry.id == "nip09_suppress_same_author_event_reference") 11161 .expect("event-reference suppression vector") 11162 .expected 11163 .as_mut() 11164 .expect("suppression expected") 11165 .as_object_mut() 11166 .expect("suppression expected object") 11167 .get_mut("event_reference") 11168 .expect("event-reference evidence") 11169 .as_object_mut() 11170 .expect("event-reference object") 11171 .insert("request_id".to_string(), Value::String("0".repeat(64))); 11172 let error = 11173 validate_deletion_operation_inventory(&manifest, &request_vector, &suppression_vector) 11174 .expect_err("evidence not bound to an input request must fail"); 11175 assert!(error.contains("must identify an input request"), "{error}"); 11176 } 11177 11178 #[test] 11179 fn deletion_vector_namespace_rejects_alternate_owners() { 11180 let canonical_request = PathBuf::from(DELETION_CONFORMANCE_VECTOR_RELATIVE); 11181 let canonical_suppression = PathBuf::from(DELETION_SUPPRESSION_CONFORMANCE_VECTOR_RELATIVE); 11182 let alternate = PathBuf::from("contracts/conformance/vectors/social/mvp.v1.json"); 11183 let vector = ConformanceVectorFile { 11184 suite: "alternate".to_string(), 11185 contract_version: "1.0.0".to_string(), 11186 vectors: vec![ConformanceVectorEntry { 11187 id: "nip09_alternate".to_string(), 11188 kind: "social.deletion_request.build_authored_draft.valid".to_string(), 11189 input: Value::Object(Default::default()), 11190 expected: Some(Value::Object(Default::default())), 11191 expected_error_contains: None, 11192 }], 11193 }; 11194 11195 let error = validate_deletion_vector_namespace( 11196 &alternate, 11197 &canonical_request, 11198 &canonical_suppression, 11199 &vector, 11200 ) 11201 .expect_err("alternate deletion vector namespace must fail"); 11202 assert!(error.contains("outside canonical vectors"), "{error}"); 11203 validate_deletion_vector_namespace( 11204 &canonical_request, 11205 &canonical_request, 11206 &canonical_suppression, 11207 &vector, 11208 ) 11209 .expect("canonical deletion vector owns the namespace"); 11210 validate_deletion_vector_namespace( 11211 &canonical_suppression, 11212 &canonical_request, 11213 &canonical_suppression, 11214 &vector, 11215 ) 11216 .expect("canonical deletion suppression vector owns the namespace"); 11217 } 11218 11219 #[test] 11220 fn food_availability_operation_authority_rejects_contract_drift() { 11221 let (manifest, vector) = current_food_availability_authority(); 11222 validate_food_availability_operation_inventory(&manifest, &vector) 11223 .expect("current FoodAvailability operation authority"); 11224 11225 let (mut manifest, vector) = current_food_availability_authority(); 11226 manifest 11227 .operations 11228 .remove("food_availability_build_authored_draft"); 11229 let error = validate_food_availability_operation_inventory(&manifest, &vector) 11230 .expect_err("missing FoodAvailability operation must fail"); 11231 assert!( 11232 error.contains("food availability operation authority drift"), 11233 "{error}" 11234 ); 11235 11236 let (mut manifest, vector) = current_food_availability_authority(); 11237 manifest 11238 .shared_types 11239 .public 11240 .retain(|value| value != "RadrootsFoodAvailabilityRevisionError"); 11241 let error = validate_food_availability_operation_inventory(&manifest, &vector) 11242 .expect_err("missing FoodAvailability public type must fail"); 11243 assert!( 11244 error.contains( 11245 "food availability operation authority requires shared public type RadrootsFoodAvailabilityRevisionError" 11246 ), 11247 "{error}" 11248 ); 11249 11250 let (mut manifest, vector) = current_food_availability_authority(); 11251 manifest 11252 .operations 11253 .get_mut("food_availability_validate_revision") 11254 .expect("revision operation") 11255 .conformance 11256 .case_kinds 11257 .pop(); 11258 let error = validate_food_availability_operation_inventory(&manifest, &vector) 11259 .expect_err("missing FoodAvailability case kind must fail"); 11260 assert!(error.contains("conformance.case_kinds drift"), "{error}"); 11261 } 11262 11263 #[test] 11264 fn food_availability_operation_authority_rejects_vector_inventory_drift() { 11265 let (manifest, mut vector) = current_food_availability_authority(); 11266 vector 11267 .vectors 11268 .iter_mut() 11269 .find(|entry| entry.id == "food_admission_normalizes_decimal_currency_014") 11270 .expect("normalization vector") 11271 .id = "food_admission_normalizes_decimal_currency_replacement".to_string(); 11272 let error = validate_food_availability_operation_inventory(&manifest, &vector) 11273 .expect_err("same-count FoodAvailability vector replacement must fail"); 11274 assert!( 11275 error.contains("food availability conformance vector inventory drift"), 11276 "{error}" 11277 ); 11278 11279 let (manifest, mut vector) = current_food_availability_authority(); 11280 vector.vectors.push(ConformanceVectorEntry { 11281 id: "food_unclaimed_case".to_string(), 11282 kind: "food_availability.unclaimed.valid".to_string(), 11283 input: Value::Object(Default::default()), 11284 expected: Some(Value::Object(Default::default())), 11285 expected_error_contains: None, 11286 }); 11287 let error = validate_food_availability_operation_inventory(&manifest, &vector) 11288 .expect_err("unclaimed FoodAvailability vector kind must fail"); 11289 assert!( 11290 error.contains("is not claimed by exactly one operation"), 11291 "{error}" 11292 ); 11293 } 11294 11295 #[test] 11296 fn version_governance_rejects_contract_workspace_and_lock_drift() { 11297 let root = create_synthetic_workspace("version_governance_drift"); 11298 let mut bundle = load_contract_bundle(&root).expect("load contract"); 11299 bundle.version.contract.version = "1.0.1".to_string(); 11300 let contract_error = validate_contract_version_lockstep(&bundle) 11301 .expect_err("contract header drift must fail"); 11302 assert!(contract_error.contains("must match manifest contract version")); 11303 11304 let member_path = root.join("crates/a/Cargo.toml"); 11305 let member = fs::read_to_string(&member_path).expect("read member manifest"); 11306 write_file( 11307 &member_path, 11308 &member.replace("version = \"1.0.0\"", "version.workspace = true"), 11309 ); 11310 let member_error = validate_workspace_version_lockstep(&root, "1.0.0") 11311 .expect_err("inherited member version must fail"); 11312 assert!(member_error.contains("must set an explicit package version")); 11313 write_file(&member_path, &member); 11314 11315 let workspace_path = root.join("Cargo.toml"); 11316 let workspace = fs::read_to_string(&workspace_path).expect("read workspace manifest"); 11317 write_file( 11318 &workspace_path, 11319 &workspace.replacen( 11320 "radroots_a = { path = \"crates/a\", version = \"=1.0.0\" }", 11321 "radroots_a = { path = \"crates/a\", version = \"1.0.0\" }", 11322 1, 11323 ), 11324 ); 11325 let requirement_error = validate_workspace_version_lockstep(&root, "1.0.0") 11326 .expect_err("non-exact internal dependency must fail"); 11327 assert!(requirement_error.contains("exact requirement =1.0.0")); 11328 write_file(&workspace_path, &workspace); 11329 11330 let lock_path = root.join("Cargo.lock"); 11331 let lock = fs::read_to_string(&lock_path).expect("read Cargo.lock"); 11332 write_file(&lock_path, &lock.replacen("1.0.0", "1.0.1", 1)); 11333 let lock_error = validate_workspace_version_lockstep(&root, "1.0.0") 11334 .expect_err("lockfile version drift must fail"); 11335 assert!(lock_error.contains("Cargo.lock package radroots_a version")); 11336 11337 write_file( 11338 &root.join("contracts/crates/release_v1/radroots_crates_release_v1.toml"), 11339 r#"spec_id = "radroots.crates.release.v1" 11340 package_count = 0 11341 package = [] 11342 11343 [repositories.lib] 11344 version = "0.1.0-alpha" 11345 packages = [] 11346 11347 [repositories.sdk] 11348 version = "0.1.0" 11349 packages = [] 11350 "#, 11351 ); 11352 let architecture_error = validate_workspace_version_lockstep(&root, "1.0.0") 11353 .expect_err("repository version authority must override protocol version"); 11354 assert!(architecture_error.contains("must match library repository version 0.1.0-alpha")); 11355 11356 assert!(parse_semver_version("01.0.0").is_err()); 11357 assert!(parse_semver_version("1.0").is_err()); 11358 assert!(parse_semver_version("1.0.0-alpha_1").is_err()); 11359 let _ = fs::remove_dir_all(root); 11360 } 11361 11362 #[test] 11363 fn replica_contract_governance_rejects_metadata_policy_and_transfer_drift() { 11364 let root = create_synthetic_workspace("replica_contract_drift"); 11365 let bundle = load_contract_bundle(&root).expect("load synthetic contract"); 11366 validate_replica_contract(&bundle, &root).expect("validate replica contract"); 11367 11368 let assert_replica_error = |expected: &str, mutator: fn(&mut ContractBundle)| { 11369 let mut bundle = load_contract_bundle(&root).expect("load synthetic contract"); 11370 mutator(&mut bundle); 11371 let error = validate_replica_contract(&bundle, &root) 11372 .expect_err("replica contract drift must fail"); 11373 assert!( 11374 error.contains(expected), 11375 "expected `{expected}` in `{error}`" 11376 ); 11377 }; 11378 11379 assert_replica_error("schema_version must be 1", |bundle| { 11380 bundle.replica.schema_version = 2; 11381 }); 11382 assert_replica_error("name must be radroots_replica_contract", |bundle| { 11383 bundle.replica.contract.name = "replica".to_string(); 11384 }); 11385 assert_replica_error("must match manifest contract version", |bundle| { 11386 bundle.replica.contract.version = "1.0.1".to_string(); 11387 }); 11388 assert_replica_error("purpose is required", |bundle| { 11389 bundle.replica.contract.purpose.clear(); 11390 }); 11391 assert_replica_error("crate_family.schema", |bundle| { 11392 bundle.replica.crate_family.schema = "radroots_b".to_string(); 11393 }); 11394 assert_replica_error("must name a workspace package", |bundle| { 11395 bundle.replica.crate_family.schema = "radroots_missing".to_string(); 11396 bundle 11397 .manifest 11398 .surface 11399 .internal_replica_crates 11400 .as_mut() 11401 .expect("replica family") 11402 .schema = "radroots_missing".to_string(); 11403 }); 11404 assert_replica_error("policy.replica is required", |bundle| { 11405 bundle.manifest.policy.replica = None; 11406 }); 11407 assert_replica_error("transport_agnostic_sync_core", |bundle| { 11408 bundle.replica.policy.transport_agnostic_sync_core = false; 11409 }); 11410 assert_replica_error("profile_event_emission must be excluded", |bundle| { 11411 bundle.replica.policy.profile_event_emission = "included".to_string(); 11412 }); 11413 assert_replica_error("unknown_sync_request_fields must be reject", |bundle| { 11414 bundle.replica.policy.unknown_sync_request_fields = "ignore".to_string(); 11415 }); 11416 assert_replica_error( 11417 "classified_listing_signature_verification must be required_before_state", 11418 |bundle| { 11419 bundle 11420 .replica 11421 .policy 11422 .classified_listing_signature_verification = "unchecked".to_string(); 11423 }, 11424 ); 11425 assert_replica_error( 11426 "classified_listing_head_selection must be raw_before_profile", 11427 |bundle| { 11428 bundle.replica.policy.classified_listing_head_selection = 11429 "profile_before_raw".to_string(); 11430 }, 11431 ); 11432 assert_replica_error( 11433 "classified_listing_operational_projection must be operational_partition_only", 11434 |bundle| { 11435 bundle 11436 .replica 11437 .policy 11438 .classified_listing_operational_projection = "all_partitions".to_string(); 11439 }, 11440 ); 11441 assert_replica_error( 11442 "classified_listing_excluded_or_rejected_head must be remove_projection_and_advance", 11443 |bundle| { 11444 bundle 11445 .replica 11446 .policy 11447 .classified_listing_excluded_or_rejected_head = "retain_projection".to_string(); 11448 }, 11449 ); 11450 assert_replica_error( 11451 "classified_listing_head_only_ingest must be reject_require_profile_aware", 11452 |bundle| { 11453 bundle.replica.policy.classified_listing_head_only_ingest = 11454 "allow_head_only".to_string(); 11455 }, 11456 ); 11457 assert_replica_error( 11458 "legacy_bare_envelope_ingest must be explicit_non_default_feature_only", 11459 |bundle| { 11460 bundle.replica.policy.legacy_bare_envelope_ingest = "default".to_string(); 11461 }, 11462 ); 11463 assert_replica_error("legacy_ingest_feature must be legacy-ingest", |bundle| { 11464 bundle.replica.policy.legacy_ingest_feature = "std".to_string(); 11465 }); 11466 assert_replica_error("phase_1_ingest_replacement must be none", |bundle| { 11467 bundle.replica.policy.phase_1_ingest_replacement = "legacy".to_string(); 11468 }); 11469 assert_replica_error( 11470 "future_product_ingest_input must be store_produced_verified_valid_visible_admission", 11471 |bundle| { 11472 bundle.replica.policy.future_product_ingest_input = "bare_envelope".to_string(); 11473 }, 11474 ); 11475 assert_replica_error("transfer.version must be 2", |bundle| { 11476 bundle.replica.transfer.version = 1; 11477 }); 11478 assert_replica_error("transfer.constant", |bundle| { 11479 bundle.replica.transfer.constant = "REPLICA_VERSION".to_string(); 11480 }); 11481 assert_replica_error("transfer.source", |bundle| { 11482 bundle.replica.transfer.source = "crates/a/src/types.rs".to_string(); 11483 }); 11484 11485 let source_path = root.join("crates/b/src/types.rs"); 11486 let source = fs::read_to_string(&source_path).expect("read replica types source"); 11487 write_file( 11488 &source_path, 11489 &source.replace( 11490 "pub const RADROOTS_REPLICA_TRANSFER_VERSION: u32 = 2;", 11491 "pub const RADROOTS_REPLICA_TRANSFER_VERSION: u32 = 1;", 11492 ), 11493 ); 11494 let bundle = load_contract_bundle(&root).expect("load source-drift contract"); 11495 let source_error = validate_replica_contract(&bundle, &root) 11496 .expect_err("source constant version drift must fail"); 11497 assert!(source_error.contains("source constant")); 11498 assert!(source_error.contains("must match contract version 2")); 11499 11500 let _ = fs::remove_dir_all(root); 11501 } 11502 11503 #[test] 11504 fn replica_policy_source_witnesses_reject_runtime_drift() { 11505 let root = create_synthetic_workspace("replica_policy_source_drift"); 11506 let cargo_path = root.join("crates/b/Cargo.toml"); 11507 let lib_path = root.join("crates/b/src/lib.rs"); 11508 let types_path = root.join("crates/b/src/types.rs"); 11509 let emit_path = root.join("crates/b/src/emit.rs"); 11510 let cargo = fs::read_to_string(&cargo_path).expect("read replica cargo manifest"); 11511 let lib = fs::read_to_string(&lib_path).expect("read replica lib source"); 11512 let types = fs::read_to_string(&types_path).expect("read replica types source"); 11513 let emit = fs::read_to_string(&emit_path).expect("read replica emit source"); 11514 11515 write_file( 11516 &cargo_path, 11517 &cargo.replace("std = []", "std = [\"legacy-ingest\"]"), 11518 ); 11519 let bundle = 11520 load_contract_bundle(&root).expect("load transitive default-feature drift contract"); 11521 let default_feature_error = validate_replica_contract(&bundle, &root) 11522 .expect_err("transitively default legacy ingest feature must fail"); 11523 assert!(default_feature_error.contains("must not be enabled by default features")); 11524 11525 write_file(&cargo_path, &cargo); 11526 write_file( 11527 &lib_path, 11528 &format!( 11529 "{}\n/*\n#[cfg(feature = \"legacy-ingest\")]\npub mod ingest;\n*/\n", 11530 lib.replace( 11531 "#[cfg(feature = \"legacy-ingest\")]\npub mod ingest;", 11532 "#[cfg(feature = \"std\")]\npub mod ingest;", 11533 ) 11534 ), 11535 ); 11536 let bundle = load_contract_bundle(&root).expect("load ingest-module drift contract"); 11537 let module_error = validate_replica_contract(&bundle, &root) 11538 .expect_err("comment-only legacy guard witness must fail"); 11539 assert!(module_error.contains("must be guarded by exact")); 11540 11541 write_file( 11542 &lib_path, 11543 &format!("{lib}\npub use ingest::RadrootsReplicaIngestOutcome;\n"), 11544 ); 11545 let bundle = load_contract_bundle(&root).expect("load second-reexport drift contract"); 11546 let reexport_error = validate_replica_contract(&bundle, &root) 11547 .expect_err("ungated second ingest re-export must fail"); 11548 assert!(reexport_error.contains("every public replica ingest re-export")); 11549 11550 write_file( 11551 &lib_path, 11552 &lib.replacen( 11553 "#[cfg(feature = \"legacy-ingest\")]\npub use ingest::{", 11554 "#[cfg(any(feature = \"legacy-ingest\", feature = \"std\"))]\npub use ingest::{", 11555 1, 11556 ), 11557 ); 11558 let bundle = load_contract_bundle(&root).expect("load broadened-reexport contract"); 11559 let broadened_error = validate_replica_contract(&bundle, &root) 11560 .expect_err("broadened ingest re-export guard must fail"); 11561 assert!(broadened_error.contains("every public replica ingest re-export")); 11562 11563 write_file( 11564 &lib_path, 11565 &format!( 11566 "{lib}\npub mod nested {{\n pub use super::ingest::RadrootsReplicaIngestOutcome;\n}}\n" 11567 ), 11568 ); 11569 let bundle = load_contract_bundle(&root).expect("load nested-reexport drift contract"); 11570 let nested_error = validate_replica_contract(&bundle, &root) 11571 .expect_err("ungated nested public ingest re-export must fail"); 11572 assert!(nested_error.contains("every public replica ingest re-export")); 11573 11574 write_file(&lib_path, &lib); 11575 11576 write_file( 11577 &types_path, 11578 &types.replace( 11579 "#[serde(deny_unknown_fields)]\npub struct RadrootsReplicaSyncOptions", 11580 "pub struct RadrootsReplicaSyncOptions", 11581 ), 11582 ); 11583 let bundle = load_contract_bundle(&root).expect("load attribute-drift contract"); 11584 let attribute_error = validate_replica_contract(&bundle, &root) 11585 .expect_err("missing fail-closed request attribute must fail"); 11586 assert!(attribute_error.contains("RadrootsReplicaSyncOptions")); 11587 assert!(attribute_error.contains("immediately before")); 11588 11589 write_file( 11590 &types_path, 11591 &format!("{types}\npub struct include_profiles;\n"), 11592 ); 11593 let bundle = load_contract_bundle(&root).expect("load retired-option contract"); 11594 let retired_error = validate_replica_contract(&bundle, &root) 11595 .expect_err("retired include_profiles identifier must fail"); 11596 assert!(retired_error.contains("include_profiles is forbidden")); 11597 11598 write_file(&types_path, &types); 11599 write_file( 11600 &emit_path, 11601 &emit.replace( 11602 "#[cfg(test)]\nmod tests {}", 11603 "fn emit_profile_event() {}\n\n#[cfg(test)]\nmod tests {}", 11604 ), 11605 ); 11606 let bundle = load_contract_bundle(&root).expect("load profile-emitter contract"); 11607 let profile_error = validate_replica_contract(&bundle, &root) 11608 .expect_err("Profile-related production emitter must fail"); 11609 assert!(profile_error.contains("Profile-related identifier emit_profile_event")); 11610 11611 write_file( 11612 &emit_path, 11613 &emit.replace( 11614 "#[cfg(test)]\nmod tests {}", 11615 "fn emit_kind_zero() { let _event = Event { kind: 0 }; }\n\n#[cfg(test)]\nmod tests {}", 11616 ), 11617 ); 11618 let bundle = load_contract_bundle(&root).expect("load literal-kind-zero contract"); 11619 let kind_error = validate_replica_contract(&bundle, &root) 11620 .expect_err("literal kind-0 production emitter must fail"); 11621 assert!(kind_error.contains("must not construct a literal kind-0 event")); 11622 11623 let _ = fs::remove_dir_all(root); 11624 } 11625 11626 #[test] 11627 fn replica_contract_is_required_and_rejects_unknown_fields() { 11628 let missing_root = create_synthetic_workspace("replica_contract_missing"); 11629 fs::remove_file(missing_root.join(REPLICA_CONTRACT_RELATIVE)) 11630 .expect("remove replica contract"); 11631 let missing_error = load_contract_bundle(&missing_root) 11632 .expect_err("missing replica contract must fail bundle loading"); 11633 assert!(missing_error.contains(REPLICA_CONTRACT_RELATIVE)); 11634 let _ = fs::remove_dir_all(missing_root); 11635 11636 let unknown_root = create_synthetic_workspace("replica_contract_unknown_field"); 11637 let replica_path = unknown_root.join(REPLICA_CONTRACT_RELATIVE); 11638 let replica = fs::read_to_string(&replica_path).expect("read replica contract"); 11639 write_file(&replica_path, &format!("{replica}unexpected = true\n")); 11640 let unknown_error = load_contract_bundle(&unknown_root) 11641 .expect_err("unknown replica contract field must fail bundle loading"); 11642 assert!(unknown_error.contains(REPLICA_CONTRACT_RELATIVE)); 11643 assert!(unknown_error.contains("unexpected")); 11644 let _ = fs::remove_dir_all(unknown_root); 11645 } 11646 11647 #[test] 11648 fn conformance_vector_mirrors_are_required_even_when_parent_is_deleted() { 11649 let root = create_synthetic_workspace("required_conformance_mirrors"); 11650 validate_conformance_vector_mirrors(&root).expect("validate synthetic mirrors"); 11651 11652 let (_, mirror_relative) = CONFORMANCE_VECTOR_MIRRORS[0]; 11653 let mirror_path = root.join(mirror_relative); 11654 fs::remove_file(&mirror_path).expect("remove required mirror"); 11655 let missing_file_error = validate_conformance_vector_mirrors(&root) 11656 .expect_err("missing required mirror file must fail"); 11657 assert!(missing_file_error.contains(&format!("read {mirror_relative}"))); 11658 11659 write_file(&mirror_path, SYNTHETIC_CONFORMANCE_VECTOR); 11660 fs::remove_dir_all(mirror_path.parent().expect("mirror parent")) 11661 .expect("remove required mirror parent"); 11662 let missing_parent_error = validate_conformance_vector_mirrors(&root) 11663 .expect_err("missing required mirror parent must fail"); 11664 assert!(missing_parent_error.contains(&format!("read {mirror_relative}"))); 11665 11666 let _ = fs::remove_dir_all(root); 11667 } 11668 11669 #[test] 11670 fn release_record_and_conformance_mirror_validation_reject_drift() { 11671 let root = create_synthetic_workspace("release_record_drift"); 11672 let bundle = load_contract_bundle(&root).expect("load synthetic contract"); 11673 validate_release_record(&root, "1.0.0", &bundle.version.semver) 11674 .expect("validate release record"); 11675 11676 let record_path = root.join("contracts/releases/1.0.0.toml"); 11677 let record = fs::read_to_string(&record_path).expect("read release record"); 11678 write_file( 11679 &record_path, 11680 &record.replace("status = \"unreleased\"", "status = \"pending\""), 11681 ); 11682 let status_error = validate_release_record(&root, "1.0.0", &bundle.version.semver) 11683 .expect_err("unsupported release status must fail"); 11684 assert!(status_error.contains("must be unreleased, released, or yanked")); 11685 11686 write_file( 11687 &record_path, 11688 &record.replace( 11689 "replica = \"contracts/replica.toml\"", 11690 "replica = \"contracts/replica-v1.toml\"", 11691 ), 11692 ); 11693 let replica_artifact_error = 11694 validate_release_record(&root, "1.0.0", &bundle.version.semver) 11695 .expect_err("noncanonical replica artifact must fail"); 11696 assert!(replica_artifact_error.contains( 11697 "release artifact path contracts/replica-v1.toml must use canonical path contracts/replica.toml" 11698 )); 11699 11700 write_file( 11701 &record_path, 11702 &record.replace( 11703 "operations = \"contracts/operations.toml\"", 11704 "operations = \"contracts/operations-v1.toml\"", 11705 ), 11706 ); 11707 let operations_artifact_error = 11708 validate_release_record(&root, "1.0.0", &bundle.version.semver) 11709 .expect_err("noncanonical operations artifact must fail"); 11710 assert!(operations_artifact_error.contains( 11711 "release artifact path contracts/operations-v1.toml must use canonical path contracts/operations.toml" 11712 )); 11713 11714 write_file(&record_path, &record); 11715 let operations_path = root.join("contracts").join("operations.toml"); 11716 let operations = fs::read_to_string(&operations_path).expect("read operations manifest"); 11717 fs::remove_file(&operations_path).expect("remove operations manifest"); 11718 let missing_operations_error = 11719 validate_release_record(&root, "1.0.0", &bundle.version.semver) 11720 .expect_err("missing operations artifact must fail"); 11721 assert!( 11722 missing_operations_error 11723 .contains("release artifact contracts/operations.toml does not exist") 11724 ); 11725 write_file(&operations_path, &operations); 11726 11727 write_file( 11728 &record_path, 11729 &record.replace("id = \"synthetic-major-release\"", "id = \"Bad_Id\""), 11730 ); 11731 let id_error = validate_release_record(&root, "1.0.0", &bundle.version.semver) 11732 .expect_err("invalid release change id must fail"); 11733 assert!(id_error.contains("lowercase kebab-case")); 11734 write_file(&record_path, &record); 11735 11736 write_file( 11737 &record_path, 11738 &record.replace( 11739 "semver_impacts = [\"breaking\"]", 11740 "semver_impacts = [\"fix\"]", 11741 ), 11742 ); 11743 let classification_error = validate_release_record(&root, "1.0.0", &bundle.version.semver) 11744 .expect_err("classification and semver impact mismatch must fail"); 11745 assert!(classification_error.contains("does not match its governed semver impacts")); 11746 11747 write_file( 11748 &record_path, 11749 &record.replace( 11750 "semver_impacts = [\"breaking\"]", 11751 "semver_impacts = [\"unknown-impact\"]", 11752 ), 11753 ); 11754 let impact_error = validate_release_record(&root, "1.0.0", &bundle.version.semver) 11755 .expect_err("unknown semver impact must fail"); 11756 assert!(impact_error.contains("is not governed by contracts/version.toml")); 11757 write_file(&record_path, &record); 11758 11759 write_file(&root.join(CHANGELOG_RELATIVE), "# Changelog\n"); 11760 let notes_error = validate_release_record(&root, "1.0.0", &bundle.version.semver) 11761 .expect_err("missing release notes must fail"); 11762 assert!(notes_error.contains("missing heading")); 11763 11764 let (canonical_relative, mirror_relative) = CONFORMANCE_VECTOR_MIRRORS[0]; 11765 write_file(&root.join(canonical_relative), "canonical\n"); 11766 write_file(&root.join(mirror_relative), "drifted\n"); 11767 let mirror_error = validate_conformance_vector_mirrors(&root) 11768 .expect_err("packaged conformance drift must fail"); 11769 assert!(mirror_error.contains("must exactly match")); 11770 11771 let _ = fs::remove_dir_all(root); 11772 } 11773 11774 #[test] 11775 fn calendar_operation_authority_reports_exact_signature_drift() { 11776 let root = workspace_root(); 11777 let mut bundle = load_contract_bundle(&root).expect("load contract"); 11778 let manifest = &mut bundle.operations_manifest; 11779 let shared_types = 11780 collect_non_empty_set(&manifest.shared_types.public, "shared_types.public") 11781 .expect("shared public types"); 11782 manifest 11783 .operations 11784 .get_mut("social_calendar_date_event_build_authored_draft") 11785 .expect("calendar authored operation") 11786 .outputs = vec!["NostrTags".to_string()]; 11787 11788 let error = validate_calendar_operation_authority(manifest, &shared_types) 11789 .expect_err("calendar operation signature drift"); 11790 assert!(error.contains("outputs drift")); 11791 } 11792 11793 #[test] 11794 fn calendar_operation_authority_reports_obsolete_operation_drift() { 11795 let root = workspace_root(); 11796 let mut bundle = load_contract_bundle(&root).expect("load contract"); 11797 let manifest = &mut bundle.operations_manifest; 11798 let shared_types = 11799 collect_non_empty_set(&manifest.shared_types.public, "shared_types.public") 11800 .expect("shared public types"); 11801 let obsolete = manifest 11802 .operations 11803 .remove("social_calendar_date_event_build_authored_draft") 11804 .expect("calendar authored operation"); 11805 manifest.operations.insert( 11806 "social_calendar_date_event_build_tags".to_string(), 11807 obsolete, 11808 ); 11809 11810 let error = validate_calendar_operation_authority(manifest, &shared_types) 11811 .expect_err("obsolete calendar operation drift"); 11812 assert!(error.contains("calendar operation authority drift")); 11813 assert!(error.contains("social_calendar_date_event_build_tags")); 11814 } 11815 11816 #[test] 11817 fn calendar_operation_authority_reports_obsolete_rsvp_operation_drift() { 11818 let root = workspace_root(); 11819 let mut bundle = load_contract_bundle(&root).expect("load contract"); 11820 let manifest = &mut bundle.operations_manifest; 11821 let shared_types = 11822 collect_non_empty_set(&manifest.shared_types.public, "shared_types.public") 11823 .expect("shared public types"); 11824 let obsolete = manifest 11825 .operations 11826 .remove("social_calendar_rsvp_build_authored_draft") 11827 .expect("calendar RSVP authored operation"); 11828 manifest 11829 .operations 11830 .insert("social_calendar_rsvp_build_tags".to_string(), obsolete); 11831 11832 let error = validate_calendar_operation_authority(manifest, &shared_types) 11833 .expect_err("obsolete calendar RSVP operation drift"); 11834 assert!(error.contains("calendar operation authority drift")); 11835 assert!(error.contains("social_calendar_rsvp_build_tags")); 11836 } 11837 11838 #[test] 11839 fn validate_current_canonical_event_boundary() { 11840 let root = workspace_root(); 11841 validate_canonical_event_boundary(&root).expect("validate canonical event boundary"); 11842 } 11843 11844 #[test] 11845 fn canonical_event_boundary_reports_row_drift() { 11846 let root = workspace_root(); 11847 let matrix_path = resolve_event_boundary_matrix_path(&root).expect("matrix path"); 11848 let raw = fs::read_to_string(&matrix_path).expect("read matrix"); 11849 let drifted = raw.replacen( 11850 "| message | 14 | Message |", 11851 "| message | 999 | Message |", 11852 1, 11853 ); 11854 let temp = temp_root("event_boundary_drift"); 11855 let override_path = temp.join("spec-coverage.md"); 11856 write_file(&override_path, &drifted); 11857 11858 let err = validate_canonical_event_boundary_at_path(&root, &override_path) 11859 .expect_err("message kind drift should fail"); 11860 assert!(err.contains("message kind drift")); 11861 11862 let _ = fs::remove_dir_all(temp); 11863 } 11864 11865 #[test] 11866 fn canonical_event_boundary_rejects_deletion_operation_drift() { 11867 let root = workspace_root(); 11868 let matrix_path = resolve_event_boundary_matrix_path(&root).expect("matrix path"); 11869 let raw = fs::read_to_string(&matrix_path).expect("read matrix"); 11870 let (preamble, table) = raw 11871 .split_once("## Coverage matrix") 11872 .expect("coverage matrix marker"); 11873 let drifted = format!( 11874 "{preamble}## Coverage matrix{}", 11875 table.replacen( 11876 "social.deletion_request.project_verified_event", 11877 "social.deletion_request.project_unverified_event", 11878 1, 11879 ) 11880 ); 11881 let temp = temp_root("deletion_event_boundary_drift"); 11882 let override_path = temp.join("spec-coverage.md"); 11883 write_file(&override_path, &drifted); 11884 11885 let error = validate_canonical_event_boundary_at_path(&root, &override_path) 11886 .expect_err("deletion operation drift must fail"); 11887 assert!(error.contains("deletion_request rpc drift"), "{error}"); 11888 11889 let _ = fs::remove_dir_all(temp); 11890 } 11891 11892 #[test] 11893 fn event_boundary_never_falls_back_to_parent_human_documentation() { 11894 let parent = temp_root("event_boundary_parent_docs"); 11895 let capsule = parent.join("oss/lib"); 11896 fs::create_dir_all(&capsule).expect("capsule root"); 11897 let parent_doc = parent.join( 11898 "docs/platform/canonical/open_source/radroots_v1_spec/02_public_contract_and_runtime/08_event_boundary_matrix.md", 11899 ); 11900 write_file(&parent_doc, &synthetic_event_boundary_matrix()); 11901 11902 let error = resolve_event_boundary_matrix_path(&capsule) 11903 .expect_err("parent human documentation must not become contract input"); 11904 assert!(error.contains(EVENT_BOUNDARY_MATRIX_RELATIVE)); 11905 let _ = fs::remove_dir_all(parent); 11906 } 11907 11908 #[test] 11909 fn validate_synthetic_operation_contract_bundle() { 11910 let root = create_synthetic_workspace("operation_contract_bundle"); 11911 add_operation_contract_files(&root); 11912 let bundle = load_contract_bundle(&root).expect("load contract"); 11913 validate_generic_contract_bundle(&bundle).expect("validate contract"); 11914 let _ = fs::remove_dir_all(root); 11915 } 11916 11917 #[test] 11918 fn parses_enum_variants_in_declared_order() { 11919 let source = r#" 11920 pub enum UnitDimension { 11921 Count, 11922 Mass, 11923 Volume, 11924 } 11925 "#; 11926 let enum_body = extract_enum_body(source, "UnitDimension").expect("enum body"); 11927 let variants = parse_enum_variants(enum_body); 11928 assert_eq!(variants, vec!["Count", "Mass", "Volume"]); 11929 } 11930 11931 #[test] 11932 fn fails_when_enum_order_does_not_match_contract() { 11933 let source = r#" 11934 pub enum UnitDimension { 11935 Mass, 11936 Count, 11937 Volume, 11938 } 11939 "#; 11940 let enum_body = extract_enum_body(source, "UnitDimension").expect("enum body"); 11941 let variants = parse_enum_variants(enum_body); 11942 let expected = CORE_UNIT_DIMENSION_ORDER 11943 .iter() 11944 .map(|item| (*item).to_string()) 11945 .collect::<Vec<_>>(); 11946 assert_ne!(variants, expected); 11947 } 11948 11949 #[test] 11950 fn coverage_policy_matches_non_simplex_workspace_crates() { 11951 let root = workspace_root(); 11952 let expected_names = 11953 coverage_required_workspace_crates(&root).expect("workspace coverage crates"); 11954 let policy = load_coverage_policy(&root.join("contracts")).expect("coverage policy"); 11955 let required_names = policy 11956 .required_crates() 11957 .expect("required crates") 11958 .into_iter() 11959 .collect::<BTreeSet<_>>(); 11960 assert_eq!(expected_names, required_names); 11961 assert!( 11962 required_names 11963 .iter() 11964 .all(|crate_name| !coverage_policy_excludes_workspace_crate(crate_name)) 11965 ); 11966 } 11967 11968 #[test] 11969 fn coverage_required_workspace_crates_excludes_non_policy_packages() { 11970 let root = temp_root("coverage_required_workspace_simplex"); 11971 write_file( 11972 &root.join("Cargo.toml"), 11973 r#"[workspace] 11974 members = ["crates/a", "crates/radroots_simplex_probe", "crates/simplex_probe"] 11975 resolver = "2" 11976 "#, 11977 ); 11978 write_file( 11979 &root.join("crates").join("a").join("Cargo.toml"), 11980 r#"[package] 11981 name = "radroots_a" 11982 version = "1.0.0" 11983 edition = "2024" 11984 "#, 11985 ); 11986 write_file( 11987 &root 11988 .join("crates") 11989 .join("radroots_simplex_probe") 11990 .join("Cargo.toml"), 11991 r#"[package] 11992 name = "radroots_simplex_probe" 11993 version = "1.0.0" 11994 edition = "2024" 11995 "#, 11996 ); 11997 write_file( 11998 &root.join("crates").join("simplex_probe").join("Cargo.toml"), 11999 r#"[package] 12000 name = "simplex_probe" 12001 version = "1.0.0" 12002 edition = "2024" 12003 "#, 12004 ); 12005 12006 let required = 12007 coverage_required_workspace_crates(&root).expect("workspace coverage crates"); 12008 assert_eq!( 12009 required, 12010 ["radroots_a".to_string()] 12011 .into_iter() 12012 .collect::<BTreeSet<_>>() 12013 ); 12014 assert!(coverage_policy_excludes_workspace_crate( 12015 "radroots_simplex_probe" 12016 )); 12017 assert!(coverage_policy_excludes_workspace_crate("simplex_probe")); 12018 assert!(!coverage_policy_excludes_workspace_crate("radroots_a")); 12019 12020 let _ = fs::remove_dir_all(root); 12021 } 12022 12023 #[test] 12024 fn coverage_required_crates_match_policy_required_status() { 12025 let root = workspace_root(); 12026 let contract_root = root.join("contracts"); 12027 let policy = load_coverage_policy(&contract_root).expect("coverage policy"); 12028 let required = CoverageRequiredFile { 12029 required: CoverageRequiredSection { 12030 crates: policy.required_crates().expect("coverage required"), 12031 }, 12032 }; 12033 let required_names = required 12034 .required 12035 .crates 12036 .into_iter() 12037 .collect::<BTreeSet<_>>(); 12038 let policy_required = policy 12039 .required_crates() 12040 .expect("policy required crates") 12041 .into_iter() 12042 .collect::<BTreeSet<_>>(); 12043 assert_eq!(required_names, policy_required); 12044 } 12045 12046 #[test] 12047 fn coverage_policy_required_crates_report_policy_errors() { 12048 let missing_root = temp_root("load_coverage_required_missing_policy"); 12049 let missing_err = 12050 load_coverage_policy(&missing_root).expect_err("missing policy should fail"); 12051 assert!(missing_err.contains("coverage.toml")); 12052 let _ = fs::remove_dir_all(&missing_root); 12053 12054 let duplicate_root = 12055 create_synthetic_workspace("load_coverage_required_duplicate_required"); 12056 let contract_root = duplicate_root.join("contracts"); 12057 let coverage_root = coverage_root(&contract_root); 12058 write_file( 12059 &coverage_root.join("coverage.toml"), 12060 "[gate]\nfail_under_exec_lines = 100.0\nfail_under_functions = 100.0\nfail_under_regions = 100.0\nfail_under_branches = 100.0\nrequire_branches = true\n\n[required]\ncrates = [\"radroots_a\", \"radroots_a\"]\n", 12061 ); 12062 let duplicate_err = 12063 load_coverage_policy(&contract_root).expect_err("duplicate required crates"); 12064 assert!(duplicate_err.contains("duplicate crate")); 12065 let _ = fs::remove_dir_all(&duplicate_root); 12066 } 12067 12068 #[test] 12069 fn package_field_configured_accepts_workspace_table() { 12070 let mut package = toml::value::Table::new(); 12071 let mut repository = toml::value::Table::new(); 12072 repository.insert("workspace".to_string(), toml::Value::Boolean(true)); 12073 package.insert("repository".to_string(), toml::Value::Table(repository)); 12074 assert!(package_field_configured(&package, "repository")); 12075 } 12076 12077 #[test] 12078 fn validate_required_coverage_summary_enforces_required_threshold() { 12079 let root = temp_root("coverage_summary"); 12080 let coverage_dir = root.join("target").join("coverage"); 12081 fs::create_dir_all(&coverage_dir).expect("create coverage dir"); 12082 fs::write( 12083 coverage_dir.join("coverage-refresh.tsv"), 12084 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_core\tpass\t90.0\t90.0\t90.0\t90.0\tfile\n", 12085 ) 12086 .expect("write coverage file"); 12087 let required = ["radroots_core".to_string()] 12088 .into_iter() 12089 .collect::<BTreeSet<_>>(); 12090 validate_required_coverage_summary(&root, &required, required_thresholds()) 12091 .expect("coverage summary"); 12092 12093 fs::write( 12094 coverage_dir.join("coverage-refresh.tsv"), 12095 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_core\tpass\t90.0\t89.9\t90.0\t90.0\tfile\n", 12096 ) 12097 .expect("write function coverage file"); 12098 let func_err = validate_required_coverage_summary(&root, &required, required_thresholds()) 12099 .expect_err("function coverage below 90"); 12100 assert!(func_err.contains("must satisfy coverage policy")); 12101 12102 fs::write( 12103 coverage_dir.join("coverage-refresh.tsv"), 12104 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_core\tpass\t90.0\t90.0\t89.9\t90.0\tfile\n", 12105 ) 12106 .expect("write branch coverage file"); 12107 let branch_err = 12108 validate_required_coverage_summary(&root, &required, required_thresholds()) 12109 .expect_err("branch coverage below 90"); 12110 assert!(branch_err.contains("must satisfy coverage policy")); 12111 12112 fs::write( 12113 coverage_dir.join("coverage-refresh.tsv"), 12114 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_core\tpass\t90.0\t90.0\tunavailable\t90.0\tfile\n", 12115 ) 12116 .expect("write unavailable branch coverage file"); 12117 let missing_branch_err = 12118 validate_required_coverage_summary(&root, &required, required_thresholds()) 12119 .expect_err("branch coverage missing under strict policy"); 12120 assert!(missing_branch_err.contains("unavailable")); 12121 12122 fs::write( 12123 coverage_dir.join("coverage-refresh.tsv"), 12124 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_core\tpass\t90.0\t90.0\t90.0\t89.9\tfile\n", 12125 ) 12126 .expect("write region coverage file"); 12127 let region_err = 12128 validate_required_coverage_summary(&root, &required, required_thresholds()) 12129 .expect_err("region coverage below 90"); 12130 assert!(region_err.contains("must satisfy coverage policy")); 12131 let _ = fs::remove_dir_all(&root); 12132 } 12133 12134 #[test] 12135 fn validate_required_coverage_summary_with_policy_honors_scope_override() { 12136 let root = temp_root("coverage_summary_override"); 12137 write_test_coverage_refresh( 12138 &root, 12139 &[ 12140 TestCoverageRefreshRow { 12141 crate_name: "radroots_event_codec", 12142 status: "pass", 12143 thresholds: CoverageThresholds { 12144 fail_under_exec_lines: 100.0, 12145 fail_under_functions: 100.0, 12146 fail_under_regions: 99.946, 12147 fail_under_branches: 100.0, 12148 require_branches: true, 12149 }, 12150 exec: 100.0, 12151 func: 100.0, 12152 branch: Some(100.0), 12153 region: 99.946385, 12154 report_pass: true, 12155 }, 12156 TestCoverageRefreshRow { 12157 crate_name: "radroots_log", 12158 status: "pass", 12159 thresholds: coverage_thresholds(100.0, false), 12160 exec: 100.0, 12161 func: 100.0, 12162 branch: None, 12163 region: 100.0, 12164 report_pass: true, 12165 }, 12166 ], 12167 ); 12168 let policy_dir = root.join("contracts"); 12169 fs::create_dir_all(&policy_dir).expect("create policy dir"); 12170 fs::write( 12171 policy_dir.join("coverage.toml"), 12172 "[gate]\nfail_under_exec_lines = 100.0\nfail_under_functions = 100.0\nfail_under_regions = 100.0\nfail_under_branches = 100.0\nrequire_branches = true\n\n[overrides.radroots_event_codec]\nfail_under_exec_lines = 100.0\nfail_under_functions = 100.0\nfail_under_regions = 99.946\nfail_under_branches = 100.0\ntemporary = true\nreason = \"publish 0.1.0-alpha temporary coverage override\"\n\n[overrides.radroots_log]\nfail_under_exec_lines = 100.0\nfail_under_functions = 100.0\nfail_under_regions = 100.0\nfail_under_branches = 100.0\nrequire_branches = false\ntemporary = true\nreason = \"branch coverage is not applicable while the crate has no measured branch records\"\n\n[required]\ncrates = [\"radroots_event_codec\", \"radroots_log\"]\n", 12173 ) 12174 .expect("write coverage policy"); 12175 let required = [ 12176 "radroots_event_codec".to_string(), 12177 "radroots_log".to_string(), 12178 ] 12179 .into_iter() 12180 .collect::<BTreeSet<_>>(); 12181 let policy = read_coverage_policy(&policy_dir.join("coverage.toml")) 12182 .expect("parse override coverage policy"); 12183 validate_required_coverage_summary_with_policy(&root, &required, &policy) 12184 .expect("coverage summary should honor override"); 12185 let _ = fs::remove_dir_all(&root); 12186 } 12187 12188 #[test] 12189 fn validate_required_coverage_summary_with_policy_rejects_synthetic_report_path() { 12190 let root = temp_root("coverage_summary_synthetic_report_path"); 12191 write_file( 12192 &root 12193 .join("target") 12194 .join("coverage") 12195 .join("coverage-refresh.tsv"), 12196 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_a\tpass\t100.0\t100.0\t100.0\t100.0\tfile\n", 12197 ); 12198 let required = ["radroots_a".to_string()] 12199 .into_iter() 12200 .collect::<BTreeSet<_>>(); 12201 let policy_dir = root.join("contracts"); 12202 write_file( 12203 &policy_dir.join("coverage.toml"), 12204 "[gate]\nfail_under_exec_lines = 100.0\nfail_under_functions = 100.0\nfail_under_regions = 100.0\nfail_under_branches = 100.0\nrequire_branches = true\n\n[required]\ncrates = [\"radroots_a\"]\n", 12205 ); 12206 let policy = 12207 read_coverage_policy(&policy_dir.join("coverage.toml")).expect("parse coverage policy"); 12208 let err = validate_required_coverage_summary_with_policy(&root, &required, &policy) 12209 .expect_err("synthetic report path should fail"); 12210 assert!(err.contains("coverage gate report")); 12211 let _ = fs::remove_dir_all(&root); 12212 } 12213 12214 #[test] 12215 fn validate_required_coverage_summary_with_policy_rejects_stale_gate_report_thresholds() { 12216 let root = temp_root("coverage_summary_stale_gate_report_thresholds"); 12217 let row = TestCoverageRefreshRow { 12218 crate_name: "radroots_a", 12219 status: "pass", 12220 thresholds: coverage_thresholds(90.0, true), 12221 exec: 100.0, 12222 func: 100.0, 12223 branch: Some(100.0), 12224 region: 100.0, 12225 report_pass: true, 12226 }; 12227 write_test_coverage_refresh(&root, &[row]); 12228 let required = ["radroots_a".to_string()] 12229 .into_iter() 12230 .collect::<BTreeSet<_>>(); 12231 let policy_dir = root.join("contracts"); 12232 write_file( 12233 &policy_dir.join("coverage.toml"), 12234 "[gate]\nfail_under_exec_lines = 100.0\nfail_under_functions = 100.0\nfail_under_regions = 100.0\nfail_under_branches = 100.0\nrequire_branches = true\n\n[required]\ncrates = [\"radroots_a\"]\n", 12235 ); 12236 let policy = 12237 read_coverage_policy(&policy_dir.join("coverage.toml")).expect("parse coverage policy"); 12238 let err = validate_required_coverage_summary_with_policy(&root, &required, &policy) 12239 .expect_err("stale threshold report should fail"); 12240 assert!(err.contains("thresholds do not match policy")); 12241 let _ = fs::remove_dir_all(&root); 12242 } 12243 12244 #[test] 12245 fn validate_required_coverage_summary_with_policy_rejects_row_report_mismatch() { 12246 let root = temp_root("coverage_summary_row_report_mismatch"); 12247 let row = TestCoverageRefreshRow { 12248 crate_name: "radroots_a", 12249 status: "pass", 12250 thresholds: coverage_thresholds(100.0, true), 12251 exec: 99.0, 12252 func: 100.0, 12253 branch: Some(100.0), 12254 region: 100.0, 12255 report_pass: true, 12256 }; 12257 let report_relative = write_test_coverage_gate_report(&root, &row); 12258 write_file( 12259 &root 12260 .join("target") 12261 .join("coverage") 12262 .join("coverage-refresh.tsv"), 12263 &format!( 12264 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_a\tpass\t100.0\t100.0\t100.0\t100.0\t{report_relative}\n" 12265 ), 12266 ); 12267 let required = ["radroots_a".to_string()] 12268 .into_iter() 12269 .collect::<BTreeSet<_>>(); 12270 let policy_dir = root.join("contracts"); 12271 write_file( 12272 &policy_dir.join("coverage.toml"), 12273 "[gate]\nfail_under_exec_lines = 100.0\nfail_under_functions = 100.0\nfail_under_regions = 100.0\nfail_under_branches = 100.0\nrequire_branches = true\n\n[required]\ncrates = [\"radroots_a\"]\n", 12274 ); 12275 let policy = 12276 read_coverage_policy(&policy_dir.join("coverage.toml")).expect("parse coverage policy"); 12277 let err = validate_required_coverage_summary_with_policy(&root, &required, &policy) 12278 .expect_err("row and report mismatch should fail"); 12279 assert!(err.contains("does not match coverage gate report")); 12280 let _ = fs::remove_dir_all(&root); 12281 } 12282 12283 #[test] 12284 fn validate_publish_package_metadata_requires_description() { 12285 let root = temp_root("publish_metadata"); 12286 fs::create_dir_all(root.join("crates").join("a")).expect("create crate dir"); 12287 fs::write( 12288 root.join("Cargo.toml"), 12289 r#"[workspace] 12290 members = ["crates/a"] 12291 "#, 12292 ) 12293 .expect("write workspace manifest"); 12294 fs::write( 12295 root.join("crates").join("a").join("Cargo.toml"), 12296 r#"[package] 12297 name = "radroots_a" 12298 version = "1.0.0" 12299 edition = "2024" 12300 repository = { workspace = true } 12301 homepage = { workspace = true } 12302 documentation = "https://docs.rs/radroots_a" 12303 readme = { workspace = true } 12304 "#, 12305 ) 12306 .expect("write package manifest"); 12307 let publish = ["radroots_a".to_string()] 12308 .into_iter() 12309 .collect::<BTreeSet<_>>(); 12310 let err = 12311 validate_publish_package_metadata(&root, &publish).expect_err("missing description"); 12312 assert!(err.contains("package.description")); 12313 let _ = fs::remove_dir_all(&root); 12314 } 12315 12316 #[test] 12317 fn synthetic_workspace_validates_contract_and_release_preflight() { 12318 let root = create_synthetic_workspace("synthetic_valid"); 12319 let bundle = load_contract_bundle(&root).expect("load synthetic bundle"); 12320 validate_generic_contract_bundle(&bundle).expect("validate synthetic bundle"); 12321 validate_generic_release_preflight(&root).expect("validate synthetic preflight"); 12322 let _ = fs::remove_dir_all(root); 12323 } 12324 12325 #[test] 12326 fn helper_functions_cover_error_paths() { 12327 let empty = collect_unique_set(&["".to_string()], "field").expect_err("empty value"); 12328 assert!(empty.contains("field contains an empty crate name")); 12329 let duplicate = collect_unique_set(&["a".to_string(), "a".to_string()], "field") 12330 .expect_err("duplicate value"); 12331 assert!(duplicate.contains("field has duplicate crate a")); 12332 12333 let values = ["b".to_string(), "a".to_string()]; 12334 let set = collect_unique_set(&values, "field").expect("unique values"); 12335 assert_eq!(join_set(&set), "a, b".to_string()); 12336 12337 assert!(package_publish_enabled(None)); 12338 assert!(package_publish_enabled(Some(&PackagePublish::Bool(true)))); 12339 assert!(!package_publish_enabled(Some(&PackagePublish::Bool(false)))); 12340 assert!(package_publish_enabled(Some(&PackagePublish::Registries( 12341 vec!["crates-io".to_string(),] 12342 )))); 12343 assert!(!package_publish_enabled(Some(&PackagePublish::Registries( 12344 Vec::new() 12345 )))); 12346 12347 let mut package = toml::value::Table::new(); 12348 package.insert("description".to_string(), toml::Value::Integer(42)); 12349 assert!(!package_field_configured(&package, "description")); 12350 12351 assert!(!publish_config_is_public(None)); 12352 assert!(!publish_config_is_public(Some(&PackagePublish::Bool(true)))); 12353 assert!(publish_config_is_public(Some(&PackagePublish::Registries( 12354 vec!["crates-io".to_string(),] 12355 )))); 12356 assert!(!publish_config_is_public(Some( 12357 &PackagePublish::Registries(vec!["crates-io".to_string(), "mirror".to_string(),]) 12358 ))); 12359 assert!(!publish_config_is_public(Some( 12360 &PackagePublish::Registries(vec!["mirror".to_string(),]) 12361 ))); 12362 12363 assert!(!publish_config_is_non_public(None)); 12364 assert!(!publish_config_is_non_public(Some(&PackagePublish::Bool( 12365 true 12366 )))); 12367 assert!(publish_config_is_non_public(Some(&PackagePublish::Bool( 12368 false 12369 )))); 12370 assert!(!publish_config_is_non_public(Some( 12371 &PackagePublish::Registries(vec!["crates-io".to_string(),]) 12372 ))); 12373 } 12374 12375 #[test] 12376 fn release_contract_helpers_cover_classification_and_env_override_paths() { 12377 let release = ReleaseSection { 12378 version: "1.0.0".to_string(), 12379 }; 12380 let empty_order = ReleaseCrateSet { crates: Vec::new() }; 12381 12382 let legacy = ReleaseContractFile { 12383 release: ReleaseSection { 12384 version: release.version.clone(), 12385 }, 12386 publication: None, 12387 workspace_classification: None, 12388 classification: ReleaseClassification::default(), 12389 publish: Some(ReleaseCrateSet { 12390 crates: vec!["radroots_public".to_string()], 12391 }), 12392 internal: Some(ReleaseCrateSet { 12393 crates: vec!["radroots_internal".to_string()], 12394 }), 12395 publish_order: ReleaseCrateSet { 12396 crates: empty_order.crates.clone(), 12397 }, 12398 }; 12399 assert!(!legacy.uses_classification()); 12400 assert_eq!(legacy.public_crates(), vec!["radroots_public".to_string()]); 12401 assert_eq!( 12402 legacy.internal_crates(), 12403 vec!["radroots_internal".to_string()] 12404 ); 12405 12406 let empty_legacy = ReleaseContractFile { 12407 release: ReleaseSection { 12408 version: release.version.clone(), 12409 }, 12410 publication: None, 12411 workspace_classification: None, 12412 classification: ReleaseClassification::default(), 12413 publish: None, 12414 internal: None, 12415 publish_order: ReleaseCrateSet { 12416 crates: empty_order.crates.clone(), 12417 }, 12418 }; 12419 assert!(!empty_legacy.uses_classification()); 12420 assert_eq!(empty_legacy.public_crates(), Vec::<String>::new()); 12421 assert_eq!(empty_legacy.internal_crates(), Vec::<String>::new()); 12422 12423 let internal = ReleaseContractFile { 12424 release: ReleaseSection { 12425 version: release.version.clone(), 12426 }, 12427 publication: None, 12428 workspace_classification: None, 12429 classification: ReleaseClassification { 12430 internal: vec!["radroots_internal_only".to_string()], 12431 ..ReleaseClassification::default() 12432 }, 12433 publish: None, 12434 internal: None, 12435 publish_order: ReleaseCrateSet { 12436 crates: empty_order.crates.clone(), 12437 }, 12438 }; 12439 assert!(internal.uses_classification()); 12440 12441 let deferred = ReleaseContractFile { 12442 release: ReleaseSection { 12443 version: release.version.clone(), 12444 }, 12445 publication: None, 12446 workspace_classification: None, 12447 classification: ReleaseClassification { 12448 deferred: vec!["radroots_deferred".to_string()], 12449 ..ReleaseClassification::default() 12450 }, 12451 publish: None, 12452 internal: None, 12453 publish_order: ReleaseCrateSet { 12454 crates: empty_order.crates.clone(), 12455 }, 12456 }; 12457 assert!(deferred.uses_classification()); 12458 assert_eq!( 12459 deferred.deferred_crates(), 12460 vec!["radroots_deferred".to_string()] 12461 ); 12462 12463 let retired = ReleaseContractFile { 12464 release: ReleaseSection { 12465 version: release.version.clone(), 12466 }, 12467 publication: None, 12468 workspace_classification: None, 12469 classification: ReleaseClassification { 12470 retired: vec!["radroots_retired".to_string()], 12471 ..ReleaseClassification::default() 12472 }, 12473 publish: None, 12474 internal: None, 12475 publish_order: ReleaseCrateSet { 12476 crates: empty_order.crates.clone(), 12477 }, 12478 }; 12479 assert!(retired.uses_classification()); 12480 assert_eq!( 12481 retired.retired_crates(), 12482 vec!["radroots_retired".to_string()] 12483 ); 12484 12485 let yank_only = ReleaseContractFile { 12486 release, 12487 publication: None, 12488 workspace_classification: None, 12489 classification: ReleaseClassification { 12490 yank_only: vec!["radroots_yank_only".to_string()], 12491 ..ReleaseClassification::default() 12492 }, 12493 publish: None, 12494 internal: None, 12495 publish_order: empty_order, 12496 }; 12497 assert!(yank_only.uses_classification()); 12498 assert_eq!( 12499 yank_only.yank_only_crates(), 12500 vec!["radroots_yank_only".to_string()] 12501 ); 12502 12503 let root = create_synthetic_workspace("release_contract_env_override"); 12504 let policy_path = root_release_policy_path(&root); 12505 let resolved = 12506 resolve_release_contract_path_with_override(&root, "1.0.0", Some(policy_path.clone())) 12507 .expect("existing override policy should resolve"); 12508 assert_eq!(resolved, policy_path); 12509 12510 let missing_policy = root.join("missing-release-policy.toml"); 12511 let err = resolve_release_contract_path_with_override( 12512 &root, 12513 "1.0.0", 12514 Some(missing_policy.clone()), 12515 ) 12516 .expect_err("missing fixture policy should fail"); 12517 assert!(err.contains("release policy override points to a missing file")); 12518 assert!(err.contains(&missing_policy.display().to_string())); 12519 12520 let _ = fs::remove_dir_all(&root); 12521 } 12522 12523 #[test] 12524 fn workspace_package_manifests_reject_duplicate_package_names() { 12525 let root = temp_root("workspace_manifest_duplicates"); 12526 write_file( 12527 &root.join("Cargo.toml"), 12528 r#"[workspace] 12529 members = ["crates/a", "crates/b"] 12530 "#, 12531 ); 12532 let package_manifest = 12533 "[package]\nname = \"duplicate\"\nversion = \"0.1.0\"\nedition = \"2024\"\n"; 12534 write_file( 12535 &root.join("crates").join("a").join("Cargo.toml"), 12536 package_manifest, 12537 ); 12538 write_file( 12539 &root.join("crates").join("b").join("Cargo.toml"), 12540 package_manifest, 12541 ); 12542 let err = workspace_package_manifests(&root) 12543 .expect_err("duplicate package names in manifest map"); 12544 assert!(err.contains("duplicate workspace package name in manifest map")); 12545 let _ = fs::remove_dir_all(root); 12546 } 12547 12548 #[test] 12549 fn coverage_refresh_parsing_and_summary_errors_are_reported() { 12550 let root = temp_root("coverage_refresh_errors"); 12551 let coverage_dir = root.join("target").join("coverage"); 12552 fs::create_dir_all(&coverage_dir).expect("create coverage dir"); 12553 12554 write_file( 12555 &coverage_dir.join("coverage-refresh.tsv"), 12556 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nbad-row\n", 12557 ); 12558 let bad_row = load_coverage_refresh_rows(&root).expect_err("invalid coverage row"); 12559 assert!(bad_row.contains("at least 7 columns")); 12560 12561 write_file( 12562 &coverage_dir.join("coverage-refresh.tsv"), 12563 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_a\tpass\tnot-a-number\t100\t100\t100\tfile\n", 12564 ); 12565 let bad_percent = load_coverage_refresh_rows(&root).expect_err("invalid coverage percent"); 12566 assert!(bad_percent.contains("parse exec")); 12567 12568 write_file( 12569 &coverage_dir.join("coverage-refresh.tsv"), 12570 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_a\tpass\t100\t100\t100\tnot-a-number\tfile\n", 12571 ); 12572 let bad_region = 12573 load_coverage_refresh_rows(&root).expect_err("invalid region coverage percent"); 12574 assert!(bad_region.contains("parse region")); 12575 12576 write_file( 12577 &coverage_dir.join("coverage-refresh.tsv"), 12578 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_a\tpass\t100\t100\t100\t100\tfile\nradroots_a\tpass\t100\t100\t100\t100\tfile\n", 12579 ); 12580 let duplicate_row = load_coverage_refresh_rows(&root).expect_err("duplicate coverage row"); 12581 assert!(duplicate_row.contains("duplicate coverage row")); 12582 12583 write_file( 12584 &coverage_dir.join("coverage-refresh.tsv"), 12585 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_a\tfail\t100\t100\t100\t100\tfile\n", 12586 ); 12587 let required = ["radroots_a".to_string()] 12588 .into_iter() 12589 .collect::<BTreeSet<_>>(); 12590 let non_pass = validate_required_coverage_summary(&root, &required, required_thresholds()) 12591 .expect_err("non-pass status"); 12592 assert!(non_pass.contains("non-pass status")); 12593 12594 write_file( 12595 &coverage_dir.join("coverage-refresh.tsv"), 12596 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_a\tpass\t89.9\t90\t90\t90\tfile\n", 12597 ); 12598 let below_90 = validate_required_coverage_summary(&root, &required, required_thresholds()) 12599 .expect_err("coverage below 90"); 12600 assert!(below_90.contains("must satisfy coverage policy")); 12601 12602 let missing = ["missing".to_string()].into_iter().collect::<BTreeSet<_>>(); 12603 let missing_err = 12604 validate_required_coverage_summary(&root, &missing, required_thresholds()) 12605 .expect_err("missing required row"); 12606 assert!(missing_err.contains("missing from coverage-refresh.tsv")); 12607 12608 let _ = fs::remove_dir_all(root); 12609 } 12610 12611 #[test] 12612 fn enum_extract_and_parse_error_paths_are_reported() { 12613 let missing = 12614 extract_enum_body("pub struct X;", "UnitDimension").expect_err("missing enum"); 12615 assert!(missing.contains("missing enum")); 12616 12617 let missing_brace = extract_enum_body("pub enum UnitDimension", "UnitDimension") 12618 .expect_err("missing opening brace"); 12619 assert!(missing_brace.contains("missing opening brace")); 12620 12621 let missing_close = 12622 extract_enum_body("pub enum UnitDimension { Count, Mass", "UnitDimension") 12623 .expect_err("missing closing brace"); 12624 assert!(missing_close.contains("missing closing brace")); 12625 12626 let variants = parse_enum_variants( 12627 r#" 12628 , 12629 = 1, 12630 // skip 12631 #![cfg(test)] 12632 Count, 12633 "#, 12634 ); 12635 assert_eq!(variants, vec!["Count".to_string()]); 12636 12637 let nested = extract_enum_body( 12638 "pub enum UnitDimension { Count = { 1 }, Mass = 2 }", 12639 "UnitDimension", 12640 ) 12641 .expect("nested braces in enum body"); 12642 assert!(nested.contains("Count")); 12643 } 12644 12645 #[test] 12646 fn coverage_policy_parity_reports_contract_errors() { 12647 let root = create_synthetic_workspace("coverage_policy_errors"); 12648 let contract_root = root.join("contracts"); 12649 let coverage_root = coverage_root(&contract_root); 12650 12651 write_file( 12652 &coverage_root.join("coverage.toml"), 12653 r#"[gate] 12654 fail_under_exec_lines = 90.0 12655 fail_under_functions = 90.0 12656 fail_under_regions = 90.0 12657 fail_under_branches = 90.0 12658 require_branches = true 12659 12660 [required] 12661 crates = [] 12662 "#, 12663 ); 12664 let empty_required = 12665 validate_coverage_policy_parity(&root, &contract_root).expect_err("empty required"); 12666 assert!(empty_required.contains("required crates list must not be empty")); 12667 12668 write_file( 12669 &coverage_root.join("coverage.toml"), 12670 r#"[gate] 12671 fail_under_exec_lines = 89.0 12672 fail_under_functions = 90.0 12673 fail_under_regions = 90.0 12674 fail_under_branches = 90.0 12675 require_branches = true 12676 12677 [required] 12678 crates = ["radroots_a", "radroots_b"] 12679 "#, 12680 ); 12681 let invalid_gate = validate_coverage_policy_parity(&root, &contract_root) 12682 .expect_err("invalid policy thresholds"); 12683 assert!(invalid_gate.contains("90/90/90/90")); 12684 12685 write_file( 12686 &coverage_root.join("coverage.toml"), 12687 r#"[gate] 12688 fail_under_exec_lines = 90.0 12689 fail_under_functions = 89.0 12690 fail_under_regions = 90.0 12691 fail_under_branches = 90.0 12692 require_branches = true 12693 12694 [required] 12695 crates = ["radroots_a", "radroots_b"] 12696 "#, 12697 ); 12698 let invalid_functions = validate_coverage_policy_parity(&root, &contract_root) 12699 .expect_err("invalid function threshold"); 12700 assert!(invalid_functions.contains("90/90/90/90")); 12701 12702 write_file( 12703 &coverage_root.join("coverage.toml"), 12704 r#"[gate] 12705 fail_under_exec_lines = 90.0 12706 fail_under_functions = 90.0 12707 fail_under_regions = 89.0 12708 fail_under_branches = 90.0 12709 require_branches = true 12710 12711 [required] 12712 crates = ["radroots_a", "radroots_b"] 12713 "#, 12714 ); 12715 let invalid_regions = validate_coverage_policy_parity(&root, &contract_root) 12716 .expect_err("invalid region threshold"); 12717 assert!(invalid_regions.contains("90/90/90/90")); 12718 12719 write_file( 12720 &coverage_root.join("coverage.toml"), 12721 r#"[gate] 12722 fail_under_exec_lines = 90.0 12723 fail_under_functions = 90.0 12724 fail_under_regions = 90.0 12725 fail_under_branches = 89.0 12726 require_branches = true 12727 12728 [required] 12729 crates = ["radroots_a", "radroots_b"] 12730 "#, 12731 ); 12732 let invalid_branches = validate_coverage_policy_parity(&root, &contract_root) 12733 .expect_err("invalid branch threshold"); 12734 assert!(invalid_branches.contains("90/90/90/90")); 12735 12736 write_file( 12737 &coverage_root.join("coverage.toml"), 12738 r#"[gate] 12739 fail_under_exec_lines = 90.0 12740 fail_under_functions = 90.0 12741 fail_under_regions = 90.0 12742 fail_under_branches = 90.0 12743 require_branches = true 12744 12745 [required] 12746 crates = ["radroots_a", "radroots_a"] 12747 "#, 12748 ); 12749 let duplicate_required = validate_coverage_policy_parity(&root, &contract_root) 12750 .expect_err("duplicate required crate"); 12751 assert!(duplicate_required.contains("duplicate crate")); 12752 12753 write_file( 12754 &coverage_root.join("coverage.toml"), 12755 r#"[gate] 12756 fail_under_exec_lines = 90.0 12757 fail_under_functions = 90.0 12758 fail_under_regions = 90.0 12759 fail_under_branches = 90.0 12760 require_branches = false 12761 12762 [required] 12763 crates = ["radroots_a", "radroots_b"] 12764 "#, 12765 ); 12766 let branches_optional = validate_coverage_policy_parity(&root, &contract_root) 12767 .expect_err("branches must be required"); 12768 assert!(branches_optional.contains("required branches")); 12769 12770 write_file( 12771 &coverage_root.join("coverage.toml"), 12772 r#"[gate] 12773 fail_under_exec_lines = 90.0 12774 fail_under_functions = 90.0 12775 fail_under_regions = 90.0 12776 fail_under_branches = 90.0 12777 require_branches = true 12778 12779 [overrides.radroots_a] 12780 fail_under_exec_lines = 89.9 12781 temporary = true 12782 reason = "invalid override below the active development baseline" 12783 12784 [required] 12785 crates = ["radroots_a", "radroots_b"] 12786 "#, 12787 ); 12788 let below_minimum_override = validate_coverage_policy_parity(&root, &contract_root) 12789 .expect_err("numeric override below the active baseline"); 12790 assert!(below_minimum_override.contains("scope radroots_a")); 12791 assert!(below_minimum_override.contains("at least 90/90/90/90")); 12792 12793 write_file( 12794 &coverage_root.join("coverage.toml"), 12795 r#"[gate] 12796 fail_under_exec_lines = 90.0 12797 fail_under_functions = 90.0 12798 fail_under_regions = 90.0 12799 fail_under_branches = 90.0 12800 require_branches = true 12801 12802 [required] 12803 crates = ["radroots_b"] 12804 "#, 12805 ); 12806 let missing_workspace = validate_coverage_policy_parity(&root, &contract_root) 12807 .expect_err("missing workspace crate in policy"); 12808 assert!(missing_workspace.contains("missing workspace crates")); 12809 12810 write_file( 12811 &coverage_root.join("coverage.toml"), 12812 r#"[gate] 12813 fail_under_exec_lines = 90.0 12814 fail_under_functions = 90.0 12815 fail_under_regions = 90.0 12816 fail_under_branches = 90.0 12817 require_branches = true 12818 12819 [required] 12820 crates = ["unknown"] 12821 "#, 12822 ); 12823 let required_unknown = validate_coverage_policy_parity(&root, &contract_root) 12824 .expect_err("unknown required crate"); 12825 assert!(required_unknown.contains("includes excluded or unknown crates")); 12826 12827 let _ = fs::remove_dir_all(root); 12828 } 12829 12830 #[test] 12831 fn release_publish_policy_reports_contract_errors() { 12832 let root = create_synthetic_workspace("release_policy_errors"); 12833 let contract_root = root.join("contracts"); 12834 let release_policy_path = root_release_policy_path(&root); 12835 12836 write_file( 12837 &release_policy_path, 12838 r#"[release] 12839 version = "" 12840 12841 [publish] 12842 crates = ["radroots_a"] 12843 12844 [internal] 12845 crates = ["radroots_b"] 12846 12847 [publish_order] 12848 crates = ["radroots_a"] 12849 "#, 12850 ); 12851 let empty_version = validate_release_publish_policy(&root, &contract_root, "1.0.0") 12852 .expect_err("empty release version"); 12853 assert!(empty_version.contains("must not be empty")); 12854 12855 write_file( 12856 &release_policy_path, 12857 r#"[release] 12858 version = "2.0.0" 12859 12860 [publish] 12861 crates = ["radroots_a"] 12862 12863 [internal] 12864 crates = ["radroots_b"] 12865 12866 [publish_order] 12867 crates = ["radroots_a"] 12868 "#, 12869 ); 12870 let version_mismatch = validate_release_publish_policy(&root, &contract_root, "1.0.0") 12871 .expect_err("release version mismatch"); 12872 assert!(version_mismatch.contains("must match contract version")); 12873 12874 write_file( 12875 &release_policy_path, 12876 r#"[release] 12877 version = "1.0.0" 12878 12879 [publish] 12880 crates = ["radroots_a"] 12881 12882 [internal] 12883 crates = ["radroots_a"] 12884 12885 [publish_order] 12886 crates = ["radroots_a"] 12887 "#, 12888 ); 12889 let overlap = validate_release_publish_policy(&root, &contract_root, "1.0.0") 12890 .expect_err("publish/internal overlap"); 12891 assert!(overlap.contains("overlap is not allowed")); 12892 12893 write_file( 12894 &release_policy_path, 12895 r#"[release] 12896 version = "1.0.0" 12897 12898 [publish] 12899 crates = ["radroots_a"] 12900 12901 [internal] 12902 crates = [] 12903 12904 [publish_order] 12905 crates = ["radroots_a"] 12906 "#, 12907 ); 12908 let missing_workspace = validate_release_publish_policy(&root, &contract_root, "1.0.0") 12909 .expect_err("missing workspace crate"); 12910 assert!(missing_workspace.contains("missing workspace crates")); 12911 12912 write_file( 12913 &release_policy_path, 12914 r#"[release] 12915 version = "1.0.0" 12916 12917 [publish] 12918 crates = ["radroots_a"] 12919 12920 [internal] 12921 crates = ["radroots_b"] 12922 12923 [publish_order] 12924 crates = [] 12925 "#, 12926 ); 12927 let missing_publish_order = validate_release_publish_policy(&root, &contract_root, "1.0.0") 12928 .expect_err("missing publish order entries"); 12929 assert!(missing_publish_order.contains("missing publish crates")); 12930 12931 write_file( 12932 &release_policy_path, 12933 r#"[release] 12934 version = "1.0.0" 12935 12936 [publish] 12937 crates = ["radroots_a"] 12938 12939 [internal] 12940 crates = ["radroots_b"] 12941 12942 [publish_order] 12943 crates = ["radroots_a", "radroots_b"] 12944 "#, 12945 ); 12946 let extra_publish_order = validate_release_publish_policy(&root, &contract_root, "1.0.0") 12947 .expect_err("extra publish order entries"); 12948 assert!(extra_publish_order.contains("non-publish crates")); 12949 12950 write_file( 12951 &root.join("crates").join("a").join("Cargo.toml"), 12952 r#"[package] 12953 name = "radroots_a" 12954 publish = ["crates-io"] 12955 version = "1.0.0" 12956 edition = "2024" 12957 authors = ["Radroots Test"] 12958 rust-version = "1.97" 12959 license = "MIT OR Apache-2.0" 12960 description = "crate a" 12961 repository = "https://example.com/a" 12962 homepage = "https://example.com/a" 12963 documentation = "https://docs.rs/radroots_a" 12964 readme = "README.md" 12965 keywords = ["radroots"] 12966 categories = ["data-structures"] 12967 include = ["src/**", "tests/**", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 12968 12969 [package.metadata.docs.rs] 12970 features = [] 12971 12972 [dependencies] 12973 radroots_b = { path = "../b" } 12974 "#, 12975 ); 12976 write_file( 12977 &root.join("crates").join("b").join("Cargo.toml"), 12978 r#"[package] 12979 name = "radroots_b" 12980 version = "1.0.0" 12981 edition = "2024" 12982 description = "crate b" 12983 repository = "https://example.com/b" 12984 homepage = "https://example.com/b" 12985 documentation = "https://docs.example.com/b" 12986 readme = "README" 12987 "#, 12988 ); 12989 write_file( 12990 &release_policy_path, 12991 r#"[release] 12992 version = "1.0.0" 12993 12994 [publish] 12995 crates = ["radroots_a", "radroots_b"] 12996 12997 [internal] 12998 crates = [] 12999 13000 [publish_order] 13001 crates = ["radroots_a", "radroots_b"] 13002 "#, 13003 ); 13004 let dependency_order = validate_release_publish_policy(&root, &contract_root, "1.0.0") 13005 .expect_err("dependency order violation"); 13006 assert!(dependency_order.contains("must place dependency")); 13007 13008 write_file( 13009 &release_policy_path, 13010 r#"[release] 13011 version = "1.0.0" 13012 13013 [publish] 13014 crates = ["radroots_a"] 13015 13016 [internal] 13017 crates = ["radroots_b"] 13018 13019 [publish_order] 13020 crates = ["radroots_a"] 13021 "#, 13022 ); 13023 write_file( 13024 &root.join("crates").join("b").join("Cargo.toml"), 13025 r#"[package] 13026 name = "radroots_b" 13027 version = "1.0.0" 13028 edition = "2024" 13029 publish = false 13030 "#, 13031 ); 13032 validate_release_publish_policy(&root, &contract_root, "1.0.0") 13033 .expect("internal dependency should be ignored in publish ordering"); 13034 13035 write_file( 13036 &root.join("crates").join("a").join("Cargo.toml"), 13037 r#"[package] 13038 name = "radroots_a" 13039 version = "1.0.0" 13040 edition = "2024" 13041 publish = false 13042 "#, 13043 ); 13044 write_file( 13045 &release_policy_path, 13046 r#"[release] 13047 version = "1.0.0" 13048 13049 [publish] 13050 crates = ["radroots_a"] 13051 13052 [internal] 13053 crates = ["radroots_b"] 13054 13055 [publish_order] 13056 crates = ["radroots_a"] 13057 "#, 13058 ); 13059 let publish_flag = validate_release_publish_policy(&root, &contract_root, "1.0.0") 13060 .expect_err("publish crate must be publishable"); 13061 assert!(publish_flag.contains("must set publish = [\"crates-io\"]")); 13062 13063 write_file( 13064 &root.join("crates").join("a").join("Cargo.toml"), 13065 r#"[package] 13066 name = "radroots_a" 13067 publish = ["crates-io"] 13068 version = "1.0.0" 13069 edition = "2024" 13070 description = "crate a" 13071 repository = "https://example.com/a" 13072 homepage = "https://example.com/a" 13073 documentation = "https://docs.example.com/a" 13074 readme = "README" 13075 "#, 13076 ); 13077 write_file( 13078 &root.join("crates").join("b").join("Cargo.toml"), 13079 r#"[package] 13080 name = "radroots_b" 13081 version = "1.0.0" 13082 edition = "2024" 13083 "#, 13084 ); 13085 let internal_flag = validate_release_publish_policy(&root, &contract_root, "1.0.0") 13086 .expect_err("internal crate must be non-publishable"); 13087 assert!(internal_flag.contains("non-public crate")); 13088 13089 let _ = fs::remove_dir_all(root); 13090 } 13091 13092 #[test] 13093 fn publication_freeze_requires_every_workspace_package_to_be_private() { 13094 let root = create_synthetic_workspace("publication_freeze"); 13095 let contract_root = root.join("contracts"); 13096 let release_policy_path = root_release_policy_path(&root); 13097 write_file( 13098 &root.join("crates").join("a").join("Cargo.toml"), 13099 r#"[package] 13100 name = "radroots_a" 13101 version = "1.0.0" 13102 edition = "2024" 13103 publish = false 13104 "#, 13105 ); 13106 write_file( 13107 &release_policy_path, 13108 r#"[release] 13109 version = "1.0.0" 13110 13111 [publication] 13112 frozen = true 13113 registry = "crates-io" 13114 final_enablement_step = 305 13115 13116 [publish] 13117 crates = ["radroots_a"] 13118 13119 [internal] 13120 crates = ["radroots_b"] 13121 13122 [publish_order] 13123 crates = ["radroots_a"] 13124 "#, 13125 ); 13126 validate_release_publish_policy_with_override( 13127 &root, 13128 &contract_root, 13129 "1.0.0", 13130 Some(release_policy_path.clone()), 13131 ) 13132 .expect("fully private workspace should satisfy publication freeze"); 13133 13134 write_file( 13135 &root.join("crates").join("a").join("Cargo.toml"), 13136 r#"[package] 13137 name = "radroots_a" 13138 version = "1.0.0" 13139 edition = "2024" 13140 publish = ["crates-io"] 13141 "#, 13142 ); 13143 let publishable = validate_release_publish_policy_with_override( 13144 &root, 13145 &contract_root, 13146 "1.0.0", 13147 Some(release_policy_path.clone()), 13148 ) 13149 .expect_err("publication freeze must reject a publishable package"); 13150 assert!(publishable.contains("publication freeze requires workspace crate radroots_a")); 13151 13152 write_file( 13153 &release_policy_path, 13154 r#"[release] 13155 version = "1.0.0" 13156 13157 [publish] 13158 crates = ["radroots_a"] 13159 13160 [internal] 13161 crates = ["radroots_b"] 13162 13163 [publish_order] 13164 crates = ["radroots_a"] 13165 "#, 13166 ); 13167 let missing_control = validate_release_publish_policy_with_override( 13168 &root, 13169 &contract_root, 13170 "1.0.0", 13171 Some(release_policy_path), 13172 ) 13173 .expect_err("release policy must carry explicit publication control"); 13174 assert!(missing_control.contains("publication control is required")); 13175 13176 let _ = fs::remove_dir_all(root); 13177 } 13178 13179 #[test] 13180 fn v1_release_policy_covers_approved_unapproved_unclassified_and_private_fixtures() { 13181 let root = create_synthetic_workspace("v1_release_policy"); 13182 let contract_root = root.join("contracts"); 13183 let release_policy_path = root_release_policy_path(&root); 13184 for member in ["a", "b"] { 13185 write_file( 13186 &root.join("crates").join(member).join("Cargo.toml"), 13187 &format!( 13188 "[package]\nname = \"radroots_{member}\"\nversion = \"1.0.0\"\nedition = \"2024\"\npublish = false\n" 13189 ), 13190 ); 13191 } 13192 13193 let approved = (1..=19) 13194 .map(|index| format!("package-{index:02}")) 13195 .collect::<Vec<_>>(); 13196 let approved_toml = approved 13197 .iter() 13198 .map(|name| format!("\"{name}\"")) 13199 .collect::<Vec<_>>() 13200 .join(", "); 13201 let external_toml = approved[1..] 13202 .iter() 13203 .map(|name| format!("\"{name}\"")) 13204 .collect::<Vec<_>>() 13205 .join(", "); 13206 let mut architecture = format!( 13207 "spec_id = \"radroots.crates.release.v1\"\npackage_count = 19\n\n[repositories.lib]\nversion = \"0.1.0-alpha\"\npackages = [\"package-01\"]\n\n[repositories.sdk]\nversion = \"0.1.0\"\npackages = [{external_toml}]\n" 13208 ); 13209 for name in &approved { 13210 architecture.push_str(&format!("\n[[package]]\nname = \"{name}\"\n")); 13211 } 13212 write_file( 13213 &root.join("contracts/crates/release_v1/radroots_crates_release_v1.toml"), 13214 &architecture, 13215 ); 13216 13217 let policy = |approved_packages: &str, test_support: &str| { 13218 format!( 13219 r#"[release] 13220 version = "1.0.0" 13221 13222 [publication] 13223 frozen = true 13224 registry = "crates-io" 13225 final_enablement_step = 305 13226 spec_id = "radroots.crates.release.v1" 13227 approved_packages = [{approved_packages}] 13228 local_packages = ["package-01"] 13229 external_packages = [{external_toml}] 13230 13231 [workspace_classification] 13232 private = ["radroots_a"] 13233 build_codegen = [] 13234 test_support = [{test_support}] 13235 preview = [] 13236 retired = [] 13237 13238 [publish_order] 13239 crates = [] 13240 "# 13241 ) 13242 }; 13243 13244 write_file( 13245 &release_policy_path, 13246 &policy(&approved_toml, "\"radroots_b\""), 13247 ); 13248 validate_release_publish_policy(&root, &contract_root, "1.0.0") 13249 .expect("approved and exhaustively classified fixture must pass"); 13250 13251 let unapproved = format!("{approved_toml}, \"unapproved-public\""); 13252 write_file(&release_policy_path, &policy(&unapproved, "\"radroots_b\"")); 13253 let unapproved_error = validate_release_publish_policy(&root, &contract_root, "1.0.0") 13254 .expect_err("unapproved public package must fail"); 13255 assert!(unapproved_error.contains("unapproved packages: unapproved-public")); 13256 13257 write_file(&release_policy_path, &policy(&approved_toml, "")); 13258 let unclassified = validate_release_publish_policy(&root, &contract_root, "1.0.0") 13259 .expect_err("unclassified workspace package must fail"); 13260 assert!(unclassified.contains("workspace classification is missing packages: radroots_b")); 13261 13262 write_file( 13263 &release_policy_path, 13264 &policy(&approved_toml, "\"radroots_b\""), 13265 ); 13266 write_file( 13267 &root.join("crates/a/Cargo.toml"), 13268 "[package]\nname = \"radroots_a\"\nversion = \"1.0.0\"\nedition = \"2024\"\npublish = [\"crates-io\"]\n", 13269 ); 13270 let private = validate_release_publish_policy(&root, &contract_root, "1.0.0") 13271 .expect_err("private package must remain non-publishable"); 13272 assert!(private.contains("publication freeze requires workspace crate radroots_a")); 13273 13274 let _ = fs::remove_dir_all(root); 13275 } 13276 13277 #[test] 13278 fn release_preflight_rejects_public_dto_tooling_git_or_path_sources() { 13279 let root = create_synthetic_workspace("release_policy_dto_tooling_sources"); 13280 13281 write_file( 13282 &root.join("crates").join("a").join("Cargo.toml"), 13283 r#"[package] 13284 name = "radroots_a" 13285 publish = ["crates-io"] 13286 version = "1.0.0" 13287 edition = "2024" 13288 authors = ["Radroots Test"] 13289 rust-version = "1.97" 13290 license = "MIT OR Apache-2.0" 13291 description = "crate a" 13292 repository = "https://example.com/a" 13293 homepage = "https://example.com/a" 13294 documentation = "https://docs.rs/radroots_a" 13295 readme = "README.md" 13296 keywords = ["radroots"] 13297 categories = ["data-structures"] 13298 include = ["src/**", "tests/**", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 13299 13300 [package.metadata.docs.rs] 13301 features = [] 13302 13303 [dependencies] 13304 dto_bindgen_core = { path = "../../dto_bindgen_core", version = "0.1.0", optional = true } 13305 "#, 13306 ); 13307 let path_err = 13308 validate_generic_release_preflight(&root).expect_err("public path DTO dependency"); 13309 assert!(path_err.contains("radroots_a dependencies.dto_bindgen_core")); 13310 assert!(path_err.contains("not a path source")); 13311 13312 write_file( 13313 &root.join("Cargo.toml"), 13314 r#"[workspace] 13315 members = ["crates/a", "crates/b"] 13316 resolver = "2" 13317 13318 [workspace.package] 13319 version = "1.0.0" 13320 13321 [workspace.dependencies] 13322 dto_bindgen = { version = "0.1.0", git = "https://example.com/dto_bindgen", rev = "abc123" } 13323 radroots_a = { path = "crates/a", version = "=1.0.0" } 13324 radroots_b = { path = "crates/b", version = "=1.0.0" } 13325 "#, 13326 ); 13327 write_file( 13328 &root.join("crates").join("a").join("Cargo.toml"), 13329 r#"[package] 13330 name = "radroots_a" 13331 publish = ["crates-io"] 13332 version = "1.0.0" 13333 edition = "2024" 13334 description = "crate a" 13335 repository = "https://example.com/a" 13336 homepage = "https://example.com/a" 13337 documentation = "https://docs.example.com/a" 13338 readme = "README" 13339 13340 [dependencies] 13341 dto_bindgen = { workspace = true, optional = true } 13342 "#, 13343 ); 13344 let git_err = validate_generic_release_preflight(&root) 13345 .expect_err("public workspace git DTO dependency"); 13346 assert!(git_err.contains("radroots_a dependencies.dto_bindgen")); 13347 assert!(git_err.contains("not a git source")); 13348 13349 write_file( 13350 &root.join("crates").join("a").join("Cargo.toml"), 13351 r#"[package] 13352 name = "radroots_a" 13353 publish = ["crates-io"] 13354 version = "1.0.0" 13355 edition = "2024" 13356 authors = ["Radroots Test"] 13357 rust-version = "1.97" 13358 license = "MIT OR Apache-2.0" 13359 description = "crate a" 13360 repository = "https://example.com/a" 13361 homepage = "https://example.com/a" 13362 documentation = "https://docs.rs/radroots_a" 13363 readme = "README.md" 13364 keywords = ["radroots"] 13365 categories = ["data-structures"] 13366 include = ["src/**", "tests/**", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 13367 13368 [package.metadata.docs.rs] 13369 features = [] 13370 "#, 13371 ); 13372 write_file( 13373 &root.join("crates").join("b").join("Cargo.toml"), 13374 r#"[package] 13375 name = "radroots_b" 13376 version = "1.0.0" 13377 edition = "2024" 13378 publish = false 13379 13380 [dependencies] 13381 dto_bindgen = { workspace = true, optional = true } 13382 13383 [features] 13384 default = ["std"] 13385 std = [] 13386 legacy-ingest = ["std"] 13387 "#, 13388 ); 13389 validate_generic_release_preflight(&root) 13390 .expect("internal DTO tooling source does not block public publish policy"); 13391 13392 let _ = fs::remove_dir_all(root); 13393 } 13394 13395 #[test] 13396 fn validate_contract_bundle_reports_required_field_errors() { 13397 let root = create_synthetic_workspace("contract_bundle_errors"); 13398 13399 let assert_bundle_error = |expected: &str, mutator: fn(&mut ContractBundle)| { 13400 let mut bundle = load_contract_bundle(&root).expect("load bundle"); 13401 mutator(&mut bundle); 13402 let err = match validate_generic_contract_bundle(&bundle) { 13403 Ok(()) => panic!("expected bundle validation error: {expected}"), 13404 Err(err) => err, 13405 }; 13406 assert!(err.contains(expected), "expected `{expected}` in `{err}`"); 13407 }; 13408 13409 assert_bundle_error("contract name is required", |bundle| { 13410 bundle.manifest.contract.name.clear(); 13411 }); 13412 assert_bundle_error("contract version is required", |bundle| { 13413 bundle.manifest.contract.version.clear(); 13414 }); 13415 assert_bundle_error("contract source is required", |bundle| { 13416 bundle.manifest.contract.source.clear(); 13417 }); 13418 assert_bundle_error("surface.model_crates must not be empty", |bundle| { 13419 bundle.manifest.surface.model_crates.clear(); 13420 }); 13421 assert_bundle_error("surface.algorithm_crates must not be empty", |bundle| { 13422 bundle.manifest.surface.algorithm_crates.clear(); 13423 }); 13424 assert_bundle_error( 13425 "surface.internal_replica_crates.storage must be a crate identifier", 13426 |bundle| { 13427 bundle.manifest.surface.internal_replica_crates = Some(InternalReplicaCrates { 13428 schema: "radroots_replica_schema".to_string(), 13429 storage: "crates/replica_store".to_string(), 13430 sync: "radroots_replica_sync".to_string(), 13431 }); 13432 }, 13433 ); 13434 assert_bundle_error("version.contract.version is required", |bundle| { 13435 bundle.version.contract.version.clear(); 13436 }); 13437 assert_bundle_error("version.contract.stability is required", |bundle| { 13438 bundle.version.contract.stability.clear(); 13439 }); 13440 assert_bundle_error("version.semver rules must all be non-empty", |bundle| { 13441 bundle.version.semver.major_on.clear(); 13442 }); 13443 assert_bundle_error("version.semver rules must all be non-empty", |bundle| { 13444 bundle.version.semver.minor_on.clear(); 13445 }); 13446 assert_bundle_error("version.semver rules must all be non-empty", |bundle| { 13447 bundle.version.semver.patch_on.clear(); 13448 }); 13449 assert_bundle_error( 13450 "release_integrity.requires_conformance_pass must be true", 13451 |bundle| { 13452 bundle.version.release_integrity.requires_conformance_pass = false; 13453 }, 13454 ); 13455 assert_bundle_error( 13456 "release_integrity.requires_contract_manifest_diff must be true", 13457 |bundle| { 13458 bundle 13459 .version 13460 .release_integrity 13461 .requires_contract_manifest_diff = false; 13462 }, 13463 ); 13464 assert_bundle_error( 13465 "release_integrity.requires_release_notes must be true", 13466 |bundle| { 13467 bundle.version.release_integrity.requires_release_notes = false; 13468 }, 13469 ); 13470 assert_bundle_error("contract policy flags must all be true", |bundle| { 13471 bundle.manifest.policy.exclude_internal_workspace_crates = false; 13472 }); 13473 assert_bundle_error("contract policy flags must all be true", |bundle| { 13474 bundle.manifest.policy.require_reproducible_exports = false; 13475 }); 13476 assert_bundle_error("contract policy flags must all be true", |bundle| { 13477 bundle.manifest.policy.require_conformance_vectors = false; 13478 }); 13479 assert_bundle_error("contract replica policy flags must all be true", |bundle| { 13480 bundle.manifest.policy.replica = Some(ReplicaPolicy { 13481 forbid_legacy_alias_identifiers: false, 13482 require_transport_agnostic_sync_contract: true, 13483 require_deterministic_emit_ingest: true, 13484 }); 13485 }); 13486 13487 let _ = fs::remove_dir_all(root); 13488 } 13489 13490 #[test] 13491 fn load_contract_bundle_rejects_stale_consumer_sdk_tables() { 13492 let stale_manifest_root = create_synthetic_workspace("stale_manifest_consumer_sdk"); 13493 let manifest_path = stale_manifest_root.join("contracts").join("manifest.toml"); 13494 let mut manifest = fs::read_to_string(&manifest_path).expect("manifest"); 13495 manifest.push_str( 13496 r#" 13497 [consumer_sdk] 13498 rust_package = "radroots_sdk" 13499 "#, 13500 ); 13501 write_file(&manifest_path, &manifest); 13502 let manifest_err = 13503 load_contract_bundle(&stale_manifest_root).expect_err("stale manifest table"); 13504 assert!(manifest_err.contains("manifest.toml")); 13505 assert!(manifest_err.contains("consumer_sdk")); 13506 let _ = fs::remove_dir_all(stale_manifest_root); 13507 13508 let stale_operations_root = create_synthetic_workspace("stale_operations_consumer_sdk"); 13509 add_operation_contract_files(&stale_operations_root); 13510 let operations_path = stale_operations_root 13511 .join("contracts") 13512 .join("operations.toml"); 13513 let mut operations = fs::read_to_string(&operations_path).expect("operations"); 13514 operations.push_str( 13515 r#" 13516 [consumer_sdk] 13517 rust_package = "radroots_sdk" 13518 "#, 13519 ); 13520 write_file(&operations_path, &operations); 13521 let operations_err = 13522 load_contract_bundle(&stale_operations_root).expect_err("stale operations table"); 13523 assert!(operations_err.contains("operations.toml")); 13524 assert!(operations_err.contains("consumer_sdk")); 13525 let _ = fs::remove_dir_all(stale_operations_root); 13526 } 13527 13528 #[test] 13529 fn load_contract_bundle_rejects_legacy_contract_roots() { 13530 let stale_spec_root = create_synthetic_workspace("stale_spec_root"); 13531 fs::create_dir_all(stale_spec_root.join("spec")).expect("create spec root"); 13532 let spec_err = load_contract_bundle(&stale_spec_root).expect_err("stale spec root"); 13533 assert!(spec_err.contains("legacy contract root")); 13534 assert!(spec_err.contains("spec")); 13535 let _ = fs::remove_dir_all(stale_spec_root); 13536 13537 let stale_policy_root = create_synthetic_workspace("stale_policy_root"); 13538 fs::create_dir_all(stale_policy_root.join("policy")).expect("create policy root"); 13539 let policy_err = load_contract_bundle(&stale_policy_root).expect_err("stale policy root"); 13540 assert!(policy_err.contains("legacy contract root")); 13541 assert!(policy_err.contains("policy")); 13542 let _ = fs::remove_dir_all(stale_policy_root); 13543 } 13544 13545 #[test] 13546 fn load_contract_bundle_requires_operations_manifest() { 13547 let root = create_synthetic_workspace("missing_operations_manifest"); 13548 fs::remove_file(root.join("contracts").join("operations.toml")) 13549 .expect("remove operations manifest"); 13550 13551 let error = load_contract_bundle(&root).expect_err("missing operations manifest"); 13552 assert!(error.contains("operations.toml"), "{error}"); 13553 assert!(error.contains("read"), "{error}"); 13554 13555 let _ = fs::remove_dir_all(root); 13556 } 13557 13558 #[test] 13559 fn capsule_operation_authority_cannot_be_disabled_by_domain_removal() { 13560 let root = workspace_root(); 13561 13562 let mut social_bundle = load_contract_bundle(&root).expect("load current contract"); 13563 social_bundle 13564 .operations_manifest 13565 .public 13566 .domains 13567 .retain(|domain| domain != "social"); 13568 social_bundle 13569 .operations_manifest 13570 .operations 13571 .retain(|_, operation| operation.domain != "social"); 13572 let social_error = validate_contract_bundle(&social_bundle) 13573 .expect_err("removing social authority must fail"); 13574 assert!( 13575 social_error.contains("comment operation authority drift"), 13576 "{social_error}" 13577 ); 13578 13579 let mut food_bundle = load_contract_bundle(&root).expect("load current contract"); 13580 food_bundle 13581 .operations_manifest 13582 .public 13583 .domains 13584 .retain(|domain| domain != "food_availability"); 13585 food_bundle 13586 .operations_manifest 13587 .operations 13588 .retain(|_, operation| operation.domain != "food_availability"); 13589 let food_error = validate_contract_bundle(&food_bundle) 13590 .expect_err("removing FoodAvailability authority must fail"); 13591 assert!( 13592 food_error.contains("food availability operation authority drift"), 13593 "{food_error}" 13594 ); 13595 } 13596 13597 #[test] 13598 fn validate_contract_bundle_reports_operation_contract_errors() { 13599 let root = create_synthetic_workspace("operation_contract_bundle_errors"); 13600 add_operation_contract_files(&root); 13601 13602 let assert_bundle_error = |expected: &str, mutator: fn(&mut ContractBundle)| { 13603 let mut bundle = load_contract_bundle(&root).expect("load bundle"); 13604 mutator(&mut bundle); 13605 let err = 13606 validate_generic_contract_bundle(&bundle).expect_err("bundle validation error"); 13607 assert!(err.contains(expected), "expected `{expected}` in `{err}`"); 13608 }; 13609 13610 assert_bundle_error("public.domains must not be empty", |bundle| { 13611 bundle.operations_manifest.public.domains.clear(); 13612 }); 13613 assert_bundle_error( 13614 "shared_types.public uses retired event type RadrootsNostrEvent", 13615 |bundle| { 13616 bundle 13617 .operations_manifest 13618 .shared_types 13619 .public 13620 .push("RadrootsNostrEvent".to_string()); 13621 }, 13622 ); 13623 assert_bundle_error( 13624 "shared_types.public uses retired event type RadrootsInboundCalendarDateEvent", 13625 |bundle| { 13626 bundle 13627 .operations_manifest 13628 .shared_types 13629 .public 13630 .push("RadrootsInboundCalendarDateEvent".to_string()); 13631 }, 13632 ); 13633 assert_bundle_error( 13634 "shared_types.public uses retired event type RadrootsCalendar", 13635 |bundle| { 13636 bundle 13637 .operations_manifest 13638 .shared_types 13639 .public 13640 .push("RadrootsCalendar".to_string()); 13641 }, 13642 ); 13643 assert_bundle_error( 13644 "shared_types.public uses retired event type RadrootsCalendarEventRsvp", 13645 |bundle| { 13646 bundle 13647 .operations_manifest 13648 .shared_types 13649 .public 13650 .push("RadrootsCalendarEventRsvp".to_string()); 13651 }, 13652 ); 13653 assert_bundle_error( 13654 "shared_types.public uses retired event type RadrootsCalendarRsvp", 13655 |bundle| { 13656 bundle 13657 .operations_manifest 13658 .shared_types 13659 .public 13660 .push("RadrootsCalendarRsvp".to_string()); 13661 }, 13662 ); 13663 assert_bundle_error( 13664 "operation profile.build_authored_draft inputs uses retired event type RadrootsNostrEvent", 13665 |bundle| { 13666 bundle 13667 .operations_manifest 13668 .operations 13669 .get_mut("profile_build_authored_draft") 13670 .expect("profile operation") 13671 .inputs 13672 .push("RadrootsNostrEvent".to_string()); 13673 }, 13674 ); 13675 assert_bundle_error( 13676 "operation profile.build_authored_draft outputs uses retired event type WireEventParts", 13677 |bundle| { 13678 bundle 13679 .operations_manifest 13680 .operations 13681 .get_mut("profile_build_authored_draft") 13682 .expect("profile operation") 13683 .outputs 13684 .push("WireEventParts".to_string()); 13685 }, 13686 ); 13687 assert_bundle_error( 13688 "operation profile.build_authored_draft implementation.rust_types uses retired event type RadrootsNostrEventPtr", 13689 |bundle| { 13690 bundle 13691 .operations_manifest 13692 .operations 13693 .get_mut("profile_build_authored_draft") 13694 .expect("profile operation") 13695 .implementation 13696 .rust_types 13697 .push("radroots_event::RadrootsNostrEventPtr".to_string()); 13698 }, 13699 ); 13700 let _ = fs::remove_dir_all(root); 13701 } 13702 13703 #[test] 13704 fn validate_contract_bundle_requires_real_conformance_assets() { 13705 let missing_schema_root = create_synthetic_workspace("operation_contract_missing_schema"); 13706 add_operation_contract_files(&missing_schema_root); 13707 let _ = fs::remove_file(conformance_schema_path(&missing_schema_root)); 13708 let bundle = load_contract_bundle(&missing_schema_root).expect("load bundle"); 13709 let err = 13710 validate_generic_contract_bundle(&bundle).expect_err("missing schema should fail"); 13711 assert!(err.contains("vector.schema.json")); 13712 let _ = fs::remove_dir_all(&missing_schema_root); 13713 13714 let invalid_vector_root = create_synthetic_workspace("operation_contract_invalid_vector"); 13715 add_operation_contract_files(&invalid_vector_root); 13716 let invalid_vector_path = invalid_vector_root 13717 .join("contracts") 13718 .join("conformance") 13719 .join("vectors") 13720 .join("profile") 13721 .join("metadata.v1.json"); 13722 write_file( 13723 &invalid_vector_path, 13724 r#"{ 13725 "suite": "profile", 13726 "contract_version": "1.0.0", 13727 "vectors": [ 13728 { 13729 "id": "profile_build_authored_draft_minimal_001", 13730 "kind": "profile.build_authored_draft", 13731 "input": {} 13732 } 13733 ] 13734 } 13735 "#, 13736 ); 13737 let bundle = load_contract_bundle(&invalid_vector_root).expect("load bundle"); 13738 let err = 13739 validate_generic_contract_bundle(&bundle).expect_err("invalid vector should fail"); 13740 assert!(err.contains("metadata.v1.json")); 13741 assert!(err.contains("exactly one of expected or expected_error_contains")); 13742 13743 write_file( 13744 &invalid_vector_path, 13745 r#"{ 13746 "suite": "profile", 13747 "contract_version": "1.0.0", 13748 "vectors": [ 13749 { 13750 "id": "profile_build_authored_draft_minimal_001", 13751 "kind": "profile.build_authored_draft", 13752 "input": {}, 13753 "expected": {}, 13754 "expected_error_contains": "invalid" 13755 } 13756 ] 13757 } 13758 "#, 13759 ); 13760 let err = validate_generic_contract_bundle(&bundle) 13761 .expect_err("vector with two result authorities should fail"); 13762 assert!(err.contains("exactly one of expected or expected_error_contains")); 13763 13764 write_file( 13765 &invalid_vector_path, 13766 r#"{ 13767 "suite": "profile", 13768 "contract_version": "1.0.0", 13769 "vectors": [ 13770 { 13771 "id": "profile_build_authored_draft_minimal_001", 13772 "kind": "profile.build_authored_draft", 13773 "input": {}, 13774 "expected_error_contains": " " 13775 } 13776 ] 13777 } 13778 "#, 13779 ); 13780 let err = validate_generic_contract_bundle(&bundle) 13781 .expect_err("blank expected error fragment should fail"); 13782 assert!(err.contains("expected_error_contains must not be blank")); 13783 let _ = fs::remove_dir_all(&invalid_vector_root); 13784 13785 let root = create_synthetic_workspace("operation_contract_vector_path"); 13786 add_operation_contract_files(&root); 13787 let mut bundle = load_contract_bundle(&root).expect("load bundle"); 13788 bundle 13789 .operations_manifest 13790 .operations 13791 .get_mut("profile_build_authored_draft") 13792 .expect("profile operation") 13793 .conformance 13794 .vector = "conformance/vectors/profile/metadata.v1.json".to_string(); 13795 let err = validate_generic_contract_bundle(&bundle).expect_err("legacy path should fail"); 13796 assert!(err.contains("must live under contracts/conformance/")); 13797 let _ = fs::remove_dir_all(root); 13798 } 13799 13800 #[test] 13801 fn parse_toml_and_publish_flags_report_failures() { 13802 let missing = temp_root("parse_toml_missing"); 13803 let read_err = 13804 parse_toml::<WorkspaceCargoManifest>(&missing.join("Cargo.toml")).expect_err("missing"); 13805 assert!(read_err.contains("read")); 13806 let _ = fs::remove_dir_all(&missing); 13807 13808 let invalid = temp_root("parse_toml_invalid"); 13809 write_file(&invalid.join("Cargo.toml"), "[workspace]\nmembers = ["); 13810 let parse_err = parse_toml::<WorkspaceCargoManifest>(&invalid.join("Cargo.toml")) 13811 .expect_err("invalid manifest"); 13812 assert!(parse_err.contains("parse")); 13813 let _ = fs::remove_dir_all(&invalid); 13814 13815 let contract_manifest_missing = temp_root("parse_contract_manifest_missing"); 13816 let contract_manifest_read_err = 13817 parse_toml::<ContractManifest>(&contract_manifest_missing.join("manifest.toml")) 13818 .expect_err("missing contract manifest"); 13819 assert!(contract_manifest_read_err.contains("read")); 13820 let _ = fs::remove_dir_all(&contract_manifest_missing); 13821 13822 let contract_manifest_invalid = temp_root("parse_contract_manifest_invalid"); 13823 write_file( 13824 &contract_manifest_invalid.join("manifest.toml"), 13825 "[contract", 13826 ); 13827 let contract_manifest_parse_err = 13828 parse_toml::<ContractManifest>(&contract_manifest_invalid.join("manifest.toml")) 13829 .expect_err("invalid contract manifest"); 13830 assert!(contract_manifest_parse_err.contains("parse")); 13831 let _ = fs::remove_dir_all(&contract_manifest_invalid); 13832 13833 let version_missing = temp_root("parse_version_policy_missing"); 13834 let version_read_err = parse_toml::<VersionPolicy>(&version_missing.join("version.toml")) 13835 .expect_err("missing version policy"); 13836 assert!(version_read_err.contains("read")); 13837 let _ = fs::remove_dir_all(&version_missing); 13838 13839 let version_invalid = temp_root("parse_version_policy_invalid"); 13840 write_file(&version_invalid.join("version.toml"), "[version"); 13841 let version_parse_err = parse_toml::<VersionPolicy>(&version_invalid.join("version.toml")) 13842 .expect_err("invalid version policy"); 13843 assert!(version_parse_err.contains("parse")); 13844 let _ = fs::remove_dir_all(&version_invalid); 13845 13846 let release_missing = temp_root("parse_release_contract_missing"); 13847 let release_read_err = 13848 parse_toml::<ReleaseContractFile>(&release_missing.join("publish-set.toml")) 13849 .expect_err("missing release contract"); 13850 assert!(release_read_err.contains("read")); 13851 let _ = fs::remove_dir_all(&release_missing); 13852 13853 let release_invalid = temp_root("parse_release_contract_invalid"); 13854 write_file(&release_invalid.join("publish-set.toml"), "[release"); 13855 let release_parse_err = 13856 parse_toml::<ReleaseContractFile>(&release_invalid.join("publish-set.toml")) 13857 .expect_err("invalid release contract"); 13858 assert!(release_parse_err.contains("parse")); 13859 let _ = fs::remove_dir_all(&release_invalid); 13860 13861 let operations_missing = temp_root("parse_operations_manifest_missing"); 13862 let operations_read_err = 13863 parse_toml::<OperationsContractManifest>(&operations_missing.join("operations.toml")) 13864 .expect_err("missing operations manifest"); 13865 assert!(operations_read_err.contains("read")); 13866 let _ = fs::remove_dir_all(&operations_missing); 13867 13868 let operations_invalid = temp_root("parse_operations_manifest_invalid"); 13869 write_file(&operations_invalid.join("operations.toml"), "[operations"); 13870 let operations_parse_err = 13871 parse_toml::<OperationsContractManifest>(&operations_invalid.join("operations.toml")) 13872 .expect_err("invalid operations manifest"); 13873 assert!(operations_parse_err.contains("parse")); 13874 let _ = fs::remove_dir_all(&operations_invalid); 13875 13876 let dup = temp_root("publish_flags_duplicate"); 13877 write_file( 13878 &dup.join("Cargo.toml"), 13879 r#"[workspace] 13880 members = ["crates/a", "crates/b"] 13881 "#, 13882 ); 13883 let member_manifest = 13884 "[package]\nname = \"duplicate\"\nversion = \"0.1.0\"\nedition = \"2024\"\n"; 13885 write_file( 13886 &dup.join("crates").join("a").join("Cargo.toml"), 13887 member_manifest, 13888 ); 13889 write_file( 13890 &dup.join("crates").join("b").join("Cargo.toml"), 13891 member_manifest, 13892 ); 13893 let dup_err = workspace_package_publish_flags(&dup).expect_err("duplicate publish flags"); 13894 assert!(dup_err.contains("duplicate workspace package name")); 13895 let _ = fs::remove_dir_all(&dup); 13896 } 13897 13898 #[test] 13899 fn workspace_package_records_and_callers_report_member_manifest_errors() { 13900 let root = temp_root("workspace_package_record_errors"); 13901 write_file( 13902 &root.join("Cargo.toml"), 13903 r#"[workspace] 13904 members = ["crates/a"] 13905 "#, 13906 ); 13907 13908 let read_err = 13909 workspace_package_records(&root).expect_err("missing member manifest should fail"); 13910 assert!(read_err.contains("read")); 13911 13912 let names_err = workspace_package_names(&root).expect_err("names should fail"); 13913 assert!(names_err.contains("read")); 13914 let manifests_err = workspace_package_manifests(&root).expect_err("manifests should fail"); 13915 assert!(manifests_err.contains("read")); 13916 let flags_err = workspace_package_publish_flags(&root).expect_err("flags should fail"); 13917 assert!(flags_err.contains("read")); 13918 let deps_err = read_workspace_package_dependencies(&root).expect_err("deps should fail"); 13919 assert!(deps_err.contains("read")); 13920 13921 let publish = ["radroots_a".to_string()] 13922 .into_iter() 13923 .collect::<BTreeSet<_>>(); 13924 let publish_err = 13925 validate_publish_package_metadata(&root, &publish).expect_err("publish metadata"); 13926 assert!(publish_err.contains("read")); 13927 13928 write_file( 13929 &root.join("crates").join("a").join("Cargo.toml"), 13930 "[package", 13931 ); 13932 let parse_value_err = 13933 workspace_package_records(&root).expect_err("invalid toml should fail"); 13934 assert!(parse_value_err.contains("parse")); 13935 13936 write_file( 13937 &root.join("crates").join("a").join("Cargo.toml"), 13938 r#"[workspace] 13939 resolver = "2" 13940 "#, 13941 ); 13942 let parse_package_err = 13943 workspace_package_records(&root).expect_err("missing package table should fail"); 13944 assert!(parse_package_err.contains("parse")); 13945 13946 let _ = fs::remove_dir_all(&root); 13947 } 13948 13949 #[test] 13950 fn workspace_package_manifests_success_and_publish_metadata_duplicate_names() { 13951 let root = create_synthetic_workspace("workspace_manifest_success"); 13952 let manifests = workspace_package_manifests(&root).expect("workspace manifests"); 13953 assert_eq!(manifests.len(), 2); 13954 assert!(manifests.contains_key("radroots_a")); 13955 assert!(manifests.contains_key("radroots_b")); 13956 13957 write_file( 13958 &root.join("crates").join("b").join("Cargo.toml"), 13959 r#"[package] 13960 name = "radroots_a" 13961 version = "1.0.0" 13962 edition = "2024" 13963 description = "crate b duplicate name" 13964 repository = "https://example.com/b" 13965 homepage = "https://example.com/b" 13966 documentation = "https://docs.example.com/b" 13967 readme = "README" 13968 publish = false 13969 "#, 13970 ); 13971 let publish = ["radroots_a".to_string()] 13972 .into_iter() 13973 .collect::<BTreeSet<_>>(); 13974 let duplicate_err = 13975 validate_publish_package_metadata(&root, &publish).expect_err("duplicate package map"); 13976 assert!(duplicate_err.contains("duplicate workspace package name")); 13977 13978 let _ = fs::remove_dir_all(&root); 13979 } 13980 13981 #[test] 13982 fn workspace_package_publish_configs_cover_success_and_duplicate_names() { 13983 let root = create_synthetic_workspace("workspace_publish_configs"); 13984 let flags = workspace_package_publish_flags(&root).expect("publish flags"); 13985 assert!(flags["radroots_a"]); 13986 assert!(!flags["radroots_b"]); 13987 13988 let configs = workspace_package_publish_configs(&root).expect("publish configs"); 13989 assert_eq!( 13990 configs["radroots_a"], 13991 Some(PackagePublish::Registries(vec!["crates-io".to_string()])) 13992 ); 13993 assert_eq!(configs["radroots_b"], Some(PackagePublish::Bool(false))); 13994 13995 write_file( 13996 &root.join("crates").join("b").join("Cargo.toml"), 13997 r#"[package] 13998 name = "radroots_a" 13999 version = "1.0.0" 14000 edition = "2024" 14001 publish = false 14002 "#, 14003 ); 14004 let duplicate_err = workspace_package_publish_configs(&root) 14005 .expect_err("duplicate package name in publish configs"); 14006 assert!(duplicate_err.contains("duplicate workspace package name")); 14007 14008 let _ = fs::remove_dir_all(&root); 14009 } 14010 14011 #[test] 14012 fn workspace_package_publish_configs_report_workspace_record_errors() { 14013 let root = temp_root("workspace_publish_configs_errors"); 14014 let err = workspace_package_publish_configs(&root) 14015 .expect_err("missing workspace manifest should fail"); 14016 assert!(err.contains("Cargo.toml")); 14017 14018 let _ = fs::remove_dir_all(&root); 14019 } 14020 14021 #[test] 14022 fn coverage_release_and_bundle_loaders_report_parse_and_read_errors() { 14023 let root = create_synthetic_workspace("coverage_release_loader_errors"); 14024 let contract_root = root.join("contracts"); 14025 let coverage_root = coverage_root(&contract_root); 14026 let release_policy_path = root_release_policy_path(&root); 14027 14028 let missing_workspace = temp_root("coverage_missing_workspace_manifest"); 14029 let policy_workspace_err = 14030 validate_coverage_policy_parity(&missing_workspace, &contract_root) 14031 .expect_err("coverage workspace lookup error"); 14032 assert!(policy_workspace_err.contains("Cargo.toml")); 14033 let _ = fs::remove_dir_all(&missing_workspace); 14034 14035 let _ = fs::remove_file(coverage_root.join("coverage.toml")); 14036 let policy_load_err = validate_coverage_policy_parity(&root, &contract_root) 14037 .expect_err("coverage policy read error"); 14038 assert!(policy_load_err.contains("coverage.toml")); 14039 write_file( 14040 &coverage_root.join("coverage.toml"), 14041 r#"[gate] 14042 fail_under_exec_lines = 100.0 14043 fail_under_functions = 100.0 14044 fail_under_regions = 100.0 14045 fail_under_branches = 100.0 14046 require_branches = true 14047 14048 [required] 14049 crates = ["radroots_a", "radroots_b"] 14050 "#, 14051 ); 14052 14053 let missing_release = temp_root("release_missing_workspace_manifest"); 14054 write_root_release_policy( 14055 &missing_release, 14056 r#"[release] 14057 version = "1.0.0" 14058 14059 [publish] 14060 crates = ["radroots_a"] 14061 14062 [internal] 14063 crates = ["radroots_b"] 14064 14065 [publish_order] 14066 crates = ["radroots_a"] 14067 "#, 14068 ); 14069 let release_workspace_err = 14070 validate_release_publish_policy(&missing_release, &contract_root, "1.0.0") 14071 .expect_err("release workspace read error"); 14072 assert!(release_workspace_err.contains("Cargo.toml")); 14073 let _ = fs::remove_dir_all(&missing_release); 14074 14075 let _ = fs::remove_file(&release_policy_path); 14076 let release_load_err = validate_release_publish_policy(&root, &contract_root, "1.0.0") 14077 .expect_err("release contract read error"); 14078 assert!(release_load_err.contains(RELEASE_POLICY_RELATIVE)); 14079 14080 write_file( 14081 &release_policy_path, 14082 r#"[release] 14083 version = "1.0.0" 14084 14085 [publish] 14086 crates = ["radroots_a", "radroots_a"] 14087 14088 [internal] 14089 crates = ["radroots_b"] 14090 14091 [publish_order] 14092 crates = ["radroots_a"] 14093 "#, 14094 ); 14095 let duplicate_publish = validate_release_publish_policy(&root, &contract_root, "1.0.0") 14096 .expect_err("duplicate publish crates"); 14097 assert!(duplicate_publish.contains("publish.crates has duplicate crate")); 14098 14099 write_file( 14100 &release_policy_path, 14101 r#"[release] 14102 version = "1.0.0" 14103 14104 [publish] 14105 crates = ["radroots_a"] 14106 14107 [internal] 14108 crates = ["radroots_b", "radroots_b"] 14109 14110 [publish_order] 14111 crates = ["radroots_a"] 14112 "#, 14113 ); 14114 let duplicate_internal = validate_release_publish_policy(&root, &contract_root, "1.0.0") 14115 .expect_err("duplicate internal crates"); 14116 assert!(duplicate_internal.contains("internal.crates has duplicate crate")); 14117 14118 write_file( 14119 &release_policy_path, 14120 r#"[release] 14121 version = "1.0.0" 14122 14123 [publish] 14124 crates = ["radroots_a"] 14125 14126 [internal] 14127 crates = ["radroots_b"] 14128 14129 [publish_order] 14130 crates = ["radroots_a", "radroots_a"] 14131 "#, 14132 ); 14133 let duplicate_order = validate_release_publish_policy(&root, &contract_root, "1.0.0") 14134 .expect_err("duplicate publish order"); 14135 assert!(duplicate_order.contains("publish_order.crates has duplicate crate")); 14136 14137 write_file( 14138 &release_policy_path, 14139 r#"[release] 14140 version = "1.0.0" 14141 14142 [publish] 14143 crates = ["radroots_a"] 14144 14145 [internal] 14146 crates = ["radroots_b"] 14147 14148 [publish_order] 14149 crates = ["radroots_a"] 14150 "#, 14151 ); 14152 write_file( 14153 &root.join("crates").join("a").join("Cargo.toml"), 14154 "[package", 14155 ); 14156 let dependency_err = validate_release_publish_policy(&root, &contract_root, "1.0.0") 14157 .expect_err("workspace dependency parse error"); 14158 assert!(dependency_err.contains("parse")); 14159 14160 let _ = fs::remove_dir_all(&root); 14161 } 14162 14163 #[test] 14164 fn load_release_contract_with_override_reports_override_and_missing_policy_errors() { 14165 let root = create_synthetic_workspace("release_contract_loader_errors"); 14166 14167 let missing_override = root.join("missing-release-policy.toml"); 14168 let override_err = 14169 load_release_contract_with_override(&root, "1.0.0", Some(missing_override.clone())) 14170 .expect_err("missing override should fail"); 14171 assert!(override_err.contains("release policy override points to a missing file")); 14172 14173 let _ = fs::remove_file(root_release_policy_path(&root)); 14174 let missing_policy_err = load_release_contract_with_override(&root, "1.0.0", None) 14175 .expect_err("missing release policy should fail"); 14176 assert!(missing_policy_err.contains("release publish policy not found")); 14177 assert!(missing_policy_err.contains(RELEASE_POLICY_RELATIVE)); 14178 14179 let _ = fs::remove_dir_all(&root); 14180 } 14181 14182 #[test] 14183 fn release_contract_discovery_does_not_search_parent_directories() { 14184 let parent = temp_root("release_contract_parent_isolation"); 14185 write_file( 14186 &release_contract_path(&parent, "1.0.0"), 14187 "[release]\nversion = \"1.0.0\"\n\n[publish_order]\ncrates = []\n", 14188 ); 14189 let capsule = parent.join("capsule"); 14190 fs::create_dir_all(&capsule).expect("create isolated capsule root"); 14191 14192 let err = resolve_release_contract_path_with_override(&capsule, "1.0.0", None) 14193 .expect_err("parent release contract must be ignored"); 14194 assert!(err.contains(&capsule.display().to_string())); 14195 assert!( 14196 !err.contains( 14197 &release_contract_path(&parent, "1.0.0") 14198 .display() 14199 .to_string() 14200 ) 14201 ); 14202 14203 let _ = fs::remove_dir_all(&parent); 14204 } 14205 14206 #[test] 14207 fn root_release_policy_preflight_covers_classification_variants() { 14208 let root = create_synthetic_workspace("root_release_policy_classifications"); 14209 configure_root_release_policy_workspace(&root); 14210 write_root_release_policy( 14211 &root, 14212 r#"[release] 14213 version = "1.0.0" 14214 14215 [classification] 14216 public = ["radroots_a"] 14217 internal = ["radroots_b"] 14218 deferred = ["radroots_c"] 14219 retired = ["radroots_d"] 14220 yank_only = ["radroots_e"] 14221 14222 [publish_order] 14223 crates = ["radroots_a"] 14224 "#, 14225 ); 14226 14227 let bundle = load_contract_bundle(&root).expect("load root release policy bundle"); 14228 validate_generic_contract_bundle(&bundle).expect("validate root release policy bundle"); 14229 validate_generic_release_preflight(&root).expect("validate root release policy preflight"); 14230 14231 let _ = fs::remove_dir_all(&root); 14232 } 14233 14234 #[test] 14235 fn root_release_policy_reports_deferred_retired_and_yank_only_errors() { 14236 for (label, policy_body, expected) in [ 14237 ( 14238 "deferred", 14239 r#"[release] 14240 version = "1.0.0" 14241 14242 [classification] 14243 public = ["radroots_a"] 14244 internal = ["radroots_b"] 14245 deferred = ["radroots_c", "radroots_c"] 14246 retired = ["radroots_d"] 14247 yank_only = ["radroots_e"] 14248 14249 [publish_order] 14250 crates = ["radroots_a"] 14251 "#, 14252 "classification.deferred has duplicate crate radroots_c", 14253 ), 14254 ( 14255 "retired", 14256 r#"[release] 14257 version = "1.0.0" 14258 14259 [classification] 14260 public = ["radroots_a"] 14261 internal = ["radroots_b"] 14262 deferred = ["radroots_c"] 14263 retired = [""] 14264 yank_only = ["radroots_e"] 14265 14266 [publish_order] 14267 crates = ["radroots_a"] 14268 "#, 14269 "classification.retired contains an empty crate name", 14270 ), 14271 ( 14272 "yank_only", 14273 r#"[release] 14274 version = "1.0.0" 14275 14276 [classification] 14277 public = ["radroots_a"] 14278 internal = ["radroots_b"] 14279 deferred = ["radroots_c"] 14280 retired = ["radroots_d"] 14281 yank_only = ["radroots_e", "radroots_e"] 14282 14283 [publish_order] 14284 crates = ["radroots_a"] 14285 "#, 14286 "classification.yank_only has duplicate crate radroots_e", 14287 ), 14288 ] { 14289 let root = create_synthetic_workspace(&format!("root_release_policy_{label}_error")); 14290 configure_root_release_policy_workspace(&root); 14291 write_root_release_policy(&root, policy_body); 14292 14293 let err = validate_release_publish_policy(&root, &root.join("contracts"), "1.0.0") 14294 .expect_err("invalid non-public classification should fail"); 14295 assert!(err.contains(expected), "{label} err: {err}"); 14296 14297 let _ = fs::remove_dir_all(&root); 14298 } 14299 } 14300 14301 #[test] 14302 fn validate_release_preflight_reports_each_stage_error() { 14303 let missing_contract_root = temp_root("preflight_missing_contract"); 14304 let missing_contract_err = validate_generic_release_preflight(&missing_contract_root) 14305 .expect_err("missing contract"); 14306 assert!(missing_contract_err.contains("manifest.toml")); 14307 let _ = fs::remove_dir_all(&missing_contract_root); 14308 14309 let invalid_bundle = create_synthetic_workspace("preflight_invalid_bundle"); 14310 write_file( 14311 &invalid_bundle.join("contracts").join("manifest.toml"), 14312 r#"[contract] 14313 name = "radroots_contract" 14314 version = "1.0.0" 14315 source = "synthetic" 14316 14317 [surface] 14318 model_crates = ["radroots_a"] 14319 algorithm_crates = ["radroots_b"] 14320 14321 [policy] 14322 exclude_internal_workspace_crates = false 14323 require_reproducible_exports = true 14324 require_conformance_vectors = true 14325 "#, 14326 ); 14327 let invalid_bundle_err = 14328 validate_generic_release_preflight(&invalid_bundle).expect_err("bundle validation"); 14329 assert!(invalid_bundle_err.contains("contract policy flags must all be true")); 14330 let _ = fs::remove_dir_all(&invalid_bundle); 14331 14332 let missing_release = create_synthetic_workspace("preflight_missing_release"); 14333 let _ = fs::remove_file(root_release_policy_path(&missing_release)); 14334 let missing_release_err = 14335 validate_generic_release_preflight(&missing_release).expect_err("missing release"); 14336 assert!(missing_release_err.contains(RELEASE_POLICY_RELATIVE)); 14337 let _ = fs::remove_dir_all(&missing_release); 14338 14339 let missing_required = create_synthetic_workspace("preflight_missing_required"); 14340 let _ = fs::remove_file(missing_required.join("contracts").join("coverage.toml")); 14341 let missing_required_err = validate_generic_release_preflight(&missing_required) 14342 .expect_err("missing required list"); 14343 assert!(missing_required_err.contains("coverage.toml")); 14344 let _ = fs::remove_dir_all(&missing_required); 14345 14346 let duplicate_publish = create_synthetic_workspace("preflight_duplicate_publish"); 14347 write_file( 14348 &root_release_policy_path(&duplicate_publish), 14349 r#"[release] 14350 version = "1.0.0" 14351 14352 [publish] 14353 crates = ["radroots_a", "radroots_a"] 14354 14355 [internal] 14356 crates = ["radroots_b"] 14357 14358 [publish_order] 14359 crates = ["radroots_a"] 14360 "#, 14361 ); 14362 let duplicate_publish_err = validate_generic_release_preflight(&duplicate_publish) 14363 .expect_err("duplicate publish crates"); 14364 assert!(duplicate_publish_err.contains("publish.crates has duplicate crate")); 14365 let _ = fs::remove_dir_all(&duplicate_publish); 14366 14367 let duplicate_required = create_synthetic_workspace("preflight_duplicate_required"); 14368 write_file( 14369 &duplicate_required.join("contracts").join("coverage.toml"), 14370 "[gate]\nfail_under_exec_lines = 100.0\nfail_under_functions = 100.0\nfail_under_regions = 100.0\nfail_under_branches = 100.0\nrequire_branches = true\n\n[required]\ncrates = [\"radroots_a\", \"radroots_a\"]\n", 14371 ); 14372 let duplicate_required_err = validate_generic_release_preflight(&duplicate_required) 14373 .expect_err("duplicate required crates"); 14374 assert!(duplicate_required_err.contains("duplicate crate")); 14375 let _ = fs::remove_dir_all(&duplicate_required); 14376 14377 let publish_metadata = create_synthetic_workspace("preflight_publish_metadata"); 14378 write_file( 14379 &publish_metadata.join("crates").join("a").join("Cargo.toml"), 14380 r#"[package] 14381 name = "radroots_a" 14382 publish = ["crates-io"] 14383 version = "1.0.0" 14384 edition = "2024" 14385 "#, 14386 ); 14387 let publish_metadata_err = validate_generic_release_preflight(&publish_metadata) 14388 .expect_err("publish metadata validation"); 14389 assert!(publish_metadata_err.contains("must define a non-empty package.description")); 14390 let _ = fs::remove_dir_all(&publish_metadata); 14391 14392 let missing_coverage_row = create_synthetic_workspace("preflight_missing_coverage_row"); 14393 write_file( 14394 &missing_coverage_row 14395 .join("target") 14396 .join("coverage") 14397 .join("coverage-refresh.tsv"), 14398 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\n", 14399 ); 14400 let missing_coverage_row_err = validate_generic_release_preflight(&missing_coverage_row) 14401 .expect_err("required coverage refresh row missing"); 14402 assert!(missing_coverage_row_err.contains("missing from coverage-refresh.tsv")); 14403 let _ = fs::remove_dir_all(&missing_coverage_row); 14404 } 14405 14406 #[test] 14407 fn load_contract_bundle_and_validation_report_version_core_and_coverage_errors() { 14408 let root = create_synthetic_workspace("bundle_version_core_and_coverage_errors"); 14409 write_file(&root.join("contracts").join("version.toml"), "[contract"); 14410 let version_parse_err = load_contract_bundle(&root).expect_err("invalid version file"); 14411 assert!(version_parse_err.contains("version.toml")); 14412 14413 write_file( 14414 &root.join("contracts").join("version.toml"), 14415 r#"[contract] 14416 version = "1.0.0" 14417 stability = "alpha" 14418 14419 [semver] 14420 major_on = ["breaking"] 14421 minor_on = ["feature"] 14422 patch_on = ["fix"] 14423 14424 [release_integrity] 14425 requires_conformance_pass = true 14426 requires_contract_manifest_diff = true 14427 requires_release_notes = true 14428 "#, 14429 ); 14430 let bundle = load_contract_bundle(&root).expect("load bundle"); 14431 write_file( 14432 &root.join("crates").join("core").join("src").join("unit.rs"), 14433 r#"pub enum UnitDimension { 14434 Mass, 14435 Count, 14436 Volume, 14437 } 14438 "#, 14439 ); 14440 let core_err = validate_generic_contract_bundle(&bundle).expect_err("core unit mismatch"); 14441 assert!(core_err.contains("variant order must be")); 14442 14443 write_file( 14444 &root.join("crates").join("core").join("src").join("unit.rs"), 14445 r#"pub enum UnitDimension { 14446 Count, 14447 Mass, 14448 Volume, 14449 } 14450 "#, 14451 ); 14452 write_file( 14453 &root.join("contracts").join("coverage.toml"), 14454 r#"[gate] 14455 fail_under_exec_lines = 90.0 14456 fail_under_functions = 90.0 14457 fail_under_regions = 90.0 14458 fail_under_branches = 90.0 14459 require_branches = false 14460 14461 [required] 14462 crates = ["radroots_a", "radroots_b"] 14463 "#, 14464 ); 14465 let policy_err = 14466 validate_generic_contract_bundle(&bundle).expect_err("coverage policy validation"); 14467 assert!(policy_err.contains("90/90/90/90")); 14468 14469 let _ = fs::remove_dir_all(&root); 14470 } 14471 14472 #[test] 14473 fn coverage_summary_and_core_enum_additional_error_paths() { 14474 let coverage_root = temp_root("coverage_summary_additional_errors"); 14475 write_file( 14476 &coverage_root 14477 .join("target") 14478 .join("coverage") 14479 .join("coverage-refresh.tsv"), 14480 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_a\tpass\t100\tbad\t100\t100\tfile\n", 14481 ); 14482 let func_err = load_coverage_refresh_rows(&coverage_root).expect_err("func parse error"); 14483 assert!(func_err.contains("parse func")); 14484 write_file( 14485 &coverage_root 14486 .join("target") 14487 .join("coverage") 14488 .join("coverage-refresh.tsv"), 14489 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\nradroots_a\tpass\t100\t100\tbad\t100\tfile\n", 14490 ); 14491 let branch_err = 14492 load_coverage_refresh_rows(&coverage_root).expect_err("branch parse error"); 14493 assert!(branch_err.contains("parse branch")); 14494 let _ = fs::remove_dir_all(&coverage_root); 14495 14496 let missing_refresh_root = temp_root("coverage_summary_missing_refresh"); 14497 let required = ["radroots_a".to_string()] 14498 .into_iter() 14499 .collect::<BTreeSet<_>>(); 14500 let missing_refresh_err = validate_required_coverage_summary( 14501 &missing_refresh_root, 14502 &required, 14503 required_thresholds(), 14504 ) 14505 .expect_err("missing refresh should fail"); 14506 assert!(missing_refresh_err.contains("coverage-refresh.tsv")); 14507 let _ = fs::remove_dir_all(&missing_refresh_root); 14508 14509 let enum_root = temp_root("core_unit_missing_enum"); 14510 write_file( 14511 &enum_root 14512 .join("crates") 14513 .join("core") 14514 .join("src") 14515 .join("unit.rs"), 14516 "pub struct NotTheEnum;", 14517 ); 14518 let enum_err = 14519 validate_core_unit_dimension_variant_order(&enum_root).expect_err("missing enum"); 14520 assert!(enum_err.contains("missing enum")); 14521 let _ = fs::remove_dir_all(&enum_root); 14522 } 14523 14524 #[test] 14525 fn publish_metadata_and_coverage_refresh_report_missing_paths() { 14526 let root = temp_root("publish_missing_manifest"); 14527 write_file( 14528 &root.join("Cargo.toml"), 14529 r#"[workspace] 14530 members = ["crates/a"] 14531 "#, 14532 ); 14533 write_file( 14534 &root.join("crates").join("a").join("Cargo.toml"), 14535 r#"[package] 14536 name = "radroots_a" 14537 version = "1.0.0" 14538 edition = "2024" 14539 authors = ["Radroots Test"] 14540 rust-version = "1.97" 14541 license = "MIT OR Apache-2.0" 14542 description = "crate a" 14543 repository = { workspace = true } 14544 homepage = { workspace = true } 14545 readme = { workspace = true } 14546 "#, 14547 ); 14548 let missing_manifest = ["radroots_b".to_string()] 14549 .into_iter() 14550 .collect::<BTreeSet<_>>(); 14551 let missing_err = validate_publish_package_metadata(&root, &missing_manifest) 14552 .expect_err("missing workspace manifest"); 14553 assert!(missing_err.contains("has no workspace manifest")); 14554 14555 let missing_field = ["radroots_a".to_string()] 14556 .into_iter() 14557 .collect::<BTreeSet<_>>(); 14558 let field_err = validate_publish_package_metadata(&root, &missing_field) 14559 .expect_err("missing configured field"); 14560 assert!(field_err.contains("must configure package.documentation")); 14561 14562 let refresh_missing = 14563 load_coverage_refresh_rows(&root).expect_err("missing coverage-refresh.tsv"); 14564 assert!(refresh_missing.contains("coverage-refresh.tsv")); 14565 let _ = fs::remove_dir_all(&root); 14566 } 14567 14568 #[test] 14569 fn coverage_refresh_parser_skips_blank_lines() { 14570 let root = temp_root("coverage_refresh_blank_lines"); 14571 write_file( 14572 &root 14573 .join("target") 14574 .join("coverage") 14575 .join("coverage-refresh.tsv"), 14576 "crate\tstatus\texec\tfunc\tbranch\tregion\treport\n\nradroots_a\tpass\t100\t100\t100\t100\tfile\n", 14577 ); 14578 let rows = load_coverage_refresh_rows(&root).expect("rows"); 14579 assert_eq!(rows.len(), 1); 14580 assert!(rows.contains_key("radroots_a")); 14581 let _ = fs::remove_dir_all(&root); 14582 } 14583 14584 #[test] 14585 fn core_unit_dimension_validation_reports_missing_and_mismatch() { 14586 let missing = temp_root("core_unit_missing"); 14587 let missing_err = validate_core_unit_dimension_variant_order(&missing) 14588 .expect_err("missing unit file should fail"); 14589 assert!(missing_err.contains("unit.rs")); 14590 let _ = fs::remove_dir_all(&missing); 14591 14592 let mismatch = temp_root("core_unit_mismatch"); 14593 write_file( 14594 &mismatch 14595 .join("crates") 14596 .join("core") 14597 .join("src") 14598 .join("unit.rs"), 14599 r#"pub enum UnitDimension { 14600 Mass, 14601 Count, 14602 Volume, 14603 } 14604 "#, 14605 ); 14606 let mismatch_err = validate_core_unit_dimension_variant_order(&mismatch) 14607 .expect_err("mismatched enum order should fail"); 14608 assert!(mismatch_err.contains("variant order must be")); 14609 let _ = fs::remove_dir_all(&mismatch); 14610 } 14611 14612 #[test] 14613 fn coverage_and_release_additional_error_branches_are_reported() { 14614 let root = create_synthetic_workspace("coverage_release_extra_errors"); 14615 let contract_root = root.join("contracts"); 14616 let coverage_root = coverage_root(&contract_root); 14617 let release_policy_path = root_release_policy_path(&root); 14618 14619 write_file( 14620 &coverage_root.join("coverage.toml"), 14621 r#"[gate] 14622 fail_under_exec_lines = 90.0 14623 fail_under_functions = 90.0 14624 fail_under_regions = 90.0 14625 fail_under_branches = 90.0 14626 require_branches = true 14627 14628 [required] 14629 crates = ["radroots_a", "radroots_b", "radroots_extra"] 14630 "#, 14631 ); 14632 let coverage_extra = validate_coverage_policy_parity(&root, &contract_root) 14633 .expect_err("coverage unknown crate"); 14634 assert!(coverage_extra.contains("includes excluded or unknown crates")); 14635 14636 write_file( 14637 &coverage_root.join("coverage.toml"), 14638 r#"[gate] 14639 fail_under_exec_lines = 90.0 14640 fail_under_functions = 90.0 14641 fail_under_regions = 90.0 14642 fail_under_branches = 90.0 14643 require_branches = true 14644 14645 [required] 14646 crates = ["radroots_b"] 14647 "#, 14648 ); 14649 let required_list_mismatch = validate_coverage_policy_parity(&root, &contract_root) 14650 .expect_err("required list must match workspace crates"); 14651 assert!(required_list_mismatch.contains("missing workspace crates")); 14652 14653 write_file( 14654 &release_policy_path, 14655 r#"[release] 14656 version = "1.0.0" 14657 14658 [publish] 14659 crates = ["radroots_a", "radroots_b", "radroots_extra"] 14660 14661 [internal] 14662 crates = [] 14663 14664 [publish_order] 14665 crates = ["radroots_a", "radroots_b"] 14666 "#, 14667 ); 14668 let release_extra = validate_release_publish_policy(&root, &contract_root, "1.0.0") 14669 .expect_err("release extra crate"); 14670 assert!(release_extra.contains("include unknown crates")); 14671 14672 write_file( 14673 &release_policy_path, 14674 r#"[release] 14675 version = "1.0.0" 14676 14677 [publish] 14678 crates = ["radroots_a"] 14679 14680 [internal] 14681 crates = ["radroots_b"] 14682 14683 [publish_order] 14684 crates = ["radroots_a", "radroots_b"] 14685 "#, 14686 ); 14687 let publish_order_extra = validate_release_publish_policy(&root, &contract_root, "1.0.0") 14688 .expect_err("publish order non-publish crate"); 14689 assert!(publish_order_extra.contains("non-publish crates")); 14690 14691 let _ = fs::remove_dir_all(&root); 14692 } 14693 14694 #[test] 14695 fn validate_contract_bundle_reports_release_policy_errors() { 14696 let release_error_root = create_synthetic_workspace("bundle_release_policy_error"); 14697 write_file( 14698 &root_release_policy_path(&release_error_root), 14699 r#"[release] 14700 version = "1.0.0" 14701 14702 [publish] 14703 crates = ["radroots_a"] 14704 14705 [internal] 14706 crates = ["radroots_b"] 14707 14708 [publish_order] 14709 crates = [] 14710 "#, 14711 ); 14712 let bundle = load_contract_bundle(&release_error_root).expect("load release error bundle"); 14713 let release_err = 14714 validate_generic_contract_bundle(&bundle).expect_err("release policy failure"); 14715 assert!(release_err.contains("publish_order.crates is missing publish crates")); 14716 let _ = fs::remove_dir_all(&release_error_root); 14717 } 14718 }