@qijenchen/governance 0.1.0-beta.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +89 -0
  2. package/bin/attest.mjs +4 -0
  3. package/bin/check.mjs +4 -0
  4. package/bin/doctor.mjs +4 -0
  5. package/bin/generate.mjs +4 -0
  6. package/bin/governance.mjs +4 -0
  7. package/bin/hook.mjs +4 -0
  8. package/bin/upgrade.mjs +4 -0
  9. package/canonical/gates.json +42 -0
  10. package/canonical/manifest.json +476 -0
  11. package/canonical/plugin-aliases.json +25 -0
  12. package/canonical/provider-lifecycle.json +48 -0
  13. package/canonical/providers.json +455 -0
  14. package/canonical/roles.json +12 -0
  15. package/canonical/rules.json +81 -0
  16. package/canonical/schemas/attestation.schema.json +61 -0
  17. package/canonical/schemas/diagnostic.schema.json +37 -0
  18. package/canonical/schemas/gates.schema.json +27 -0
  19. package/canonical/schemas/lock.schema.json +189 -0
  20. package/canonical/schemas/manifest.schema.json +103 -0
  21. package/canonical/schemas/plugin-aliases.schema.json +59 -0
  22. package/canonical/schemas/provider-hook-coverage.schema.json +173 -0
  23. package/canonical/schemas/provider-lifecycle.schema.json +126 -0
  24. package/canonical/schemas/providers.schema.json +917 -0
  25. package/canonical/schemas/roles.schema.json +27 -0
  26. package/canonical/schemas/rules.schema.json +46 -0
  27. package/canonical/schemas/upgrade-plan.schema.json +31 -0
  28. package/package.json +42 -0
  29. package/src/authority-decision-evidence.mjs +413 -0
  30. package/src/canonical-order.mjs +8 -0
  31. package/src/carrier-projection.mjs +407 -0
  32. package/src/cli.mjs +114 -0
  33. package/src/closed-tool-execution.mjs +1001 -0
  34. package/src/common.mjs +278 -0
  35. package/src/contract.mjs +760 -0
  36. package/src/hook-api.mjs +107 -0
  37. package/src/index.mjs +14 -0
  38. package/src/provider-hook-normalization.mjs +1646 -0
  39. package/src/provider-review-binding.mjs +2377 -0
  40. package/src/snapshot.mjs +520 -0
