@orkestrel/rater 0.0.24 → 0.0.26

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.
@@ -1,5 +1,5 @@
1
- import { INTRINSICS, arrayOf, arrayShape, auditFaultShape, booleanShape, createContract, describeFaults, holds, isArray, isAuditFault, isBoolean, isFiniteNumber, isFunction, isJSONValue, isNumber, isObject, isRecord, isString, jsonShape, literalOf, literalShape, nullableShape, numberShape, objectOf, objectShape, optionalShape, recordOf, shapeShape, stringShape } from "@orkestrel/contract";
2
- import { AGGREGATIONS, CHECK_STATES, COMPARISONS, createQuantitativeReasoner, createReason, createSubjectDoor, fieldPathShape, filterUniqueFaults, filterUniqueFields, formatField, isAggregation, isCheckState, isComparison, isContractShape, isFieldPath, isQuantitativeDefinition, isQuantitativeResult, isReasonError, projectValue, quantitativeDefinitionShape, scanShape, scanShapeReads } from "@orkestrel/reason";
1
+ import { INTRINSICS, arrayOf, arrayShape, attempt, auditFaultShape, booleanShape, createContract, holds, isAuditFault, isBoolean, isFiniteNumber, isFunction, isJSONValue, isNumber, isObject, isRecord, isString, isSuccess, jsonShape, literalOf, literalShape, nullableShape, numberShape, objectOf, objectShape, optionalShape, recordOf, shapeShape, stringShape } from "@orkestrel/contract";
2
+ import { AGGREGATIONS, checkResultShape, createQuantitativeReasoner, createReason, createSubjectDoor, fieldPathShape, filterUniqueFaults, filterUniqueFields, findDuplicates, isAggregation, isCheckResult, isContractShape, isFieldPath, isQuantitativeDefinition, isQuantitativeResult, isReasonError, isReasonRefusal, nestRefusals, projectCheck, projectRefusal, projectValue, quantitativeDefinitionShape, reasonRefusalShape, scanShape, scanShapeReads } from "@orkestrel/reason";
3
3
  import { Emitter } from "@orkestrel/emitter";
4
4
  // src/core/constants.ts
5
5
  /** Lists the stages a worksheet derivation step can belong to. */
@@ -148,49 +148,14 @@ function isRatingDefinition(value) {
148
148
  ])(value);
149
149
  }
150
150
  /**
151
- * Determines whether a value is an open result-side {@link Evidence} object.
152
- *
153
- * @remarks
154
- * Optional `field` is checked as a `FieldPath`, `label` as a string,
155
- * `comparison` as a `Comparison`, and `state` as a `CheckState`, each when defined.
156
- * Unknown members, prototypes, and class instances are admitted. Arrays are
157
- * refused. `expected` and `actual` are `unknown`, so this guard does not read or
158
- * check them and a borrowed result is never narrowed on them; either member may
159
- * also be absent because `objectOf` reads declared members rather than
160
- * requiring or enumerating own keys.
161
- *
162
- * @param value - The value to test
163
- * @returns True if every checked `Evidence` member conforms; false otherwise
164
- *
165
- * @example
166
- * ```ts
167
- * import { isEvidence } from '@orkestrel/rater'
168
- *
169
- * isEvidence({ field: 'age', comparison: 'above', expected: 18, actual: 25, state: 'met' }) // true
170
- * ```
171
- */
172
- function isEvidence(value) {
173
- return objectOf({
174
- field: isFieldPath,
175
- label: isString,
176
- comparison: isComparison,
177
- state: isCheckState
178
- }, [
179
- "field",
180
- "label",
181
- "comparison",
182
- "state"
183
- ])(value);
184
- }
185
- /**
186
151
  * Determines whether a value is an open {@link WorksheetFactor} result object.
187
152
  *
188
153
  * @remarks
189
- * `id`, the optional authored text, `applied`, an optional plain-number
190
- * `value`, and each `Evidence` entry are checked. Unknown members, prototypes,
191
- * and class instances are admitted and left unchecked, because a borrowed
192
- * result implementation may add them. Arrays are refused. Optional members may
193
- * be absent or read as `undefined`.
154
+ * `id`, the optional authored text, `applied`, `fallback`, the optional plain-number
155
+ * `value` and `raw`, and each `CheckResult` entry are checked. `actual` is `unknown`, so
156
+ * this guard does not read it. Unknown members, prototypes, and class instances are
157
+ * admitted and left unchecked, because a borrowed result implementation may add them. Arrays
158
+ * are refused. Optional members may be absent or read as `undefined`.
194
159
  *
195
160
  * @param value - The value to test
196
161
  * @returns True if every published worksheet-factor member conforms; false otherwise
@@ -199,7 +164,7 @@ function isEvidence(value) {
199
164
  * ```ts
200
165
  * import { isWorksheetFactor } from '@orkestrel/rater'
201
166
  *
202
- * isWorksheetFactor({ id: 'base', applied: true, value: 100, evidence: [] }) // true
167
+ * isWorksheetFactor({ id: 'base', applied: true, value: 100, fallback: false, checks: [] }) // true
203
168
  * ```
204
169
  */
205
170
  function isWorksheetFactor(value) {
@@ -209,18 +174,21 @@ function isWorksheetFactor(value) {
209
174
  description: isString,
210
175
  applied: isBoolean,
211
176
  value: isNumber,
212
- evidence: arrayOf(isEvidence)
177
+ raw: isNumber,
178
+ fallback: isBoolean,
179
+ checks: arrayOf(isCheckResult)
213
180
  }, [
214
181
  "name",
215
182
  "description",
216
- "value"
183
+ "value",
184
+ "raw"
217
185
  ])(value);
