@openplanr/protocol 0.6.1 → 0.7.0

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 (58) hide show
  1. package/README.md +10 -0
  2. package/lib/dashboard/closed-json-contract.mjs +99 -109
  3. package/lib/dashboard/operate-experience-audit-display-contract.d.mts +128 -153
  4. package/lib/dashboard/operate-experience-audit-display-contract.mjs +530 -585
  5. package/lib/dashboard/operate-experience-display-contract.d.mts +415 -437
  6. package/lib/dashboard/operate-experience-display-contract.mjs +777 -831
  7. package/lib/dashboard/operate-experience-surface-contract.d.mts +143 -148
  8. package/lib/dashboard/operate-experience-surface-contract.mjs +72 -73
  9. package/lib/dashboard/operate-review-contract.d.mts +7 -14
  10. package/lib/dashboard/operate-review-contract.mjs +46 -42
  11. package/lib/dashboard/operate-review-display-workspace-contract.d.mts +2 -5
  12. package/lib/dashboard/operate-review-display-workspace-contract.mjs +158 -104
  13. package/lib/dashboard/operate-review-payload-safety.mjs +4 -2
  14. package/lib/dashboard/operate-review-workspace-projection-v2.d.mts +47 -33
  15. package/lib/protocol/index.d.ts +2647 -543
  16. package/package.json +1 -1
  17. package/registries/artifact-theme.json +64 -0
  18. package/registries/commands.json +40 -40
  19. package/registries/skills.json +5 -5
  20. package/schemas/v1.14.0/artifact-theme.schema.json +316 -0
  21. package/src/browser-contracts.d.mts +4 -1
  22. package/src/browser-contracts.mjs +16 -5
  23. package/src/canonical-json.d.mts +6 -1
  24. package/src/canonical-json.mjs +100 -22
  25. package/src/compat/live-evidence-v2.mjs +1611 -485
  26. package/src/compat/operate-experience-live-patch.mjs +67 -15
  27. package/src/compat/operating-planning-contracts.mjs +183 -51
  28. package/src/contracts.d.mts +54 -13
  29. package/src/contracts.mjs +635 -343
  30. package/src/design-contracts.mjs +58 -21
  31. package/src/design-handoff-contracts.d.mts +67 -11
  32. package/src/design-handoff-contracts.mjs +236 -119
  33. package/src/design-publication-contracts.mjs +98 -33
  34. package/src/diagram-authoring-contracts.d.mts +422 -78
  35. package/src/diagram-authoring-contracts.mjs +1715 -335
  36. package/src/diagram-contracts.d.mts +4 -1
  37. package/src/diagram-contracts.mjs +16 -4
  38. package/src/enterprise-contracts.d.mts +211 -46
  39. package/src/enterprise-contracts.mjs +738 -184
  40. package/src/errors.mjs +4 -0
  41. package/src/generated/canonical-registries.mjs +45 -45
  42. package/src/index.d.mts +8 -8
  43. package/src/index.mjs +36 -20
  44. package/src/json-schema.d.mts +21 -6
  45. package/src/json-schema.mjs +66 -18
  46. package/src/planning-contracts.d.mts +8 -2
  47. package/src/planning-contracts.mjs +33 -7
  48. package/src/registries.d.mts +11 -3
  49. package/src/registries.mjs +369 -87
  50. package/src/review-experience-contracts.d.mts +7 -2
  51. package/src/review-experience-contracts.mjs +198 -49
  52. package/src/semver.mjs +5 -1
  53. package/src/skill-source-contracts.d.mts +36 -16
  54. package/src/skill-source-contracts.mjs +25 -6
  55. package/src/task-contracts.d.mts +13 -3
  56. package/src/task-contracts.mjs +181 -40
  57. package/src/workspace-contracts.d.mts +38 -10
  58. package/src/workspace-contracts.mjs +147 -33
@@ -1,54 +1,141 @@
1
- import { assertProtocolArtifact } from '../contracts.mjs';
1
+ /**
2
+ * Live-evidence contracts: validates provider registrations, consent, ingestion and its accepted
3
+ * Artifact bridge, reduces connector checkpoints and measurement schedules, and evaluates Outcomes.
4
+ * Entry points: `assertOperatingLiveEvidenceIngestionV2`, `assertAcceptedLiveEvidenceBridgeV2`,
5
+ * `reduceOperatingConnectorCheckpointV2`, `reduceOperatingMeasurementScheduleV2`.
6
+ */
7
+
2
8
  import { sha256Jcs } from '../canonical-json.mjs';
9
+ import { assertProtocolArtifact } from '../contracts.mjs';
3
10
 
4
11
  const HASH = /^sha256:[a-f0-9]{64}$/u;
5
12
  const CHECKPOINT_TRANSITIONS = Object.freeze({
6
13
  prepared: Object.freeze({ request: 'requesting', absent: 'absent' }),
7
- requesting: Object.freeze({ materialize: 'materialized', absent: 'absent', uncertain: 'uncertain' }),
14
+ requesting: Object.freeze({
15
+ materialize: 'materialized',
16
+ absent: 'absent',
17
+ uncertain: 'uncertain',
18
+ }),
8
19
  materialized: Object.freeze({ commit: 'committed', uncertain: 'uncertain' }),
9
- committed: Object.freeze({}), absent: Object.freeze({}), uncertain: Object.freeze({}),
20
+ committed: Object.freeze({}),
21
+ absent: Object.freeze({}),
22
+ uncertain: Object.freeze({}),
10
23
  });
11
24
  const SCHEDULE_TRANSITIONS = Object.freeze({
12
25
  disabled: Object.freeze({ enable: 'enabled', revoke: 'revoked', expire: 'expired' }),
13
- enabled: Object.freeze({ disable: 'disabled', pause: 'paused', revoke: 'revoked', expire: 'expired', complete: 'completed', 'run-issued': 'enabled' }),
14
- paused: Object.freeze({ disable: 'disabled', resume: 'enabled', revoke: 'revoked', expire: 'expired' }),
15
- revoked: Object.freeze({}), expired: Object.freeze({}), completed: Object.freeze({}),
26
+ enabled: Object.freeze({
27
+ disable: 'disabled',
28
+ pause: 'paused',
29
+ revoke: 'revoked',
30
+ expire: 'expired',
31
+ complete: 'completed',
32
+ 'run-issued': 'enabled',
33
+ }),
34
+ paused: Object.freeze({
35
+ disable: 'disabled',
36
+ resume: 'enabled',
37
+ revoke: 'revoked',
38
+ expire: 'expired',
39
+ }),
40
+ revoked: Object.freeze({}),
41
+ expired: Object.freeze({}),
42
+ completed: Object.freeze({}),
16
43
  });
17
44
  const IMMUTABLE_CHECKPOINT_FIELDS = Object.freeze([
18
- 'checkpointId', 'requestId', 'requestHash', 'effect', 'provider', 'providerRegistrationHash',
19
- 'adapterVersion', 'sourceIdentityHash', 'credentialRefHash', 'boundsHash', 'queryHash',
20
- 'windowHash', 'redactionVersion', 'createdAt',
45
+ 'checkpointId',
46
+ 'requestId',
47
+ 'requestHash',
48
+ 'effect',
49
+ 'provider',
50
+ 'providerRegistrationHash',
51
+ 'adapterVersion',
52
+ 'sourceIdentityHash',
53
+ 'credentialRefHash',
54
+ 'boundsHash',
55
+ 'queryHash',
56
+ 'windowHash',
57
+ 'redactionVersion',
58
+ 'createdAt',
21
59
  ]);
22
60
  const CONNECTOR_EVENT_FIELDS = Object.freeze([
23
- 'eventId', 'eventHash', 'type', 'expectedGeneration', 'expectedCheckpointHash', 'at', 'patch',
61
+ 'eventId',
62
+ 'eventHash',
63
+ 'type',
64
+ 'expectedGeneration',
65
+ 'expectedCheckpointHash',
66
+ 'at',
67
+ 'patch',
24
68
  ]);
25
69
  const CONNECTOR_PATCH_FIELDS = Object.freeze({
26
- request: Object.freeze(['consentRecordId', 'consentRecordHash', 'consentExpiresAt', 'runtimeCapabilityHash', 'health']),
70
+ request: Object.freeze([
71
+ 'consentRecordId',
72
+ 'consentRecordHash',
73
+ 'consentExpiresAt',
74
+ 'runtimeCapabilityHash',
75
+ 'health',
76
+ ]),
27
77
  materialize: Object.freeze(['artifactId', 'artifactHash', 'watermarkDigest', 'health']),
28
78
  commit: Object.freeze(['watermarkDigest']),
29
79
  absent: Object.freeze(['absenceDigest', 'health']),
30
80
  uncertain: Object.freeze(['absenceDigest', 'health']),
31
81
  });
32
82
  const SCHEDULE_TRANSITION_FIELDS = Object.freeze([
33
- 'receiptId', 'type', 'expectedGeneration', 'expectedScheduleHash', 'expectedState',
34
- 'expectedRunCount', 'expectedNextEventIdentity', 'expectedNextDueAt', 'planHash',
35
- 'consentRecordHashes', 'ceilingsHash', 'clockHash', 'eventId', 'nextEventIdentity',
36
- 'nextDueAt', 'at',
83
+ 'receiptId',
84
+ 'type',
85
+ 'expectedGeneration',
86
+ 'expectedScheduleHash',
87
+ 'expectedState',
88
+ 'expectedRunCount',
89
+ 'expectedNextEventIdentity',
90
+ 'expectedNextDueAt',
91
+ 'planHash',
92
+ 'consentRecordHashes',
93
+ 'ceilingsHash',
94
+ 'clockHash',
95
+ 'eventId',
96
+ 'nextEventIdentity',
97
+ 'nextDueAt',
98
+ 'at',
37
99
  ]);
38
100
  const SOURCE_CONTRACTS = Object.freeze([
39
- 'capacity-throughput', 'channel-economics', 'ci-test-evidence', 'competitor-positioning',
40
- 'context-manifest', 'demand-market', 'finance-metrics', 'incident-history',
41
- 'objective-metrics', 'operations-customer-health', 'planning-acceptance', 'prior-decisions',
42
- 'product-activation', 'repository-architecture', 'retention-discovery', 'support-incidents',
101
+ 'capacity-throughput',
102
+ 'channel-economics',
103
+ 'ci-test-evidence',
104
+ 'competitor-positioning',
105
+ 'context-manifest',
106
+ 'demand-market',
107
+ 'finance-metrics',
108
+ 'incident-history',
109
+ 'objective-metrics',
110
+ 'operations-customer-health',
111
+ 'planning-acceptance',
112
+ 'prior-decisions',
113
+ 'product-activation',
114
+ 'repository-architecture',
115
+ 'retention-discovery',
116
+ 'support-incidents',
43
117
  ]);
44
118
 
45
119
  export const LIVE_EVIDENCE_ABSENCE_KINDS_V2 = Object.freeze([
46
- 'insufficient-evidence', 'missing-consent', 'missing-credential', 'provider-unavailable',
47
- 'rate-limited', 'stale', 'unhealthy', 'unsupported',
120
+ 'insufficient-evidence',
121
+ 'missing-consent',
122
+ 'missing-credential',
123
+ 'provider-unavailable',
124
+ 'rate-limited',
125
+ 'stale',
126
+ 'unhealthy',
127
+ 'unsupported',
48
128
  ]);
49
129
  export const LIVE_EVIDENCE_EFFECT_CLASS_V2 = 'provider-call';
50
130
  export const LIVE_EVIDENCE_PORTABLE_AUTHORITY_V2 = 'none';
51
- export const OPERATING_OUTCOME_EVALUATION_OPERATORS_V2 = Object.freeze(['gt', 'gte', 'lt', 'lte', 'eq', 'between']);
131
+ export const OPERATING_OUTCOME_EVALUATION_OPERATORS_V2 = Object.freeze([
132
+ 'gt',
133
+ 'gte',
134
+ 'lt',
135
+ 'lte',
136
+ 'eq',
137
+ 'between',
138
+ ]);
52
139
 
