@riddledc/riddle-proof 0.8.81 → 0.8.83

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.
package/README.md CHANGED
@@ -51,6 +51,7 @@ import { createCaptureDiagnostic } from "@riddledc/riddle-proof/diagnostics";
51
51
  import { toRiddleProofRunParams } from "@riddledc/riddle-proof/openclaw";
52
52
  import { assessRiddleProofChange } from "@riddledc/riddle-proof/change-proof";
53
53
  import { createRiddleProofObservationReceipt } from "@riddledc/riddle-proof/receipts";
54
+ import { composeRiddleProofSemanticCertificates } from "@riddledc/riddle-proof/semantic-certificate";
54
55
  ```
55
56
 
56
57
  The root export provides generic contracts and helpers. Integration-specific
@@ -77,6 +78,106 @@ Executor (`local_playwright`, `riddle_hosted`, or direct collection), target
77
78
  identity are independent dimensions. A merge recommendation is evidence-based
78
79
  advice; it does not grant shipping authorization.
79
80
 
81
+ ### Experimental Semantic Certificates
82
+
83
+ `riddle-proof.semantic-certificate.v0` is the first runtime surface for
84
+ compressing accepted, scoped observations into claims that another contract or
85
+ agent can inspect and compose. Every certificate has a complete scope
86
+ (`repository`, `revision`, `environment`, `target`, and `proof_attempt`), a
87
+ named and versioned claim, and at least one receipt plus artifact digest.
88
+
89
+ Atomic issuance evaluates an explicit runtime contract. A rejected contract
90
+ produces no certificate:
91
+
92
+ ```ts
93
+ import {
94
+ createRiddleProofSemanticCertificate,
95
+ composeRiddleProofSemanticCertificates,
96
+ matchRiddleProofSemanticCertificate,
97
+ } from "@riddledc/riddle-proof/semantic-certificate";
98
+
99
+ const quiet = createRiddleProofSemanticCertificate({
100
+ scope,
101
+ observation: earlyTraceSample,
102
+ evidence: [{
103
+ receipt_id: "obs_tidepool_early",
104
+ artifact_digest: orderedTraceDigest,
105
+ role: "ordered_trace_witness",
106
+ }],
107
+ contract: {
108
+ contract_id: "tidepool.early-quiescence",
109
+ contract_version: "1",
110
+ label: "The early trace is quiet",
111
+ claim: {
112
+ claim_id: "tidepool.early-quiescence",
113
+ claim_version: "1",
114
+ parameters: { sample_index: 1 },
115
+ label: "The early sample has no collision and no sound",
116
+ },
117
+ accepts: (_scope, sample) => !sample.collision && !sample.sound,
118
+ },
119
+ });
120
+
121
+ if (!quiet.ok) throw new Error(quiet.error.message);
122
+
123
+ const behavior = composeRiddleProofSemanticCertificates({
124
+ rule: {
125
+ rule_id: "tidepool.quiet-then-collision",
126
+ rule_version: "1",
127
+ label: "Interpret the two trace facts together",
128
+ premises: [quiet.certificate.claim, later.certificate.claim],
129
+ conclusion: observedWaveCollisionBehaviorClaim,
130
+ },
131
+ certificates: [quiet.certificate, later.certificate],
132
+ });
133
+ ```
134
+
135
+ A later agent can consume one exact certificate without reopening its receipt
136
+ files. The expected content ID must arrive through the consumer's trusted
137
+ handoff or configuration; copying it from the same untrusted certificate would
138
+ not add trust:
139
+
140
+ ```ts
141
+ const match = matchRiddleProofSemanticCertificate({
142
+ certificate: JSON.parse(serializedCertificate),
143
+ expected_certificate_id: trustedHandoffCertificateId,
144
+ expected_scope: scope,
145
+ expected_claim: observedWaveCollisionBehaviorClaim,
146
+ expected_assurance: "declared_runtime_rule",
147
+ });
148
+
149
+ if (!match.ok) throw new Error(match.error.message);
150
+ // match.certificate is the exact scoped certificate this consumer requested.
151
+ ```
152
+
153
+ Matching first reparses the envelope and its content ID, then compares the
154
+ trusted expected ID, all five scope fields, claim ID/version/parameters, and
155
+ top-level assurance. It does no filesystem or network I/O, and a successful
156
+ match does not authenticate the issuer or the referenced evidence.
157
+
158
+ This is an exact root-certificate handoff, not independent proof-tree
159
+ reconstruction. A composite certificate retains compact immediate-premise
160
+ snapshots, not the full transitive certificate bodies. A consumer that does not
161
+ already trust the expected root ID needs a complete certificate closure plus a
162
+ contract/rule identity policy before it can independently inspect the whole
163
+ derivation.
164
+
165
+ Composition requires the declared premise claims and exact scope equality. It
166
+ copies compact premise snapshots into the derivation and sets the higher
167
+ certificate's evidence to the ordered concatenation of premise evidence. The
168
+ snapshots retain whether each input came from a checked runtime contract or a
169
+ declared runtime rule. The parser rechecks those relationships and the
170
+ content-addressed certificate ID. The serialized v0 objects use exact keys and
171
+ reject any `status`, verdict, merge, sync, ready-to-ship, shipping-authority,
172
+ or free-form metadata field: semantic composition is deliberately separate
173
+ from release policy.
174
+
175
+ The boundary remains explicit. Derivations say `runtime_contract_accepted` or
176
+ `declared_runtime_rule`; JavaScript predicates and named rules are inspectable
177
+ runtime models, not Lean proof terms. Certificate hashes are content identities,
178
+ not signatures, and receipt IDs and digests do not authenticate browser, Git,
179
+ CDN, screenshot, or outside-world truth.
180
+
80
181
  Persist a deploy result and its immutable receipt for later Change Proof input:
81
182
 
82
183
  ```sh
