@actuarial-ts/core 0.5.0 → 0.6.1

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 (120) hide show
  1. package/README.md +65 -226
  2. package/dist/capping.d.ts.map +1 -1
  3. package/dist/capping.js +39 -6
  4. package/dist/capping.js.map +1 -1
  5. package/dist/casualtyDiagnostics.d.ts +19 -49
  6. package/dist/casualtyDiagnostics.d.ts.map +1 -1
  7. package/dist/casualtyDiagnostics.js +84 -116
  8. package/dist/casualtyDiagnostics.js.map +1 -1
  9. package/dist/diagnosticAggregation.d.ts +32 -0
  10. package/dist/diagnosticAggregation.d.ts.map +1 -0
  11. package/dist/diagnosticAggregation.js +73 -0
  12. package/dist/diagnosticAggregation.js.map +1 -0
  13. package/dist/diagnosticDefinitions.d.ts +289 -0
  14. package/dist/diagnosticDefinitions.d.ts.map +1 -0
  15. package/dist/diagnosticDefinitions.js +1688 -0
  16. package/dist/diagnosticDefinitions.js.map +1 -0
  17. package/dist/diagnosticDerivations.d.ts +35 -0
  18. package/dist/diagnosticDerivations.d.ts.map +1 -0
  19. package/dist/diagnosticDerivations.js +224 -0
  20. package/dist/diagnosticDerivations.js.map +1 -0
  21. package/dist/diagnosticExposure.d.ts +51 -0
  22. package/dist/diagnosticExposure.d.ts.map +1 -0
  23. package/dist/diagnosticExposure.js +273 -0
  24. package/dist/diagnosticExposure.js.map +1 -0
  25. package/dist/diagnosticExpressions.d.ts +56 -0
  26. package/dist/diagnosticExpressions.d.ts.map +1 -0
  27. package/dist/diagnosticExpressions.js +124 -0
  28. package/dist/diagnosticExpressions.js.map +1 -0
  29. package/dist/diagnosticFormulas.d.ts +198 -0
  30. package/dist/diagnosticFormulas.d.ts.map +1 -0
  31. package/dist/diagnosticFormulas.js +219 -0
  32. package/dist/diagnosticFormulas.js.map +1 -0
  33. package/dist/diagnosticIdentity.d.ts +251 -0
  34. package/dist/diagnosticIdentity.d.ts.map +1 -0
  35. package/dist/diagnosticIdentity.js +721 -0
  36. package/dist/diagnosticIdentity.js.map +1 -0
  37. package/dist/diagnosticOrdering.d.ts +8 -0
  38. package/dist/diagnosticOrdering.d.ts.map +1 -0
  39. package/dist/diagnosticOrdering.js +73 -0
  40. package/dist/diagnosticOrdering.js.map +1 -0
  41. package/dist/diagnosticPeriodAxis.d.ts +9 -0
  42. package/dist/diagnosticPeriodAxis.d.ts.map +1 -0
  43. package/dist/diagnosticPeriodAxis.js +69 -0
  44. package/dist/diagnosticPeriodAxis.js.map +1 -0
  45. package/dist/diagnosticPeriods.d.ts +15 -0
  46. package/dist/diagnosticPeriods.d.ts.map +1 -0
  47. package/dist/diagnosticPeriods.js +50 -0
  48. package/dist/diagnosticPeriods.js.map +1 -0
  49. package/dist/diagnosticPreparation.d.ts +131 -0
  50. package/dist/diagnosticPreparation.d.ts.map +1 -0
  51. package/dist/diagnosticPreparation.js +1539 -0
  52. package/dist/diagnosticPreparation.js.map +1 -0
  53. package/dist/diagnosticReview.d.ts +66 -0
  54. package/dist/diagnosticReview.d.ts.map +1 -0
  55. package/dist/diagnosticReview.js +490 -0
  56. package/dist/diagnosticReview.js.map +1 -0
  57. package/dist/diagnosticRules.d.ts +32 -0
  58. package/dist/diagnosticRules.d.ts.map +1 -0
  59. package/dist/diagnosticRules.js +32 -0
  60. package/dist/diagnosticRules.js.map +1 -0
  61. package/dist/diagnosticRunner.d.ts +86 -0
  62. package/dist/diagnosticRunner.d.ts.map +1 -0
  63. package/dist/diagnosticRunner.js +703 -0
  64. package/dist/diagnosticRunner.js.map +1 -0
  65. package/dist/diagnosticRuntime.d.ts +26 -0
  66. package/dist/diagnosticRuntime.d.ts.map +1 -0
  67. package/dist/diagnosticRuntime.js +243 -0
  68. package/dist/diagnosticRuntime.js.map +1 -0
  69. package/dist/diagnosticSourceOrdering.d.ts +6 -0
  70. package/dist/diagnosticSourceOrdering.d.ts.map +1 -0
  71. package/dist/diagnosticSourceOrdering.js +38 -0
  72. package/dist/diagnosticSourceOrdering.js.map +1 -0
  73. package/dist/index.d.ts +28 -1
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +16 -1
  76. package/dist/index.js.map +1 -1
  77. package/dist/mack.d.ts +4 -0
  78. package/dist/mack.d.ts.map +1 -1
  79. package/dist/mack.js +32 -4
  80. package/dist/mack.js.map +1 -1
  81. package/dist/triangle.d.ts.map +1 -1
  82. package/dist/triangle.js +59 -9
  83. package/dist/triangle.js.map +1 -1
  84. package/dist/types.d.ts +21 -0
  85. package/dist/types.d.ts.map +1 -1
  86. package/dist/types.js +128 -0
  87. package/dist/types.js.map +1 -1
  88. package/dist/version.d.ts +3 -0
  89. package/dist/version.d.ts.map +1 -0
  90. package/dist/version.js +3 -0
  91. package/dist/version.js.map +1 -0
  92. package/package.json +4 -3
  93. package/src/capping.ts +109 -18
  94. package/src/casualtyDiagnostics.ts +79 -189
  95. package/src/diagnosticAggregation.ts +128 -0
  96. package/src/diagnosticDefinitions.ts +3624 -0
  97. package/src/diagnosticDerivations.ts +321 -0
  98. package/src/diagnosticExposure.ts +482 -0
  99. package/src/diagnosticExpressions.ts +255 -0
  100. package/src/diagnosticFormulas.ts +350 -0
  101. package/src/diagnosticIdentity.ts +1267 -0
  102. package/src/diagnosticOrdering.ts +106 -0
  103. package/src/diagnosticPeriodAxis.ts +92 -0
  104. package/src/diagnosticPeriods.ts +102 -0
  105. package/src/diagnosticPreparation.ts +2475 -0
  106. package/src/diagnosticReview.ts +897 -0
  107. package/src/diagnosticRules.ts +69 -0
  108. package/src/diagnosticRunner.ts +1114 -0
  109. package/src/diagnosticRuntime.ts +264 -0
  110. package/src/diagnosticSourceOrdering.ts +50 -0
  111. package/src/index.ts +184 -1
  112. package/src/mack.ts +72 -9
  113. package/src/triangle.ts +103 -13
  114. package/src/types.ts +196 -0
  115. package/src/version.ts +2 -0
  116. package/dist/metricDiagnostics.d.ts +0 -212
  117. package/dist/metricDiagnostics.d.ts.map +0 -1
  118. package/dist/metricDiagnostics.js +0 -627
  119. package/dist/metricDiagnostics.js.map +0 -1
  120. package/src/metricDiagnostics.ts +0 -876