53
140
  export class OperatingLiveEvidenceErrorV2 extends Error {
54
141
  constructor(code, message, details = {}) {
@@ -88,14 +175,24 @@ function safePortable(value, path = '$') {
88
175
  return;
89
176
  }
90
177
  if (typeof value !== 'string') return;
91
- if (value.includes('\u0000') || value.startsWith('/') || value.startsWith('~')
92
- || /(?:^|[\s"'`(])\/(?:Users|home|private|var|etc|tmp)\//u.test(value)
93
- || /(?:^|[\s"'`(])[A-Za-z]:[\\/][^\s]+/u.test(value)
94
- || value.split(/[\\/]/u).includes('..')
95
- || /-----BEGIN [A-Z ]*PRIVATE KEY-----/u.test(value)
96
- || /\b(?:Bearer|Basic)\s+[A-Za-z0-9+/=._-]+/u.test(value)
97
- || /\b(?:api[-_ ]?key|access[-_ ]?token|client[-_ ]?secret|password|passwd|secret|token)\s*[:=]\s*[^\s]+/iu.test(value)) {
98
- fail('LIVE_EVIDENCE_UNSAFE', 'Live-evidence artifacts contain private path or credential material.', { path });
178
+ if (
179
+ value.includes('\u0000') ||
180
+ value.startsWith('/') ||
181
+ value.startsWith('~') ||
182
+ /(?:^|[\s"'`(])\/(?:Users|home|private|var|etc|tmp)\//u.test(value) ||
183
+ /(?:^|[\s"'`(])[A-Za-z]:[\\/][^\s]+/u.test(value) ||
184
+ value.split(/[\\/]/u).includes('..') ||
185
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----/u.test(value) ||
186
+ /\b(?:Bearer|Basic)\s+[A-Za-z0-9+/=._-]+/u.test(value) ||
187
+ /\b(?:api[-_ ]?key|access[-_ ]?token|client[-_ ]?secret|password|passwd|secret|token)\s*[:=]\s*[^\s]+/iu.test(
188
+ value,
189
+ )
190
+ ) {
191
+ fail(
192
+ 'LIVE_EVIDENCE_UNSAFE',
193
+ 'Live-evidence artifacts contain private path or credential material.',
194
+ { path },
195
+ );
99
196
  }
100
197
  }
101
198
 
@@ -103,7 +200,9 @@ function protocol(kind, value, protocolVersion = '2.0.0') {
103
200
  try {
104
201
  assertProtocolArtifact(kind, value, { protocolVersion });
105
202
  } catch (cause) {
106
- fail('LIVE_EVIDENCE_CONTRACT_INVALID', `Invalid ${kind} contract.`, { cause: cause.code ?? cause.message });
203
+ fail('LIVE_EVIDENCE_CONTRACT_INVALID', `Invalid ${kind} contract.`, {
204
+ cause: cause.code ?? cause.message,
205
+ });
107
206
  }
108
207
  }
109
208
 
@@ -111,18 +210,27 @@ function selfHash(record, field) {
111
210
  const { [field]: claimed, ...body } = record;
112
211
  const expected = sha256Jcs(body);
113
212
  if (!HASH.test(claimed ?? '') || claimed !== expected) {
114
- fail('LIVE_EVIDENCE_DIGEST_MISMATCH', `${field} does not bind the exact canonical record.`, { field, expected, actual: claimed ?? null });
213
+ fail('LIVE_EVIDENCE_DIGEST_MISMATCH', `${field} does not bind the exact canonical record.`, {
214
+ field,
215
+ expected,
216
+ actual: claimed ?? null,
217
+ });
115
218
  }
116
219
  return expected;
117
220
  }
118
221
 
119
222
  function exactDigest(record, expected, label) {
120
223
  const actual = sha256Jcs(record);
121
- if (actual !== expected) fail('LIVE_EVIDENCE_BASE_RECORD_MISMATCH', `${label} bytes do not match their bound digest.`, { expected, actual });
224
+ if (actual !== expected)
225
+ fail('LIVE_EVIDENCE_BASE_RECORD_MISMATCH', `${label} bytes do not match their bound digest.`, {
226
+ expected,
227
+ actual,
228
+ });
122
229
  }
123
230
 
124
231
  function same(left, right, label) {
125
- if (sha256Jcs(left) !== sha256Jcs(right)) fail('LIVE_EVIDENCE_BINDING_MISMATCH', `${label} binding changed.`, { left, right });
232
+ if (sha256Jcs(left) !== sha256Jcs(right))
233
+ fail('LIVE_EVIDENCE_BINDING_MISMATCH', `${label} binding changed.`, { left, right });
126
234
  }
127
235
 
128
236
  function assertExactKeys(value, expected, label) {
@@ -132,13 +240,19 @@ function assertExactKeys(value, expected, label) {
132
240
  const actual = Object.keys(value).sort();
133
241
  const wanted = [...expected].sort();
134
242
  if (!sameValue(actual, wanted)) {
135
- fail('LIVE_EVIDENCE_CONTRACT_INVALID', `${label} contains missing or unsupported fields.`, { actual, expected: wanted });
243
+ fail('LIVE_EVIDENCE_CONTRACT_INVALID', `${label} contains missing or unsupported fields.`, {
244
+ actual,
245
+ expected: wanted,
246
+ });
136
247
  }
137
248
  }
138
249
 
139
250
  function currentAt(timestamp, expiresAt, label) {
140
251
  if (!(Date.parse(timestamp) < Date.parse(expiresAt))) {
141
- fail('LIVE_EVIDENCE_STALE', `${label} is not current at the bound time.`, { timestamp, expiresAt });
252
+ fail('LIVE_EVIDENCE_STALE', `${label} is not current at the bound time.`, {
253
+ timestamp,
254
+ expiresAt,
255
+ });
142
256
  }
143
257
  }
144
258
 
@@ -147,28 +261,53 @@ function exactBaseRecord(options, singularKey, pluralKey, reference, identityFie
147
261
  options?.[singularKey],
148
262
  ...(Array.isArray(options?.[pluralKey]) ? options[pluralKey] : []),
149
263
  ].filter((entry) => entry !== undefined);
150
- const matching = supplied.filter((entry) => identityFields.every((field) => entry?.[field] === reference[field]));
264
+ const matching = supplied.filter((entry) =>
265
+ identityFields.every((field) => entry?.[field] === reference[field]),
266
+ );
151
267
  const unique = [...new Map(matching.map((entry) => [sha256Jcs(entry), entry])).values()];
152
268
  if (unique.length !== 1) {
153
- fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', `${label} requires exactly one matching frozen base record.`, {
154
- identity: Object.fromEntries(identityFields.map((field) => [field, reference[field]])),
155
- matches: unique.length,
156
- });
269
+ fail(
270
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
271
+ `${label} requires exactly one matching frozen base record.`,
272
+ {
273
+ identity: Object.fromEntries(identityFields.map((field) => [field, reference[field]])),
274
+ matches: unique.length,
275
+ },
276
+ );
157
277
  }
158
278
  return unique[0];
159
279
  }
160
280
 
161
281
  function assertProviderBaseRecords(record, options = {}) {
162
- const baseEvidenceProvider = exactBaseRecord(options, 'baseEvidenceProvider', 'baseEvidenceProviders',
163
- record.baseEvidenceProvider, ['providerId', 'providerVersion'], 'Live provider registration');
282
+ const baseEvidenceProvider = exactBaseRecord(
283
+ options,
284
+ 'baseEvidenceProvider',
285
+ 'baseEvidenceProviders',
286
+ record.baseEvidenceProvider,
287
+ ['providerId', 'providerVersion'],
288
+ 'Live provider registration',
289
+ );
164
290
  protocol('operate-evidence-provider-registration', baseEvidenceProvider);
165
- exactDigest(baseEvidenceProvider, record.baseEvidenceProvider.recordDigest, 'Evidence-provider registration');
166
- const baseResolver = exactBaseRecord(options, 'baseResolver', 'baseResolvers',
167
- record.baseResolver, ['resolverId', 'resolverVersion'], 'Live provider registration');
291
+ exactDigest(
292
+ baseEvidenceProvider,
293
+ record.baseEvidenceProvider.recordDigest,
294
+ 'Evidence-provider registration',
295
+ );
296
+ const baseResolver = exactBaseRecord(
297
+ options,
298
+ 'baseResolver',
299
+ 'baseResolvers',
300
+ record.baseResolver,
301
+ ['resolverId', 'resolverVersion'],
302
+ 'Live provider registration',
303
+ );
168
304
  protocol('operate-evidence-resolver-registration', baseResolver);
169
305
  exactDigest(baseResolver, record.baseResolver.recordDigest, 'Evidence-resolver registration');
170
306
  if (!baseResolver.supportedEvidenceKinds.includes('operate-artifact')) {
171
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'The base resolver must use the canonical operate-artifact boundary.');
307
+ fail(
308
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
309
+ 'The base resolver must use the canonical operate-artifact boundary.',
310
+ );
172
311
  }
173
312
  }
174
313
 
@@ -176,11 +315,19 @@ function assertLiveEvidenceProviderRegistrationStructureV2(record) {
176
315
  protocol('operate-live-evidence-provider-registration', record);
177
316
  safePortable(record);
178
317
  selfHash(record, 'registrationHash');
179
- if (record.effects.length !== 1 || record.effects[0] !== 'provider-call'
180
- || record.consent.required !== true || record.consent.mode !== 'named-owner-current'
181
- || record.consent.runtimeCapability !== 'opaque-local-preissued'
182
- || record.consent.noDefaultChoice !== true || record.consent.previewEffect !== 'none') {
183
- fail('LIVE_EVIDENCE_AUTHORITY_INVALID', 'Registration must require current consent and a pre-issued opaque capability for provider-call.');
318
+ if (
319
+ record.effects.length !== 1 ||
320
+ record.effects[0] !== 'provider-call' ||
321
+ record.consent.required !== true ||
322
+ record.consent.mode !== 'named-owner-current' ||
323
+ record.consent.runtimeCapability !== 'opaque-local-preissued' ||
324
+ record.consent.noDefaultChoice !== true ||
325
+ record.consent.previewEffect !== 'none'
326
+ ) {
327
+ fail(
328
+ 'LIVE_EVIDENCE_AUTHORITY_INVALID',
329
+ 'Registration must require current consent and a pre-issued opaque capability for provider-call.',
330
+ );
184
331
  }
185
332
  return freeze(clone(record));
186
333
  }
@@ -201,7 +348,11 @@ export function assertLiveEvidenceProviderRegistryV2(registry, options = {}) {
201
348
  assertLiveEvidenceProviderRegistrationV2(provider, options);
202
349
  const identity = `${provider.providerId}@${provider.providerVersion}`;
203
350
  if (identities.has(identity) || (previous !== null && identity.localeCompare(previous) <= 0)) {
204
- fail('LIVE_EVIDENCE_REGISTRY_CONFLICT', 'Provider registry membership must be unique and canonically ordered.', { identity });
351
+ fail(
352
+ 'LIVE_EVIDENCE_REGISTRY_CONFLICT',
353
+ 'Provider registry membership must be unique and canonically ordered.',
354
+ { identity },
355
+ );
205
356
  }
206
357
  identities.add(identity);
207
358
  previous = identity;
@@ -212,17 +363,30 @@ export function assertLiveEvidenceProviderRegistryV2(registry, options = {}) {
212
363
  export function registerLiveEvidenceProviderV2(registry, registration, options = {}) {
213
364
  const current = assertLiveEvidenceProviderRegistryV2(registry, options);
214
365
  const provider = assertLiveEvidenceProviderRegistrationV2(registration, options);
215
- const index = current.providers.findIndex((entry) => entry.providerId === provider.providerId && entry.providerVersion === provider.providerVersion);
366
+ const index = current.providers.findIndex(
367
+ (entry) =>
368
+ entry.providerId === provider.providerId &&
369
+ entry.providerVersion === provider.providerVersion,
370
+ );
216
371
  if (index >= 0) {
217
372
  if (current.providers[index].registrationHash !== provider.registrationHash) {
218
- fail('LIVE_EVIDENCE_REGISTRY_CONFLICT', 'Divergent provider bytes cannot reuse one provider identity.');
373
+ fail(
374
+ 'LIVE_EVIDENCE_REGISTRY_CONFLICT',
375
+ 'Divergent provider bytes cannot reuse one provider identity.',
376
+ );
219
377
  }
220
378
  return current;
221
379
  }
222
380
  const next = clone(current);
223
381
  next.providers.push(clone(provider));
224
- next.providers.sort((left, right) => `${left.providerId}@${left.providerVersion}`.localeCompare(`${right.providerId}@${right.providerVersion}`));
225
- next.registryHash = sha256Jcs(Object.fromEntries(Object.entries(next).filter(([key]) => key !== 'registryHash')));
382
+ next.providers.sort((left, right) =>
383
+ `${left.providerId}@${left.providerVersion}`.localeCompare(
384
+ `${right.providerId}@${right.providerVersion}`,
385
+ ),
386
+ );
387
+ next.registryHash = sha256Jcs(
388
+ Object.fromEntries(Object.entries(next).filter(([key]) => key !== 'registryHash')),
389
+ );
226
390
  return assertLiveEvidenceProviderRegistryV2(next, options);
227
391
  }
228
392
 
@@ -230,129 +394,276 @@ export function assertOperatingLiveEvidenceConsentRecordV2(record) {
230
394
  protocol('operating-live-evidence-consent-record', record);
231
395
  safePortable(record);
232
396
  selfHash(record, 'consentHash');
233
- if (record.authority !== 'none' || record.docket.defaultChoice !== null || record.docket.cancelEffect !== 'none') {
234
- fail('LIVE_EVIDENCE_AUTHORITY_INVALID', 'Consent proof and docket cannot grant access authority or preselect an owner choice.');
235
- }
236
- if (sha256Jcs(record.docket) !== record.docketHash) fail('LIVE_EVIDENCE_DIGEST_MISMATCH', 'Consent docket bytes changed.');
397
+ if (
398
+ record.authority !== 'none' ||
399
+ record.docket.defaultChoice !== null ||
400
+ record.docket.cancelEffect !== 'none'
401
+ ) {
402
+ fail(
403
+ 'LIVE_EVIDENCE_AUTHORITY_INVALID',
404
+ 'Consent proof and docket cannot grant access authority or preselect an owner choice.',
405
+ );
406
+ }
407
+ if (sha256Jcs(record.docket) !== record.docketHash)
408
+ fail('LIVE_EVIDENCE_DIGEST_MISMATCH', 'Consent docket bytes changed.');
237
409
  same(record.docket.provider, record.provider, 'Consent provider');
238
- for (const field of ['adapterVersion', 'accountIdentityHash', 'selectors', 'scopes', 'queryHash', 'window', 'ceilings', 'classification', 'purpose', 'expiresAt']) {
410
+ for (const field of [
411
+ 'adapterVersion',
412
+ 'accountIdentityHash',
413
+ 'selectors',
414
+ 'scopes',
415
+ 'queryHash',
416
+ 'window',
417
+ 'ceilings',
418
+ 'classification',
419
+ 'purpose',
420
+ 'expiresAt',
421
+ ]) {
239
422
  same(record.docket[field], record[field], `Consent ${field}`);
240
423
  }
241
424
  currentAt(record.issuedAt, record.expiresAt, 'Consent');
242
425
  return freeze(clone(record));
243
426
  }
244
427
 
245
- export function assertOperatingLiveEvidenceIngestionV2(record, {
246
- liveProviderRegistration, baseEvidenceProvider, baseResolver, assignment,
247
- consentRecord, connectorCheckpoint,
248
- } = {}) {
428
+ export function assertOperatingLiveEvidenceIngestionV2(
429
+ record,
430
+ {
431
+ liveProviderRegistration,
432
+ baseEvidenceProvider,
433
+ baseResolver,
434
+ assignment,
435
+ consentRecord,
436
+ connectorCheckpoint,
437
+ } = {},
438
+ ) {
249
439
  protocol('operating-live-evidence-ingestion', record);
250
440
  safePortable(record);
251
441
  selfHash(record, 'ingestionHash');
252
- if (!SOURCE_CONTRACTS.includes(record.sourceContract.id)) fail('LIVE_EVIDENCE_SOURCE_CONTRACT_INVALID', 'Ingestion source contract is not accepted by the frozen operate-artifact resolver.');
442
+ if (!SOURCE_CONTRACTS.includes(record.sourceContract.id))
443
+ fail(
444
+ 'LIVE_EVIDENCE_SOURCE_CONTRACT_INVALID',
445
+ 'Ingestion source contract is not accepted by the frozen operate-artifact resolver.',
446
+ );
253
447
  if (record.status === 'materialized') {
254
- if (record.health.status !== 'available' || record.absences.length !== 0 || record.records.length === 0) {
255
- fail('LIVE_EVIDENCE_FALSE_PASS', 'Materialized evidence requires available health, records, and no absence.');
448
+ if (
449
+ record.health.status !== 'available' ||
450
+ record.absences.length !== 0 ||
451
+ record.records.length === 0
452
+ ) {
453
+ fail(
454
+ 'LIVE_EVIDENCE_FALSE_PASS',
455
+ 'Materialized evidence requires available health, records, and no absence.',
456
+ );
256
457
  }
257
- if (record.materialization.contentDigest !== deriveOperatingLiveEvidenceContentDigestV2(record)) {
258
- fail('LIVE_EVIDENCE_DIGEST_MISMATCH', 'Materialization contentDigest does not bind the exact redacted record manifest.');
458
+ if (
459
+ record.materialization.contentDigest !== deriveOperatingLiveEvidenceContentDigestV2(record)
460
+ ) {
461
+ fail(
462
+ 'LIVE_EVIDENCE_DIGEST_MISMATCH',
463
+ 'Materialization contentDigest does not bind the exact redacted record manifest.',
464
+ );
259
465
  }
260
466
  currentAt(record.sourceTiming.capturedAt, record.health.freshUntil, 'Provider health');
261
467
  currentAt(record.sourceTiming.capturedAt, record.sourceTiming.freshUntil, 'Source evidence');
262
468
  }
263
- if (record.assignment.requestHash !== record.requestHash || record.submission.operation !== 'operate.assignment.submit') {
264
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Ingestion must bind its issued Assignment request and normal submission operation.');
469
+ if (
470
+ record.assignment.requestHash !== record.requestHash ||
471
+ record.submission.operation !== 'operate.assignment.submit'
472
+ ) {
473
+ fail(
474
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
475
+ 'Ingestion must bind its issued Assignment request and normal submission operation.',
476
+ );
265
477
  }
266
478
  if (record.assignment.assignmentRevision !== 1) {
267
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'The immutable Protocol 2.0 Assignment revision must be one.');
479
+ fail(
480
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
481
+ 'The immutable Protocol 2.0 Assignment revision must be one.',
482
+ );
268
483
  }
269
484
  if (record.materialization !== null) {
270
- for (const field of ['artifactId', 'artifactCreatedEventId', 'evidenceRefId']) same(record.materialization[field], record.submission[field], `Materialization ${field}`);
485
+ for (const field of ['artifactId', 'artifactCreatedEventId', 'evidenceRefId'])
486
+ same(record.materialization[field], record.submission[field], `Materialization ${field}`);
271
487
  }
272
488
  for (const candidate of record.evidenceCandidates) {
273
- if (candidate.evidenceKind !== 'operate-artifact' || candidate.sourceArtifactId !== record.submission.artifactId
274
- || candidate.locator?.artifactId !== record.submission.artifactId
275
- || candidate.locator?.expectedArtifactType !== 'live-evidence-ingestion'
276
- || candidate.locator?.expectedSchemaId !== 'operating-live-evidence-ingestion'
277
- || candidate.locator?.expectedSchemaVersion !== '2.0.0'
278
- || candidate.provider.id !== record.providerRegistration.providerId
279
- || candidate.provider.version !== record.providerRegistration.providerVersion
280
- || candidate.resolver.id !== record.resolverRegistration.resolverId
281
- || candidate.resolver.version !== record.resolverRegistration.resolverVersion) {
282
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Evidence candidates must reference the pre-issued accepted ingestion Artifact.');
489
+ if (
490
+ candidate.evidenceKind !== 'operate-artifact' ||
491
+ candidate.sourceArtifactId !== record.submission.artifactId ||
492
+ candidate.locator?.artifactId !== record.submission.artifactId ||
493
+ candidate.locator?.expectedArtifactType !== 'live-evidence-ingestion' ||
494
+ candidate.locator?.expectedSchemaId !== 'operating-live-evidence-ingestion' ||
495
+ candidate.locator?.expectedSchemaVersion !== '2.0.0' ||
496
+ candidate.provider.id !== record.providerRegistration.providerId ||
497
+ candidate.provider.version !== record.providerRegistration.providerVersion ||
498
+ candidate.resolver.id !== record.resolverRegistration.resolverId ||
499
+ candidate.resolver.version !== record.resolverRegistration.resolverVersion
500
+ ) {
501
+ fail(
502
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
503
+ 'Evidence candidates must reference the pre-issued accepted ingestion Artifact.',
504
+ );
283
505
  }
284
506
  }
285
507
  for (const link of record.evidenceClaimLinks) {
286
- if (link.sourceArtifactId !== record.submission.artifactId
287
- || !record.evidenceCandidates.some((candidate) => candidate.candidateId === link.candidateId)) {
288
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Evidence claim links must bind a declared candidate and accepted source Artifact.');
508
+ if (
509
+ link.sourceArtifactId !== record.submission.artifactId ||
510
+ !record.evidenceCandidates.some((candidate) => candidate.candidateId === link.candidateId)
511
+ ) {
512
+ fail(
513
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
514
+ 'Evidence claim links must bind a declared candidate and accepted source Artifact.',
515
+ );
289
516
  }
290
517
  }
291
518
  if (liveProviderRegistration !== undefined) {
292
- const registration = assertLiveEvidenceProviderRegistrationV2(liveProviderRegistration, { baseEvidenceProvider, baseResolver });
293
- if (registration.registrationHash !== record.providerRegistrationHash) fail('LIVE_EVIDENCE_BASE_RECORD_MISMATCH', 'Live provider registration changed.');
294
- same([registration.providerId, registration.providerVersion, registration.adapterVersion], [record.provider.id, record.provider.version, record.adapterVersion], 'Live provider');
295
- same(registration.baseEvidenceProvider, record.providerRegistration, 'Base evidence-provider reference');
296
- same(registration.baseResolver, record.resolverRegistration, 'Base evidence-resolver reference');
297
- }
298
- if (record.resolverRegistrationHash !== record.resolverRegistration.recordDigest) fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Resolver registration digest fields disagree.');
519
+ const registration = assertLiveEvidenceProviderRegistrationV2(liveProviderRegistration, {
520
+ baseEvidenceProvider,
521
+ baseResolver,
522
+ });
523
+ if (registration.registrationHash !== record.providerRegistrationHash)
524
+ fail('LIVE_EVIDENCE_BASE_RECORD_MISMATCH', 'Live provider registration changed.');
525
+ same(
526
+ [registration.providerId, registration.providerVersion, registration.adapterVersion],
527
+ [record.provider.id, record.provider.version, record.adapterVersion],
528
+ 'Live provider',
529
+ );
530
+ same(
531
+ registration.baseEvidenceProvider,
532
+ record.providerRegistration,
533
+ 'Base evidence-provider reference',
534
+ );
535
+ same(
536
+ registration.baseResolver,
537
+ record.resolverRegistration,
538
+ 'Base evidence-resolver reference',
539
+ );
540
+ }
541
+ if (record.resolverRegistrationHash !== record.resolverRegistration.recordDigest)
542
+ fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Resolver registration digest fields disagree.');
299
543
  if (baseEvidenceProvider !== undefined) {
300
544
  protocol('operate-evidence-provider-registration', baseEvidenceProvider);
301
- exactDigest(baseEvidenceProvider, record.providerRegistration.recordDigest, 'Base evidence-provider registration');
545
+ exactDigest(
546
+ baseEvidenceProvider,
547
+ record.providerRegistration.recordDigest,
548
+ 'Base evidence-provider registration',
549
+ );
302
550
  }
303
551
  if (baseResolver !== undefined) {
304
552
  protocol('operate-evidence-resolver-registration', baseResolver);
305
- exactDigest(baseResolver, record.resolverRegistration.recordDigest, 'Base evidence-resolver registration');
306
- if (!baseResolver.supportedSourceContracts.some((entry) => sameValue(entry, record.sourceContract))) {
307
- fail('LIVE_EVIDENCE_SOURCE_CONTRACT_INVALID', 'The selected resolver does not support the ingestion source contract.');
553
+ exactDigest(
554
+ baseResolver,
555
+ record.resolverRegistration.recordDigest,
556
+ 'Base evidence-resolver registration',
557
+ );
558
+ if (
559
+ !baseResolver.supportedSourceContracts.some((entry) =>
560
+ sameValue(entry, record.sourceContract),
561
+ )
562
+ ) {
563
+ fail(
564
+ 'LIVE_EVIDENCE_SOURCE_CONTRACT_INVALID',
565
+ 'The selected resolver does not support the ingestion source contract.',
566
+ );
308
567
  }
309
568
  }
310
569
  if (assignment !== undefined) {
311
570
  protocol('operating-assignment', assignment);
312
571
  exactDigest(assignment, record.assignment.assignmentHash, 'Issued Assignment');
313
- if (assignment.assignmentId !== record.assignment.assignmentId || assignment.assignmentKind !== 'verification'
314
- || assignment.outputContract.schemaId !== 'operating-live-evidence-ingestion'
315
- || assignment.outputContract.schemaVersion !== '2.0.0') {
316
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'The canonical Assignment does not authorize this ingestion output.');
572
+ if (
573
+ assignment.assignmentId !== record.assignment.assignmentId ||
574
+ assignment.assignmentKind !== 'verification' ||
575
+ assignment.outputContract.schemaId !== 'operating-live-evidence-ingestion' ||
576
+ assignment.outputContract.schemaVersion !== '2.0.0'
577
+ ) {
578
+ fail(
579
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
580
+ 'The canonical Assignment does not authorize this ingestion output.',
581
+ );
317
582
  }
318
583
  }
319
- if (record.status === 'materialized' && (assignment === undefined || consentRecord === undefined
320
- || connectorCheckpoint === undefined || liveProviderRegistration === undefined
321
- || baseEvidenceProvider === undefined || baseResolver === undefined)) {
322
- fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'Materialized ingestion requires exact Assignment, consent, checkpoint, and provider registrations.');
584
+ if (
585
+ record.status === 'materialized' &&
586
+ (assignment === undefined ||
587
+ consentRecord === undefined ||
588
+ connectorCheckpoint === undefined ||
589
+ liveProviderRegistration === undefined ||
590
+ baseEvidenceProvider === undefined ||
591
+ baseResolver === undefined)
592
+ ) {
593
+ fail(
594
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
595
+ 'Materialized ingestion requires exact Assignment, consent, checkpoint, and provider registrations.',
596
+ );
323
597
  }
324
598
  if (consentRecord !== undefined) {
325
599
  const consent = assertOperatingLiveEvidenceConsentRecordV2(consentRecord);
326
- if (consent.consentHash !== record.consentRecordHash) fail('LIVE_EVIDENCE_BASE_RECORD_MISMATCH', 'Consent record changed.');
327
- same([consent.provider, consent.adapterVersion, consent.classification], [record.provider, record.adapterVersion, record.classification], 'Consent provider');
328
- if (sha256Jcs(consent.ceilings) !== record.boundsHash) fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Consent ceilings changed.');
600
+ if (consent.consentHash !== record.consentRecordHash)
601
+ fail('LIVE_EVIDENCE_BASE_RECORD_MISMATCH', 'Consent record changed.');
602
+ same(
603
+ [consent.provider, consent.adapterVersion, consent.classification],
604
+ [record.provider, record.adapterVersion, record.classification],
605
+ 'Consent provider',
606
+ );
607
+ if (sha256Jcs(consent.ceilings) !== record.boundsHash)
608
+ fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Consent ceilings changed.');
329
609
  currentAt(record.sourceTiming.capturedAt, consent.expiresAt, 'Consent');
330
610
  }
331
611
  if (connectorCheckpoint !== undefined) {
332
612
  const checkpoint = assertOperatingConnectorCheckpointV2(connectorCheckpoint);
333
- if (checkpoint.state !== 'requesting' || checkpoint.checkpointId !== record.checkpoint.checkpointId
334
- || checkpoint.checkpointHash !== record.checkpoint.checkpointHash
335
- || checkpoint.predecessorDigest !== record.checkpoint.predecessorDigest
336
- || checkpoint.requestId !== record.requestId || checkpoint.providerRegistrationHash !== record.providerRegistrationHash
337
- || checkpoint.consentRecordHash !== record.consentRecordHash
338
- || checkpoint.runtimeCapabilityHash !== record.runtimeCapabilityHash
339
- || checkpoint.boundsHash !== record.boundsHash || !sameValue(checkpoint.provider, record.provider)
340
- || checkpoint.adapterVersion !== record.adapterVersion || !sameValue(checkpoint.health, record.health)) {
341
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Ingestion changed its exact requesting connector checkpoint.');
613
+ if (
614
+ checkpoint.state !== 'requesting' ||
615
+ checkpoint.checkpointId !== record.checkpoint.checkpointId ||
616
+ checkpoint.checkpointHash !== record.checkpoint.checkpointHash ||
617
+ checkpoint.predecessorDigest !== record.checkpoint.predecessorDigest ||
618
+ checkpoint.requestId !== record.requestId ||
619
+ checkpoint.providerRegistrationHash !== record.providerRegistrationHash ||
620
+ checkpoint.consentRecordHash !== record.consentRecordHash ||
621
+ checkpoint.runtimeCapabilityHash !== record.runtimeCapabilityHash ||
622
+ checkpoint.boundsHash !== record.boundsHash ||
623
+ !sameValue(checkpoint.provider, record.provider) ||
624
+ checkpoint.adapterVersion !== record.adapterVersion ||
625
+ !sameValue(checkpoint.health, record.health)
626
+ ) {
627
+ fail(
628
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
629
+ 'Ingestion changed its exact requesting connector checkpoint.',
630
+ );
342
631
  }
343
- if (consentRecord !== undefined && (checkpoint.queryHash !== consentRecord.queryHash
344
- || checkpoint.windowHash !== sha256Jcs(consentRecord.window)
345
- || checkpoint.boundsHash !== sha256Jcs(consentRecord.ceilings))) {
346
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Checkpoint query, window, or bounds changed from owner consent.');
632
+ if (
633
+ consentRecord !== undefined &&
634
+ (checkpoint.queryHash !== consentRecord.queryHash ||
635
+ checkpoint.windowHash !== sha256Jcs(consentRecord.window) ||
636
+ checkpoint.boundsHash !== sha256Jcs(consentRecord.ceilings))
637
+ ) {
638
+ fail(
639
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
640
+ 'Checkpoint query, window, or bounds changed from owner consent.',
641
+ );
347
642
  }
348
643
  }
349
- if (assignment !== undefined && consentRecord !== undefined && connectorCheckpoint !== undefined) {
644
+ if (
645
+ assignment !== undefined &&
646
+ consentRecord !== undefined &&
647
+ connectorCheckpoint !== undefined
648
+ ) {
350
649
  const expectedRequestHash = deriveOperatingLiveEvidenceRequestHashV2({
351
- assignment, consentRecord, connectorCheckpoint, liveProviderRegistration, sourceContract: record.sourceContract,
352
- baseEvidenceProvider, baseResolver, classification: record.classification,
650
+ assignment,
651
+ consentRecord,
652
+ connectorCheckpoint,
653
+ liveProviderRegistration,
654
+ sourceContract: record.sourceContract,
655
+ baseEvidenceProvider,
656
+ baseResolver,
657
+ classification: record.classification,
353
658
  });
354
- if (record.requestHash !== expectedRequestHash || connectorCheckpoint.requestHash !== expectedRequestHash) {
355
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Ingestion request is not the engine-derived Assignment/provider request.');
659
+ if (
660
+ record.requestHash !== expectedRequestHash ||
661
+ connectorCheckpoint.requestHash !== expectedRequestHash
662
+ ) {
663
+ fail(
664
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
665
+ 'Ingestion request is not the engine-derived Assignment/provider request.',
666
+ );
356
667
  }
357
668
  }
358
669
  return freeze(clone(record));
@@ -363,14 +674,21 @@ function sameValue(left, right) {
363
674
  }
364
675
 
365
676
  export function deriveOperatingLiveEvidenceRequestHashV2({
366
- assignment, consentRecord, connectorCheckpoint, liveProviderRegistration, baseEvidenceProvider, baseResolver,
367
- sourceContract, classification,
677
+ assignment,
678
+ consentRecord,
679
+ connectorCheckpoint,
680
+ liveProviderRegistration,
681
+ baseEvidenceProvider,
682
+ baseResolver,
683
+ sourceContract,
684
+ classification,
368
685
  }) {
369
686
  protocol('operating-assignment', assignment);
370
687
  const consent = assertOperatingLiveEvidenceConsentRecordV2(consentRecord);
371
688
  const checkpoint = assertOperatingConnectorCheckpointV2(connectorCheckpoint);
372
689
  const registration = assertLiveEvidenceProviderRegistrationV2(liveProviderRegistration, {
373
- baseEvidenceProvider, baseResolver,
690
+ baseEvidenceProvider,
691
+ baseResolver,
374
692
  });
375
693
  return sha256Jcs({
376
694
  domain: 'openplanr-operating-live-evidence-request-v2',
@@ -392,10 +710,19 @@ export function deriveOperatingLiveEvidenceRequestHashV2({
392
710
  }
393
711
 
394
712
  export function deriveOperatingLiveEvidenceContentDigestV2(record) {
395
- if (record?.materialization === null || record?.materialization === undefined || !Array.isArray(record?.records)) {
396
- fail('LIVE_EVIDENCE_CONTRACT_INVALID', 'Materialized live evidence requires a redacted record manifest.');
397
- }
398
- const records = clone(record.records).sort((left, right) => left.recordIdentityHash.localeCompare(right.recordIdentityHash));
713
+ if (
714
+ record?.materialization === null ||
715
+ record?.materialization === undefined ||
716
+ !Array.isArray(record?.records)
717
+ ) {
718
+ fail(
719
+ 'LIVE_EVIDENCE_CONTRACT_INVALID',
720
+ 'Materialized live evidence requires a redacted record manifest.',
721
+ );
722
+ }
723
+ const records = clone(record.records).sort((left, right) =>
724
+ left.recordIdentityHash.localeCompare(right.recordIdentityHash),
725
+ );
399
726
  return sha256Jcs({
400
727
  domain: 'openplanr-operating-live-evidence-redacted-content-v2',
401
728
  redactionVersion: record.materialization.redactionVersion,
@@ -403,125 +730,226 @@ export function deriveOperatingLiveEvidenceContentDigestV2(record) {
403
730
  });
404
731
  }
405
732
 
406
- export function assertAcceptedLiveEvidenceSourceV2(record, {
407
- assignment, artifact, submittedEvent, artifactCreatedEvent, validatedEvent,
408
- ...options
409
- }) {
733
+ export function assertAcceptedLiveEvidenceSourceV2(
734
+ record,
735
+ { assignment, artifact, submittedEvent, artifactCreatedEvent, validatedEvent, ...options },
736
+ ) {
410
737
  const ingestion = assertOperatingLiveEvidenceIngestionV2(record, { assignment, ...options });
411
738
  protocol('operating-artifact', artifact);
412
739
  protocol('operating-event', submittedEvent);
413
740
  protocol('operating-event', artifactCreatedEvent);
414
741
  protocol('operating-event', validatedEvent);
415
- if (artifact.artifactId !== ingestion.submission.artifactId || artifact.assignmentId !== ingestion.assignment.assignmentId
416
- || artifact.artifactType !== 'live-evidence-ingestion'
417
- || artifact.schemaId !== 'operating-live-evidence-ingestion' || artifact.artifactSchemaVersion !== '2.0.0'
418
- || artifact.canonicalHash !== sha256Jcs(ingestion)) {
419
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Accepted Artifact does not bind the exact ingestion bytes and Assignment.');
420
- }
421
- const eventBindings = [[submittedEvent, 'assignment.submitted', ingestion.submission.submittedEventId], [artifactCreatedEvent, 'artifact.created', ingestion.submission.artifactCreatedEventId], [validatedEvent, 'assignment.validated', ingestion.submission.validatedEventId]];
742
+ if (
743
+ artifact.artifactId !== ingestion.submission.artifactId ||
744
+ artifact.assignmentId !== ingestion.assignment.assignmentId ||
745
+ artifact.artifactType !== 'live-evidence-ingestion' ||
746
+ artifact.schemaId !== 'operating-live-evidence-ingestion' ||
747
+ artifact.artifactSchemaVersion !== '2.0.0' ||
748
+ artifact.canonicalHash !== sha256Jcs(ingestion)
749
+ ) {
750
+ fail(
751
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
752
+ 'Accepted Artifact does not bind the exact ingestion bytes and Assignment.',
753
+ );
754
+ }
755
+ const eventBindings = [
756
+ [submittedEvent, 'assignment.submitted', ingestion.submission.submittedEventId],
757
+ [artifactCreatedEvent, 'artifact.created', ingestion.submission.artifactCreatedEventId],
758
+ [validatedEvent, 'assignment.validated', ingestion.submission.validatedEventId],
759
+ ];
422
760
  for (const [event, type, eventId] of eventBindings) {
423
761
  selfHash(event, 'eventHash');
424
- if (event.eventId !== eventId || event.type !== type || event.cycleId !== artifact.cycleId
425
- || event.timestamp !== artifact.createdAt || event.actor.kind !== 'runtime' || event.actor.id !== 'openplanr') {
426
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Accepted Event lineage does not match the pre-issued ingestion identities.', { type });
762
+ if (
763
+ event.eventId !== eventId ||
764
+ event.type !== type ||
765
+ event.cycleId !== artifact.cycleId ||
766
+ event.timestamp !== artifact.createdAt ||
767
+ event.actor.kind !== 'runtime' ||
768
+ event.actor.id !== 'openplanr'
769
+ ) {
770
+ fail(
771
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
772
+ 'Accepted Event lineage does not match the pre-issued ingestion identities.',
773
+ { type },
774
+ );
427
775
  }
428
776
  }
429
- if (submittedEvent.entityId !== assignment.assignmentId || artifactCreatedEvent.entityId !== artifact.artifactId
430
- || validatedEvent.entityId !== assignment.assignmentId
431
- || artifactCreatedEvent.causationId !== submittedEvent.eventId || validatedEvent.causationId !== artifactCreatedEvent.eventId
432
- || submittedEvent.correlationId !== artifactCreatedEvent.correlationId || submittedEvent.correlationId !== validatedEvent.correlationId
433
- || artifactCreatedEvent.previousEventHash !== submittedEvent.eventHash || validatedEvent.previousEventHash !== artifactCreatedEvent.eventHash
434
- || artifactCreatedEvent.sequence !== submittedEvent.sequence + 1 || validatedEvent.sequence !== artifactCreatedEvent.sequence + 1
435
- || !sameValue(submittedEvent.payload, {
436
- assignmentId: assignment.assignmentId, submissionId: ingestion.submission.submissionId,
437
- rawHash: artifact.rawHash, canonicalHash: artifact.canonicalHash, sizeBytes: artifact.sizeBytes,
438
- mediaType: artifact.mediaType, encoding: artifact.encoding,
439
- }) || !sameValue(artifactCreatedEvent.payload, artifact)
440
- || validatedEvent.payload.assignmentId !== assignment.assignmentId
441
- || validatedEvent.payload.submissionId !== ingestion.submission.submissionId
442
- || validatedEvent.payload.artifactId !== artifact.artifactId
443
- || typeof validatedEvent.payload.validatorVersion !== 'string') {
444
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Runtime-created Assignment/Event payload or chain changed.');
777
+ if (
778
+ submittedEvent.entityId !== assignment.assignmentId ||
779
+ artifactCreatedEvent.entityId !== artifact.artifactId ||
780
+ validatedEvent.entityId !== assignment.assignmentId ||
781
+ artifactCreatedEvent.causationId !== submittedEvent.eventId ||
782
+ validatedEvent.causationId !== artifactCreatedEvent.eventId ||
783
+ submittedEvent.correlationId !== artifactCreatedEvent.correlationId ||
784
+ submittedEvent.correlationId !== validatedEvent.correlationId ||
785
+ artifactCreatedEvent.previousEventHash !== submittedEvent.eventHash ||
786
+ validatedEvent.previousEventHash !== artifactCreatedEvent.eventHash ||
787
+ artifactCreatedEvent.sequence !== submittedEvent.sequence + 1 ||
788
+ validatedEvent.sequence !== artifactCreatedEvent.sequence + 1 ||
789
+ !sameValue(submittedEvent.payload, {
790
+ assignmentId: assignment.assignmentId,
791
+ submissionId: ingestion.submission.submissionId,
792
+ rawHash: artifact.rawHash,
793
+ canonicalHash: artifact.canonicalHash,
794
+ sizeBytes: artifact.sizeBytes,
795
+ mediaType: artifact.mediaType,
796
+ encoding: artifact.encoding,
797
+ }) ||
798
+ !sameValue(artifactCreatedEvent.payload, artifact) ||
799
+ validatedEvent.payload.assignmentId !== assignment.assignmentId ||
800
+ validatedEvent.payload.submissionId !== ingestion.submission.submissionId ||
801
+ validatedEvent.payload.artifactId !== artifact.artifactId ||
802
+ typeof validatedEvent.payload.validatorVersion !== 'string'
803
+ ) {
804
+ fail(
805
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
806
+ 'Runtime-created Assignment/Event payload or chain changed.',
807
+ );
445
808
  }
446
809
  return ingestion;
447
810
  }
448
811
 
449
- export function assertAcceptedLiveEvidenceBridgeV2(record, {
450
- assignment, artifact, submittedEvent, artifactCreatedEvent, validatedEvent, evidenceRef,
451
- evidenceArtifact, evidenceResolution, resultCheckpoint, checkpointHistory = [],
452
- ...options
453
- }) {
812
+ export function assertAcceptedLiveEvidenceBridgeV2(
813
+ record,
814
+ {
815
+ assignment,
816
+ artifact,
817
+ submittedEvent,
818
+ artifactCreatedEvent,
819
+ validatedEvent,
820
+ evidenceRef,
821
+ evidenceArtifact,
822
+ evidenceResolution,
823
+ resultCheckpoint,
824
+ checkpointHistory = [],
825
+ ...options
826
+ },
827
+ ) {
454
828
  const ingestion = assertAcceptedLiveEvidenceSourceV2(record, {
455
- assignment, artifact, submittedEvent, artifactCreatedEvent, validatedEvent, ...options,
829
+ assignment,
830
+ artifact,
831
+ submittedEvent,
832
+ artifactCreatedEvent,
833
+ validatedEvent,
834
+ ...options,
456
835
  });
457
836
  protocol('operating-evidence-ref', evidenceRef);
458
837
  protocol('operating-artifact', evidenceArtifact);
459
838
  protocol('operating-evidence-resolution', evidenceResolution);
460
- const candidate = ingestion.evidenceCandidates.find((entry) => entry.candidateId === evidenceRef.candidateId);
461
- const expectedLocator = candidate === undefined ? null : {
462
- artifactId: candidate.locator.artifactId,
463
- expectedArtifactType: candidate.locator.expectedArtifactType,
464
- expectedSchemaId: candidate.locator.expectedSchemaId,
465
- expectedSchemaVersion: candidate.locator.expectedSchemaVersion,
466
- expectedRawHash: artifact.rawHash,
467
- expectedCanonicalHash: artifact.canonicalHash,
468
- };
469
- if (evidenceRef.evidenceRefId !== ingestion.submission.evidenceRefId || evidenceRef.sourceArtifactId !== artifact.artifactId
470
- || candidate === undefined || evidenceRef.evidenceKind !== 'operate-artifact'
471
- || !sameValue(evidenceRef.sourceContract, ingestion.sourceContract)
472
- || (candidate.locator.expectedRawHash !== undefined && candidate.locator.expectedRawHash !== artifact.rawHash)
473
- || (candidate.locator.expectedCanonicalHash !== undefined && candidate.locator.expectedCanonicalHash !== artifact.canonicalHash)
474
- || !sameValue(evidenceRef.locator, expectedLocator)
475
- || !sameValue(evidenceRef.provider, candidate.provider) || !sameValue(evidenceRef.resolver, candidate.resolver)
476
- || evidenceRef.classification !== ingestion.classification
477
- || evidenceRef.evidenceArtifactId !== evidenceArtifact.artifactId
478
- || evidenceRef.evidenceArtifactRawHash !== evidenceArtifact.rawHash
479
- || evidenceRef.evidenceArtifactCanonicalHash !== evidenceArtifact.canonicalHash
480
- || evidenceArtifact.artifactId === artifact.artifactId
481
- || evidenceArtifact.artifactType !== 'evidence-snapshot'
482
- || evidenceArtifact.assignmentId !== artifact.assignmentId || evidenceArtifact.cycleId !== artifact.cycleId
483
- || evidenceArtifact.scopeId !== artifact.scopeId || evidenceArtifact.domainId !== artifact.domainId
484
- || evidenceArtifact.domainVersion !== artifact.domainVersion
485
- || evidenceArtifact.schemaId !== 'operating-evidence-snapshot' || evidenceArtifact.artifactSchemaVersion !== '1.0.0'
486
- || evidenceArtifact.mediaType !== 'application/octet-stream' || evidenceArtifact.encoding !== 'binary'
487
- || evidenceArtifact.rawHash !== artifact.rawHash || evidenceArtifact.canonicalHash !== artifact.canonicalHash
488
- || evidenceArtifact.sizeBytes !== artifact.sizeBytes || evidenceArtifact.sensitivity !== artifact.sensitivity
489
- || evidenceArtifact.retentionClass !== artifact.retentionClass
490
- || !sameValue(evidenceArtifact.inputArtifactIds, [artifact.artifactId])
491
- || evidenceArtifact.createdAt !== evidenceRef.resolvedAt
492
- || !sameValue(evidenceArtifact.producer, { actorId: 'openplanr', roleId: 'evidence-resolver', runtime: 'openplanr' })) {
493
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Accepted EvidenceRef does not bind the ingestion Artifact.');
494
- }
495
- if (evidenceResolution.outcome !== 'resolved' || evidenceResolution.error !== null
496
- || evidenceResolution.candidateId !== candidate.candidateId
497
- || evidenceResolution.sourceArtifactId !== artifact.artifactId
498
- || evidenceResolution.evidenceKind !== 'operate-artifact'
499
- || !sameValue(evidenceResolution.sourceContract, ingestion.sourceContract)
500
- || !sameValue(evidenceResolution.provider, candidate.provider)
501
- || !sameValue(evidenceResolution.resolver, candidate.resolver)
502
- || evidenceResolution.evidenceRefId !== evidenceRef.evidenceRefId
503
- || evidenceResolution.evidenceArtifactId !== evidenceArtifact.artifactId
504
- || evidenceResolution.resolvedAt !== evidenceRef.resolvedAt
505
- || evidenceArtifact.createdAt !== evidenceResolution.resolvedAt
506
- || evidenceResolution.scopeId !== artifact.scopeId || evidenceResolution.domainId !== artifact.domainId
507
- || evidenceResolution.domainVersion !== artifact.domainVersion) {
508
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Evidence resolution changed the runtime-built snapshot or EvidenceRef custody.');
509
- }
510
- if (resultCheckpoint === undefined) fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'Accepted ingestion requires the exact post-acceptance connector checkpoint.');
839
+ const candidate = ingestion.evidenceCandidates.find(
840
+ (entry) => entry.candidateId === evidenceRef.candidateId,
841
+ );
842
+ const expectedLocator =
843
+ candidate === undefined
844
+ ? null
845
+ : {
846
+ artifactId: candidate.locator.artifactId,
847
+ expectedArtifactType: candidate.locator.expectedArtifactType,
848
+ expectedSchemaId: candidate.locator.expectedSchemaId,
849
+ expectedSchemaVersion: candidate.locator.expectedSchemaVersion,
850
+ expectedRawHash: artifact.rawHash,
851
+ expectedCanonicalHash: artifact.canonicalHash,
852
+ };
853
+ if (
854
+ evidenceRef.evidenceRefId !== ingestion.submission.evidenceRefId ||
855
+ evidenceRef.sourceArtifactId !== artifact.artifactId ||
856
+ candidate === undefined ||
857
+ evidenceRef.evidenceKind !== 'operate-artifact' ||
858
+ !sameValue(evidenceRef.sourceContract, ingestion.sourceContract) ||
859
+ (candidate.locator.expectedRawHash !== undefined &&
860
+ candidate.locator.expectedRawHash !== artifact.rawHash) ||
861
+ (candidate.locator.expectedCanonicalHash !== undefined &&
862
+ candidate.locator.expectedCanonicalHash !== artifact.canonicalHash) ||
863
+ !sameValue(evidenceRef.locator, expectedLocator) ||
864
+ !sameValue(evidenceRef.provider, candidate.provider) ||
865
+ !sameValue(evidenceRef.resolver, candidate.resolver) ||
866
+ evidenceRef.classification !== ingestion.classification ||
867
+ evidenceRef.evidenceArtifactId !== evidenceArtifact.artifactId ||
868
+ evidenceRef.evidenceArtifactRawHash !== evidenceArtifact.rawHash ||
869
+ evidenceRef.evidenceArtifactCanonicalHash !== evidenceArtifact.canonicalHash ||
870
+ evidenceArtifact.artifactId === artifact.artifactId ||
871
+ evidenceArtifact.artifactType !== 'evidence-snapshot' ||
872
+ evidenceArtifact.assignmentId !== artifact.assignmentId ||
873
+ evidenceArtifact.cycleId !== artifact.cycleId ||
874
+ evidenceArtifact.scopeId !== artifact.scopeId ||
875
+ evidenceArtifact.domainId !== artifact.domainId ||
876
+ evidenceArtifact.domainVersion !== artifact.domainVersion ||
877
+ evidenceArtifact.schemaId !== 'operating-evidence-snapshot' ||
878
+ evidenceArtifact.artifactSchemaVersion !== '1.0.0' ||
879
+ evidenceArtifact.mediaType !== 'application/octet-stream' ||
880
+ evidenceArtifact.encoding !== 'binary' ||
881
+ evidenceArtifact.rawHash !== artifact.rawHash ||
882
+ evidenceArtifact.canonicalHash !== artifact.canonicalHash ||
883
+ evidenceArtifact.sizeBytes !== artifact.sizeBytes ||
884
+ evidenceArtifact.sensitivity !== artifact.sensitivity ||
885
+ evidenceArtifact.retentionClass !== artifact.retentionClass ||
886
+ !sameValue(evidenceArtifact.inputArtifactIds, [artifact.artifactId]) ||
887
+ evidenceArtifact.createdAt !== evidenceRef.resolvedAt ||
888
+ !sameValue(evidenceArtifact.producer, {
889
+ actorId: 'openplanr',
890
+ roleId: 'evidence-resolver',
891
+ runtime: 'openplanr',
892
+ })
893
+ ) {
894
+ fail(
895
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
896
+ 'Accepted EvidenceRef does not bind the ingestion Artifact.',
897
+ );
898
+ }
899
+ if (
900
+ evidenceResolution.outcome !== 'resolved' ||
901
+ evidenceResolution.error !== null ||
902
+ evidenceResolution.candidateId !== candidate.candidateId ||
903
+ evidenceResolution.sourceArtifactId !== artifact.artifactId ||
904
+ evidenceResolution.evidenceKind !== 'operate-artifact' ||
905
+ !sameValue(evidenceResolution.sourceContract, ingestion.sourceContract) ||
906
+ !sameValue(evidenceResolution.provider, candidate.provider) ||
907
+ !sameValue(evidenceResolution.resolver, candidate.resolver) ||
908
+ evidenceResolution.evidenceRefId !== evidenceRef.evidenceRefId ||
909
+ evidenceResolution.evidenceArtifactId !== evidenceArtifact.artifactId ||
910
+ evidenceResolution.resolvedAt !== evidenceRef.resolvedAt ||
911
+ evidenceArtifact.createdAt !== evidenceResolution.resolvedAt ||
912
+ evidenceResolution.scopeId !== artifact.scopeId ||
913
+ evidenceResolution.domainId !== artifact.domainId ||
914
+ evidenceResolution.domainVersion !== artifact.domainVersion
915
+ ) {
916
+ fail(
917
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
918
+ 'Evidence resolution changed the runtime-built snapshot or EvidenceRef custody.',
919
+ );
920
+ }
921
+ if (resultCheckpoint === undefined)
922
+ fail(
923
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
924
+ 'Accepted ingestion requires the exact post-acceptance connector checkpoint.',
925
+ );
511
926
  const requestCheckpoint = assertOperatingConnectorCheckpointV2(options.connectorCheckpoint);
512
- const chain = [requestCheckpoint, ...checkpointHistory.map(assertOperatingConnectorCheckpointV2), assertOperatingConnectorCheckpointV2(resultCheckpoint)];
927
+ const chain = [
928
+ requestCheckpoint,
929
+ ...checkpointHistory.map(assertOperatingConnectorCheckpointV2),
930
+ assertOperatingConnectorCheckpointV2(resultCheckpoint),
931
+ ];
513
932
  for (let index = 1; index < chain.length; index += 1) {
514
- if (chain[index].predecessorDigest !== chain[index - 1].checkpointHash
515
- || chain[index].generation !== chain[index - 1].generation + 1) fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Connector checkpoint lineage is not contiguous.');
933
+ if (
934
+ chain[index].predecessorDigest !== chain[index - 1].checkpointHash ||
935
+ chain[index].generation !== chain[index - 1].generation + 1
936
+ )
937
+ fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Connector checkpoint lineage is not contiguous.');
516
938
  }
517
939
  const terminalCheckpoint = chain.at(-1);
518
- if (!['materialized', 'committed'].includes(terminalCheckpoint.state)
519
- || terminalCheckpoint.artifactId !== artifact.artifactId || terminalCheckpoint.artifactHash !== artifact.canonicalHash
520
- || terminalCheckpoint.requestHash !== ingestion.requestHash
521
- || terminalCheckpoint.consentRecordHash !== ingestion.consentRecordHash
522
- || terminalCheckpoint.runtimeCapabilityHash !== ingestion.runtimeCapabilityHash
523
- || !sameValue(terminalCheckpoint.health, ingestion.health)) {
524
- fail('LIVE_EVIDENCE_BRIDGE_INVALID', 'Post-acceptance checkpoint changed Artifact or request custody.');
940
+ if (
941
+ !['materialized', 'committed'].includes(terminalCheckpoint.state) ||
942
+ terminalCheckpoint.artifactId !== artifact.artifactId ||
943
+ terminalCheckpoint.artifactHash !== artifact.canonicalHash ||
944
+ terminalCheckpoint.requestHash !== ingestion.requestHash ||
945
+ terminalCheckpoint.consentRecordHash !== ingestion.consentRecordHash ||
946
+ terminalCheckpoint.runtimeCapabilityHash !== ingestion.runtimeCapabilityHash ||
947
+ !sameValue(terminalCheckpoint.health, ingestion.health)
948
+ ) {
949
+ fail(
950
+ 'LIVE_EVIDENCE_BRIDGE_INVALID',
951
+ 'Post-acceptance checkpoint changed Artifact or request custody.',
952
+ );
525
953
  }
526
954
  return ingestion;
527
955
  }
@@ -530,29 +958,70 @@ export function assertOperatingConnectorCheckpointV2(checkpoint) {
530
958
  protocol('operating-connector-checkpoint', checkpoint);
531
959
  safePortable(checkpoint);
532
960
  selfHash(checkpoint, 'checkpointHash');
533
- if (checkpoint.generation === 0 && (checkpoint.state !== 'prepared' || checkpoint.predecessorDigest !== null || checkpoint.lastEventId !== null || checkpoint.lastEventHash !== null)) {
534
- fail('LIVE_EVIDENCE_CHECKPOINT_INVALID', 'Generation-zero connector checkpoint must be an unadvanced prepared record.');
535
- }
536
- if (checkpoint.state === 'prepared' && (checkpoint.consentRecordId !== null || checkpoint.consentRecordHash !== null
537
- || checkpoint.consentExpiresAt !== null || checkpoint.runtimeCapabilityHash !== null
538
- || checkpoint.artifactId !== null || checkpoint.artifactHash !== null || checkpoint.absenceDigest !== null)) {
539
- fail('LIVE_EVIDENCE_CHECKPOINT_INVALID', 'Prepared checkpoint cannot claim consent, capability, Artifact, or absence custody.');
961
+ if (
962
+ checkpoint.generation === 0 &&
963
+ (checkpoint.state !== 'prepared' ||
964
+ checkpoint.predecessorDigest !== null ||
965
+ checkpoint.lastEventId !== null ||
966
+ checkpoint.lastEventHash !== null)
967
+ ) {
968
+ fail(
969
+ 'LIVE_EVIDENCE_CHECKPOINT_INVALID',
970
+ 'Generation-zero connector checkpoint must be an unadvanced prepared record.',
971
+ );
972
+ }
973
+ if (
974
+ checkpoint.state === 'prepared' &&
975
+ (checkpoint.consentRecordId !== null ||
976
+ checkpoint.consentRecordHash !== null ||
977
+ checkpoint.consentExpiresAt !== null ||
978
+ checkpoint.runtimeCapabilityHash !== null ||
979
+ checkpoint.artifactId !== null ||
980
+ checkpoint.artifactHash !== null ||
981
+ checkpoint.absenceDigest !== null)
982
+ ) {
983
+ fail(
984
+ 'LIVE_EVIDENCE_CHECKPOINT_INVALID',
985
+ 'Prepared checkpoint cannot claim consent, capability, Artifact, or absence custody.',
986
+ );
540
987
  }
541
988
  if (['requesting', 'materialized', 'committed'].includes(checkpoint.state)) {
542
- if (checkpoint.consentRecordId === null || checkpoint.consentRecordHash === null
543
- || checkpoint.consentExpiresAt === null || checkpoint.runtimeCapabilityHash === null) {
544
- fail('LIVE_EVIDENCE_CHECKPOINT_INVALID', 'Requested checkpoint requires exact consent and runtime capability custody.');
989
+ if (
990
+ checkpoint.consentRecordId === null ||
991
+ checkpoint.consentRecordHash === null ||
992
+ checkpoint.consentExpiresAt === null ||
993
+ checkpoint.runtimeCapabilityHash === null
994
+ ) {
995
+ fail(
996
+ 'LIVE_EVIDENCE_CHECKPOINT_INVALID',
997
+ 'Requested checkpoint requires exact consent and runtime capability custody.',
998
+ );
545
999
  }
546
1000
  currentAt(checkpoint.updatedAt, checkpoint.consentExpiresAt, 'Connector consent');
547
1001
  }
548
1002
  if (['materialized', 'committed'].includes(checkpoint.state)) {
549
- if (checkpoint.health.status !== 'available' || checkpoint.artifactId === null || checkpoint.artifactHash === null
550
- || checkpoint.absenceDigest !== null) fail('LIVE_EVIDENCE_FALSE_PASS', 'Materialized connector checkpoint requires available health and exact Artifact custody.');
1003
+ if (
1004
+ checkpoint.health.status !== 'available' ||
1005
+ checkpoint.artifactId === null ||
1006
+ checkpoint.artifactHash === null ||
1007
+ checkpoint.absenceDigest !== null
1008
+ )
1009
+ fail(
1010
+ 'LIVE_EVIDENCE_FALSE_PASS',
1011
+ 'Materialized connector checkpoint requires available health and exact Artifact custody.',
1012
+ );
551
1013
  currentAt(checkpoint.updatedAt, checkpoint.health.freshUntil, 'Provider health');
552
1014
  }
553
- if (['absent', 'uncertain'].includes(checkpoint.state)
554
- && (checkpoint.absenceDigest === null || checkpoint.artifactId !== null || checkpoint.artifactHash !== null)) {
555
- fail('LIVE_EVIDENCE_CHECKPOINT_INVALID', 'Absent or uncertain checkpoint requires one typed absence and no Artifact custody.');
1015
+ if (
1016
+ ['absent', 'uncertain'].includes(checkpoint.state) &&
1017
+ (checkpoint.absenceDigest === null ||
1018
+ checkpoint.artifactId !== null ||
1019
+ checkpoint.artifactHash !== null)
1020
+ ) {
1021
+ fail(
1022
+ 'LIVE_EVIDENCE_CHECKPOINT_INVALID',
1023
+ 'Absent or uncertain checkpoint requires one typed absence and no Artifact custody.',
1024
+ );
556
1025
  }
557
1026
  return freeze(clone(checkpoint));
558
1027
  }
@@ -561,44 +1030,95 @@ export function reduceOperatingConnectorCheckpointV2(currentValue, eventValue) {
561
1030
  const current = assertOperatingConnectorCheckpointV2(currentValue);
562
1031
  const event = clone(eventValue);
563
1032
  assertExactKeys(event, CONNECTOR_EVENT_FIELDS, 'Connector transition Event');
564
- if (!CONNECTOR_PATCH_FIELDS[event.type]) fail('LIVE_EVIDENCE_TRANSITION_INVALID', 'Unknown connector transition type.', { type: event.type });
1033
+ if (!CONNECTOR_PATCH_FIELDS[event.type])
1034
+ fail('LIVE_EVIDENCE_TRANSITION_INVALID', 'Unknown connector transition type.', {
1035
+ type: event.type,
1036
+ });
565
1037
  assertExactKeys(event.patch, CONNECTOR_PATCH_FIELDS[event.type], `${event.type} connector patch`);
566
1038
  const claimed = event.eventHash;
567
1039
  delete event.eventHash;
568
1040
  const eventHash = sha256Jcs(event);
569
- if (claimed !== eventHash) fail('LIVE_EVIDENCE_DIGEST_MISMATCH', 'Connector event hash does not bind the exact event.');
1041
+ if (claimed !== eventHash)
1042
+ fail('LIVE_EVIDENCE_DIGEST_MISMATCH', 'Connector event hash does not bind the exact event.');
570
1043
  if (current.lastEventId === event.eventId) {
571
- if (current.lastEventHash !== eventHash) fail('LIVE_EVIDENCE_REPLAY_CONFLICT', 'Divergent connector event reused one identity.');
1044
+ if (current.lastEventHash !== eventHash)
1045
+ fail('LIVE_EVIDENCE_REPLAY_CONFLICT', 'Divergent connector event reused one identity.');
572
1046
  return current;
573
1047
  }
574
- if (event.expectedGeneration !== current.generation || event.expectedCheckpointHash !== current.checkpointHash) {
575
- fail('LIVE_EVIDENCE_CONCURRENT_MODIFICATION', 'Connector checkpoint generation or digest changed.');
1048
+ if (
1049
+ event.expectedGeneration !== current.generation ||
1050
+ event.expectedCheckpointHash !== current.checkpointHash
1051
+ ) {
1052
+ fail(
1053
+ 'LIVE_EVIDENCE_CONCURRENT_MODIFICATION',
1054
+ 'Connector checkpoint generation or digest changed.',
1055
+ );
576
1056
  }
577
1057
  const target = CHECKPOINT_TRANSITIONS[current.state]?.[event.type];
578
- if (target === undefined) fail('LIVE_EVIDENCE_TRANSITION_INVALID', 'Illegal connector checkpoint transition.', { from: current.state, type: event.type });
1058
+ if (target === undefined)
1059
+ fail('LIVE_EVIDENCE_TRANSITION_INVALID', 'Illegal connector checkpoint transition.', {
1060
+ from: current.state,
1061
+ type: event.type,
1062
+ });
579
1063
  const patch = event.patch ?? {};
580
1064
  for (const field of IMMUTABLE_CHECKPOINT_FIELDS) {
581
- if (Object.hasOwn(patch, field) && !sameValue(patch[field], current[field])) fail('LIVE_EVIDENCE_BINDING_MISMATCH', `Connector ${field} cannot change.`);
1065
+ if (Object.hasOwn(patch, field) && !sameValue(patch[field], current[field]))
1066
+ fail('LIVE_EVIDENCE_BINDING_MISMATCH', `Connector ${field} cannot change.`);
582
1067
  }
583
1068
  if (current.state !== 'prepared') {
584
- for (const field of ['consentRecordId', 'consentRecordHash', 'consentExpiresAt', 'runtimeCapabilityHash']) {
1069
+ for (const field of [
1070
+ 'consentRecordId',
1071
+ 'consentRecordHash',
1072
+ 'consentExpiresAt',
1073
+ 'runtimeCapabilityHash',
1074
+ ]) {
585
1075
  if (Object.hasOwn(patch, field) && !sameValue(patch[field], current[field])) {
586
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', `Connector ${field} is frozen after request issuance.`);
1076
+ fail(
1077
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1078
+ `Connector ${field} is frozen after request issuance.`,
1079
+ );
587
1080
  }
588
1081
  }
589
1082
  }
590
- if (event.type === 'request' && (patch.consentRecordId === null || patch.consentRecordHash === null
591
- || patch.consentExpiresAt === null || patch.runtimeCapabilityHash === null)) {
592
- fail('LIVE_EVIDENCE_AUTHORITY_INVALID', 'Requesting a provider call requires current consent and one opaque runtime capability.');
593
- }
594
- if (event.type === 'materialize' && (patch.artifactId === null || patch.artifactHash === null
595
- || patch.health?.status !== 'available')) {
596
- fail('LIVE_EVIDENCE_FALSE_PASS', 'Materialize transition requires exact Artifact and current available-health proof.');
1083
+ if (
1084
+ event.type === 'request' &&
1085
+ (patch.consentRecordId === null ||
1086
+ patch.consentRecordHash === null ||
1087
+ patch.consentExpiresAt === null ||
1088
+ patch.runtimeCapabilityHash === null)
1089
+ ) {
1090
+ fail(
1091
+ 'LIVE_EVIDENCE_AUTHORITY_INVALID',
1092
+ 'Requesting a provider call requires current consent and one opaque runtime capability.',
1093
+ );
1094
+ }
1095
+ if (
1096
+ event.type === 'materialize' &&
1097
+ (patch.artifactId === null ||
1098
+ patch.artifactHash === null ||
1099
+ patch.health?.status !== 'available')
1100
+ ) {
1101
+ fail(
1102
+ 'LIVE_EVIDENCE_FALSE_PASS',
1103
+ 'Materialize transition requires exact Artifact and current available-health proof.',
1104
+ );
597
1105
  }
598
1106
  if (['absent', 'uncertain'].includes(event.type) && patch.absenceDigest === null) {
599
- fail('LIVE_EVIDENCE_CHECKPOINT_INVALID', 'Absent or uncertain transition requires a typed absence digest.');
600
- }
601
- const next = { ...clone(current), ...patch, state: target, generation: current.generation + 1, lastEventId: event.eventId, lastEventHash: eventHash, predecessorDigest: current.checkpointHash, updatedAt: event.at };
1107
+ fail(
1108
+ 'LIVE_EVIDENCE_CHECKPOINT_INVALID',
1109
+ 'Absent or uncertain transition requires a typed absence digest.',
1110
+ );
1111
+ }
1112
+ const next = {
1113
+ ...clone(current),
1114
+ ...patch,
1115
+ state: target,
1116
+ generation: current.generation + 1,
1117
+ lastEventId: event.eventId,
1118
+ lastEventHash: eventHash,
1119
+ predecessorDigest: current.checkpointHash,
1120
+ updatedAt: event.at,
1121
+ };
602
1122
  delete next.checkpointHash;
603
1123
  next.checkpointHash = sha256Jcs(next);
604
1124
  return assertOperatingConnectorCheckpointV2(next);
@@ -609,39 +1129,94 @@ export function assertOperatingMeasurementPlanV2(plan, { verificationPlan } = {}
609
1129
  safePortable(plan);
610
1130
  selfHash(plan, 'planHash');
611
1131
  const terminal = [...plan.terminalResults].sort();
612
- if (!sameValue(terminal, ['failed', 'insufficient-evidence', 'passed'])) fail('LIVE_EVIDENCE_PLAN_INVALID', 'Measurement plan must declare every terminal result.');
613
- if (plan.target.unit !== plan.metric.unit || plan.baseline.unit !== plan.metric.unit) fail('LIVE_EVIDENCE_UNIT_MISMATCH', 'Baseline and target units must match the metric.');
614
- if (![plan.baseline.value, ...(Array.isArray(plan.target.value) ? plan.target.value : [plan.target.value])].every(Number.isFinite)
615
- || Date.parse(plan.window.from) > Date.parse(plan.window.to) || Date.parse(plan.dueAt) < Date.parse(plan.window.to)) {
616
- fail('LIVE_EVIDENCE_PLAN_INVALID', 'Measurement values must be finite and the inclusive window/due chronology must be ordered.');
1132
+ if (!sameValue(terminal, ['failed', 'insufficient-evidence', 'passed']))
1133
+ fail('LIVE_EVIDENCE_PLAN_INVALID', 'Measurement plan must declare every terminal result.');
1134
+ if (plan.target.unit !== plan.metric.unit || plan.baseline.unit !== plan.metric.unit)
1135
+ fail('LIVE_EVIDENCE_UNIT_MISMATCH', 'Baseline and target units must match the metric.');
1136
+ if (
1137
+ ![
1138
+ plan.baseline.value,
1139
+ ...(Array.isArray(plan.target.value) ? plan.target.value : [plan.target.value]),
1140
+ ].every(Number.isFinite) ||
1141
+ Date.parse(plan.window.from) > Date.parse(plan.window.to) ||
1142
+ Date.parse(plan.dueAt) < Date.parse(plan.window.to)
1143
+ ) {
1144
+ fail(
1145
+ 'LIVE_EVIDENCE_PLAN_INVALID',
1146
+ 'Measurement values must be finite and the inclusive window/due chronology must be ordered.',
1147
+ );
617
1148
  }
618
1149
  const algebra = {
619
- increase: ['gt', 'gte'], decrease: ['lt', 'lte'], maintain: ['eq'], range: ['between'],
1150
+ increase: ['gt', 'gte'],
1151
+ decrease: ['lt', 'lte'],
1152
+ maintain: ['eq'],
1153
+ range: ['between'],
620
1154
  };
621
1155
  if (!algebra[plan.target.direction]?.includes(plan.target.operator)) {
622
1156
  fail('LIVE_EVIDENCE_PLAN_INVALID', 'Measurement direction and operator are incompatible.');
623
1157
  }
624
1158
  if (plan.target.operator === 'between') {
625
- if (!Array.isArray(plan.target.value) || plan.target.value.length !== 2 || plan.target.value[0] > plan.target.value[1]) {
1159
+ if (
1160
+ !Array.isArray(plan.target.value) ||
1161
+ plan.target.value.length !== 2 ||
1162
+ plan.target.value[0] > plan.target.value[1]
1163
+ ) {
626
1164
  fail('LIVE_EVIDENCE_PLAN_INVALID', 'Between target must be one ordered finite range.');
627
1165
  }
628
1166
  } else if (Array.isArray(plan.target.value)) {
629
1167
  fail('LIVE_EVIDENCE_PLAN_INVALID', 'Scalar measurement operators cannot use a range target.');
630
1168
  }
631
- if ((plan.target.direction === 'increase' && plan.target.value <= plan.baseline.value)
632
- || (plan.target.direction === 'decrease' && plan.target.value >= plan.baseline.value)
633
- || (plan.target.direction === 'maintain' && plan.target.value !== plan.baseline.value)) {
634
- fail('LIVE_EVIDENCE_PLAN_INVALID', 'Measurement target does not match the declared baseline direction.');
1169
+ if (
1170
+ (plan.target.direction === 'increase' && plan.target.value <= plan.baseline.value) ||
1171
+ (plan.target.direction === 'decrease' && plan.target.value >= plan.baseline.value) ||
1172
+ (plan.target.direction === 'maintain' && plan.target.value !== plan.baseline.value)
1173
+ ) {
1174
+ fail(
1175
+ 'LIVE_EVIDENCE_PLAN_INVALID',
1176
+ 'Measurement target does not match the declared baseline direction.',
1177
+ );
635
1178
  }
636
1179
  if (verificationPlan !== undefined) {
637
1180
  protocol('operating-action-verification-plan', verificationPlan);
638
1181
  exactDigest(verificationPlan, plan.verificationPlan.recordDigest, 'Action verification plan');
639
- same([verificationPlan.verificationPlanId, verificationPlan.actionId, verificationPlan.metricId, verificationPlan.baseline, verificationPlan.target], [plan.verificationPlan.verificationPlanId, plan.action.actionId, plan.metric.metricId, plan.baseline.value, plan.verificationPlan.canonicalTarget], 'Measurement-plan specialization');
640
- same(sha256Jcs(verificationPlan.window), plan.verificationPlan.windowDigest, 'Verification window digest');
641
- same(sha256Jcs(verificationPlan.method), plan.verificationPlan.methodDigest, 'Verification method digest');
642
- same(sha256Jcs(verificationPlan.evaluationRules), plan.verificationPlan.evaluationRulesDigest, 'Verification rule digest');
1182
+ same(
1183
+ [
1184
+ verificationPlan.verificationPlanId,
1185
+ verificationPlan.actionId,
1186
+ verificationPlan.metricId,
1187
+ verificationPlan.baseline,
1188
+ verificationPlan.target,
1189
+ ],
1190
+ [
1191
+ plan.verificationPlan.verificationPlanId,
1192
+ plan.action.actionId,
1193
+ plan.metric.metricId,
1194
+ plan.baseline.value,
1195
+ plan.verificationPlan.canonicalTarget,
1196
+ ],
1197
+ 'Measurement-plan specialization',
1198
+ );
1199
+ same(
1200
+ sha256Jcs(verificationPlan.window),
1201
+ plan.verificationPlan.windowDigest,
1202
+ 'Verification window digest',
1203
+ );
1204
+ same(
1205
+ sha256Jcs(verificationPlan.method),
1206
+ plan.verificationPlan.methodDigest,
1207
+ 'Verification method digest',
1208
+ );
1209
+ same(
1210
+ sha256Jcs(verificationPlan.evaluationRules),
1211
+ plan.verificationPlan.evaluationRulesDigest,
1212
+ 'Verification rule digest',
1213
+ );
643
1214
  const targetValues = Array.isArray(plan.target.value) ? plan.target.value : [plan.target.value];
644
- if (!targetValues.includes(verificationPlan.target)) fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Measurement target is not derivable from the canonical verification target.');
1215
+ if (!targetValues.includes(verificationPlan.target))
1216
+ fail(
1217
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1218
+ 'Measurement target is not derivable from the canonical verification target.',
1219
+ );
645
1220
  }
646
1221
  return freeze(clone(plan));
647
1222
  }
@@ -650,24 +1225,48 @@ export function assertOperatingMeasurementScheduleV2(schedule) {
650
1225
  protocol('operating-measurement-schedule', schedule);
651
1226
  safePortable(schedule);
652
1227
  selfHash(schedule, 'scheduleHash');
653
- if (schedule.generation === 0 && (schedule.state !== 'disabled' || schedule.runCount !== 0
654
- || schedule.nextEventIdentity !== null || schedule.nextDueAt !== null
655
- || schedule.lastReceiptId !== null || schedule.lastTransitionHash !== null)) {
1228
+ if (
1229
+ schedule.generation === 0 &&
1230
+ (schedule.state !== 'disabled' ||
1231
+ schedule.runCount !== 0 ||
1232
+ schedule.nextEventIdentity !== null ||
1233
+ schedule.nextDueAt !== null ||
1234
+ schedule.lastReceiptId !== null ||
1235
+ schedule.lastTransitionHash !== null)
1236
+ ) {
656
1237
  fail('LIVE_EVIDENCE_SCHEDULE_INVALID', 'New schedules must be disabled and unadvanced.');
657
1238
  }
658
- if (schedule.recurrence.kind === 'once' && schedule.recurrence.intervalSeconds !== null) fail('LIVE_EVIDENCE_SCHEDULE_INVALID', 'One-time schedules cannot carry an interval.');
659
- if (schedule.recurrence.kind === 'interval' && schedule.recurrence.intervalSeconds === null) fail('LIVE_EVIDENCE_SCHEDULE_INVALID', 'Interval schedules require a bounded interval.');
660
- if (Date.parse(schedule.startsAt) > Date.parse(schedule.endsAt ?? schedule.startsAt)
661
- || schedule.runCount > schedule.maxRuns) fail('LIVE_EVIDENCE_SCHEDULE_INVALID', 'Schedule time bounds or run count are invalid.');
662
- if (schedule.state === 'enabled' && (schedule.consentRecordHashes.length === 0
663
- || schedule.nextEventIdentity === null || schedule.nextDueAt === null
664
- || schedule.runCount >= schedule.maxRuns || Date.parse(schedule.nextDueAt) < Date.parse(schedule.startsAt)
665
- || (schedule.endsAt !== null && Date.parse(schedule.nextDueAt) > Date.parse(schedule.endsAt)))) {
666
- fail('LIVE_EVIDENCE_SCHEDULE_INVALID', 'Enabled schedule requires current consent, one due identity, and remaining bounded runs.');
667
- }
668
- if (['disabled', 'revoked', 'expired', 'completed'].includes(schedule.state)
669
- && (schedule.nextEventIdentity !== null || schedule.nextDueAt !== null)) {
670
- fail('LIVE_EVIDENCE_SCHEDULE_INVALID', 'Inactive schedule cannot retain an executable due identity.');
1239
+ if (schedule.recurrence.kind === 'once' && schedule.recurrence.intervalSeconds !== null)
1240
+ fail('LIVE_EVIDENCE_SCHEDULE_INVALID', 'One-time schedules cannot carry an interval.');
1241
+ if (schedule.recurrence.kind === 'interval' && schedule.recurrence.intervalSeconds === null)
1242
+ fail('LIVE_EVIDENCE_SCHEDULE_INVALID', 'Interval schedules require a bounded interval.');
1243
+ if (
1244
+ Date.parse(schedule.startsAt) > Date.parse(schedule.endsAt ?? schedule.startsAt) ||
1245
+ schedule.runCount > schedule.maxRuns
1246
+ )
1247
+ fail('LIVE_EVIDENCE_SCHEDULE_INVALID', 'Schedule time bounds or run count are invalid.');
1248
+ if (
1249
+ schedule.state === 'enabled' &&
1250
+ (schedule.consentRecordHashes.length === 0 ||
1251
+ schedule.nextEventIdentity === null ||
1252
+ schedule.nextDueAt === null ||
1253
+ schedule.runCount >= schedule.maxRuns ||
1254
+ Date.parse(schedule.nextDueAt) < Date.parse(schedule.startsAt) ||
1255
+ (schedule.endsAt !== null && Date.parse(schedule.nextDueAt) > Date.parse(schedule.endsAt)))
1256
+ ) {
1257
+ fail(
1258
+ 'LIVE_EVIDENCE_SCHEDULE_INVALID',
1259
+ 'Enabled schedule requires current consent, one due identity, and remaining bounded runs.',
1260
+ );
1261
+ }
1262
+ if (
1263
+ ['disabled', 'revoked', 'expired', 'completed'].includes(schedule.state) &&
1264
+ (schedule.nextEventIdentity !== null || schedule.nextDueAt !== null)
1265
+ ) {
1266
+ fail(
1267
+ 'LIVE_EVIDENCE_SCHEDULE_INVALID',
1268
+ 'Inactive schedule cannot retain an executable due identity.',
1269
+ );
671
1270
  }
672
1271
  return freeze(clone(schedule));
673
1272
  }
@@ -676,32 +1275,52 @@ function assertOperatingMeasurementScheduleReceiptStructureV2(receipt) {
676
1275
  protocol('operating-measurement-schedule-receipt', receipt);
677
1276
  safePortable(receipt);
678
1277
  selfHash(receipt, 'receiptHash');
679
- if (receipt.authority !== 'none' || receipt.scheduleHash !== receipt.resultingScheduleHash) fail('LIVE_EVIDENCE_SCHEDULE_INVALID', 'Schedule receipt is non-authoritative and must bind its exact result schedule.');
1278
+ if (receipt.authority !== 'none' || receipt.scheduleHash !== receipt.resultingScheduleHash)
1279
+ fail(
1280
+ 'LIVE_EVIDENCE_SCHEDULE_INVALID',
1281
+ 'Schedule receipt is non-authoritative and must bind its exact result schedule.',
1282
+ );
680
1283
  return freeze(clone(receipt));
681
1284
  }
682
1285
 
683
1286
  function assertScheduleReceiptPredecessor(receipt, previousSchedule) {
684
1287
  const previous = assertOperatingMeasurementScheduleV2(previousSchedule);
685
- if (previous.scheduleHash !== receipt.previousScheduleHash || previous.scheduleId !== receipt.scheduleId
686
- || previous.state !== receipt.fromState || previous.runCount !== receipt.previousRunCount
687
- || previous.nextEventIdentity !== receipt.previousNextEventIdentity || previous.nextDueAt !== receipt.previousNextDueAt) {
1288
+ if (
1289
+ previous.scheduleHash !== receipt.previousScheduleHash ||
1290
+ previous.scheduleId !== receipt.scheduleId ||
1291
+ previous.state !== receipt.fromState ||
1292
+ previous.runCount !== receipt.previousRunCount ||
1293
+ previous.nextEventIdentity !== receipt.previousNextEventIdentity ||
1294
+ previous.nextDueAt !== receipt.previousNextDueAt
1295
+ ) {
688
1296
  fail('LIVE_EVIDENCE_BASE_RECORD_MISMATCH', 'Schedule receipt changed its exact predecessor.');
689
1297
  }
690
1298
  }
691
1299
 
692
1300
  function assertScheduleReceiptResult(receipt, resultingSchedule) {
693
1301
  const result = assertOperatingMeasurementScheduleV2(resultingSchedule);
694
- if (result.scheduleHash !== receipt.resultingScheduleHash || result.scheduleId !== receipt.scheduleId
695
- || result.state !== receipt.toState || result.runCount !== receipt.resultingRunCount
696
- || result.nextEventIdentity !== receipt.resultingNextEventIdentity || result.nextDueAt !== receipt.resultingNextDueAt) {
1302
+ if (
1303
+ result.scheduleHash !== receipt.resultingScheduleHash ||
1304
+ result.scheduleId !== receipt.scheduleId ||
1305
+ result.state !== receipt.toState ||
1306
+ result.runCount !== receipt.resultingRunCount ||
1307
+ result.nextEventIdentity !== receipt.resultingNextEventIdentity ||
1308
+ result.nextDueAt !== receipt.resultingNextDueAt
1309
+ ) {
697
1310
  fail('LIVE_EVIDENCE_BASE_RECORD_MISMATCH', 'Schedule receipt changed its exact result.');
698
1311
  }
699
1312
  }
700
1313
 
701
- export function assertOperatingMeasurementScheduleReceiptV2(receipt, { previousSchedule, resultingSchedule } = {}) {
1314
+ export function assertOperatingMeasurementScheduleReceiptV2(
1315
+ receipt,
1316
+ { previousSchedule, resultingSchedule } = {},
1317
+ ) {
702
1318
  const normalized = assertOperatingMeasurementScheduleReceiptStructureV2(receipt);
703
1319
  if (previousSchedule === undefined || resultingSchedule === undefined) {
704
- fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'A certifying schedule receipt requires its exact predecessor and resulting schedules.');
1320
+ fail(
1321
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
1322
+ 'A certifying schedule receipt requires its exact predecessor and resulting schedules.',
1323
+ );
705
1324
  }
706
1325
  assertScheduleReceiptPredecessor(normalized, previousSchedule);
707
1326
  assertScheduleReceiptResult(normalized, resultingSchedule);
@@ -710,155 +1329,372 @@ export function assertOperatingMeasurementScheduleReceiptV2(receipt, { previousS
710
1329
 
711
1330
  function scheduleReceipt(schedule, transition, next) {
712
1331
  const receipt = {
713
- kind: 'operating-measurement-schedule-receipt', schemaVersion: '1.0.0', protocolVersion: '2.0.0', receiptId: transition.receiptId,
714
- authority: 'none', scheduleId: schedule.scheduleId, scheduleHash: next.scheduleHash,
715
- previousScheduleHash: transition.expectedScheduleHash, resultingScheduleHash: next.scheduleHash,
716
- measurementPlanId: schedule.measurementPlanId, planHash: schedule.planHash,
717
- consentRecordHashes: clone(schedule.consentRecordHashes), ceilingsHash: schedule.ceilingsHash, clockHash: transition.clockHash,
718
- recurrenceHash: sha256Jcs(schedule.recurrence), startsAt: schedule.startsAt, endsAt: schedule.endsAt, maxRuns: schedule.maxRuns,
719
- misfirePolicy: schedule.misfirePolicy, dstPolicy: schedule.dstPolicy, transition: transition.type,
720
- fromState: transition.expectedState, toState: next.state,
721
- previousRunCount: transition.expectedRunCount, resultingRunCount: next.runCount,
722
- previousNextEventIdentity: transition.expectedNextEventIdentity, resultingNextEventIdentity: next.nextEventIdentity,
723
- previousNextDueAt: transition.expectedNextDueAt, resultingNextDueAt: next.nextDueAt,
724
- ownerActorId: schedule.ownerActorId, eventId: transition.eventId, nextEventIdentity: next.nextEventIdentity,
1332
+ kind: 'operating-measurement-schedule-receipt',
1333
+ schemaVersion: '1.0.0',
1334
+ protocolVersion: '2.0.0',
1335
+ receiptId: transition.receiptId,
1336
+ authority: 'none',
1337
+ scheduleId: schedule.scheduleId,
1338
+ scheduleHash: next.scheduleHash,
1339
+ previousScheduleHash: transition.expectedScheduleHash,
1340
+ resultingScheduleHash: next.scheduleHash,
1341
+ measurementPlanId: schedule.measurementPlanId,
1342
+ planHash: schedule.planHash,
1343
+ consentRecordHashes: clone(schedule.consentRecordHashes),
1344
+ ceilingsHash: schedule.ceilingsHash,
1345
+ clockHash: transition.clockHash,
1346
+ recurrenceHash: sha256Jcs(schedule.recurrence),
1347
+ startsAt: schedule.startsAt,
1348
+ endsAt: schedule.endsAt,
1349
+ maxRuns: schedule.maxRuns,
1350
+ misfirePolicy: schedule.misfirePolicy,
1351
+ dstPolicy: schedule.dstPolicy,
1352
+ transition: transition.type,
1353
+ fromState: transition.expectedState,
1354
+ toState: next.state,
1355
+ previousRunCount: transition.expectedRunCount,
1356
+ resultingRunCount: next.runCount,
1357
+ previousNextEventIdentity: transition.expectedNextEventIdentity,
1358
+ resultingNextEventIdentity: next.nextEventIdentity,
1359
+ previousNextDueAt: transition.expectedNextDueAt,
1360
+ resultingNextDueAt: next.nextDueAt,
1361
+ ownerActorId: schedule.ownerActorId,
1362
+ eventId: transition.eventId,
1363
+ nextEventIdentity: next.nextEventIdentity,
725
1364
  at: transition.at,
726
1365
  };
727
1366
  receipt.receiptHash = sha256Jcs(receipt);
728
1367
  return receipt;
729
1368
  }
730
1369
 
731
- export function reduceOperatingMeasurementScheduleV2(scheduleValue, transitionValue, { priorReceipt } = {}) {
1370
+ export function reduceOperatingMeasurementScheduleV2(
1371
+ scheduleValue,
1372
+ transitionValue,
1373
+ { priorReceipt } = {},
1374
+ ) {
732
1375
  const schedule = assertOperatingMeasurementScheduleV2(scheduleValue);
733
1376
  const transition = clone(transitionValue);
734
1377
  assertExactKeys(transition, SCHEDULE_TRANSITION_FIELDS, 'Measurement schedule transition');
735
1378
  const transitionHash = sha256Jcs(transition);
736
1379
  if (schedule.lastReceiptId === transition.receiptId) {
737
- if (schedule.lastTransitionHash !== transitionHash) fail('LIVE_EVIDENCE_REPLAY_CONFLICT', 'Divergent schedule transition reused one receipt identity.');
738
- if (priorReceipt === undefined) fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'Exact schedule replay requires the stored immutable prior receipt.');
1380
+ if (schedule.lastTransitionHash !== transitionHash)
1381
+ fail(
1382
+ 'LIVE_EVIDENCE_REPLAY_CONFLICT',
1383
+ 'Divergent schedule transition reused one receipt identity.',
1384
+ );
1385
+ if (priorReceipt === undefined)
1386
+ fail(
1387
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
1388
+ 'Exact schedule replay requires the stored immutable prior receipt.',
1389
+ );
739
1390
  const receipt = assertOperatingMeasurementScheduleReceiptStructureV2(priorReceipt);
740
1391
  const expected = scheduleReceipt(schedule, transition, schedule);
741
- if (!sameValue(receipt, expected)) fail('LIVE_EVIDENCE_REPLAY_CONFLICT', 'Stored schedule receipt does not match the exact replay request and resulting schedule.');
1392
+ if (!sameValue(receipt, expected))
1393
+ fail(
1394
+ 'LIVE_EVIDENCE_REPLAY_CONFLICT',
1395
+ 'Stored schedule receipt does not match the exact replay request and resulting schedule.',
1396
+ );
742
1397
  assertScheduleReceiptResult(receipt, schedule);
743
1398
  return freeze({ replay: true, schedule, receipt });
744
1399
  }
745
- if (transition.expectedGeneration !== schedule.generation || transition.expectedScheduleHash !== schedule.scheduleHash) fail('LIVE_EVIDENCE_CONCURRENT_MODIFICATION', 'Schedule generation or digest changed.');
746
- if (transition.expectedState !== schedule.state || transition.expectedRunCount !== schedule.runCount
747
- || transition.expectedNextEventIdentity !== schedule.nextEventIdentity || transition.expectedNextDueAt !== schedule.nextDueAt) {
748
- fail('LIVE_EVIDENCE_CONCURRENT_MODIFICATION', 'Schedule state, run count, or due identity changed.');
1400
+ if (
1401
+ transition.expectedGeneration !== schedule.generation ||
1402
+ transition.expectedScheduleHash !== schedule.scheduleHash
1403
+ )
1404
+ fail('LIVE_EVIDENCE_CONCURRENT_MODIFICATION', 'Schedule generation or digest changed.');
1405
+ if (
1406
+ transition.expectedState !== schedule.state ||
1407
+ transition.expectedRunCount !== schedule.runCount ||
1408
+ transition.expectedNextEventIdentity !== schedule.nextEventIdentity ||
1409
+ transition.expectedNextDueAt !== schedule.nextDueAt
1410
+ ) {
1411
+ fail(
1412
+ 'LIVE_EVIDENCE_CONCURRENT_MODIFICATION',
1413
+ 'Schedule state, run count, or due identity changed.',
1414
+ );
749
1415
  }
750
1416
  let toState = SCHEDULE_TRANSITIONS[schedule.state]?.[transition.type];
751
- if (toState === undefined) fail('LIVE_EVIDENCE_TRANSITION_INVALID', 'Illegal measurement schedule transition.', { from: schedule.state, type: transition.type });
752
- if (transition.planHash !== schedule.planHash || !sameValue(transition.consentRecordHashes, schedule.consentRecordHashes)
753
- || transition.ceilingsHash !== schedule.ceilingsHash) fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Schedule transition changed plan or consent custody.');
1417
+ if (toState === undefined)
1418
+ fail('LIVE_EVIDENCE_TRANSITION_INVALID', 'Illegal measurement schedule transition.', {
1419
+ from: schedule.state,
1420
+ type: transition.type,
1421
+ });
1422
+ if (
1423
+ transition.planHash !== schedule.planHash ||
1424
+ !sameValue(transition.consentRecordHashes, schedule.consentRecordHashes) ||
1425
+ transition.ceilingsHash !== schedule.ceilingsHash
1426
+ )
1427
+ fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Schedule transition changed plan or consent custody.');
754
1428
  let runCount = schedule.runCount;
755
1429
  if (transition.type === 'enable') {
756
- if (schedule.consentRecordHashes.length === 0 || transition.nextEventIdentity === null || transition.nextDueAt === null
757
- || Date.parse(transition.nextDueAt) < Date.parse(schedule.startsAt)) {
758
- fail('LIVE_EVIDENCE_AUTHORITY_INVALID', 'Enabling measurement requires consent custody and a bounded runtime-issued due identity.');
1430
+ if (
1431
+ schedule.consentRecordHashes.length === 0 ||
1432
+ transition.nextEventIdentity === null ||
1433
+ transition.nextDueAt === null ||
1434
+ Date.parse(transition.nextDueAt) < Date.parse(schedule.startsAt)
1435
+ ) {
1436
+ fail(
1437
+ 'LIVE_EVIDENCE_AUTHORITY_INVALID',
1438
+ 'Enabling measurement requires consent custody and a bounded runtime-issued due identity.',
1439
+ );
759
1440
  }
760
1441
  } else if (transition.type === 'run-issued') {
761
- if (schedule.nextEventIdentity !== transition.eventId || schedule.nextDueAt === null
762
- || Date.parse(transition.at) < Date.parse(schedule.nextDueAt)
763
- || (schedule.endsAt !== null && Date.parse(transition.at) > Date.parse(schedule.endsAt))) {
764
- fail('LIVE_EVIDENCE_TRANSITION_INVALID', 'Measurement run is not the exact due runtime identity within its schedule window.');
1442
+ if (
1443
+ schedule.nextEventIdentity !== transition.eventId ||
1444
+ schedule.nextDueAt === null ||
1445
+ Date.parse(transition.at) < Date.parse(schedule.nextDueAt) ||
1446
+ (schedule.endsAt !== null && Date.parse(transition.at) > Date.parse(schedule.endsAt))
1447
+ ) {
1448
+ fail(
1449
+ 'LIVE_EVIDENCE_TRANSITION_INVALID',
1450
+ 'Measurement run is not the exact due runtime identity within its schedule window.',
1451
+ );
765
1452
  }
766
1453
  runCount += 1;
767
1454
  const terminalRun = runCount >= schedule.maxRuns || schedule.recurrence.kind === 'once';
768
1455
  toState = terminalRun ? 'completed' : 'enabled';
769
- if (terminalRun ? (transition.nextEventIdentity !== null || transition.nextDueAt !== null)
770
- : (transition.nextEventIdentity === null || transition.nextDueAt === null
771
- || transition.nextEventIdentity === transition.eventId
772
- || Date.parse(transition.nextDueAt) <= Date.parse(schedule.nextDueAt))) {
773
- fail('LIVE_EVIDENCE_TRANSITION_INVALID', 'Measurement run successor identity or completion state is invalid.');
1456
+ if (
1457
+ terminalRun
1458
+ ? transition.nextEventIdentity !== null || transition.nextDueAt !== null
1459
+ : transition.nextEventIdentity === null ||
1460
+ transition.nextDueAt === null ||
1461
+ transition.nextEventIdentity === transition.eventId ||
1462
+ Date.parse(transition.nextDueAt) <= Date.parse(schedule.nextDueAt)
1463
+ ) {
1464
+ fail(
1465
+ 'LIVE_EVIDENCE_TRANSITION_INVALID',
1466
+ 'Measurement run successor identity or completion state is invalid.',
1467
+ );
774
1468
  }
775
1469
  } else if (['disable', 'revoke', 'expire', 'complete'].includes(transition.type)) {
776
- if (transition.nextEventIdentity !== null || transition.nextDueAt !== null) fail('LIVE_EVIDENCE_TRANSITION_INVALID', 'Inactive transition cannot retain an executable due identity.');
777
- } else if (transition.nextEventIdentity !== schedule.nextEventIdentity || transition.nextDueAt !== schedule.nextDueAt) {
778
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Pause or resume cannot substitute the scheduled due identity.');
779
- }
780
- const next = { ...clone(schedule), generation: schedule.generation + 1, state: toState, runCount,
781
- nextEventIdentity: transition.nextEventIdentity, nextDueAt: transition.nextDueAt,
782
- lastReceiptId: transition.receiptId, lastTransitionHash: transitionHash };
1470
+ if (transition.nextEventIdentity !== null || transition.nextDueAt !== null)
1471
+ fail(
1472
+ 'LIVE_EVIDENCE_TRANSITION_INVALID',
1473
+ 'Inactive transition cannot retain an executable due identity.',
1474
+ );
1475
+ } else if (
1476
+ transition.nextEventIdentity !== schedule.nextEventIdentity ||
1477
+ transition.nextDueAt !== schedule.nextDueAt
1478
+ ) {
1479
+ fail(
1480
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1481
+ 'Pause or resume cannot substitute the scheduled due identity.',
1482
+ );
1483
+ }
1484
+ const next = {
1485
+ ...clone(schedule),
1486
+ generation: schedule.generation + 1,
1487
+ state: toState,
1488
+ runCount,
1489
+ nextEventIdentity: transition.nextEventIdentity,
1490
+ nextDueAt: transition.nextDueAt,
1491
+ lastReceiptId: transition.receiptId,
1492
+ lastTransitionHash: transitionHash,
1493
+ };
783
1494
  delete next.scheduleHash;
784
1495
  next.scheduleHash = sha256Jcs(next);
785
1496
  const normalizedNext = assertOperatingMeasurementScheduleV2(next);
786
1497
  const receipt = scheduleReceipt(schedule, transition, normalizedNext);
787
- return freeze({ replay: false, schedule: normalizedNext,
788
- receipt: assertOperatingMeasurementScheduleReceiptV2(receipt, { previousSchedule: schedule, resultingSchedule: normalizedNext }) });
1498
+ return freeze({
1499
+ replay: false,
1500
+ schedule: normalizedNext,
1501
+ receipt: assertOperatingMeasurementScheduleReceiptV2(receipt, {
1502
+ previousSchedule: schedule,
1503
+ resultingSchedule: normalizedNext,
1504
+ }),
1505
+ });
789
1506
  }
790
1507
 
791
- export function assertOperatingEvidenceObservationV2(observation, {
792
- measurementPlan, metricObservation, ingestion, connectorCheckpoint, artifact, evidenceRefs, acceptedBridge,
793
- } = {}) {
1508
+ export function assertOperatingEvidenceObservationV2(
1509
+ observation,
1510
+ {
1511
+ measurementPlan,
1512
+ metricObservation,
1513
+ ingestion,
1514
+ connectorCheckpoint,
1515
+ artifact,
1516
+ evidenceRefs,
1517
+ acceptedBridge,
1518
+ } = {},
1519
+ ) {
794
1520
  protocol('operating-evidence-observation', observation);
795
1521
  safePortable(observation);
796
1522
  selfHash(observation, 'observationHash');
797
- if (measurementPlan === undefined) fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'Evidence observation requires the exact measurement plan.');
1523
+ if (measurementPlan === undefined)
1524
+ fail(
1525
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
1526
+ 'Evidence observation requires the exact measurement plan.',
1527
+ );
798
1528
  const plan = assertOperatingMeasurementPlanV2(measurementPlan);
799
- if (plan.measurementPlanId !== observation.measurementPlan.recordId || plan.planHash !== observation.measurementPlan.recordDigest
800
- || plan.metric.metricId !== observation.metricId || plan.metric.unit !== observation.unit || plan.metric.dimension !== observation.dimension) {
801
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Evidence observation changed measurement-plan metric custody.');
802
- }
803
- if (ingestion === undefined || connectorCheckpoint === undefined || artifact === undefined || !Array.isArray(evidenceRefs)
804
- || acceptedBridge === undefined) {
805
- fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'Evidence observation requires the exact accepted ingestion bridge, checkpoint, Artifact, and EvidenceRef custody.');
1529
+ if (
1530
+ plan.measurementPlanId !== observation.measurementPlan.recordId ||
1531
+ plan.planHash !== observation.measurementPlan.recordDigest ||
1532
+ plan.metric.metricId !== observation.metricId ||
1533
+ plan.metric.unit !== observation.unit ||
1534
+ plan.metric.dimension !== observation.dimension
1535
+ ) {
1536
+ fail(
1537
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1538
+ 'Evidence observation changed measurement-plan metric custody.',
1539
+ );
1540
+ }
1541
+ if (
1542
+ ingestion === undefined ||
1543
+ connectorCheckpoint === undefined ||
1544
+ artifact === undefined ||
1545
+ !Array.isArray(evidenceRefs) ||
1546
+ acceptedBridge === undefined
1547
+ ) {
1548
+ fail(
1549
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
1550
+ 'Evidence observation requires the exact accepted ingestion bridge, checkpoint, Artifact, and EvidenceRef custody.',
1551
+ );
806
1552
  }
807
1553
  const accepted = assertAcceptedLiveEvidenceBridgeV2(ingestion, acceptedBridge);
808
- if (accepted.ingestionHash !== ingestion.ingestionHash
809
- || acceptedBridge.artifact?.artifactId !== artifact.artifactId
810
- || acceptedBridge.resultCheckpoint?.checkpointId !== connectorCheckpoint.checkpointId
811
- || evidenceRefs.length !== 1
812
- || acceptedBridge.evidenceRef?.evidenceRefId !== evidenceRefs[0]?.evidenceRefId
813
- || sha256Jcs(acceptedBridge.evidenceRef) !== sha256Jcs(evidenceRefs[0])) {
814
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Observation custody is not the exact accepted live-evidence bridge.');
1554
+ if (
1555
+ accepted.ingestionHash !== ingestion.ingestionHash ||
1556
+ acceptedBridge.artifact?.artifactId !== artifact.artifactId ||
1557
+ acceptedBridge.resultCheckpoint?.checkpointId !== connectorCheckpoint.checkpointId ||
1558
+ evidenceRefs.length !== 1 ||
1559
+ acceptedBridge.evidenceRef?.evidenceRefId !== evidenceRefs[0]?.evidenceRefId ||
1560
+ sha256Jcs(acceptedBridge.evidenceRef) !== sha256Jcs(evidenceRefs[0])
1561
+ ) {
1562
+ fail(
1563
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1564
+ 'Observation custody is not the exact accepted live-evidence bridge.',
1565
+ );
815
1566
  }
816
1567
  const checkpoint = assertOperatingConnectorCheckpointV2(connectorCheckpoint);
817
1568
  protocol('operating-artifact', artifact);
818
- if (observation.ingestion.ingestionId !== ingestion.ingestionId || observation.ingestion.ingestionHash !== ingestion.ingestionHash
819
- || observation.checkpoint.checkpointId !== checkpoint.checkpointId || observation.checkpoint.checkpointHash !== checkpoint.checkpointHash
820
- || observation.artifact.artifactId !== artifact.artifactId || observation.artifact.recordDigest !== sha256Jcs(artifact)
821
- || artifact.canonicalHash !== sha256Jcs(ingestion) || ingestion.providerRegistrationHash !== observation.providerRegistrationHash
822
- || !sameValue(ingestion.provider, observation.provider)) {
823
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Evidence observation changed live-ingestion Artifact or provider custody.');
824
- }
825
- const refs = evidenceRefs.map((entry) => {
826
- protocol('operating-evidence-ref', entry);
827
- return { evidenceRefId: entry.evidenceRefId, recordDigest: sha256Jcs(entry) };
828
- }).sort((left, right) => left.evidenceRefId.localeCompare(right.evidenceRefId));
829
- const claimedRefs = [...observation.evidenceRefs].sort((left, right) => left.evidenceRefId.localeCompare(right.evidenceRefId));
830
- if (!sameValue(refs, claimedRefs)) fail('LIVE_EVIDENCE_BASE_RECORD_MISMATCH', 'Evidence observation changed EvidenceRef membership or bytes.');
1569
+ if (
1570
+ observation.ingestion.ingestionId !== ingestion.ingestionId ||
1571
+ observation.ingestion.ingestionHash !== ingestion.ingestionHash ||
1572
+ observation.checkpoint.checkpointId !== checkpoint.checkpointId ||
1573
+ observation.checkpoint.checkpointHash !== checkpoint.checkpointHash ||
1574
+ observation.artifact.artifactId !== artifact.artifactId ||
1575
+ observation.artifact.recordDigest !== sha256Jcs(artifact) ||
1576
+ artifact.canonicalHash !== sha256Jcs(ingestion) ||
1577
+ ingestion.providerRegistrationHash !== observation.providerRegistrationHash ||
1578
+ !sameValue(ingestion.provider, observation.provider)
1579
+ ) {
1580
+ fail(
1581
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1582
+ 'Evidence observation changed live-ingestion Artifact or provider custody.',
1583
+ );
1584
+ }
1585
+ const refs = evidenceRefs
1586
+ .map((entry) => {
1587
+ protocol('operating-evidence-ref', entry);
1588
+ return { evidenceRefId: entry.evidenceRefId, recordDigest: sha256Jcs(entry) };
1589
+ })
1590
+ .sort((left, right) => left.evidenceRefId.localeCompare(right.evidenceRefId));
1591
+ const claimedRefs = [...observation.evidenceRefs].sort((left, right) =>
1592
+ left.evidenceRefId.localeCompare(right.evidenceRefId),
1593
+ );
1594
+ if (!sameValue(refs, claimedRefs))
1595
+ fail(
1596
+ 'LIVE_EVIDENCE_BASE_RECORD_MISMATCH',
1597
+ 'Evidence observation changed EvidenceRef membership or bytes.',
1598
+ );
831
1599
  if (observation.status === 'observed') {
832
1600
  currentAt(observation.observedAt, observation.freshUntil, 'Observation');
833
- if (metricObservation === undefined) fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'Observed evidence requires the exact canonical metric observation.');
1601
+ if (metricObservation === undefined)
1602
+ fail(
1603
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
1604
+ 'Observed evidence requires the exact canonical metric observation.',
1605
+ );
834
1606
  protocol('operating-metric-observation', metricObservation);
835
- exactDigest(metricObservation, observation.metricObservation.recordDigest, 'Metric observation');
836
- same([metricObservation.observationId, metricObservation.metricId, metricObservation.value, metricObservation.unit, metricObservation.observedAt, metricObservation.sourceArtifactId, metricObservation.evidenceRefIds], [observation.metricObservation.recordId, observation.metricId, observation.value, observation.unit, observation.observedAt, observation.artifact.artifactId, observation.evidenceRefs.map((entry) => entry.evidenceRefId)], 'Metric observation');
837
- } else if ((observation.status === 'absent' && observation.absences.length === 0)
838
- || (observation.status === 'contradicted' && observation.contradictions.length === 0)) {
839
- fail('LIVE_EVIDENCE_FALSE_PASS', 'Non-observed evidence must retain its typed absence or contradiction.');
1607
+ exactDigest(
1608
+ metricObservation,
1609
+ observation.metricObservation.recordDigest,
1610
+ 'Metric observation',
1611
+ );
1612
+ same(
1613
+ [
1614
+ metricObservation.observationId,
1615
+ metricObservation.metricId,
1616
+ metricObservation.value,
1617
+ metricObservation.unit,
1618
+ metricObservation.observedAt,
1619
+ metricObservation.sourceArtifactId,
1620
+ metricObservation.evidenceRefIds,
1621
+ ],
1622
+ [
1623
+ observation.metricObservation.recordId,
1624
+ observation.metricId,
1625
+ observation.value,
1626
+ observation.unit,
1627
+ observation.observedAt,
1628
+ observation.artifact.artifactId,
1629
+ observation.evidenceRefs.map((entry) => entry.evidenceRefId),
1630
+ ],
1631
+ 'Metric observation',
1632
+ );
1633
+ } else if (
1634
+ (observation.status === 'absent' && observation.absences.length === 0) ||
1635
+ (observation.status === 'contradicted' && observation.contradictions.length === 0)
1636
+ ) {
1637
+ fail(
1638
+ 'LIVE_EVIDENCE_FALSE_PASS',
1639
+ 'Non-observed evidence must retain its typed absence or contradiction.',
1640
+ );
840
1641
  }
841
1642
  return freeze(clone(observation));
842
1643
  }
843
1644
 
844
1645
  function observationCustodyFor(observation, custody) {
845
- const matches = custody.filter((entry) => entry?.evidenceObservationId === observation.evidenceObservationId);
846
- if (matches.length !== 1) fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'Each evidence observation requires one exact custody bundle.', { evidenceObservationId: observation.evidenceObservationId });
1646
+ const matches = custody.filter(
1647
+ (entry) => entry?.evidenceObservationId === observation.evidenceObservationId,
1648
+ );
1649
+ if (matches.length !== 1)
1650
+ fail(
1651
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
1652
+ 'Each evidence observation requires one exact custody bundle.',
1653
+ { evidenceObservationId: observation.evidenceObservationId },
1654
+ );
847
1655
  return matches[0];
848
1656
  }
849
1657
 
850
- function canonicalEvaluationInputs({ evaluation, plan, evidenceObservations, metricObservations, observationCustody }) {
851
- if (!Array.isArray(observationCustody)) fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'Outcome evaluation requires exact observation custody bundles.');
1658
+ function canonicalEvaluationInputs({
1659
+ evaluation,
1660
+ plan,
1661
+ evidenceObservations,
1662
+ metricObservations,
1663
+ observationCustody,
1664
+ }) {
1665
+ if (!Array.isArray(observationCustody))
1666
+ fail(
1667
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
1668
+ 'Outcome evaluation requires exact observation custody bundles.',
1669
+ );
852
1670
  const ids = new Set();
853
- const normalizedEvidence = evidenceObservations.map((entry) => {
854
- if (ids.has(entry.evidenceObservationId)) fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Duplicate evidence observation identity is forbidden.', { evidenceObservationId: entry.evidenceObservationId });
855
- ids.add(entry.evidenceObservationId);
856
- const custody = observationCustodyFor(entry, observationCustody);
857
- const metricObservation = entry.metricObservation === null ? undefined
858
- : metricObservations.find((candidate) => candidate.observationId === entry.metricObservation.recordId);
859
- return assertOperatingEvidenceObservationV2(entry, { measurementPlan: plan, metricObservation, ...custody });
860
- }).sort((left, right) => left.evidenceObservationId.localeCompare(right.evidenceObservationId));
861
- if (normalizedEvidence.length !== evaluation.observations.length || observationCustody.length !== normalizedEvidence.length) {
1671
+ const normalizedEvidence = evidenceObservations
1672
+ .map((entry) => {
1673
+ if (ids.has(entry.evidenceObservationId))
1674
+ fail(
1675
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1676
+ 'Duplicate evidence observation identity is forbidden.',
1677
+ { evidenceObservationId: entry.evidenceObservationId },
1678
+ );
1679
+ ids.add(entry.evidenceObservationId);
1680
+ const custody = observationCustodyFor(entry, observationCustody);
1681
+ const metricObservation =
1682
+ entry.metricObservation === null
1683
+ ? undefined
1684
+ : metricObservations.find(
1685
+ (candidate) => candidate.observationId === entry.metricObservation.recordId,
1686
+ );
1687
+ return assertOperatingEvidenceObservationV2(entry, {
1688
+ measurementPlan: plan,
1689
+ metricObservation,
1690
+ ...custody,
1691
+ });
1692
+ })
1693
+ .sort((left, right) => left.evidenceObservationId.localeCompare(right.evidenceObservationId));
1694
+ if (
1695
+ normalizedEvidence.length !== evaluation.observations.length ||
1696
+ observationCustody.length !== normalizedEvidence.length
1697
+ ) {
862
1698
  fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Evaluation observation membership changed.');
863
1699
  }
864
1700
  const wrappers = normalizedEvidence.map((entry) => ({
@@ -872,72 +1708,216 @@ function canonicalEvaluationInputs({ evaluation, plan, evidenceObservations, met
872
1708
  freshUntil: entry.freshUntil,
873
1709
  status: entry.status,
874
1710
  }));
875
- if (!sameValue(evaluation.observations, wrappers)) fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Evaluation wrappers are not the canonical unique observation set.');
876
- const inWindow = normalizedEvidence.filter((entry) => Date.parse(entry.observedAt) >= Date.parse(plan.window.from)
877
- && Date.parse(entry.observedAt) <= Date.parse(plan.window.to));
878
- const observed = inWindow.filter((entry) => entry.status === 'observed' && Date.parse(entry.freshUntil) > Date.parse(evaluation.evaluatedAt));
879
- const absences = inWindow.flatMap((entry) => entry.absences.map((absence) => absence.detailsHash));
880
- for (const entry of inWindow.filter((item) => item.status === 'observed' && Date.parse(item.freshUntil) <= Date.parse(evaluation.evaluatedAt))) {
881
- absences.push(sha256Jcs({ kind: 'stale', evidenceObservationId: entry.evidenceObservationId, observationHash: entry.observationHash, evaluatedAt: evaluation.evaluatedAt }));
1711
+ if (!sameValue(evaluation.observations, wrappers))
1712
+ fail(
1713
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1714
+ 'Evaluation wrappers are not the canonical unique observation set.',
1715
+ );
1716
+ const inWindow = normalizedEvidence.filter(
1717
+ (entry) =>
1718
+ Date.parse(entry.observedAt) >= Date.parse(plan.window.from) &&
1719
+ Date.parse(entry.observedAt) <= Date.parse(plan.window.to),
1720
+ );
1721
+ const observed = inWindow.filter(
1722
+ (entry) =>
1723
+ entry.status === 'observed' &&
1724
+ Date.parse(entry.freshUntil) > Date.parse(evaluation.evaluatedAt),
1725
+ );
1726
+ const absences = inWindow.flatMap((entry) =>
1727
+ entry.absences.map((absence) => absence.detailsHash),
1728
+ );
1729
+ for (const entry of inWindow.filter(
1730
+ (item) =>
1731
+ item.status === 'observed' &&
1732
+ Date.parse(item.freshUntil) <= Date.parse(evaluation.evaluatedAt),
1733
+ )) {
1734
+ absences.push(
1735
+ sha256Jcs({
1736
+ kind: 'stale',
1737
+ evidenceObservationId: entry.evidenceObservationId,
1738
+ observationHash: entry.observationHash,
1739
+ evaluatedAt: evaluation.evaluatedAt,
1740
+ }),
1741
+ );
882
1742
  }
883
1743
  const contradictions = inWindow.flatMap((entry) => entry.contradictions);
884
1744
  return {
885
- normalizedEvidence, wrappers, inWindow, observed,
886
- absences: [...new Set(absences)].sort(), contradictions: [...new Set(contradictions)].sort(),
1745
+ normalizedEvidence,
1746
+ wrappers,
1747
+ inWindow,
1748
+ observed,
1749
+ absences: [...new Set(absences)].sort(),
1750
+ contradictions: [...new Set(contradictions)].sort(),
887
1751
  };
888
1752
  }
889
1753
 
890
- export function assertOperatingOutcomeEvaluationV2(evaluation, {
891
- measurementPlan, verificationPlan, outcome, evidenceObservations, metricObservations = [],
892
- observationCustody, previousEvaluation,
893
- } = {}) {
1754
+ export function assertOperatingOutcomeEvaluationV2(
1755
+ evaluation,
1756
+ {
1757
+ measurementPlan,
1758
+ verificationPlan,
1759
+ outcome,
1760
+ evidenceObservations,
1761
+ metricObservations = [],
1762
+ observationCustody,
1763
+ previousEvaluation,
1764
+ } = {},
1765
+ ) {
894
1766
  protocol('operating-outcome-evaluation', evaluation);
895
1767
  safePortable(evaluation);
896
1768
  selfHash(evaluation, 'evaluationHash');
897
- if (measurementPlan === undefined || verificationPlan === undefined || outcome === undefined || !Array.isArray(evidenceObservations)) fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'Outcome evaluation requires its exact plan, Outcome, and evidence observations.');
1769
+ if (
1770
+ measurementPlan === undefined ||
1771
+ verificationPlan === undefined ||
1772
+ outcome === undefined ||
1773
+ !Array.isArray(evidenceObservations)
1774
+ )
1775
+ fail(
1776
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
1777
+ 'Outcome evaluation requires its exact plan, Outcome, and evidence observations.',
1778
+ );
898
1779
  const plan = assertOperatingMeasurementPlanV2(measurementPlan, { verificationPlan });
899
- if (plan.planHash !== evaluation.measurementPlan.recordDigest || plan.measurementPlanId !== evaluation.measurementPlan.recordId) fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Evaluation changed its measurement plan.');
900
- const canonical = canonicalEvaluationInputs({ evaluation, plan, evidenceObservations, metricObservations, observationCustody });
901
- if (!sameValue([evaluation.window, evaluation.operator, evaluation.unit, evaluation.dimension, evaluation.baseline, evaluation.target, evaluation.minimumEvidence],
902
- [plan.window, plan.target.operator, plan.metric.unit, plan.metric.dimension, plan.baseline.value, plan.target.value, plan.minimumEvidence])) {
903
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Evaluation changed its exact plan algebra, window, or threshold.');
904
- }
905
- const computedResult = canonical.absences.length > 0 || canonical.contradictions.length > 0 || canonical.observed.length < plan.minimumEvidence
906
- ? 'insufficient-evidence' : canonical.observed.every((entry) => compare(plan.target.operator, entry.value, plan.target.value)) ? 'passed' : 'failed';
907
- const computedConfidence = canonical.inWindow.length === 0 ? 0 : canonical.observed.length / Math.max(canonical.inWindow.length, plan.minimumEvidence);
1780
+ if (
1781
+ plan.planHash !== evaluation.measurementPlan.recordDigest ||
1782
+ plan.measurementPlanId !== evaluation.measurementPlan.recordId
1783
+ )
1784
+ fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Evaluation changed its measurement plan.');
1785
+ const canonical = canonicalEvaluationInputs({
1786
+ evaluation,
1787
+ plan,
1788
+ evidenceObservations,
1789
+ metricObservations,
1790
+ observationCustody,
1791
+ });
1792
+ if (
1793
+ !sameValue(
1794
+ [
1795
+ evaluation.window,
1796
+ evaluation.operator,
1797
+ evaluation.unit,
1798
+ evaluation.dimension,
1799
+ evaluation.baseline,
1800
+ evaluation.target,
1801
+ evaluation.minimumEvidence,
1802
+ ],
1803
+ [
1804
+ plan.window,
1805
+ plan.target.operator,
1806
+ plan.metric.unit,
1807
+ plan.metric.dimension,
1808
+ plan.baseline.value,
1809
+ plan.target.value,
1810
+ plan.minimumEvidence,
1811
+ ],
1812
+ )
1813
+ ) {
1814
+ fail(
1815
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1816
+ 'Evaluation changed its exact plan algebra, window, or threshold.',
1817
+ );
1818
+ }
1819
+ const computedResult =
1820
+ canonical.absences.length > 0 ||
1821
+ canonical.contradictions.length > 0 ||
1822
+ canonical.observed.length < plan.minimumEvidence
1823
+ ? 'insufficient-evidence'
1824
+ : canonical.observed.every((entry) =>
1825
+ compare(plan.target.operator, entry.value, plan.target.value),
1826
+ )
1827
+ ? 'passed'
1828
+ : 'failed';
1829
+ const computedConfidence =
1830
+ canonical.inWindow.length === 0
1831
+ ? 0
1832
+ : canonical.observed.length / Math.max(canonical.inWindow.length, plan.minimumEvidence);
908
1833
  const computedInputDigest = sha256Jcs(canonical.wrappers.map((entry) => entry.observationHash));
909
- const computedProviders = [...new Map(canonical.inWindow.map((entry) => [`${entry.provider.id}@${entry.provider.version}`, entry.provider])).values()].sort((a, b) => `${a.id}@${a.version}`.localeCompare(`${b.id}@${b.version}`));
910
- if (evaluation.result !== computedResult || evaluation.confidence !== computedConfidence || evaluation.exactInputDigest !== computedInputDigest
911
- || !sameValue(evaluation.providerVersions, computedProviders) || !sameValue(evaluation.absences, canonical.absences)
912
- || !sameValue(evaluation.contradictions, canonical.contradictions)) fail('LIVE_EVIDENCE_FALSE_PASS', 'Outcome result, confidence, input digest, provider, absence, or contradiction truth is not deterministic from bound evidence.');
1834
+ const computedProviders = [
1835
+ ...new Map(
1836
+ canonical.inWindow.map((entry) => [
1837
+ `${entry.provider.id}@${entry.provider.version}`,
1838
+ entry.provider,
1839
+ ]),
1840
+ ).values(),
1841
+ ].sort((a, b) => `${a.id}@${a.version}`.localeCompare(`${b.id}@${b.version}`));
1842
+ if (
1843
+ evaluation.result !== computedResult ||
1844
+ evaluation.confidence !== computedConfidence ||
1845
+ evaluation.exactInputDigest !== computedInputDigest ||
1846
+ !sameValue(evaluation.providerVersions, computedProviders) ||
1847
+ !sameValue(evaluation.absences, canonical.absences) ||
1848
+ !sameValue(evaluation.contradictions, canonical.contradictions)
1849
+ )
1850
+ fail(
1851
+ 'LIVE_EVIDENCE_FALSE_PASS',
1852
+ 'Outcome result, confidence, input digest, provider, absence, or contradiction truth is not deterministic from bound evidence.',
1853
+ );
913
1854
  if (verificationPlan !== undefined) {
914
1855
  protocol('operating-action-verification-plan', verificationPlan);
915
1856
  exactDigest(verificationPlan, evaluation.verificationPlan.recordDigest, 'Verification plan');
916
- same([verificationPlan.verificationPlanId, verificationPlan.actionId, verificationPlan.metricId], [evaluation.verificationPlan.recordId, evaluation.actionId, evaluation.metricId], 'Evaluation verification plan');
1857
+ same(
1858
+ [verificationPlan.verificationPlanId, verificationPlan.actionId, verificationPlan.metricId],
1859
+ [evaluation.verificationPlan.recordId, evaluation.actionId, evaluation.metricId],
1860
+ 'Evaluation verification plan',
1861
+ );
917
1862
  }
918
1863
  if (outcome !== undefined) {
919
1864
  protocol('operating-outcome', outcome);
920
1865
  exactDigest(outcome, evaluation.outcome.recordDigest, 'Outcome');
921
- const status = evaluation.result === 'passed' ? 'succeeded' : evaluation.result === 'failed' ? 'failed' : 'insufficient-evidence';
922
- same([outcome.outcomeId, outcome.actionId, outcome.verificationPlanId, outcome.status], [evaluation.outcome.recordId, evaluation.actionId, evaluation.verificationPlan.recordId, status], 'Outcome evaluation');
1866
+ const status =
1867
+ evaluation.result === 'passed'
1868
+ ? 'succeeded'
1869
+ : evaluation.result === 'failed'
1870
+ ? 'failed'
1871
+ : 'insufficient-evidence';
1872
+ same(
1873
+ [outcome.outcomeId, outcome.actionId, outcome.verificationPlanId, outcome.status],
1874
+ [
1875
+ evaluation.outcome.recordId,
1876
+ evaluation.actionId,
1877
+ evaluation.verificationPlan.recordId,
1878
+ status,
1879
+ ],
1880
+ 'Outcome evaluation',
1881
+ );
923
1882
  }
924
1883
  if (evaluation.previousEvaluationHash === null) {
925
- if (previousEvaluation !== undefined && previousEvaluation !== null) fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Initial evaluation cannot carry a predecessor.');
1884
+ if (previousEvaluation !== undefined && previousEvaluation !== null)
1885
+ fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Initial evaluation cannot carry a predecessor.');
926
1886
  } else {
927
- if (previousEvaluation === undefined || previousEvaluation === null) fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'Reevaluation requires the exact immutable predecessor.');
1887
+ if (previousEvaluation === undefined || previousEvaluation === null)
1888
+ fail(
1889
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
1890
+ 'Reevaluation requires the exact immutable predecessor.',
1891
+ );
928
1892
  protocol('operating-outcome-evaluation', previousEvaluation);
929
1893
  selfHash(previousEvaluation, 'evaluationHash');
930
- if (previousEvaluation.evaluationHash !== evaluation.previousEvaluationHash
931
- || !sameValue([previousEvaluation.measurementPlan, previousEvaluation.verificationPlan, previousEvaluation.outcome],
932
- [evaluation.measurementPlan, evaluation.verificationPlan, evaluation.outcome])
933
- || Date.parse(previousEvaluation.evaluatedAt) >= Date.parse(evaluation.evaluatedAt)
934
- || previousEvaluation.exactInputDigest === evaluation.exactInputDigest) {
935
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Reevaluation predecessor, lineage, time, or changed evidence custody is invalid.');
1894
+ if (
1895
+ previousEvaluation.evaluationHash !== evaluation.previousEvaluationHash ||
1896
+ !sameValue(
1897
+ [
1898
+ previousEvaluation.measurementPlan,
1899
+ previousEvaluation.verificationPlan,
1900
+ previousEvaluation.outcome,
1901
+ ],
1902
+ [evaluation.measurementPlan, evaluation.verificationPlan, evaluation.outcome],
1903
+ ) ||
1904
+ Date.parse(previousEvaluation.evaluatedAt) >= Date.parse(evaluation.evaluatedAt) ||
1905
+ previousEvaluation.exactInputDigest === evaluation.exactInputDigest
1906
+ ) {
1907
+ fail(
1908
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1909
+ 'Reevaluation predecessor, lineage, time, or changed evidence custody is invalid.',
1910
+ );
936
1911
  }
937
1912
  }
938
- if (evaluation.revisit.required !== (evaluation.result !== 'passed')
939
- || !sameValue(evaluation.revisit.decisionIds, verificationPlan.revisitDecisionIds)) {
940
- fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Evaluation revisit truth changed from its result or verification plan.');
1913
+ if (
1914
+ evaluation.revisit.required !== (evaluation.result !== 'passed') ||
1915
+ !sameValue(evaluation.revisit.decisionIds, verificationPlan.revisitDecisionIds)
1916
+ ) {
1917
+ fail(
1918
+ 'LIVE_EVIDENCE_BINDING_MISMATCH',
1919
+ 'Evaluation revisit truth changed from its result or verification plan.',
1920
+ );
941
1921
  }
942
1922
  return freeze(clone(evaluation));
943
1923
  }
@@ -952,68 +1932,214 @@ function compare(operator, value, target) {
952
1932
  }
953
1933
 
954
1934
  export function evaluateOperatingOutcomeV2({
955
- plan, observations, metricObservations, observationCustody, evaluationId, outcome, verificationPlan,
956
- evaluatedAt, previousEvaluation = null,
1935
+ plan,
1936
+ observations,
1937
+ metricObservations,
1938
+ observationCustody,
1939
+ evaluationId,
1940
+ outcome,
1941
+ verificationPlan,
1942
+ evaluatedAt,
1943
+ previousEvaluation = null,
957
1944
  }) {
958
1945
  const normalizedPlan = assertOperatingMeasurementPlanV2(plan, { verificationPlan });
959
- const normalized = observations.map((entry) => {
960
- const custody = observationCustodyFor(entry, observationCustody);
961
- return assertOperatingEvidenceObservationV2(entry, { measurementPlan: normalizedPlan,
962
- metricObservation: entry.metricObservation === null ? undefined : metricObservations.find((candidate) => candidate.observationId === entry.metricObservation.recordId),
963
- ...custody });
964
- }).sort((left, right) => left.evidenceObservationId.localeCompare(right.evidenceObservationId));
965
- const inWindow = normalized.filter((entry) => Date.parse(entry.observedAt) >= Date.parse(plan.window.from) && Date.parse(entry.observedAt) <= Date.parse(plan.window.to));
966
- const observed = inWindow.filter((entry) => entry.status === 'observed' && Date.parse(entry.freshUntil) > Date.parse(evaluatedAt));
967
- const absences = inWindow.flatMap((entry) => entry.absences.map((absence) => absence.detailsHash));
968
- for (const entry of inWindow.filter((item) => item.status === 'observed' && Date.parse(item.freshUntil) <= Date.parse(evaluatedAt))) {
969
- absences.push(sha256Jcs({ kind: 'stale', evidenceObservationId: entry.evidenceObservationId, observationHash: entry.observationHash, evaluatedAt }));
1946
+ const normalized = observations
1947
+ .map((entry) => {
1948
+ const custody = observationCustodyFor(entry, observationCustody);
1949
+ return assertOperatingEvidenceObservationV2(entry, {
1950
+ measurementPlan: normalizedPlan,
1951
+ metricObservation:
1952
+ entry.metricObservation === null
1953
+ ? undefined
1954
+ : metricObservations.find(
1955
+ (candidate) => candidate.observationId === entry.metricObservation.recordId,
1956
+ ),
1957
+ ...custody,
1958
+ });
1959
+ })
1960
+ .sort((left, right) => left.evidenceObservationId.localeCompare(right.evidenceObservationId));
1961
+ const inWindow = normalized.filter(
1962
+ (entry) =>
1963
+ Date.parse(entry.observedAt) >= Date.parse(plan.window.from) &&
1964
+ Date.parse(entry.observedAt) <= Date.parse(plan.window.to),
1965
+ );
1966
+ const observed = inWindow.filter(
1967
+ (entry) =>
1968
+ entry.status === 'observed' && Date.parse(entry.freshUntil) > Date.parse(evaluatedAt),
1969
+ );
1970
+ const absences = inWindow.flatMap((entry) =>
1971
+ entry.absences.map((absence) => absence.detailsHash),
1972
+ );
1973
+ for (const entry of inWindow.filter(
1974
+ (item) => item.status === 'observed' && Date.parse(item.freshUntil) <= Date.parse(evaluatedAt),
1975
+ )) {
1976
+ absences.push(
1977
+ sha256Jcs({
1978
+ kind: 'stale',
1979
+ evidenceObservationId: entry.evidenceObservationId,
1980
+ observationHash: entry.observationHash,
1981
+ evaluatedAt,
1982
+ }),
1983
+ );
970
1984
  }
971
1985
  const contradictions = inWindow.flatMap((entry) => entry.contradictions);
972
1986
  let result = 'insufficient-evidence';
973
- if (absences.length === 0 && contradictions.length === 0 && observed.length >= plan.minimumEvidence) {
974
- result = observed.every((entry) => compare(plan.target.operator, entry.value, plan.target.value)) ? 'passed' : 'failed';
1987
+ if (
1988
+ absences.length === 0 &&
1989
+ contradictions.length === 0 &&
1990
+ observed.length >= plan.minimumEvidence
1991
+ ) {
1992
+ result = observed.every((entry) =>
1993
+ compare(plan.target.operator, entry.value, plan.target.value),
1994
+ )
1995
+ ? 'passed'
1996
+ : 'failed';
975
1997
  }
976
1998
  const evaluation = {
977
- kind: 'operating-outcome-evaluation', schemaVersion: '1.0.0', protocolVersion: '2.0.0', evaluationId, previousEvaluationHash: previousEvaluation?.evaluationHash ?? null,
978
- measurementPlan: { contractId: 'operating-measurement-plan', schemaVersion: '1.0.0', protocolVersion: '2.0.0', recordId: plan.measurementPlanId, recordDigest: plan.planHash },
979
- verificationPlan: { contractId: 'operating-action-verification-plan', schemaVersion: '1.0.0', protocolVersion: '2.0.0', recordId: verificationPlan.verificationPlanId, recordDigest: sha256Jcs(verificationPlan) },
980
- outcome: { contractId: 'operating-outcome', schemaVersion: '1.0.0', protocolVersion: '2.0.0', recordId: outcome.outcomeId, recordDigest: sha256Jcs(outcome) },
981
- actionId: plan.action.actionId, metricId: plan.metric.metricId,
982
- observations: normalized.map((entry) => ({ evidenceObservationId: entry.evidenceObservationId, observationId: entry.metricObservation?.recordId ?? null, observationHash: entry.observationHash, metricObservationDigest: entry.metricObservation?.recordDigest ?? null, value: entry.value, unit: entry.unit, observedAt: entry.observedAt, freshUntil: entry.freshUntil, status: entry.status })),
983
- providerVersions: [...new Map(inWindow.map((entry) => [`${entry.provider.id}@${entry.provider.version}`, entry.provider])).values()].sort((a, b) => `${a.id}@${a.version}`.localeCompare(`${b.id}@${b.version}`)),
984
- window: clone(plan.window), operator: plan.target.operator, unit: plan.metric.unit, dimension: plan.metric.dimension,
985
- baseline: plan.baseline.value, target: clone(plan.target.value), minimumEvidence: plan.minimumEvidence,
986
- exactInputDigest: sha256Jcs(normalized.map((entry) => entry.observationHash)), result,
987
- confidence: inWindow.length === 0 ? 0 : observed.length / Math.max(inWindow.length, plan.minimumEvidence), absences: [...new Set(absences)].sort(),
988
- contradictions: [...new Set(contradictions)].sort(), evaluatedAt,
989
- revisit: { required: result !== 'passed', condition: result === 'passed' ? null : 'Evidence did not prove the declared target.', decisionIds: clone(verificationPlan.revisitDecisionIds) },
1999
+ kind: 'operating-outcome-evaluation',
2000
+ schemaVersion: '1.0.0',
2001
+ protocolVersion: '2.0.0',
2002
+ evaluationId,
2003
+ previousEvaluationHash: previousEvaluation?.evaluationHash ?? null,
2004
+ measurementPlan: {
2005
+ contractId: 'operating-measurement-plan',
2006
+ schemaVersion: '1.0.0',
2007
+ protocolVersion: '2.0.0',
2008
+ recordId: plan.measurementPlanId,
2009
+ recordDigest: plan.planHash,
2010
+ },
2011
+ verificationPlan: {
2012
+ contractId: 'operating-action-verification-plan',
2013
+ schemaVersion: '1.0.0',
2014
+ protocolVersion: '2.0.0',
2015
+ recordId: verificationPlan.verificationPlanId,
2016
+ recordDigest: sha256Jcs(verificationPlan),
2017
+ },
2018
+ outcome: {
2019
+ contractId: 'operating-outcome',
2020
+ schemaVersion: '1.0.0',
2021
+ protocolVersion: '2.0.0',
2022
+ recordId: outcome.outcomeId,
2023
+ recordDigest: sha256Jcs(outcome),
2024
+ },
2025
+ actionId: plan.action.actionId,
2026
+ metricId: plan.metric.metricId,
2027
+ observations: normalized.map((entry) => ({
2028
+ evidenceObservationId: entry.evidenceObservationId,
2029
+ observationId: entry.metricObservation?.recordId ?? null,
2030
+ observationHash: entry.observationHash,
2031
+ metricObservationDigest: entry.metricObservation?.recordDigest ?? null,
2032
+ value: entry.value,
2033
+ unit: entry.unit,
2034
+ observedAt: entry.observedAt,
2035
+ freshUntil: entry.freshUntil,
2036
+ status: entry.status,
2037
+ })),
2038
+ providerVersions: [
2039
+ ...new Map(
2040
+ inWindow.map((entry) => [`${entry.provider.id}@${entry.provider.version}`, entry.provider]),
2041
+ ).values(),
2042
+ ].sort((a, b) => `${a.id}@${a.version}`.localeCompare(`${b.id}@${b.version}`)),
2043
+ window: clone(plan.window),
2044
+ operator: plan.target.operator,
2045
+ unit: plan.metric.unit,
2046
+ dimension: plan.metric.dimension,
2047
+ baseline: plan.baseline.value,
2048
+ target: clone(plan.target.value),
2049
+ minimumEvidence: plan.minimumEvidence,
2050
+ exactInputDigest: sha256Jcs(normalized.map((entry) => entry.observationHash)),
2051
+ result,
2052
+ confidence:
2053
+ inWindow.length === 0 ? 0 : observed.length / Math.max(inWindow.length, plan.minimumEvidence),
2054
+ absences: [...new Set(absences)].sort(),
2055
+ contradictions: [...new Set(contradictions)].sort(),
2056
+ evaluatedAt,
2057
+ revisit: {
2058
+ required: result !== 'passed',
2059
+ condition: result === 'passed' ? null : 'Evidence did not prove the declared target.',
2060
+ decisionIds: clone(verificationPlan.revisitDecisionIds),
2061
+ },
990
2062
  };
991
2063
  evaluation.evaluationHash = sha256Jcs(evaluation);
992
- return assertOperatingOutcomeEvaluationV2(evaluation, { measurementPlan: normalizedPlan, verificationPlan, outcome,
993
- evidenceObservations: normalized, metricObservations, observationCustody, previousEvaluation });
2064
+ return assertOperatingOutcomeEvaluationV2(evaluation, {
2065
+ measurementPlan: normalizedPlan,
2066
+ verificationPlan,
2067
+ outcome,
2068
+ evidenceObservations: normalized,
2069
+ metricObservations,
2070
+ observationCustody,
2071
+ previousEvaluation,
2072
+ });
994
2073
  }
995
2074
 
996
- export function assertOperatingLearningReceiptV2(receipt, {
997
- learning, outcome, evaluation, measurementPlan, verificationPlan, evidenceObservations,
998
- metricObservations, observationCustody, previousEvaluation,
999
- } = {}) {
2075
+ export function assertOperatingLearningReceiptV2(
2076
+ receipt,
2077
+ {
2078
+ learning,
2079
+ outcome,
2080
+ evaluation,
2081
+ measurementPlan,
2082
+ verificationPlan,
2083
+ evidenceObservations,
2084
+ metricObservations,
2085
+ observationCustody,
2086
+ previousEvaluation,
2087
+ } = {},
2088
+ ) {
1000
2089
  protocol('operating-learning-receipt', receipt);
1001
2090
  safePortable(receipt);
1002
2091
  selfHash(receipt, 'receiptHash');
1003
- if (learning === undefined || outcome === undefined || evaluation === undefined
1004
- || measurementPlan === undefined || verificationPlan === undefined
1005
- || !Array.isArray(evidenceObservations) || !Array.isArray(metricObservations)
1006
- || !Array.isArray(observationCustody)) {
1007
- fail('LIVE_EVIDENCE_BASE_RECORD_REQUIRED', 'A certifying Learning receipt requires exact Learning, Outcome, evaluation, plan, and observation custody.');
2092
+ if (
2093
+ learning === undefined ||
2094
+ outcome === undefined ||
2095
+ evaluation === undefined ||
2096
+ measurementPlan === undefined ||
2097
+ verificationPlan === undefined ||
2098
+ !Array.isArray(evidenceObservations) ||
2099
+ !Array.isArray(metricObservations) ||
2100
+ !Array.isArray(observationCustody)
2101
+ ) {
2102
+ fail(
2103
+ 'LIVE_EVIDENCE_BASE_RECORD_REQUIRED',
2104
+ 'A certifying Learning receipt requires exact Learning, Outcome, evaluation, plan, and observation custody.',
2105
+ );
1008
2106
  }
1009
2107
  protocol('operating-learning', learning);
1010
2108
  exactDigest(learning, receipt.learning.recordDigest, 'Learning');
1011
- same([learning.learningId, learning.outcomeId, learning.assumptionIds, learning.decisionIds, learning.evidenceRefIds], [receipt.learning.recordId, receipt.outcome.recordId, receipt.assumptionIds, receipt.decisionIds, receipt.evidenceRefIds], 'Learning receipt');
2109
+ same(
2110
+ [
2111
+ learning.learningId,
2112
+ learning.outcomeId,
2113
+ learning.assumptionIds,
2114
+ learning.decisionIds,
2115
+ learning.evidenceRefIds,
2116
+ ],
2117
+ [
2118
+ receipt.learning.recordId,
2119
+ receipt.outcome.recordId,
2120
+ receipt.assumptionIds,
2121
+ receipt.decisionIds,
2122
+ receipt.evidenceRefIds,
2123
+ ],
2124
+ 'Learning receipt',
2125
+ );
1012
2126
  same(sha256Jcs(learning.statement), receipt.statementDigest, 'Learning statement digest');
1013
2127
  protocol('operating-outcome', outcome);
1014
2128
  exactDigest(outcome, receipt.outcome.recordDigest, 'Learning outcome');
1015
- assertOperatingOutcomeEvaluationV2(evaluation, { measurementPlan, verificationPlan, outcome,
1016
- evidenceObservations, metricObservations, observationCustody, previousEvaluation });
1017
- if (evaluation.evaluationId !== receipt.evaluation.evaluationId || evaluation.evaluationHash !== receipt.evaluation.evaluationHash || evaluation.result !== receipt.evaluation.result) fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Learning receipt changed the evaluation result.');
2129
+ assertOperatingOutcomeEvaluationV2(evaluation, {
2130
+ measurementPlan,
2131
+ verificationPlan,
2132
+ outcome,
2133
+ evidenceObservations,
2134
+ metricObservations,
2135
+ observationCustody,
2136
+ previousEvaluation,
2137
+ });
2138
+ if (
2139
+ evaluation.evaluationId !== receipt.evaluation.evaluationId ||
2140
+ evaluation.evaluationHash !== receipt.evaluation.evaluationHash ||
2141
+ evaluation.result !== receipt.evaluation.result
2142
+ )
2143
+ fail('LIVE_EVIDENCE_BINDING_MISMATCH', 'Learning receipt changed the evaluation result.');
1018
2144
  return freeze(clone(receipt));
1019
2145
  }