@@ -0,0 +1,585 @@
1
+ // src/semantic-certificate.ts
2
+ import { createHash } from "crypto";
3
+ var RIDDLE_PROOF_SEMANTIC_CERTIFICATE_VERSION = "riddle-proof.semantic-certificate.v0";
4
+ var SCOPE_FIELDS = [
5
+ "repository",
6
+ "revision",
7
+ "environment",
8
+ "target",
9
+ "proof_attempt"
10
+ ];
11
+ var AUTHORITY_FIELDS = [
12
+ "authority",
13
+ "status",
14
+ "verdict",
15
+ "ready_to_ship",
16
+ "merge_ready",
17
+ "sync_allowed",
18
+ "ship_authorized",
19
+ "shipping_authorized",
20
+ "shipping_disabled",
21
+ "merge_recommended",
22
+ "merge_recommendation",
23
+ "shipping_authorization"
24
+ ];
25
+ var CERTIFICATE_FIELDS = /* @__PURE__ */ new Set([
26
+ "version",
27
+ "certificate_id",
28
+ "scope",
29
+ "claim",
30
+ "evidence",
31
+ "derivation",
32
+ "issued_at"
33
+ ]);
34
+ function isRecord(value) {
35
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
36
+ }
37
+ function safeErrorMessage(error) {
38
+ try {
39
+ if (error instanceof Error) return String(error.message);
40
+ } catch {
41
+ }
42
+ try {
43
+ return String(error);
44
+ } catch {
45
+ return "unprintable thrown value";
46
+ }
47
+ }
48
+ function assertOnlyKeys(record, allowed, context) {
49
+ const allowedSet = new Set(allowed);
50
+ for (const key of Object.keys(record)) {
51
+ if (!allowedSet.has(key)) {
52
+ throw new Error(`${context} contains unsupported field ${key}.`);
53
+ }
54
+ }
55
+ }
56
+ function requiredString(record, key, context) {
57
+ const value = record[key];
58
+ if (typeof value !== "string" || !value.trim()) {
59
+ throw new Error(`${context}.${key} must be a non-empty string.`);
60
+ }
61
+ return value.trim();
62
+ }
63
+ function optionalString(record, key, context) {
64
+ if (record[key] === void 0) return void 0;
65
+ return requiredString(record, key, context);
66
+ }
67
+ function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
68
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
69
+ return true;
70
+ }
71
+ if (typeof value === "number") return Number.isFinite(value);
72
+ if (Array.isArray(value)) {
73
+ if (ancestors.has(value)) return false;
74
+ ancestors.add(value);
75
+ const valid2 = value.every((entry) => isJsonValue(entry, ancestors));
76
+ ancestors.delete(value);
77
+ return valid2;
78
+ }
79
+ if (!isRecord(value)) return false;
80
+ const prototype = Object.getPrototypeOf(value);
81
+ if (prototype !== Object.prototype && prototype !== null) return false;
82
+ if (ancestors.has(value)) return false;
83
+ ancestors.add(value);
84
+ const valid = Object.values(value).every((entry) => isJsonValue(entry, ancestors));
85
+ ancestors.delete(value);
86
+ return valid;
87
+ }
88
+ function parseJsonObject(value, context) {
89
+ if (value === void 0) return void 0;
90
+ if (!isRecord(value) || !isJsonValue(value)) {
91
+ throw new Error(`${context} must be a JSON object.`);
92
+ }
93
+ const cloned = JSON.parse(JSON.stringify(value));
94
+ if (!isRecord(cloned) || !isJsonValue(cloned)) {
95
+ throw new Error(`${context} must remain a JSON object when serialized.`);
96
+ }
97
+ return cloned;
98
+ }
99
+ function parseIssuedAt(value, context) {
100
+ if (typeof value !== "string" || !value.trim() || !Number.isFinite(Date.parse(value))) {
101
+ throw new Error(`${context} must be a valid timestamp.`);
102
+ }
103
+ return value.trim();
104
+ }
105
+ function parseScope(value, context) {
106
+ if (!isRecord(value)) throw new Error(`${context} must be an object.`);
107
+ assertOnlyKeys(value, SCOPE_FIELDS, context);
108
+ return {
109
+ repository: requiredString(value, "repository", context),
110
+ revision: requiredString(value, "revision", context),
111
+ environment: requiredString(value, "environment", context),
112
+ target: requiredString(value, "target", context),
113
+ proof_attempt: requiredString(value, "proof_attempt", context)
114
+ };
115
+ }
116
+ function parseClaimRef(value, context, allowedExtras = []) {
117
+ if (!isRecord(value)) throw new Error(`${context} must be an object.`);
118
+ assertOnlyKeys(value, ["claim_id", "claim_version", "parameters", ...allowedExtras], context);
119
+ const parameters = parseJsonObject(value.parameters, `${context}.parameters`);
120
+ return {
121
+ claim_id: requiredString(value, "claim_id", context),
122
+ claim_version: requiredString(value, "claim_version", context),
123
+ ...parameters ? { parameters } : {}
124
+ };
125
+ }
126
+ function parseClaim(value, context) {
127
+ if (!isRecord(value)) throw new Error(`${context} must be an object.`);
128
+ return {
129
+ ...parseClaimRef(value, context, ["label"]),
130
+ label: requiredString(value, "label", context)
131
+ };
132
+ }
133
+ function parseEvidenceRef(value, context) {
134
+ if (!isRecord(value)) throw new Error(`${context} must be an object.`);
135
+ assertOnlyKeys(
136
+ value,
137
+ ["receipt_id", "artifact_digest", "role", "artifact_url", "artifact_path"],
138
+ context
139
+ );
140
+ const artifactDigest = requiredString(value, "artifact_digest", context).toLowerCase();
141
+ if (!/^sha256:[0-9a-f]{64}$/u.test(artifactDigest)) {
142
+ throw new Error(`${context}.artifact_digest must be a full sha256 digest.`);
143
+ }
144
+ const artifactUrl = optionalString(value, "artifact_url", context);
145
+ const artifactPath = optionalString(value, "artifact_path", context);
146
+ return {
147
+ receipt_id: requiredString(value, "receipt_id", context),
148
+ artifact_digest: artifactDigest,
149
+ role: requiredString(value, "role", context),
150
+ ...artifactUrl ? { artifact_url: artifactUrl } : {},
151
+ ...artifactPath ? { artifact_path: artifactPath } : {}
152
+ };
153
+ }
154
+ function parseEvidenceBundle(value, context) {
155
+ if (!Array.isArray(value) || value.length === 0) {
156
+ throw new Error(`${context} must contain at least one evidence reference.`);
157
+ }
158
+ return value.map((entry, index) => parseEvidenceRef(entry, `${context}[${index}]`));
159
+ }
160
+ function parseContractRef(value, context) {
161
+ if (!isRecord(value)) throw new Error(`${context} must be an object.`);
162
+ return {
163
+ contract_id: requiredString(value, "contract_id", context),
164
+ contract_version: requiredString(value, "contract_version", context),
165
+ label: requiredString(value, "label", context)
166
+ };
167
+ }
168
+ function parseContract(value, context, allowRuntimePredicate = false) {
169
+ if (!isRecord(value)) throw new Error(`${context} must be an object.`);
170
+ assertOnlyKeys(
171
+ value,
172
+ ["contract_id", "contract_version", "label", "claim", ...allowRuntimePredicate ? ["accepts"] : []],
173
+ context
174
+ );
175
+ if (allowRuntimePredicate && typeof value.accepts !== "function") {
176
+ throw new Error(`${context}.accepts must be a function.`);
177
+ }
178
+ return {
179
+ ...parseContractRef(value, context),
180
+ claim: parseClaim(value.claim, `${context}.claim`)
181
+ };
182
+ }
183
+ function parseRule(value, context, allowFullPremises = false) {
184
+ if (!isRecord(value)) throw new Error(`${context} must be an object.`);
185
+ assertOnlyKeys(value, ["rule_id", "rule_version", "label", "premises", "conclusion"], context);
186
+ if (!Array.isArray(value.premises) || value.premises.length === 0) {
187
+ throw new Error(`${context}.premises must contain at least one claim reference.`);
188
+ }
189
+ return {
190
+ rule_id: requiredString(value, "rule_id", context),
191
+ rule_version: requiredString(value, "rule_version", context),
192
+ label: requiredString(value, "label", context),
193
+ premises: value.premises.map((premise, index) => parseClaimRef(
194
+ premise,
195
+ `${context}.premises[${index}]`,
196
+ allowFullPremises ? ["label"] : []
197
+ )),
198
+ conclusion: parseClaim(value.conclusion, `${context}.conclusion`)
199
+ };
200
+ }
201
+ function parsePremise(value, context) {
202
+ if (!isRecord(value)) throw new Error(`${context} must be an object.`);
203
+ assertOnlyKeys(
204
+ value,
205
+ ["certificate_id", "derivation_kind", "assurance", "scope", "claim", "evidence"],
206
+ context
207
+ );
208
+ const derivationKind = requiredString(value, "derivation_kind", context);
209
+ const assurance = requiredString(value, "assurance", context);
210
+ const validAssurance = derivationKind === "contract" && assurance === "runtime_contract_accepted" || derivationKind === "composition" && assurance === "declared_runtime_rule";
211
+ if (!validAssurance) {
212
+ throw new Error(`${context} must preserve a valid derivation_kind and assurance pair.`);
213
+ }
214
+ return {
215
+ certificate_id: requiredString(value, "certificate_id", context),
216
+ derivation_kind: derivationKind,
217
+ assurance,
218
+ scope: parseScope(value.scope, `${context}.scope`),
219
+ claim: parseClaim(value.claim, `${context}.claim`),
220
+ evidence: parseEvidenceBundle(value.evidence, `${context}.evidence`)
221
+ };
222
+ }
223
+ function stableJson(value) {
224
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
225
+ if (isRecord(value)) {
226
+ return `{${Object.keys(value).filter((key) => value[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
227
+ }
228
+ const encoded = JSON.stringify(value);
229
+ if (encoded === void 0) throw new Error("Semantic certificate contains a non-JSON value.");
230
+ return encoded;
231
+ }
232
+ function sameClaimRef(left, right) {
233
+ return left.claim_id === right.claim_id && left.claim_version === right.claim_version && stableJson(left.parameters || {}) === stableJson(right.parameters || {});
234
+ }
235
+ function sameEvidence(left, right) {
236
+ return stableJson(left) === stableJson(right);
237
+ }
238
+ function certificateId(body) {
239
+ const digest = createHash("sha256").update(stableJson(body)).digest("hex");
240
+ return `rpsc_${digest}`;
241
+ }
242
+ function withCertificateId(body) {
243
+ return { ...body, certificate_id: certificateId(body) };
244
+ }
245
+ function parseDerivation(value, context) {
246
+ if (!isRecord(value)) throw new Error(`${context} must be an object.`);
247
+ const kind = requiredString(value, "kind", context);
248
+ if (kind === "contract") {
249
+ assertOnlyKeys(value, ["kind", "assurance", "contract"], context);
250
+ if (value.assurance !== "runtime_contract_accepted") {
251
+ throw new Error(`${context}.assurance must be runtime_contract_accepted.`);
252
+ }
253
+ return {
254
+ kind,
255
+ assurance: "runtime_contract_accepted",
256
+ contract: parseContract(value.contract, `${context}.contract`)
257
+ };
258
+ }
259
+ if (kind === "composition") {
260
+ assertOnlyKeys(value, ["kind", "assurance", "rule", "premises"], context);
261
+ if (value.assurance !== "declared_runtime_rule") {
262
+ throw new Error(`${context}.assurance must be declared_runtime_rule.`);
263
+ }
264
+ if (!Array.isArray(value.premises) || value.premises.length === 0) {
265
+ throw new Error(`${context}.premises must contain at least one certificate premise.`);
266
+ }
267
+ return {
268
+ kind,
269
+ assurance: "declared_runtime_rule",
270
+ rule: parseRule(value.rule, `${context}.rule`),
271
+ premises: value.premises.map((premise, index) => parsePremise(premise, `${context}.premises[${index}]`))
272
+ };
273
+ }
274
+ throw new Error(`${context}.kind must be contract or composition.`);
275
+ }
276
+ function riddleProofSemanticScopesEqual(left, right) {
277
+ return SCOPE_FIELDS.every((field) => left[field] === right[field]);
278
+ }
279
+ function createRiddleProofSemanticCertificate(input) {
280
+ if (!isRecord(input)) throw new Error("Semantic certificate input must be an object.");
281
+ assertOnlyKeys(
282
+ input,
283
+ ["scope", "evidence", "observation", "contract", "issued_at"],
284
+ "semantic certificate input"
285
+ );
286
+ const scope = parseScope(input.scope, "semantic certificate scope");
287
+ const evidence = parseEvidenceBundle(input.evidence, "semantic certificate evidence");
288
+ const contract = parseContract(input.contract, "semantic certificate contract", true);
289
+ const contractRef = {
290
+ contract_id: contract.contract_id,
291
+ contract_version: contract.contract_version,
292
+ label: contract.label
293
+ };
294
+ const claim = contract.claim;
295
+ let accepted;
296
+ try {
297
+ accepted = input.contract.accepts({ ...scope }, input.observation) === true;
298
+ } catch (error) {
299
+ return {
300
+ ok: false,
301
+ error: {
302
+ code: "contract_error",
303
+ contract: contractRef,
304
+ message: `Semantic contract evaluation failed: ${error instanceof Error ? error.message : String(error)}.`
305
+ }
306
+ };
307
+ }
308
+ if (!accepted) {
309
+ return {
310
+ ok: false,
311
+ error: {
312
+ code: "contract_rejected",
313
+ contract: contractRef,
314
+ message: "Semantic contract rejected the supplied observation at this scope."
315
+ }
316
+ };
317
+ }
318
+ const body = {
319
+ version: RIDDLE_PROOF_SEMANTIC_CERTIFICATE_VERSION,
320
+ scope,
321
+ claim,
322
+ evidence,
323
+ derivation: { kind: "contract", assurance: "runtime_contract_accepted", contract },
324
+ issued_at: parseIssuedAt(input.issued_at || (/* @__PURE__ */ new Date()).toISOString(), "semantic certificate issued_at")
325
+ };
326
+ return { ok: true, certificate: withCertificateId(body) };
327
+ }
328
+ function parseRiddleProofSemanticCertificate(value) {
329
+ if (!isRecord(value)) throw new Error("Semantic certificate must be an object.");
330
+ if (value.version !== RIDDLE_PROOF_SEMANTIC_CERTIFICATE_VERSION) {
331
+ throw new Error(`Unsupported Semantic certificate version ${String(value.version || "missing")}.`);
332
+ }
333
+ for (const field of AUTHORITY_FIELDS) {
334
+ if (Object.prototype.hasOwnProperty.call(value, field)) {
335
+ throw new Error(`Semantic certificate must not contain authority field ${field}.`);
336
+ }
337
+ }
338
+ for (const field of Object.keys(value)) {
339
+ if (!CERTIFICATE_FIELDS.has(field)) {
340
+ throw new Error(`Semantic certificate contains unsupported field ${field}.`);
341
+ }
342
+ }
343
+ const scope = parseScope(value.scope, "semantic certificate scope");
344
+ const claim = parseClaim(value.claim, "semantic certificate claim");
345
+ const evidence = parseEvidenceBundle(value.evidence, "semantic certificate evidence");
346
+ const derivation = parseDerivation(value.derivation, "semantic certificate derivation");
347
+ if (derivation.kind === "contract" && !sameClaimRef(claim, derivation.contract.claim)) {
348
+ throw new Error("Semantic contract-derived claim must match its contract claim.");
349
+ }
350
+ if (derivation.kind === "composition") {
351
+ if (derivation.premises.length !== derivation.rule.premises.length) {
352
+ throw new Error("Semantic composition premises must match the rule premise count.");
353
+ }
354
+ derivation.premises.forEach((premise, index) => {
355
+ if (!riddleProofSemanticScopesEqual(scope, premise.scope)) {
356
+ throw new Error(`Semantic composition premise ${index} must have the certificate scope.`);
357
+ }
358
+ if (!sameClaimRef(premise.claim, derivation.rule.premises[index])) {
359
+ throw new Error(`Semantic composition premise ${index} must match its rule claim.`);
360
+ }
361
+ });
362
+ if (!sameClaimRef(claim, derivation.rule.conclusion)) {
363
+ throw new Error("Semantic composition claim must match its rule conclusion.");
364
+ }
365
+ const expectedEvidence = derivation.premises.flatMap((premise) => premise.evidence);
366
+ if (!sameEvidence(evidence, expectedEvidence)) {
367
+ throw new Error("Semantic composition evidence must be the ordered concatenation of premise evidence.");
368
+ }
369
+ }
370
+ const body = {
371
+ version: RIDDLE_PROOF_SEMANTIC_CERTIFICATE_VERSION,
372
+ scope,
373
+ claim,
374
+ evidence,
375
+ derivation,
376
+ issued_at: parseIssuedAt(value.issued_at, "semantic certificate issued_at")
377
+ };
378
+ const observedId = requiredString(value, "certificate_id", "semantic certificate");
379
+ const expectedId = certificateId(body);
380
+ if (observedId !== expectedId) {
381
+ throw new Error("Semantic certificate_id must match its content.");
382
+ }
383
+ return { ...body, certificate_id: observedId };
384
+ }
385
+ function matchRiddleProofSemanticCertificate(input) {
386
+ if (!isRecord(input)) throw new Error("Semantic certificate match input must be an object.");
387
+ assertOnlyKeys(
388
+ input,
389
+ [
390
+ "certificate",
391
+ "expected_certificate_id",
392
+ "expected_scope",
393
+ "expected_claim",
394
+ "expected_assurance"
395
+ ],
396
+ "semantic certificate match input"
397
+ );
398
+ const expectedCertificateId = requiredString(
399
+ input,
400
+ "expected_certificate_id",
401
+ "semantic certificate match input"
402
+ );
403
+ if (!/^rpsc_[0-9a-f]{64}$/u.test(expectedCertificateId)) {
404
+ throw new Error(
405
+ "Semantic certificate match input.expected_certificate_id must be a full rpsc content ID."
406
+ );
407
+ }
408
+ const expectedScope = parseScope(
409
+ input.expected_scope,
410
+ "semantic certificate match expected_scope"
411
+ );
412
+ const expectedClaim = parseClaimRef(
413
+ input.expected_claim,
414
+ "semantic certificate match expected_claim",
415
+ ["label"]
416
+ );
417
+ const expectedAssurance = requiredString(
418
+ input,
419
+ "expected_assurance",
420
+ "semantic certificate match input"
421
+ );
422
+ if (expectedAssurance !== "runtime_contract_accepted" && expectedAssurance !== "declared_runtime_rule") {
423
+ throw new Error(
424
+ "Semantic certificate match input.expected_assurance must be runtime_contract_accepted or declared_runtime_rule."
425
+ );
426
+ }
427
+ let certificate;
428
+ try {
429
+ certificate = parseRiddleProofSemanticCertificate(input.certificate);
430
+ } catch (error) {
431
+ return {
432
+ ok: false,
433
+ error: {
434
+ code: "invalid_certificate",
435
+ message: `Semantic certificate did not parse: ${safeErrorMessage(error)}`
436
+ }
437
+ };
438
+ }
439
+ if (certificate.certificate_id !== expectedCertificateId) {
440
+ return {
441
+ ok: false,
442
+ error: {
443
+ code: "certificate_id_mismatch",
444
+ expected: expectedCertificateId,
445
+ observed: certificate.certificate_id,
446
+ message: "Semantic certificate does not match the trusted expected content ID."
447
+ }
448
+ };
449
+ }
450
+ const scopeMismatch = firstScopeMismatch(expectedScope, certificate.scope);
451
+ if (scopeMismatch) {
452
+ return {
453
+ ok: false,
454
+ error: {
455
+ code: "scope_mismatch",
456
+ ...scopeMismatch,
457
+ message: `Semantic certificate has a different ${scopeMismatch.field} than the consumer expected.`
458
+ }
459
+ };
460
+ }
461
+ if (!sameClaimRef(expectedClaim, certificate.claim)) {
462
+ return {
463
+ ok: false,
464
+ error: {
465
+ code: "claim_mismatch",
466
+ expected: expectedClaim,
467
+ observed: parseClaimRef(
468
+ certificate.claim,
469
+ "semantic certificate match observed claim",
470
+ ["label"]
471
+ ),
472
+ message: "Semantic certificate does not state the claim the consumer expected."
473
+ }
474
+ };
475
+ }
476
+ if (certificate.derivation.assurance !== expectedAssurance) {
477
+ return {
478
+ ok: false,
479
+ error: {
480
+ code: "assurance_mismatch",
481
+ expected: expectedAssurance,
482
+ observed: certificate.derivation.assurance,
483
+ message: "Semantic certificate does not have the assurance the consumer expected."
484
+ }
485
+ };
486
+ }
487
+ return { ok: true, certificate };
488
+ }
489
+ function firstScopeMismatch(expected, observed) {
490
+ for (const field of SCOPE_FIELDS) {
491
+ if (expected[field] !== observed[field]) {
492
+ return { field, expected: expected[field], observed: observed[field] };
493
+ }
494
+ }
495
+ return void 0;
496
+ }
497
+ function premiseFromCertificate(certificate) {
498
+ return {
499
+ certificate_id: certificate.certificate_id,
500
+ derivation_kind: certificate.derivation.kind,
501
+ assurance: certificate.derivation.assurance,
502
+ scope: { ...certificate.scope },
503
+ claim: parseClaim(certificate.claim, "semantic composition premise claim"),
504
+ evidence: certificate.evidence.map((entry) => ({ ...entry }))
505
+ };
506
+ }
507
+ function composeRiddleProofSemanticCertificates(input) {
508
+ if (!isRecord(input)) throw new Error("Semantic composition input must be an object.");
509
+ assertOnlyKeys(
510
+ input,
511
+ ["rule", "certificates", "issued_at"],
512
+ "semantic composition input"
513
+ );
514
+ const rule = parseRule(input.rule, "semantic composition rule", true);
515
+ if (!Array.isArray(input.certificates) || input.certificates.length === 0) {
516
+ throw new Error("Semantic composition requires at least one certificate.");
517
+ }
518
+ const certificates = input.certificates.map((certificate) => parseRiddleProofSemanticCertificate(certificate));
519
+ if (certificates.length !== rule.premises.length) {
520
+ return {
521
+ ok: false,
522
+ error: {
523
+ code: "premise_count_mismatch",
524
+ expected: rule.premises.length,
525
+ observed: certificates.length,
526
+ message: `Semantic rule expected ${rule.premises.length} certificate(s), received ${certificates.length}.`
527
+ }
528
+ };
529
+ }
530
+ const expectedScope = certificates[0].scope;
531
+ for (let index = 1; index < certificates.length; index += 1) {
532
+ const mismatch = firstScopeMismatch(expectedScope, certificates[index].scope);
533
+ if (mismatch) {
534
+ return {
535
+ ok: false,
536
+ error: {
537
+ code: "scope_mismatch",
538
+ input_index: index,
539
+ ...mismatch,
540
+ message: `Semantic certificate ${index} has a different ${mismatch.field}.`
541
+ }
542
+ };
543
+ }
544
+ }
545
+ for (let index = 0; index < certificates.length; index += 1) {
546
+ const expected = rule.premises[index];
547
+ const observed = certificates[index].claim;
548
+ if (!sameClaimRef(expected, observed)) {
549
+ return {
550
+ ok: false,
551
+ error: {
552
+ code: "premise_mismatch",
553
+ input_index: index,
554
+ expected,
555
+ observed: parseClaimRef(observed, "semantic composition observed claim", ["label"]),
556
+ message: `Semantic certificate ${index} does not satisfy its declared rule premise.`
557
+ }
558
+ };
559
+ }
560
+ }
561
+ const evidence = certificates.flatMap((certificate) => certificate.evidence);
562
+ const body = {
563
+ version: RIDDLE_PROOF_SEMANTIC_CERTIFICATE_VERSION,
564
+ scope: { ...expectedScope },
565
+ claim: { ...rule.conclusion },
566
+ evidence,
567
+ derivation: {
568
+ kind: "composition",
569
+ assurance: "declared_runtime_rule",
570
+ rule,
571
+ premises: certificates.map(premiseFromCertificate)
572
+ },
573
+ issued_at: parseIssuedAt(input.issued_at || (/* @__PURE__ */ new Date()).toISOString(), "semantic certificate issued_at")
574
+ };
575
+ return { ok: true, certificate: withCertificateId(body) };
576
+ }
577
+
578
+ export {
579
+ RIDDLE_PROOF_SEMANTIC_CERTIFICATE_VERSION,
580
+ riddleProofSemanticScopesEqual,
581
+ createRiddleProofSemanticCertificate,
582
+ parseRiddleProofSemanticCertificate,
583
+ matchRiddleProofSemanticCertificate,
584
+ composeRiddleProofSemanticCertificates
585
+ };