@@ -0,0 +1,2377 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { compareUtf8Bytes } from './canonical-order.mjs'
3
+
4
+ export const EXACT_REVIEW_CERTIFICATION_CONTRACT = 'exact-provider-runtime-surface-role-target-v1'
5
+ export const MANAGED_REVIEW_TRANSPORT = 'managed-model-broker-v1'
6
+ export const PORTABLE_REVIEW_EXCHANGE_CORE = 'content-addressed-model-broker-exchange-v1'
7
+ export const REVIEW_TARGET_AXES = Object.freeze([
8
+ 'operatingSystem',
9
+ 'platform',
10
+ 'arch',
11
+ 'executionEnvironment',
12
+ 'distributionVersion',
13
+ 'pathClass',
14
+ ])
15
+
16
+ const PROVIDER_ID = /^[a-z][a-z0-9-]*$/
17
+ const TARGET_ID = /^[a-z0-9][a-z0-9-]*$/
18
+ const SHA256 = /^[a-f0-9]{64}$/
19
+ const REVIEW_PROFILE_ID = /^[a-z][a-z0-9-]*$/
20
+ const REVIEW_TIERS = Object.freeze(['standard', 'high', 'maximum'])
21
+ // Capability authority must not be transferable by reflecting over an object
22
+ // or replayable after its invocation-profile authority changes. Module-private
23
+ // metadata binds the exact minted object to the exact profile that authorized
24
+ // its runtime/surface/check/assertion evidence; serialized or stale records must
25
+ // be reverified.
26
+ const VERIFIED_ENTITLEMENT_AVAILABILITY = new WeakMap()
27
+
28
+ export class ProviderReviewBindingError extends Error {
29
+ constructor(code, detail) {
30
+ super(`${code}:${detail}`)
31
+ this.name = 'ProviderReviewBindingError'
32
+ this.code = code
33
+ }
34
+ }
35
+
36
+ function block(code, detail) {
37
+ throw new ProviderReviewBindingError(code, detail)
38
+ }
39
+
40
+ function object(value, code, label) {
41
+ if (!value || typeof value !== 'object' || Array.isArray(value)) block(code, `${label} is missing or invalid`)
42
+ return value
43
+ }
44
+
45
+ function nonEmpty(value, code, label) {
46
+ if (typeof value !== 'string' || !value.trim()) block(code, `${label} is missing or invalid`)
47
+ return value
48
+ }
49
+
50
+ function stableValue(value) {
51
+ if (Array.isArray(value)) return value.map(stableValue)
52
+ if (value && typeof value === 'object') {
53
+ return Object.fromEntries(Object.keys(value).sort(compareUtf8Bytes).map((key) => [key, stableValue(value[key])]))
54
+ }
55
+ return value
56
+ }
57
+
58
+ function digest(value) {
59
+ return createHash('sha256').update(JSON.stringify(stableValue(value))).digest('hex')
60
+ }
61
+
62
+ function providerById(registry, providerId, label) {
63
+ if (!PROVIDER_ID.test(providerId ?? '')) block('REVIEW_PROVIDER_INVALID', `${label} provider id is invalid:${providerId ?? '<missing>'}`)
64
+ const matches = (registry.providers || []).filter((provider) => provider?.id === providerId)
65
+ if (matches.length !== 1) block('REVIEW_PROVIDER_UNAVAILABLE', `${label} provider is not a registered concrete runtime:${providerId}`)
66
+ if (matches[0].providerKind && matches[0].providerKind !== 'concrete-runtime') {
67
+ block('REVIEW_PROVIDER_UNAVAILABLE', `${label} provider is not a concrete runtime:${providerId}`)
68
+ }
69
+ return matches[0]
70
+ }
71
+
72
+ function exactReviewPolicy(registry, policyId, reviewClass) {
73
+ const policies = object(registry.canonical?.reviewSelectionPolicies, 'REVIEW_SELECTION_POLICY_UNAVAILABLE', 'review selection policies')
74
+ const policy = object(policies[policyId], 'REVIEW_SELECTION_POLICY_UNAVAILABLE', `review selection policy ${policyId}`)
75
+ if (policy.schemaVersion !== 1
76
+ || JSON.stringify(policy.assuranceTierOrder) !== JSON.stringify(REVIEW_TIERS)
77
+ || JSON.stringify(policy.reasoningTierOrder) !== JSON.stringify(REVIEW_TIERS)
78
+ || JSON.stringify(policy.computeTierOrder) !== JSON.stringify(REVIEW_TIERS)
79
+ || policy.costPolicy !== 'batch-or-stop-never-capability-downgrade'
80
+ || policy.bindingPolicy !== 'freeze-exact-provider-profile-model-and-registry-digests-after-selection'
81
+ || policy.unavailableOutcome !== 'REVIEW-BLOCKED') {
82
+ block('REVIEW_SELECTION_POLICY_INVALID', policyId)
83
+ }
84
+ const expectedRanking = [
85
+ 'assurance-tier-desc',
86
+ 'reasoning-tier-desc',
87
+ 'compute-tier-desc',
88
+ 'available-required-entitlement-route-first',
89
+ 'provider-local-capability-rank-desc',
90
+ 'provider-id-utf8-asc',
91
+ 'review-profile-id-utf8-asc',
92
+ 'model-release-id-utf8-asc',
93
+ ]
94
+ if (JSON.stringify(policy.ranking) !== JSON.stringify(expectedRanking)) {
95
+ block('REVIEW_SELECTION_POLICY_INVALID', `${policyId}:ranking`)
96
+ }
97
+ const eligibility = policy.eligibility
98
+ if (!eligibility || Object.values(eligibility).some((value) => value !== true)) {
99
+ block('REVIEW_SELECTION_POLICY_INVALID', `${policyId}:eligibility`)
100
+ }
101
+ const reviewClassPolicy = object(policy.reviewClasses?.[reviewClass], 'REVIEW_CLASS_UNAVAILABLE', `${policyId}/${reviewClass}`)
102
+ if (!REVIEW_TIERS.includes(reviewClassPolicy.assuranceTier)
103
+ || !REVIEW_TIERS.includes(reviewClassPolicy.reasoningTier)
104
+ || !REVIEW_TIERS.includes(reviewClassPolicy.computeTier)) {
105
+ block('REVIEW_CLASS_INVALID', `${policyId}/${reviewClass}`)
106
+ }
107
+ return { policy, reviewClassPolicy }
108
+ }
109
+
110
+ function reviewBinding(registry, skill, selfProviderId, authorProviderId) {
111
+ object(registry, 'REVIEW_REGISTRY_INVALID', 'provider registry')
112
+ if (!Array.isArray(registry.providers)) block('REVIEW_REGISTRY_INVALID', 'provider registry providers must be an array')
113
+ if (typeof skill !== 'string' || !/^[a-z][a-z0-9-]*$/.test(skill)) block('REVIEW_SKILL_INVALID', `review skill is invalid:${skill ?? '<missing>'}`)
114
+ const self = providerById(registry, selfProviderId, 'self')
115
+ if (authorProviderId !== self.id) block('REVIEW_AUTHOR_COLLISION', `author must equal the current provider:${authorProviderId ?? '<missing>'}/${self.id}`)
116
+ const binding = self.adapter?.skillBindings?.[skill]
117
+ if (!binding || typeof binding !== 'object' || Array.isArray(binding)) {
118
+ block('REVIEW_BINDING_UNAVAILABLE', `${self.id} has no binding for ${skill}`)
119
+ }
120
+ if (binding.self !== self.id) block('REVIEW_BINDING_INVALID', `${self.id}/${skill} self binding mismatches`)
121
+ if (Object.hasOwn(binding, 'peer')) block('REVIEW_FIXED_PEER_FORBIDDEN', `${self.id}/${skill}`)
122
+ if (!/^[a-z][a-z0-9-]*-v[1-9][0-9]*$/.test(binding.selectionPolicy ?? '')) {
123
+ block('REVIEW_SELECTION_POLICY_UNAVAILABLE', `${self.id}/${skill}`)
124
+ }
125
+ if (!/^[a-z][a-z0-9-]*$/.test(binding.reviewClass ?? '')) block('REVIEW_CLASS_INVALID', `${self.id}/${skill}`)
126
+ const { policy, reviewClassPolicy } = exactReviewPolicy(registry, binding.selectionPolicy, binding.reviewClass)
127
+ return { self, binding, policy, reviewClassPolicy }
128
+ }
129
+
130
+ function records(value, field, code, label) {
131
+ object(value, code, label)
132
+ if (!Array.isArray(value[field])) block(code, `${label}.${field} must be an array`)
133
+ return value[field]
134
+ }
135
+
136
+ function uniqueSortedById(items, code, label) {
137
+ const ids = items.map((item) => item?.id)
138
+ if (ids.some((id) => typeof id !== 'string')
139
+ || new Set(ids).size !== ids.length
140
+ || ids.some((id, index) => index > 0 && compareUtf8Bytes(ids[index - 1], id) >= 0)) {
141
+ block(code, `${label} must be unique and UTF-8 sorted by id`)
142
+ }
143
+ }
144
+
145
+ function tierRank(policy, axis, value, label) {
146
+ const order = policy[axis]
147
+ const rank = Array.isArray(order) ? order.indexOf(value) : -1
148
+ if (rank < 0) block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${label}:${value ?? '<missing>'}`)
149
+ return rank
150
+ }
151
+
152
+ function invocationProfileById(invocationRegistry, profileId) {
153
+ object(invocationRegistry, 'REVIEW_INVOCATION_REGISTRY_INVALID', 'model invocation profile registry')
154
+ const matches = [
155
+ ...(invocationRegistry.profiles?.[profileId] ? [invocationRegistry.profiles[profileId]] : []),
156
+ ...(invocationRegistry.externalEntitlementProfiles?.[profileId] ? [invocationRegistry.externalEntitlementProfiles[profileId]] : []),
157
+ ]
158
+ if (matches.length !== 1) block('REVIEW_INVOCATION_PROFILE_UNAVAILABLE', profileId)
159
+ return matches[0]
160
+ }
161
+
162
+ function modelReleaseById(modelReleaseRegistry, modelReleaseId) {
163
+ const releaseRecords = records(modelReleaseRegistry, 'records', 'REVIEW_MODEL_RELEASE_REGISTRY_INVALID', 'model release registry')
164
+ const matches = releaseRecords.filter((record) => record?.id === modelReleaseId)
165
+ if (matches.length !== 1) block('REVIEW_MODEL_RELEASE_UNAVAILABLE', modelReleaseId)
166
+ return matches[0]
167
+ }
168
+
169
+ function reviewProfileRecords(capabilityRegistry) {
170
+ if (capabilityRegistry?.schemaVersion !== 1
171
+ || capabilityRegistry?.kind !== 'provider-neutral-review-capability-registry'
172
+ || capabilityRegistry?.selectionSemantics !== 'exact-candidates-only-capability-values-require-separate-certification'
173
+ || !capabilityRegistry.providerCapabilityPrecedence
174
+ || typeof capabilityRegistry.providerCapabilityPrecedence !== 'object'
175
+ || Array.isArray(capabilityRegistry.providerCapabilityPrecedence)) {
176
+ block('REVIEW_CAPABILITY_REGISTRY_INVALID', 'review capability registry identity is invalid')
177
+ }
178
+ const profiles = records(capabilityRegistry, 'reviewProfiles', 'REVIEW_CAPABILITY_REGISTRY_INVALID', 'review capability registry')
179
+ if (profiles.length === 0) block('REVIEW_CAPABILITY_REGISTRY_INVALID', 'review capability registry is empty')
180
+ uniqueSortedById(profiles, 'REVIEW_CAPABILITY_REGISTRY_INVALID', 'review capability profiles')
181
+ return profiles
182
+ }
183
+
184
+ function providerCapabilityForProfile(capabilityRegistry, profile) {
185
+ const providerRows = capabilityRegistry.providerCapabilityPrecedence?.[profile.providerId]
186
+ if (!Array.isArray(providerRows) || providerRows.length === 0) {
187
+ block('REVIEW_CAPABILITY_REGISTRY_INVALID', `${profile.providerId} lacks provider-local capability precedence`)
188
+ }
189
+ const modelIds = new Set()
190
+ const ranks = new Set()
191
+ for (const row of providerRows) {
192
+ exactObjectKeys(row, [
193
+ 'modelReleaseId',
194
+ 'capabilityRank',
195
+ 'assuranceTier',
196
+ 'reasoningTier',
197
+ 'computeTier',
198
+ 'exchangeBudget',
199
+ ], 'REVIEW_CAPABILITY_REGISTRY_INVALID', `${profile.providerId} capability precedence`)
200
+ exactObjectKeys(row.exchangeBudget, [
201
+ 'maxInputBytes',
202
+ 'maxOutputBytes',
203
+ 'maxPayloadBytes',
204
+ ], 'REVIEW_CAPABILITY_REGISTRY_INVALID', `${row.modelReleaseId} exchange budget`)
205
+ if (!row.modelReleaseId.startsWith(`${profile.providerId}/`)
206
+ || modelIds.has(row.modelReleaseId)
207
+ || !Number.isSafeInteger(row.capabilityRank)
208
+ || row.capabilityRank <= 0
209
+ || ranks.has(row.capabilityRank)
210
+ || !REVIEW_TIERS.includes(row.assuranceTier)
211
+ || !REVIEW_TIERS.includes(row.reasoningTier)
212
+ || !REVIEW_TIERS.includes(row.computeTier)
213
+ || !Number.isSafeInteger(row.exchangeBudget.maxInputBytes)
214
+ || row.exchangeBudget.maxInputBytes <= 0
215
+ || !Number.isSafeInteger(row.exchangeBudget.maxOutputBytes)
216
+ || row.exchangeBudget.maxOutputBytes <= 0
217
+ || !Number.isSafeInteger(row.exchangeBudget.maxPayloadBytes)
218
+ || row.exchangeBudget.maxPayloadBytes
219
+ < row.exchangeBudget.maxInputBytes + row.exchangeBudget.maxOutputBytes) {
220
+ block('REVIEW_CAPABILITY_REGISTRY_INVALID', `${profile.providerId}/${row.modelReleaseId ?? '<missing>'}`)
221
+ }
222
+ modelIds.add(row.modelReleaseId)
223
+ ranks.add(row.capabilityRank)
224
+ }
225
+ const matches = providerRows.filter((row) => row.modelReleaseId === profile.modelReleaseId)
226
+ if (matches.length !== 1) {
227
+ block('REVIEW_CAPABILITY_REGISTRY_INVALID', `${profile.id} lacks one exact provider-local capability rank`)
228
+ }
229
+ return matches[0]
230
+ }
231
+
232
+ function capabilityCertificationRecords(certificationLedger) {
233
+ if (certificationLedger?.schemaVersion !== 1
234
+ || certificationLedger?.kind !== 'review-capability-certification-ledger') {
235
+ block('REVIEW_CAPABILITY_CERTIFICATION_LEDGER_INVALID', 'review capability certification ledger identity is invalid')
236
+ }
237
+ const certifications = records(
238
+ certificationLedger,
239
+ 'certifications',
240
+ 'REVIEW_CAPABILITY_CERTIFICATION_LEDGER_INVALID',
241
+ 'review capability certification ledger',
242
+ )
243
+ uniqueSortedById(certifications, 'REVIEW_CAPABILITY_CERTIFICATION_LEDGER_INVALID', 'review capability certifications')
244
+ return certifications
245
+ }
246
+
247
+ function validateExactReviewProfile({
248
+ profile,
249
+ registry,
250
+ invocationRegistry,
251
+ modelReleaseRegistry,
252
+ } = {}) {
253
+ object(profile, 'REVIEW_CAPABILITY_PROFILE_INVALID', 'review capability profile')
254
+ if (!REVIEW_PROFILE_ID.test(profile.id ?? '')
255
+ || !PROVIDER_ID.test(profile.providerId ?? '')
256
+ || !['managed-api', 'subscription-entitlement'].includes(profile.routeClass)
257
+ || !REVIEW_PROFILE_ID.test(profile.invocationProfileId ?? '')
258
+ || !/^[a-z][a-z0-9-]*\/[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(profile.modelReleaseId ?? '')
259
+ || typeof profile.requestModelId !== 'string'
260
+ || profile.modelIdentityPolicy !== 'exact-model-release-response-match-no-mutable-alias') {
261
+ block('REVIEW_CAPABILITY_PROFILE_INVALID', profile.id ?? '<missing>')
262
+ }
263
+ providerById(registry, profile.providerId, 'capability')
264
+ const release = modelReleaseById(modelReleaseRegistry, profile.modelReleaseId)
265
+ if (release.providerId !== profile.providerId
266
+ || release.requestModelId !== profile.requestModelId
267
+ || release.responseModelPolicy?.kind !== 'exact'
268
+ || release.responseModelPolicy.expectedModelId !== profile.requestModelId
269
+ || release.id !== `${profile.providerId}/${profile.requestModelId}`) {
270
+ block('REVIEW_MODEL_ALIAS_FORBIDDEN', profile.id)
271
+ }
272
+ const invocationProfile = invocationProfileById(invocationRegistry, profile.invocationProfileId)
273
+ if (invocationProfile.providerId !== profile.providerId
274
+ || !invocationProfile.modelIdentity?.allowedModelReleaseIds?.includes(profile.modelReleaseId)) {
275
+ block('REVIEW_INVOCATION_PROFILE_MISMATCH', profile.id)
276
+ }
277
+ if (profile.routeClass === 'subscription-entitlement') {
278
+ if (typeof profile.entitlementId !== 'string'
279
+ || invocationProfile.mode !== 'external-subscription-entitlement'
280
+ || invocationProfile.entitlementId !== profile.entitlementId
281
+ || invocationProfile.availabilityPolicy !== 'exact-certified-entitlement-readback-required'
282
+ || invocationProfile.runtimeCertification !== 'required-not-source-certified'
283
+ || invocationProfile.availabilityEvidence?.kind !== 'certified-runtime-evidence-assertion-v1'
284
+ || !PROVIDER_ID.test(invocationProfile.availabilityEvidence.compatibilityProviderId ?? '')
285
+ || invocationProfile.availabilityEvidence.runtimeProviderId !== profile.providerId
286
+ || invocationProfile.availabilityEvidence.runtimeProfileId !== profile.providerId
287
+ || !REVIEW_PROFILE_ID.test(invocationProfile.availabilityEvidence.runtimeKind ?? '')
288
+ || !REVIEW_PROFILE_ID.test(invocationProfile.availabilityEvidence.surface ?? '')
289
+ || !REVIEW_PROFILE_ID.test(invocationProfile.availabilityEvidence.repositoryRole ?? '')
290
+ || invocationProfile.availabilityEvidence.providerEvidenceId !== profile.providerId
291
+ || !REVIEW_PROFILE_ID.test(invocationProfile.availabilityEvidence.checkId ?? '')
292
+ || !REVIEW_PROFILE_ID.test(invocationProfile.availabilityEvidence.assertionId ?? '')
293
+ || invocationProfile.costFallbackPolicy !== 'forbidden'
294
+ || invocationProfile.responseSelector?.schemaVersion !== 1
295
+ || invocationProfile.responseSelector?.kind !== 'provider-review-result-response-selector'
296
+ || invocationProfile.responseSelector?.carrierShape !== 'content-addressed-provider-review-result-v1') {
297
+ block('REVIEW_ENTITLEMENT_PROFILE_INVALID', profile.id)
298
+ }
299
+ } else if (profile.entitlementId !== null || invocationProfile.mode !== 'broker-content-only') {
300
+ block('REVIEW_INVOCATION_PROFILE_MISMATCH', profile.id)
301
+ }
302
+ return { release, invocationProfile }
303
+ }
304
+
305
+ function activeCapabilityCertification(certifications, profile, policy, now) {
306
+ const matching = certifications.filter((record) => record?.reviewProfileId === profile.id)
307
+ const eligible = []
308
+ for (const certification of matching) {
309
+ if (!REVIEW_PROFILE_ID.test(certification.id ?? '')
310
+ || certification.reviewProfileDigest !== digest(profile)
311
+ || certification.providerId !== profile.providerId
312
+ || certification.modelReleaseId !== profile.modelReleaseId
313
+ || certification.entitlementId !== profile.entitlementId
314
+ || !['certified', 'expired', 'revoked'].includes(certification.status)
315
+ || !Number.isFinite(Date.parse(certification.certifiedAt ?? ''))
316
+ || !Number.isFinite(Date.parse(certification.expiresAt ?? ''))
317
+ || Date.parse(certification.expiresAt) <= Date.parse(certification.certifiedAt)
318
+ || !certification.evidence
319
+ || typeof certification.evidence.reference !== 'string'
320
+ || !SHA256.test(certification.evidence.sha256 ?? '')) {
321
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${profile.id}/${certification?.id ?? '<missing>'}`)
322
+ }
323
+ tierRank(policy, 'assuranceTierOrder', certification.assuranceTier, `${certification.id}/assuranceTier`)
324
+ tierRank(policy, 'reasoningTierOrder', certification.reasoningTier, `${certification.id}/reasoningTier`)
325
+ tierRank(policy, 'computeTierOrder', certification.computeTier, `${certification.id}/computeTier`)
326
+ if (certification.status === 'certified'
327
+ && Date.parse(certification.certifiedAt) <= now.getTime()
328
+ && Date.parse(certification.expiresAt) > now.getTime()) eligible.push(certification)
329
+ }
330
+ if (eligible.length > 1) block('REVIEW_CAPABILITY_CERTIFICATION_AMBIGUOUS', profile.id)
331
+ return eligible[0] ?? null
332
+ }
333
+
334
+ function selectionReceiptDigest(receipt) {
335
+ const { selectionDigest: ignored, ...content } = receipt
336
+ return digest(content)
337
+ }
338
+
339
+ function entitlementAvailabilityKey(record) {
340
+ return `${record?.providerId ?? ''}/${record?.invocationProfileId ?? ''}/${record?.entitlementId ?? ''}`
341
+ }
342
+
343
+ function exactObjectKeys(value, expected, code, label) {
344
+ object(value, code, label)
345
+ const actual = Object.keys(value).sort(compareUtf8Bytes)
346
+ const normalizedExpected = [...expected].sort(compareUtf8Bytes)
347
+ if (actual.length !== normalizedExpected.length
348
+ || actual.some((key, index) => key !== normalizedExpected[index])) {
349
+ block(code, `${label} has an invalid or open shape`)
350
+ }
351
+ }
352
+
353
+ function runtimeEvidenceUnsigned(evidence) {
354
+ const { attestation: ignoredAttestation, evidenceDigest: ignoredDigest, ...unsigned } = evidence
355
+ return unsigned
356
+ }
357
+
358
+ function evidenceBytes(value) {
359
+ if (Buffer.isBuffer(value)) return Buffer.from(value)
360
+ if (value instanceof Uint8Array) return Buffer.from(value)
361
+ if (typeof value === 'string') return Buffer.from(value, 'utf8')
362
+ block('REVIEW_ENTITLEMENT_EVIDENCE_INVALID', 'runtime evidence bytes are missing or invalid')
363
+ }
364
+
365
+ function contentSha256(bytes) {
366
+ return createHash('sha256').update(bytes).digest('hex')
367
+ }
368
+
369
+ function freezeEntitlementRecord(record, invocationProfile) {
370
+ Object.freeze(record.target)
371
+ Object.freeze(record.evidence)
372
+ Object.freeze(record)
373
+ VERIFIED_ENTITLEMENT_AVAILABILITY.set(record, Object.freeze({
374
+ invocationProfileDigest: digest(invocationProfile),
375
+ }))
376
+ return record
377
+ }
378
+
379
+ /**
380
+ * Mint the only entitlement-availability value accepted by capability selection.
381
+ *
382
+ * The token is derived from an existing exact runtime certification and the exact
383
+ * content-addressed runtime evidence bytes named by that certification. No caller
384
+ * supplied availability boolean, hash-only record, or serialized receipt can mint
385
+ * the private in-process capability.
386
+ */
387
+ export function verifyEntitlementAvailabilityEvidence({
388
+ invocationRegistry,
389
+ invocationProfileId,
390
+ certificationLedger,
391
+ target,
392
+ expectedGitTree = null,
393
+ runtimeEvidenceBytes,
394
+ now = new Date(),
395
+ } = {}) {
396
+ if (!(now instanceof Date) || !Number.isFinite(now.getTime())) {
397
+ block('REVIEW_TIME_INVALID', 'entitlement evidence verification clock is invalid')
398
+ }
399
+ const invocationProfile = invocationProfileById(invocationRegistry, invocationProfileId)
400
+ const binding = object(
401
+ invocationProfile.availabilityEvidence,
402
+ 'REVIEW_ENTITLEMENT_EVIDENCE_INVALID',
403
+ `${invocationProfileId} availability evidence binding`,
404
+ )
405
+ exactObjectKeys(binding, [
406
+ 'kind',
407
+ 'compatibilityProviderId',
408
+ 'runtimeProviderId',
409
+ 'runtimeProfileId',
410
+ 'runtimeKind',
411
+ 'surface',
412
+ 'repositoryRole',
413
+ 'providerEvidenceId',
414
+ 'checkId',
415
+ 'assertionId',
416
+ ], 'REVIEW_ENTITLEMENT_EVIDENCE_INVALID', `${invocationProfileId} availability evidence binding`)
417
+ if (invocationProfile.mode !== 'external-subscription-entitlement'
418
+ || invocationProfile.availabilityPolicy !== 'exact-certified-entitlement-readback-required'
419
+ || binding.kind !== 'certified-runtime-evidence-assertion-v1'
420
+ || binding.runtimeProviderId !== invocationProfile.providerId
421
+ || binding.runtimeProfileId !== invocationProfile.providerId
422
+ || binding.providerEvidenceId !== invocationProfile.providerId) {
423
+ block('REVIEW_ENTITLEMENT_EVIDENCE_INVALID', `${invocationProfileId} is not an exact entitlement readback profile`)
424
+ }
425
+ if (certificationLedger?.schemaVersion !== 2
426
+ || certificationLedger?.$schema !== '../schemas/provider-surface-certification.schema.json') {
427
+ block('REVIEW_ENTITLEMENT_CERTIFICATION_UNTRUSTED', 'entitlement readback requires the promoted canonical provider certification ledger')
428
+ }
429
+ const certification = verifyExactProviderCertification({
430
+ certificationLedger,
431
+ compatibilityProviderId: binding.compatibilityProviderId,
432
+ runtimeProviderId: binding.runtimeProviderId,
433
+ runtimeProfileId: binding.runtimeProfileId,
434
+ runtimeKind: binding.runtimeKind,
435
+ surface: binding.surface,
436
+ repositoryRole: binding.repositoryRole,
437
+ target,
438
+ expectedGitTree,
439
+ now,
440
+ requireEvidence: true,
441
+ })
442
+ const bytes = evidenceBytes(runtimeEvidenceBytes)
443
+ const artifactSha256 = contentSha256(bytes)
444
+ const certifiedEvidence = object(
445
+ certification.evidence,
446
+ 'REVIEW_ENTITLEMENT_EVIDENCE_INVALID',
447
+ `${certification.certificationId} runtime evidence binding`,
448
+ )
449
+ if (certifiedEvidence.artifactSha256 !== artifactSha256
450
+ || certifiedEvidence.reference !== `infra/governance/evidence/provider-runtime/${artifactSha256}.json`) {
451
+ block('REVIEW_ENTITLEMENT_EVIDENCE_CONTENT_MISMATCH', `${certification.certificationId}/${invocationProfileId}`)
452
+ }
453
+ let evidence
454
+ try {
455
+ evidence = JSON.parse(bytes.toString('utf8'))
456
+ } catch {
457
+ block('REVIEW_ENTITLEMENT_EVIDENCE_INVALID', `${certification.certificationId} runtime evidence is not JSON`)
458
+ }
459
+ // Trust is inherited from the promoted exact certification record above. The
460
+ // embedded attestation status remains a required consistency assertion, but
461
+ // is never accepted without that canonical certification/content binding.
462
+ if (evidence?.schemaVersion !== 4
463
+ || evidence.kind !== 'provider-runtime-conformance'
464
+ || evidence.scope !== 'provider'
465
+ || evidence.status !== 'pass'
466
+ || evidence.attestation?.status !== 'verified'
467
+ || evidence.evidenceDigest !== certifiedEvidence.evidenceDigest
468
+ || evidence.evidenceDigest !== `sha256:${digest(runtimeEvidenceUnsigned(evidence))}`
469
+ || evidence.subject?.gitTree !== (expectedGitTree ?? evidence.subject?.gitTree)) {
470
+ block('REVIEW_ENTITLEMENT_EVIDENCE_UNTRUSTED', `${certification.certificationId}/${invocationProfileId}`)
471
+ }
472
+ const observedAt = evidence.run?.generatedAt
473
+ const evidenceExpiresAt = evidence.run?.validUntil
474
+ if (!Number.isFinite(Date.parse(observedAt ?? ''))
475
+ || !Number.isFinite(Date.parse(evidenceExpiresAt ?? ''))
476
+ || Date.parse(evidenceExpiresAt) <= Date.parse(observedAt)
477
+ || Date.parse(observedAt) > now.getTime()
478
+ || Date.parse(evidenceExpiresAt) <= now.getTime()) {
479
+ block('REVIEW_ENTITLEMENT_UNAVAILABLE', `${invocationProfile.providerId}/${invocationProfileId}/${invocationProfile.entitlementId}`)
480
+ }
481
+ const providerMatches = (evidence.providers || []).filter((provider) => provider?.id === binding.providerEvidenceId)
482
+ if (providerMatches.length !== 1
483
+ || providerMatches[0].status !== 'pass'
484
+ || providerMatches[0].targetBinding?.id !== certification.target.id) {
485
+ block('REVIEW_ENTITLEMENT_EVIDENCE_TARGET_MISMATCH', `${certification.certificationId}/${certification.target.id}`)
486
+ }
487
+ if (certifiedEvidence.targetId !== certification.target.id
488
+ || certifiedEvidence.providerId !== binding.runtimeProfileId
489
+ || (certifiedEvidence.targetDigest !== undefined
490
+ && certifiedEvidence.targetDigest !== providerMatches[0].targetBinding?.digest)) {
491
+ block('REVIEW_ENTITLEMENT_EVIDENCE_TARGET_MISMATCH', `${certification.certificationId}/${certification.target.id}`)
492
+ }
493
+ const checkMatches = (providerMatches[0].checks || []).filter((check) => check?.id === binding.checkId)
494
+ const assertionMatches = checkMatches.length === 1
495
+ ? (checkMatches[0].result?.assertions || []).filter((assertion) => assertion?.id === binding.assertionId)
496
+ : []
497
+ if (checkMatches.length !== 1
498
+ || checkMatches[0].certificationImpact !== 'capability-only'
499
+ || checkMatches[0].status !== 'pass'
500
+ || assertionMatches.length !== 1
501
+ || assertionMatches[0].pass !== true) {
502
+ block('REVIEW_ENTITLEMENT_READBACK_REJECTED', `${invocationProfile.providerId}/${invocationProfileId}/${invocationProfile.entitlementId}`)
503
+ }
504
+ const expiresAt = new Date(Math.min(
505
+ Date.parse(evidenceExpiresAt),
506
+ Date.parse(certification.expiresAt),
507
+ )).toISOString()
508
+ if (Date.parse(expiresAt) <= now.getTime()) {
509
+ block('REVIEW_ENTITLEMENT_UNAVAILABLE', `${invocationProfile.providerId}/${invocationProfileId}/${invocationProfile.entitlementId}`)
510
+ }
511
+ const readback = {
512
+ providerId: invocationProfile.providerId,
513
+ invocationProfileId,
514
+ entitlementId: invocationProfile.entitlementId,
515
+ source: 'verified-provider-adapter-readback',
516
+ status: 'available',
517
+ observedAt,
518
+ expiresAt,
519
+ runtimeProviderId: binding.runtimeProviderId,
520
+ runtimeProfileId: binding.runtimeProfileId,
521
+ runtimeKind: binding.runtimeKind,
522
+ runtimeSurface: binding.surface,
523
+ repositoryRole: binding.repositoryRole,
524
+ target: certification.target,
525
+ targetDigest: certification.targetDigest,
526
+ runtimeCertificationId: certification.certificationId,
527
+ runtimeCertificationDigest: certification.recordDigest,
528
+ runtimeEvidenceDigest: evidence.evidenceDigest,
529
+ evidence: {
530
+ reference: certifiedEvidence.reference,
531
+ sha256: artifactSha256,
532
+ },
533
+ }
534
+ const record = {
535
+ ...readback,
536
+ adapterReadbackDigest: digest(readback),
537
+ }
538
+ return freezeEntitlementRecord(record, invocationProfile)
539
+ }
540
+
541
+ function validateEntitlementAvailability(value, {
542
+ code = 'REVIEW_ENTITLEMENT_AVAILABILITY_INVALID',
543
+ now = null,
544
+ requireVerified = true,
545
+ invocationRegistry = null,
546
+ } = {}) {
547
+ if (!Array.isArray(value)) block(code, 'entitlement availability must be an array')
548
+ const keys = value.map(entitlementAvailabilityKey)
549
+ if (new Set(keys).size !== keys.length
550
+ || keys.some((key, index) => index > 0 && compareUtf8Bytes(keys[index - 1], key) >= 0)) {
551
+ block(code, 'entitlement availability must be unique and UTF-8 sorted')
552
+ }
553
+ for (const record of value) {
554
+ exactObjectKeys(record, [
555
+ 'providerId',
556
+ 'invocationProfileId',
557
+ 'entitlementId',
558
+ 'source',
559
+ 'status',
560
+ 'observedAt',
561
+ 'expiresAt',
562
+ 'runtimeProviderId',
563
+ 'runtimeProfileId',
564
+ 'runtimeKind',
565
+ 'runtimeSurface',
566
+ 'repositoryRole',
567
+ 'target',
568
+ 'targetDigest',
569
+ 'runtimeCertificationId',
570
+ 'runtimeCertificationDigest',
571
+ 'runtimeEvidenceDigest',
572
+ 'adapterReadbackDigest',
573
+ 'evidence',
574
+ ], code, `entitlement availability ${entitlementAvailabilityKey(record)}`)
575
+ exactObjectKeys(record.evidence, ['reference', 'sha256'], code, `entitlement availability evidence ${entitlementAvailabilityKey(record)}`)
576
+ if (!PROVIDER_ID.test(record?.providerId ?? '')
577
+ || !REVIEW_PROFILE_ID.test(record?.invocationProfileId ?? '')
578
+ || !/^[a-z][a-z0-9-]*$/.test(record?.entitlementId ?? '')
579
+ || record.source !== 'verified-provider-adapter-readback'
580
+ || record.status !== 'available'
581
+ || !Number.isFinite(Date.parse(record.observedAt ?? ''))
582
+ || !Number.isFinite(Date.parse(record.expiresAt ?? ''))
583
+ || Date.parse(record.expiresAt) <= Date.parse(record.observedAt)
584
+ || !PROVIDER_ID.test(record.runtimeProviderId ?? '')
585
+ || !REVIEW_PROFILE_ID.test(record.runtimeProfileId ?? '')
586
+ || !REVIEW_PROFILE_ID.test(record.runtimeKind ?? '')
587
+ || !REVIEW_PROFILE_ID.test(record.runtimeSurface ?? '')
588
+ || !REVIEW_PROFILE_ID.test(record.repositoryRole ?? '')
589
+ || !REVIEW_PROFILE_ID.test(record.runtimeCertificationId ?? '')
590
+ || digest(reviewTargetIdentity(record.target)) !== record.targetDigest
591
+ || !SHA256.test(record.runtimeCertificationDigest ?? '')
592
+ || !/^sha256:[a-f0-9]{64}$/.test(record.runtimeEvidenceDigest ?? '')
593
+ || !SHA256.test(record.adapterReadbackDigest ?? '')
594
+ || !record.evidence
595
+ || record.evidence.reference !== `infra/governance/evidence/provider-runtime/${record.evidence.sha256}.json`
596
+ || !SHA256.test(record.evidence.sha256 ?? '')
597
+ || record.adapterReadbackDigest !== digest(Object.fromEntries(
598
+ Object.entries(record).filter(([key]) => key !== 'adapterReadbackDigest'),
599
+ ))
600
+ || (requireVerified && !VERIFIED_ENTITLEMENT_AVAILABILITY.has(record))) {
601
+ block(code, entitlementAvailabilityKey(record))
602
+ }
603
+ if (requireVerified) {
604
+ const currentProfile = invocationProfileById(invocationRegistry, record.invocationProfileId)
605
+ if (VERIFIED_ENTITLEMENT_AVAILABILITY.get(record)?.invocationProfileDigest !== digest(currentProfile)) {
606
+ block(code, `${entitlementAvailabilityKey(record)}:invocation profile authority is stale`)
607
+ }
608
+ }
609
+ if (now && (Date.parse(record.observedAt) > now.getTime()
610
+ || Date.parse(record.expiresAt) <= now.getTime())) {
611
+ block('REVIEW_ENTITLEMENT_UNAVAILABLE', entitlementAvailabilityKey(record))
612
+ }
613
+ }
614
+ return value
615
+ }
616
+
617
+ export function validateBlockedReviewCapabilitySelectionReceipt(receipt) {
618
+ object(receipt, 'REVIEW_SELECTION_RECEIPT_INVALID', 'blocked review capability selection receipt')
619
+ if (receipt.schemaVersion !== 1
620
+ || receipt.kind !== 'provider-review-capability-selection-blocked'
621
+ || receipt.selectionStatus !== 'REVIEW-BLOCKED'
622
+ || !['REVIEW_CAPABILITY_UNAVAILABLE', 'REVIEW_ENTITLEMENT_UNAVAILABLE'].includes(receipt.selectionReasonCode)
623
+ || !PROVIDER_ID.test(receipt.authorProviderId ?? '')
624
+ || receipt.selfProviderId !== receipt.authorProviderId
625
+ || !/^[a-z][a-z0-9-]*$/.test(receipt.skill ?? '')
626
+ || !/^[a-z][a-z0-9-]*-v[1-9][0-9]*$/.test(receipt.selectionPolicy ?? '')
627
+ || !/^[a-z][a-z0-9-]*$/.test(receipt.reviewClass ?? '')
628
+ || !REVIEW_TIERS.includes(receipt.requiredAssuranceTier)
629
+ || !REVIEW_TIERS.includes(receipt.requiredReasoningTier)
630
+ || !REVIEW_TIERS.includes(receipt.requiredComputeTier)
631
+ || (receipt.requiredEntitlementId !== null
632
+ && !/^[a-z][a-z0-9-]*$/.test(receipt.requiredEntitlementId ?? ''))
633
+ || !SHA256.test(receipt.bindingDigest ?? '')
634
+ || !SHA256.test(receipt.selectionPolicyDigest ?? '')
635
+ || !SHA256.test(receipt.providerRegistryDigest ?? '')
636
+ || !SHA256.test(receipt.capabilityRegistryDigest ?? '')
637
+ || !SHA256.test(receipt.capabilityCertificationLedgerDigest ?? '')
638
+ || !SHA256.test(receipt.invocationRegistryDigest ?? '')
639
+ || !SHA256.test(receipt.modelReleaseRegistryDigest ?? '')
640
+ || !SHA256.test(receipt.entitlementAvailabilityDigest ?? '')
641
+ || receipt.entitlementAvailabilityDigest !== digest(receipt.entitlementAvailability)
642
+ || !SHA256.test(receipt.selectionDigest ?? '')
643
+ || receipt.selectionDigest !== selectionReceiptDigest(receipt)) {
644
+ block('REVIEW_SELECTION_RECEIPT_INVALID', 'blocked selection receipt identity, shape, or digest mismatches')
645
+ }
646
+ validateEntitlementAvailability(receipt.entitlementAvailability, {
647
+ code: 'REVIEW_SELECTION_RECEIPT_INVALID',
648
+ requireVerified: false,
649
+ })
650
+ return true
651
+ }
652
+
653
+ export function validateReviewCapabilitySelectionReceipt(receipt) {
654
+ object(receipt, 'REVIEW_SELECTION_RECEIPT_INVALID', 'review capability selection receipt')
655
+ if (receipt.schemaVersion !== 1
656
+ || receipt.kind !== 'provider-review-capability-selection'
657
+ || !PROVIDER_ID.test(receipt.authorProviderId ?? '')
658
+ || receipt.selfProviderId !== receipt.authorProviderId
659
+ || !/^[a-z][a-z0-9-]*$/.test(receipt.skill ?? '')
660
+ || !/^[a-z][a-z0-9-]*-v[1-9][0-9]*$/.test(receipt.selectionPolicy ?? '')
661
+ || !/^[a-z][a-z0-9-]*$/.test(receipt.reviewClass ?? '')
662
+ || !REVIEW_TIERS.includes(receipt.requiredAssuranceTier)
663
+ || !REVIEW_TIERS.includes(receipt.requiredReasoningTier)
664
+ || !REVIEW_TIERS.includes(receipt.requiredComputeTier)
665
+ || !receipt.selected
666
+ || !PROVIDER_ID.test(receipt.selected.providerId ?? '')
667
+ || receipt.selected.providerId === receipt.authorProviderId
668
+ || !REVIEW_PROFILE_ID.test(receipt.selected.reviewProfileId ?? '')
669
+ || !REVIEW_PROFILE_ID.test(receipt.selected.invocationProfileId ?? '')
670
+ || !['managed-api', 'subscription-entitlement'].includes(receipt.selected.routeClass)
671
+ || !/^[a-z][a-z0-9-]*\/[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(receipt.selected.modelReleaseId ?? '')
672
+ || typeof receipt.selected.requestModelId !== 'string'
673
+ || !REVIEW_TIERS.includes(receipt.selected.assuranceTier)
674
+ || !REVIEW_TIERS.includes(receipt.selected.reasoningTier)
675
+ || !REVIEW_TIERS.includes(receipt.selected.computeTier)
676
+ || !REVIEW_PROFILE_ID.test(receipt.selected.capabilityCertificationId ?? '')
677
+ || !Number.isFinite(Date.parse(receipt.selected.capabilityCertificationExpiresAt ?? ''))
678
+ || !SHA256.test(receipt.selected.capabilityEvidenceDigest ?? '')
679
+ || !SHA256.test(receipt.bindingDigest ?? '')
680
+ || !SHA256.test(receipt.selectionPolicyDigest ?? '')
681
+ || !SHA256.test(receipt.providerRegistryDigest ?? '')
682
+ || !SHA256.test(receipt.capabilityRegistryDigest ?? '')
683
+ || !SHA256.test(receipt.capabilityCertificationLedgerDigest ?? '')
684
+ || !SHA256.test(receipt.invocationRegistryDigest ?? '')
685
+ || !SHA256.test(receipt.modelReleaseRegistryDigest ?? '')
686
+ || !SHA256.test(receipt.selectedProviderRecordDigest ?? '')
687
+ || !SHA256.test(receipt.selectedProfileDigest ?? '')
688
+ || !SHA256.test(receipt.selectedInvocationProfileDigest ?? '')
689
+ || !SHA256.test(receipt.selectedModelReleaseDigest ?? '')
690
+ || !SHA256.test(receipt.selectedCapabilityCertificationDigest ?? '')
691
+ || !SHA256.test(receipt.entitlementAvailabilityDigest ?? '')
692
+ || receipt.entitlementAvailabilityDigest !== digest(receipt.entitlementAvailability)
693
+ || !SHA256.test(receipt.selectionDigest ?? '')
694
+ || receipt.selectionDigest !== selectionReceiptDigest(receipt)) {
695
+ block('REVIEW_SELECTION_RECEIPT_INVALID', 'selection receipt identity, shape, or digest mismatches')
696
+ }
697
+ validateEntitlementAvailability(receipt.entitlementAvailability, {
698
+ code: 'REVIEW_SELECTION_RECEIPT_INVALID',
699
+ requireVerified: false,
700
+ })
701
+ if (receipt.selected.routeClass === 'subscription-entitlement') {
702
+ if (typeof receipt.selected.entitlementId !== 'string'
703
+ || !receipt.entitlementAvailability.some((record) => (
704
+ record.providerId === receipt.selected.providerId
705
+ && record.invocationProfileId === receipt.selected.invocationProfileId
706
+ && record.entitlementId === receipt.selected.entitlementId
707
+ ))
708
+ || (receipt.requiredEntitlementId !== null
709
+ && receipt.requiredEntitlementId !== receipt.selected.entitlementId)) {
710
+ block('REVIEW_SELECTION_RECEIPT_INVALID', 'subscription entitlement binding mismatches')
711
+ }
712
+ } else if (receipt.selected.entitlementId !== null || receipt.requiredEntitlementId !== null) {
713
+ block('REVIEW_SELECTION_RECEIPT_INVALID', 'managed API selection cannot claim an entitlement')
714
+ }
715
+ return true
716
+ }
717
+
718
+ export function resolveHighestCertifiedReviewCapability({
719
+ registry,
720
+ capabilityRegistry,
721
+ capabilityCertificationLedger,
722
+ invocationRegistry,
723
+ modelReleaseRegistry,
724
+ skill,
725
+ selfProviderId,
726
+ authorProviderId = selfProviderId,
727
+ requiredEntitlementId = null,
728
+ entitlementAvailability = [],
729
+ expectedPeerProviderId = null,
730
+ expectedReviewProfileId = null,
731
+ expectedModelReleaseId = null,
732
+ now = new Date(),
733
+ } = {}) {
734
+ if (!(now instanceof Date) || !Number.isFinite(now.getTime())) block('REVIEW_TIME_INVALID', 'capability selection clock is invalid')
735
+ const { self, binding, policy, reviewClassPolicy } = reviewBinding(registry, skill, selfProviderId, authorProviderId)
736
+ if (requiredEntitlementId !== null && !/^[a-z][a-z0-9-]*$/.test(requiredEntitlementId)) {
737
+ block('REVIEW_ENTITLEMENT_INVALID', requiredEntitlementId ?? '<missing>')
738
+ }
739
+ validateEntitlementAvailability(entitlementAvailability, { now, invocationRegistry })
740
+ if (requiredEntitlementId !== null
741
+ && !entitlementAvailability.some((record) => record.entitlementId === requiredEntitlementId)) {
742
+ block('REVIEW_ENTITLEMENT_UNAVAILABLE', requiredEntitlementId)
743
+ }
744
+ const profiles = reviewProfileRecords(capabilityRegistry)
745
+ const certifications = capabilityCertificationRecords(capabilityCertificationLedger)
746
+ const candidates = []
747
+ for (const profile of profiles) {
748
+ const { release, invocationProfile } = validateExactReviewProfile({
749
+ profile,
750
+ registry,
751
+ invocationRegistry,
752
+ modelReleaseRegistry,
753
+ })
754
+ if (profile.providerId === self.id || profile.providerId === authorProviderId) continue
755
+ if (profile.routeClass === 'subscription-entitlement'
756
+ && !entitlementAvailability.some((record) => (
757
+ record.providerId === profile.providerId
758
+ && record.invocationProfileId === profile.invocationProfileId
759
+ && record.entitlementId === profile.entitlementId
760
+ ))) continue
761
+ if (requiredEntitlementId !== null && profile.entitlementId !== requiredEntitlementId) continue
762
+ const certification = activeCapabilityCertification(certifications, profile, policy, now)
763
+ if (!certification) continue
764
+ const providerCapability = providerCapabilityForProfile(capabilityRegistry, profile)
765
+ const requiredAssuranceRank = tierRank(
766
+ policy,
767
+ 'assuranceTierOrder',
768
+ reviewClassPolicy.assuranceTier,
769
+ `${binding.reviewClass}/assuranceTier`,
770
+ )
771
+ const requiredReasoningRank = tierRank(
772
+ policy,
773
+ 'reasoningTierOrder',
774
+ reviewClassPolicy.reasoningTier,
775
+ `${binding.reviewClass}/reasoningTier`,
776
+ )
777
+ const requiredComputeRank = tierRank(
778
+ policy,
779
+ 'computeTierOrder',
780
+ reviewClassPolicy.computeTier,
781
+ `${binding.reviewClass}/computeTier`,
782
+ )
783
+ const assuranceRank = tierRank(policy, 'assuranceTierOrder', certification.assuranceTier, `${certification.id}/assuranceTier`)
784
+ const reasoningRank = tierRank(policy, 'reasoningTierOrder', certification.reasoningTier, `${certification.id}/reasoningTier`)
785
+ const computeRank = tierRank(policy, 'computeTierOrder', certification.computeTier, `${certification.id}/computeTier`)
786
+ if (assuranceRank < requiredAssuranceRank
787
+ || reasoningRank < requiredReasoningRank
788
+ || computeRank < requiredComputeRank) continue
789
+ candidates.push({
790
+ profile,
791
+ release,
792
+ invocationProfile,
793
+ certification,
794
+ assuranceRank,
795
+ reasoningRank,
796
+ computeRank,
797
+ providerCapabilityRank: providerCapability.capabilityRank,
798
+ availableRequiredEntitlementRoute: profile.routeClass === 'subscription-entitlement' ? 1 : 0,
799
+ })
800
+ }
801
+ candidates.sort((left, right) => (
802
+ right.assuranceRank - left.assuranceRank
803
+ || right.reasoningRank - left.reasoningRank
804
+ || right.computeRank - left.computeRank
805
+ || right.availableRequiredEntitlementRoute - left.availableRequiredEntitlementRoute
806
+ || right.providerCapabilityRank - left.providerCapabilityRank
807
+ || compareUtf8Bytes(left.profile.providerId, right.profile.providerId)
808
+ || compareUtf8Bytes(left.profile.id, right.profile.id)
809
+ || compareUtf8Bytes(left.profile.modelReleaseId, right.profile.modelReleaseId)
810
+ ))
811
+ if (candidates.length === 0) {
812
+ block('REVIEW_CAPABILITY_UNAVAILABLE', `${self.id}/${skill}/${binding.reviewClass}/${requiredEntitlementId ?? 'any-entitlement'}`)
813
+ }
814
+ const selected = candidates[0]
815
+ if (expectedPeerProviderId !== null && selected.profile.providerId !== expectedPeerProviderId) {
816
+ block('REVIEW_PEER_MISMATCH', `${selected.profile.providerId}, not ${expectedPeerProviderId}`)
817
+ }
818
+ if (expectedReviewProfileId !== null && selected.profile.id !== expectedReviewProfileId) {
819
+ block('REVIEW_PROFILE_MISMATCH', `${selected.profile.id}, not ${expectedReviewProfileId}`)
820
+ }
821
+ if (expectedModelReleaseId !== null && selected.profile.modelReleaseId !== expectedModelReleaseId) {
822
+ block('REVIEW_MODEL_RELEASE_MISMATCH', `${selected.profile.modelReleaseId}, not ${expectedModelReleaseId}`)
823
+ }
824
+ const peer = providerById(registry, selected.profile.providerId, 'peer')
825
+ const bindingDigest = digest({
826
+ skill,
827
+ self: self.id,
828
+ selectionPolicy: binding.selectionPolicy,
829
+ reviewClass: binding.reviewClass,
830
+ binding,
831
+ })
832
+ const receipt = {
833
+ schemaVersion: 1,
834
+ kind: 'provider-review-capability-selection',
835
+ skill,
836
+ authorProviderId,
837
+ selfProviderId: self.id,
838
+ selectionPolicy: binding.selectionPolicy,
839
+ reviewClass: binding.reviewClass,
840
+ requiredAssuranceTier: reviewClassPolicy.assuranceTier,
841
+ requiredReasoningTier: reviewClassPolicy.reasoningTier,
842
+ requiredComputeTier: reviewClassPolicy.computeTier,
843
+ requiredEntitlementId,
844
+ entitlementAvailability,
845
+ entitlementAvailabilityDigest: digest(entitlementAvailability),
846
+ selected: {
847
+ providerId: peer.id,
848
+ reviewProfileId: selected.profile.id,
849
+ invocationProfileId: selected.profile.invocationProfileId,
850
+ routeClass: selected.profile.routeClass,
851
+ entitlementId: selected.profile.entitlementId,
852
+ modelReleaseId: selected.profile.modelReleaseId,
853
+ requestModelId: selected.profile.requestModelId,
854
+ assuranceTier: selected.certification.assuranceTier,
855
+ reasoningTier: selected.certification.reasoningTier,
856
+ computeTier: selected.certification.computeTier,
857
+ capabilityCertificationId: selected.certification.id,
858
+ capabilityCertificationExpiresAt: selected.certification.expiresAt,
859
+ capabilityEvidenceDigest: selected.certification.evidence.sha256,
860
+ },
861
+ bindingDigest,
862
+ selectionPolicyDigest: digest(policy),
863
+ providerRegistryDigest: digest(registry),
864
+ capabilityRegistryDigest: digest(capabilityRegistry),
865
+ capabilityCertificationLedgerDigest: digest(capabilityCertificationLedger),
866
+ invocationRegistryDigest: digest(invocationRegistry),
867
+ modelReleaseRegistryDigest: digest(modelReleaseRegistry),
868
+ selectedProviderRecordDigest: digest(peer),
869
+ selectedProfileDigest: digest(selected.profile),
870
+ selectedInvocationProfileDigest: digest(selected.invocationProfile),
871
+ selectedModelReleaseDigest: digest(selected.release),
872
+ selectedCapabilityCertificationDigest: digest(selected.certification),
873
+ }
874
+ receipt.selectionDigest = selectionReceiptDigest(receipt)
875
+ validateReviewCapabilitySelectionReceipt(receipt)
876
+ return {
877
+ skill,
878
+ self,
879
+ peer,
880
+ transport: binding.transport,
881
+ invocation: binding.invocation ?? null,
882
+ certificationContract: binding.certificationContract ?? null,
883
+ binding,
884
+ bindingDigest,
885
+ policy,
886
+ reviewClassPolicy,
887
+ selectedProfile: selected.profile,
888
+ selectedCapabilityCertification: selected.certification,
889
+ selectionReceipt: receipt,
890
+ }
891
+ }
892
+
893
+ function blockedCapabilitySelection({
894
+ registry,
895
+ capabilityRegistry,
896
+ capabilityCertificationLedger,
897
+ invocationRegistry,
898
+ modelReleaseRegistry,
899
+ skill,
900
+ self,
901
+ binding,
902
+ policy,
903
+ reviewClassPolicy,
904
+ requiredEntitlementId,
905
+ entitlementAvailability,
906
+ selectionReasonCode,
907
+ } = {}) {
908
+ const bindingDigest = digest({
909
+ skill,
910
+ self: self.id,
911
+ selectionPolicy: binding.selectionPolicy,
912
+ reviewClass: binding.reviewClass,
913
+ binding,
914
+ })
915
+ const receipt = {
916
+ schemaVersion: 1,
917
+ kind: 'provider-review-capability-selection-blocked',
918
+ selectionStatus: 'REVIEW-BLOCKED',
919
+ selectionReasonCode,
920
+ skill,
921
+ authorProviderId: self.id,
922
+ selfProviderId: self.id,
923
+ selectionPolicy: binding.selectionPolicy,
924
+ reviewClass: binding.reviewClass,
925
+ requiredAssuranceTier: reviewClassPolicy.assuranceTier,
926
+ requiredReasoningTier: reviewClassPolicy.reasoningTier,
927
+ requiredComputeTier: reviewClassPolicy.computeTier,
928
+ requiredEntitlementId,
929
+ entitlementAvailability,
930
+ entitlementAvailabilityDigest: digest(entitlementAvailability),
931
+ bindingDigest,
932
+ selectionPolicyDigest: digest(policy),
933
+ providerRegistryDigest: digest(registry),
934
+ capabilityRegistryDigest: digest(capabilityRegistry),
935
+ capabilityCertificationLedgerDigest: digest(capabilityCertificationLedger),
936
+ invocationRegistryDigest: digest(invocationRegistry),
937
+ modelReleaseRegistryDigest: digest(modelReleaseRegistry),
938
+ }
939
+ receipt.selectionDigest = selectionReceiptDigest(receipt)
940
+ validateBlockedReviewCapabilitySelectionReceipt(receipt)
941
+ return receipt
942
+ }
943
+
944
+ export function verifyReviewCapabilitySelection({
945
+ receipt,
946
+ registry,
947
+ capabilityRegistry,
948
+ capabilityCertificationLedger,
949
+ invocationRegistry,
950
+ modelReleaseRegistry,
951
+ skill,
952
+ selfProviderId,
953
+ authorProviderId = selfProviderId,
954
+ requiredEntitlementId = null,
955
+ entitlementAvailability = [],
956
+ observedProviderId,
957
+ observedReviewProfileId,
958
+ observedModelReleaseId,
959
+ observedResponseModelId,
960
+ now = new Date(),
961
+ } = {}) {
962
+ validateReviewCapabilitySelectionReceipt(receipt)
963
+ if (!(now instanceof Date) || !Number.isFinite(now.getTime())) block('REVIEW_TIME_INVALID', 'selection verification clock is invalid')
964
+ if (typeof skill !== 'string' || !selfProviderId || !authorProviderId) {
965
+ block('REVIEW_SELECTION_VERIFICATION_CONTEXT_REQUIRED', 'skill, self provider, and author provider must be explicit')
966
+ }
967
+ validateEntitlementAvailability(entitlementAvailability, { now, invocationRegistry })
968
+ for (const [actual, expected, code, label] of [
969
+ [digest(registry), receipt.providerRegistryDigest, 'REVIEW_PROVIDER_REGISTRY_STALE', 'provider registry'],
970
+ [digest(capabilityRegistry), receipt.capabilityRegistryDigest, 'REVIEW_CAPABILITY_REGISTRY_STALE', 'capability registry'],
971
+ [digest(capabilityCertificationLedger), receipt.capabilityCertificationLedgerDigest, 'REVIEW_CAPABILITY_CERTIFICATION_STALE', 'capability certification ledger'],
972
+ [digest(invocationRegistry), receipt.invocationRegistryDigest, 'REVIEW_INVOCATION_REGISTRY_STALE', 'invocation registry'],
973
+ [digest(modelReleaseRegistry), receipt.modelReleaseRegistryDigest, 'REVIEW_MODEL_RELEASE_REGISTRY_STALE', 'model release registry'],
974
+ ]) {
975
+ if (actual !== expected) block(code, label)
976
+ }
977
+ const canonical = resolveHighestCertifiedReviewCapability({
978
+ registry,
979
+ capabilityRegistry,
980
+ capabilityCertificationLedger,
981
+ invocationRegistry,
982
+ modelReleaseRegistry,
983
+ skill,
984
+ selfProviderId,
985
+ authorProviderId,
986
+ requiredEntitlementId,
987
+ entitlementAvailability,
988
+ now,
989
+ }).selectionReceipt
990
+ if (JSON.stringify(stableValue(canonical)) !== JSON.stringify(stableValue(receipt))) {
991
+ block('REVIEW_SELECTION_RECEIPT_NONCANONICAL', 'selection receipt differs from the current canonical highest eligible capability')
992
+ }
993
+ const selected = canonical.selected
994
+ if (authorProviderId === selected.providerId
995
+ || observedProviderId !== selected.providerId) {
996
+ block('REVIEW_PROVIDER_SUBSTITUTION', `${observedProviderId ?? '<missing>'}/${selected.providerId}`)
997
+ }
998
+ if (observedReviewProfileId !== selected.reviewProfileId) {
999
+ block('REVIEW_PROFILE_SUBSTITUTION', `${observedReviewProfileId ?? '<missing>'}/${selected.reviewProfileId}`)
1000
+ }
1001
+ if (observedModelReleaseId !== selected.modelReleaseId) {
1002
+ block('REVIEW_MODEL_RELEASE_SUBSTITUTION', `${observedModelReleaseId ?? '<missing>'}/${selected.modelReleaseId}`)
1003
+ }
1004
+ if (observedResponseModelId !== selected.requestModelId) {
1005
+ block('REVIEW_MODEL_SUBSTITUTION', `${observedResponseModelId ?? '<missing>'}/${selected.requestModelId}`)
1006
+ }
1007
+ if (Date.parse(selected.capabilityCertificationExpiresAt) <= now.getTime()) {
1008
+ block('REVIEW_CAPABILITY_CERTIFICATION_EXPIRED', selected.capabilityCertificationId)
1009
+ }
1010
+ return true
1011
+ }
1012
+
1013
+ export function resolveProviderReviewBinding({
1014
+ registry,
1015
+ skill,
1016
+ selfProviderId,
1017
+ authorProviderId = selfProviderId,
1018
+ expectedPeerProviderId = null,
1019
+ requireCertificationContract = false,
1020
+ capabilityRegistry = null,
1021
+ capabilityCertificationLedger = null,
1022
+ invocationRegistry = null,
1023
+ modelReleaseRegistry = null,
1024
+ requiredEntitlementId = null,
1025
+ entitlementAvailability = [],
1026
+ expectedReviewProfileId = null,
1027
+ expectedModelReleaseId = null,
1028
+ requireSelectedCapability = false,
1029
+ now = new Date(),
1030
+ } = {}) {
1031
+ const { self, binding, policy, reviewClassPolicy } = reviewBinding(registry, skill, selfProviderId, authorProviderId)
1032
+ const transport = nonEmpty(binding.transport, 'REVIEW_TRANSPORT_UNAVAILABLE', `${self.id}/${skill} transport`)
1033
+ if (requireCertificationContract && binding.certificationContract !== EXACT_REVIEW_CERTIFICATION_CONTRACT) {
1034
+ block('REVIEW_CERTIFICATION_CONTRACT_UNAVAILABLE', `${self.id}/${skill} lacks ${EXACT_REVIEW_CERTIFICATION_CONTRACT}`)
1035
+ }
1036
+ if (requireCertificationContract && transport !== PORTABLE_REVIEW_EXCHANGE_CORE) {
1037
+ block('REVIEW_EXCHANGE_CORE_UNATTESTED', `${self.id}/${skill} must use ${PORTABLE_REVIEW_EXCHANGE_CORE}`)
1038
+ }
1039
+ const selectionInputs = [capabilityRegistry, capabilityCertificationLedger, invocationRegistry, modelReleaseRegistry]
1040
+ const suppliedSelectionInputs = selectionInputs.filter((value) => value !== null).length
1041
+ if (suppliedSelectionInputs !== 0 && suppliedSelectionInputs !== selectionInputs.length) {
1042
+ block('REVIEW_CAPABILITY_INPUTS_INCOMPLETE', `${self.id}/${skill}`)
1043
+ }
1044
+ if (suppliedSelectionInputs === selectionInputs.length) {
1045
+ try {
1046
+ return resolveHighestCertifiedReviewCapability({
1047
+ registry,
1048
+ capabilityRegistry,
1049
+ capabilityCertificationLedger,
1050
+ invocationRegistry,
1051
+ modelReleaseRegistry,
1052
+ skill,
1053
+ selfProviderId,
1054
+ authorProviderId,
1055
+ requiredEntitlementId,
1056
+ entitlementAvailability,
1057
+ expectedPeerProviderId,
1058
+ expectedReviewProfileId,
1059
+ expectedModelReleaseId,
1060
+ now,
1061
+ })
1062
+ } catch (error) {
1063
+ if (requireSelectedCapability
1064
+ || !['REVIEW_CAPABILITY_UNAVAILABLE', 'REVIEW_ENTITLEMENT_UNAVAILABLE'].includes(error?.code)) throw error
1065
+ const bindingDigest = digest({
1066
+ skill,
1067
+ self: self.id,
1068
+ selectionPolicy: binding.selectionPolicy,
1069
+ reviewClass: binding.reviewClass,
1070
+ binding,
1071
+ })
1072
+ return {
1073
+ skill,
1074
+ self,
1075
+ peer: null,
1076
+ transport,
1077
+ invocation: binding.invocation ?? null,
1078
+ certificationContract: binding.certificationContract ?? null,
1079
+ binding,
1080
+ bindingDigest,
1081
+ policy,
1082
+ reviewClassPolicy,
1083
+ selectionStatus: 'REVIEW-BLOCKED',
1084
+ selectionReasonCode: error.code,
1085
+ selectionReceipt: blockedCapabilitySelection({
1086
+ registry,
1087
+ capabilityRegistry,
1088
+ capabilityCertificationLedger,
1089
+ invocationRegistry,
1090
+ modelReleaseRegistry,
1091
+ skill,
1092
+ self,
1093
+ binding,
1094
+ policy,
1095
+ reviewClassPolicy,
1096
+ requiredEntitlementId,
1097
+ entitlementAvailability,
1098
+ selectionReasonCode: error.code,
1099
+ }),
1100
+ }
1101
+ }
1102
+ }
1103
+ if (requireSelectedCapability || expectedPeerProviderId !== null
1104
+ || expectedReviewProfileId !== null || expectedModelReleaseId !== null
1105
+ || requiredEntitlementId !== null) {
1106
+ block('REVIEW_CAPABILITY_SELECTION_REQUIRED', `${self.id}/${skill}`)
1107
+ }
1108
+ const bindingDigest = digest({
1109
+ skill,
1110
+ self: self.id,
1111
+ selectionPolicy: binding.selectionPolicy,
1112
+ reviewClass: binding.reviewClass,
1113
+ binding,
1114
+ })
1115
+ return {
1116
+ skill,
1117
+ self,
1118
+ peer: null,
1119
+ transport,
1120
+ invocation: binding.invocation ?? null,
1121
+ certificationContract: binding.certificationContract ?? null,
1122
+ binding,
1123
+ bindingDigest,
1124
+ policy,
1125
+ reviewClassPolicy,
1126
+ selectionStatus: 'REVIEW-BLOCKED',
1127
+ selectionReasonCode: 'REVIEW_CAPABILITY_SELECTION_REQUIRED',
1128
+ }
1129
+ }
1130
+
1131
+ /**
1132
+ * Resolve native-hook projection eligibility from the same provider registry and review-binding
1133
+ * authority used at runtime. Both the adapter generator and the event dispatcher consume this
1134
+ * function so a batch cannot silently select a different descriptor set than its generated view.
1135
+ */
1136
+ export function resolveProviderHookEligibility({
1137
+ registry,
1138
+ providerId,
1139
+ descriptor,
1140
+ hasUsableVersionedTranscript,
1141
+ allowDeferredSelection = false,
1142
+ } = {}) {
1143
+ object(registry, 'HOOK_ELIGIBILITY_REGISTRY_INVALID', 'provider registry')
1144
+ object(descriptor, 'HOOK_ELIGIBILITY_DESCRIPTOR_INVALID', 'hook descriptor')
1145
+ if (typeof hasUsableVersionedTranscript !== 'function') {
1146
+ block('HOOK_ELIGIBILITY_TRANSCRIPT_CONTRACT_INVALID', 'versioned transcript predicate is unavailable')
1147
+ }
1148
+ const provider = providerById(registry, providerId, 'hook')
1149
+ if (descriptor.transcript === 'stable-required'
1150
+ && !hasUsableVersionedTranscript(provider.runtime?.transcript)) {
1151
+ return {
1152
+ eligible: false,
1153
+ reasonCode: 'STABLE_TRANSCRIPT_CONTRACT_UNAVAILABLE',
1154
+ detail: `${providerId} does not declare a tested versioned native transcript contract`,
1155
+ peer: null,
1156
+ }
1157
+ }
1158
+
1159
+ const requirements = descriptor.requires || []
1160
+ if (!requirements.length) return { eligible: true, reasonCode: null, detail: null, peer: null }
1161
+ let resolved = null
1162
+ try {
1163
+ resolved = resolveProviderReviewBinding({
1164
+ registry,
1165
+ skill: descriptor.reviewSkill,
1166
+ selfProviderId: providerId,
1167
+ requireCertificationContract: ['deep-audit-cross-codex', 'independent-review'].includes(descriptor.reviewSkill),
1168
+ })
1169
+ } catch (error) {
1170
+ if (requirements.includes('peer-review-binding') || requirements.includes('peer-cli')) {
1171
+ return {
1172
+ eligible: false,
1173
+ reasonCode: error.code || 'PEER_REVIEW_BINDING_UNAVAILABLE',
1174
+ detail: `${providerId} has no distinct registered ${descriptor.reviewSkill} peer`,
1175
+ peer: null,
1176
+ }
1177
+ }
1178
+ throw error
1179
+ }
1180
+ if (!resolved.peer && (requirements.includes('peer-review-binding') || requirements.includes('peer-cli'))) {
1181
+ if (allowDeferredSelection) {
1182
+ return {
1183
+ eligible: true,
1184
+ reasonCode: null,
1185
+ detail: null,
1186
+ peer: null,
1187
+ selectionStatus: 'deferred-to-review-prepare',
1188
+ selectionPolicy: resolved.binding.selectionPolicy,
1189
+ reviewClass: resolved.binding.reviewClass,
1190
+ }
1191
+ }
1192
+ return {
1193
+ eligible: false,
1194
+ reasonCode: resolved.selectionReasonCode || 'REVIEW_CAPABILITY_SELECTION_REQUIRED',
1195
+ detail: `${providerId} requires a distinct certified capability selection at review prepare time`,
1196
+ peer: null,
1197
+ selectionPolicy: resolved.binding.selectionPolicy,
1198
+ reviewClass: resolved.binding.reviewClass,
1199
+ }
1200
+ }
1201
+ if (requirements.includes('peer-cli')) {
1202
+ const cli = resolved.peer?.runtime?.cli
1203
+ if (!cli?.executable
1204
+ || !cli?.localExecutable
1205
+ || !cli?.replyArtifactPrefix
1206
+ || !cli?.briefInvocationMarkers?.length
1207
+ || !cli?.discoveryMarkers?.length) {
1208
+ return {
1209
+ eligible: false,
1210
+ reasonCode: 'PEER_CLI_METADATA_UNAVAILABLE',
1211
+ detail: `${providerId} peer ${resolved.peer?.id || '<missing>'} has no complete CLI/reply/discovery metadata`,
1212
+ peer: null,
1213
+ }
1214
+ }
1215
+ }
1216
+ return {
1217
+ eligible: true,
1218
+ reasonCode: null,
1219
+ detail: null,
1220
+ peer: resolved.peer,
1221
+ }
1222
+ }
1223
+
1224
+ export function compatibilityProviderIdForAdapter(compatibilityMatrix, adapterProviderId) {
1225
+ object(compatibilityMatrix, 'REVIEW_COMPATIBILITY_INVALID', 'compatibility matrix')
1226
+ object(compatibilityMatrix.providers, 'REVIEW_COMPATIBILITY_INVALID', 'compatibility matrix providers')
1227
+ const matches = Object.entries(compatibilityMatrix.providers)
1228
+ .filter(([, record]) => record?.adapterProviderId === adapterProviderId)
1229
+ .map(([providerId]) => providerId)
1230
+ if (matches.length !== 1) {
1231
+ block('REVIEW_COMPATIBILITY_UNAVAILABLE', `adapter provider must map to exactly one compatibility provider:${adapterProviderId}`)
1232
+ }
1233
+ return matches[0]
1234
+ }
1235
+
1236
+ export function reviewTargetIdentity(target) {
1237
+ object(target, 'REVIEW_TARGET_INVALID', 'review target')
1238
+ if (!TARGET_ID.test(target.id ?? '')) block('REVIEW_TARGET_INVALID', `review target id is invalid:${target.id ?? '<missing>'}`)
1239
+ const result = { id: target.id }
1240
+ for (const axis of REVIEW_TARGET_AXES) result[axis] = nonEmpty(target[axis], 'REVIEW_TARGET_INVALID', `review target.${axis}`)
1241
+ return result
1242
+ }
1243
+
1244
+ export function certificationAggregateStatus(certification, { now = new Date() } = {}) {
1245
+ object(certification, 'REVIEW_CERTIFICATION_INVALID', 'certification')
1246
+ if (!(now instanceof Date) || !Number.isFinite(now.getTime())) block('REVIEW_TIME_INVALID', 'certification clock is invalid')
1247
+ if (!Array.isArray(certification.platformMatrix) || certification.platformMatrix.length === 0) {
1248
+ block('REVIEW_CERTIFICATION_INVALID', `${certification.id ?? '<unknown>'} has no platform targets`)
1249
+ }
1250
+ const targets = certification.platformMatrix.filter((target) => target.status !== 'unsupported')
1251
+ if (targets.length === 0) return 'not-applicable'
1252
+ let certified = 0
1253
+ let expired = 0
1254
+ for (const target of targets) {
1255
+ if (target.status !== 'certified') continue
1256
+ const expiresAt = target.expiresAt ?? certification.expiresAt
1257
+ if (typeof expiresAt === 'string' && Number.isFinite(Date.parse(expiresAt)) && Date.parse(expiresAt) <= now.getTime()) expired += 1
1258
+ else certified += 1
1259
+ }
1260
+ if (certified === targets.length) return 'certified'
1261
+ if (certified > 0) return 'conditional'
1262
+ if (expired > 0 && expired === targets.length) return 'expired'
1263
+ return 'not-certified'
1264
+ }
1265
+
1266
+ function certificationRecords(ledger) {
1267
+ if (Array.isArray(ledger)) return ledger
1268
+ object(ledger, 'REVIEW_CERTIFICATION_LEDGER_INVALID', 'certification ledger')
1269
+ if (!Array.isArray(ledger.certifications)) block('REVIEW_CERTIFICATION_LEDGER_INVALID', 'certification ledger records must be an array')
1270
+ return ledger.certifications
1271
+ }
1272
+
1273
+ export function verifyExactProviderCertification({
1274
+ certificationLedger,
1275
+ compatibilityProviderId,
1276
+ runtimeProviderId,
1277
+ runtimeProfileId = runtimeProviderId,
1278
+ runtimeKind,
1279
+ surface,
1280
+ repositoryRole,
1281
+ target,
1282
+ expectedGitTree = null,
1283
+ now = new Date(),
1284
+ requireEvidence = true,
1285
+ } = {}) {
1286
+ if (!(now instanceof Date) || !Number.isFinite(now.getTime())) block('REVIEW_TIME_INVALID', 'certification clock is invalid')
1287
+ for (const [value, label] of [
1288
+ [compatibilityProviderId, 'provider'], [runtimeProviderId, 'runtimeProviderId'], [runtimeKind, 'runtimeKind'],
1289
+ [runtimeProfileId, 'runtimeProfileId'], [surface, 'surface'], [repositoryRole, 'repositoryRole'],
1290
+ ]) nonEmpty(value, 'REVIEW_CERTIFICATION_REQUEST_INVALID', label)
1291
+ const identity = reviewTargetIdentity(target)
1292
+ const records = certificationRecords(certificationLedger).filter((record) => (
1293
+ record?.provider === compatibilityProviderId
1294
+ && record.runtimeKind === runtimeKind
1295
+ && record.surface === surface
1296
+ && record.repositoryRole === repositoryRole
1297
+ ))
1298
+ if (records.length !== 1) {
1299
+ block(records.length ? 'REVIEW_CERTIFICATION_AMBIGUOUS' : 'REVIEW_CERTIFICATION_MISSING', `${compatibilityProviderId}/${runtimeKind}/${surface}/${repositoryRole}`)
1300
+ }
1301
+ const record = records[0]
1302
+ if (record.status === 'expired') block('REVIEW_CERTIFICATION_EXPIRED', `${record.id}:${record.status}`)
1303
+ if (!['certified', 'conditional'].includes(record.status)) block('REVIEW_NOT_CERTIFIED', `${record.id}:${record.status}`)
1304
+ const matches = record.platformMatrix.filter((candidate) => candidate?.id === identity.id)
1305
+ if (matches.length !== 1) block('REVIEW_TARGET_UNCERTIFIED', `${record.id}/${identity.id}`)
1306
+ const certifiedTarget = matches[0]
1307
+ for (const axis of REVIEW_TARGET_AXES) {
1308
+ if (certifiedTarget[axis] !== identity[axis]) {
1309
+ block('REVIEW_TARGET_AXES_MISMATCH', `${record.id}/${identity.id}/${axis}:${identity[axis]}!=${certifiedTarget[axis]}`)
1310
+ }
1311
+ }
1312
+ if (certifiedTarget.status !== 'certified') block('REVIEW_TARGET_UNCERTIFIED', `${record.id}/${identity.id}:${certifiedTarget.status}`)
1313
+ const certifiedAt = certifiedTarget.certifiedAt ?? record.certifiedAt
1314
+ const expiresAt = certifiedTarget.expiresAt ?? record.expiresAt
1315
+ if (!Number.isFinite(Date.parse(certifiedAt ?? '')) || !Number.isFinite(Date.parse(expiresAt ?? ''))) {
1316
+ block('REVIEW_CERTIFICATION_DATES_INVALID', `${record.id}/${identity.id}`)
1317
+ }
1318
+ if (Date.parse(expiresAt) <= Date.parse(certifiedAt)) block('REVIEW_CERTIFICATION_DATES_INVALID', `${record.id}/${identity.id}:expiry ordering`)
1319
+ if (Date.parse(expiresAt) <= now.getTime()) block('REVIEW_CERTIFICATION_EXPIRED', `${record.id}/${identity.id}`)
1320
+ const aggregate = certificationAggregateStatus(record, { now })
1321
+ if (!['certified', 'conditional'].includes(aggregate)) block('REVIEW_NOT_CERTIFIED', `${record.id}:${record.status}/${aggregate}`)
1322
+ const evidence = certifiedTarget.runtimeEvidence ?? record.runtimeEvidence ?? null
1323
+ if (requireEvidence && (!evidence || typeof evidence !== 'object' || Array.isArray(evidence))) {
1324
+ block('REVIEW_CERTIFICATION_EVIDENCE_MISSING', `${record.id}/${identity.id}`)
1325
+ }
1326
+ if (evidence) {
1327
+ const observedRuntimeIdentity = evidence.profileId ?? evidence.providerId
1328
+ const expectedRuntimeIdentity = evidence.profileId === undefined ? runtimeProviderId : runtimeProfileId
1329
+ if (observedRuntimeIdentity !== expectedRuntimeIdentity) block('REVIEW_CERTIFICATION_EVIDENCE_PROVIDER_MISMATCH', `${record.id}/${identity.id}`)
1330
+ if (evidence.targetId !== identity.id) block('REVIEW_CERTIFICATION_EVIDENCE_TARGET_MISMATCH', `${record.id}/${identity.id}`)
1331
+ for (const axis of REVIEW_TARGET_AXES) {
1332
+ if (evidence[axis] !== identity[axis]) block('REVIEW_CERTIFICATION_EVIDENCE_AXES_MISMATCH', `${record.id}/${identity.id}/${axis}`)
1333
+ }
1334
+ if (expectedGitTree !== null && evidence.gitTree !== expectedGitTree) {
1335
+ block('REVIEW_CERTIFICATION_STALE', `${record.id}/${identity.id}`)
1336
+ }
1337
+ }
1338
+ return {
1339
+ certificationId: record.id,
1340
+ certificationStatus: record.status,
1341
+ aggregateStatus: aggregate,
1342
+ compatibilityProviderId,
1343
+ runtimeProviderId,
1344
+ runtimeKind,
1345
+ surface,
1346
+ repositoryRole,
1347
+ target: identity,
1348
+ targetDigest: digest(identity),
1349
+ certifiedAt,
1350
+ expiresAt,
1351
+ evidence,
1352
+ record,
1353
+ recordDigest: digest(record),
1354
+ }
1355
+ }
1356
+
1357
+ function canonicalIsoTime(value, code, label) {
1358
+ if (typeof value !== 'string'
1359
+ || !Number.isFinite(Date.parse(value))
1360
+ || new Date(Date.parse(value)).toISOString() !== value) {
1361
+ block(code, `${label} is not a canonical ISO timestamp`)
1362
+ }
1363
+ return value
1364
+ }
1365
+
1366
+ function reviewCapabilityEvidenceProjection(value) {
1367
+ const { evidenceDigest: ignoredEvidenceDigest, ...projection } = value
1368
+ return projection
1369
+ }
1370
+
1371
+ function reviewCapabilityEvidenceBytes(value) {
1372
+ return Buffer.from(`${JSON.stringify(stableValue(value))}\n`, 'utf8')
1373
+ }
1374
+
1375
+ function reviewCapabilityCertificationRecord({
1376
+ certificationId,
1377
+ profile,
1378
+ capability,
1379
+ certifiedAt,
1380
+ expiresAt,
1381
+ evidenceReference,
1382
+ evidenceSha256,
1383
+ }) {
1384
+ return {
1385
+ id: certificationId,
1386
+ reviewProfileId: profile.id,
1387
+ reviewProfileDigest: digest(profile),
1388
+ providerId: profile.providerId,
1389
+ modelReleaseId: profile.modelReleaseId,
1390
+ entitlementId: profile.entitlementId,
1391
+ status: 'certified',
1392
+ assuranceTier: capability.assuranceTier,
1393
+ reasoningTier: capability.reasoningTier,
1394
+ computeTier: capability.computeTier,
1395
+ certifiedAt,
1396
+ expiresAt,
1397
+ evidence: {
1398
+ reference: evidenceReference,
1399
+ sha256: evidenceSha256,
1400
+ },
1401
+ }
1402
+ }
1403
+
1404
+ function exactFlagValue(args, flag, expected, code, label) {
1405
+ const indexes = args.flatMap((value, index) => value === flag ? [index] : [])
1406
+ if (indexes.length !== 1 || args[indexes[0] + 1] !== expected) {
1407
+ block(code, `${label} does not bind ${flag}=${JSON.stringify(expected)}`)
1408
+ }
1409
+ }
1410
+
1411
+ function verifySignedReviewCapabilityProbe({
1412
+ runtimeEvidenceBytes,
1413
+ capabilityRegistry,
1414
+ invocationProfile,
1415
+ profile,
1416
+ capability,
1417
+ target,
1418
+ } = {}) {
1419
+ let evidence
1420
+ try {
1421
+ evidence = JSON.parse(evidenceBytes(runtimeEvidenceBytes).toString('utf8'))
1422
+ } catch {
1423
+ block('REVIEW_CAPABILITY_PROBE_INVALID', `${profile.id}:runtime evidence is not JSON`)
1424
+ }
1425
+ const providerMatches = (evidence.providers || []).filter(
1426
+ (provider) => provider?.id === invocationProfile.availabilityEvidence.providerEvidenceId,
1427
+ )
1428
+ const distribution = providerMatches[0]?.tool?.distribution
1429
+ if (providerMatches.length !== 1
1430
+ || providerMatches[0].status !== 'pass'
1431
+ || distribution?.resolutionStatus !== 'pass'
1432
+ || distribution.distributionVersion !== target.distributionVersion
1433
+ || !/^sha256:[a-f0-9]{64}$/.test(distribution.authorityDigest ?? '')) {
1434
+ block('REVIEW_CAPABILITY_PROBE_INVALID', `${profile.id}:signed exact runtime evidence is absent or failed`)
1435
+ }
1436
+ const candidates = reviewProfileRecords(capabilityRegistry)
1437
+ .filter((candidate) => (
1438
+ candidate.providerId === profile.providerId
1439
+ && candidate.routeClass === 'subscription-entitlement'
1440
+ && candidate.entitlementId === profile.entitlementId
1441
+ && candidate.invocationProfileId === profile.invocationProfileId
1442
+ ))
1443
+ .map((candidate) => ({
1444
+ profile: candidate,
1445
+ capability: providerCapabilityForProfile(capabilityRegistry, candidate),
1446
+ }))
1447
+ .sort((left, right) => (
1448
+ right.capability.capabilityRank - left.capability.capabilityRank
1449
+ || compareUtf8Bytes(left.profile.id, right.profile.id)
1450
+ ))
1451
+ const selectedIndex = candidates.findIndex(
1452
+ (candidate) => candidate.profile.id === profile.id,
1453
+ )
1454
+ if (selectedIndex < 0) {
1455
+ block('REVIEW_CAPABILITY_PROBE_INVALID', `${profile.id}:candidate schedule is incomplete`)
1456
+ }
1457
+ const probeRows = candidates.slice(0, selectedIndex + 1).map((candidate, ordinal) => {
1458
+ const candidateProfile = candidate.profile
1459
+ const checkId = `review-capability-${candidateProfile.id}`
1460
+ const checkMatches = (providerMatches[0].checks || [])
1461
+ .filter((check) => check?.id === checkId)
1462
+ const check = checkMatches[0]
1463
+ const args = check?.command?.arguments
1464
+ const selectedCandidate = candidateProfile.id === profile.id
1465
+ const assertions = new Map(
1466
+ (check?.result?.assertions || [])
1467
+ .map((assertion) => [assertion?.id, assertion?.pass]),
1468
+ )
1469
+ if (checkMatches.length !== 1
1470
+ || check.driver !== 'claude-review-capability-probe'
1471
+ || check.certificationImpact !== 'capability-only'
1472
+ || check.command?.executable
1473
+ !== invocationProfile.deploymentAdapter.executable
1474
+ || check.command.cwd !== '<fixture>'
1475
+ || check.command.stdin !== 'sha256'
1476
+ || !Array.isArray(args)) {
1477
+ block('REVIEW_CAPABILITY_PROBE_INVALID',
1478
+ `${candidateProfile.id}:signed exact candidate outcome is absent or failed`)
1479
+ }
1480
+ if (check.status !== 'pass') {
1481
+ block(
1482
+ selectedCandidate
1483
+ ? 'REVIEW_CAPABILITY_PROBE_INVALID'
1484
+ : 'REVIEW_HIGHER_CAPABILITY_OUTCOME_UNVERIFIED',
1485
+ `${candidateProfile.id}:candidate probe is transient, quota/capacity/auth blocked, timed out, or otherwise unverified`,
1486
+ )
1487
+ }
1488
+ if (assertions.get('review-capability-profile-observed') !== true
1489
+ || assertions.get('review-capability-maximum-compute-observed') !== true
1490
+ || assertions.get('review-capability-isolated-no-tools-route-observed') !== true) {
1491
+ block('REVIEW_CAPABILITY_PROBE_INVALID',
1492
+ `${candidateProfile.id}:successful candidate outcome lacks exact profile/compute/isolation evidence`)
1493
+ }
1494
+ exactFlagValue(args, '--model', candidateProfile.requestModelId,
1495
+ 'REVIEW_CAPABILITY_PROBE_INVALID', candidateProfile.id)
1496
+ exactFlagValue(args, '--effort', invocationProfile.deploymentAdapter
1497
+ .effortByComputeTier[candidate.capability.computeTier],
1498
+ 'REVIEW_CAPABILITY_PROBE_INVALID', candidateProfile.id)
1499
+ exactFlagValue(args, '--tools', '',
1500
+ 'REVIEW_CAPABILITY_PROBE_INVALID', candidateProfile.id)
1501
+ exactFlagValue(args, '--mcp-config', '{"mcpServers":{}}',
1502
+ 'REVIEW_CAPABILITY_PROBE_INVALID', candidateProfile.id)
1503
+ exactFlagValue(args, '--permission-mode', 'plan',
1504
+ 'REVIEW_CAPABILITY_PROBE_INVALID', candidateProfile.id)
1505
+ for (const required of [
1506
+ '--no-session-persistence',
1507
+ '--strict-mcp-config',
1508
+ '--safe-mode',
1509
+ '--no-chrome',
1510
+ ]) {
1511
+ if (args.filter((value) => value === required).length !== 1) {
1512
+ block('REVIEW_CAPABILITY_PROBE_INVALID',
1513
+ `${candidateProfile.id} lacks exact ${required}`)
1514
+ }
1515
+ }
1516
+ if (args.some((value) => (
1517
+ [
1518
+ '--fallback-model',
1519
+ '--resume',
1520
+ '--continue',
1521
+ '--max-budget-usd',
1522
+ ].includes(value)
1523
+ ))) {
1524
+ block('REVIEW_CAPABILITY_PROBE_INVALID',
1525
+ `${candidateProfile.id} capability probe permits fallback or session reuse`)
1526
+ }
1527
+ const available =
1528
+ assertions.get('review-capability-outcome-available') === true
1529
+ && assertions.get('review-capability-model-usage-exact') === true
1530
+ const permanentlyUnavailable =
1531
+ assertions.get('review-capability-outcome-permanently-unavailable') === true
1532
+ && assertions.get('review-capability-machine-readable-unavailability-observed') === true
1533
+ if (available === permanentlyUnavailable) {
1534
+ block('REVIEW_CAPABILITY_PROBE_INVALID',
1535
+ `${candidateProfile.id}:candidate outcome is ambiguous`)
1536
+ }
1537
+ if ((selectedCandidate && !available)
1538
+ || (!selectedCandidate && !permanentlyUnavailable)) {
1539
+ block(
1540
+ selectedCandidate
1541
+ ? 'REVIEW_CAPABILITY_PROBE_INVALID'
1542
+ : (available
1543
+ ? 'REVIEW_HIGHER_CAPABILITY_AVAILABLE'
1544
+ : 'REVIEW_HIGHER_CAPABILITY_OUTCOME_UNVERIFIED'),
1545
+ `${candidateProfile.id}:${selectedCandidate ? 'selected-not-available' : (available ? 'higher-candidate-available' : 'higher-candidate-not-permanently-unavailable')}`,
1546
+ )
1547
+ }
1548
+ return {
1549
+ ordinal,
1550
+ reviewProfileId: candidateProfile.id,
1551
+ modelReleaseId: candidateProfile.modelReleaseId,
1552
+ requestModelId: candidateProfile.requestModelId,
1553
+ capabilityRank: candidate.capability.capabilityRank,
1554
+ checkId,
1555
+ outcome: available ? 'available' : 'permanently-unavailable',
1556
+ checkDigest: digest(check),
1557
+ }
1558
+ })
1559
+ const checkId = `review-capability-${profile.id}`
1560
+ const selectedRow = probeRows[probeRows.length - 1]
1561
+ const candidateSet = candidates.map(({ profile: candidateProfile, capability: row }) => ({
1562
+ reviewProfileId: candidateProfile.id,
1563
+ modelReleaseId: candidateProfile.modelReleaseId,
1564
+ requestModelId: candidateProfile.requestModelId,
1565
+ capabilityRank: row.capabilityRank,
1566
+ }))
1567
+ const projection = {
1568
+ reviewProfileId: profile.id,
1569
+ requestModelId: profile.requestModelId,
1570
+ computeTier: capability.computeTier,
1571
+ effort: invocationProfile.deploymentAdapter.effortByComputeTier[capability.computeTier],
1572
+ checkId,
1573
+ checkDigest: selectedRow.checkDigest,
1574
+ candidateSetDigest: digest(candidateSet),
1575
+ orderedProbeRows: probeRows,
1576
+ orderedProbeSetDigest: digest(probeRows),
1577
+ runtimeExecutableAuthorityDigest: distribution.authorityDigest.slice('sha256:'.length),
1578
+ distributionVersion: distribution.distributionVersion,
1579
+ }
1580
+ return {
1581
+ ...projection,
1582
+ capabilityProbeDigest: digest(projection),
1583
+ }
1584
+ }
1585
+
1586
+ /**
1587
+ * Prepare a deterministic capability-certification carrier from an already
1588
+ * promoted exact runtime certification. The function does not grant trust to
1589
+ * an unsigned runtime observation: the existing provider certification ledger
1590
+ * and its content-addressed runtime evidence remain the trust root. The tier
1591
+ * assertion becomes authoritative only when the returned record is reviewed
1592
+ * and materialized in the canonical capability ledger.
1593
+ */
1594
+ export function prepareReviewCapabilityCertification({
1595
+ registry,
1596
+ capabilityRegistry,
1597
+ invocationRegistry,
1598
+ modelReleaseRegistry,
1599
+ runtimeCertificationLedger,
1600
+ reviewProfileId,
1601
+ certificationId,
1602
+ capability,
1603
+ target,
1604
+ expectedGitTree,
1605
+ runtimeEvidenceBytes,
1606
+ certifiedAt,
1607
+ expiresAt,
1608
+ now = new Date(),
1609
+ } = {}) {
1610
+ if (!(now instanceof Date) || !Number.isFinite(now.getTime())) {
1611
+ block('REVIEW_TIME_INVALID', 'capability certification clock is invalid')
1612
+ }
1613
+ if (!REVIEW_PROFILE_ID.test(reviewProfileId ?? '')
1614
+ || !REVIEW_PROFILE_ID.test(certificationId ?? '')) {
1615
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${certificationId ?? '<missing>'}/${reviewProfileId ?? '<missing>'}`)
1616
+ }
1617
+ exactObjectKeys(capability, [
1618
+ 'assuranceTier',
1619
+ 'reasoningTier',
1620
+ 'computeTier',
1621
+ 'exchangeBudget',
1622
+ ], 'REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${certificationId} capability`)
1623
+ for (const [field, value] of Object.entries(capability)
1624
+ .filter(([key]) => key !== 'exchangeBudget')) {
1625
+ if (!REVIEW_TIERS.includes(value)) {
1626
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${certificationId}/${field}:${value ?? '<missing>'}`)
1627
+ }
1628
+ }
1629
+ exactObjectKeys(capability.exchangeBudget, [
1630
+ 'maxInputBytes',
1631
+ 'maxOutputBytes',
1632
+ 'maxPayloadBytes',
1633
+ ], 'REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${certificationId} exchange budget`)
1634
+ const { maxInputBytes, maxOutputBytes, maxPayloadBytes } = capability.exchangeBudget
1635
+ if (!Number.isSafeInteger(maxInputBytes) || maxInputBytes <= 0
1636
+ || !Number.isSafeInteger(maxOutputBytes) || maxOutputBytes <= 0
1637
+ || !Number.isSafeInteger(maxPayloadBytes)
1638
+ || maxPayloadBytes < maxInputBytes + maxOutputBytes) {
1639
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${certificationId}:exchange budget`)
1640
+ }
1641
+ canonicalIsoTime(certifiedAt, 'REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${certificationId}.certifiedAt`)
1642
+ canonicalIsoTime(expiresAt, 'REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${certificationId}.expiresAt`)
1643
+ if (Date.parse(certifiedAt) > now.getTime()
1644
+ || Date.parse(expiresAt) <= Date.parse(certifiedAt)
1645
+ || Date.parse(expiresAt) <= now.getTime()) {
1646
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${certificationId}:validity window`)
1647
+ }
1648
+ const profiles = reviewProfileRecords(capabilityRegistry)
1649
+ const matchingProfiles = profiles.filter((profile) => profile.id === reviewProfileId)
1650
+ if (matchingProfiles.length !== 1) {
1651
+ block('REVIEW_CAPABILITY_PROFILE_INVALID', reviewProfileId)
1652
+ }
1653
+ const profile = matchingProfiles[0]
1654
+ const providerCapability = providerCapabilityForProfile(capabilityRegistry, profile)
1655
+ const governedCapability = {
1656
+ assuranceTier: providerCapability.assuranceTier,
1657
+ reasoningTier: providerCapability.reasoningTier,
1658
+ computeTier: providerCapability.computeTier,
1659
+ exchangeBudget: stableValue(providerCapability.exchangeBudget),
1660
+ }
1661
+ if (JSON.stringify(stableValue(capability))
1662
+ !== JSON.stringify(stableValue(governedCapability))) {
1663
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID',
1664
+ `${reviewProfileId}:caller capability differs from reviewed provider-local capability authority`)
1665
+ }
1666
+ const { release, invocationProfile } = validateExactReviewProfile({
1667
+ profile,
1668
+ registry,
1669
+ invocationRegistry,
1670
+ modelReleaseRegistry,
1671
+ })
1672
+ if (profile.routeClass !== 'subscription-entitlement') {
1673
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${reviewProfileId} is not an external entitlement route`)
1674
+ }
1675
+ const availability = verifyEntitlementAvailabilityEvidence({
1676
+ invocationRegistry,
1677
+ invocationProfileId: profile.invocationProfileId,
1678
+ certificationLedger: runtimeCertificationLedger,
1679
+ target,
1680
+ expectedGitTree,
1681
+ runtimeEvidenceBytes,
1682
+ now,
1683
+ })
1684
+ if (availability.providerId !== profile.providerId
1685
+ || availability.entitlementId !== profile.entitlementId
1686
+ || availability.invocationProfileId !== profile.invocationProfileId) {
1687
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${reviewProfileId}:runtime entitlement binding`)
1688
+ }
1689
+ const capabilityProbe = verifySignedReviewCapabilityProbe({
1690
+ runtimeEvidenceBytes,
1691
+ capabilityRegistry,
1692
+ invocationProfile,
1693
+ profile,
1694
+ capability: governedCapability,
1695
+ target,
1696
+ })
1697
+ const effectiveExpiresAt = new Date(Math.min(
1698
+ Date.parse(expiresAt),
1699
+ Date.parse(availability.expiresAt),
1700
+ )).toISOString()
1701
+ if (Date.parse(effectiveExpiresAt) <= Date.parse(certifiedAt)) {
1702
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', `${certificationId}:runtime-bound expiry`)
1703
+ }
1704
+ const projection = {
1705
+ schemaVersion: 1,
1706
+ kind: 'provider-neutral-review-capability-certification-evidence',
1707
+ certificationContract: EXACT_REVIEW_CERTIFICATION_CONTRACT,
1708
+ exchangeCore: PORTABLE_REVIEW_EXCHANGE_CORE,
1709
+ certificationId,
1710
+ reviewProfileId: profile.id,
1711
+ reviewProfileDigest: digest(profile),
1712
+ providerId: profile.providerId,
1713
+ invocationProfileId: profile.invocationProfileId,
1714
+ invocationProfileDigest: digest(invocationProfile),
1715
+ routeClass: profile.routeClass,
1716
+ entitlementId: profile.entitlementId,
1717
+ modelReleaseId: profile.modelReleaseId,
1718
+ requestModelId: profile.requestModelId,
1719
+ modelReleaseDigest: digest(release),
1720
+ capabilityRank: providerCapability.capabilityRank,
1721
+ capability: stableValue(governedCapability),
1722
+ capabilityProbe,
1723
+ certifiedAt,
1724
+ expiresAt: effectiveExpiresAt,
1725
+ runtimeBinding: {
1726
+ compatibilityProviderId: invocationProfile.availabilityEvidence.compatibilityProviderId,
1727
+ runtimeProviderId: availability.runtimeProviderId,
1728
+ runtimeProfileId: availability.runtimeProfileId,
1729
+ runtimeKind: availability.runtimeKind,
1730
+ surface: availability.runtimeSurface,
1731
+ repositoryRole: availability.repositoryRole,
1732
+ certificationId: availability.runtimeCertificationId,
1733
+ certificationDigest: availability.runtimeCertificationDigest,
1734
+ target: stableValue(availability.target),
1735
+ targetDigest: availability.targetDigest,
1736
+ evidenceReference: availability.evidence.reference,
1737
+ evidenceSha256: availability.evidence.sha256,
1738
+ runtimeEvidenceDigest: availability.runtimeEvidenceDigest,
1739
+ runtimeExecutableAuthorityDigest:
1740
+ capabilityProbe.runtimeExecutableAuthorityDigest,
1741
+ capabilityProbeDigest: capabilityProbe.capabilityProbeDigest,
1742
+ },
1743
+ }
1744
+ const evidence = {
1745
+ ...projection,
1746
+ evidenceDigest: digest(projection),
1747
+ }
1748
+ const bytes = reviewCapabilityEvidenceBytes(evidence)
1749
+ const evidenceSha256 = contentSha256(bytes)
1750
+ const evidenceReference =
1751
+ `infra/governance/evidence/review-capability/${evidenceSha256}.json`
1752
+ const certification = reviewCapabilityCertificationRecord({
1753
+ certificationId,
1754
+ profile,
1755
+ capability,
1756
+ certifiedAt,
1757
+ expiresAt: effectiveExpiresAt,
1758
+ evidenceReference,
1759
+ evidenceSha256,
1760
+ })
1761
+ return Object.freeze({
1762
+ evidence: Object.freeze(evidence),
1763
+ evidenceBytes: bytes,
1764
+ evidenceSha256,
1765
+ evidenceReference,
1766
+ certification: Object.freeze(certification),
1767
+ })
1768
+ }
1769
+
1770
+ export function materializeReviewCapabilityCertification({
1771
+ capabilityCertificationLedger,
1772
+ prepared,
1773
+ } = {}) {
1774
+ capabilityCertificationRecords(capabilityCertificationLedger)
1775
+ object(prepared, 'REVIEW_CAPABILITY_CERTIFICATION_INVALID', 'prepared capability certification')
1776
+ if (!Buffer.isBuffer(prepared.evidenceBytes)
1777
+ || prepared.evidenceBytes.length === 0
1778
+ || prepared.evidenceSha256 !== contentSha256(prepared.evidenceBytes)
1779
+ || prepared.evidenceReference
1780
+ !== `infra/governance/evidence/review-capability/${prepared.evidenceSha256}.json`
1781
+ || prepared.certification?.evidence?.reference !== prepared.evidenceReference
1782
+ || prepared.certification?.evidence?.sha256 !== prepared.evidenceSha256) {
1783
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', 'prepared evidence is not content-addressed')
1784
+ }
1785
+ let decoded
1786
+ try {
1787
+ decoded = JSON.parse(prepared.evidenceBytes.toString('utf8'))
1788
+ } catch {
1789
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', 'prepared evidence is invalid JSON')
1790
+ }
1791
+ if (JSON.stringify(stableValue(decoded)) !== JSON.stringify(stableValue(prepared.evidence))
1792
+ || decoded?.schemaVersion !== 1
1793
+ || decoded.kind !== 'provider-neutral-review-capability-certification-evidence'
1794
+ || decoded.certificationContract !== EXACT_REVIEW_CERTIFICATION_CONTRACT
1795
+ || decoded.exchangeCore !== PORTABLE_REVIEW_EXCHANGE_CORE
1796
+ || decoded.evidenceDigest !== digest(reviewCapabilityEvidenceProjection(decoded))
1797
+ || decoded.certificationId !== prepared.certification?.id
1798
+ || decoded.reviewProfileId !== prepared.certification?.reviewProfileId
1799
+ || decoded.reviewProfileDigest !== prepared.certification?.reviewProfileDigest
1800
+ || decoded.providerId !== prepared.certification?.providerId
1801
+ || decoded.modelReleaseId !== prepared.certification?.modelReleaseId
1802
+ || decoded.entitlementId !== prepared.certification?.entitlementId
1803
+ || decoded.certifiedAt !== prepared.certification?.certifiedAt
1804
+ || decoded.expiresAt !== prepared.certification?.expiresAt
1805
+ || decoded.capability?.assuranceTier !== prepared.certification?.assuranceTier
1806
+ || decoded.capability?.reasoningTier !== prepared.certification?.reasoningTier
1807
+ || decoded.capability?.computeTier !== prepared.certification?.computeTier) {
1808
+ block('REVIEW_CAPABILITY_CERTIFICATION_INVALID', 'prepared evidence/ledger projection mismatches')
1809
+ }
1810
+ const current = capabilityCertificationLedger.certifications
1811
+ const sameId = current.filter((record) => record.id === prepared.certification.id)
1812
+ if (sameId.length > 1) {
1813
+ block('REVIEW_CAPABILITY_CERTIFICATION_AMBIGUOUS', prepared.certification.id)
1814
+ }
1815
+ if (sameId.length === 1) {
1816
+ if (JSON.stringify(stableValue(sameId[0]))
1817
+ !== JSON.stringify(stableValue(prepared.certification))) {
1818
+ block('REVIEW_CAPABILITY_CERTIFICATION_SUBSTITUTED', prepared.certification.id)
1819
+ }
1820
+ return capabilityCertificationLedger
1821
+ }
1822
+ const overlapping = current.filter((record) => (
1823
+ record.reviewProfileId === prepared.certification.reviewProfileId
1824
+ && record.status === 'certified'
1825
+ && Date.parse(record.expiresAt) > Date.parse(prepared.certification.certifiedAt)
1826
+ && Date.parse(record.certifiedAt) < Date.parse(prepared.certification.expiresAt)
1827
+ ))
1828
+ if (overlapping.length > 0) {
1829
+ block('REVIEW_CAPABILITY_CERTIFICATION_AMBIGUOUS', prepared.certification.reviewProfileId)
1830
+ }
1831
+ const next = {
1832
+ ...capabilityCertificationLedger,
1833
+ certifications: [...current, prepared.certification]
1834
+ .sort((left, right) => compareUtf8Bytes(left.id, right.id)),
1835
+ }
1836
+ capabilityCertificationRecords(next)
1837
+ return next
1838
+ }
1839
+
1840
+ function genuineReceiptProjection(receipt) {
1841
+ const { receiptDigest: ignoredReceiptDigest, ...projection } = receipt
1842
+ return projection
1843
+ }
1844
+
1845
+ export function validateGenuineCrossProviderReviewReceipt(receipt) {
1846
+ exactObjectKeys(receipt, [
1847
+ 'schemaVersion',
1848
+ 'kind',
1849
+ 'protocol',
1850
+ 'exchangeCore',
1851
+ 'assurance',
1852
+ 'authorProviderId',
1853
+ 'reviewerProviderId',
1854
+ 'reviewProfileId',
1855
+ 'invocationProfileId',
1856
+ 'modelReleaseId',
1857
+ 'requestModelId',
1858
+ 'observedResponseModelId',
1859
+ 'selectionDigest',
1860
+ 'capabilityCertificationId',
1861
+ 'capabilityCertificationDigest',
1862
+ 'capabilityEvidenceDigest',
1863
+ 'runtimeCertificationId',
1864
+ 'runtimeCertificationDigest',
1865
+ 'runtimeTargetDigest',
1866
+ 'structuralCompletionDigest',
1867
+ 'exchangeScheduleDigest',
1868
+ 'capabilityBudgetDigest',
1869
+ 'aggregateVerdict',
1870
+ 'taskRootVerdictSetDigest',
1871
+ 'requestCount',
1872
+ 'responseDigestSetDigest',
1873
+ 'executionEvidenceDigest',
1874
+ 'fullNoSampleClosure',
1875
+ 'genuineCrossProviderReview',
1876
+ 'promotionEligible',
1877
+ 'managedEvidence',
1878
+ 'receiptDigest',
1879
+ ], 'REVIEW_GENUINE_RECEIPT_INVALID', 'genuine review receipt')
1880
+ if (receipt.schemaVersion !== 1
1881
+ || receipt.kind !== 'provider-neutral-genuine-cross-provider-review-receipt'
1882
+ || receipt.exchangeCore !== PORTABLE_REVIEW_EXCHANGE_CORE
1883
+ || receipt.assurance !== 'exact-runtime-and-capability-attested'
1884
+ || !PROVIDER_ID.test(receipt.authorProviderId ?? '')
1885
+ || !PROVIDER_ID.test(receipt.reviewerProviderId ?? '')
1886
+ || receipt.authorProviderId === receipt.reviewerProviderId
1887
+ || !REVIEW_PROFILE_ID.test(receipt.reviewProfileId ?? '')
1888
+ || !REVIEW_PROFILE_ID.test(receipt.invocationProfileId ?? '')
1889
+ || !REVIEW_PROFILE_ID.test(receipt.capabilityCertificationId ?? '')
1890
+ || !REVIEW_PROFILE_ID.test(receipt.runtimeCertificationId ?? '')
1891
+ || typeof receipt.modelReleaseId !== 'string'
1892
+ || typeof receipt.requestModelId !== 'string'
1893
+ || receipt.observedResponseModelId !== receipt.requestModelId
1894
+ || !SHA256.test(receipt.selectionDigest ?? '')
1895
+ || !SHA256.test(receipt.capabilityCertificationDigest ?? '')
1896
+ || !SHA256.test(receipt.capabilityEvidenceDigest ?? '')
1897
+ || !SHA256.test(receipt.runtimeCertificationDigest ?? '')
1898
+ || !SHA256.test(receipt.runtimeTargetDigest ?? '')
1899
+ || !SHA256.test(receipt.structuralCompletionDigest ?? '')
1900
+ || !SHA256.test(receipt.exchangeScheduleDigest ?? '')
1901
+ || !SHA256.test(receipt.capabilityBudgetDigest ?? '')
1902
+ || !['verified', 'findings', 'unverifiable'].includes(receipt.aggregateVerdict)
1903
+ || !SHA256.test(receipt.taskRootVerdictSetDigest ?? '')
1904
+ || !Number.isSafeInteger(receipt.requestCount)
1905
+ || receipt.requestCount <= 0
1906
+ || !SHA256.test(receipt.responseDigestSetDigest ?? '')
1907
+ || !SHA256.test(receipt.executionEvidenceDigest ?? '')
1908
+ || receipt.fullNoSampleClosure !== true
1909
+ || receipt.genuineCrossProviderReview !== true
1910
+ || receipt.promotionEligible !== (receipt.aggregateVerdict === 'verified')
1911
+ || receipt.managedEvidence !== false
1912
+ || !SHA256.test(receipt.receiptDigest ?? '')
1913
+ || receipt.receiptDigest !== digest(genuineReceiptProjection(receipt))) {
1914
+ block('REVIEW_GENUINE_RECEIPT_INVALID', 'genuine review receipt identity or digest mismatches')
1915
+ }
1916
+ return true
1917
+ }
1918
+
1919
+ /**
1920
+ * Upgrade a portable structural closure to a genuine review receipt only after
1921
+ * the exact capability selection, runtime certification, response identity,
1922
+ * and every ordered provider invocation are revalidated. This does not rewrite
1923
+ * the structural completion and cannot be used to claim managed execution.
1924
+ */
1925
+ export function buildGenuineCrossProviderReviewReceipt({
1926
+ structuralCompletion,
1927
+ exchangeSchedule,
1928
+ executionEvidence,
1929
+ selectionReceipt,
1930
+ registry,
1931
+ capabilityRegistry,
1932
+ capabilityCertificationLedger,
1933
+ invocationRegistry,
1934
+ modelReleaseRegistry,
1935
+ entitlementAvailability,
1936
+ capabilityEvidenceBytes,
1937
+ runtimeCertificationLedger,
1938
+ runtimeTarget,
1939
+ expectedGitTree,
1940
+ now = new Date(),
1941
+ } = {}) {
1942
+ object(structuralCompletion, 'REVIEW_GENUINE_TRANSITION_BLOCKED', 'structural completion')
1943
+ object(exchangeSchedule, 'REVIEW_GENUINE_TRANSITION_BLOCKED', 'exchange schedule')
1944
+ validateReviewCapabilitySelectionReceipt(selectionReceipt)
1945
+ if (!(now instanceof Date) || !Number.isFinite(now.getTime())) {
1946
+ block('REVIEW_TIME_INVALID', 'genuine review transition clock is invalid')
1947
+ }
1948
+ const selected = selectionReceipt.selected
1949
+ verifyReviewCapabilitySelection({
1950
+ receipt: selectionReceipt,
1951
+ registry,
1952
+ capabilityRegistry,
1953
+ capabilityCertificationLedger,
1954
+ invocationRegistry,
1955
+ modelReleaseRegistry,
1956
+ skill: selectionReceipt.skill,
1957
+ selfProviderId: selectionReceipt.selfProviderId,
1958
+ authorProviderId: selectionReceipt.authorProviderId,
1959
+ requiredEntitlementId: selectionReceipt.requiredEntitlementId,
1960
+ entitlementAvailability,
1961
+ observedProviderId: selected.providerId,
1962
+ observedReviewProfileId: selected.reviewProfileId,
1963
+ observedModelReleaseId: selected.modelReleaseId,
1964
+ observedResponseModelId: selected.requestModelId,
1965
+ now,
1966
+ })
1967
+ const capabilityRecords = capabilityCertificationRecords(capabilityCertificationLedger)
1968
+ const capabilityMatches = capabilityRecords.filter((record) => (
1969
+ record.id === selected.capabilityCertificationId
1970
+ ))
1971
+ if (capabilityMatches.length !== 1
1972
+ || digest(capabilityMatches[0]) !== selectionReceipt.selectedCapabilityCertificationDigest) {
1973
+ block('REVIEW_GENUINE_TRANSITION_BLOCKED', 'selected capability certification is absent or substituted')
1974
+ }
1975
+ const capabilityRecord = capabilityMatches[0]
1976
+ const capabilityBytes = evidenceBytes(capabilityEvidenceBytes)
1977
+ if (contentSha256(capabilityBytes) !== capabilityRecord.evidence.sha256
1978
+ || capabilityRecord.evidence.reference
1979
+ !== `infra/governance/evidence/review-capability/${capabilityRecord.evidence.sha256}.json`) {
1980
+ block('REVIEW_GENUINE_TRANSITION_BLOCKED', 'capability evidence content binding mismatches')
1981
+ }
1982
+ let capabilityEvidence
1983
+ try {
1984
+ capabilityEvidence = JSON.parse(capabilityBytes.toString('utf8'))
1985
+ } catch {
1986
+ block('REVIEW_GENUINE_TRANSITION_BLOCKED', 'capability evidence is invalid JSON')
1987
+ }
1988
+ if (capabilityEvidence?.schemaVersion !== 1
1989
+ || capabilityEvidence.kind !== 'provider-neutral-review-capability-certification-evidence'
1990
+ || capabilityEvidence.evidenceDigest
1991
+ !== digest(reviewCapabilityEvidenceProjection(capabilityEvidence))
1992
+ || capabilityEvidence.certificationId !== capabilityRecord.id
1993
+ || capabilityEvidence.reviewProfileId !== selected.reviewProfileId
1994
+ || capabilityEvidence.reviewProfileDigest !== selectionReceipt.selectedProfileDigest
1995
+ || capabilityEvidence.providerId !== selected.providerId
1996
+ || capabilityEvidence.invocationProfileId !== selected.invocationProfileId
1997
+ || capabilityEvidence.modelReleaseId !== selected.modelReleaseId
1998
+ || capabilityEvidence.requestModelId !== selected.requestModelId
1999
+ || capabilityEvidence.capability?.assuranceTier !== selected.assuranceTier
2000
+ || capabilityEvidence.capability?.reasoningTier !== selected.reasoningTier
2001
+ || capabilityEvidence.capability?.computeTier !== selected.computeTier) {
2002
+ block('REVIEW_GENUINE_TRANSITION_BLOCKED', 'capability evidence is stale or substituted')
2003
+ }
2004
+ const certifiedBudget = capabilityEvidence.capability?.exchangeBudget
2005
+ if (!certifiedBudget
2006
+ || exchangeSchedule.capabilityBudget?.capabilityCertificationId
2007
+ !== capabilityRecord.id
2008
+ || exchangeSchedule.capabilityBudget?.selectedCapabilityCertificationDigest
2009
+ !== selectionReceipt.selectedCapabilityCertificationDigest
2010
+ || exchangeSchedule.capabilityBudget?.maxInputBytes !== certifiedBudget.maxInputBytes
2011
+ || exchangeSchedule.capabilityBudget?.maxOutputBytes !== certifiedBudget.maxOutputBytes
2012
+ || exchangeSchedule.capabilityBudget?.maxPayloadBytes !== certifiedBudget.maxPayloadBytes
2013
+ || exchangeSchedule.capabilityBudgetDigest
2014
+ !== exchangeSchedule.capabilityBudget.capabilityBudgetDigest) {
2015
+ block('REVIEW_GENUINE_TRANSITION_BLOCKED', 'exchange schedule is detached from the certified capability budget')
2016
+ }
2017
+ const invocationProfile = invocationProfileById(
2018
+ invocationRegistry,
2019
+ selected.invocationProfileId,
2020
+ )
2021
+ const runtimeBinding = capabilityEvidence.runtimeBinding
2022
+ const runtimeCertification = verifyExactProviderCertification({
2023
+ certificationLedger: runtimeCertificationLedger,
2024
+ compatibilityProviderId: invocationProfile.availabilityEvidence.compatibilityProviderId,
2025
+ runtimeProviderId: selected.providerId,
2026
+ runtimeProfileId: invocationProfile.availabilityEvidence.runtimeProfileId,
2027
+ runtimeKind: invocationProfile.availabilityEvidence.runtimeKind,
2028
+ surface: invocationProfile.availabilityEvidence.surface,
2029
+ repositoryRole: invocationProfile.availabilityEvidence.repositoryRole,
2030
+ target: runtimeTarget,
2031
+ expectedGitTree,
2032
+ now,
2033
+ requireEvidence: true,
2034
+ })
2035
+ if (runtimeBinding?.runtimeProviderId !== runtimeCertification.runtimeProviderId
2036
+ || runtimeBinding.runtimeProfileId !== invocationProfile.availabilityEvidence.runtimeProfileId
2037
+ || runtimeBinding.runtimeKind !== runtimeCertification.runtimeKind
2038
+ || runtimeBinding.surface !== runtimeCertification.surface
2039
+ || runtimeBinding.repositoryRole !== runtimeCertification.repositoryRole
2040
+ || runtimeBinding.certificationId !== runtimeCertification.certificationId
2041
+ || runtimeBinding.certificationDigest !== runtimeCertification.recordDigest
2042
+ || runtimeBinding.targetDigest !== runtimeCertification.targetDigest) {
2043
+ block('REVIEW_GENUINE_TRANSITION_BLOCKED', 'runtime certification is detached from the capability evidence')
2044
+ }
2045
+ const { completionDigest, ...structuralProjection } = structuralCompletion
2046
+ if (structuralCompletion.evidenceKind
2047
+ !== 'deep-audit-model-broker-review-graph-exchange-completion'
2048
+ || completionDigest !== digest(structuralProjection)
2049
+ || structuralCompletion.exchangeScheduleDigest
2050
+ !== exchangeSchedule.exchangeScheduleDigest
2051
+ || structuralCompletion.requestCount !== exchangeSchedule.requestCount
2052
+ || !['verified', 'findings', 'unverifiable']
2053
+ .includes(structuralCompletion.aggregateVerdict)
2054
+ || !SHA256.test(structuralCompletion.taskRootVerdictSetDigest ?? '')
2055
+ || structuralCompletion.taskRootVerdictSetDigest
2056
+ !== digest(structuralCompletion.taskRootVerdicts)
2057
+ || structuralCompletion.fullNoSampleClosure !== true
2058
+ || structuralCompletion.structuralOnly !== true
2059
+ || structuralCompletion.genuineCrossProviderReview !== false
2060
+ || structuralCompletion.promotionEligible !== false
2061
+ || structuralCompletion.managedEvidence !== false
2062
+ || exchangeSchedule.fullRegisteredReview !== true
2063
+ || exchangeSchedule.sampling !== false
2064
+ || exchangeSchedule.structuralOnly !== true
2065
+ || exchangeSchedule.genuineCrossProviderReview !== false
2066
+ || exchangeSchedule.reviewIdentity?.selectionDigest !== selectionReceipt.selectionDigest) {
2067
+ block('REVIEW_GENUINE_TRANSITION_BLOCKED', 'structural completion/schedule is incomplete, stale, or overclaimed')
2068
+ }
2069
+ if (!Array.isArray(executionEvidence)
2070
+ || executionEvidence.length !== exchangeSchedule.requestCount) {
2071
+ block('REVIEW_GENUINE_TRANSITION_BLOCKED', 'execution evidence is partial')
2072
+ }
2073
+ const responseRows = []
2074
+ const providerRunIds = new Set()
2075
+ for (const [ordinal, row] of executionEvidence.entries()) {
2076
+ const planned = exchangeSchedule.requests[ordinal]
2077
+ exactObjectKeys(row, [
2078
+ 'requestOrdinal',
2079
+ 'requestDigest',
2080
+ 'carrierDigest',
2081
+ 'providerRunId',
2082
+ 'responseSha256',
2083
+ 'observedProviderId',
2084
+ 'observedReviewProfileId',
2085
+ 'observedInvocationProfileId',
2086
+ 'observedModelReleaseId',
2087
+ 'observedResponseModelId',
2088
+ 'runtimeCertificationId',
2089
+ 'runtimeCertificationDigest',
2090
+ 'runtimeTargetDigest',
2091
+ 'runtimeExecutableAuthorityDigest',
2092
+ 'runtimeExecutableBindingDigest',
2093
+ 'executionBindingDigest',
2094
+ 'authReadbackDigest',
2095
+ 'versionReadbackDigest',
2096
+ 'isolationPathClass',
2097
+ 'repositoryMounted',
2098
+ ], 'REVIEW_GENUINE_TRANSITION_BLOCKED', `execution evidence ${ordinal}`)
2099
+ if (!planned
2100
+ || row.requestOrdinal !== ordinal
2101
+ || row.requestDigest !== planned.requestDigest
2102
+ || !SHA256.test(row.carrierDigest ?? '')
2103
+ || !nonEmpty(row.providerRunId, 'REVIEW_GENUINE_TRANSITION_BLOCKED', `execution evidence ${ordinal}.providerRunId`)
2104
+ || providerRunIds.has(row.providerRunId)
2105
+ || !SHA256.test(row.responseSha256 ?? '')
2106
+ || row.observedProviderId !== selected.providerId
2107
+ || row.observedReviewProfileId !== selected.reviewProfileId
2108
+ || row.observedInvocationProfileId !== selected.invocationProfileId
2109
+ || row.observedModelReleaseId !== selected.modelReleaseId
2110
+ || row.observedResponseModelId !== selected.requestModelId
2111
+ || row.runtimeCertificationId !== runtimeCertification.certificationId
2112
+ || row.runtimeCertificationDigest !== runtimeCertification.recordDigest
2113
+ || row.runtimeTargetDigest !== runtimeCertification.targetDigest
2114
+ || row.runtimeExecutableAuthorityDigest
2115
+ !== runtimeBinding.runtimeExecutableAuthorityDigest
2116
+ || !SHA256.test(row.runtimeExecutableBindingDigest ?? '')
2117
+ || !SHA256.test(row.executionBindingDigest ?? '')
2118
+ || !SHA256.test(row.authReadbackDigest ?? '')
2119
+ || !SHA256.test(row.versionReadbackDigest ?? '')
2120
+ || !['no-space', 'contains-space'].includes(row.isolationPathClass)
2121
+ || row.repositoryMounted !== false
2122
+ || row.executionBindingDigest !== digest({
2123
+ schemaVersion: 1,
2124
+ kind: 'provider-neutral-external-entitlement-execution-binding',
2125
+ runtimeExecutableAuthorityDigest: row.runtimeExecutableAuthorityDigest,
2126
+ runtimeExecutableBindingDigest: row.runtimeExecutableBindingDigest,
2127
+ certifiedRuntimeTargetDigest: row.runtimeTargetDigest,
2128
+ authReadbackDigest: row.authReadbackDigest,
2129
+ versionReadbackDigest: row.versionReadbackDigest,
2130
+ isolationPathClass: row.isolationPathClass,
2131
+ repositoryMounted: row.repositoryMounted,
2132
+ })) {
2133
+ block('REVIEW_GENUINE_TRANSITION_BLOCKED', `execution evidence is missing, duplicate, reordered, or substituted:${ordinal}`)
2134
+ }
2135
+ providerRunIds.add(row.providerRunId)
2136
+ responseRows.push({
2137
+ requestDigest: row.requestDigest,
2138
+ carrierDigest: row.carrierDigest,
2139
+ providerRunId: row.providerRunId,
2140
+ responseSha256: row.responseSha256,
2141
+ })
2142
+ }
2143
+ const responseDigestSetDigest = digest(responseRows)
2144
+ if (responseDigestSetDigest !== structuralCompletion.responseDigestSetDigest) {
2145
+ block('REVIEW_GENUINE_TRANSITION_BLOCKED', 'execution response closure differs from the structural completion')
2146
+ }
2147
+ const executionEvidenceDigest = digest(executionEvidence)
2148
+ const projection = {
2149
+ schemaVersion: 1,
2150
+ kind: 'provider-neutral-genuine-cross-provider-review-receipt',
2151
+ protocol: exchangeSchedule.protocol,
2152
+ exchangeCore: PORTABLE_REVIEW_EXCHANGE_CORE,
2153
+ assurance: 'exact-runtime-and-capability-attested',
2154
+ authorProviderId: selectionReceipt.authorProviderId,
2155
+ reviewerProviderId: selected.providerId,
2156
+ reviewProfileId: selected.reviewProfileId,
2157
+ invocationProfileId: selected.invocationProfileId,
2158
+ modelReleaseId: selected.modelReleaseId,
2159
+ requestModelId: selected.requestModelId,
2160
+ observedResponseModelId: selected.requestModelId,
2161
+ selectionDigest: selectionReceipt.selectionDigest,
2162
+ capabilityCertificationId: capabilityRecord.id,
2163
+ capabilityCertificationDigest: digest(capabilityRecord),
2164
+ capabilityEvidenceDigest: capabilityEvidence.evidenceDigest,
2165
+ runtimeCertificationId: runtimeCertification.certificationId,
2166
+ runtimeCertificationDigest: runtimeCertification.recordDigest,
2167
+ runtimeTargetDigest: runtimeCertification.targetDigest,
2168
+ structuralCompletionDigest: completionDigest,
2169
+ exchangeScheduleDigest: exchangeSchedule.exchangeScheduleDigest,
2170
+ capabilityBudgetDigest: exchangeSchedule.capabilityBudgetDigest,
2171
+ aggregateVerdict: structuralCompletion.aggregateVerdict,
2172
+ taskRootVerdictSetDigest: structuralCompletion.taskRootVerdictSetDigest,
2173
+ requestCount: exchangeSchedule.requestCount,
2174
+ responseDigestSetDigest,
2175
+ executionEvidenceDigest,
2176
+ fullNoSampleClosure: true,
2177
+ genuineCrossProviderReview: true,
2178
+ promotionEligible: structuralCompletion.aggregateVerdict === 'verified',
2179
+ managedEvidence: false,
2180
+ }
2181
+ const receipt = { ...projection, receiptDigest: digest(projection) }
2182
+ validateGenuineCrossProviderReviewReceipt(receipt)
2183
+ return receipt
2184
+ }
2185
+
2186
+ export function projectProviderReviewBindings({
2187
+ registry,
2188
+ compatibilityMatrix,
2189
+ certificationLedger,
2190
+ skill = 'independent-review',
2191
+ repositoryRole = 'product-consumer',
2192
+ } = {}) {
2193
+ object(registry, 'REVIEW_REGISTRY_INVALID', 'provider registry')
2194
+ const providers = (registry.providers || []).filter((provider) => provider?.adapter?.generate)
2195
+ const bindings = providers.map((provider) => {
2196
+ const resolved = resolveProviderReviewBinding({
2197
+ registry,
2198
+ skill,
2199
+ selfProviderId: provider.id,
2200
+ requireCertificationContract: true,
2201
+ })
2202
+ return {
2203
+ selfProviderId: provider.id,
2204
+ selectionPolicy: resolved.binding.selectionPolicy,
2205
+ reviewClass: resolved.binding.reviewClass,
2206
+ requiredAssuranceTier: resolved.reviewClassPolicy.assuranceTier,
2207
+ requiredReasoningTier: resolved.reviewClassPolicy.reasoningTier,
2208
+ requiredComputeTier: resolved.reviewClassPolicy.computeTier,
2209
+ transport: resolved.transport,
2210
+ invocation: resolved.invocation,
2211
+ certificationContract: resolved.certificationContract,
2212
+ bindingDigest: resolved.bindingDigest,
2213
+ }
2214
+ }).sort((left, right) => compareUtf8Bytes(left.selfProviderId, right.selfProviderId))
2215
+ const providerCompatibility = (registry.providers || [])
2216
+ .filter((provider) => provider?.providerKind === 'concrete-runtime')
2217
+ .map((provider) => ({
2218
+ providerId: provider.id,
2219
+ compatibilityProviderId: compatibilityProviderIdForAdapter(compatibilityMatrix, provider.id),
2220
+ }))
2221
+ .sort((left, right) => compareUtf8Bytes(left.providerId, right.providerId))
2222
+ const compatibilityIds = new Set(providerCompatibility.map((binding) => binding.compatibilityProviderId))
2223
+ const certifications = certificationRecords(certificationLedger)
2224
+ .filter((record) => compatibilityIds.has(record.provider) && record.repositoryRole === repositoryRole)
2225
+ .sort((left, right) => compareUtf8Bytes(left.id, right.id))
2226
+ return {
2227
+ schemaVersion: 2,
2228
+ kind: 'provider-neutral-independent-review-projection',
2229
+ skill,
2230
+ repositoryRole,
2231
+ certificationContract: EXACT_REVIEW_CERTIFICATION_CONTRACT,
2232
+ bindings,
2233
+ providerCompatibility,
2234
+ certifications,
2235
+ projectionDigest: digest({ skill, repositoryRole, bindings, providerCompatibility, certifications }),
2236
+ }
2237
+ }
2238
+
2239
+ export function resolveProjectedReviewRequest({
2240
+ projection,
2241
+ selectionReceipt,
2242
+ registry,
2243
+ capabilityRegistry,
2244
+ capabilityCertificationLedger,
2245
+ invocationRegistry,
2246
+ modelReleaseRegistry,
2247
+ selfProviderId,
2248
+ authorProviderId = selfProviderId,
2249
+ runtimeKind,
2250
+ surface,
2251
+ repositoryRole,
2252
+ target,
2253
+ requiredEntitlementId = null,
2254
+ entitlementAvailability = [],
2255
+ now = new Date(),
2256
+ requireEvidence = true,
2257
+ } = {}) {
2258
+ object(projection, 'REVIEW_PROJECTION_INVALID', 'independent review projection')
2259
+ if (projection.schemaVersion !== 2 || projection.kind !== 'provider-neutral-independent-review-projection') {
2260
+ block('REVIEW_PROJECTION_INVALID', 'independent review projection identity is invalid')
2261
+ }
2262
+ if (projection.skill !== 'independent-review' || typeof projection.repositoryRole !== 'string') {
2263
+ block('REVIEW_PROJECTION_INVALID', 'independent review projection role or skill is invalid')
2264
+ }
2265
+ if (projection.projectionDigest !== digest({
2266
+ skill: projection.skill,
2267
+ repositoryRole: projection.repositoryRole,
2268
+ bindings: projection.bindings,
2269
+ providerCompatibility: projection.providerCompatibility,
2270
+ certifications: projection.certifications,
2271
+ })) block('REVIEW_PROJECTION_TAMPERED', 'independent review projection digest mismatches')
2272
+ if (projection.certificationContract !== EXACT_REVIEW_CERTIFICATION_CONTRACT) {
2273
+ block('REVIEW_CERTIFICATION_CONTRACT_UNAVAILABLE', 'projection certification contract is missing or stale')
2274
+ }
2275
+ if (repositoryRole !== projection.repositoryRole) {
2276
+ block('REVIEW_ROLE_MISMATCH', `${repositoryRole ?? '<missing>'}/${projection.repositoryRole}`)
2277
+ }
2278
+ if (authorProviderId !== selfProviderId) block('REVIEW_AUTHOR_COLLISION', `${authorProviderId ?? '<missing>'}/${selfProviderId ?? '<missing>'}`)
2279
+ const bindings = (projection.bindings || []).filter((binding) => binding?.selfProviderId === selfProviderId)
2280
+ if (bindings.length !== 1) block('REVIEW_BINDING_UNAVAILABLE', `${projection.skill}/${selfProviderId ?? '<missing>'}`)
2281
+ const binding = bindings[0]
2282
+ if (binding.certificationContract !== EXACT_REVIEW_CERTIFICATION_CONTRACT) {
2283
+ block('REVIEW_CERTIFICATION_CONTRACT_UNAVAILABLE', `${projection.skill}/${selfProviderId}`)
2284
+ }
2285
+ if (selectionReceipt === null || selectionReceipt === undefined) {
2286
+ return {
2287
+ skill: projection.skill,
2288
+ authorProviderId,
2289
+ currentProviderId: selfProviderId,
2290
+ peerProviderId: null,
2291
+ reviewProfileId: null,
2292
+ modelReleaseId: null,
2293
+ requestModelId: null,
2294
+ selectionDigest: null,
2295
+ selectionPolicy: binding.selectionPolicy,
2296
+ reviewClass: binding.reviewClass,
2297
+ requiredAssuranceTier: binding.requiredAssuranceTier,
2298
+ requiredReasoningTier: binding.requiredReasoningTier,
2299
+ requiredComputeTier: binding.requiredComputeTier,
2300
+ selectionStatus: 'REVIEW-BLOCKED',
2301
+ selectionReasonCode: 'REVIEW_CAPABILITY_SELECTION_REQUIRED',
2302
+ transport: binding.transport,
2303
+ invocation: binding.invocation,
2304
+ certificationContract: binding.certificationContract,
2305
+ bindingDigest: binding.bindingDigest,
2306
+ certification: null,
2307
+ }
2308
+ }
2309
+ if (binding.selectionPolicy !== selectionReceipt?.selectionPolicy
2310
+ || binding.reviewClass !== selectionReceipt?.reviewClass
2311
+ || binding.requiredAssuranceTier !== selectionReceipt?.requiredAssuranceTier
2312
+ || binding.requiredReasoningTier !== selectionReceipt?.requiredReasoningTier
2313
+ || binding.requiredComputeTier !== selectionReceipt?.requiredComputeTier
2314
+ || binding.bindingDigest !== selectionReceipt?.bindingDigest) {
2315
+ block('REVIEW_SELECTION_BINDING_MISMATCH', `${projection.skill}/${selfProviderId}`)
2316
+ }
2317
+ verifyReviewCapabilitySelection({
2318
+ receipt: selectionReceipt,
2319
+ registry,
2320
+ capabilityRegistry,
2321
+ capabilityCertificationLedger,
2322
+ invocationRegistry,
2323
+ modelReleaseRegistry,
2324
+ skill: projection.skill,
2325
+ selfProviderId,
2326
+ authorProviderId,
2327
+ requiredEntitlementId,
2328
+ entitlementAvailability,
2329
+ observedProviderId: selectionReceipt.selected?.providerId,
2330
+ observedReviewProfileId: selectionReceipt.selected?.reviewProfileId,
2331
+ observedModelReleaseId: selectionReceipt.selected?.modelReleaseId,
2332
+ observedResponseModelId: selectionReceipt.selected?.requestModelId,
2333
+ now,
2334
+ })
2335
+ if (selectionReceipt.selfProviderId !== selfProviderId
2336
+ || selectionReceipt.authorProviderId !== authorProviderId
2337
+ || selectionReceipt.skill !== projection.skill) {
2338
+ block('REVIEW_SELECTION_BINDING_MISMATCH', `${projection.skill}/${selfProviderId}`)
2339
+ }
2340
+ const compatibility = (projection.providerCompatibility || [])
2341
+ .filter((entry) => entry?.providerId === selectionReceipt.selected.providerId)
2342
+ if (compatibility.length !== 1) block('REVIEW_COMPATIBILITY_UNAVAILABLE', selectionReceipt.selected.providerId)
2343
+ nonEmpty(binding.transport, 'REVIEW_TRANSPORT_UNAVAILABLE', `${projection.skill}/${selfProviderId} transport`)
2344
+ const certification = verifyExactProviderCertification({
2345
+ certificationLedger: projection.certifications,
2346
+ compatibilityProviderId: compatibility[0].compatibilityProviderId,
2347
+ runtimeProviderId: selectionReceipt.selected.providerId,
2348
+ runtimeKind,
2349
+ surface,
2350
+ repositoryRole,
2351
+ target,
2352
+ now,
2353
+ requireEvidence,
2354
+ })
2355
+ return {
2356
+ skill: projection.skill,
2357
+ authorProviderId,
2358
+ currentProviderId: selfProviderId,
2359
+ peerProviderId: selectionReceipt.selected.providerId,
2360
+ reviewProfileId: selectionReceipt.selected.reviewProfileId,
2361
+ modelReleaseId: selectionReceipt.selected.modelReleaseId,
2362
+ requestModelId: selectionReceipt.selected.requestModelId,
2363
+ selectionDigest: selectionReceipt.selectionDigest,
2364
+ selectionPolicy: selectionReceipt.selectionPolicy,
2365
+ reviewClass: selectionReceipt.reviewClass,
2366
+ requiredAssuranceTier: selectionReceipt.requiredAssuranceTier,
2367
+ requiredReasoningTier: selectionReceipt.requiredReasoningTier,
2368
+ requiredComputeTier: selectionReceipt.requiredComputeTier,
2369
+ selectionStatus: 'selected',
2370
+ selectionReasonCode: null,
2371
+ transport: binding.transport,
2372
+ invocation: binding.invocation,
2373
+ certificationContract: binding.certificationContract,
2374
+ bindingDigest: binding.bindingDigest,
2375
+ certification,
2376
+ }
2377
+ }