@actuarial-ts/compliance 0.6.0 → 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.
- package/README.md +19 -9
- package/dist/bundle.d.ts +1 -1
- package/dist/bundle.d.ts.map +1 -1
- package/dist/bundle.js +163 -21
- package/dist/bundle.js.map +1 -1
- package/dist/diagnosticArtifactStream.d.ts +30 -0
- package/dist/diagnosticArtifactStream.d.ts.map +1 -0
- package/dist/diagnosticArtifactStream.js +128 -0
- package/dist/diagnosticArtifactStream.js.map +1 -0
- package/dist/diagnosticByteSource.d.ts +10 -0
- package/dist/diagnosticByteSource.d.ts.map +1 -0
- package/dist/diagnosticByteSource.js +70 -0
- package/dist/diagnosticByteSource.js.map +1 -0
- package/dist/diagnosticByteView.d.ts +3 -0
- package/dist/diagnosticByteView.d.ts.map +1 -0
- package/dist/diagnosticByteView.js +27 -0
- package/dist/diagnosticByteView.js.map +1 -0
- package/dist/diagnosticCompactRun.d.ts +43 -0
- package/dist/diagnosticCompactRun.d.ts.map +1 -0
- package/dist/diagnosticCompactRun.js +253 -0
- package/dist/diagnosticCompactRun.js.map +1 -0
- package/dist/diagnosticReplayFrames.d.ts +10 -0
- package/dist/diagnosticReplayFrames.d.ts.map +1 -0
- package/dist/diagnosticReplayFrames.js +99 -0
- package/dist/diagnosticReplayFrames.js.map +1 -0
- package/dist/diagnosticReplayProtocol.d.ts +17 -0
- package/dist/diagnosticReplayProtocol.d.ts.map +1 -0
- package/dist/diagnosticReplayProtocol.js +98 -0
- package/dist/diagnosticReplayProtocol.js.map +1 -0
- package/dist/diagnosticReplayReader.d.ts +41 -0
- package/dist/diagnosticReplayReader.d.ts.map +1 -0
- package/dist/diagnosticReplayReader.js +346 -0
- package/dist/diagnosticReplayReader.js.map +1 -0
- package/dist/diagnosticReplayValue.d.ts +34 -0
- package/dist/diagnosticReplayValue.d.ts.map +1 -0
- package/dist/diagnosticReplayValue.js +269 -0
- package/dist/diagnosticReplayValue.js.map +1 -0
- package/dist/diagnosticReplayWriter.d.ts +25 -0
- package/dist/diagnosticReplayWriter.d.ts.map +1 -0
- package/dist/diagnosticReplayWriter.js +148 -0
- package/dist/diagnosticReplayWriter.js.map +1 -0
- package/dist/diagnosticRun.d.ts +52 -29
- package/dist/diagnosticRun.d.ts.map +1 -1
- package/dist/diagnosticRun.js +564 -174
- package/dist/diagnosticRun.js.map +1 -1
- package/dist/diagnosticRunEvidence.d.ts +18 -0
- package/dist/diagnosticRunEvidence.d.ts.map +1 -0
- package/dist/diagnosticRunEvidence.js +195 -0
- package/dist/diagnosticRunEvidence.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/ledger.d.ts.map +1 -1
- package/dist/ledger.js +47 -6
- package/dist/ledger.js.map +1 -1
- package/dist/metadata.d.ts.map +1 -1
- package/dist/metadata.js +27 -3
- package/dist/metadata.js.map +1 -1
- package/dist/sha256Stream.d.ts +6 -0
- package/dist/sha256Stream.d.ts.map +1 -0
- package/dist/sha256Stream.js +103 -0
- package/dist/sha256Stream.js.map +1 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +6 -5
- package/src/bundle.ts +272 -32
- package/src/diagnosticArtifactStream.ts +148 -0
- package/src/diagnosticByteSource.ts +82 -0
- package/src/diagnosticByteView.ts +27 -0
- package/src/diagnosticCompactRun.ts +462 -0
- package/src/diagnosticReplayFrames.ts +99 -0
- package/src/diagnosticReplayProtocol.ts +99 -0
- package/src/diagnosticReplayReader.ts +428 -0
- package/src/diagnosticReplayValue.ts +269 -0
- package/src/diagnosticReplayWriter.ts +190 -0
- package/src/diagnosticRun.ts +1030 -93
- package/src/diagnosticRunEvidence.ts +391 -0
- package/src/index.ts +10 -0
- package/src/ledger.ts +59 -8
- package/src/metadata.ts +48 -7
- package/src/sha256Stream.ts +108 -0
- package/src/version.ts +1 -1
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CORE_PACKAGE_VERSION,
|
|
3
|
+
canonicalFnv1a64,
|
|
4
|
+
compareDiagnosticIdentityDocuments,
|
|
5
|
+
createDiagnosticIdentityArray,
|
|
6
|
+
createDiagnosticIdentityObject,
|
|
7
|
+
createDiagnosticIdentityValue,
|
|
8
|
+
fingerprintDiagnosticIdentity,
|
|
9
|
+
getCompactMetricDiagnosticsResultIdentityDocument,
|
|
10
|
+
getCompactPreparedDiagnosticDataFingerprint,
|
|
11
|
+
normalizeDiagnosticsFilterIdentity,
|
|
12
|
+
runMetricDiagnosticsCompact,
|
|
13
|
+
type DiagnosticIdentityDocument,
|
|
14
|
+
} from "@actuarial-ts/core";
|
|
15
|
+
import {
|
|
16
|
+
DATA_PACKAGE_VERSION,
|
|
17
|
+
assertCompletedCompactMetricDiagnosticsRun,
|
|
18
|
+
getCompactDiagnosticReviewReceiptFingerprint,
|
|
19
|
+
getCompactDiagnosticReviewReceiptIdentityDocument,
|
|
20
|
+
reviewPreparedDiagnosticDataCompact,
|
|
21
|
+
type CompletedCompactMetricDiagnosticsRun,
|
|
22
|
+
} from "@actuarial-ts/data";
|
|
23
|
+
import {
|
|
24
|
+
assertComputedDiagnosticArtifactDigest,
|
|
25
|
+
type ComputedDiagnosticArtifactDigest,
|
|
26
|
+
} from "./diagnosticArtifactStream.js";
|
|
27
|
+
import type {
|
|
28
|
+
DiagnosticArtifactDigest,
|
|
29
|
+
DiagnosticPreparationLineage,
|
|
30
|
+
DiagnosticRunIdentity,
|
|
31
|
+
DiagnosticRunProvenance,
|
|
32
|
+
} from "./diagnosticRun.js";
|
|
33
|
+
import {
|
|
34
|
+
plain,
|
|
35
|
+
snapshotLineage,
|
|
36
|
+
token,
|
|
37
|
+
validateArtifactGraph,
|
|
38
|
+
} from "./diagnosticRunEvidence.js";
|
|
39
|
+
import { ComplianceError } from "./errors.js";
|
|
40
|
+
import { COMPLIANCE_PACKAGE_VERSION } from "./version.js";
|
|
41
|
+
|
|
42
|
+
/** Computed digests must be authentic completed byte-stream receipts, not JSON copies. */
|
|
43
|
+
export type CompactDiagnosticArtifactEvidence =
|
|
44
|
+
| ComputedDiagnosticArtifactDigest
|
|
45
|
+
| Extract<DiagnosticArtifactDigest, { assurance: "caller-declared" }>;
|
|
46
|
+
|
|
47
|
+
export interface CreateCompactDiagnosticRunIdentityInput {
|
|
48
|
+
readonly completedRun: CompletedCompactMetricDiagnosticsRun;
|
|
49
|
+
readonly inputArtifacts: readonly CompactDiagnosticArtifactEvidence[];
|
|
50
|
+
readonly preparationArtifacts: readonly CompactDiagnosticArtifactEvidence[];
|
|
51
|
+
readonly preparationLineage: readonly DiagnosticPreparationLineage[];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
declare const verifiedCompactDiagnosticRunProvenanceBrand: unique symbol;
|
|
55
|
+
/**
|
|
56
|
+
* Verified compact evidence, not a legacy provenance DTO or BundleDoc.
|
|
57
|
+
* Documents emit the complete legacy normalized manifest/result identity bytes.
|
|
58
|
+
* They retain immutable owners, not expanded identity arrays or source bytes.
|
|
59
|
+
* The provenance brand, not a structural document, establishes verification.
|
|
60
|
+
*/
|
|
61
|
+
export interface VerifiedCompactDiagnosticRunProvenance
|
|
62
|
+
extends DiagnosticRunIdentity {
|
|
63
|
+
readonly [verifiedCompactDiagnosticRunProvenanceBrand]: true;
|
|
64
|
+
readonly definition: DiagnosticRunProvenance["definition"];
|
|
65
|
+
readonly inputArtifacts: readonly DiagnosticArtifactDigest[];
|
|
66
|
+
readonly preparationArtifacts: readonly DiagnosticArtifactDigest[];
|
|
67
|
+
readonly preparationLineage: readonly DiagnosticPreparationLineage[];
|
|
68
|
+
readonly preparationFingerprint: string;
|
|
69
|
+
readonly reviewFingerprint: string;
|
|
70
|
+
readonly manifestIdentityDocument: DiagnosticIdentityDocument;
|
|
71
|
+
readonly resultIdentityDocument: DiagnosticIdentityDocument;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const verified = new WeakMap<object, CompletedCompactMetricDiagnosticsRun>();
|
|
75
|
+
|
|
76
|
+
function bad(message: string, path: string): never {
|
|
77
|
+
throw new ComplianceError("BAD_DIAGNOSTIC_RUN", message, path);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Snapshot boundary metadata without invoking getters or caller array methods. */
|
|
81
|
+
function record(
|
|
82
|
+
value: unknown,
|
|
83
|
+
allowed: readonly string[],
|
|
84
|
+
path: string,
|
|
85
|
+
): Record<string, unknown> {
|
|
86
|
+
if (!plain(value)) bad("Expected a plain metadata object", path);
|
|
87
|
+
const copy: Record<string, unknown> = Object.create(null);
|
|
88
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
89
|
+
if (typeof key !== "string" || !allowed.includes(key))
|
|
90
|
+
bad("Unknown metadata field", `${path}.${String(key)}`);
|
|
91
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
92
|
+
if (!descriptor || !descriptor.enumerable || !("value" in descriptor))
|
|
93
|
+
bad(
|
|
94
|
+
"Metadata fields must be enumerable data properties",
|
|
95
|
+
`${path}.${key}`,
|
|
96
|
+
);
|
|
97
|
+
copy[key] = descriptor.value;
|
|
98
|
+
}
|
|
99
|
+
return copy;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function array(value: unknown, path: string): unknown[] {
|
|
103
|
+
if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype)
|
|
104
|
+
bad("Expected a plain metadata array", path);
|
|
105
|
+
const length = Object.getOwnPropertyDescriptor(value, "length")?.value;
|
|
106
|
+
if (!Number.isSafeInteger(length) || length < 0)
|
|
107
|
+
bad("Invalid array length", path);
|
|
108
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
109
|
+
if (key === "length") continue;
|
|
110
|
+
if (
|
|
111
|
+
typeof key !== "string" ||
|
|
112
|
+
!/^(0|[1-9][0-9]*)$/.test(key) ||
|
|
113
|
+
Number(key) >= length
|
|
114
|
+
)
|
|
115
|
+
bad("Unexpected array property", `${path}.${String(key)}`);
|
|
116
|
+
}
|
|
117
|
+
const copy: unknown[] = [];
|
|
118
|
+
for (let index = 0; index < length; index++) {
|
|
119
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
|
|
120
|
+
if (!descriptor || !descriptor.enumerable || !("value" in descriptor))
|
|
121
|
+
bad("Array items must be present data properties", `${path}[${index}]`);
|
|
122
|
+
copy.push(descriptor.value);
|
|
123
|
+
}
|
|
124
|
+
return copy;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function artifacts(
|
|
128
|
+
value: unknown,
|
|
129
|
+
scope: "input" | "preparation",
|
|
130
|
+
path: string,
|
|
131
|
+
): readonly DiagnosticArtifactDigest[] {
|
|
132
|
+
const seen = new Set<string>();
|
|
133
|
+
const result = array(value, path).map(
|
|
134
|
+
(raw, index): DiagnosticArtifactDigest => {
|
|
135
|
+
const itemPath = `${path}[${index}]`;
|
|
136
|
+
const item = record(
|
|
137
|
+
raw,
|
|
138
|
+
["id", "scope", "assurance", "algorithm", "value", "byteLength"],
|
|
139
|
+
itemPath,
|
|
140
|
+
);
|
|
141
|
+
if (typeof item.id !== "string")
|
|
142
|
+
bad("Artifact id must be a string", `${itemPath}.id`);
|
|
143
|
+
token(item.id, `${itemPath}.id`);
|
|
144
|
+
if (seen.has(item.id))
|
|
145
|
+
bad("Artifact IDs must be unique", `${itemPath}.id`);
|
|
146
|
+
seen.add(item.id);
|
|
147
|
+
if (item.scope !== scope)
|
|
148
|
+
bad(`Artifact must have ${scope} scope`, `${itemPath}.scope`);
|
|
149
|
+
if (item.assurance === "sdk-computed") {
|
|
150
|
+
assertComputedDiagnosticArtifactDigest(raw);
|
|
151
|
+
return raw;
|
|
152
|
+
}
|
|
153
|
+
if (item.assurance !== "caller-declared")
|
|
154
|
+
bad("Unknown artifact assurance", `${itemPath}.assurance`);
|
|
155
|
+
if (Object.hasOwn(item, "byteLength"))
|
|
156
|
+
bad(
|
|
157
|
+
"Caller-declared evidence cannot claim a computed byte length",
|
|
158
|
+
`${itemPath}.byteLength`,
|
|
159
|
+
);
|
|
160
|
+
if (typeof item.algorithm !== "string" || typeof item.value !== "string")
|
|
161
|
+
bad("Declared algorithm and value must be strings", itemPath);
|
|
162
|
+
token(item.algorithm, `${itemPath}.algorithm`);
|
|
163
|
+
token(item.value, `${itemPath}.value`);
|
|
164
|
+
return Object.freeze({
|
|
165
|
+
id: item.id,
|
|
166
|
+
scope,
|
|
167
|
+
assurance: "caller-declared",
|
|
168
|
+
algorithm: item.algorithm,
|
|
169
|
+
value: item.value,
|
|
170
|
+
});
|
|
171
|
+
},
|
|
172
|
+
);
|
|
173
|
+
return Object.freeze(
|
|
174
|
+
result.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)),
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function lineage(value: unknown): readonly DiagnosticPreparationLineage[] {
|
|
179
|
+
const copied = array(value, "$.preparationLineage").map((raw, index) => {
|
|
180
|
+
const path = `$.preparationLineage[${index}]`;
|
|
181
|
+
const item = record(
|
|
182
|
+
raw,
|
|
183
|
+
["outputArtifactId", "inputArtifactIds", "transformationArtifactIds"],
|
|
184
|
+
path,
|
|
185
|
+
);
|
|
186
|
+
return {
|
|
187
|
+
outputArtifactId: item.outputArtifactId,
|
|
188
|
+
inputArtifactIds: array(
|
|
189
|
+
item.inputArtifactIds,
|
|
190
|
+
`${path}.inputArtifactIds`,
|
|
191
|
+
),
|
|
192
|
+
transformationArtifactIds: array(
|
|
193
|
+
item.transformationArtifactIds,
|
|
194
|
+
`${path}.transformationArtifactIds`,
|
|
195
|
+
),
|
|
196
|
+
};
|
|
197
|
+
});
|
|
198
|
+
return Object.freeze(
|
|
199
|
+
snapshotLineage(copied).map((edge) =>
|
|
200
|
+
Object.freeze({
|
|
201
|
+
outputArtifactId: edge.outputArtifactId,
|
|
202
|
+
inputArtifactIds: Object.freeze([...edge.inputArtifactIds]),
|
|
203
|
+
transformationArtifactIds: Object.freeze([
|
|
204
|
+
...edge.transformationArtifactIds,
|
|
205
|
+
]),
|
|
206
|
+
}),
|
|
207
|
+
),
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function requireEqual(
|
|
212
|
+
actual: DiagnosticIdentityDocument,
|
|
213
|
+
expected: DiagnosticIdentityDocument,
|
|
214
|
+
path: string,
|
|
215
|
+
): void {
|
|
216
|
+
const comparison = compareDiagnosticIdentityDocuments(actual, expected);
|
|
217
|
+
if (!comparison.equal)
|
|
218
|
+
throw new ComplianceError(
|
|
219
|
+
"DIAGNOSTIC_MISMATCH",
|
|
220
|
+
`Deterministic replay differs at canonical code-unit offset ${comparison.codeUnitOffset}`,
|
|
221
|
+
path,
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Replay before issuing authority; hashes never replace complete identity comparison. */
|
|
226
|
+
function rerunAndVerify(run: CompletedCompactMetricDiagnosticsRun): void {
|
|
227
|
+
const review = reviewPreparedDiagnosticDataCompact({
|
|
228
|
+
prepared: run.prepared,
|
|
229
|
+
evidence: run.review.evidence,
|
|
230
|
+
});
|
|
231
|
+
requireEqual(
|
|
232
|
+
getCompactDiagnosticReviewReceiptIdentityDocument(review),
|
|
233
|
+
getCompactDiagnosticReviewReceiptIdentityDocument(run.review),
|
|
234
|
+
"$.review",
|
|
235
|
+
);
|
|
236
|
+
const rerun = runMetricDiagnosticsCompact({
|
|
237
|
+
prepared: run.prepared,
|
|
238
|
+
groupMap: run.groupMap,
|
|
239
|
+
groupDimensions: run.groupDimensions,
|
|
240
|
+
});
|
|
241
|
+
requireEqual(
|
|
242
|
+
getCompactMetricDiagnosticsResultIdentityDocument(rerun),
|
|
243
|
+
getCompactMetricDiagnosticsResultIdentityDocument(run.result),
|
|
244
|
+
"$.result",
|
|
245
|
+
);
|
|
246
|
+
const counts = review.evaluations.summary;
|
|
247
|
+
const effectiveCounts = {
|
|
248
|
+
pass: counts.pass,
|
|
249
|
+
warning: counts.warning,
|
|
250
|
+
fail: counts.fail,
|
|
251
|
+
"not-evaluated": counts.notEvaluated,
|
|
252
|
+
};
|
|
253
|
+
const statuses = ["pass", "warning", "fail", "not-evaluated"] as const;
|
|
254
|
+
const reviewBlocked =
|
|
255
|
+
review.report.checks.some(
|
|
256
|
+
(check) => !run.gate.allowedReviewStatuses.includes(check.status),
|
|
257
|
+
) ||
|
|
258
|
+
statuses.some(
|
|
259
|
+
(status) =>
|
|
260
|
+
effectiveCounts[status] > 0 &&
|
|
261
|
+
!run.gate.allowedReviewStatuses.includes(status),
|
|
262
|
+
);
|
|
263
|
+
const metricBlocked = rerun.findings.some(
|
|
264
|
+
(finding) =>
|
|
265
|
+
finding.category !== "structural" &&
|
|
266
|
+
!run.gate.allowedMetricFindingSeverities.includes(finding.severity),
|
|
267
|
+
);
|
|
268
|
+
if (
|
|
269
|
+
reviewBlocked ||
|
|
270
|
+
metricBlocked ||
|
|
271
|
+
run.gate.reviewGate !== "passed" ||
|
|
272
|
+
run.gate.metricGate !== "passed"
|
|
273
|
+
)
|
|
274
|
+
throw new ComplianceError(
|
|
275
|
+
"DIAGNOSTIC_MISMATCH",
|
|
276
|
+
"Diagnostic execution gates do not recompute as passed",
|
|
277
|
+
"$.gate",
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function manifestDocument(
|
|
282
|
+
run: CompletedCompactMetricDiagnosticsRun,
|
|
283
|
+
inputArtifacts: readonly DiagnosticArtifactDigest[],
|
|
284
|
+
preparationArtifacts: readonly DiagnosticArtifactDigest[],
|
|
285
|
+
preparationLineage: readonly DiagnosticPreparationLineage[],
|
|
286
|
+
preparationFingerprint: string,
|
|
287
|
+
reviewFingerprint: string,
|
|
288
|
+
): DiagnosticIdentityDocument {
|
|
289
|
+
const prepared = run.prepared;
|
|
290
|
+
const expectedCells = createDiagnosticIdentityArray(
|
|
291
|
+
prepared.expectedCells.length,
|
|
292
|
+
(index) => {
|
|
293
|
+
const cell = prepared.expectedCells[index]!;
|
|
294
|
+
return createDiagnosticIdentityObject({
|
|
295
|
+
sourceGroup: createDiagnosticIdentityValue(cell.sourceGroup),
|
|
296
|
+
origin: createDiagnosticIdentityValue(cell.origin),
|
|
297
|
+
valuation: createDiagnosticIdentityValue(cell.valuation),
|
|
298
|
+
source: createDiagnosticIdentityValue(cell.source ?? null),
|
|
299
|
+
});
|
|
300
|
+
},
|
|
301
|
+
);
|
|
302
|
+
return createDiagnosticIdentityObject({
|
|
303
|
+
definitionIntegrity: createDiagnosticIdentityValue(
|
|
304
|
+
prepared.definition.definitionIntegrity,
|
|
305
|
+
),
|
|
306
|
+
preparationFingerprint: createDiagnosticIdentityValue(
|
|
307
|
+
preparationFingerprint,
|
|
308
|
+
),
|
|
309
|
+
runPresetId: createDiagnosticIdentityValue(run.runPresetId),
|
|
310
|
+
datasetArtifactId: createDiagnosticIdentityValue(run.datasetArtifactId),
|
|
311
|
+
inputArtifacts: createDiagnosticIdentityValue(inputArtifacts),
|
|
312
|
+
preparationArtifacts: createDiagnosticIdentityValue(preparationArtifacts),
|
|
313
|
+
preparationLineage: createDiagnosticIdentityValue(preparationLineage),
|
|
314
|
+
inputAudit: createDiagnosticIdentityValue(prepared.inputAudit),
|
|
315
|
+
filter: createDiagnosticIdentityValue(
|
|
316
|
+
normalizeDiagnosticsFilterIdentity(prepared.filter),
|
|
317
|
+
),
|
|
318
|
+
groupMap: createDiagnosticIdentityValue(run.groupMap),
|
|
319
|
+
groupDimensions: createDiagnosticIdentityValue(run.groupDimensions),
|
|
320
|
+
completePeriodCutoffs: createDiagnosticIdentityValue(
|
|
321
|
+
prepared.completePeriodCutoffs,
|
|
322
|
+
),
|
|
323
|
+
expectedCellGridFingerprint: createDiagnosticIdentityValue(
|
|
324
|
+
prepared.expectedCellsProvided
|
|
325
|
+
? fingerprintDiagnosticIdentity(expectedCells, {
|
|
326
|
+
kind: "diagnostic-expected-cell-grid",
|
|
327
|
+
property: "expectedCells",
|
|
328
|
+
})
|
|
329
|
+
: null,
|
|
330
|
+
),
|
|
331
|
+
executionPolicy: createDiagnosticIdentityObject({
|
|
332
|
+
gate: createDiagnosticIdentityValue(run.gate),
|
|
333
|
+
review: createDiagnosticIdentityObject({
|
|
334
|
+
body: getCompactDiagnosticReviewReceiptIdentityDocument(run.review),
|
|
335
|
+
reportFingerprint: createDiagnosticIdentityValue(reviewFingerprint),
|
|
336
|
+
}),
|
|
337
|
+
}),
|
|
338
|
+
engine: createDiagnosticIdentityValue(
|
|
339
|
+
Object.freeze({
|
|
340
|
+
packages: Object.freeze({
|
|
341
|
+
core: CORE_PACKAGE_VERSION,
|
|
342
|
+
data: DATA_PACKAGE_VERSION,
|
|
343
|
+
compliance: COMPLIANCE_PACKAGE_VERSION,
|
|
344
|
+
}),
|
|
345
|
+
algorithmVersion: "diagnostics-1",
|
|
346
|
+
}),
|
|
347
|
+
),
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Verify an authentic compact completed run and bind completed artifact digests.
|
|
353
|
+
* Synchronous: source bytes were consumed by digestDiagnosticArtifactChunks already.
|
|
354
|
+
* This deliberately replays review/math and compares every identity code unit.
|
|
355
|
+
*/
|
|
356
|
+
export function createCompactDiagnosticRunIdentity(
|
|
357
|
+
input: CreateCompactDiagnosticRunIdentityInput,
|
|
358
|
+
): VerifiedCompactDiagnosticRunProvenance {
|
|
359
|
+
const snapshot = record(
|
|
360
|
+
input,
|
|
361
|
+
[
|
|
362
|
+
"completedRun",
|
|
363
|
+
"inputArtifacts",
|
|
364
|
+
"preparationArtifacts",
|
|
365
|
+
"preparationLineage",
|
|
366
|
+
],
|
|
367
|
+
"$",
|
|
368
|
+
);
|
|
369
|
+
const run = snapshot.completedRun;
|
|
370
|
+
try {
|
|
371
|
+
assertCompletedCompactMetricDiagnosticsRun(run);
|
|
372
|
+
} catch {
|
|
373
|
+
bad(
|
|
374
|
+
"completedRun must be an authentic completed compact diagnostic run",
|
|
375
|
+
"$.completedRun",
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
const inputArtifacts = artifacts(
|
|
379
|
+
snapshot.inputArtifacts,
|
|
380
|
+
"input",
|
|
381
|
+
"$.inputArtifacts",
|
|
382
|
+
);
|
|
383
|
+
const preparationArtifacts = artifacts(
|
|
384
|
+
snapshot.preparationArtifacts,
|
|
385
|
+
"preparation",
|
|
386
|
+
"$.preparationArtifacts",
|
|
387
|
+
);
|
|
388
|
+
const preparationLineage = lineage(snapshot.preparationLineage);
|
|
389
|
+
validateArtifactGraph(
|
|
390
|
+
run,
|
|
391
|
+
inputArtifacts,
|
|
392
|
+
preparationArtifacts,
|
|
393
|
+
preparationLineage,
|
|
394
|
+
);
|
|
395
|
+
rerunAndVerify(run);
|
|
396
|
+
const preparationFingerprint = getCompactPreparedDiagnosticDataFingerprint(
|
|
397
|
+
run.prepared,
|
|
398
|
+
);
|
|
399
|
+
const reviewFingerprint = getCompactDiagnosticReviewReceiptFingerprint(
|
|
400
|
+
run.review,
|
|
401
|
+
);
|
|
402
|
+
const manifestIdentityDocument = manifestDocument(
|
|
403
|
+
run,
|
|
404
|
+
inputArtifacts,
|
|
405
|
+
preparationArtifacts,
|
|
406
|
+
preparationLineage,
|
|
407
|
+
preparationFingerprint,
|
|
408
|
+
reviewFingerprint,
|
|
409
|
+
);
|
|
410
|
+
const resultIdentityDocument =
|
|
411
|
+
getCompactMetricDiagnosticsResultIdentityDocument(run.result);
|
|
412
|
+
const runFingerprint = fingerprintDiagnosticIdentity(
|
|
413
|
+
manifestIdentityDocument,
|
|
414
|
+
{ kind: "diagnostic-run", property: "manifest" },
|
|
415
|
+
);
|
|
416
|
+
const resultFingerprint = fingerprintDiagnosticIdentity(
|
|
417
|
+
resultIdentityDocument,
|
|
418
|
+
{ kind: "diagnostic-result", property: "result" },
|
|
419
|
+
);
|
|
420
|
+
const runResultFingerprint = `fnv1a64-jcs-v1:${canonicalFnv1a64({ identityVersion: 1, kind: "diagnostic-run-result", runFingerprint, resultFingerprint })}`;
|
|
421
|
+
const definition = run.prepared.definition;
|
|
422
|
+
const provenance = Object.freeze({
|
|
423
|
+
definition: Object.freeze({
|
|
424
|
+
definition: definition.definition,
|
|
425
|
+
identities: Object.freeze({
|
|
426
|
+
algorithm: "fnv1a64-jcs-v1" as const,
|
|
427
|
+
formulaById: Object.freeze({ ...definition.formulaFingerprints }),
|
|
428
|
+
calculationByInstanceId: Object.freeze({
|
|
429
|
+
...definition.calculationFingerprints,
|
|
430
|
+
}),
|
|
431
|
+
definition: definition.definitionIntegrity,
|
|
432
|
+
}),
|
|
433
|
+
}),
|
|
434
|
+
inputArtifacts,
|
|
435
|
+
preparationArtifacts,
|
|
436
|
+
preparationLineage,
|
|
437
|
+
preparationFingerprint,
|
|
438
|
+
reviewFingerprint,
|
|
439
|
+
manifestIdentityDocument,
|
|
440
|
+
resultIdentityDocument,
|
|
441
|
+
runFingerprint,
|
|
442
|
+
resultFingerprint,
|
|
443
|
+
runResultFingerprint,
|
|
444
|
+
}) as VerifiedCompactDiagnosticRunProvenance;
|
|
445
|
+
verified.set(provenance, run);
|
|
446
|
+
return provenance;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export function assertVerifiedCompactDiagnosticRunProvenance(
|
|
450
|
+
value: unknown,
|
|
451
|
+
): asserts value is VerifiedCompactDiagnosticRunProvenance {
|
|
452
|
+
if (value === null || typeof value !== "object" || !verified.has(value))
|
|
453
|
+
bad("Value is not authentic verified compact diagnostic provenance", "$");
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** Internal transport plumbing; deliberately not exported from the package index. */
|
|
457
|
+
export function getCompactDiagnosticRunOwner(
|
|
458
|
+
provenance: VerifiedCompactDiagnosticRunProvenance,
|
|
459
|
+
): CompletedCompactMetricDiagnosticsRun {
|
|
460
|
+
assertVerifiedCompactDiagnosticRunProvenance(provenance);
|
|
461
|
+
return verified.get(provenance)!;
|
|
462
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { ComplianceError } from "./errors.js";
|
|
2
|
+
import { diagnosticByteView } from "./diagnosticByteView.js";
|
|
3
|
+
import { consumeDiagnosticByteSource } from "./diagnosticByteSource.js";
|
|
4
|
+
|
|
5
|
+
// Transport granularity only: not a limit on total evidence or dataset size.
|
|
6
|
+
export const MAX_REPLAY_FRAME_BYTES = 131_072;
|
|
7
|
+
export const MAX_REPLAY_READ_BYTES = 131_072;
|
|
8
|
+
export const REPLAY_TEXT_UNITS = 16_384;
|
|
9
|
+
export type ReplayAtom = string | number | boolean | null;
|
|
10
|
+
export type ReplayFrame = readonly ReplayAtom[];
|
|
11
|
+
function invalid(message: string): never {
|
|
12
|
+
throw new ComplianceError("BAD_DIAGNOSTIC_RUN", message, "$.replayFrames");
|
|
13
|
+
}
|
|
14
|
+
function snapshotFrame(value: unknown): ReplayFrame {
|
|
15
|
+
if (!Array.isArray(value)) invalid("Replay frame must be an array");
|
|
16
|
+
const length = Object.getOwnPropertyDescriptor(value, "length")?.value;
|
|
17
|
+
if (!Number.isInteger(length) || length < 1 || length > 16)
|
|
18
|
+
invalid("Replay frame must be a nonempty flat array with at most 16 items");
|
|
19
|
+
const owned: ReplayAtom[] = [];
|
|
20
|
+
for (let index = 0; index < length; index++) {
|
|
21
|
+
const field = Object.getOwnPropertyDescriptor(value, String(index));
|
|
22
|
+
if (!field || !("value" in field))
|
|
23
|
+
invalid("Replay frames must contain indexed data properties");
|
|
24
|
+
const item: unknown = field.value;
|
|
25
|
+
if (item === null || typeof item === "boolean") {
|
|
26
|
+
owned.push(item);
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (typeof item === "number" && Number.isFinite(item)) {
|
|
30
|
+
owned.push(item);
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
// Enough for a base64-encoded 64 KiB artifact chunk. Higher-level protocol
|
|
34
|
+
// validates each event's arity, sequencing, and narrower field limits.
|
|
35
|
+
if (typeof item === "string" && item.length <= 87_384) {
|
|
36
|
+
owned.push(item);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
invalid("Replay frames contain only bounded JSON primitives");
|
|
40
|
+
}
|
|
41
|
+
return Object.freeze(owned);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Private transport codec; construction does not grant diagnostic authority. */
|
|
45
|
+
export async function* encodeReplayFrames(
|
|
46
|
+
frames: AsyncIterable<ReplayFrame> | Iterable<ReplayFrame>,
|
|
47
|
+
): AsyncGenerator<Uint8Array> {
|
|
48
|
+
const encoder = new TextEncoder();
|
|
49
|
+
for await (const frame of frames) {
|
|
50
|
+
const owned = snapshotFrame(frame);
|
|
51
|
+
const atoms: string[] = [];
|
|
52
|
+
let bytes = 3;
|
|
53
|
+
for (const item of owned) {
|
|
54
|
+
const text = JSON.stringify(item);
|
|
55
|
+
bytes += encoder.encode(text).byteLength + (atoms.length ? 1 : 0);
|
|
56
|
+
if (bytes > MAX_REPLAY_FRAME_BYTES) invalid("Replay frame exceeds its byte limit");
|
|
57
|
+
atoms.push(text);
|
|
58
|
+
}
|
|
59
|
+
yield encoder.encode(`[${atoms.join(",")}]\n`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Parse bounded flat frames, never a complete candidate audit/identity. */
|
|
64
|
+
export async function* decodeReplayFrames(
|
|
65
|
+
chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>,
|
|
66
|
+
): AsyncGenerator<ReplayFrame> {
|
|
67
|
+
const line = new Uint8Array(MAX_REPLAY_FRAME_BYTES);
|
|
68
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
69
|
+
let used = 0;
|
|
70
|
+
try {
|
|
71
|
+
for await (const chunk of consumeDiagnosticByteSource(chunks)) {
|
|
72
|
+
const view = diagnosticByteView(chunk);
|
|
73
|
+
if (view.byteLength > MAX_REPLAY_READ_BYTES)
|
|
74
|
+
invalid("Replay read chunk exceeds its transport limit; split input reads");
|
|
75
|
+
// Snapshot before yielding any frame: reused buffers cannot alter later
|
|
76
|
+
// frames in the same delivered chunk. This copy is always bounded.
|
|
77
|
+
const owned = new Uint8Array(view);
|
|
78
|
+
for (const byte of owned) {
|
|
79
|
+
if (byte === 10) {
|
|
80
|
+
if (used === 0) invalid("Empty replay frame");
|
|
81
|
+
let parsed: unknown;
|
|
82
|
+
try {
|
|
83
|
+
parsed = JSON.parse(decoder.decode(line.subarray(0, used)));
|
|
84
|
+
} catch {
|
|
85
|
+
invalid("Replay frame is not valid UTF-8 JSON");
|
|
86
|
+
}
|
|
87
|
+
used = 0;
|
|
88
|
+
yield snapshotFrame(parsed);
|
|
89
|
+
} else {
|
|
90
|
+
if (used >= MAX_REPLAY_FRAME_BYTES - 1) invalid("Replay frame exceeds its byte limit");
|
|
91
|
+
line[used++] = byte;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (used !== 0) invalid("Replay stream ended inside a frame");
|
|
96
|
+
} finally {
|
|
97
|
+
line.fill(0);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { isDiagnosticPlainRecord, isDiagnosticToken } from "@actuarial-ts/core";
|
|
2
|
+
import { ComplianceError } from "./errors.js";
|
|
3
|
+
import { MAX_REPLAY_FRAME_BYTES, type ReplayFrame } from "./diagnosticReplayFrames.js";
|
|
4
|
+
|
|
5
|
+
export const REPLAY_FORMAT = "diagnostic-replay";
|
|
6
|
+
export const REPLAY_VERSION = 1;
|
|
7
|
+
export const ARTIFACT_CHUNK_BYTES = 65_536;
|
|
8
|
+
|
|
9
|
+
export function badReplay(message: string): never {
|
|
10
|
+
throw new ComplianceError("BAD_DIAGNOSTIC_RUN", message, "$.replay");
|
|
11
|
+
}
|
|
12
|
+
export function mismatch(message: string): never {
|
|
13
|
+
throw new ComplianceError("DIAGNOSTIC_MISMATCH", message, "$.replay");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Snapshot host metadata once, without invoking accessors or caller methods. */
|
|
17
|
+
export function replayRecord(value: unknown, keys: readonly string[]): Record<string, unknown> {
|
|
18
|
+
if (!isDiagnosticPlainRecord(value)) badReplay("Expected a plain replay metadata object");
|
|
19
|
+
const result: Record<string, unknown> = Object.create(null);
|
|
20
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
21
|
+
if (typeof key !== "string" || !keys.includes(key)) badReplay("Unknown replay metadata field");
|
|
22
|
+
const field = Object.getOwnPropertyDescriptor(value, key);
|
|
23
|
+
if (!field || !("value" in field) || !field.enumerable)
|
|
24
|
+
badReplay("Replay metadata must contain enumerable data properties");
|
|
25
|
+
result[key] = field.value;
|
|
26
|
+
}
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
export function replayArray(value: unknown): unknown[] {
|
|
30
|
+
if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype)
|
|
31
|
+
badReplay("Expected a plain replay metadata array");
|
|
32
|
+
const length: unknown = Object.getOwnPropertyDescriptor(value, "length")?.value;
|
|
33
|
+
if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0)
|
|
34
|
+
badReplay("Invalid replay metadata array length");
|
|
35
|
+
for (const key of Reflect.ownKeys(value))
|
|
36
|
+
if (
|
|
37
|
+
key !== "length" &&
|
|
38
|
+
(typeof key !== "string" || !/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= length)
|
|
39
|
+
)
|
|
40
|
+
badReplay("Unexpected replay array property");
|
|
41
|
+
const result: unknown[] = [];
|
|
42
|
+
for (let index = 0; index < length; index++) {
|
|
43
|
+
const field = Object.getOwnPropertyDescriptor(value, String(index));
|
|
44
|
+
if (!field || !("value" in field) || !field.enumerable)
|
|
45
|
+
badReplay("Replay array has a hole or accessor");
|
|
46
|
+
result.push(field.value);
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
export function replayToken(value: unknown): string {
|
|
51
|
+
if (!isDiagnosticToken(value)) badReplay("Expected a nonempty replay token with valid Unicode");
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
export function replayLimit(value: unknown, label: string): number {
|
|
55
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
|
|
56
|
+
badReplay(`${label} must be a positive safe integer`);
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")!.get!;
|
|
61
|
+
const throwIfAborted = AbortSignal.prototype.throwIfAborted;
|
|
62
|
+
export function replayCancellation(signal: unknown): () => void {
|
|
63
|
+
if (signal === undefined) return () => {};
|
|
64
|
+
try {
|
|
65
|
+
signalAborted.call(signal);
|
|
66
|
+
} catch {
|
|
67
|
+
badReplay("Replay signal must be an AbortSignal");
|
|
68
|
+
}
|
|
69
|
+
return () => throwIfAborted.call(signal);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Exactly the writer's bounded canonical flat-frame bytes, including newline. */
|
|
73
|
+
export function replayFrameBytes(frame: ReplayFrame): Uint8Array {
|
|
74
|
+
const bytes = new TextEncoder().encode(`${JSON.stringify(frame)}\n`);
|
|
75
|
+
if (bytes.byteLength > MAX_REPLAY_FRAME_BYTES) badReplay("Replay frame exceeds its byte limit");
|
|
76
|
+
return bytes;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function encodeArtifactChunk(bytes: Uint8Array): string {
|
|
80
|
+
let binary = "";
|
|
81
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
82
|
+
return btoa(binary);
|
|
83
|
+
}
|
|
84
|
+
export function decodeArtifactChunk(value: unknown): Uint8Array {
|
|
85
|
+
if (
|
|
86
|
+
typeof value !== "string" ||
|
|
87
|
+
!value.length ||
|
|
88
|
+
value.length > 87_384 ||
|
|
89
|
+
value.length % 4 ||
|
|
90
|
+
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)
|
|
91
|
+
)
|
|
92
|
+
badReplay("Invalid bounded artifact base64 chunk");
|
|
93
|
+
const binary = atob(value);
|
|
94
|
+
if (binary.length > ARTIFACT_CHUNK_BYTES || btoa(binary) !== value)
|
|
95
|
+
badReplay("Artifact base64 must use canonical padding bits and bounded chunks");
|
|
96
|
+
const bytes = new Uint8Array(binary.length);
|
|
97
|
+
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
|
98
|
+
return bytes;
|
|
99
|
+
}
|