218
186
  }
219
187
  /**
220
188
  * Determines whether a value is an open {@link WorksheetGroup} result object.
221
189
  *
222
190
  * @remarks
223
- * `id`, the optional authored text, `applied`, a plain-number `value`, and each
191
+ * `id`, the optional authored text, `applied`, an optional plain-number `value`, and each
224
192
  * `WorksheetFactor` entry are checked. Unknown members, prototypes, and class
225
193
  * instances are admitted and left unchecked, because a borrowed result
226
194
  * implementation may add them. Arrays are refused. Optional members may be
@@ -244,13 +212,17 @@ function isWorksheetGroup(value) {
244
212
  applied: isBoolean,
245
213
  value: isNumber,
246
214
  factors: arrayOf(isWorksheetFactor)
247
- }, ["name", "description"])(value);
215
+ }, [
216
+ "name",
217
+ "description",
218
+ "value"
219
+ ])(value);
248
220
  }
249
221
  /**
250
222
  * Determines whether a value is an open {@link Step} result object.
251
223
  *
252
224
  * @remarks
253
- * `stage` is checked through `isWorksheetStage`, `id`, `name`, and `expression` when
225
+ * `stage` is checked through `isWorksheetStage`, `id` and `name` when
254
226
  * defined, and `value` as a plain number. Unknown members, prototypes, and
255
227
  * class instances are admitted and left unchecked, because a borrowed result
256
228
  * implementation may add them. Arrays are refused. Optional members may be
@@ -271,13 +243,8 @@ function isStep(value) {
271
243
  stage: isWorksheetStage,
272
244
  id: isString,
273
245
  name: isString,
274
- value: isNumber,
275
- expression: isString
276
- }, [
277
- "id",
278
- "name",
279
- "expression"
280
- ])(value);
246
+ value: isNumber
247
+ }, ["id", "name"])(value);
281
248
  }
282
249
  /**
283
250
  * Determines whether a value is an open {@link Worksheet} result object.
@@ -285,7 +252,7 @@ function isStep(value) {
285
252
  * @remarks
286
253
  * Identity, `aggregation` through reason's `isAggregation`, an optional
287
254
  * plain-number `precision`, a plain-number `value`, the nested groups and steps,
288
- * `trace`, `errors`, and `success` are checked. Unknown members, prototypes, and
255
+ * `trace`, `refusals` through reason's `isReasonRefusal`, and `success` are checked. Unknown members, prototypes, and
289
256
  * class instances are admitted and left unchecked, because a borrowed result
290
257
  * implementation may add them. Arrays are refused. Optional members may be
291
258
  * absent or read as `undefined`.
@@ -297,7 +264,7 @@ function isStep(value) {
297
264
  * ```ts
298
265
  * import { isWorksheet } from '@orkestrel/rater'
299
266
  *
300
- * isWorksheet({ id: 'quote', name: 'Quote', aggregation: 'sum', value: 0, groups: [], steps: [], trace: [], errors: [], success: true, faults: [], repairs: [], defaulted: [] }) // true
267
+ * isWorksheet({ id: 'quote', name: 'Quote', aggregation: 'sum', value: 0, groups: [], steps: [], trace: [], refusals: [], success: true, faults: [], repairs: [], defaulted: [] }) // true
301
268
  * ```
302
269
  */