@@ -0,0 +1,897 @@
1
+ import {
2
+ getCompiledDiagnosticDefinitionInternals,
3
+ type DiagnosticControlTotalProjection,
4
+ type DiagnosticDeepReadonly,
5
+ type DiagnosticReviewFilter,
6
+ type DiagnosticReviewRule,
7
+ type DiagnosticSourceLocation,
8
+ } from "./diagnosticDefinitions.js";
9
+ import type { NormalizedDiagnosticReviewFilterIdentity } from "./diagnosticIdentity.js";
10
+ import { canonicalJson } from "./canonical.js";
11
+ import { normalizeDiagnosticPeriod } from "./diagnosticPeriods.js";
12
+ import {
13
+ evaluateDiagnosticMeasureExpression,
14
+ type FinalizedDiagnosticMeasure,
15
+ } from "./diagnosticFormulas.js";
16
+ import {
17
+ assertPreparedDiagnosticData,
18
+ type PreparedDiagnosticData,
19
+ } from "./diagnosticPreparation.js";
20
+ import {
21
+ classifyDiagnosticComparison,
22
+ diagnosticPredicateMatches,
23
+ type DiagnosticExpressionOverflow,
24
+ type DiagnosticRuleNotEvaluatedReason,
25
+ } from "./diagnosticRules.js";
26
+ import { finalizeDiagnosticContributions } from "./diagnosticAggregation.js";
27
+ import {
28
+ compareDiagnosticSourceLocations,
29
+ normalizeDiagnosticSourceLocations,
30
+ } from "./diagnosticSourceOrdering.js";
31
+
32
+ export interface DiagnosticReviewCoordinate {
33
+ readonly sourceGroup: string;
34
+ readonly origin: string;
35
+ readonly valuation: string;
36
+ readonly developmentAge: number;
37
+ readonly ageUnit: string;
38
+ }
39
+
40
+ export type DiagnosticCellReviewScope = {
41
+ readonly kind: "cell";
42
+ readonly cell: DiagnosticReviewCoordinate;
43
+ readonly sources: readonly DiagnosticSourceLocation[];
44
+ };
45
+ export type DiagnosticValuationPairReviewScope = {
46
+ readonly kind: "valuation-pair";
47
+ readonly previous: DiagnosticReviewCoordinate;
48
+ readonly current: DiagnosticReviewCoordinate;
49
+ readonly sources: readonly DiagnosticSourceLocation[];
50
+ };
51
+ export type DiagnosticControlTotalReviewScope = {
52
+ readonly kind: "control-total";
53
+ readonly projection: DiagnosticDeepReadonly<DiagnosticControlTotalProjection>;
54
+ readonly filter: NormalizedDiagnosticReviewFilterIdentity | null;
55
+ readonly selectedCellCount: number;
56
+ readonly selectedContributionCount: number;
57
+ readonly sources: readonly DiagnosticSourceLocation[];
58
+ };
59
+
60
+ export type DiagnosticReviewEvaluationScope =
61
+ | DiagnosticCellReviewScope
62
+ | DiagnosticValuationPairReviewScope
63
+ | DiagnosticControlTotalReviewScope;
64
+
65
+ export interface DiagnosticReviewExpressionOverflow
66
+ extends DiagnosticExpressionOverflow {
67
+ readonly coordinate: DiagnosticReviewCoordinate | null;
68
+ }
69
+
70
+ export interface DiagnosticReviewRuleEvaluationBase {
71
+ readonly ruleId: string;
72
+ readonly ruleKind: DiagnosticReviewRule["kind"];
73
+ readonly status: "pass" | "triggered" | "not-evaluated";
74
+ readonly severity: "warning" | "fail";
75
+ readonly triggerReason:
76
+ | "predicate"
77
+ | "missing-input"
78
+ | "aggregation-overflow"
79
+ | "expression-overflow"
80
+ | "tolerance-overflow"
81
+ | null;
82
+ readonly left: number | null;
83
+ readonly right: number | null;
84
+ readonly relation: "less" | "equal" | "greater" | null;
85
+ readonly notEvaluatedReasons: readonly DiagnosticRuleNotEvaluatedReason[];
86
+ readonly expressionOverflows: readonly DiagnosticReviewExpressionOverflow[];
87
+ readonly scope: DiagnosticReviewEvaluationScope;
88
+ }
89
+
90
+ export type DiagnosticReviewRuleEvaluation =
91
+ | (DiagnosticReviewRuleEvaluationBase & {
92
+ readonly ruleKind: "compare" | "reconcile";
93
+ readonly scope: DiagnosticCellReviewScope;
94
+ })
95
+ | (DiagnosticReviewRuleEvaluationBase & {
96
+ readonly ruleKind: "monotonic";
97
+ readonly scope: DiagnosticValuationPairReviewScope;
98
+ })
99
+ | (DiagnosticReviewRuleEvaluationBase & {
100
+ readonly ruleKind: "layer-order";
101
+ readonly scope: DiagnosticCellReviewScope;
102
+ readonly comparability: Extract<
103
+ DiagnosticReviewRule,
104
+ { kind: "layer-order" }
105
+ >["comparability"];
106
+ })
107
+ | (DiagnosticReviewRuleEvaluationBase & {
108
+ readonly ruleKind: "control-total";
109
+ readonly scope: DiagnosticControlTotalReviewScope;
110
+ });
111
+
112
+ interface EvaluatedOperand {
113
+ readonly value: number | null;
114
+ readonly reasons: readonly DiagnosticRuleNotEvaluatedReason[];
115
+ readonly overflows: readonly DiagnosticReviewExpressionOverflow[];
116
+ readonly sources: readonly DiagnosticSourceLocation[];
117
+ }
118
+
119
+ const REASON_ORDER: readonly DiagnosticRuleNotEvaluatedReason[] = [
120
+ "missing",
121
+ "imputed",
122
+ "non-finite",
123
+ "structural-ambiguity",
124
+ "aggregation-overflow",
125
+ "expression-overflow",
126
+ "tolerance-overflow",
127
+ ];
128
+
129
+ function codeUnit(left: string, right: string): number {
130
+ return left < right ? -1 : left > right ? 1 : 0;
131
+ }
132
+
133
+ function uniqueReasons(
134
+ values: readonly DiagnosticRuleNotEvaluatedReason[],
135
+ ): DiagnosticRuleNotEvaluatedReason[] {
136
+ return REASON_ORDER.filter((reason) => values.includes(reason));
137
+ }
138
+
139
+ function uniqueSources(
140
+ values: readonly DiagnosticSourceLocation[],
141
+ ): DiagnosticSourceLocation[] {
142
+ return normalizeDiagnosticSourceLocations(values);
143
+ }
144
+
145
+ function expressionMeasureIds(
146
+ expression: import("./diagnosticExpressions.js").DiagnosticMeasureExpression,
147
+ ): string[] {
148
+ if (expression.op === "measure") return [expression.measureId];
149
+ return [
150
+ ...new Set(
151
+ (expression.op === "add"
152
+ ? expression.terms
153
+ : [expression.left, expression.right]
154
+ ).flatMap(expressionMeasureIds),
155
+ ),
156
+ ].sort(codeUnit);
157
+ }
158
+
159
+ function expressionLeafPaths(
160
+ expression: import("./diagnosticExpressions.js").DiagnosticMeasureExpression,
161
+ path: string,
162
+ ): readonly { readonly measureId: string; readonly expressionPath: string }[] {
163
+ if (expression.op === "measure")
164
+ return [{ measureId: expression.measureId, expressionPath: path }];
165
+ if (expression.op === "add")
166
+ return expression.terms.flatMap((term, index) =>
167
+ expressionLeafPaths(term, `${path}/terms/${index}`),
168
+ );
169
+ return [
170
+ ...expressionLeafPaths(expression.left, `${path}/left`),
171
+ ...expressionLeafPaths(expression.right, `${path}/right`),
172
+ ];
173
+ }
174
+
175
+ function states(
176
+ prepared: PreparedDiagnosticData,
177
+ cell: PreparedDiagnosticData["cells"][number],
178
+ ): Record<string, FinalizedDiagnosticMeasure> {
179
+ const internals = getCompiledDiagnosticDefinitionInternals(
180
+ prepared.definition,
181
+ );
182
+ return Object.fromEntries(
183
+ Object.entries(cell.components).map(([id, stats]) => {
184
+ const measure = internals.measuresById.get(id)!;
185
+ const readiness: DiagnosticRuleNotEvaluatedReason[] = [];
186
+ if (stats.missing)
187
+ readiness.push(stats.imputedZero ? "imputed" : "missing");
188
+ if (stats.nonFinite) readiness.push("non-finite");
189
+ if (stats.structural) readiness.push("structural-ambiguity");
190
+ if (stats.sum === null && !stats.nonFinite && !stats.structural)
191
+ readiness.push("aggregation-overflow");
192
+ return [
193
+ id,
194
+ {
195
+ quantity: {
196
+ kind: measure.kind,
197
+ unit: measure.unit,
198
+ ...(measure.basisId ? { basisId: measure.basisId } : {}),
199
+ ...(measure.countPopulationId
200
+ ? { countPopulationId: measure.countPopulationId }
201
+ : {}),
202
+ ...(measure.exposureBasisId
203
+ ? { exposureBasisId: measure.exposureBasisId }
204
+ : {}),
205
+ value: stats.value,
206
+ },
207
+ stats,
208
+ readiness,
209
+ sources: cellSources(cell, [id]),
210
+ },
211
+ ];
212
+ }),
213
+ );
214
+ }
215
+
216
+ function coordinate(
217
+ cell: PreparedDiagnosticData["cells"][number],
218
+ ): DiagnosticReviewCoordinate {
219
+ return {
220
+ sourceGroup: cell.sourceGroup,
221
+ origin: cell.origin,
222
+ valuation: cell.valuation,
223
+ developmentAge: cell.developmentAge,
224
+ ageUnit: cell.ageUnit,
225
+ };
226
+ }
227
+
228
+ function coordinateFromLabels(
229
+ prepared: PreparedDiagnosticData,
230
+ sourceGroup: string,
231
+ originLabel: string,
232
+ valuationLabel: string,
233
+ ): DiagnosticReviewCoordinate {
234
+ const origin = normalizeDiagnosticPeriod(
235
+ prepared.definition,
236
+ "origin",
237
+ originLabel,
238
+ );
239
+ const valuation = normalizeDiagnosticPeriod(
240
+ prepared.definition,
241
+ "valuation",
242
+ valuationLabel,
243
+ );
244
+ return {
245
+ sourceGroup,
246
+ origin: origin.label,
247
+ valuation: valuation.label,
248
+ developmentAge:
249
+ valuation.coordinate -
250
+ origin.coordinate +
251
+ prepared.definition.definition.periodAxis.ageOffset,
252
+ ageUnit: prepared.definition.definition.periodAxis.ageUnit,
253
+ };
254
+ }
255
+
256
+ function cellSources(
257
+ cell: PreparedDiagnosticData["cells"][number],
258
+ measureIds?: readonly string[],
259
+ ): DiagnosticSourceLocation[] {
260
+ const ids = measureIds ?? Object.keys(cell.contributions);
261
+ return uniqueSources(
262
+ ids.flatMap((measureId) => [
263
+ ...(cell.contributions[measureId] ?? []).flatMap(
264
+ (contribution) => contribution.sources,
265
+ ),
266
+ ...(cell.structuralBlockers[measureId] ?? []).flatMap(
267
+ (blocker) => blocker.sources,
268
+ ),
269
+ ]),
270
+ );
271
+ }
272
+
273
+ function cellSourcesForSelection(
274
+ cells: readonly PreparedDiagnosticData["cells"][number][],
275
+ measureId: string,
276
+ ): DiagnosticSourceLocation[] {
277
+ return uniqueSources(
278
+ cells.flatMap((cell) => [
279
+ ...(cell.contributions[measureId] ?? []).flatMap(
280
+ (contribution) => contribution.sources,
281
+ ),
282
+ ...(cell.structuralBlockers[measureId] ?? []).flatMap(
283
+ (blocker) => blocker.sources,
284
+ ),
285
+ ]),
286
+ );
287
+ }
288
+
289
+ function evaluateExpression(
290
+ prepared: PreparedDiagnosticData,
291
+ cell: PreparedDiagnosticData["cells"][number],
292
+ expression: import("./diagnosticExpressions.js").DiagnosticMeasureExpression,
293
+ path: string,
294
+ ): EvaluatedOperand {
295
+ const result = evaluateDiagnosticMeasureExpression(
296
+ expression,
297
+ states(prepared, cell),
298
+ path,
299
+ );
300
+ const sources = cellSources(cell, expressionMeasureIds(expression));
301
+ return {
302
+ value: result.value,
303
+ reasons: result.reasons,
304
+ overflows: result.overflows.map((overflow) => ({
305
+ ...overflow,
306
+ coordinate: coordinate(cell),
307
+ sources,
308
+ })),
309
+ sources,
310
+ };
311
+ }
312
+
313
+ function constant(value: number): EvaluatedOperand {
314
+ return { value, reasons: [], overflows: [], sources: [] };
315
+ }
316
+
317
+ function evaluation(
318
+ prepared: PreparedDiagnosticData,
319
+ rule: DiagnosticReviewRule,
320
+ scope: DiagnosticReviewEvaluationScope,
321
+ left: EvaluatedOperand,
322
+ right: EvaluatedOperand,
323
+ passes: (relation: "less" | "equal" | "greater") => boolean,
324
+ extraReasons: readonly DiagnosticRuleNotEvaluatedReason[] = [],
325
+ ): DiagnosticReviewRuleEvaluation {
326
+ const expressionOverflows = [
327
+ ...new Map(
328
+ [...left.overflows, ...right.overflows].map((item) => [
329
+ canonicalJson(item),
330
+ item,
331
+ ]),
332
+ ).values(),
333
+ ].sort((a, b) => {
334
+ const path = codeUnit(a.expressionPath, b.expressionPath);
335
+ if (path !== 0) return path;
336
+ if (a.coordinate === null) return b.coordinate === null ? 0 : 1;
337
+ if (b.coordinate === null) return -1;
338
+ const coordinate =
339
+ codeUnit(a.coordinate.sourceGroup, b.coordinate.sourceGroup) ||
340
+ normalizeDiagnosticPeriod(
341
+ prepared.definition,
342
+ "origin",
343
+ a.coordinate.origin,
344
+ ).coordinate -
345
+ normalizeDiagnosticPeriod(
346
+ prepared.definition,
347
+ "origin",
348
+ b.coordinate.origin,
349
+ ).coordinate ||
350
+ normalizeDiagnosticPeriod(
351
+ prepared.definition,
352
+ "valuation",
353
+ a.coordinate.valuation,
354
+ ).coordinate -
355
+ normalizeDiagnosticPeriod(
356
+ prepared.definition,
357
+ "valuation",
358
+ b.coordinate.valuation,
359
+ ).coordinate ||
360
+ codeUnit(a.coordinate.origin, b.coordinate.origin) ||
361
+ codeUnit(a.coordinate.valuation, b.coordinate.valuation);
362
+ if (coordinate !== 0) return coordinate;
363
+ for (
364
+ let index = 0;
365
+ index < Math.min(a.sources.length, b.sources.length);
366
+ index++
367
+ ) {
368
+ const source = compareDiagnosticSourceLocations(
369
+ a.sources[index]!,
370
+ b.sources[index]!,
371
+ );
372
+ if (source !== 0) return source;
373
+ }
374
+ return a.sources.length - b.sources.length;
375
+ });
376
+ const reasons = uniqueReasons([
377
+ ...left.reasons,
378
+ ...right.reasons,
379
+ ...extraReasons,
380
+ ...(expressionOverflows.length > 0 ? ["expression-overflow" as const] : []),
381
+ ...((left.value === null || right.value === null) &&
382
+ left.reasons.length === 0 &&
383
+ right.reasons.length === 0 &&
384
+ expressionOverflows.length === 0
385
+ ? ["missing" as const]
386
+ : []),
387
+ ]);
388
+ const missingReason = (): DiagnosticReviewRuleEvaluation["triggerReason"] => {
389
+ if (
390
+ reasons.some((reason) =>
391
+ ["missing", "imputed", "non-finite", "structural-ambiguity"].includes(
392
+ reason,
393
+ ),
394
+ )
395
+ )
396
+ return "missing-input";
397
+ if (reasons.includes("aggregation-overflow")) return "aggregation-overflow";
398
+ if (reasons.includes("expression-overflow")) return "expression-overflow";
399
+ if (reasons.includes("tolerance-overflow")) return "tolerance-overflow";
400
+ return "missing-input";
401
+ };
402
+ const result = (
403
+ value: Omit<
404
+ DiagnosticReviewRuleEvaluationBase,
405
+ "ruleId" | "ruleKind" | "severity" | "scope"
406
+ >,
407
+ ): DiagnosticReviewRuleEvaluation =>
408
+ ({
409
+ ruleId: rule.id,
410
+ ruleKind: rule.kind,
411
+ severity: rule.severity,
412
+ scope,
413
+ ...value,
414
+ ...(rule.kind === "layer-order"
415
+ ? { comparability: rule.comparability }
416
+ : {}),
417
+ }) as DiagnosticReviewRuleEvaluation;
418
+ if (reasons.length > 0)
419
+ return result({
420
+ status: rule.missingInput === "finding" ? "triggered" : "not-evaluated",
421
+ triggerReason: rule.missingInput === "finding" ? missingReason() : null,
422
+ left: left.value,
423
+ right: right.value,
424
+ relation: null,
425
+ notEvaluatedReasons: reasons,
426
+ expressionOverflows,
427
+ });
428
+ const compared = classifyDiagnosticComparison(
429
+ left.value,
430
+ right.value,
431
+ rule.tolerance,
432
+ );
433
+ if (compared.status === "not-evaluated")
434
+ return result({
435
+ status: rule.missingInput === "finding" ? "triggered" : "not-evaluated",
436
+ triggerReason:
437
+ rule.missingInput === "finding"
438
+ ? compared.reason === "tolerance-overflow"
439
+ ? "tolerance-overflow"
440
+ : "missing-input"
441
+ : null,
442
+ left: left.value,
443
+ right: right.value,
444
+ relation: null,
445
+ notEvaluatedReasons: [compared.reason],
446
+ expressionOverflows: [],
447
+ });
448
+ const pass = passes(compared.relation);
449
+ return result({
450
+ status: pass ? "pass" : "triggered",
451
+ triggerReason: pass ? null : "predicate",
452
+ left: left.value,
453
+ right: right.value,
454
+ relation: compared.relation,
455
+ notEvaluatedReasons: [],
456
+ expressionOverflows: [],
457
+ });
458
+ }
459
+
460
+ function filterCells(
461
+ prepared: PreparedDiagnosticData,
462
+ filter: DiagnosticReviewFilter | null | undefined,
463
+ ): readonly PreparedDiagnosticData["cells"][number][] {
464
+ if (!filter) return prepared.cells;
465
+ const originFrom =
466
+ filter.originFrom == null
467
+ ? null
468
+ : normalizeDiagnosticPeriod(
469
+ prepared.definition,
470
+ "origin",
471
+ filter.originFrom,
472
+ ).coordinate;
473
+ const originThrough =
474
+ filter.originThrough == null
475
+ ? null
476
+ : normalizeDiagnosticPeriod(
477
+ prepared.definition,
478
+ "origin",
479
+ filter.originThrough,
480
+ ).coordinate;
481
+ const valuationFrom =
482
+ filter.valuationFrom == null
483
+ ? null
484
+ : normalizeDiagnosticPeriod(
485
+ prepared.definition,
486
+ "valuation",
487
+ filter.valuationFrom,
488
+ ).coordinate;
489
+ const valuationThrough =
490
+ filter.valuationThrough == null
491
+ ? null
492
+ : normalizeDiagnosticPeriod(
493
+ prepared.definition,
494
+ "valuation",
495
+ filter.valuationThrough,
496
+ ).coordinate;
497
+ return prepared.cells.filter((cell) => {
498
+ const origin = normalizeDiagnosticPeriod(
499
+ prepared.definition,
500
+ "origin",
501
+ cell.origin,
502
+ ).coordinate;
503
+ const valuation = normalizeDiagnosticPeriod(
504
+ prepared.definition,
505
+ "valuation",
506
+ cell.valuation,
507
+ ).coordinate;
508
+ return (
509
+ (filter.sourceGroups == null ||
510
+ filter.sourceGroups.includes(cell.sourceGroup)) &&
511
+ (filter.origins == null || filter.origins.includes(cell.origin)) &&
512
+ (originFrom === null || origin >= originFrom) &&
513
+ (originThrough === null || origin <= originThrough) &&
514
+ (filter.valuations == null ||
515
+ filter.valuations.includes(cell.valuation)) &&
516
+ (valuationFrom === null || valuation >= valuationFrom) &&
517
+ (valuationThrough === null || valuation <= valuationThrough) &&
518
+ (filter.minDevelopmentAge == null ||
519
+ cell.developmentAge >= filter.minDevelopmentAge) &&
520
+ (filter.maxDevelopmentAge == null ||
521
+ cell.developmentAge <= filter.maxDevelopmentAge)
522
+ );
523
+ });
524
+ }
525
+
526
+ function projectedCells(
527
+ prepared: PreparedDiagnosticData,
528
+ rule: Extract<DiagnosticReviewRule, { kind: "control-total" }>,
529
+ ): readonly PreparedDiagnosticData["cells"][number][] {
530
+ const selected = filterCells(prepared, rule.filter);
531
+ if (rule.projection.kind === "all-cells") return selected;
532
+ if (rule.projection.kind === "valuation") {
533
+ const valuation = normalizeDiagnosticPeriod(
534
+ prepared.definition,
535
+ "valuation",
536
+ rule.projection.valuation,
537
+ ).label;
538
+ return selected.filter((cell) => cell.valuation === valuation);
539
+ }
540
+ const latest = new Map<string, PreparedDiagnosticData["cells"][number]>();
541
+ for (const cell of selected) {
542
+ const key = canonicalJson([cell.sourceGroup, cell.origin]);
543
+ const previous = latest.get(key);
544
+ if (!previous || cell.developmentAge > previous.developmentAge)
545
+ latest.set(key, cell);
546
+ }
547
+ return [...latest.values()].sort(
548
+ (left, right) =>
549
+ codeUnit(left.sourceGroup, right.sourceGroup) ||
550
+ codeUnit(left.origin, right.origin),
551
+ );
552
+ }
553
+
554
+ /** Evaluates definition-owned semantic review rules over authenticated prepared cells. */
555
+ export function evaluateDiagnosticReviewRules(
556
+ prepared: PreparedDiagnosticData,
557
+ ): readonly DiagnosticReviewRuleEvaluation[] {
558
+ assertPreparedDiagnosticData(prepared);
559
+ const results: DiagnosticReviewRuleEvaluation[] = [];
560
+ for (const [ruleIndex, rule] of (
561
+ prepared.definition.definition
562
+ .reviewRules as unknown as readonly DiagnosticReviewRule[]
563
+ ).entries()) {
564
+ const basePath = `/reviewRules/${ruleIndex}`;
565
+ if (rule.kind === "control-total") {
566
+ const cells = projectedCells(prepared, rule);
567
+ const internals = getCompiledDiagnosticDefinitionInternals(
568
+ prepared.definition,
569
+ );
570
+ const measureIds = expressionMeasureIds(rule.expression);
571
+ const sourceByMeasure = Object.fromEntries(
572
+ measureIds.map((measureId) => [
573
+ measureId,
574
+ cellSourcesForSelection(cells, measureId),
575
+ ]),
576
+ );
577
+ const globalStates: Record<string, FinalizedDiagnosticMeasure> =
578
+ Object.create(null);
579
+ const leaves = expressionLeafPaths(
580
+ rule.expression,
581
+ `/reviewRules/${ruleIndex}/expression`,
582
+ );
583
+ for (const measureId of measureIds) {
584
+ const measure = internals.measuresById.get(measureId)!;
585
+ const contributions = cells.flatMap(
586
+ (cell) => cell.contributions[measureId] ?? [],
587
+ );
588
+ const blockers = [
589
+ ...new Map(
590
+ cells
591
+ .flatMap((cell) => cell.structuralBlockers[measureId] ?? [])
592
+ .map((blocker) => [canonicalJson(blocker), blocker]),
593
+ ).entries(),
594
+ ]
595
+ .sort(([left], [right]) => codeUnit(left, right))
596
+ .map(([, blocker]) => blocker);
597
+ const stats = finalizeDiagnosticContributions(
598
+ contributions,
599
+ measure.missing,
600
+ blockers,
601
+ );
602
+ const sourceCellOverflow = cells.some((cell) => {
603
+ const component = cell.components[measureId];
604
+ return (
605
+ component !== undefined &&
606
+ component.sum === null &&
607
+ component.nonFinite === 0 &&
608
+ component.structural === 0
609
+ );
610
+ });
611
+ const selectionOverflow =
612
+ stats.sum === null && stats.nonFinite === 0 && stats.structural === 0;
613
+ const emptySelection = cells.length === 0;
614
+ const expressionOverflows =
615
+ selectionOverflow && !sourceCellOverflow
616
+ ? leaves
617
+ .filter((leaf) => leaf.measureId === measureId)
618
+ .map((leaf) => ({
619
+ expressionPath: leaf.expressionPath,
620
+ sources: sourceByMeasure[measureId]!,
621
+ }))
622
+ : [];
623
+ const reasons: DiagnosticRuleNotEvaluatedReason[] = [];
624
+ if (emptySelection || stats.missing)
625
+ reasons.push(stats.imputedZero ? "imputed" : "missing");
626
+ if (stats.nonFinite) reasons.push("non-finite");
627
+ if (stats.structural) reasons.push("structural-ambiguity");
628
+ if (sourceCellOverflow) reasons.push("aggregation-overflow");
629
+ else if (selectionOverflow) reasons.push("expression-overflow");
630
+ globalStates[measureId] = {
631
+ quantity: {
632
+ kind: measure.kind,
633
+ unit: measure.unit,
634
+ ...(measure.basisId ? { basisId: measure.basisId } : {}),
635
+ ...(measure.countPopulationId
636
+ ? { countPopulationId: measure.countPopulationId }
637
+ : {}),
638
+ ...(measure.exposureBasisId
639
+ ? { exposureBasisId: measure.exposureBasisId }
640
+ : {}),
641
+ value:
642
+ emptySelection || sourceCellOverflow || selectionOverflow
643
+ ? null
644
+ : stats.value,
645
+ },
646
+ stats,
647
+ readiness: reasons,
648
+ expressionOverflows,
649
+ sources: sourceByMeasure[measureId],
650
+ };
651
+ }
652
+ const evaluated = evaluateDiagnosticMeasureExpression(
653
+ rule.expression,
654
+ globalStates,
655
+ `/reviewRules/${ruleIndex}/expression`,
656
+ );
657
+ const sources = uniqueSources(
658
+ measureIds.flatMap((measureId) => sourceByMeasure[measureId] ?? []),
659
+ );
660
+ const left: EvaluatedOperand = {
661
+ value: evaluated.value,
662
+ reasons: evaluated.reasons,
663
+ overflows: evaluated.overflows.map((overflow) => ({
664
+ ...overflow,
665
+ coordinate: null,
666
+ sources: overflow.sources.length > 0 ? overflow.sources : sources,
667
+ })),
668
+ sources,
669
+ };
670
+ const scope: DiagnosticReviewEvaluationScope = {
671
+ kind: "control-total",
672
+ projection: rule.projection,
673
+ filter: (rule.filter ??
674
+ null) as NormalizedDiagnosticReviewFilterIdentity | null,
675
+ selectedCellCount: cells.length,
676
+ selectedContributionCount: cells.reduce(
677
+ (sum, cell) =>
678
+ sum +
679
+ measureIds.reduce(
680
+ (count, measureId) =>
681
+ count + (cell.contributions[measureId]?.length ?? 0),
682
+ 0,
683
+ ),
684
+ 0,
685
+ ),
686
+ sources,
687
+ };
688
+ results.push(
689
+ evaluation(
690
+ prepared,
691
+ rule,
692
+ scope,
693
+ left,
694
+ constant(rule.expected),
695
+ (relation) => relation === "equal",
696
+ ),
697
+ );
698
+ continue;
699
+ }
700
+ if (rule.kind === "monotonic") {
701
+ const groups = new Map<string, Set<string>>();
702
+ for (const cell of prepared.cells) {
703
+ const key = canonicalJson([cell.sourceGroup, cell.origin]);
704
+ const values = groups.get(key) ?? new Set<string>();
705
+ values.add(cell.valuation);
706
+ groups.set(key, values);
707
+ }
708
+ for (const expected of prepared.expectedCells) {
709
+ const key = canonicalJson([expected.sourceGroup, expected.origin]);
710
+ const values = groups.get(key) ?? new Set<string>();
711
+ values.add(expected.valuation);
712
+ groups.set(key, values);
713
+ }
714
+ for (const [key, valuations] of [...groups.entries()].sort(
715
+ ([left], [right]) => codeUnit(left, right),
716
+ )) {
717
+ const [sourceGroup, origin] = JSON.parse(key) as [string, string];
718
+ const sorted = [...valuations].sort(
719
+ (left, right) =>
720
+ normalizeDiagnosticPeriod(prepared.definition, "valuation", left)
721
+ .coordinate -
722
+ normalizeDiagnosticPeriod(prepared.definition, "valuation", right)
723
+ .coordinate || codeUnit(left, right),
724
+ );
725
+ for (let index = 1; index < sorted.length; index++) {
726
+ const previousValuation = sorted[index - 1]!;
727
+ const currentValuation = sorted[index]!;
728
+ const previous = prepared.cells.find(
729
+ (cell) =>
730
+ cell.sourceGroup === sourceGroup &&
731
+ cell.origin === origin &&
732
+ cell.valuation === previousValuation,
733
+ );
734
+ const current = prepared.cells.find(
735
+ (cell) =>
736
+ cell.sourceGroup === sourceGroup &&
737
+ cell.origin === origin &&
738
+ cell.valuation === currentValuation,
739
+ );
740
+ const expectedSources = (valuation: string) =>
741
+ prepared.expectedCells
742
+ .filter(
743
+ (cell) =>
744
+ cell.sourceGroup === sourceGroup &&
745
+ cell.origin === origin &&
746
+ cell.valuation === valuation,
747
+ )
748
+ .flatMap((cell) => (cell.source ? [cell.source] : []));
749
+ const left = previous
750
+ ? evaluateExpression(
751
+ prepared,
752
+ previous,
753
+ rule.expression,
754
+ `${basePath}/expression`,
755
+ )
756
+ : {
757
+ value: null,
758
+ reasons: ["missing" as const],
759
+ overflows: [],
760
+ sources: uniqueSources(expectedSources(previousValuation)),
761
+ };
762
+ const right = current
763
+ ? evaluateExpression(
764
+ prepared,
765
+ current,
766
+ rule.expression,
767
+ `${basePath}/expression`,
768
+ )
769
+ : {
770
+ value: null,
771
+ reasons: ["missing" as const],
772
+ overflows: [],
773
+ sources: uniqueSources(expectedSources(currentValuation)),
774
+ };
775
+ const scope: DiagnosticReviewEvaluationScope = {
776
+ kind: "valuation-pair",
777
+ previous: previous
778
+ ? coordinate(previous)
779
+ : coordinateFromLabels(
780
+ prepared,
781
+ sourceGroup,
782
+ origin,
783
+ previousValuation,
784
+ ),
785
+ current: current
786
+ ? coordinate(current)
787
+ : coordinateFromLabels(
788
+ prepared,
789
+ sourceGroup,
790
+ origin,
791
+ currentValuation,
792
+ ),
793
+ sources: uniqueSources([...left.sources, ...right.sources]),
794
+ };
795
+ results.push(
796
+ evaluation(prepared, rule, scope, left, right, (relation) =>
797
+ rule.direction === "nondecreasing"
798
+ ? relation !== "greater"
799
+ : relation !== "less",
800
+ ),
801
+ );
802
+ }
803
+ }
804
+ continue;
805
+ }
806
+ for (const cell of prepared.cells) {
807
+ const scopeFor = (
808
+ sources: readonly DiagnosticSourceLocation[],
809
+ ): DiagnosticCellReviewScope => ({
810
+ kind: "cell",
811
+ cell: coordinate(cell),
812
+ sources: uniqueSources(sources),
813
+ });
814
+ if (rule.kind === "compare") {
815
+ const operand = (item: typeof rule.when.left, path: string) =>
816
+ item.op === "constant"
817
+ ? constant(item.value)
818
+ : evaluateExpression(prepared, cell, item, path);
819
+ const left = operand(rule.when.left, `${basePath}/when/left`);
820
+ const right = operand(rule.when.right, `${basePath}/when/right`);
821
+ results.push(
822
+ evaluation(
823
+ prepared,
824
+ rule,
825
+ scopeFor([...left.sources, ...right.sources]),
826
+ left,
827
+ right,
828
+ (relation) =>
829
+ !diagnosticPredicateMatches(rule.when.operator, relation),
830
+ ),
831
+ );
832
+ } else if (rule.kind === "reconcile") {
833
+ const left = evaluateExpression(
834
+ prepared,
835
+ cell,
836
+ rule.actual,
837
+ `${basePath}/actual`,
838
+ );
839
+ const right =
840
+ rule.expected.op === "constant"
841
+ ? constant(rule.expected.value)
842
+ : evaluateExpression(
843
+ prepared,
844
+ cell,
845
+ rule.expected,
846
+ `${basePath}/expected`,
847
+ );
848
+ results.push(
849
+ evaluation(
850
+ prepared,
851
+ rule,
852
+ scopeFor([...left.sources, ...right.sources]),
853
+ left,
854
+ right,
855
+ (relation) => relation === "equal",
856
+ ),
857
+ );
858
+ } else {
859
+ const left = evaluateExpression(
860
+ prepared,
861
+ cell,
862
+ rule.narrower,
863
+ `${basePath}/narrower`,
864
+ );
865
+ const right = evaluateExpression(
866
+ prepared,
867
+ cell,
868
+ rule.broader,
869
+ `${basePath}/broader`,
870
+ );
871
+ results.push(
872
+ evaluation(
873
+ prepared,
874
+ rule,
875
+ scopeFor([...left.sources, ...right.sources]),
876
+ left,
877
+ right,
878
+ (relation) => relation !== "greater",
879
+ ),
880
+ );
881
+ }
882
+ }
883
+ }
884
+ return deepFreeze(results);
885
+ }
886
+
887
+ function deepFreeze<T>(
888
+ value: T,
889
+ seen = new WeakSet<object>(),
890
+ ): DiagnosticDeepReadonly<T> {
891
+ if (value === null || typeof value !== "object" || seen.has(value))
892
+ return value as DiagnosticDeepReadonly<T>;
893
+ seen.add(value);
894
+ for (const child of Object.values(value as Record<string, unknown>))
895
+ deepFreeze(child, seen);
896
+ return Object.freeze(value) as DiagnosticDeepReadonly<T>;
897
+ }