303
270
  function isWorksheet(value) {
@@ -310,7 +277,7 @@ function isWorksheet(value) {
310
277
  groups: arrayOf(isWorksheetGroup),
311
278
  steps: arrayOf(isStep),
312
279
  trace: arrayOf(isString),
313
- errors: arrayOf(isString),
280
+ refusals: arrayOf(isReasonRefusal),
314
281
  success: isBoolean,
315
282
  faults: arrayOf(isAuditFault),
316
283
  repairs: arrayOf(isAuditFault),
@@ -337,7 +304,7 @@ function isWorksheet(value) {
337
304
  * ```ts
338
305
  * import { isLineResult } from '@orkestrel/rater'
339
306
  *
340
- * isLineResult({ id: 'base', name: 'Base', worksheet: { id: 'base', name: 'Base', aggregation: 'sum', value: 0, groups: [], steps: [], trace: [], errors: [], success: false } }) // true
307
+ * isLineResult({ id: 'base', name: 'Base', worksheet: { id: 'base', name: 'Base', aggregation: 'sum', value: 0, groups: [], steps: [], trace: [], refusals: [], success: false } }) // true
341
308
  * ```
342
309
  */
343
310
  function isLineResult(value) {
@@ -367,7 +334,7 @@ function isLineResult(value) {
367
334
  * ```ts
368
335
  * import { isRatingResult } from '@orkestrel/rater'
369
336
  *
370
- * isRatingResult({ lines: [], success: true, errors: [], faults: [], repairs: [], defaulted: [] }) // true
337
+ * isRatingResult({ lines: [], success: true, refusals: [], faults: [], repairs: [], defaulted: [] }) // true
371
338
  * ```
372
339
  */
373
340
  function isRatingResult(value) {
@@ -375,7 +342,7 @@ function isRatingResult(value) {
375
342
  lines: arrayOf(isLineResult),
376
343
  total: isNumber,
377
344
  success: isBoolean,
378
- errors: arrayOf(isString),
345
+ refusals: arrayOf(isReasonRefusal),
379
346
  faults: arrayOf(isAuditFault),
380
347
  repairs: arrayOf(isAuditFault),
381
348
  defaulted: arrayOf(isFieldPath)
@@ -438,66 +405,11 @@ function buildRatingDefinition(id, name, lines, overrides) {
438
405
  };
439
406
  }
440
407
  /**
441
- * Builds an {@link Evidence} row from an evaluated {@link Check}.
442
- *
443
- * @param check - The authored check
444
- * @param actual - The resolved subject value
445
- * @param state - The check's state; absent when the check was not evaluated
446
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
447
- * @returns A fresh evidence row
448
- *
449
- * @example
450
- * ```ts
451
- * import { createCheck } from '@orkestrel/reason'
452
- * import { buildEvidence } from '@orkestrel/rater'
453
- *
454
- * const entry = createCheck('age', 'above', 18)
455
- * buildEvidence(entry, 25, 'met') // { field: 'age', comparison: 'above', expected: 18, actual: 25, state: 'met' }
456
- * ```
457
- */
458
- function buildEvidence(check, actual, state, labels) {
459
- const field = formatField(check.field);
460
- const label = labels !== void 0 && Object.hasOwn(labels, field) ? labels[field] : void 0;
461
- return {
462
- field: check.field,
463
- ...label === void 0 ? {} : { label },
464
- comparison: check.operator,
465
- expected: check.value,
466
- actual,
467
- ...state === void 0 ? {} : { state }
468
- };
469
- }
470
- /**
471
- * Builds one evidence row per authored check of a quantitative factor, joined
472
- * to that check's evaluated result.
473
- *
474
- * @param checks - The factor's authored checks
475
- * @param results - The corresponding {@link CheckResult}s, in the same order
476
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
477
- * @returns A fresh list of evidence rows, one per authored check
478
- *
479
- * @example
480
- * ```ts
481
- * import { createCheck } from '@orkestrel/reason'
482
- * import { buildEvidenceRows } from '@orkestrel/rater'
483
- *
484
- * const checks = [createCheck('age', 'above', 18)]
485
- * buildEvidenceRows(checks, [{ field: 'age', state: 'met', actual: 25 }])
486
- * ```
487
- */
488
- function buildEvidenceRows(checks, results, labels) {
489
- return (checks ?? []).map((check, index) => {
490
- const result = results?.[index];
491
- return buildEvidence(check, result?.actual, result?.state, labels);
492
- });
493
- }
494
- /**
495
408
  * Joins one authored quantitative factor to its evaluated {@link FactorResult}.
496
409
  *
497
410
  * @param definition - The authored factor
498
411
  * @param results - The group's factor results
499
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
500
- * @returns A fresh worksheet factor
412
+ * @returns A fresh worksheet factor, its `checks` empty for a factor that never ran
501
413
  *
502
414
  * @example
503
415
  * ```ts
@@ -505,10 +417,10 @@ function buildEvidenceRows(checks, results, labels) {
505
417
  * import { buildWorksheetFactor } from '@orkestrel/rater'
506
418
  *
507
419
  * const factor = createFieldFactor('seats', 'seats')
508
- * buildWorksheetFactor(factor, [{ id: 'seats', applied: true, value: 10 }])
420
+ * buildWorksheetFactor(factor, [{ id: 'seats', applied: true, value: 10, fallback: false }])
509
421
  * ```
510
422
  */
511
- function buildWorksheetFactor(definition, results, labels) {
423
+ function buildWorksheetFactor(definition, results) {
512
424
  const result = results.find((entry) => entry.id === definition.id);
513
425
  return {
514
426
  id: definition.id,
@@ -516,7 +428,10 @@ function buildWorksheetFactor(definition, results, labels) {
516
428
  ...definition.description === void 0 ? {} : { description: definition.description },
517
429
  applied: result?.applied ?? false,
518
430
  ...result?.value === void 0 ? {} : { value: result.value },
519
- evidence: buildEvidenceRows(definition.checks, result?.checks, labels)
431
+ ...result?.raw === void 0 ? {} : { raw: result.raw },
432
+ ...result?.actual === void 0 ? {} : { actual: result.actual },
433
+ fallback: result?.fallback ?? false,
434
+ checks: result?.checks ?? []
520
435
  };
521
436
  }
522
437
  /**
@@ -524,7 +439,6 @@ function buildWorksheetFactor(definition, results, labels) {
524
439
  *
525
440
  * @param definition - The authored group
526
441
  * @param results - The definition's group results
527
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
528
442
  * @returns A fresh worksheet group
529
443
  *
530
444
  * @example
@@ -536,15 +450,15 @@ function buildWorksheetFactor(definition, results, labels) {
536
450
  * buildWorksheetGroup(group, [{ id: 'charge', applied: true, value: 100, factors: [] }])
537
451
  * ```
538
452
  */
539
- function buildWorksheetGroup(definition, results, labels) {
453
+ function buildWorksheetGroup(definition, results) {
540
454
  const result = results.find((entry) => entry.id === definition.id);
541
455
  return {
542
456
  id: definition.id,
543
457
  name: definition.name,
544
458
  ...definition.description === void 0 ? {} : { description: definition.description },
545
459
  applied: result?.applied ?? false,
546
- value: result?.value ?? 0,
547
- factors: definition.factors.map((factor) => buildWorksheetFactor(factor, result?.factors ?? [], labels))
460
+ ...result === void 0 ? {} : { value: result.value },
461
+ factors: definition.factors.map((factor) => buildWorksheetFactor(factor, result?.factors ?? []))
548
462
  };
549
463
  }
550
464
  /**
@@ -554,24 +468,22 @@ function buildWorksheetGroup(definition, results, labels) {
554
468
  * @param id - The stage's authored id, when it has one
555
469
  * @param name - The stage's authored name, when it has one
556
470
  * @param value - The stage's resolved value
557
- * @param expression - A display-neutral expression string
558
471
  * @returns A fresh step
559
472
  *
560
473
  * @example
561
474
  * ```ts
562
475
  * import { buildWorksheetStep } from '@orkestrel/rater'
563
476
  *
564
- * buildWorksheetStep('total', 'quote', 'Quote', 110, 'sum = 110')
565
- * // { stage: 'total', id: 'quote', name: 'Quote', value: 110, expression: 'sum = 110' }
477
+ * buildWorksheetStep('total', 'quote', 'Quote', 110)
478
+ * // { stage: 'total', id: 'quote', name: 'Quote', value: 110 }
566
479
  * ```
567
480
  */
568
- function buildWorksheetStep(stage, id, name, value, expression) {
481
+ function buildWorksheetStep(stage, id, name, value) {
569
482
  return {
570
483
  stage,
571
484
  ...id === void 0 ? {} : { id },
572
485
  ...name === void 0 ? {} : { name },
573
- value,
574
- expression
486
+ value
575
487
  };
576
488
  }
577
489
  /**
@@ -597,10 +509,10 @@ function buildWorksheetStep(stage, id, name, value, expression) {
597
509
  function buildWorksheetSteps(definition, result, groups) {
598
510
  const output = [];
599
511
  for (const group of groups) {
600
- for (const factor of group.factors) if (factor.applied && factor.value !== void 0) output.push(buildWorksheetStep("factor", factor.id, factor.name, factor.value, `${factor.id} = ${factor.value}`));
601
- output.push(buildWorksheetStep("group", group.id, group.name, group.value, `${group.id} = ${group.value}`));
512
+ for (const factor of group.factors) if (factor.applied && factor.value !== void 0) output.push(buildWorksheetStep("factor", factor.id, factor.name, factor.value));
513
+ if (group.value !== void 0) output.push(buildWorksheetStep("group", group.id, group.name, group.value));
602
514
  }
603
- output.push(buildWorksheetStep("total", definition.id, definition.name, result.value, `${definition.aggregation} = ${result.value}`));
515
+ output.push(buildWorksheetStep("total", definition.id, definition.name, result.value));
604
516
  return output;
605
517
  }
606
518
  /**
@@ -609,7 +521,6 @@ function buildWorksheetSteps(definition, result, groups) {
609
521
  *
610
522
  * @param definition - The authored quantitative definition
611
523
  * @param result - The evaluated quantitative result
612
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
613
524
  * @returns A fresh worksheet
614
525
  *
615
526
  * @example
@@ -622,8 +533,8 @@ function buildWorksheetSteps(definition, result, groups) {
622
533
  * if (result.reasoning === 'quantitative') buildWorksheet(definition, result) // the full audit trail
623
534
  * ```
624
535
  */
625
- function buildWorksheet(definition, result, labels) {
626
- const groups = definition.groups.map((group) => buildWorksheetGroup(group, result.groups, labels));
536
+ function buildWorksheet(definition, result) {
537
+ const groups = definition.groups.map((group) => buildWorksheetGroup(group, result.groups));
627
538
  return {
628
539
  id: definition.id,
629
540
  name: definition.name,
@@ -633,7 +544,7 @@ function buildWorksheet(definition, result, labels) {
633
544
  groups,
634
545
  steps: buildWorksheetSteps(definition, result, groups),
635
546
  trace: result.trace,
636
- errors: result.errors,
547
+ refusals: result.refusals,
637
548
  success: result.success,
638
549
  faults: result.faults,
639
550
  repairs: result.repairs,
@@ -646,7 +557,6 @@ function buildWorksheet(definition, result, labels) {
646
557
  *
647
558
  * @param definition - The authored line definition
648
559
  * @param result - The evaluated quantitative result
649
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
650
560
  * @returns A fresh line result
651
561
  *
652
562
  * @example
@@ -659,12 +569,272 @@ function buildWorksheet(definition, result, labels) {
659
569
  * if (result.reasoning === 'quantitative') buildLineResult(line, result) // amount present only on a successful worksheet
660
570
  * ```
661
571
  */
662
- function buildLineResult(definition, result, labels) {
572
+ function buildLineResult(definition, result) {
663
573
  return {
664
574
  id: definition.id,
665
575
  name: definition.name,
666
576
  ...result.success ? { amount: result.value } : {},
667
- worksheet: buildWorksheet(definition.rate, result, labels)
577
+ worksheet: buildWorksheet(definition.rate, result)
578
+ };
579
+ }
580
+ /**
581
+ * Copies a quantitative result into plain objects and arrays this package owns, reading each
582
+ * member of it once.
583
+ *
584
+ * @remarks
585
+ * The copy reaches the result's groups, their factors, and each factor's checks. A check's own
586
+ * `check` and `actual`, and the entries of `refusals`, `faults`, and `repairs`, are carried as
587
+ * they were read.
588
+ *
589
+ * @param result - The quantitative result to copy
590
+ * @returns A fresh result that holds each member as it read
591
+ *
592
+ * @example
593
+ * ```ts
594
+ * import { copyResult } from '@orkestrel/rater'
595
+ *
596
+ * const answer = {
597
+ * reasoning: 'quantitative',
598
+ * value: 5,
599
+ * groups: [],
600
+ * count: 0,
601
+ * success: true,
602
+ * trace: [],
603
+ * refusals: [],
604
+ * faults: [],
605
+ * repairs: [],
606
+ * defaulted: [],
607
+ * } as const
608
+ * copyResult(answer) === answer // false
609
+ * ```
610
+ */
611
+ function copyResult(result) {
612
+ const { reasoning, value, groups, count, success, trace, refusals, faults, repairs, defaulted } = result;
613
+ return {
614
+ reasoning,
615
+ value,
616
+ groups: groups.map(({ id, applied, value: held, factors }) => ({
617
+ id,
618
+ applied,
619
+ value: held,
620
+ factors: factors.map(({ id: key, applied: ran, value: scored, raw, actual, fallback, checks }) => ({
621
+ id: key,
622
+ applied: ran,
623
+ value: scored,
624
+ ...raw === void 0 ? {} : { raw },
625
+ ...actual === void 0 ? {} : { actual },
626
+ fallback,
627
+ ...checks === void 0 ? {} : { checks: checks.map((read) => ({
628
+ check: read.check,
629
+ state: read.state,
630
+ actual: read.actual
631
+ })) }
632
+ }))
633
+ })),
634
+ count,
635
+ success,
636
+ trace: [...trace],
637
+ refusals: [...refusals],
638
+ faults: [...faults],
639
+ repairs: [...repairs],
640
+ defaulted: [...defaulted]
641
+ };
642
+ }
643
+ /**
644
+ * Finds each enabled group of a definition that a result omits, and each enabled factor an
645
+ * answered group omits.
646
+ *
647
+ * @remarks
648
+ * An omitted group is named alone, because its factors have no group to answer in.
649
+ *
650
+ * @param definition - The authored quantitative definition
651
+ * @param result - The result the engine answered with
652
+ * @returns The `group`, and the `factor` where one is omitted, of each omission, in definition order
653
+ *
654
+ * @example
655
+ * ```ts
656
+ * import { createFactorGroup, createQuantitativeDefinition, createStaticFactor } from '@orkestrel/reason'
657
+ * import { findUnansweredParts } from '@orkestrel/rater'
658
+ *
659
+ * const definition = createQuantitativeDefinition('quote', 'Quote', [
660
+ * createFactorGroup('charge', 'sum', [createStaticFactor('base', 100)]),
661
+ * ])
662
+ * findUnansweredParts(definition, {
663
+ * reasoning: 'quantitative',
664
+ * value: 0,
665
+ * groups: [],
666
+ * count: 0,
667
+ * success: true,
668
+ * trace: [],
669
+ * refusals: [],
670
+ * faults: [],
671
+ * repairs: [],
672
+ * defaulted: [],
673
+ * }) // [{ group: 'charge' }]
674
+ * ```
675
+ */
676
+ function findUnansweredParts(definition, result) {
677
+ const answered = new Map(result.groups.map((group) => [group.id, new Set(group.factors.map((factor) => factor.id))]));
678
+ return definition.groups.filter((group) => group.enabled !== false).flatMap((group) => {
679
+ const held = answered.get(group.id);
680
+ if (held === void 0) return [{ group: group.id }];
681
+ return group.factors.filter((factor) => factor.enabled !== false && !held.has(factor.id)).map((factor) => ({
682
+ group: group.id,
683
+ factor: factor.id
684
+ }));
685
+ });
686
+ }
687
+ /**
688
+ * Finds each group id a result lists more than once, and each factor id one of its groups lists
689
+ * more than once.
690
+ *
691
+ * @remarks
692
+ * An entry that repeats an id is refused whatever it holds, because a worksheet reads the first
693
+ * entry and a completeness check reads the last. Each repeated id is named once, however many
694
+ * entries repeat it.
695
+ *
696
+ * @param result - The result the engine answered with
697
+ * @returns The `group`, and the `factor` where a factor repeats, of each repeated id
698
+ *
699
+ * @example
700
+ * ```ts
701
+ * import { findRepeatedParts } from '@orkestrel/rater'
702
+ *
703
+ * const group = { id: 'charge', applied: true, value: 100, factors: [] }
704
+ * findRepeatedParts({
705
+ * reasoning: 'quantitative',
706
+ * value: 100,
707
+ * groups: [group, group],
708
+ * count: 1,
709
+ * success: true,
710
+ * trace: [],
711
+ * refusals: [],
712
+ * faults: [],
713
+ * repairs: [],
714
+ * defaulted: [],
715
+ * }) // [{ group: 'charge' }]
716
+ * ```
717
+ */
718
+ function findRepeatedParts(result) {
719
+ const groups = findDuplicates(result.groups).map((group) => ({ group }));
720
+ const factors = result.groups.flatMap((group) => findDuplicates(group.factors).map((factor) => ({
721
+ group: group.id,
722
+ factor
723
+ })));
724
+ return [...groups, ...factors].filter((part, index, all) => all.findIndex((held) => held.group === part.group && held.factor === part.factor) === index);
725
+ }
726
+ /**
727
+ * Finds each line whose id an earlier line of the list holds.
728
+ *
729
+ * @param lines - The lines of one rating, in order
730
+ * @returns One `definition` refusal for each such line, its `path` the id and its `index` the line's place
731
+ *
732
+ * @example
733
+ * ```ts
734
+ * import { createQuantitativeDefinition } from '@orkestrel/reason'
735
+ * import { buildLineDefinition, findRepeatedLines } from '@orkestrel/rater'
736
+ *
737
+ * const rate = createQuantitativeDefinition('base', 'Base', [])
738
+ * const line = buildLineDefinition('base', 'Base', rate)
739
+ * findRepeatedLines([line, line]) // [{ cause: 'definition', path: ['base'], index: 1 }]
740
+ * ```
741
+ */
742
+ function findRepeatedLines(lines) {
743
+ const earliest = new Map(lines.map((line, index) => [line.id, index]).toReversed());
744
+ return lines.flatMap((line, index) => earliest.get(line.id) === index ? [] : [{
745
+ cause: "definition",
746
+ path: [line.id],
747
+ index
748
+ }]);
749
+ }
750
+ /**
751
+ * Holds an engine's answer to what its own members and the definition support.
752
+ *
753
+ * @remarks
754
+ * The answer is read once, through {@link copyResult}, and every verdict follows from that copy.
755
+ * An answer that is no quantitative result is `malformed` alone. A success beside a refusal or a
756
+ * fault, beside each enabled group or factor the answer omits, beside each group or factor id it
757
+ * lists more than once, and beside a value that is not a finite number, fails closed with one
758
+ * `malformed` refusal for each, the part in `group` and `factor` and the value in `actual`. A failure that names no refusal and no fault is
759
+ * `silent`. Any other answer returns as its copy.
760
+ *
761
+ * @param answer - What the engine answered
762
+ * @param definition - The authored quantitative definition the engine ran
763
+ * @returns A fresh result the package owns
764
+ *
765
+ * @example
766
+ * ```ts
767
+ * import { createQuantitativeDefinition } from '@orkestrel/reason'
768
+ * import { settleResult } from '@orkestrel/rater'
769
+ *
770
+ * settleResult(
771
+ * {
772
+ * reasoning: 'quantitative',
773
+ * value: 5,
774
+ * groups: [],
775
+ * count: 0,
776
+ * success: false,
777
+ * trace: [],
778
+ * refusals: [],
779
+ * faults: [],
780
+ * repairs: [],
781
+ * defaulted: [],
782
+ * },
783
+ * createQuantitativeDefinition('base', 'Base', []),
784
+ * ).refusals // [{ cause: 'silent' }]
785
+ * ```
786
+ */
787
+ function settleResult(answer, definition) {
788
+ const copied = isQuantitativeResult(answer) ? attempt(() => copyResult(answer)) : void 0;
789
+ if (copied === void 0 || !isSuccess(copied) || !isQuantitativeResult(copied.value)) return buildMalformedResult();
790
+ const result = copied.value;
791
+ const { success, value, refusals, faults } = result;
792
+ const named = refusals.length > 0 || faults.length > 0;
793
+ if (!success) return named ? result : {
794
+ ...result,
795
+ refusals: [{ cause: "silent" }]
796
+ };
797
+ const held = [
798
+ ...named ? [{}] : [],
799
+ ...findUnansweredParts(definition, result),
800
+ ...findRepeatedParts(result),
801
+ ...isFiniteNumber(value) ? [] : [{ actual: value }]
802
+ ];
803
+ if (held.length === 0) return result;
804
+ const contradictions = held.map((part) => ({
805
+ cause: "malformed",
806
+ ...part
807
+ }));
808
+ return {
809
+ ...result,
810
+ success: false,
811
+ refusals: [...refusals, ...contradictions]
812
+ };
813
+ }
814
+ /**
815
+ * Builds the failed {@link QuantitativeResult} for an engine answer that is no quantitative result.
816
+ *
817
+ * @returns A fresh failed result carrying one `malformed` refusal
818
+ *
819
+ * @example
820
+ * ```ts
821
+ * import { buildMalformedResult } from '@orkestrel/rater'
822
+ *
823
+ * buildMalformedResult().refusals // [{ cause: 'malformed' }]
824
+ * ```
825
+ */
826
+ function buildMalformedResult() {
827
+ return {
828
+ reasoning: "quantitative",
829
+ value: 0,
830
+ groups: [],
831
+ count: 0,
832
+ success: false,
833
+ trace: [],
834
+ refusals: [{ cause: "malformed" }],
835
+ faults: [],
836
+ repairs: [],
837
+ defaulted: []
668
838
  };
669
839
  }
670
840
  /**
@@ -692,8 +862,9 @@ function sumAmounts(lines) {
692
862
  * Projects a result to the JSON its contract reads.
693
863
  *
694
864
  * @remarks
695
- * An evidence row's `actual` holds whatever the subject held and a worksheet's numbers may be
696
- * `NaN`, so a result crosses a boundary as this projection, each `actual` on its own budget.
865
+ * A factor's `actual`, a check's `actual`, and a refusal's `actual` hold whatever the subject held
866
+ * and a worksheet's numbers may be `NaN`, so a result crosses a boundary as this projection, each
867
+ * `actual` on its own budget.
697
868
  *
698
869
  * @param result - The rating result
699
870
  * @returns Its JSON projection, which `ratingResultContract` admits
@@ -712,20 +883,21 @@ function projectRatingResult(result) {
712
883
  ...line,
713
884
  worksheet: {
714
885
  ...line.worksheet,
886
+ refusals: line.worksheet.refusals.map((refusal) => projectRefusal(refusal)),
715
887
  groups: line.worksheet.groups.map((group) => ({
716
888
  ...group,
717
889
  factors: group.factors.map((factor) => ({
718
890
  ...factor,
719
- evidence: factor.evidence.map((row) => ({
720
- ...row,
721
- actual: projectValue(row.actual)
722
- }))
891
+ actual: projectValue(factor.actual),
892
+ checks: factor.checks.map((check) => projectCheck(check))
723
893
  }))
724
894
  }))
725
895
  }
726
896
  }));
897
+ const refusals = result.refusals.map((refusal) => projectRefusal(refusal));
727
898
  return projectValue({
728
899
  ...result,
900
+ refusals,
729
901
  lines
730
902
  }, /* @__PURE__ */ new Set(), { left: Number.POSITIVE_INFINITY });
731
903
  }
@@ -749,15 +921,6 @@ var ratingDefinitionShape = objectShape({
749
921
  metadata: optionalShape(jsonShape()),
750
922
  shape: optionalShape(shapeShape())
751
923
  });
752
- /** Describes an `Evidence` row in its JSON projection. */
753
- var evidenceShape = objectShape({
754
- field: optionalShape(fieldPathShape),
755
- label: optionalShape(stringShape()),
756
- comparison: optionalShape(literalShape(COMPARISONS)),
757
- expected: optionalShape(jsonShape()),
758
- actual: optionalShape(jsonShape()),
759
- state: optionalShape(literalShape(CHECK_STATES))
760
- });
761
924
  /** Describes a `WorksheetFactor` in its JSON projection. */
762
925
  var worksheetFactorShape = objectShape({
763
926
  id: stringShape(),
@@ -765,7 +928,10 @@ var worksheetFactorShape = objectShape({
765
928
  description: optionalShape(stringShape()),
766
929
  applied: booleanShape(),
767
930
  value: optionalShape(nullableShape(numberShape())),
768
- evidence: arrayShape(evidenceShape)
931
+ raw: optionalShape(nullableShape(numberShape())),
932
+ actual: optionalShape(jsonShape()),
933
+ fallback: booleanShape(),
934
+ checks: arrayShape(checkResultShape)
769
935
  });
770
936
  /** Describes a `WorksheetGroup` in its JSON projection. */
771
937
  var worksheetGroupShape = objectShape({
@@ -773,7 +939,7 @@ var worksheetGroupShape = objectShape({
773
939
  name: optionalShape(stringShape()),
774
940
  description: optionalShape(stringShape()),
775
941
  applied: booleanShape(),
776
- value: nullableShape(numberShape()),
942
+ value: optionalShape(nullableShape(numberShape())),
777
943
  factors: arrayShape(worksheetFactorShape)
778
944
  });
779
945
  /** Describes a `Step` in its JSON projection. */
@@ -781,8 +947,7 @@ var worksheetStepShape = objectShape({
781
947
  stage: literalShape(WORKSHEET_STAGES),
782
948
  id: optionalShape(stringShape()),
783
949
  name: optionalShape(stringShape()),
784
- value: nullableShape(numberShape()),
785
- expression: optionalShape(stringShape())
950
+ value: nullableShape(numberShape())
786
951
  });
787
952
  /** Describes a `Worksheet` in its JSON projection. */
788
953
  var worksheetShape = objectShape({
@@ -794,7 +959,7 @@ var worksheetShape = objectShape({
794
959
  groups: arrayShape(worksheetGroupShape),
795
960
  steps: arrayShape(worksheetStepShape),
796
961
  trace: arrayShape(stringShape()),
797
- errors: arrayShape(stringShape()),
962
+ refusals: arrayShape(reasonRefusalShape),
798
963
  success: booleanShape(),
799
964
  faults: arrayShape(auditFaultShape()),
800
965
  repairs: arrayShape(auditFaultShape()),
@@ -812,7 +977,7 @@ var ratingResultShape = objectShape({
812
977
  lines: arrayShape(lineResultShape),
813
978
  total: optionalShape(nullableShape(numberShape())),
814
979
  success: booleanShape(),
815
- errors: arrayShape(stringShape()),
980
+ refusals: arrayShape(reasonRefusalShape),
816
981
  faults: arrayShape(auditFaultShape()),
817
982
  repairs: arrayShape(auditFaultShape()),
818
983
  defaulted: arrayShape(fieldPathShape)
@@ -852,7 +1017,6 @@ var Rater = class {
852
1017
  #engine;
853
1018
  #owned;
854
1019
  #total;
855
- #labels;
856
1020
  #door = createSubjectDoor();
857
1021
  #valid = /* @__PURE__ */ new WeakSet();
858
1022
  #destroyed = false;
@@ -872,7 +1036,6 @@ var Rater = class {
872
1036
  this.#owned = false;
873
1037
  }
874
1038
  this.#total = options?.total;
875
- this.#labels = options?.labels;
876
1039
  }
877
1040
  get emitter() {
878
1041
  return this.#emitter;
@@ -887,7 +1050,7 @@ var Rater = class {
887
1050
  const refused = {
888
1051
  lines: [],
889
1052
  success: false,
890
- errors: admission.errors,
1053
+ refusals: admission.refusals,
891
1054
  faults: admission.faults,
892
1055
  repairs: [],
893
1056
  defaulted: []
@@ -896,29 +1059,29 @@ var Rater = class {
896
1059
  return refused;
897
1060
  }
898
1061
  const results = lines.map((line) => this.#rateLine(line, admitted));
899
- const rated = results.every((entry) => entry.worksheet.success);
1062
+ const repeated = findRepeatedLines(lines);
1063
+ const rated = results.every((entry) => entry.worksheet.success) && repeated.length === 0;
900
1064
  const summed = rated ? (this.#total ?? sumAmounts)(results) : void 0;
901
1065
  const overflowed = summed !== void 0 && !isFiniteNumber(summed);
902
1066
  const total = overflowed ? void 0 : summed;
903
1067
  const success = rated && !overflowed;
904
1068
  const faults = filterUniqueFaults(results.flatMap((entry) => entry.worksheet.faults));
905
- const said = new Set(faults.map((fault) => describeFaults([fault])));
906
- const other = results.flatMap((entry) => {
907
- const { errors, success: settled } = entry.worksheet;
908
- if (!settled && errors.length === 0) return [`${entry.id}: The line failed and said nothing`];
909
- return errors.filter((error) => !said.has(error)).map((error) => `${entry.id}: ${error}`);
910
- });
1069
+ const unfinite = overflowed ? [{
1070
+ cause: "value",
1071
+ actual: summed
1072
+ }] : [];
1073
+ const refusals = [
1074
+ ...results.flatMap((entry) => nestRefusals(entry.worksheet.refusals, entry.id)),
1075
+ ...repeated,
1076
+ ...unfinite
1077
+ ];
911
1078
  const repairs = filterUniqueFaults([...admission.repairs, ...results.flatMap((entry) => entry.worksheet.repairs)]);
912
1079
  const defaulted = filterUniqueFields([...admission.defaulted, ...results.flatMap((entry) => entry.worksheet.defaulted)]);
913
1080
  const result = {
914
1081
  lines: results,
915
1082
  ...total === void 0 ? {} : { total },
916
1083
  success,
917
- errors: [
918
- ...other,
919
- ...said,
920
- ...overflowed ? ["The total is not a finite number"] : []
921
- ],
1084
+ refusals,
922
1085
  faults,
923
1086
  repairs,
924
1087
  defaulted
@@ -949,35 +1112,10 @@ var Rater = class {
949
1112
  return shape;
950
1113
  }
951
1114
  #rateLine(line, subject) {
952
- return buildLineResult(line, this.#reasonQuantitative(subject, line.rate), this.#labels);
1115
+ return buildLineResult(line, this.#reasonQuantitative(subject, line.rate));
953
1116
  }
954
1117
  #reasonQuantitative(subject, definition) {
955
- const result = this.#reason(subject, definition);
956
- if (isQuantitativeResult(result)) return this.#settle(result);
957
- const answer = isRecord(result) ? result : {};
958
- const named = isString(answer.reasoning) ? answer.reasoning : "something else";
959
- return {
960
- reasoning: "quantitative",
961
- value: 0,
962
- groups: [],
963
- count: 0,
964
- success: false,
965
- trace: [],
966
- errors: [...isArray(answer.errors) ? answer.errors.filter(isString) : [], `Expected quantitative result, got ${named}`],
967
- faults: [],
968
- repairs: [],
969
- defaulted: []
970
- };
971
- }
972
- #settle(result) {
973
- if (!result.success) return result;
974
- if (result.errors.length === 0 && result.faults.length === 0 && isFiniteNumber(result.value)) return result;
975
- const said = result.errors.length > 0 ? [] : ["The line succeeded beside a fault or no value"];
976
- return {
977
- ...result,
978
- success: false,
979
- errors: [...result.errors, ...said]
980
- };
1118
+ return settleResult(this.#reason(subject, definition), definition);
981
1119
  }
982
1120
  #reason(subject, definition) {
983
1121
  try {
@@ -996,7 +1134,7 @@ var Rater = class {
996
1134
  * Creates a rating orchestrator over the shared quantitative engine, seeded
997
1135
  * from {@link RaterOptions} and returning a {@link RaterInterface}.
998
1136
  *
999
- * @param options - Optional total handler, labels, injected engine, and emitter hooks
1137
+ * @param options - Optional total handler, injected engine, and emitter hooks
1000
1138
  * @returns A {@link RaterInterface}
1001
1139
  *
1002
1140
  * @example Create a rater
@@ -1010,6 +1148,6 @@ var Rater = class {
1010
1148
  function createRater(options) {
1011
1149
  return new Rater(options);
1012
1150
  }
1013
- export { Rater, RaterError, WORKSHEET_STAGES, buildEvidence, buildEvidenceRows, buildLineDefinition, buildLineResult, buildRatingDefinition, buildWorksheet, buildWorksheetFactor, buildWorksheetGroup, buildWorksheetStep, buildWorksheetSteps, createRater, evidenceShape, isEvidence, isLineDefinition, isLineResult, isRaterError, isRatingDefinition, isRatingResult, isStep, isWorksheet, isWorksheetFactor, isWorksheetGroup, isWorksheetStage, lineDefinitionShape, lineResultShape, projectRatingResult, ratingDefinitionContract, ratingDefinitionShape, ratingResultContract, ratingResultShape, sumAmounts, worksheetFactorShape, worksheetGroupShape, worksheetShape, worksheetStepShape };
1151
+ export { Rater, RaterError, WORKSHEET_STAGES, buildLineDefinition, buildLineResult, buildMalformedResult, buildRatingDefinition, buildWorksheet, buildWorksheetFactor, buildWorksheetGroup, buildWorksheetStep, buildWorksheetSteps, copyResult, createRater, findRepeatedLines, findRepeatedParts, findUnansweredParts, isLineDefinition, isLineResult, isRaterError, isRatingDefinition, isRatingResult, isStep, isWorksheet, isWorksheetFactor, isWorksheetGroup, isWorksheetStage, lineDefinitionShape, lineResultShape, projectRatingResult, ratingDefinitionContract, ratingDefinitionShape, ratingResultContract, ratingResultShape, settleResult, sumAmounts, worksheetFactorShape, worksheetGroupShape, worksheetShape, worksheetStepShape };
1014
1152
 
1015
1153
  //# sourceMappingURL=index.js.map